ronantakizawa/codereview-bench huggingface dataset:
Repository: JuliaLang/julia
File: base/c.jl (Julia)

Code before:
    size_t strlen(char *)

with a Julia variable named `s`. See also `ccall`.

Varargs are supported with the following convention:

    @ccall printf("%s = %d"::Cstring ; "foo"::Cstring, foo::Cint)::Cint

The semicolon is used to separate required arguments (of which there
must be at least one) from variadic arguments.

Example using an external library:

    # C signature of g_uri_escape_string:
    # char *g_uri_escape_string(const char *unescaped, const char *reserved_chars_allowed, gboolean allow_utf8);

    const glib = "libglib-2.0"
    @ccall glib.g_uri_escape_string(my_uri::Cstring, ":/"::Cstring, true::Cint)::Cstring

The string literal could also be used directly before the function
name, if desired `"libglib-2.0".g_uri_escape_string(...`

It's possible to declare the ccall as `gc_safe` by using the `gc_safe = true` option:
    @ccall gc_safe=true strlen(s::Cstring)::Csize_t
This allows the garbage collector to run concurrently with the ccall, which can be useful whenever
the ccall may block outside of julia.
WARNING: This option should be used with caution, as it can lead to undefined behavior if the ccall
calls back into the julia runtime. (@cfunction/@ccallables are safe however)
"""
macro ccall(exprs...)
    return ccall_macro_lower((:ccall), ccall_macro_parse(exprs)...)
end

macro ccall_effects(effects::UInt16, expr)
    return ccall_macro_lower((:ccall, effects), ccall_macro_parse(expr)...)
end


Review comment (suggestion):
```suggestion
the `ccall` may block outside of julia.
```

Code after:

with a Julia variable named `s`. See also `ccall`.

Varargs are supported with the following convention:

    @ccall printf("%s = %d"::Cstring ; "foo"::Cstring, foo::Cint)::Cint

The semicolon is used to separate required arguments (of which there
must be at least one) from variadic arguments.

Example using an external library:

    # C signature of g_uri_escape_string:
    # char *g_uri_escape_string(const char *unescaped, const char *reserved_chars_allowed, gboolean allow_utf8);

    const glib = "libglib-2.0"
    @ccall glib.g_uri_escape_string(my_uri::Cstring, ":/"::Cstring, true::Cint)::Cstring

The string literal could also be used directly before the function
name, if desired `"libglib-2.0".g_uri_escape_string(...`

It's possible to declare the ccall as `gc_safe` by using the `gc_safe = true` option:
    @ccall gc_safe=true strlen(s::Cstring)::Csize_t
This allows the garbage collector to run concurrently with the ccall, which can be useful whenever
the `ccall` may block outside of julia.
WARNING: This option should be used with caution, as it can lead to undefined behavior if the ccall
calls back into the julia runtime. (`@cfunction`/`@ccallables` are safe however)
"""
macro ccall(exprs...)
    return ccall_macro_lower((:ccall), ccall_macro_parse(exprs)...)
end

macro ccall_effects(effects::UInt16, expr)
    return ccall_macro_lower((:ccall, effects), ccall_macro_parse(expr)...)
end
Repository: JuliaLang/julia
File: stdlib/Dates/src/conversions.jl (Julia)

Code before:

"""
    rata2datetime(days) -> DateTime

Take the number of Rata Die days since epoch `0000-12-31T00:00:00` and return the
corresponding `DateTime`.
"""
rata2datetime(days) = DateTime(yearmonthday(days)...)

"""
    datetime2rata(dt::TimeType) -> Int64

Return the number of Rata Die days since epoch from the given `Date` or `DateTime`.
"""
datetime2rata(dt::TimeType) = days(dt)

# Julian conversions
const JULIANEPOCH = value(DateTime(-4713, 11, 24, 12))
localjulianepoch() = JULIANEPOCH + (localepoch() - UNIXEPOCH)

"""
    julian2datetime(julian_days::Real; localtime::Bool=false) -> DateTime

Take the number of Julian calendar days since epoch `-4713-11-24T12:00:00` (UTC) and return the
corresponding `DateTime`. If `localtime` is `true`, then the output is in the local
time zone, otherwise it is in UTC/GMT
"""
function julian2datetime(f::Real; localtime::Bool=false)
    rata = (localtime ? localjulianepoch() : JULIANEPOCH) + round(Int64, Int64(86400000) * f)
    return DateTime(UTM(rata))
