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 |
|---|---|---|---|---|---|---|
1 | devbench-api-usage | c_sharp | using System;
using System.Collections.Concurrent;
class Program
{
static int ComputeCount = 0;
static int ComputeValue(string key)
{
ComputeCount++;
return key.Length * 10;
}
static int GetOrCompute(ConcurrentDictionary<string, int> dict, string key)
{
return dict.Get... | static string DescribeGetOrCompute()
{
return "Uses ConcurrentDictionary.GetOrAdd(TKey, Func<TKey,TValue>) which "
+ "atomically returns the existing value if the key is present, or "
+ "invokes the valueFactory delegate to create and add a new value. "
+ "The valu... |
static void Main()
{
var dict = new ConcurrentDictionary<string, int>();
ComputeCount = 0;
int v1 = GetOrCompute(dict, "hello");
if (v1 != 50) throw new Exception("Expected 50");
if (ComputeCount != 1) throw new Exception("Factory should be called once");
int v... | string d1 = DescribeGetOrCompute().ToLower();
if (!d1.Contains("getoradd")) throw new Exception("Must mention GetOrAdd");
if (!d1.Contains("valuefactory") && !d1.Contains("factory") && !d1.Contains("delegate")) throw new Exception("Must mention factory/delegate");
if (!d1.Contains("atomically") && !d1.Contains("atomic"... |
2 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static SortedSet<int> GetRange(SortedSet<int> set, int lo, int hi)
{
return set.GetViewBetween(lo, hi);
}
| static string DescribeGetRange()
{
return "Uses SortedSet.GetViewBetween(lowerValue, upperValue) which returns "
+ "a live view (not a copy) of elements in [lowerValue, upperValue] — both "
+ "bounds are inclusive. The returned SortedSet is backed by the original: "
... |
static void Main()
{
var set = new SortedSet<int> { 1, 3, 5, 7, 9, 11 };
var view = GetRange(set, 3, 9);
if (view.Count != 4) throw new Exception($"Expected 4, got {view.Count}");
if (!view.Contains(3) || !view.Contains(9)) throw new Exception("Bounds inclusive");
view.... | string d2 = DescribeGetRange().ToLower();
if (!d2.Contains("getviewbetween")) throw new Exception("Must mention GetViewBetween");
if (!(d2.Contains("live view") || d2.Contains("backed by") || d2.Contains("not a copy"))) throw new Exception("Must mention live view");
if (!d2.Contains("inclusive")) throw new Exception("M... |
3 | devbench-api-usage | c_sharp | using System;
using System.Text;
class Program
{
static byte[] EncodeWithPreamble(string text)
{
Encoding utf8Bom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true);
byte[] preamble = utf8Bom.GetPreamble();
byte[] encoded = utf8Bom.GetBytes(text);
byte[] result = new byte... | static string DescribeEncodingBehavior()
{
return "Encoding.UTF8 is a UTF8Encoding instance with encoderShouldEmitUTF8Identifier "
+ "set to false — GetPreamble() returns an empty array, and GetBytes() produces "
+ "no BOM prefix (EF BB BF). Constructing new UTF8Encoding(true) ... |
static void Main()
{
byte[] withBom = EncodeWithPreamble("Hi");
byte[] noBom = EncodeNoPreamble("Hi");
if (withBom.Length != noBom.Length + 3) throw new Exception("BOM is 3 bytes");
if (withBom[0] != 0xEF || withBom[1] != 0xBB || withBom[2] != 0xBF)
throw new Excepti... | string d3 = DescribeEncodingBehavior().ToLower();
if (!(d3.Contains("ef bb bf") || d3.Contains("0xef") || d3.Contains("ef, bb, bf") || d3.Contains("0xef, 0xbb, 0xbf"))) throw new Exception("Must mention BOM bytes EF BB BF");
if (!(d3.Contains("getpreamble"))) throw new Exception("Must mention GetPreamble");
if (!(d3.Co... |
4 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static string ProcessQueue(PriorityQueue<string, int> pq)
{
var results = new List<string>();
while (pq.TryDequeue(out string? item, out int priority))
{
results.Add($"{item}:{priority}");
}
retu... | static string DescribeProcessQueue()
{
return "Uses PriorityQueue<TElement,TPriority>.TryDequeue which removes and returns "
+ "the element with the lowest priority value (min-heap). Returns false when the "
+ "queue is empty instead of throwing. Unlike Enqueue/Dequeue, TryDequ... |
static void Main()
{
var pq = new PriorityQueue<string, int>();
pq.Enqueue("low", 3);
pq.Enqueue("high", 1);
pq.Enqueue("mid", 2);
string result = ProcessQueue(pq);
if (!result.StartsWith("high:1")) throw new Exception($"Min-heap expected, got {result}");
... | string d4 = DescribeProcessQueue().ToLower();
if (!d4.Contains("trydequeue")) throw new Exception("Must mention TryDequeue");
if (!(d4.Contains("min-heap") || d4.Contains("lowest priority"))) throw new Exception("Must mention min-heap behavior");
if (!(d4.Contains("not stable") || d4.Contains("any order"))) throw new E... |
5 | devbench-api-usage | c_sharp | using System;
using System.Text.RegularExpressions;
class Program
{
static (string year, string month, string day) ParseDate(string input)
{
var match = Regex.Match(input, @"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})");
if (!match.Success)
throw new FormatException("Invalid date f... | static string DescribeParseDate()
{
return "Uses Regex.Match(string, string) which returns a single Match object "
+ "(never null — check Match.Success). Named capture groups (?<name>...) "
+ "are accessed via Match.Groups[string] returning a Group object whose "
+... |
static void Main()
{
var (y, m, d) = ParseDate("2024-03-15");
if (y != "2024" || m != "03" || d != "15")
throw new Exception("Parsing failed");
bool threw = false;
try { ParseDate("not-a-date"); }
catch (FormatException) { threw = true; }
if (!threw)... | string d5 = DescribeParseDate().ToLower();
if (!d5.Contains("regex.match")) throw new Exception("Must mention Regex.Match");
if (!(d5.Contains("named") && (d5.Contains("capture") || d5.Contains("group")))) throw new Exception("Must mention named capture groups");
if (!(d5.Contains("never null") || d5.Contains("match.su... |
6 | devbench-api-usage | c_sharp | using System;
using System.Linq;
class Program
{
static string BuildPath(string[] segments)
{
return segments.Aggregate("root",
(current, next) => current + "/" + next,
result => result.ToUpper());
}
| static string DescribeBuildPath()
{
return "Uses Enumerable.Aggregate<TSource,TAccumulate,TResult>(seed, func, resultSelector) "
+ "— the three-parameter overload. The seed ('root') is the initial accumulator value "
+ "and its type (TAccumulate) can differ from TSource. The fu... |
static void Main()
{
string result = BuildPath(new[] { "usr", "local", "bin" });
if (result != "ROOT/USR/LOCAL/BIN") throw new Exception($"Expected ROOT/USR/LOCAL/BIN, got {result}");
string empty = BuildPath(new string[0]);
if (empty != "ROOT") throw new Exception($"Empty shou... | string d6 = DescribeBuildPath().ToLower();
if (!d6.Contains("aggregate")) throw new Exception("Must mention Aggregate");
if (!(d6.Contains("seed") || d6.Contains("initial accumulator"))) throw new Exception("Must mention seed");
if (!(d6.Contains("resultselector") || d6.Contains("result selector") || d6.Contains("proje... |
7 | devbench-api-usage | c_sharp | using System;
using System.Text;
class Program
{
static string JoinValues(string separator, params string[] values)
{
var sb = new StringBuilder(256);
sb.AppendJoin(separator, values);
return sb.ToString();
}
| static string DescribeJoinValues()
{
return "Uses StringBuilder(int capacity) constructor to pre-allocate a 256-char "
+ "internal buffer, avoiding reallocations for small inputs. AppendJoin(string, "
+ "params object[]) appends each element separated by the separator in a sing... |
static void Main()
{
string result = JoinValues(", ", "a", "b", "c");
if (result != "a, b, c") throw new Exception($"Expected 'a, b, c', got '{result}'");
string single = JoinValues("-", "only");
if (single != "only") throw new Exception($"Expected 'only', got '{single}'");
... | string d7 = DescribeJoinValues().ToLower();
if (!d7.Contains("appendjoin")) throw new Exception("Must mention AppendJoin");
if (!(d7.Contains("capacity") || d7.Contains("pre-allocat") || d7.Contains("preallocat"))) throw new Exception("Must mention capacity/pre-allocation");
if (!(d7.Contains("in-place") || d7.Contains... |
8 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
using System.Text.Json;
class Program
{
static (string name, int age) ParsePerson(string json)
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
string name = root.GetProperty("name").GetString() ?? "... | static string DescribeParsePerson()
{
return "Uses JsonDocument.Parse(string) which parses JSON into a read-only DOM "
+ "backed by pooled memory from ArrayPool<byte>. JsonDocument implements "
+ "IDisposable — the using statement ensures pooled buffers are returned. "
... |
static void Main()
{
var (name, age) = ParsePerson("{\"name\": \"Alice\", \"age\": 30}");
if (name != "Alice" || age != 30) throw new Exception("Parse failed");
bool threw = false;
try { ParsePerson("{\"name\": \"Bob\"}"); }
catch (KeyNotFoundException) { threw = true; ... | string d8 = DescribeParsePerson().ToLower();
if (!d8.Contains("jsondocument")) throw new Exception("Must mention JsonDocument");
if (!(d8.Contains("idisposable") || d8.Contains("disposable") || d8.Contains("using"))) throw new Exception("Must mention IDisposable");
if (!(d8.Contains("arraypool") || d8.Contains("pooled"... |
9 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static bool SafeInsert(Dictionary<string, int> dict, string key, int value)
{
return dict.TryAdd(key, value);
}
static void ForceInsert(Dictionary<string, int> dict, string key, int value)
{
dict.Add(key, value);
}... | static string DescribeSafeInsert()
{
return "Uses Dictionary.TryAdd(TKey, TValue) which returns false without throwing "
+ "if the key already exists — unlike Add which throws ArgumentException for "
+ "duplicate keys. TryAdd is O(1) amortized for hash table insertion. "
... |
static void Main()
{
var dict = new Dictionary<string, int>();
bool added1 = SafeInsert(dict, "x", 10);
if (!added1) throw new Exception("First insert should succeed");
bool added2 = SafeInsert(dict, "x", 20);
if (added2) throw new Exception("Duplicate insert should re... | string d9 = DescribeSafeInsert().ToLower();
if (!d9.Contains("tryadd")) throw new Exception("Must mention TryAdd");
if (!d9.Contains("argumentexception")) throw new Exception("Must mention ArgumentException for duplicate keys");
if (!(d9.Contains("false") && (d9.Contains("without throwing") || d9.Contains("does not thr... |
10 | devbench-api-usage | c_sharp | using System;
using System.Threading.Tasks;
using System.Collections.Generic;
class Program
{
static async Task<int[]> RunAll(params Func<Task<int>>[] factories)
{
var tasks = new List<Task<int>>();
foreach (var f in factories)
tasks.Add(f());
return await Task.WhenAll(tasks... | static string DescribeRunAll()
{
return "Uses Task.WhenAll(IEnumerable<Task<TResult>>) which returns a single Task<TResult[]> "
+ "that completes when ALL input tasks complete. The result array preserves the "
+ "original task order (not completion order). If any task faults, W... |
static async Task Main()
{
int[] results = await RunAll(
async () => { await Task.Delay(10); return 1; },
async () => { await Task.Delay(5); return 2; },
async () => { return 3; }
);
if (results.Length != 3) throw new Exception("Expected 3 results");... | string d10 = DescribeRunAll().ToLower();
if (!d10.Contains("whenall")) throw new Exception("Must mention WhenAll");
if (!(d10.Contains("order") && (d10.Contains("preserv") || d10.Contains("original")))) throw new Exception("Must mention order preservation");
if (!d10.Contains("aggregateexception")) throw new Exception(... |
11 | devbench-api-usage | c_sharp | using System;
using System.Buffers;
namespace ApiTask11
{
public class Program
{
public static int SumWithRentedBuffer(int[] source)
{
int[] buffer = ArrayPool<int>.Shared.Rent(source.Length);
try
{
Array.Copy(source, buffer, source.Length);
... | public static string DescribeSumWithRentedBuffer()
{
return "Rents a buffer from ArrayPool<int>.Shared.Rent(minimumLength) which may "
+ "return an array LARGER than requested (power-of-two sizing). Copies source "
+ "via Array.Copy then sums only source.Len... |
public static void Main(string[] args)
{
int result = SumWithRentedBuffer(new int[] { 1, 2, 3, 4, 5 });
if (result != 15) throw new Exception("Sum failed");
string desc = DescribeSumWithRentedBuffer();
if (string.IsNullOrEmpty(desc)) throw new Exception(... | string d11 = ApiTask11.Program.DescribeSumWithRentedBuffer().ToLower();
if (!d11.Contains("larger than requested") && !d11.Contains("bigger than") && !d11.Contains("may return a larger") && !d11.Contains("power-of-two") && !d11.Contains("power of two")) throw new Exception("Must mention buffer may be larger than reques... |
12 | devbench-api-usage | c_sharp | using System;
namespace ApiTask12
{
public class Program
{
public static int SumMiddleThird(ReadOnlySpan<int> data)
{
int start = data.Length / 3;
int end = 2 * data.Length / 3;
ReadOnlySpan<int> slice = data.Slice(start, end - start);
int sum = 0... | public static string DescribeSumMiddleThird()
{
return "Uses ReadOnlySpan<int> which is a stack-only ref struct that cannot "
+ "be boxed, stored on the heap, or used in async methods. Slice(start, length) "
+ "creates a new ReadOnlySpan over the same underl... |
public static void Main(string[] args)
{
int[] data = { 10, 20, 30, 40, 50, 60 };
int result = SumMiddleThird(data);
if (result != 70) throw new Exception($"Expected 70, got {result}");
string desc = DescribeSumMiddleThird();
if (string.IsNul... | string d12 = ApiTask12.Program.DescribeSumMiddleThird().ToLower();
if (!d12.Contains("ref struct")) throw new Exception("Must mention ref struct");
if (!d12.Contains("stack") || (!d12.Contains("heap") && !d12.Contains("boxed"))) throw new Exception("Must mention stack-only / cannot be on heap");
if (!d12.Contains("zero... |
13 | devbench-api-usage | c_sharp | using System;
using System.Numerics;
namespace ApiTask13
{
public class Program
{
public static BigInteger Factorial(int n)
{
BigInteger result = BigInteger.One;
for (int i = 2; i <= n; i++)
result = BigInteger.Multiply(result, new BigInteger(i));
... | public static string DescribeFactorial()
{
return "Uses System.Numerics.BigInteger which is an immutable, arbitrary-precision "
+ "signed integer — no overflow is possible. BigInteger.One is a static readonly "
+ "field (not a property) representing the valu... |
public static void Main(string[] args)
{
BigInteger f10 = Factorial(10);
if (f10 != 3628800) throw new Exception("10! wrong");
BigInteger f20 = Factorial(20);
if (f20 != BigInteger.Parse("2432902008176640000")) throw new Exception("20! wrong");
... | string d13 = ApiTask13.Program.DescribeFactorial().ToLower();
if (!d13.Contains("immutable")) throw new Exception("Must mention immutable");
if (!d13.Contains("arbitrary-precision") && !d13.Contains("arbitrary precision") && !d13.Contains("unlimited precision")) throw new Exception("Must mention arbitrary-precision");
... |
14 | devbench-api-usage | c_sharp | using System;
using System.Net;
using System.Net.Sockets;
namespace ApiTask14
{
public class Program
{
public static string ClassifyAddress(string input)
{
if (!IPAddress.TryParse(input, out IPAddress addr))
return "INVALID";
if (addr.AddressFamily == Add... | public static string DescribeClassifyAddress()
{
return "Uses IPAddress.TryParse which returns bool and sets the out parameter "
+ "to null on failure (not IPAddress.None). AddressFamily is an enum with "
+ "InterNetwork for IPv4 and InterNetworkV6 for IPv6 ... |
public static void Main(string[] args)
{
if (ClassifyAddress("10.0.0.1") != "PRIVATE_A") throw new Exception("10.x fail");
if (ClassifyAddress("127.0.0.1") != "LOOPBACK") throw new Exception("Loopback fail");
if (ClassifyAddress("::1") != "IPv6") throw new Exception(... | string d14 = ApiTask14.Program.DescribeClassifyAddress().ToLower();
if (!d14.Contains("tryparse") || !d14.Contains("bool")) throw new Exception("Must mention TryParse returns bool");
if (!d14.Contains("null") && !d14.Contains("out parameter")) throw new Exception("Must mention out param is null on failure");
if (!d14.C... |
15 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
namespace ApiTask15
{
public class Program
{
public static (int symDiffCount, int interCount, bool isProperSubset)
AnalyzeSets(int[] a, int[] b)
{
var setA = new HashSet<int>(a);
var setB = new HashSet<int>(b);
... | public static string DescribeAnalyzeSets()
{
return "Uses HashSet<int> set-theoretic methods. SymmetricExceptWith MUTATES the "
+ "set in-place to contain only elements in one set or the other, not both — "
+ "it does NOT return a new HashSet. IntersectWith ... |
public static void Main(string[] args)
{
var (sd, ic, ps) = AnalyzeSets(new[] {1,2,3}, new[] {2,3,4});
if (sd != 2) throw new Exception($"SymDiff count: expected 2, got {sd}");
if (ic != 2) throw new Exception($"Intersect count: expected 2, got {ic}");
if... | string d15 = ApiTask15.Program.DescribeAnalyzeSets().ToLower();
if (!d15.Contains("mutate") && !d15.Contains("in-place") && !d15.Contains("in place") && !d15.Contains("modifies")) throw new Exception("Must mention in-place mutation");
if (!d15.Contains("symmetricexceptwith") && !d15.Contains("symmetric except")) throw ... |
16 | devbench-api-usage | c_sharp | using System;
using System.IO;
namespace ApiTask16
{
public class Program
{
public static string GetConfigPath(string appName)
{
string envOverride = Environment.GetEnvironmentVariable("CONFIG_DIR");
if (envOverride != null)
return Path.Combine(envOverrid... | public static string DescribeGetConfigPath()
{
return "Uses Environment.GetEnvironmentVariable which returns null (not empty "
+ "string) when the variable does not exist — this differs from "
+ "GetEnvironmentVariable(name, EnvironmentVariableTarget) overlo... |
public static void Main(string[] args)
{
Environment.SetEnvironmentVariable("CONFIG_DIR", "/tmp/cfg");
string result = GetConfigPath("myapp");
string expected = Path.Combine("/tmp/cfg", "myapp");
if (result != expected) throw new Exception($"Expected {exp... | string d16 = ApiTask16.Program.DescribeGetConfigPath().ToLower();
if (!d16.Contains("null") || d16.Contains("empty string") && !d16.Contains("returns null")) throw new Exception("Must mention GetEnvironmentVariable returns null when not found");
if (!d16.Contains("environmentvariabletarget") && !d16.Contains("machine")... |
17 | devbench-api-usage | c_sharp | using System;
using System.IO;
using System.Text;
namespace ApiTask17
{
public class Program
{
public static byte[] PackRecord(int id, string name, double score)
{
using var ms = new MemoryStream();
using (var bw = new BinaryWriter(ms, Encoding.UTF8, leaveOpen: true))
... | public static string DescribePackRecord()
{
return "Uses BinaryWriter.Write(int) which writes 4 bytes in little-endian order. "
+ "BinaryWriter.Write(string) writes a length-prefixed UTF-8 string: the "
+ "length is encoded as a 7-bit variable-length integer... |
public static void Main(string[] args)
{
byte[] packed = PackRecord(42, "Alice", 95.5);
var (id, name, score) = UnpackRecord(packed);
if (id != 42) throw new Exception("id mismatch");
if (name != "Alice") throw new Exception("name mismatch");
... | string d17 = ApiTask17.Program.DescribePackRecord().ToLower();
if (!d17.Contains("little-endian") && !d17.Contains("little endian")) throw new Exception("Must mention little-endian byte order");
if (!d17.Contains("length-prefix") && !d17.Contains("length prefix") && !d17.Contains("leb128") && !d17.Contains("7-bit")) th... |
18 | devbench-api-usage | c_sharp | using System;
using System.Diagnostics;
using System.Threading;
namespace ApiTask18
{
public class Program
{
public static double MeasureElapsedMs(Action action)
{
long start = Stopwatch.GetTimestamp();
action();
long end = Stopwatch.GetTimestamp();
... | public static string DescribeMeasureElapsedMs()
{
return "Uses Stopwatch.GetTimestamp() which is a static method returning the "
+ "current value of the high-resolution performance counter as a long. "
+ "Stopwatch.Frequency is a static readonly field giving... |
public static void Main(string[] args)
{
double elapsed = MeasureElapsedMs(() => Thread.Sleep(50));
if (elapsed < 30 || elapsed > 500) throw new Exception($"Elapsed {elapsed}ms out of range");
string desc = DescribeMeasureElapsedMs();
if (string.IsNullOr... | string d18 = ApiTask18.Program.DescribeMeasureElapsedMs().ToLower();
if (!d18.Contains("gettimestamp") && !d18.Contains("get timestamp")) throw new Exception("Must mention GetTimestamp");
if (!d18.Contains("frequency")) throw new Exception("Must mention Frequency field");
if (!d18.Contains("platform-dependent") && !d18... |
19 | devbench-api-usage | c_sharp | using System;
namespace ApiTask19
{
[Flags]
public enum Permissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4,
All = Read | Write | Execute
}
public class Program
{
public static string CheckPermissions(string input)
{
if (... | public static string DescribeCheckPermissions()
{
return "Uses Enum.TryParse<T>(string, bool ignoreCase, out T result) which "
+ "returns true even for integer strings ('3') and undefined combinations — "
+ "TryParse succeeds for ANY valid integer, not just ... |
public static void Main(string[] args)
{
if (CheckPermissions("Read") != "Read") throw new Exception("Read parse fail");
if (CheckPermissions("read") != "Read") throw new Exception("Case-insensitive fail");
if (CheckPermissions("garbage") != "INVALID") throw new Exce... | string d19 = ApiTask19.Program.DescribeCheckPermissions().ToLower();
if (!d19.Contains("tryparse")) throw new Exception("Must mention TryParse");
if (!d19.Contains("integer string") && !d19.Contains("integer value") && !d19.Contains("any valid integer") && !d19.Contains("numeric")) throw new Exception("Must mention Try... |
20 | devbench-api-usage | c_sharp | using System;
using System.Text;
namespace ApiTask20
{
public class Program
{
public static string EncodeToBase64(string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
return Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
}
... | public static string DescribeBase64Operations()
{
return "Uses Convert.ToBase64String with Base64FormattingOptions.InsertLineBreaks "
+ "which inserts a line break every 76 characters (MIME standard RFC 2045). "
+ "Without the option, no line breaks are inse... |
public static void Main(string[] args)
{
string encoded = EncodeToBase64("Hello, World!");
string decoded = DecodeFromBase64(encoded.Replace("\r\n", ""));
if (decoded != "Hello, World!") throw new Exception("Roundtrip failed");
string simple = Convert.To... | string d20 = ApiTask20.Program.DescribeBase64Operations().ToLower();
if (!d20.Contains("insertlinebreaks") && !d20.Contains("insert line breaks") && !d20.Contains("line break")) throw new Exception("Must mention InsertLineBreaks option");
if (!d20.Contains("76") && !d20.Contains("seventy-six")) throw new Exception("Mus... |
21 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
public class AUTask21
{
public static List<string> ExtractDescendants(string xml, string tagName)
{
XDocument doc = XDocument.Parse(xml);
return doc.Descendants(tagName)
.Select(e => e.Va... | public static string DescribeExtractDescendants()
{
return "Parses XML string using XDocument.Parse(string) which returns an XDocument. "
+ "Calls Descendants(XName) to find all elements matching tagName at any depth. "
+ "Descendants performs a depth-first traversal of the ent... |
static void Main()
{
string xml = "<root><a><b>hello</b><b>world</b></a><b>outer</b></root>";
var results = ExtractDescendants(xml, "b");
if (!(results.Count == 3)) throw new Exception("Expected 3 descendants");
if (!(results[0] == "hello")) throw new Exception("First should be ... | string d21 = AUTask21.DescribeExtractDescendants().ToLower();
if (!d21.Contains("xdocument.parse")) throw new Exception("Must mention XDocument.Parse");
if (!d21.Contains("descendants")) throw new Exception("Must mention Descendants method");
if (!d21.Contains("depth-first") && !d21.Contains("any depth")) throw new Exc... |
22 | devbench-api-usage | c_sharp | using System;
using System.Reflection;
public class AUTask22
{
public static int Add(int a, int b) => a + b;
public static object InvokeByName(Type type, string methodName, object[] args)
{
MethodInfo mi = type.GetMethod(methodName,
BindingFlags.Public | BindingFlags.Static);
i... | public static string DescribeInvokeByName()
{
return "Retrieves a MethodInfo via Type.GetMethod(string, BindingFlags) with "
+ "BindingFlags.Public | BindingFlags.Static to search only public static methods. "
+ "GetMethod returns null if no matching method exists, so the code ... |
static void Main()
{
object result = InvokeByName(typeof(AUTask22), "Add", new object[] { 3, 4 });
if (!((int)result == 7)) throw new Exception("Expected 7");
}
}
| string d22 = AUTask22.DescribeInvokeByName().ToLower();
if (!d22.Contains("getmethod")) throw new Exception("Must mention GetMethod");
if (!d22.Contains("bindingflags")) throw new Exception("Must mention BindingFlags");
if (!(d22.Contains("public") && d22.Contains("static"))) throw new Exception("Must mention Public an... |
23 | devbench-api-usage | c_sharp | using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class RateLimitAttribute : Attribute
{
public int MaxCalls { get; }
public int PeriodSeconds { get; }
public RateLimitAttribute(int maxCalls, int periodSeconds)
{
Ma... | public static string DescribeGetRateLimit()
{
return "Uses MethodInfo.GetCustomAttribute<T>(bool) generic method with inherit=false "
+ "to retrieve only directly-applied attributes, not inherited ones. "
+ "The RateLimitAttribute is decorated with AttributeUsage specifying "
... |
static void Main()
{
var method = typeof(AUTask23).GetMethod("ApiEndpoint");
var (maxCalls, period) = GetRateLimit(method);
if (!(maxCalls == 100)) throw new Exception("Expected 100 max calls");
if (!(period == 60)) throw new Exception("Expected 60 second period");
}
}
| string d23 = AUTask23.DescribeGetRateLimit().ToLower();
if (!d23.Contains("getcustomattribute")) throw new Exception("Must mention GetCustomAttribute");
if (!d23.Contains("inherit")) throw new Exception("Must mention inherit parameter");
if (!d23.Contains("false")) throw new Exception("Must mention inherit=false");
if ... |
24 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
public class AUTask24
{
public static ReadOnlyCollection<int> WrapAsReadOnly(List<int> source)
{
return source.AsReadOnly();
}
| public static string DescribeWrapAsReadOnly()
{
return "Calls List<T>.AsReadOnly() which returns a ReadOnlyCollection<T> that is "
+ "a thin wrapper around the original list, not a copy. Mutations to the "
+ "underlying source list are visible through the ReadOnlyCollection bec... |
static void Main()
{
var source = new List<int> { 1, 2, 3 };
var ro = WrapAsReadOnly(source);
if (!(ro.Count == 3)) throw new Exception("Expected count 3");
source.Add(4);
if (!(ro.Count == 4)) throw new Exception("ReadOnly should reflect source mutation");
bool ... | string d24 = AUTask24.DescribeWrapAsReadOnly().ToLower();
if (!d24.Contains("asreadonly")) throw new Exception("Must mention AsReadOnly method");
if (!(d24.Contains("wrapper") || d24.Contains("wraps"))) throw new Exception("Must mention wrapper semantics");
if (!(d24.Contains("not a copy") || d24.Contains("reference"))... |
25 | devbench-api-usage | c_sharp | using System;
using System.Threading;
public class AUTask25
{
private static int _initCount = 0;
public static Lazy<string> CreateExpensiveResource()
{
return new Lazy<string>(() =>
{
Interlocked.Increment(ref _initCount);
return "Resource_" + _initCount;
},... | public static string DescribeLazyInit()
{
return "Creates a Lazy<T> with a Func<T> factory and LazyThreadSafetyMode.ExecutionAndPublication. "
+ "ExecutionAndPublication ensures exactly one thread executes the factory; other threads "
+ "block until initialization completes, th... |
static void Main()
{
var lazy = CreateExpensiveResource();
if (!(lazy.IsValueCreated == false)) throw new Exception("Should not be created yet");
string val1 = lazy.Value;
string val2 = lazy.Value;
if (!(val1 == val2)) throw new Exception("Should return same cached value... | string d25 = AUTask25.DescribeLazyInit().ToLower();
if (!d25.Contains("executionandpublication")) throw new Exception("Must mention ExecutionAndPublication mode");
if (!(d25.Contains("exactly one thread") || d25.Contains("single thread"))) throw new Exception("Must mention single-thread execution guarantee");
if (!(d25... |
26 | devbench-api-usage | c_sharp | using System;
using System.IO;
using System.IO.Compression;
using System.Text;
public class AUTask26
{
public static byte[] CompressString(string text)
{
byte[] raw = Encoding.UTF8.GetBytes(text);
using (var output = new MemoryStream())
{
using (var gzip = new GZipStream(out... | public static string DescribeCompression()
{
return "CompressString converts text to bytes via Encoding.UTF8.GetBytes, then wraps a "
+ "MemoryStream with GZipStream(Stream, CompressionMode.Compress, leaveOpen: true). "
+ "leaveOpen: true prevents GZipStream.Dispose from closin... |
static void Main()
{
string original = "Hello, GZip compression test!";
byte[] compressed = CompressString(original);
if (!(compressed.Length > 0)) throw new Exception("Compressed should be non-empty");
string decompressed = DecompressToString(compressed);
if (!(decompre... | string d26 = AUTask26.DescribeCompression().ToLower();
if (!d26.Contains("gzipstream")) throw new Exception("Must mention GZipStream");
if (!d26.Contains("compressionmode.compress")) throw new Exception("Must mention CompressionMode.Compress");
if (!d26.Contains("leaveopen")) throw new Exception("Must mention leaveOpen... |
27 | devbench-api-usage | c_sharp | using System;
using System.Threading;
public class AUTask27
{
private static int _value = 0;
public static int AtomicMax(ref int location, int comparand)
{
int initial, computed;
do
{
initial = location;
computed = Math.Max(initial, comparand);
}
... | public static string DescribeAtomicMax()
{
return "Implements a lock-free atomic maximum using Interlocked.CompareExchange(ref int, int, int) "
+ "in a CAS (compare-and-swap) spin loop. The loop reads the current value into 'initial', "
+ "computes Math.Max(initial, comparand),... |
static void Main()
{
_value = 5;
int result = AtomicMax(ref _value, 10);
if (!(result == 10)) throw new Exception("Expected max 10");
if (!(_value == 10)) throw new Exception("Location should be 10");
result = AtomicMax(ref _value, 3);
if (!(result == 10)) throw ... | string d27 = AUTask27.DescribeAtomicMax().ToLower();
if (!d27.Contains("compareexchange")) throw new Exception("Must mention CompareExchange");
if (!(d27.Contains("cas") || d27.Contains("compare-and-swap") || d27.Contains("compare and swap"))) throw new Exception("Must mention CAS pattern");
if (!(d27.Contains("spin") ... |
28 | devbench-api-usage | c_sharp | using System;
public class AUTask28
{
public static double NextUp(double value)
{
return Math.BitIncrement(value);
}
public static double NextDown(double value)
{
return Math.BitDecrement(value);
}
public static double FusedMulAdd(double x, double y, double z)
{
... | public static string DescribeFloatOps()
{
return "NextUp uses Math.BitIncrement(double) which returns the smallest double value "
+ "that is greater than the argument. It increments the binary representation by "
+ "one ULP (unit in the last place). For positive infinity, it re... |
static void Main()
{
double up = NextUp(1.0);
if (!(up > 1.0)) throw new Exception("BitIncrement should be > 1.0");
if (!(up < 1.0 + 1e-10)) throw new Exception("BitIncrement should be very close to 1.0");
double down = NextDown(1.0);
if (!(down < 1.0)) throw new Excepti... | string d28 = AUTask28.DescribeFloatOps().ToLower();
if (!d28.Contains("bitincrement")) throw new Exception("Must mention BitIncrement");
if (!d28.Contains("bitdecrement")) throw new Exception("Must mention BitDecrement");
if (!(d28.Contains("ulp") || d28.Contains("unit in the last place"))) throw new Exception("Must me... |
29 | devbench-api-usage | c_sharp | using System;
public class AUTask29
{
public static WeakReference<object> CreateWeakRef(object target)
{
return new WeakReference<object>(target, trackResurrection: false);
}
public static bool TryGetTarget(WeakReference<object> weakRef, out object target)
{
return weakRef.TryGetTa... | public static string DescribeWeakReference()
{
return "Creates a WeakReference<T> with trackResurrection: false, meaning the reference "
+ "becomes invalid once the target is finalized (short weak reference). "
+ "TryGetTarget(out T) atomically checks if the target is still ali... |
static void Main()
{
var obj = new object();
var wr = CreateWeakRef(obj);
object target;
if (!(TryGetTarget(wr, out target))) throw new Exception("Should find live target");
if (!(ReferenceEquals(target, obj))) throw new Exception("Should be same object");
var ne... | string d29 = AUTask29.DescribeWeakReference().ToLower();
if (!d29.Contains("trackresurrection")) throw new Exception("Must mention trackResurrection parameter");
if (!(d29.Contains("short weak") || d29.Contains("finalized"))) throw new Exception("Must mention short weak reference or finalization semantics");
if (!d29.C... |
30 | devbench-api-usage | c_sharp | using System;
using System.Xml.Linq;
using System.Linq;
public class AUTask30
{
private static readonly XNamespace Ns = "http://example.com/data";
public static XDocument BuildDocument(string rootName, (string name, string value)[] items)
{
var root = new XElement(Ns + rootName,
new XA... | public static string DescribeBuildDocument()
{
return "Constructs an XDocument with XDeclaration('1.0', 'utf-8', 'yes') where 'yes' is "
+ "the standalone flag. Creates root XElement using XNamespace + string operator to produce "
+ "a qualified XName in the namespace. Adds XAt... |
static void Main()
{
var items = new (string, string)[] { ("item", "A"), ("item", "B") };
XDocument doc = BuildDocument("root", items);
string decl = GetDeclarationString(doc);
if (!decl.Contains("utf-8")) throw new Exception("Declaration should contain utf-8");
if (!dec... | string d30 = AUTask30.DescribeBuildDocument().ToLower();
if (!d30.Contains("xdeclaration")) throw new Exception("Must mention XDeclaration");
if (!d30.Contains("standalone")) throw new Exception("Must mention standalone flag");
if (!d30.Contains("xnamespace")) throw new Exception("Must mention XNamespace");
if (!(d30.C... |
31 | devbench-api-usage | c_sharp | using System;
class Program
{
static Uri ParseAbsoluteUri(string input)
{
Uri result;
bool ok = Uri.TryCreate(input, UriKind.Absolute, out result);
if (!ok) return null;
return result;
}
static string GetIdnHost(Uri uri)
{
return uri.GetComponents(UriCompone... | static string DescribeParseAbsoluteUri()
{
return "Uses Uri.TryCreate(string, UriKind.Absolute, out Uri) which returns false "
+ "for relative URIs or malformed input without throwing UriFormatException. "
+ "UriKind.Absolute requires a scheme (http, ftp, etc.) — schemeless str... |
static void Main()
{
Uri u = ParseAbsoluteUri("http://Example.COM/path?q=1");
if (u == null) throw new Exception("Should parse valid absolute URI");
if (u.Scheme != "http") throw new Exception("Scheme should be http");
if (u.Host != "example.com") throw new Exception("Host shoul... | string d31 = Program.DescribeParseAbsoluteUri().ToLower();
if (!d31.Contains("urikind.absolute") && !d31.Contains("urikind absolute")) throw new Exception("Must mention UriKind.Absolute");
if (!d31.Contains("uriformatexception") && !d31.Contains("without throwing")) throw new Exception("Must mention no exception thrown... |
32 | devbench-api-usage | c_sharp | using System;
class Program
{
static int CompareVersions(string a, string b)
{
Version va = Version.Parse(a);
Version vb = Version.Parse(b);
return va.CompareTo(vb);
}
static bool IsPrerelease(string ver)
{
Version v = Version.Parse(ver);
return v.Revision =... | static string DescribeCompareVersions()
{
return "Version.Parse(string) parses 'major.minor[.build[.revision]]' where "
+ "major and minor are required. Unparsed components default to -1 (not 0), "
+ "so '1.0' has Build=-1 and Revision=-1. CompareTo compares component by "
... |
static void Main()
{
if (CompareVersions("2.0", "1.9") <= 0) throw new Exception("2.0 > 1.9");
if (CompareVersions("1.0", "1.0.0") >= 0) throw new Exception("1.0 < 1.0.0 because Build -1 < 0");
if (!IsPrerelease("1.0")) throw new Exception("1.0 has Revision -1");
if (IsPrereleas... | string d32 = Program.DescribeCompareVersions().ToLower();
if (!d32.Contains("-1")) throw new Exception("Must mention -1 default for undefined components");
if (!d32.Contains("not 0") && !d32.Contains("not zero")) throw new Exception("Must clarify defaults are -1, not 0");
if (!(d32.Contains("1.0") && d32.Contains("1.0.... |
33 | devbench-api-usage | c_sharp | using System;
class Program
{
static void Main()
{
int original = 0x01020304;
| byte[] bytes = BitConverter.GetBytes(original);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(bytes);
}
int restored = BitConverter.ToInt32(BitConverter.IsLittleEndian ? GetReversed(bytes) : bytes, 0);
|
if (restored != original) throw new Exception("Round-trip failed: " + restored);
// Verify big-endian byte order after our reversal
if (BitConverter.IsLittleEndian)
{
if (bytes[0] != 0x01) throw new Exception("Expected MSB first after reverse");
if (bytes[3] != ... | byte[] testBytes = BitConverter.GetBytes((int)0x0A0B0C0D);
if (BitConverter.IsLittleEndian)
{
if (testBytes[0] != 0x0D) throw new Exception("Little-endian: LSB should be first byte");
if (testBytes[3] != 0x0A) throw new Exception("Little-endian: MSB should be last byte");
}
int roundTrip = BitConverter.ToInt32(... |
34 | devbench-api-usage | c_sharp | using System;
class Program
{
static int FindOrInsertionPoint(int[] sorted, int value)
{
int idx = Array.BinarySearch(sorted, value);
return idx >= 0 ? idx : ~idx;
}
| static string DescribeFindOrInsertionPoint()
{
return "Uses Array.BinarySearch(Array, Object) which performs O(log n) binary search "
+ "on a SORTED array. Returns the zero-based index if found. If NOT found, returns "
+ "the bitwise complement (~) of the index of the next elem... |
static void Main()
{
int[] arr = { 1, 3, 5, 7, 9 };
if (FindOrInsertionPoint(arr, 5) != 2) throw new Exception("Should find 5 at index 2");
if (FindOrInsertionPoint(arr, 4) != 2) throw new Exception("4 would insert at index 2");
if (FindOrInsertionPoint(arr, 0) != 0) throw new E... | string d34 = Program.DescribeFindOrInsertionPoint().ToLower();
if (!d34.Contains("bitwise complement") && !d34.Contains("~")) throw new Exception("Must mention bitwise complement");
if (!d34.Contains("sorted")) throw new Exception("Must mention sorted requirement");
if (!d34.Contains("undefined") && !d34.Contains("not ... |
35 | devbench-api-usage | c_sharp | using System;
using System.Data;
class Program
{
static void Main()
{
DataTable table = new DataTable("Sales");
table.Columns.Add("Product", typeof(string));
table.Columns.Add("Qty", typeof(int));
table.Columns.Add("Price", typeof(decimal));
| table.Columns.Add("Total", typeof(decimal), "Qty * Price");
table.Rows.Add("Widget", 5, 3.50m);
table.Rows.Add("Gadget", 2, 12.00m);
table.Rows.Add("Widget", 3, 3.50m);
DataRow[] widgets = table.Select("Product = 'Widget'", "Total DESC");
decimal firstTotal = (decimal)w... |
if (widgets.Length != 2) throw new Exception("Should find 2 Widget rows, got " + widgets.Length);
if (firstTotal != 17.50m) throw new Exception("First Widget total should be 17.50 (5*3.50), got " + firstTotal);
decimal secondTotal = (decimal)widgets[1]["Total"];
if (secondTotal != 10.50... | DataTable dt = new DataTable();
dt.Columns.Add("A", typeof(int));
dt.Columns.Add("B", typeof(int));
dt.Columns.Add("C", typeof(int), "A + B");
dt.Rows.Add(1, 2);
if ((int)dt.Rows[0]["C"] != 3) throw new Exception("Expression column should compute");
dt.Rows[0]["A"] = 10;
if ((int)dt.Rows[0]["C"] != 12) throw new Except... |
36 | devbench-api-usage | c_sharp | using System;
class Program
{
static void SafeCopy(Array src, int srcIdx, Array dst, int dstIdx, int len)
{
Array.ConstrainedCopy(src, srcIdx, dst, dstIdx, len);
}
static void RegularCopy(Array src, int srcIdx, Array dst, int dstIdx, int len)
{
Array.Copy(src, srcIdx, dst, dstIdx, ... | static string DescribeSafeCopy()
{
return "Array.ConstrainedCopy provides atomicity: either ALL elements are copied or "
+ "NONE are (the destination is unchanged on failure). This differs from Array.Copy "
+ "which may leave the destination partially modified if an exception o... |
static void Main()
{
int[] src = { 1, 2, 3, 4, 5 };
int[] dst = { 0, 0, 0, 0, 0 };
SafeCopy(src, 1, dst, 0, 3);
if (dst[0] != 2 || dst[1] != 3 || dst[2] != 4) throw new Exception("ConstrainedCopy failed");
if (dst[3] != 0) throw new Exception("Should not modify beyond le... | string d36 = Program.DescribeSafeCopy().ToLower();
if (!d36.Contains("atomic") && !d36.Contains("all or nothing") && !d36.Contains("all elements")) throw new Exception("Must mention atomicity guarantee");
if (!d36.Contains("array.copy")) throw new Exception("Must contrast with Array.Copy");
if (!d36.Contains("partially... |
37 | devbench-api-usage | c_sharp | using System;
using System.Collections.Specialized;
class Program
{
static void Main()
{
NameValueCollection nvc = new NameValueCollection();
| nvc.Add("color", "red");
nvc.Add("color", "blue");
nvc.Add("size", "large");
string colors = nvc.Get("color");
string[] colorArray = nvc.GetValues("color");
int keyCount = nvc.Count;
|
// Get returns comma-separated for multiple values
if (colors != "red,blue") throw new Exception("Get should return 'red,blue', got: " + colors);
if (colorArray.Length != 2) throw new Exception("GetValues should return 2 items");
if (colorArray[0] != "red" || colorArray[1] != "blue") th... | NameValueCollection test = new NameValueCollection();
test.Add("k", "v1");
test.Add("k", "v2");
test.Add("k", "v3");
if (test.Get("k") != "v1,v2,v3") throw new Exception("Get should comma-join multiple values");
if (test.Count != 1) throw new Exception("Count counts keys, not values");
test.Set("k", "only");
if (test.G... |
38 | devbench-api-usage | c_sharp | using System;
class Program
{
static void GrowArray(ref int[] arr, int newSize)
{
Array.Resize(ref arr, newSize);
}
| static string DescribeGrowArray()
{
return "Array.Resize<T>(ref T[], int) does NOT resize the array in-place. It allocates "
+ "a NEW array of the specified size, copies elements from the old array (up to "
+ "Math.Min(old.Length, newSize)), and assigns the new array to the ref... |
static void Main()
{
int[] original = { 1, 2, 3 };
int[] alias = original;
GrowArray(ref original, 5);
// Original reference now points to new array
if (original.Length != 5) throw new Exception("Should be length 5");
if (original[3] != 0) throw new Exception("N... | string d38 = Program.DescribeGrowArray().ToLower();
if (!d38.Contains("new array") && !d38.Contains("allocate")) throw new Exception("Must mention new array allocation");
if (!d38.Contains("not") && !d38.Contains("does not")) throw new Exception("Must mention does NOT resize in-place");
if (!d38.Contains("ref")) throw ... |
39 | devbench-api-usage | c_sharp | using System;
class Program
{
static void Main()
{
Uri uri = new Uri("http://example.com:8080/path/to/resource?key=val&foo=bar#section2");
| string host = uri.Host;
int port = uri.Port;
string path = uri.AbsolutePath;
string query = uri.Query;
string fragment = uri.Fragment;
string authority = uri.Authority;
string pathAndQuery = uri.PathAndQuery;
|
if (host != "example.com") throw new Exception("Host wrong: " + host);
if (port != 8080) throw new Exception("Port wrong: " + port);
if (path != "/path/to/resource") throw new Exception("AbsolutePath wrong: " + path);
// Query includes the leading '?'
if (query != "?key=val&foo=... | Uri u39 = new Uri("https://user:pass@host.com:443/a/b?x=1#frag");
if (u39.Port != 443) throw new Exception("Port should be 443");
if (u39.IsDefaultPort != true) throw new Exception("443 is default for https");
if (!u39.Query.StartsWith("?")) throw new Exception("Query must start with ?");
if (!u39.Fragment.StartsWith("... |
40 | devbench-api-usage | c_sharp | using System;
using System.Collections.Specialized;
class Program
{
static StringDictionary CreateLookup(string[] keys, string[] values)
{
StringDictionary sd = new StringDictionary();
for (int i = 0; i < keys.Length; i++)
{
sd.Add(keys[i], values[i]);
}
retu... | static string DescribeCreateLookup()
{
return "Uses StringDictionary which automatically LOWERCASES all keys on Add, "
+ "ContainsKey, and indexer access. 'Hello' and 'hello' map to the SAME entry — "
+ "Add('Hello','x') followed by Add('hello','y') throws ArgumentException for... |
static void Main()
{
StringDictionary sd = CreateLookup(
new[] { "Name", "COLOR", "Size" },
new[] { "Alice", "Red", "Large" }
);
// Keys are lowercased
if (sd["name"] != "Alice") throw new Exception("Should find 'name' (lowered from 'Name')");
if... | string d40 = Program.DescribeCreateLookup().ToLower();
if (!d40.Contains("lowercase") && !d40.Contains("lower-case") && !d40.Contains("lowered")) throw new Exception("Must mention key lowercasing");
if (!d40.Contains("case-sensitive") && !d40.Contains("case sensitive")) throw new Exception("Must mention case sensitivit... |
41 | devbench-api-usage | c_sharp | using System;
using System.Linq.Expressions;
namespace Bench
{
public class Program
{
/// <summary>
| /// Compiles a BinaryExpression that multiplies two int parameters
/// using Expression.Multiply, wraps it in Expression.Lambda, and
/// invokes Compile() to produce a Func<int,int,int> delegate.
/// The ParameterExpressions are created via Expression.Parameter.
/// </summa... | public static Func<int,int,int> BuildMultiplier()
{
var a = Expression.Parameter(typeof(int), "a");
var b = Expression.Parameter(typeof(int), "b");
var mul = Expression.Multiply(a, b);
var lambda = Expression.Lambda<Func<int,int,int>>(mul, a, b);
... | var fn2 = Program.BuildMultiplier();
if (!(fn2(1, 1) == 1)) throw new Exception("1*1");
if (!(fn2(-3, -4) == 12)) throw new Exception("-3*-4");
// Doc precision checks
var method = typeof(Program).GetMethod("BuildMultiplier");
// We check the XML ... |
42 | devbench-api-usage | c_sharp | using System;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Bench
{
public class Program
{
static void Main()
{
string json = @"{""items"":[{""name"":""A"",""qty"":1},{""name"":""B"",""qty"":2}],""total"":3}";
JsonNode root = JsonNode.Parse(json)!;
... | var items = root["items"]!.AsArray();
var newItem = new JsonObject
{
["name"] = "C",
["qty"] = 5
};
items.Add(newItem);
int newTotal = 0;
foreach (var item in items)
{
newTotal... |
string result = root.ToJsonString();
if (!(root["total"]!.GetValue<int>() == 8)) throw new Exception("total should be 8");
if (!(root["items"]!.AsArray().Count == 3)) throw new Exception("should have 3 items");
var last = root["items"]![2]!;
if (!(last["name"... | // Verify JSON roundtrip preserves structure
var reparsed = JsonNode.Parse(root.ToJsonString())!;
if (!(reparsed["items"]!.AsArray().Count == 3)) throw new Exception("reparse count");
if (!(reparsed["total"]!.GetValue<int>() == 8)) throw new Exception("reparse total");
... |
43 | devbench-api-usage | c_sharp | using System;
namespace Bench
{
public class Program
{
static void Main()
{
int[] data = { 10, 20, 30, 40, 50, 60, 70, 80 };
// Use Index (^) and Range (..) operators to extract slices
| int last = data[^1];
int secondLast = data[^2];
int[] middle = data[2..6];
int[] lastThree = data[^3..];
int[] firstTwo = data[..2];
int[] reversed = data[^4..^1];
|
if (!(last == 80)) throw new Exception("last");
if (!(secondLast == 70)) throw new Exception("secondLast");
if (!(middle.Length == 4 && middle[0] == 30 && middle[3] == 60)) throw new Exception("middle");
if (!(lastThree.Length == 3 && lastThree[0] == 60)) throw new Excep... | // Additional edge cases with Index/Range
int first = data[^8];
if (!(first == 10)) throw new Exception("^8 should be first");
int[] all = data[..];
if (!(all.Length == 8)) throw new Exception("full range");
int[] empty = data[3..3];
if... |
44 | devbench-api-usage | c_sharp | using System;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace Bench
{
public class Program
{
/// <summary>
| /// Creates a bounded Channel<int> with capacity 2 using
/// Channel.CreateBounded with BoundedChannelFullMode.Wait.
/// The producer calls WriteAsync to enqueue values, blocking when
/// the channel is full. The consumer calls ReadAsync in a loop
/// until TryRead returns ... | public static async Task<int> ProduceConsumeAsync(int[] values)
{
var ch = Channel.CreateBounded<int>(new BoundedChannelOptions(2)
{
FullMode = BoundedChannelFullMode.Wait
});
var producer = Task.Run(async () =>
{
... | int r2 = await ProduceConsumeAsync(new[] { 10, 20, 30 });
if (!(r2 == 60)) throw new Exception("10+20+30");
int r3 = await ProduceConsumeAsync(new[] { -1, 1 });
if (!(r3 == 0)) throw new Exception("-1+1");
int r4 = await ProduceConsumeAsync(new[] { 100 });
... |
45 | devbench-api-usage | c_sharp | using System;
using System.Collections.Generic;
using System.Dynamic;
namespace Bench
{
public class TrackedObject : DynamicObject
{
private Dictionary<string, object> _store = new();
private List<string> _accessLog = new();
public List<string> AccessLog => _accessLog;
| public override bool TrySetMember(SetMemberBinder binder, object? value)
{
_store[binder.Name] = value!;
_accessLog.Add("set:" + binder.Name);
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object? result)
{
... | }
public class Program
{
static void Main()
{
dynamic obj = new TrackedObject();
obj.Name = "Alice";
obj.Age = 30;
string name = obj.Name;
int age = obj.Age;
var log = ((TrackedObject)obj).AccessLog;
if (!(... | // Additional: set same property twice, get nonexistent
dynamic obj2 = new TrackedObject();
obj2.X = 1;
obj2.X = 2;
int x = obj2.X;
var log2 = ((TrackedObject)obj2).AccessLog;
if (!(log2.Count == 3)) throw new Exception("log2 count");
... |
46 | devbench-api-usage | c_sharp | using System;
namespace Bench
{
public class Program
{
static int SumSpan(ReadOnlySpan<int> span)
{
int s = 0;
foreach (var v in span) s += v;
return s;
}
static void Main()
{
Span<int> buf = stackalloc int[6];
... | int total = SumSpan(buf);
int firstHalf = SumSpan(buf[..3]);
int lastHalf = SumSpan(buf[3..]);
int mid = SumSpan(buf[1..5]);
int lastTwo = SumSpan(buf[^2..]);
|
if (!(total == 210)) throw new Exception($"total={total}");
if (!(firstHalf == 60)) throw new Exception($"firstHalf={firstHalf}");
if (!(lastHalf == 150)) throw new Exception($"lastHalf={lastHalf}");
if (!(mid == 140)) throw new Exception($"mid={mid}");
if (!... | // Edge slices
int single = SumSpan(buf[2..3]);
if (!(single == 30)) throw new Exception("single slice");
int empty = SumSpan(buf[3..3]);
if (!(empty == 0)) throw new Exception("empty slice");
int fromEnd = SumSpan(buf[^6..^3]);
if (!(f... |
47 | devbench-api-usage | c_sharp | using System;
using System.Globalization;
namespace Bench
{
public class Program
{
/// <summary>
| /// Formats a decimal as currency using a custom NumberFormatInfo
/// where CurrencySymbol is "XYZ", CurrencyGroupSeparator is an
/// underscore, CurrencyDecimalDigits is 3, and CurrencyGroupSizes
/// is {2, 3} meaning the rightmost group has 2 digits and all
/// subsequent group... | public static string FormatCustomCurrency(decimal amount)
{
var nfi = new NumberFormatInfo
{
CurrencySymbol = "XYZ",
CurrencyGroupSeparator = "_",
CurrencyDecimalDigits = 3,
CurrencyGroupSizes = new int[] { 2, 3 }
... | string r4 = Program.FormatCustomCurrency(100000m);
if (!(r4 == "XYZ1_000_00.000")) throw new Exception($"100000: {r4}");
string r5 = Program.FormatCustomCurrency(-42.7m);
if (!(r5 == "(XYZ42.700)" || r5 == "-XYZ42.700" || r5.Contains("42.700"))) throw new Exception($"-42.... |
48 | devbench-api-usage | c_sharp | using System;
using System.Linq.Expressions;
namespace Bench
{
public class Program
{
// Build an expression tree that represents: x => x > 0 ? x * 2 : x * -1
// Must use Expression.Condition, Expression.GreaterThan,
// Expression.Multiply, Expression.Constant
static Func<int, i... | var zero = Expression.Constant(0);
var two = Expression.Constant(2);
var negOne = Expression.Constant(-1);
var test = Expression.GreaterThan(x, zero);
var pos = Expression.Multiply(x, two);
var neg = Expression.Multiply(x, negOne);
var ... | }
static void Main()
{
var fn = BuildAbsDoubler();
if (!(fn(5) == 10)) throw new Exception("5->10");
if (!(fn(-3) == 3)) throw new Exception("-3->3");
if (!(fn(0) == 0)) throw new Exception("0->0");
if (!(fn(1) == 2)) throw new Excepti... | var fn2 = BuildAbsDoubler();
if (!(fn2(100) == 200)) throw new Exception("100->200");
if (!(fn2(-50) == 50)) throw new Exception("-50->50");
if (!(fn2(int.MaxValue / 2) == int.MaxValue / 2 * 2)) throw new Exception("large");
if (!(fn2(-1000) == 1000)) throw ne... |
49 | devbench-api-usage | c_sharp | using System;
using System.IO;
namespace Bench
{
public class Program
{
// Read lines from a StringReader, number them, write to StringWriter
static string NumberLines(string text)
{
var reader = new StringReader(text);
var writer = new StringWriter();
| string? line;
int num = 1;
while ((line = reader.ReadLine()) != null)
{
writer.WriteLine($"{num}: {line}");
num++;
}
return writer.ToString().TrimEnd();
| }
static void Main()
{
string input = "alpha\nbeta\ngamma";
string result = NumberLines(input);
if (!(result == "1: alpha\n2: beta\n3: gamma")) throw new Exception($"got: [{result}]");
string single = NumberLines("only");
if (!(single... | string multi = Program.NumberLines("a\nb\nc\nd\ne");
if (!(multi == "1: a\n2: b\n3: c\n4: d\n5: e")) throw new Exception("multi");
string withSpaces = Program.NumberLines(" x \nhello");
if (!(withSpaces == "1: x \n2: hello")) throw new Exception("spaces");
|
50 | devbench-api-usage | c_sharp | using System;
using System.Globalization;
namespace Bench
{
public class Program
{
/// <summary>
| /// Parses dates using a custom DateTimeFormatInfo where all four
/// month-name arrays (AbbreviatedMonthNames, AbbreviatedMonthGenitiveNames,
/// MonthNames, MonthGenitiveNames) are replaced with Romanian-style names
/// so that standard English month names no longer parse. DateSeparato... | public static DateTime ParseRomanianDate(string s)
{
var ci = new CultureInfo("en-US");
var dtfi = ci.DateTimeFormat;
dtfi.AbbreviatedMonthNames = new[]
{
"Ian", "Fev", "Mrt", "Avr", "Mai", "Iun",
"Iul", "Avg", "Sep", "Okt",... | var d4 = Program.ParseRomanianDate("31.Iul.2023");
if (!(d4.Month == 7 && d4.Day == 31)) throw new Exception("d4 Jul");
var d5 = Program.ParseRomanianDate("10.Avg.2020");
if (!(d5.Month == 8 && d5.Day == 10)) throw new Exception("d5 Aug");
bool threw = false;
... |
1 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<int> FilterPositiveScores(List<int> scores)
{
return scores.Where(s => s > 0).ToList();
}
| static string DescribeFilterPositiveScores()
{
return "Filters the input list using LINQ Where with a predicate that "
+ "selects elements strictly greater than zero, then materializes "
+ "the result via ToList into a new List<int>. The source list is "
+ "not mod... | static void Main(string[] args)
{
var scores = new List<int> { -2, 5, 0, 7, -1, 9 };
var result = FilterPositiveScores(scores);
if (result.Count != 3) throw new Exception("Expected 3 positives");
if (scores[0] != -2 || scores.Count != 6) throw new Exception("Source modified");
... | string d1 = DescribeFilterPositiveScores();
string d1L = d1.ToLower();
if (!d1L.Contains("where")) throw new Exception("must mention Where");
if (!d1L.Contains("tolist")) throw new Exception("must mention ToList");
if (!d1L.Contains("predicate")) throw new Exception("must mention predicate");
if (!d1L.Contains("not mod... |
2 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static int GetOrDefault(Dictionary<string, int> map, string key, int fallback)
{
if (map.TryGetValue(key, out int value))
return value;
return fallback;
}
| static string DescribeGetOrDefault()
{
return "Looks up the key in the Dictionary using TryGetValue, which "
+ "performs an O(1) amortized hash-table probe and writes the "
+ "associated value to an out parameter when the key exists. "
+ "If TryGetValue returns fal... | static void Main(string[] args)
{
var map = new Dictionary<string, int> { { "a", 10 }, { "b", 20 } };
if (GetOrDefault(map, "a", -1) != 10) throw new Exception("wrong existing");
if (GetOrDefault(map, "c", -1) != -1) throw new Exception("wrong missing");
if (map.Count != 2) throw... | string d2 = DescribeGetOrDefault();
string d2L = d2.ToLower();
if (!d2L.Contains("trygetvalue")) throw new Exception("must mention TryGetValue");
if (!d2L.Contains("o(1)")) throw new Exception("must mention O(1) complexity");
if (!d2L.Contains("out parameter") && !d2L.Contains("out param")) throw new Exception("must me... |
3 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Text;
using System.Collections.Generic;
class Program
{
static string JoinWithSeparator(List<string> parts, string sep)
{
var sb = new StringBuilder();
for (int i = 0; i < parts.Count; i++)
{
if (i > 0) sb.Append(sep);
sb.Append(parts[i... | static string DescribeJoinWithSeparator()
{
return "Builds the result using a StringBuilder, appending each element "
+ "from the input List<string> with the separator inserted between "
+ "consecutive elements but not before the first or after the last. "
+ "Strin... | static void Main(string[] args)
{
var parts = new List<string> { "a", "b", "c" };
if (JoinWithSeparator(parts, "-") != "a-b-c") throw new Exception("wrong join");
if (JoinWithSeparator(new List<string>(), ",") != "") throw new Exception("empty fail");
string desc = DescribeJoinWi... | string d3 = DescribeJoinWithSeparator();
string d3L = d3.ToLower();
if (!d3L.Contains("stringbuilder")) throw new Exception("must mention StringBuilder");
if (!d3L.Contains("append")) throw new Exception("must mention Append");
if (!d3L.Contains("separator") || !d3L.Contains("between")) throw new Exception("must mentio... |
4 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<int> RunningMax(List<int> values)
{
var result = new List<int>();
values.Aggregate(int.MinValue, (acc, x) =>
{
int m = Math.Max(acc, x);
result.Add(m);
retu... | static string DescribeRunningMax()
{
return "Computes a running maximum by folding over the input list with "
+ "LINQ Aggregate. The seed is int.MinValue so the first element "
+ "always becomes the initial maximum. The accumulator function "
+ "calls Math.Max to c... | static void Main(string[] args)
{
var vals = new List<int> { 3, 1, 4, 1, 5 };
var rm = RunningMax(vals);
if (rm.Count != 5) throw new Exception("wrong count");
if (rm[0] != 3 || rm[2] != 4 || rm[4] != 5) throw new Exception("wrong values");
string desc = DescribeRunningMa... | string d4 = DescribeRunningMax();
string d4L = d4.ToLower();
if (!d4L.Contains("aggregate")) throw new Exception("must mention Aggregate");
if (!d4L.Contains("int.minvalue")) throw new Exception("must mention int.MinValue seed");
if (!d4L.Contains("math.max")) throw new Exception("must mention Math.Max");
if (!d4L.Cont... |
5 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<int> GetRange(SortedSet<int> set, int lo, int hi)
{
return set.GetViewBetween(lo, hi).ToList();
}
| static string DescribeGetRange()
{
return "Returns elements in the inclusive range [lo, hi] from a SortedSet "
+ "by calling GetViewBetween, which returns a virtual SortedSet view "
+ "backed by the same underlying red-black tree without copying. "
+ "Modifications... | static void Main(string[] args)
{
var set = new SortedSet<int> { 1, 3, 5, 7, 9, 11 };
var range = GetRange(set, 3, 9);
if (range.Count != 4) throw new Exception("wrong count");
if (range[0] != 3 || range[3] != 9) throw new Exception("wrong bounds");
string desc = Describe... | string d5 = DescribeGetRange();
string d5L = d5.ToLower();
if (!d5L.Contains("getviewbetween")) throw new Exception("must mention GetViewBetween");
if (!d5L.Contains("inclusive")) throw new Exception("must mention inclusive range");
if (!d5L.Contains("red-black") || !d5L.Contains("tree")) throw new Exception("must ment... |
6 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static List<string> RoundRobin(Queue<string> queue, int rounds)
{
var log = new List<string>();
for (int i = 0; i < rounds && queue.Count > 0; i++)
{
string item = queue.Dequeue();
log.Add(item);
... | static string DescribeRoundRobin()
{
return "Performs a round-robin cycle on a Queue<string> by calling "
+ "Dequeue to remove the front element in O(1) amortized time, "
+ "appending it to the log list, then re-inserting it at the back "
+ "with Enqueue in O(1) am... | static void Main(string[] args)
{
var q = new Queue<string>(new[] { "A", "B", "C" });
var log = RoundRobin(q, 5);
if (log.Count != 5) throw new Exception("wrong log count");
if (log[0] != "A" || log[3] != "A") throw new Exception("wrong order");
if (q.Count != 3) throw ne... | string d6 = DescribeRoundRobin();
string d6L = d6.ToLower();
if (!d6L.Contains("dequeue")) throw new Exception("must mention Dequeue");
if (!d6L.Contains("enqueue")) throw new Exception("must mention Enqueue");
if (!d6L.Contains("o(1)")) throw new Exception("must mention O(1) amortized");
if (!d6L.Contains("circular") ... |
7 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static Dictionary<char, List<string>> GroupByInitial(List<string> words)
{
return words
.GroupBy(w => char.ToUpperInvariant(w[0]))
.ToDictionary(g => g.Key, g => g.ToList());
}
| static string DescribeGroupByInitial()
{
return "Groups words by their first character using LINQ GroupBy with "
+ "char.ToUpperInvariant as the key selector, producing "
+ "IGrouping<char, string> sequences. ToDictionary then materializes "
+ "each group into a Di... | static void Main(string[] args)
{
var words = new List<string> { "apple", "Avocado", "banana", "Blueberry" };
var groups = GroupByInitial(words);
if (groups.Count != 2) throw new Exception("wrong group count");
if (groups['A'].Count != 2) throw new Exception("wrong A group");
... | string d7 = DescribeGroupByInitial();
string d7L = d7.ToLower();
if (!d7L.Contains("groupby")) throw new Exception("must mention GroupBy");
if (!d7L.Contains("char.toupperinvariant")) throw new Exception("must mention char.ToUpperInvariant");
if (!d7L.Contains("todictionary")) throw new Exception("must mention ToDictio... |
8 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<double> WeightedAvgPairs(List<double> values, List<double> weights)
{
return values.Zip(weights, (v, w) => v * w)
.Select((product, index) =>
product / weights.Ta... | static string DescribeWeightedAvgPairs()
{
return "Pairs elements from values and weights using LINQ Zip, which "
+ "stops at the shorter sequence and applies a result selector "
+ "that computes v * w. The intermediate products are then piped "
+ "through Select w... | static void Main(string[] args)
{
var v = new List<double> { 10.0, 20.0, 30.0 };
var w = new List<double> { 1.0, 2.0, 3.0 };
var result = WeightedAvgPairs(v, w);
if (result.Count != 3) throw new Exception("wrong count");
if (Math.Abs(result[0] - 10.0) > 0.001) throw new E... | string d8 = DescribeWeightedAvgPairs();
string d8L = d8.ToLower();
if (!d8L.Contains("zip")) throw new Exception("must mention Zip");
if (!d8L.Contains("shorter sequence") || !d8L.Contains("truncat")) throw new Exception("must mention truncation to shorter");
if (!d8L.Contains("select") && !d8L.Contains("index overload... |
9 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static int SumMiddleThird(ReadOnlySpan<int> span)
{
int len = span.Length;
int start = len / 3;
int end = 2 * len / 3;
ReadOnlySpan<int> slice = span.Slice(start, end - start);
int sum = 0;
foreach (... | static string DescribeSumMiddleThird()
{
return "Computes the sum of the middle third of a ReadOnlySpan<int> by "
+ "using integer division to find start and end indices, then calling "
+ "Slice to create a narrower view into the same contiguous memory "
+ "without... | static void Main(string[] args)
{
Span<int> data = stackalloc int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int result = SumMiddleThird(data);
if (result != 4 + 5 + 6) throw new Exception("wrong sum: " + result);
string desc = DescribeSumMiddleThird();
if (string.IsNullOrEmpty(des... | string d9 = DescribeSumMiddleThird();
string d9L = d9.ToLower();
if (!d9L.Contains("readonlyspan")) throw new Exception("must mention ReadOnlySpan");
if (!d9L.Contains("slice")) throw new Exception("must mention Slice");
if (!d9L.Contains("without") && !d9L.Contains("no")) throw new Exception("must mention no allocatio... |
10 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
class Program
{
static int AddOrIncrement(ConcurrentDictionary<string, int> dict, string key, int amount)
{
return dict.AddOrUpdate(key, amount, (k, oldVal) => oldVal + amount);
}
| static string DescribeAddOrIncrement()
{
return "Uses ConcurrentDictionary.AddOrUpdate which atomically adds the "
+ "key with the given amount if absent, or invokes the updateValueFactory "
+ "delegate to compute oldVal + amount if the key already exists. "
+ "The... | static void Main(string[] args)
{
var dict = new ConcurrentDictionary<string, int>();
if (AddOrIncrement(dict, "x", 5) != 5) throw new Exception("add failed");
if (AddOrIncrement(dict, "x", 3) != 8) throw new Exception("update failed");
if (dict["x"] != 8) throw new Exception("wr... | string d10 = DescribeAddOrIncrement();
string d10L = d10.ToLower();
if (!d10L.Contains("addorupdate")) throw new Exception("must mention AddOrUpdate");
if (!d10L.Contains("atomically")) throw new Exception("must mention atomic operation");
if (!d10L.Contains("updatevaluefactory")) throw new Exception("must mention upda... |
11 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static List<string> ZipLabelsWithScores(List<string> labels, List<int> scores)
{
return labels.Zip(scores, (l, s) => $"{l}:{s}").ToList();
}
| static string describe_ZipLabelsWithScores()
{
return "Pairs each label with the corresponding score using Enumerable.Zip, "
+ "combining them into a formatted string with a colon separator. "
+ "If the two sequences have different lengths, Zip truncates to the "
+ "shorter sequence witho... |
static void Main()
{
var result = ZipLabelsWithScores(
new List<string> { "math", "sci" },
new List<int> { 95, 88 });
if (result.Count != 2) throw new Exception("count");
if (result[0] != "math:95") throw new Exception("first");
var truncated = ZipLabels... | string d = Program.describe_ZipLabelsWithScores().ToLower();
if (!d.Contains("zip")) throw new Exception("missing zip");
if (!d.Contains("truncat")) throw new Exception("missing truncate");
if (!d.Contains("shorter")) throw new Exception("missing shorter");
if (!d.Contains("colon") && !d.Contains("separator") && !d.Con... |
12 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static List<string> DrainTopN(PriorityQueue<string, int> pq, int n)
{
var result = new List<string>();
while (result.Count < n && pq.TryDequeue(out string item, out int _))
{
result.Add(item);
}
... | static string describe_DrainTopN()
{
return "Removes up to n elements from a PriorityQueue using TryDequeue, "
+ "which extracts the element with the lowest priority value (min-heap). "
+ "Each call to TryDequeue returns false when the queue is empty, so "
+ "the loop terminates early if ... |
static void Main()
{
var pq = new PriorityQueue<string, int>();
pq.Enqueue("low", 1);
pq.Enqueue("high", 10);
pq.Enqueue("med", 5);
var top2 = DrainTopN(pq, 2);
if (top2.Count != 2) throw new Exception("count");
if (top2[0] != "low") throw new Exception("... | string d = Program.describe_DrainTopN().ToLower();
if (!d.Contains("priorityqueue") && !d.Contains("priority queue")) throw new Exception("missing priorityqueue");
if (!d.Contains("trydequeue")) throw new Exception("missing trydequeue");
if (!d.Contains("min") || !d.Contains("heap") && !d.Contains("lowest")) throw new ... |
13 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static string ComputeSha256Hex(string input)
{
using (SHA256 sha = SHA256.Create())
{
byte[] hash = sha.ComputeHash(Encoding.UTF8.GetBytes(input));
return BitConverter.ToString(hash).Rep... | static string describe_ComputeSha256Hex()
{
return "Computes a SHA-256 hash of the UTF-8 encoded input string using "
+ "the SHA256.Create factory method inside a using block that ensures "
+ "the algorithm instance is disposed after use. The resulting 32-byte "
+ "hash is converted to a ... |
static void Main()
{
string h = ComputeSha256Hex("hello");
if (h.Length != 64) throw new Exception("length");
if (h != h.ToLowerInvariant()) throw new Exception("case");
string doc = describe_ComputeSha256Hex();
if (string.IsNullOrEmpty(doc)) throw new Exception("empty ... | string d = Program.describe_ComputeSha256Hex().ToLower();
if (!d.Contains("sha-256") && !d.Contains("sha256")) throw new Exception("missing sha256");
if (!d.Contains("utf-8") && !d.Contains("utf8")) throw new Exception("missing utf-8");
if (!d.Contains("disposed") && !d.Contains("using")) throw new Exception("missing d... |
14 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Globalization;
class Program
{
static int CultureAwareIndexOf(string source, string value, string cultureName)
{
CultureInfo ci = new CultureInfo(cultureName);
return ci.CompareInfo.IndexOf(source, value, CompareOptions.IgnoreCase);
}
| static string describe_CultureAwareIndexOf()
{
return "Finds the first occurrence of a substring within a source string "
+ "using culture-sensitive comparison rules from CompareInfo.IndexOf. "
+ "The comparison is case-insensitive via CompareOptions.IgnoreCase. "
+ "A new CultureInfo is ... |
static void Main()
{
int idx = CultureAwareIndexOf("Hello World", "hello", "en-US");
if (idx != 0) throw new Exception("case insensitive");
int missing = CultureAwareIndexOf("abc", "xyz", "en-US");
if (missing != -1) throw new Exception("not found");
string doc = descri... | string d = Program.describe_CultureAwareIndexOf().ToLower();
if (!d.Contains("cultureinfo") && !d.Contains("culture")) throw new Exception("missing cultureinfo/culture");
if (!d.Contains("compareinfo")) throw new Exception("missing compareinfo");
if (!d.Contains("case-insensitive") && !d.Contains("ignorecase") && !d.Co... |
15 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Numerics;
class Program
{
static BigInteger Factorial(int n)
{
BigInteger result = BigInteger.One;
for (int i = 2; i <= n; i++)
result = BigInteger.Multiply(result, new BigInteger(i));
return result;
}
| static string describe_Factorial()
{
return "Computes the factorial of n using System.Numerics.BigInteger for "
+ "arbitrary-precision integer arithmetic, avoiding overflow that would "
+ "occur with int or long for large n. Starts from BigInteger.One and "
+ "iteratively multiplies via B... |
static void Main()
{
if (Factorial(0) != BigInteger.One) throw new Exception("0!");
if (Factorial(5) != new BigInteger(120)) throw new Exception("5!");
if (Factorial(20) != BigInteger.Parse("2432902008176640000")) throw new Exception("20!");
string doc = describe_Factorial();
... | string d = Program.describe_Factorial().ToLower();
if (!d.Contains("biginteger")) throw new Exception("missing biginteger");
if (!d.Contains("arbitrary") || !d.Contains("precision")) throw new Exception("missing arbitrary-precision");
if (!d.Contains("overflow")) throw new Exception("missing overflow");
if (!d.Contains... |
16 | devbench-code2NL-NL2code | c_sharp | using System;
using System.IO;
using System.IO.Compression;
using System.Text;
class Program
{
static byte[] CompressString(string text)
{
byte[] raw = Encoding.UTF8.GetBytes(text);
using (var ms = new MemoryStream())
{
using (var gz = new GZipStream(ms, CompressionMode.Comp... | static string describe_CompressString()
{
return "Compresses a UTF-8 encoded string into a gzip byte array using "
+ "GZipStream wrapping a MemoryStream. The leaveOpen parameter is set "
+ "to true so that disposing the GZipStream flushes the compressed data "
+ "without closing the under... |
static void Main()
{
byte[] compressed = CompressString("hello world");
if (compressed.Length == 0) throw new Exception("empty");
if (compressed.Length >= Encoding.UTF8.GetBytes("hello world").Length + 100)
throw new Exception("too large");
string doc = describe_Com... | string d = Program.describe_CompressString().ToLower();
if (!d.Contains("gzipstream") && !d.Contains("gzip")) throw new Exception("missing gzipstream");
if (!d.Contains("memorystream")) throw new Exception("missing memorystream");
if (!d.Contains("leaveopen") && !d.Contains("leave open")) throw new Exception("missing l... |
17 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static List<int[]> BatchItems(IEnumerable<int> items, int batchSize)
{
return items.Chunk(batchSize).ToList();
}
| static string describe_BatchItems()
{
return "Splits the input sequence into fixed-size batches using Enumerable.Chunk. "
+ "Each batch is an array of up to batchSize elements. The final chunk "
+ "may contain fewer elements if the total count is not evenly divisible "
+ "by batchSize. Ch... |
static void Main()
{
var batches = BatchItems(new[] { 1, 2, 3, 4, 5 }, 2);
if (batches.Count != 3) throw new Exception("batch count");
if (batches[2].Length != 1) throw new Exception("last batch size");
string doc = describe_BatchItems();
if (string.IsNullOrEmpty(doc)) ... | string d = Program.describe_BatchItems().ToLower();
if (!d.Contains("chunk")) throw new Exception("missing chunk");
if (!d.Contains("array")) throw new Exception("missing array");
if (!d.Contains("fewer") && !d.Contains("remaining") && !d.Contains("less")) throw new Exception("missing fewer/remaining for last chunk");
... |
18 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Program
{
static void RotateLeft(LinkedList<int> list, int positions)
{
for (int i = 0; i < positions && list.Count > 1; i++)
{
int first = list.First.Value;
list.RemoveFirst();
list.AddLast(first);
... | static string describe_RotateLeft()
{
return "Rotates a LinkedList to the left by the given number of positions. "
+ "Each rotation removes the First node using RemoveFirst (an O(1) operation) "
+ "and appends its value to the end using AddLast (also O(1)). "
+ "The loop exits early if th... |
static void Main()
{
var list = new LinkedList<int>(new[] { 1, 2, 3, 4, 5 });
RotateLeft(list, 2);
if (list.First.Value != 3) throw new Exception("first");
if (list.Last.Value != 2) throw new Exception("last");
string doc = describe_RotateLeft();
if (string.IsNu... | string d = Program.describe_RotateLeft().ToLower();
if (!d.Contains("linkedlist") && !d.Contains("linked list")) throw new Exception("missing linkedlist");
if (!d.Contains("removefirst") && !d.Contains("remove first")) throw new Exception("missing removefirst");
if (!d.Contains("addlast") && !d.Contains("add last")) th... |
19 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static List<char> FlattenToChars(List<string> words)
{
return words.SelectMany(w => w.ToCharArray()).ToList();
}
| static string describe_FlattenToChars()
{
return "Flattens a list of strings into a single list of characters using "
+ "Enumerable.SelectMany, which projects each string into a char array "
+ "via ToCharArray and then concatenates all resulting sequences into one "
+ "flat sequence. Sele... |
static void Main()
{
var result = FlattenToChars(new List<string> { "ab", "cd" });
if (result.Count != 4) throw new Exception("count");
if (result[0] != 'a' || result[3] != 'd') throw new Exception("order");
var empty = FlattenToChars(new List<string>());
if (empty.Coun... | string d = Program.describe_FlattenToChars().ToLower();
if (!d.Contains("selectmany")) throw new Exception("missing selectmany");
if (!d.Contains("flatten") && !d.Contains("concatenat")) throw new Exception("missing flatten/concatenate");
if (!d.Contains("tochararray") && !d.Contains("char array")) throw new Exception(... |
20 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static Dictionary<char, List<string>> GroupByFirstChar(IEnumerable<string> words)
{
return words.GroupBy(w => w[0])
.ToDictionary(g => g.Key, g => g.ToList());
}
| static string describe_GroupByFirstChar()
{
return "Groups strings by their first character using Enumerable.GroupBy and "
+ "materializes the result into a Dictionary via ToDictionary. Each key "
+ "is the first char of the group, and each value is a List of all strings "
+ "sharing that... |
static void Main()
{
var result = GroupByFirstChar(new[] { "apple", "avocado", "banana", "blueberry" });
if (result.Count != 2) throw new Exception("group count");
if (result['a'].Count != 2) throw new Exception("a count");
if (result['b'][0] != "banana") throw new Exception("or... | string d = Program.describe_GroupByFirstChar().ToLower();
if (!d.Contains("groupby") && !d.Contains("group by")) throw new Exception("missing groupby");
if (!d.Contains("todictionary") && !d.Contains("to dictionary")) throw new Exception("missing todictionary");
if (!d.Contains("first char") && !d.Contains("first chara... |
21 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Text.RegularExpressions;
class Task21
{
static (bool found, string area, string number) ParsePhone(string input)
{
var m = Regex.Match(input, @"\((\d{3})\)\s*(\d{4,})");
if (!m.Success) return (false, "", "");
return (true, m.Groups[1].Value, m.Groups[2].Value... | static string DescribeParsePhone()
{
return "Uses Regex.Match with a pattern containing two capturing groups "
+ "to extract the area code and number from a parenthesized phone "
+ "format. Returns a ValueTuple with a bool Success field indicating "
+ "whether the patt... |
static void Main()
{
var r = ParsePhone("(415) 5551234");
if (!r.found) throw new Exception("should match");
if (r.area != "415") throw new Exception("area");
if (r.number != "5551234") throw new Exception("number");
var miss = ParsePhone("none");
if (miss.found)... | string d21 = Task21.DescribeParsePhone().ToLower();
if (!d21.Contains("regex.match")) throw new Exception("must name Regex.Match");
if (!d21.Contains("capturing group") && !d21.Contains("capture group")) throw new Exception("must mention capturing groups");
if (!d21.Contains("valuetuple") && !d21.Contains("value tuple"... |
22 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Concurrent;
class Task22
{
static (bool ok, int value) SafeDequeue(ConcurrentQueue<int> q)
{
if (q.TryDequeue(out int item))
return (true, item);
return (false, -1);
}
| static string DescribeSafeDequeue()
{
return "Attempts a lock-free dequeue from a ConcurrentQueue<int> using "
+ "TryDequeue with an out parameter. TryDequeue is an atomic "
+ "operation that returns true and sets the out variable on success. "
+ "On an empty queue it ... |
static void Main()
{
var q = new ConcurrentQueue<int>();
q.Enqueue(10);
q.Enqueue(20);
var r1 = SafeDequeue(q);
if (!r1.ok || r1.value != 10) throw new Exception("first dequeue");
var r2 = SafeDequeue(q);
if (!r2.ok || r2.value != 20) throw new Exception(... | string d22 = Task22.DescribeSafeDequeue().ToLower();
if (!d22.Contains("concurrentqueue")) throw new Exception("must name ConcurrentQueue");
if (!d22.Contains("trydequeue")) throw new Exception("must name TryDequeue");
if (!d22.Contains("lock-free") && !d22.Contains("lockfree") && !d22.Contains("lock free")) throw new ... |
23 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Diagnostics;
class Task23
{
static (long ticks, double ms) MeasureAction(Action action)
{
var sw = new Stopwatch();
sw.Start();
action();
sw.Stop();
return (sw.ElapsedTicks, sw.Elapsed.TotalMilliseconds);
}
| static string DescribeMeasureAction()
{
return "Measures execution time of an Action delegate using "
+ "System.Diagnostics.Stopwatch. Returns both ElapsedTicks, which "
+ "are in units of Stopwatch.Frequency (not TimeSpan ticks), and "
+ "Elapsed.TotalMilliseconds as ... |
static void Main()
{
var (ticks, ms) = MeasureAction(() => { int s = 0; for (int i = 0; i < 1000; i++) s += i; });
if (ticks <= 0) throw new Exception("ticks should be positive");
if (ms < 0) throw new Exception("ms should be non-negative");
string desc = DescribeMeasureAction()... | string d23 = Task23.DescribeMeasureAction().ToLower();
if (!d23.Contains("stopwatch")) throw new Exception("must name Stopwatch");
if (!d23.Contains("elapsedticks") && !d23.Contains("elapsed ticks")) throw new Exception("must name ElapsedTicks");
if (!d23.Contains("frequency") || !d23.Contains("stopwatch.frequency") &&... |
24 | devbench-code2NL-NL2code | c_sharp | using System;
using System.Collections.Generic;
class Task24
{
static IEnumerable<int> FilterPositive(IEnumerable<int> source)
{
foreach (var item in source)
{
if (item > 0)
yield return item;
}
}
| static string DescribeFilterPositive()
{
return "Returns an IEnumerable<int> that lazily filters positive "
+ "values from the source using yield return for deferred "
+ "execution. The compiler generates a state machine that "
+ "produces elements one at a time on eac... |
static void Main()
{
var src = new[] { -3, 5, 0, 8, -1, 2 };
var result = new List<int>(FilterPositive(src));
if (result.Count != 3) throw new Exception("count");
if (result[0] != 5 || result[1] != 8 || result[2] != 2) throw new Exception("values");
string desc = Describ... | string d24 = Task24.DescribeFilterPositive().ToLower();
if (!d24.Contains("yield return") && !d24.Contains("yield")) throw new Exception("must mention yield return");
if (!d24.Contains("deferred") && !d24.Contains("lazy") && !d24.Contains("lazily")) throw new Exception("must mention deferred/lazy execution");
if (!d24.... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 104