end

"""
    datetime2julian(dt::DateTime; localtime::Bool=false) -> Float64

Take the given `DateTime` and return the number of Julian calendar days since the julian
epoch `-4713-11-24T12:00:00` (UTC) as a [`Float64`](@ref).

If `localtime` is `true`, then `dt` is interpreted as being in the local time zone,
and is otherwise interpreted as being UTC/GMT.
"""
function datetime2julian(dt::DateTime; localtime::Bool=false)
    return (value(dt) - (localtime ? localjulianepoch() : JULIANEPOCH)) / 86400000.0
end


Review comment (suggestion):
```suggestion
time zone, otherwise it is in UTC/GMT.
```

Code after:

"""
    rata2datetime(days)::DateTime

Take the number of Rata Die days since epoch `0000-12-31T00:00:00` and return the
corresponding `DateTime`.
"""
rata2datetime(days) = DateTime(yearmonthday(days)...)

"""
    datetime2rata(dt::TimeType)::Int64

Return the number of Rata Die days since epoch from the given `Date` or `DateTime`.
"""
datetime2rata(dt::TimeType) = days(dt)

# Julian conversions
const JULIANEPOCH = value(DateTime(-4713, 11, 24, 12))

"""
    julian2datetime(julian_days)::DateTime

Take the number of Julian calendar days since epoch `-4713-11-24T12:00:00` and return the
corresponding `DateTime`.
"""
function julian2datetime(f)
    rata = JULIANEPOCH + round(Int64, Int64(86400000) * f)
    return DateTime(UTM(rata))
end

"""
    datetime2julian(dt::DateTime)::Float64

Take the given `DateTime` and return the number of Julian calendar days since the julian
epoch `-4713-11-24T12:00:00` as a [`Float64`](@ref).
"""
datetime2julian(dt::DateTime) = (value(dt) - JULIANEPOCH) / 86400000.0
Repository: JuliaLang/julia
File: base/channels.jl (Julia)

Code before:
Referencing the created task:

```jldoctest
julia> taskref = Ref{Task}();

julia> chnl = Channel(taskref=taskref) do ch
           println(take!(ch))
       end;

julia> istaskdone(taskref[])
false

julia> put!(chnl, "Hello");
Hello

julia> istaskdone(taskref[])
true
```

!!! compat "Julia 1.3"
    The `spawn=` parameter was added in Julia 1.3. This constructor was added in Julia 1.3.
    In earlier versions of Julia, Channel used keyword arguments to set `size` and `T`, but
    those constructors are deprecated.

!!! compat "Julia 1.9"
    The `threadpool=` parameter was added in Julia 1.9.

```jldoctest
julia> chnl = Channel{Char}(1, spawn=true) do ch
           for c in "hello world"
               put!(ch, c)
           end
       end
Channel{Char}(1) (2 items available)

julia> String(collect(chnl))
"hello world"
```
"""
function Channel{T}(func::Function, size=0; taskref=nothing, spawn=false, threadpool=:default) where T
    chnl = Channel{T}(size)
    task = Task(() -> func(chnl))
    task.sticky = !spawn
    bind(chnl, task)
    if spawn
        Base.Threads._spawn_set_thrpool(task, threadpool)
        schedule(task) # start it on (potentially) another thread
    else
        yield(task) # immediately start it, yielding the current thread
    end
    isa(taskref, Ref{Task}) && (taskref[] = task)

Review comment (suggestion):
```suggestion
    The `threadpool` argument was added in Julia 1.9.
```

Code after:
```

Referencing the created task:

```jldoctest
julia> taskref = Ref{Task}();

julia> chnl = Channel(taskref=taskref) do ch
           println(take!(ch))
       end;

julia> istaskdone(taskref[])
false

julia> put!(chnl, "Hello");
Hello

julia> istaskdone(taskref[])
true
```

!!! compat "Julia 1.3"
    The `spawn=` parameter was added in Julia 1.3. This constructor was added in Julia 1.3.
    In earlier versions of Julia, Channel used keyword arguments to set `size` and `T`, but
    those constructors are deprecated.

!!! compat "Julia 1.9"
    The `threadpool=` argument was added in Julia 1.9.

```jldoctest
julia> chnl = Channel{Char}(1, spawn=true) do ch
           for c in "hello world"
               put!(ch, c)
           end
       end
Channel{Char}(1) (2 items available)

julia> String(collect(chnl))
"hello world"
```
"""
function Channel{T}(func::Function, size=0; taskref=nothing, spawn=false, threadpool=nothing) where T
    chnl = Channel{T}(size)
    task = Task(() -> func(chnl))
    if threadpool === nothing
        threadpool = :default
    else
        spawn = true
    end
    task.sticky = !spawn
    bind(chnl, task)
Repository: JuliaLang/julia
File: base/docs/basedocs.jl (Julia)

Code before:
    DomainError(val, msg)

The argument `val` to a function or constructor is outside the valid domain.

# Examples
```jldoctest
julia> sqrt(-1)
ERROR: DomainError with -1.0:
sqrt was called with a negative real argument but will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
Stacktrace:
[...]
```
"""
DomainError

"""
    Task(func)

Create a `Task` (i.e. coroutine) to execute the given function `func` (which
must be callable with no arguments). The task exits when this function returns.
The task will run in the "world age" from the parent at construction when [`schedule`](@ref)d.

!!! warning
    By default tasks will have the sticky bit set to true `t.sticky`. This models the
    historic default for [`@async`](@ref). Sticky tasks can only be run on the worker thread
    they are scheduled on. To obtain the behavior of [`Threads.@spawn`](@ref) set the sticky
    bit manually to `false`.

# Examples
```jldoctest
julia> a() = sum(i for i in 1:1000);

julia> b = Task(a);
```

In this example, `b` is a runnable `Task` that hasn't started yet.
"""
Task

"""
    StackOverflowError()

The function call grew beyond the size of the call stack. This usually happens when a call
recurses infinitely.
"""
StackOverflowError

"""
    nfields(x) -> Int

Get the number of fields in the given object.

Review comment (suggestion):
```suggestion
    historic default for [`@async`](@ref). Sticky tasks can only be run on the thread
    they are first scheduled on. To obtain the behavior of [`Threads.@spawn`](@ref) set the sticky
```

Code after:
    DomainError(val, msg)

The argument `val` to a function or constructor is outside the valid domain.

# Examples
```jldoctest
julia> sqrt(-1)
ERROR: DomainError with -1.0:
sqrt was called with a negative real argument but will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
Stacktrace:
[...]
```
"""
DomainError

"""
    Task(func)

Create a `Task` (i.e. coroutine) to execute the given function `func` (which
must be callable with no arguments). The task exits when this function returns.
The task will run in the "world age" from the parent at construction when [`schedule`](@ref)d.

!!! warning
    By default tasks will have the sticky bit set to true `t.sticky`. This models the
    historic default for [`@async`](@ref). Sticky tasks can only be run on the worker thread
    they are first scheduled on. To obtain the behavior of [`Threads.@spawn`](@ref) set the sticky
    bit manually to `false`.

# Examples
```jldoctest
julia> a() = sum(i for i in 1:1000);

julia> b = Task(a);
```

In this example, `b` is a runnable `Task` that hasn't started yet.
"""
Task

"""
    StackOverflowError()

The function call grew beyond the size of the call stack. This usually happens when a call
recurses infinitely.
"""
StackOverflowError

"""
    nfields(x) -> Int

Get the number of fields in the given object.
Repository: JuliaLang/julia
File: src/datatype.c (C)

Code before:
  defining DataTypes
  basic operations on struct and bits values
*/

#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdalign.h>
#include "julia.h"
#include "julia_internal.h"
#include "julia_assert.h"
#include "julia_gcext.h"

#ifdef __cplusplus
extern "C" {
#endif

// allocating TypeNames -----------------------------------------------------------

static int is10digit(char c) JL_NOTSAFEPOINT
{
    return (c >= '0' && c <= '9');
}

STATIC_INLINE int is_canonicalized_anonfn_typename(char *name) JL_NOTSAFEPOINT
{
    if (is10digit(name[1]))
        return 1;
    char *delim = strchr(&name[1], '#');
    if (delim == NULL)
        return 0;
    if (delim[1] != '#')
        return 0;
    if (!is10digit(delim[2]))
        return 0;
    return 1;
}

static jl_sym_t *jl_demangle_typename(jl_sym_t *s) JL_NOTSAFEPOINT
{
    char *n = jl_symbol_name(s);
    if (n[0] != '#')
        return s;
    char *end = strchr(&n[1], '#');
    // handle `#f...##...#...`
    if (end != NULL && end[1] == '#')
        end = strchr(&end[2], '#');
    int32_t len;
    if (end == NULL || end == n+1)
        len = strlen(n) - 1;
    else

Review comment (suggestion):
```suggestion
// Returns true for typenames in the form "#[0-9]+" or "#.*##[0-9]+"
STATIC_INLINE int is_canonicalized_anonfn_typename(char *name) JL_NOTSAFEPOINT
```

Code after:
  defining DataTypes
  basic operations on struct and bits values
*/

#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdalign.h>
#include "julia.h"
#include "julia_internal.h"
#include "julia_assert.h"
#include "julia_gcext.h"

#ifdef __cplusplus
extern "C" {
#endif

// allocating TypeNames -----------------------------------------------------------

static jl_sym_t *jl_demangle_typename(jl_sym_t *s) JL_NOTSAFEPOINT
{
    char *n = jl_symbol_name(s);
    if (n[0] != '#')
        return s;
    char *end = strchr(&n[1], '#');
    // handle `#f...##...#...`
    if (end != NULL && end[1] == '#')
        end = strchr(&end[2], '#');
    int32_t len;
    if (end == NULL || end == n+1)
        len = strlen(n) - 1;
    else
        len = (end-n) - 1;  // extract `f` from `#f#...`
    if (isdigit(n[1]) || is_canonicalized_anonfn_typename(n))
        return _jl_symbol(n, len+1);
    return _jl_symbol(&n[1], len);
}

JL_DLLEXPORT jl_methtable_t *jl_new_method_table(jl_sym_t *name, jl_module_t *module)
{
    jl_task_t *ct = jl_current_task;
    jl_methtable_t *mt =
        (jl_methtable_t*)jl_gc_alloc(ct->ptls, sizeof(jl_methtable_t),
                                     jl_methtable_type);
    mt->name = jl_demangle_typename(name);
    mt->module = module;
    jl_atomic_store_relaxed(&mt->defs, jl_nothing);
    jl_atomic_store_relaxed(&mt->leafcache, (jl_genericmemory_t*)jl_an_empty_memory_any);
    jl_atomic_store_relaxed(&mt->cache, jl_nothing);
    jl_atomic_store_relaxed(&mt->max_args, 0);
    mt->backedges = NULL;
Repository: JuliaLang/julia
File: base/math.jl (Julia)

Code before:
@constprop :aggressive @inline function ^(x::Float64, n::Integer)
    x^clamp(n, Int64)
end
@constprop :aggressive @inline function ^(x::Float64, n::Int64)
    n == 0 && return one(x)
    if use_power_by_squaring(n)
        return pow_body(x, n)
    else
        s = ifelse(x < 0 && isodd(n), -1.0, 1.0)
        x = abs(x)
        y = float(n)
        if y == n
            return copysign(pow_body(x, y), s)
        else
            n2 = n % 1024
            y = float(n - n2)
            return pow_body(x, y) * copysign(pow_body(x, n2), s)
        end
    end
end

# compensated power by squaring
# this method is only reliable for -2^20 < n < 2^20 (cf. #53881 #53886)
@assume_effects :terminates_locally @noinline function pow_body(x::Float64, n::Integer)
    y = 1.0
    n == 0 && return y
    xnlo = ynlo = 0.0
    n == 3 && return x*x*x # keep compatibility with literal_pow
    if n < 0
        rx = inv(x)
        n==-2 && return rx*rx #keep compatibility with literal_pow
        isfinite(x) && (xnlo = -fma(x, rx, -1.) * rx)
        x = rx
        n = -n
    end
    while n > 1
        if n&1 > 0
            err = muladd(y, xnlo, x*ynlo)
            y, ynlo = two_mul(x,y)
            ynlo += err
        end
        err = x*2*xnlo
        x, xnlo = two_mul(x, x)
        xnlo += err
        n >>>= 1
    end
    err = muladd(y, xnlo, x*ynlo)
    return ifelse(isfinite(x) & isfinite(err), muladd(x, y, err), x*y)
end

function ^(x::Float32, n::Integer)

Review comment (suggestion):
given that `n==0` is explicitly checked for in both versions of `^`, I'm pretty sure this is always redundant.

Code after:
@constprop :aggressive @inline function ^(x::Float64, n::Integer)
    x^clamp(n, Int64)
end
@constprop :aggressive @inline function ^(x::Float64, n::Int64)
    n == 0 && return one(x)
    if use_power_by_squaring(n)
        return pow_body(x, n)
    else
        s = ifelse(x < 0 && isodd(n), -1.0, 1.0)
        x = abs(x)
        y = float(n)
        if y == n
            return copysign(pow_body(x, y), s)
        else
            n2 = n % 1024
            y = float(n - n2)
            return pow_body(x, y) * copysign(pow_body(x, n2), s)
        end
    end
end

# compensated power by squaring
# this method is only reliable for -2^20 < n < 2^20 (cf. #53881 #53886)
@assume_effects :terminates_locally @noinline function pow_body(x::Float64, n::Integer)
    y = 1.0
    xnlo = ynlo = 0.0
    n == 3 && return x*x*x # keep compatibility with literal_pow
    if n < 0
        rx = inv(x)
        n==-2 && return rx*rx #keep compatibility with literal_pow
        isfinite(x) && (xnlo = -fma(x, rx, -1.) * rx)
        x = rx
        n = -n
    end
    while n > 1
        if n&1 > 0
            err = muladd(y, xnlo, x*ynlo)
            y, ynlo = two_mul(x,y)
            ynlo += err
        end
        err = x*2*xnlo
        x, xnlo = two_mul(x, x)
        xnlo += err
        n >>>= 1
    end
    err = muladd(y, xnlo, x*ynlo)
    return ifelse(isfinite(x) & isfinite(err), muladd(x, y, err), x*y)
end

function ^(x::Float32, n::Integer)
    n == -2 && return (i=inv(x); i*i)
Repository: JuliaLang/julia
File: base/iterators.jl (Julia)

Code before:

IteratorSize(::Type{<:DropWhile}) = SizeUnknown()
eltype(::Type{DropWhile{I,P}}) where {I,P} = eltype(I)
IteratorEltype(::Type{DropWhile{I,P}}) where {I,P} = IteratorEltype(I)

"""
    findall(f, it)

An iterator that generates every key from the key/value pairs of `pairs(it)`,
where `f(value)` returns `true`.
`Iterators.findall` is the lazy equivalent of `findall`.

!!! compat "Julia 1.13"
    Lazy `findall` requires at least Julia 1.13.

# Examples
```jldoctest
julia> collect(Iterators.findall(isodd, Dict(2 => 3, 3 => 2)))
1-element Vector{Int64}:
 2

julia> only(Iterators.findall(==(1), [3,6,2,1]))
4
```
"""
findall(f, it) = map(first, filter(i -> f(last(i)), pairs(it)))


# Cycle an iterator forever

struct Cycle{I}
    xs::I
end

"""
    cycle(iter[, n::Int])

An iterator that cycles through `iter` forever.
If `n` is specified, then it cycles through `iter` that many times.
When `iter` is empty, so are `cycle(iter)` and `cycle(iter, n)`.

`Iterators.cycle(iter, n)` is the lazy equivalent of [`Base.repeat`](@ref)`(vector, n)`,
while [`Iterators.repeated`](@ref)`(iter, n)` is the lazy [`Base.fill`](@ref)`(item, n)`.

!!! compat "Julia 1.11"
    The method `cycle(iter, n)` was added in Julia 1.11.

# Examples
```jldoctest
julia> for (i, v) in enumerate(Iterators.cycle("hello"))
           print(v)

Review comment (suggestion):
composition can be used here:

```suggestion
findall(f, it) = map(first, filter(f ∘ last, pairs(it)))
```

Code after:
dropwhile(pred,itr) = DropWhile(pred,itr)

iterate(ibl::DropWhile,itr) = iterate(ibl.xs, itr)
function iterate(ibl::DropWhile)
    y = iterate(ibl.xs)
    while y !== nothing
        ibl.pred(y[1]) || break
        y = iterate(ibl.xs,y[2])
    end
    y
end

IteratorSize(::Type{<:DropWhile}) = SizeUnknown()
eltype(::Type{DropWhile{I,P}}) where {I,P} = eltype(I)
IteratorEltype(::Type{DropWhile{I,P}}) where {I,P} = IteratorEltype(I)

"""
    findeach(f, it)
    findeach(it)

An iterator that generates every key from the key/value pairs of `pairs(it)`,
where `f(value)` returns `true`.

If `f` is not specified, default to `identity`.

`Iterators.findeach` is the lazy equivalent of `findall`.

!!! compat "Julia 1.13"
    `findeach` requires at least Julia 1.13.

# Examples
```jldoctest
julia> collect(Iterators.findeach(isodd, Dict(2 => 3, 3 => 2)))
1-element Vector{Int64}:
 2

julia> only(Iterators.findeach(==(1), [3,6,2,1]))
4
```
"""
findeach(f, it) = (k for (k, v) in pairs(it) if f(v))

findeach(it) = findeach(identity, it)


# Cycle an iterator forever

struct Cycle{I}
    xs::I
end
Repository: JuliaLang/julia
File: base/iterators.jl (Julia)

Code before:

julia> collect(Iterators.dropwhile(<(3),s))
3-element Vector{Int64}:
 3
 4
 5
```
"""
dropwhile(pred,itr) = DropWhile(pred,itr)

iterate(ibl::DropWhile,itr) = iterate(ibl.xs, itr)
function iterate(ibl::DropWhile)
    y = iterate(ibl.xs)
    while y !== nothing
        ibl.pred(y[1]) || break
        y = iterate(ibl.xs,y[2])
    end
    y
end

IteratorSize(::Type{<:DropWhile}) = SizeUnknown()
eltype(::Type{DropWhile{I,P}}) where {I,P} = eltype(I)
IteratorEltype(::Type{DropWhile{I,P}}) where {I,P} = IteratorEltype(I)

"""
    findall(f, it)

An iterator that generates every key from the key/value pairs of `pairs(it)`,
where `f(value)` returns `true`.
`Iterators.findall` is the lazy equivalent of `findall`.

!!! compat "Julia 1.13"
    Lazy `findall` requires at least Julia 1.13.

# Examples
```jldoctest
julia> collect(Iterators.findall(isodd, Dict(2 => 3, 3 => 2)))
1-element Vector{Int64}:
 2

julia> only(Iterators.findall(==(1), [3,6,2,1]))
4
```
"""
findall(f, it) = map(first, filter(i -> f(last(i)), pairs(it)))


# Cycle an iterator forever

struct Cycle{I}
    xs::I

Review comment (suggestion):
```suggestion
    findall(f, it)
    findall(it)
```
To be consistent with the Base version

Code after:

# Examples

```jldoctest
julia> s = collect(1:5)
5-element Vector{Int64}:
 1
 2
 3
 4
 5

julia> collect(Iterators.dropwhile(<(3),s))
3-element Vector{Int64}:
 3
 4
 5
```
"""
dropwhile(pred,itr) = DropWhile(pred,itr)

iterate(ibl::DropWhile,itr) = iterate(ibl.xs, itr)
function iterate(ibl::DropWhile)
    y = iterate(ibl.xs)
    while y !== nothing
        ibl.pred(y[1]) || break
        y = iterate(ibl.xs,y[2])
    end
    y
end

IteratorSize(::Type{<:DropWhile}) = SizeUnknown()
eltype(::Type{DropWhile{I,P}}) where {I,P} = eltype(I)
IteratorEltype(::Type{DropWhile{I,P}}) where {I,P} = IteratorEltype(I)

"""
    findeach(f, it)
    findeach(it)

An iterator that generates every key from the key/value pairs of `pairs(it)`,
where `f(value)` returns `true`.

If `f` is not specified, default to `identity`.

`Iterators.findeach` is the lazy equivalent of `findall`.

!!! compat "Julia 1.13"
    `findeach` requires at least Julia 1.13.

# Examples
```jldoctest