text:
julia> [RpcApi.SimpleOrganism(0x0000000000045060,:(function (o::Creature.Organism,)
        function func_420(var_419::Int16=-11171)
            return var_419
        end
        local var_413::Int8 = -128
        function func_286(var_284::Int16=2081,var_285::Int64=9145930075523767031)
            Creature.stepRight(o)
            Creature.stepRight(o)
            Creature.stepRight(o)
            Creature.stepRight(o)
            return var_284
        end
        local var_280::Int64 = -2141542542016055773
        local var_243::Bool = false
        function func_232(var_230::Bool=false,var_231::Int16=-29748)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            Creature.stepDown(o)
            var_230 = Bool(abs(var_230 - var_230))
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            return var_230
        end
        function func_189(var_188::Int16=2883)
            local var_421::Int16 = -32012
            var_188 = if haskey(o.mem,var_188)
                    o.mem[var_188]
                else
                    var_188
                end
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            return var_188
        end
        function func_142(var_141::Int64=7558744495470982559)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
            var_141 = var_141 - var_141
            Creature.stepUp(o)
            return var_141
        end
        local var_123::Bool = true
        local var_120::Int16 = -4015
        local var_117::Int8 = 61
        var_243 = func_232(var_123)
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_120)))
        Creature.eatRight(o,Int(var_117))
        Creature.stepDown(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.stepUp(o)
        var_156 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_156
            end
        var_243 = func_232(var_243)
        Creature.stepDown(o)
        var_117 = var_117 + var_117
        Creature.stepLeft(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        if var_243 <= var_123
        end
        Creature.stepRight(o)
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.eatRight(o,Int(var_117))
        var_120 = func_286(var_120)
        var_120 = func_286(var_120,var_280)
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.eatDown(o,Int(var_117))
        if var_117 != var_413
            local var_417::ASCIIString = "EXjqGHrT"
        end
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 - var_120
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_156)))
        Creature.eatUp(o,Int(var_117))
        o.mem[var_156] = var_120
        var_243 = var_243 | var_123
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        o.mem[var_120] = var_120
        Creature.eatRight(o,Int(var_117))
        var_120 = func_189(var_120)
        o.mem[var_120] = var_120
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        Creature.stepUp(o)
        var_124 = func_142(var_124)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 * var_156
        Creature.stepUp(o)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        var_120 = var_120 * var_120
        o.mem[var_120] = var_120
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_117))
        Creature.stepUp(o)
        var_243 = var_123 | var_243
        Creature.eatLeft(o,Int(var_117))
        return true
    end),[110,300,95,0,1,1,1],6,9396,84,173130,0x00000151,Dict(-26920=>-26920,-1631=>-1631,0=>0,-29748=>-29748,-8030=>-8030,10070=>10070,-4015=>0,23323=>23323,19308=>0,1512=>1512,9463=>9463,1=>1),[1917,737],93),RpcApi.SimpleOrganism(0x00
000000000453ec,:(function (o::Creature.Organism,)
        function func_420(var_419::Int16=-11171)
            return var_419
        end
        local var_413::Int8 = -128
        function func_286(var_284::Int16=2081,var_285::Int64=9145930075523767031)
            Creature.stepRight(o)
            Creature.stepRight(o)
            if var_285 > var_285
            end
            return var_284
        end
        local var_280::Int64 = -2141542542016055773
        local var_243::Bool = false
        function func_232(var_230::Bool=false,var_231::Int16=-29748)
            Creature.stepDown(o)
            if var_231 > var_231
            end
            Creature.stepDown(o)
            var_230 = Bool(abs(var_230 - var_230))
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            return var_230
        end
        function func_189(var_188::Int16=2883)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            return var_188
        end
        function func_142(var_141::Int64=7558744495470982559)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            return var_141
        end
        local var_123::Bool = true
        local var_120::Int16 = -4015
        local var_117::Int8 = 61
        var_243 = func_232(var_123)
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_120)))
        Creature.eatRight(o,Int(var_117))
        Creature.stepDown(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.stepUp(o)
        var_156 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_156
            end
        var_243 = func_232(var_243)
        Creature.stepUp(o)
        Creature.stepDown(o)
        var_117 = var_117 + var_117
        Creature.stepLeft(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepRight(o)
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.eatRight(o,Int(var_117))
        var_120 = func_286(var_120)
        var_120 = func_286(var_120,var_280)
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.eatDown(o,Int(var_117))
        if var_117 != var_413
            local var_417::ASCIIString = "EXjqGHrT"
        end
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 - var_120
        Creature.eatUp(o,Int(var_117))
        o.mem[var_156] = var_120
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        o.mem[var_120] = var_120
        Creature.eatRight(o,Int(var_117))
        var_120 = func_189(var_120)
        o.mem[var_120] = var_120
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        Creature.stepUp(o)
        var_124 = func_142(var_124)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 * var_156
        Creature.stepUp(o)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        var_120 = var_120 * var_120
        o.mem[var_120] = var_120
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_117))
        Creature.stepUp(o)
        var_243 = var_123 | var_243
        Creature.eatLeft(o,Int(var_117))
        return true
    end),[110,300,95,0,1,1,1],6,9396,84,143226,0x00000142,Dict(-26920=>-26920,-1631=>-1631,0=>0,-29748=>-29748,-8030=>-8030,10070=>10070,-4015=>0,23323=>23323,19308=>0,1512=>1512,9463=>9463,1=>1),[1914,702],86),RpcApi.SimpleOrganism(0x00
000000000452aa,:(function (o::Creature.Organism,)
        function func_420(var_419::Int16=-11171)
            return var_419
        end
        local var_413::Int8 = -128
        function func_286(var_284::Int16=2081,var_285::Int64=9145930075523767031)
            local var_424::Int64 = -7569825667664057809
            Creature.stepRight(o)
            Creature.stepRight(o)
            Creature.stepRight(o)
            Creature.stepRight(o)
            return var_284
        end
        local var_280::Int64 = -2141542542016055773
        local var_243::Bool = false
        function func_232(var_230::Bool=false,var_231::Int16=-29748)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            Creature.stepDown(o)
            var_230 = Bool(abs(var_230 - var_230))
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            return var_230
        end
        function func_189(var_188::Int16=2883)
            local var_421::Int16 = -32012
            var_188 = if haskey(o.mem,var_188)
                    o.mem[var_188]
                else
                    var_188
                end
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            return var_188
        end
        function func_142(var_141::Int64=7558744495470982559)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
            var_141 = var_141 - var_141
            Creature.stepUp(o)
            return var_141
        end
        local var_123::Bool = true
        local var_120::Int16 = -4015
        local var_117::Int8 = 61
        var_243 = func_232(var_123)
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_120)))
        Creature.eatRight(o,Int(var_117))
        Creature.stepDown(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.stepUp(o)
        var_156 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_156
            end
        var_243 = func_232(var_243)
        Creature.stepDown(o)
        var_117 = var_117 + var_117
        Creature.stepLeft(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        if var_243 <= var_123
        end
        Creature.stepRight(o)
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.eatRight(o,Int(var_117))
        var_120 = func_286(var_120)
        var_120 = func_286(var_120,var_280)
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.eatDown(o,Int(var_117))
        if var_117 != var_413
            local var_417::ASCIIString = "EXjqGHrT"
        end
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 - var_120
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_156)))
        Creature.eatUp(o,Int(var_117))
        o.mem[var_156] = var_120
        var_243 = var_243 | var_123
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        o.mem[var_120] = var_120
        Creature.eatRight(o,Int(var_117))
        var_120 = func_189(var_120)
        o.mem[var_120] = var_120
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        Creature.stepUp(o)
        var_124 = func_142(var_124)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 * var_156
        Creature.stepUp(o)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        var_120 = var_120 * var_120
        o.mem[var_120] = var_120
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_117))
        Creature.stepUp(o)
        var_243 = var_123 | var_243
        Creature.eatLeft(o,Int(var_117))
        return true
    end),[110,300,95,0,1,1,1],6,9396,84,128376,0x00000152,Dict(-26920=>-26920,-1631=>-1631,0=>0,-29748=>-29748,-8030=>-8030,10070=>10070,-4015=>0,23323=>23323,19308=>0,1512=>1512,9463=>9463,1=>1),[1905,713],94),RpcApi.SimpleOrganism(0x00
00000000045629,:(function (o::Creature.Organism,)
        function func_420(var_419::Int16=-11171)
            return var_419
        end
        local var_413::Int8 = -128
        function func_286(var_284::Int16=2081,var_285::Int64=9145930075523767031)
            Creature.stepRight(o)
            Creature.stepRight(o)
            Creature.stepLeft(o)
            Creature.stepRight(o)
            return var_284
        end
        local var_280::Int64 = -2141542542016055773
        local var_243::Bool = false
        function func_232(var_230::Bool=false,var_231::Int16=-29748)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            Creature.stepDown(o)
            var_230 = Bool(abs(var_230 - var_230))
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            return var_230
        end
        function func_189(var_188::Int16=2883)
            local var_421::Int16 = -32012
            var_188 = if haskey(o.mem,var_188)
                    o.mem[var_188]
                else
                    var_188
                end
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            return var_188
        end
        function func_142(var_141::Int64=7558744495470982559)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
            var_141 = var_141 / var_141
            Creature.stepUp(o)
            return var_141
        end
        local var_123::Bool = true
        local var_120::Int16 = -4015
        local var_117::Int8 = 61
        var_243 = func_232(var_123)
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_120)))
        Creature.eatRight(o,Int(var_117))
        Creature.stepDown(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.stepUp(o)
        var_156 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_156
            end
        var_243 = func_232(var_243)
        Creature.stepDown(o)
        var_117 = var_117 + var_117
        Creature.stepLeft(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        if var_243 <= var_123
        end
        Creature.stepRight(o)
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.eatRight(o,Int(var_117))
        var_120 = func_286(var_120)
        var_120 = func_286(var_120,var_280)
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.eatDown(o,Int(var_117))
        if var_117 != var_413
            local var_417::ASCIIString = "EXjqGHrT"
        end
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 - var_120
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_156)))
        Creature.eatUp(o,Int(var_117))
        o.mem[var_156] = var_120
        var_243 = var_243 | var_123
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        o.mem[var_120] = var_120
        Creature.eatRight(o,Int(var_117))
        var_120 = func_189(var_120)
        o.mem[var_120] = var_120
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        Creature.stepUp(o)
        var_124 = func_142(var_124)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 * var_156
        Creature.stepUp(o)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        var_120 = var_120 * var_120
        o.mem[var_120] = var_120
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_117))
        var_124 = var_124 + var_124
        var_243 = var_123 | var_243
        Creature.eatLeft(o,Int(var_117))
        return true
    end),[110,300,95,0,1,1,1],6,9396,84,101169,0x00000157,Dict(-26920=>-26920,-1631=>-1631,0=>0,-29748=>-29748,-8030=>-8030,10070=>10070,-4015=>0,23323=>23323,19308=>0,1512=>1512,9463=>9463,1=>1),[1918,934],93),RpcApi.SimpleOrganism(0x00
000000000453d3,:(function (o::Creature.Organism,)
        function func_420(var_419::Int16=-11171)
            return var_419
        end
        local var_413::Int8 = -128
        function func_286(var_284::Int16=2081,var_285::Int64=9145930075523767031)
            local var_424::Int64 = -7569825667664057809
            Creature.stepRight(o)
            Creature.stepRight(o)
            Creature.stepRight(o)
            Creature.stepRight(o)
            return var_284
        end
        local var_280::Int64 = -2141542542016055773
        local var_243::Bool = false
        function func_232(var_230::Bool=false,var_231::Int16=-29748)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            var_230 = Bool(abs(var_230 - var_230))
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            return var_230
        end
        function func_189(var_188::Int16=2883)
            local var_421::Int16 = -32012
            var_188 = if haskey(o.mem,var_188)
                    o.mem[var_188]
                else
                    var_188
                end
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            return var_188
        end
        function func_142(var_141::Int64=7558744495470982559)
            Creature.stepUp(o)
            Creature.stepUp(o)
            var_141 = var_141 - var_141
            Creature.stepUp(o)
            return var_141
        end
        local var_123::Bool = true
        local var_120::Int16 = -4015
        local var_117::Int8 = 61
        var_243 = func_232(var_123)
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_120)))
        Creature.eatRight(o,Int(var_117))
        Creature.stepDown(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.stepUp(o)
        var_156 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_156
            end
        var_243 = func_232(var_243)
        Creature.stepDown(o)
        var_117 = var_117 + var_117
        Creature.stepLeft(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        if var_243 <= var_123
        end
        Creature.stepRight(o)
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.eatRight(o,Int(var_117))
        var_120 = func_286(var_120)
        var_120 = func_286(var_120,var_280)
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.eatDown(o,Int(var_117))
        if var_117 != var_413
            local var_417::ASCIIString = "EXjqGHrT"
        end
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 - var_120
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_156)))
        Creature.eatUp(o,Int(var_117))
        o.mem[var_156] = var_120
        var_243 = var_243 | var_123
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        o.mem[var_120] = var_120
        Creature.eatRight(o,Int(var_117))
        var_120 = func_189(var_120)
        o.mem[var_120] = var_120
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        Creature.stepUp(o)
        var_124 = func_142(var_124)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 * var_156
        Creature.stepUp(o)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        var_120 = var_120 * var_120
        o.mem[var_120] = var_120
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_117))
        Creature.stepUp(o)
        var_243 = var_123 | var_243
        Creature.eatLeft(o,Int(var_117))
        return true
    end),[110,300,95,0,1,1,1],6,9396,84,99309,0x00000155,Dict(-26920=>-26920,-1631=>-1631,0=>0,-29748=>-29748,-8030=>-8030,10070=>10070,-4015=>0,23323=>23323,19308=>0,1512=>1512,9463=>9463,1=>1),[1916,660],92),RpcApi.SimpleOrganism(0x000
0000000045543,:(function (o::Creature.Organism,)
        function func_420(var_419::Int16=-11171)
            return var_419
        end
        local var_413::Int8 = -128
        function func_286(var_284::Int16=2081,var_285::Int64=9145930075523767031)
            Creature.stepRight(o)
            Creature.stepRight(o)
            var_285 = var_285 / var_285
            Creature.stepRight(o)
            return var_284
        end
        local var_280::Int64 = -2141542542016055773
        local var_243::Bool = false
        function func_232(var_230::Bool=false,var_231::Int16=-29748)
            local var_424::Int64 = -1230920623829471897
            Creature.stepDown(o)
            var_424 = var_424 / var_424
            Creature.stepDown(o)
            var_230 = Bool(abs(var_230 - var_230))
            Creature.stepDown(o)
            var_424 = var_424 / var_424
            Creature.stepDown(o)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            return var_230
        end
        function func_189(var_188::Int16=2883)
            local var_421::Int16 = -32012
            var_188 = if haskey(o.mem,var_421)
                    o.mem[var_421]
                else
                    var_188
                end
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            return var_188
        end
        function func_142(var_141::Int64=7558744495470982559)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            return var_141
        end
        local var_123::Bool = true
        local var_120::Int16 = -4015
        local var_117::Int8 = 61
        var_243 = func_232(var_123)
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_120)))
        Creature.eatRight(o,Int(var_117))
        Creature.stepDown(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        var_124 = var_124 - var_124
        Creature.stepDown(o)
        Creature.stepUp(o)
        var_156 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_156
            end
        var_243 = func_232(var_243)
        Creature.stepUp(o)
        Creature.stepDown(o)
        var_117 = var_117 + var_117
        Creature.stepLeft(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepRight(o)
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.eatRight(o,Int(var_117))
        var_120 = func_286(var_120)
        var_120 = func_286(var_120,var_280)
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.eatDown(o,Int(var_117))
        if var_117 != var_413
            local var_417::ASCIIString = "EXjqGHrT"
        end
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 - var_120
        Creature.eatUp(o,Int(var_117))
        o.mem[var_156] = var_120
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        o.mem[var_120] = var_120
        Creature.eatRight(o,Int(var_117))
        var_120 = func_189(var_120)
        o.mem[var_120] = var_120
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        Creature.stepUp(o)
        var_124 = func_142(var_124)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 * var_156
        Creature.stepUp(o)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        var_120 = var_120 * var_120
        o.mem[var_120] = var_120
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_117))
        Creature.stepUp(o)
        var_243 = var_123 | var_243
        Creature.eatLeft(o,Int(var_117))
        return true
    end),[110,300,95,0,1,1,1],6,9396,84,99099,0x00000147,Dict(-26920=>-26920,-1631=>-1631,0=>0,-29748=>-29748,-8030=>-8030,10070=>10070,-4015=>0,23323=>23323,19308=>0,1512=>1512,9463=>9463,1=>1),[1908,775],92),RpcApi.SimpleOrganism(0x000
00000000456c2,:(function (o::Creature.Organism,)
        function func_420(var_419::Int16=-11171)
            return var_419
        end
        local var_413::Int8 = -128
        function func_286(var_284::Int16=2081,var_285::Int64=9145930075523767031)
            Creature.stepRight(o)
            Creature.stepRight(o)
            Creature.stepLeft(o)
            Creature.stepRight(o)
            return var_284
        end
        local var_280::Int64 = -2141542542016055773
        local var_243::Bool = false
        function func_232(var_230::Bool=false,var_231::Int16=-29748)
            local var_424::Int64 = 6653372799386234671
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            Creature.stepDown(o)
            var_230 = Bool(abs(var_230 - var_230))
            var_424 = Int(Creature.getEnergy(o,Int(var_231),Int(var_231)))
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            return var_230
        end
        function func_189(var_188::Int16=2883)
            local var_421::Int16 = -32012
            var_188 = if haskey(o.mem,var_188)
                    o.mem[var_188]
                else
                    var_188
                end
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            return var_188
        end
        function func_142(var_141::Int64=7558744495470982559)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
            var_141 = var_141 / var_141
            Creature.stepUp(o)
            return var_141
        end
        local var_123::Bool = true
        local var_120::Int16 = -4015
        local var_117::Int8 = 61
        var_243 = func_232(var_123)
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_120)))
        Creature.eatRight(o,Int(var_117))
        Creature.stepDown(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.stepUp(o)
        var_156 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_156
            end
        var_243 = func_232(var_243)
        Creature.stepDown(o)
        var_117 = var_117 + var_117
        Creature.stepLeft(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        if var_243 <= var_123
        end
        Creature.stepRight(o)
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.eatRight(o,Int(var_117))
        var_120 = func_286(var_120)
        var_120 = func_286(var_120,var_280)
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.eatDown(o,Int(var_117))
        if var_117 != var_413
            local var_417::ASCIIString = "EXjqGHrT"
        end
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 - var_120
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_156)))
        Creature.eatUp(o,Int(var_117))
        o.mem[var_156] = var_120
        var_243 = var_243 | var_123
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        o.mem[var_120] = var_120
        Creature.eatRight(o,Int(var_117))
        var_120 = func_189(var_120)
        o.mem[var_120] = var_120
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        Creature.stepUp(o)
        var_124 = func_142(var_124)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 * var_156
        Creature.stepUp(o)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        var_120 = var_120 * var_120
        o.mem[var_120] = var_120
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_117))
        var_124 = var_124 + var_124
        var_243 = var_123 | var_243
        Creature.eatLeft(o,Int(var_117))
        return true
    end),[110,300,95,0,1,1,1],6,9396,84,97444,0x00000159,Dict(-26920=>-26920,-1631=>-1631,0=>0,-29748=>-29748,-8030=>-8030,10070=>10070,-4015=>0,23323=>23323,19308=>0,1512=>1512,9463=>9463,1=>1),[1910,698],95),RpcApi.SimpleOrganism(0x000
00000000455ae,:(function (o::Creature.Organism,)
        function func_420(var_419::Int16=-11171)
            return var_419
        end
        local var_413::Int8 = -128
        function func_286(var_284::Int16=2081,var_285::Int64=9145930075523767031)
            Creature.stepRight(o)
            Creature.stepRight(o)
            o.mem[var_284] = var_284
            return var_284
        end
        local var_280::Int64 = -2141542542016055773
        local var_243::Bool = false
        function func_232(var_230::Bool=false,var_231::Int16=-29748)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            Creature.stepDown(o)
            var_230 = Bool(abs(var_230 - var_230))
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            var_231 = var_231 / var_231
            return var_230
        end
        function func_189(var_188::Int16=2883)
            local var_421::Int16 = -32012
            var_188 = if haskey(o.mem,var_421)
                    o.mem[var_421]
                else
                    var_188
                end
            Creature.stepUp(o)
            Creature.stepUp(o)
            return var_188
        end
        function func_142(var_141::Int64=7558744495470982559)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
            Creature.stepUp(o)
            return var_141
        end
        local var_123::Bool = true
        local var_120::Int16 = -4015
        local var_117::Int8 = 61
        var_243 = func_232(var_123)
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_120)))
        Creature.eatRight(o,Int(var_117))
        Creature.stepDown(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.stepUp(o)
        var_156 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_156
            end
        var_243 = func_232(var_243)
        Creature.stepDown(o)
        var_117 = var_117 + var_117
        Creature.stepLeft(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepRight(o)
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.eatRight(o,Int(var_117))
        var_120 = func_286(var_120)
        var_120 = func_286(var_120,var_280)
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.eatDown(o,Int(var_117))
        if var_117 != var_413
            local var_417::ASCIIString = "EXjqGHrT"
        end
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 - var_120
        Creature.eatUp(o,Int(var_117))
        o.mem[var_156] = var_120
        var_243 = var_243 | var_123
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        o.mem[var_120] = var_120
        Creature.eatRight(o,Int(var_117))
        var_120 = func_189(var_120)
        o.mem[var_120] = var_120
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        Creature.stepUp(o)
        var_124 = func_142(var_124)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 * var_156
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.stepUp(o)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        var_120 = var_120 * var_120
        o.mem[var_120] = var_120
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_117))
        Creature.stepUp(o)
        var_243 = var_123 | var_243
        Creature.eatLeft(o,Int(var_117))
        return true
    end),[110,300,95,0,1,1,1],6,9079,84,93262,0x00000148,Dict(-26920=>-26920,-1631=>-1631,0=>0,-29748=>-29748,-8030=>-8030,10070=>10070,-4015=>0,23323=>23323,19308=>0,1512=>1512,9463=>9463,1=>1),[1910,894],90),RpcApi.SimpleOrganism(0x000
0000000045636,:(function (o::Creature.Organism,)
        function func_420(var_419::Int16=-11171)
            return var_419
        end
        local var_413::Int8 = -128
        function func_286(var_284::Int16=2081,var_285::Int64=9145930075523767031)
            var_285 = var_285 / var_285
            Creature.stepRight(o)
            Creature.stepRight(o)
            return var_284
        end
        local var_280::Int64 = -2141542542016055773
        local var_243::Bool = false
        function func_232(var_230::Bool=false,var_231::Int16=-29748)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            return var_230
        end
        function func_189(var_188::Int16=2883)
            local var_421::Int16 = -32012
            var_188 = if haskey(o.mem,var_421)
                    o.mem[var_421]
                else
                    var_188
                end
            Creature.stepUp(o)
            Creature.stepUp(o)
            var_188 = if haskey(o.mem,var_188)
                    o.mem[var_188]
                else
                    var_188
                end
            return var_188
        end
        function func_142(var_141::Int64=7558744495470982559)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
            Creature.stepUp(o)
            return var_141
        end
        local var_123::Bool = true
        local var_120::Int16 = -4015
        local var_117::Int8 = 61
        var_243 = func_232(var_123)
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_120)))
        Creature.eatRight(o,Int(var_117))
        Creature.stepDown(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.stepUp(o)
        var_156 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_156
            end
        var_243 = func_232(var_243)
        Creature.stepDown(o)
        var_117 = var_117 + var_117
        Creature.stepLeft(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepRight(o)
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.eatRight(o,Int(var_117))
        var_120 = func_286(var_120)
        var_120 = func_286(var_120,var_280)
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.eatDown(o,Int(var_117))
        if var_117 != var_413
            local var_417::ASCIIString = "EXjqGHrT"
        end
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.eatUp(o,Int(var_117))
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 - var_120
        Creature.eatUp(o,Int(var_117))
        o.mem[var_156] = var_120
        var_243 = var_243 | var_123
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        o.mem[var_120] = var_120
        Creature.eatRight(o,Int(var_117))
        var_120 = func_189(var_120)
        o.mem[var_120] = var_120
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        Creature.stepUp(o)
        var_124 = func_142(var_124)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 * var_156
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.stepUp(o)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        o.mem[var_120] = var_120
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_117))
        Creature.stepUp(o)
        var_243 = var_123 | var_243
        Creature.eatLeft(o,Int(var_117))
        return true
    end),[110,300,95,0,1,1,1],6,9079,84,84729,0x0000014b,Dict(-26920=>-26920,-1631=>-1631,0=>0,-29748=>-29748,-8030=>-8030,10070=>10070,-4015=>0,23323=>23323,19308=>0,1512=>1512,9463=>9463,1=>1),[1917,934],89),RpcApi.SimpleOrganism(0x000
0000000045649,:(function (o::Creature.Organism,)
        function func_420(var_419::Int16=-11171)
            return var_419
        end
        local var_413::Int8 = -128
        function func_286(var_284::Int16=2081,var_285::Int64=9145930075523767031)
            Creature.stepRight(o)
            Creature.stepRight(o)
            Creature.stepRight(o)
            Creature.stepRight(o)
            return var_284
        end
        local var_280::Int64 = -2141542542016055773
        local var_243::Bool = false
        function func_232(var_230::Bool=false,var_231::Int16=-29748)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            Creature.stepDown(o)
            var_230 = Bool(abs(var_230 - var_230))
            Creature.stepDown(o)
            Creature.stepDown(o)
            Creature.stepDown(o)
            o.mem[var_231] = var_231
            return var_230
        end
        function func_189(var_188::Int16=2883)
            local var_421::Int16 = -32012
            var_188 = if haskey(o.mem,var_188)
                    o.mem[var_188]
                else
                    var_188
                end
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepUp(o)
            return var_188
        end
        function func_142(var_141::Int64=7558744495470982559)
            Creature.stepUp(o)
            Creature.stepUp(o)
            Creature.stepRight(o)
            var_141 = var_141 - var_141
            var_141 = var_141 * var_141
            Creature.stepUp(o)
            return var_141
        end
        local var_123::Bool = true
        local var_120::Int16 = -4015
        local var_117::Int8 = 61
        var_243 = func_232(var_123)
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_120)))
        Creature.eatRight(o,Int(var_117))
        Creature.stepDown(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        Creature.stepDown(o)
        Creature.stepUp(o)
        var_156 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_156
            end
        var_243 = func_232(var_243)
        Creature.stepDown(o)
        var_117 = var_117 + var_117
        Creature.stepLeft(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepDown(o)
        if var_243 <= var_123
        end
        Creature.stepRight(o)
        var_120 = if haskey(o.mem,var_120)
                o.mem[var_120]
            else
                var_120
            end
        Creature.eatRight(o,Int(var_117))
        var_120 = func_286(var_120)
        var_120 = func_286(var_120,var_280)
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.eatDown(o,Int(var_117))
        if var_117 != var_413
            local var_417::ASCIIString = "EXjqGHrT"
        end
        Creature.stepRight(o)
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 - var_120
        var_124 = Int(Creature.getEnergy(o,Int(var_120),Int(var_156)))
        Creature.eatUp(o,Int(var_117))
        o.mem[var_156] = var_120
        var_243 = var_243 | var_123
        Creature.eatRight(o,Int(var_117))
        Creature.stepRight(o)
        o.mem[var_120] = var_120
        Creature.eatRight(o,Int(var_117))
        var_120 = func_189(var_120)
        o.mem[var_120] = var_120
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        Creature.stepUp(o)
        var_124 = func_142(var_124)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        var_120 = var_120 * var_156
        Creature.stepUp(o)
        Creature.stepUp(o)
        Creature.eatUp(o,Int(var_117))
        Creature.stepLeft(o)
        var_120 = var_120 * var_120
        o.mem[var_120] = var_120
        Creature.stepLeft(o)
        Creature.stepLeft(o)
        Creature.eatLeft(o,Int(var_117))
        Creature.stepUp(o)
        var_243 = var_123 | var_243
        Creature.eatLeft(o,Int(var_117))
        return true
    end),[110,300,95,0,1,1,1],6,9396,84,81957,0x00000153,Dict(-26920=>-26920,-1631=>-1631,0=>0,-29748=>-29748,-8030=>-8030,10070=>10070,-4015=>0,23323=>23323,19308=>0,1512=>1512,9463=>9463,1=>1),[1909,790],94)]

max_stars_repo_name: tmptrash/jevo

max_issues_repo_name: tmptrash/jevo

max_forks_repo_name: tmptrash/jevo


text:
# Convert a string to a decimal, e.g. "0.01" -> Decimal(0, 1, -2)
function Base.parse(::Type{Decimal}, str::AbstractString)
    if 'e' in str
        return parse(Decimal, scinote(str))
    end
    c, q = parameters(('.' in str) ? split(str, '.') : str)
    normalize(Decimal((str[1] == '-') ? 1 : 0, c, q))
end

decimal(str::AbstractString) = parse(Decimal, str)

# Convert a number to a decimal
Decimal(num::Real) = parse(Decimal, string(num))
Base.convert(::Type{Decimal}, num::Real) = Decimal(num::Real)
decimal(x::Real) = Decimal(x)
Decimal(x::Decimal) = x

# Get Decimal constructor parameters from string
parameters(x::AbstractString) = (abs(parse(BigInt, x)), 0)

# Get Decimal constructor parameters from array
function parameters(x::Array)
    c = parse(BigInt, join(x))
    (abs(c), -length(x[2]))
end

# Get decimal() argument from scientific notation
function scinote(str::AbstractString)
    s = (str[1] == '-') ? "-" : ""
    n, expo = split(str, 'e')
    n = split(n, '.')
    if s == "-"
        n[1] = n[1][2:end]
    end
    if parse(Int64, expo) > 0
        shift = parse(Int64, expo) - ((length(n) == 2) ? length(n[2]) : 0)
        s * join(n) * repeat("0", shift)
    else
        shift = -parse(Int64, expo) - ((length(n) == 2) ? length(n[1]) : length(n))
        s * "0." * repeat("0", shift) * join(n)
    end
end

# Convert a decimal to a string
function Base.print(io::IO, x::Decimal)
    c = string(x.c)
    negative = (x.s == 1) ? "-" : ""
    if x.q > 0
        print(io, negative, c, repeat("0", x.q))
    elseif x.q < 0
        shift = x.q + length(c)
        if shift > 0
            print(io, negative, c[1:shift], ".", c[(shift+1):end])
        else
            print(io, negative, "0.", repeat("0", -shift), c)
        end
    else
        print(io, negative, c)
    end
end

# Zero/one value
Base.zero(::Type{Decimal}) = Decimal(0,0,0)
Base.one(::Type{Decimal}) = Decimal(0,1,0)

# convert a decimal to any subtype of Real
(::Type{T})(x::Decimal) where {T<:Real} = parse(T, string(x))

# Convert a decimal to an integer if possible, a float if not
function number(x::Decimal)
    ix = (str = string(x) ; fx = parse(Float64, str); round(Int64, fx))
    (ix == fx) ? ix : fx
end

# sign
Base.signbit(x::Decimal) = x.s != 0

ext: jl


text:
import Octavian

import Aqua
import BenchmarkTools
import InteractiveUtils
import LinearAlgebra
import LoopVectorization
import Random
import Test
import VectorizationBase

using Test: @testset, @test, @test_throws, @inferred

include("test_suite_preamble.jl")

@info("VectorizationBase.num_cores() is $(VectorizationBase.num_cores())")
@info("Octavian.OCTAVIAN_NUM_TASKS[] is $(Octavian.OCTAVIAN_NUM_TASKS[]) tasks")

Random.seed!(123)

include("block_sizes.jl")
include("init.jl")
include("integer_division.jl")
include("macrokernels.jl")
include("matmul_coverage.jl")
include("utils.jl")

if !coverage
    include("matmul_main.jl")
end

include("aqua.jl") # run the Aqua.jl tests last


text:
using Base.Test

include("frames.jl")


text:
module MPITests

using Test

@testset "Hello" begin include("HelloTests.jl") end

@testset "MPIBackend" begin include("MPIBackendTests.jl") end

@testset "Interfaces" begin include("InterfacesTests.jl") end

@testset "FDM" begin include("FDMTests.jl") end

@testset "FEMSA" begin include("FEMSATests.jl") end

@testset "PTimers" begin include("PTimersTests.jl") end

end


text:
#InspectDR: Base functionnality and types for Gtk layer
#-------------------------------------------------------------------------------

import Gtk: get_gtk_property, set_gtk_property!, signal_connect, @guarded

#Create module aliasese to access constants:
#TODO: Figure out why constants are Int32 instead of Int???
import Gtk: GdkKeySyms
import Gtk: GtkPositionType, GdkEventType, GdkEventMask
import Gtk: GConstants.GtkShadowType

#==Extensions
===============================================================================#
#TODO: Why can't I just access these functions directly from Gtk/gen/gbox3???

function draw_value(scale::Gtk.GtkScale, draw_value_::Bool)
	ccall((:gtk_scale_set_draw_value,Gtk.libgtk),Nothing,(Ptr{Gtk.GObject},Cint),scale,draw_value_)
	return scale
end
function value_pos(scale::Gtk.GtkScale,pos::Int)
	ccall((:gtk_scale_set_value_pos,Gtk.libgtk),Nothing,(Ptr{Gtk.GObject},Cint),scale,pos)
	return scale
end

function can_focus(widget::Gtk.GtkWidget,can_focus_::Bool)
	ccall((:gtk_widget_set_can_focus,Gtk.libgtk),Nothing,(Ptr{Gtk.GObject},Cint),widget,can_focus_)
	return widget
end

function window_close(window::Gtk.GtkWindow)
	ccall((:gtk_window_close,Gtk.libgtk),Nothing,(Ptr{Gtk.GObject},),window)
	return
end

function focus(window::Gtk.GtkWindow,widget)
	ccall((:gtk_window_set_focus,Gtk.libgtk),Nothing,(Ptr{Gtk.GObject},Ptr{Gtk.GObject}),window,widget)
	return window
end
function focus(widget)
	ccall((:gtk_widget_grab_focus,Gtk.libgtk),Nothing,(Ptr{Gtk.GObject},),widget)
	return widget
end
#=
function activate_key(wnd::Gtk.GtkWindow,event::GdkEventKey)
	ccall((:gtk_window_activate_key,Gtk.libgtk),Cint,(Ptr{Gtk.GObject},Ptr{Gtk.GObject}),wnd,event)
	return wnd
end
#gboolean gtk_window_activate_key (GtkWindow *window, GdkEventKey *event);
=#
function gdk_cursor_new(id::String)
	d = ccall((:gdk_display_get_default,Gtk.libgdk),Ptr{Nothing},(Cstring,),id)
	return ccall((:gdk_cursor_new_from_name,Gtk.libgdk),Ptr{Nothing},(Ptr{Nothing}, Cstring), d,id)
end

function gdk_window_set_cursor(wnd, cursor::Ptr{Nothing})
	wptr = Gtk.GAccessor.window(wnd)
	ccall((:gdk_window_set_cursor,Gtk.libgdk),Nothing,(Ptr{Nothing},Ptr{Nothing}), wptr, cursor)
	return
end

#==Constants
===============================================================================#
function initialize_cursors()
	global CURSOR_DEFAULT = Gtk.C_NULL #WANTCONST
	global CURSOR_PAN = gdk_cursor_new("grabbing") #WANTCONST
	global CURSOR_MOVE = gdk_cursor_new("move") #WANTCONST
	global CURSOR_BOXSELECT = gdk_cursor_new("crosshair") #WANTCONST
end

const XAXIS_SCALEMAX = 1000
const XAXIS_POS_STEPRES = 1/500

#==Display types
===============================================================================#
#Generic type used to spawn new InspectDR display windows:
struct GtkDisplay <: AbstractDisplay
end

#==Main types
===============================================================================#
abstract type InputState end #Identifies current user input state.

abstract type CtrlElement end #Controllable element
#=Implement:
TODO: explain interface
=#

mutable struct CtrlMarker <: CtrlElement
	prop::HVMarker #Properties
	Δinfo::Vector2D #Offset of Δ-information block
	Δbb::BoundingBox #Last postion of Δ-information block (optimize hit test)
	ref::NullOr{CtrlMarker} #Reference marker
end

#Grouping of controllable markers (used to get ::Plot object to render)
mutable struct CtrlMarkerGroup <: PlotAnnotation
	elem::Vector{CtrlMarker}
	fntcoord::Font
	fntdelta::Font
end
CtrlMarkerGroup(reffont::Font) = CtrlMarkerGroup([],
	Font(reffont, _size = 10), Font(reffont, _size = 12)
)

mutable struct GtkMouseOver
	istrip::Int
	pos::NullOr{Point2D}
end
GtkMouseOver() = GtkMouseOver(0, nothing)

mutable struct PlotWidget
	widget::_Gtk.Box #Base widget
	canvas::_Gtk.Canvas #Actual plot area
	src::Plot
	plotinfo::Plot2DInfo
	state::InputState

	#Scrollbars to control x-scale & position:
	w_xscale::_Gtk.Scale
	xscale::_Gtk.Adjustment
	w_xpos::_Gtk.Scale
	xpos::_Gtk.Adjustment

	#Display image (Cached):
	plotbuf::CairoBufferedPlot
#	bufbb::BoundingBox

	curstrip::Int #Currently active strip
	mouseover::GtkMouseOver #Where is mouse

	#Control elements:
	markers::CtrlMarkerGroup
	refmarker::NullOr{CtrlMarker} #Used as ref

	#Restrict h/v motion:
	hallowed::Bool
	vallowed::Bool

	#External event handlers:
	eh_plothover::NullOr{HandlerInfo}
end

#Supports multiplot:
mutable struct GtkPlot
	destroyed::Bool #Way to know if window is actually desplayed
	wnd::_Gtk.Window
	grd::_Gtk.Grid #Holds subplot widgets
	subplots::Vector{PlotWidget}
	src::Multiplot #Akward for sync: subplots.src are references to src.subplots.
	status::_Gtk.Label
end

#==Accessors
===============================================================================#
function activestrip(w::PlotWidget)
	istrip = w.curstrip
	nstrips = length(w.src.strips)
	if istrip < 1 || istrip > nstrips
		istrip = 0
	end
	return istrip
end

#==Mutators
===============================================================================#
function settitle(wnd::_Gtk.Window, title::String)
	if length(title)> 0
		title = "InspectDR - $(title)"
	else
		title = "InspectDR"
	end
	set_gtk_property!(wnd, :title, title)
end

function settitle(gplot::GtkPlot, title::String)
	gplot.src.title = title
	settitle(gplot.wnd, gplot.src.title)
end

#==Main functions
===============================================================================#

function invalidbuffersize(pwidget::PlotWidget)
	return width(pwidget.canvas) != width(pwidget.plotbuf.surf) ||
		height(pwidget.canvas) != height(pwidget.plotbuf.surf)
end

#Render PlotWidget widget to buffer:
#-------------------------------------------------------------------------------
function render(pwidget::PlotWidget; refreshdata::Bool=true)
	plot = pwidget.src #WANTCONST
	#Create new buffer large enough to match canvas:
	#TODO: Is crating surfaces expensive?  This solution might be bad.
	if invalidbuffersize(pwidget)
		Cairo.destroy(pwidget.plotbuf.surf)
		Cairo.destroy(pwidget.plotbuf.data)
		#TODO: use RGB surface? Gtk.cairo_surface_for() appears to generate ARGB surface (slower?)
		#pwidget.plotbuf.surf = Cairo.CairoRGBSurface(width(pwidget.canvas),height(pwidget.canvas))
		pwidget.plotbuf.surf = Gtk.cairo_surface_for(pwidget.canvas) #create similar
		pwidget.plotbuf.data = Gtk.cairo_surface_for(pwidget.canvas) #create similar - must be ARGB
	end

	w = width(pwidget.canvas); h = height(pwidget.canvas)
	bb = BoundingBox(0, w, 0, h)
	pwidget.plotinfo = render(pwidget.plotbuf, plot, bb, refreshdata)
	nstrips = length(pwidget.plotinfo.strips)
	pwidget.curstrip = max(pwidget.curstrip, 1) #Focus on 1st strip - if no strip has focus
	pwidget.curstrip = min(pwidget.curstrip, nstrips) #Make sure focus is not beyond nstrips
	return
end

function refresh(w::PlotWidget; refreshdata::Bool=true)
	render(w, refreshdata=refreshdata)
	Gtk.draw(w.canvas)
	return
end

#==IO functions
===============================================================================#
#_write() GtkPlot: Auto-coumpute w/h
function _write(path::String, mime::MIME, gplot::GtkPlot)
	_write(path, mime, gplot.src)
end

write_png(path::String, gplot::GtkPlot) = _write(path, MIMEpng(), gplot)
write_svg(path::String, gplot::GtkPlot) = _write(path, MIMEsvg(), gplot)
write_eps(path::String, gplot::GtkPlot) = _write(path, MIMEeps(), gplot)
write_pdf(path::String, gplot::GtkPlot) = _write(path, MIMEpdf(), gplot)

#Last line


text:
# Make an instance of a ChronAgeData object for nSamples
nSamples = 4
smpl = NewChronAgeData(nSamples)
smpl.Name          = ("Sample 1", "Sample 2", "Sample 3", "Sample 4") # Et cetera
smpl.Age          .= [ 699.1,  708.8,  723.0,  754.0,] # Measured ages
smpl.Age_sigma    .= [   3.0,    7.0,    5.0,    5.0,] # Measured 1-σ uncertainties
smpl.Height       .= [ -355,  -380,-397.0,-411.5,] # Depths below surface should be negative
smpl.Height_sigma .= fill(0.01, nSamples) # Usually assume little or no sample height uncertainty
smpl.Age_Sidedness .= zeros(nSamples) # Sidedness (zeros by default: geochron constraints are two-sided). Use -1 for a maximum age and +1 for a minimum age, 0 for two-sided
smpl.Age_Unit = "Years BP" # Unit of measurement for ages
smpl.Height_Unit = "m" # Unit of measurement for Height and Height_sigma

# Configure the stratigraphic Monte Carlo model
config = NewStratAgeModelConfiguration()
config.resolution = 5 # Same units as sample height. Smaller is slower!
config.bounding = 0.5 # how far away do we place runaway bounds, as a fraction of total section height. Larger is slower.
(bottom, top) = extrema(smpl.Height)
npoints_approx = round(Int,length(bottom:config.resolution:top) * (1 + 2*config.bounding))
config.nsteps = 100000 # Number of steps to run in distribution MCMC
config.burnin = 100000*npoints_approx # Number to discard
config.sieve = round(Int,npoints_approx) # Record one out of every nsieve steps

# Run the stratigraphic MCMC model
@time (mdl, agedist, lldist) = StratMetropolis(smpl, config)

# Test that results match expectation, within some tolerance
@test isa(mdl.Age, Array{Float64,1})
@test isapprox(mdl.Age, [751.74, 742.70, 733.65, 724.51, 720.14, 715.96, 711.79, 709.14, 706.57, 703.70, 701.36], atol=1)
@test isapprox(mdl.Age_025CI, [742.41, 723.83, 718.67, 715.69, 707.41, 703.72, 701.34, 698.16, 696.27, 694.94, 693.89], atol=1.5)
@test isapprox(mdl.Age_975CI, [761.04, 757.86, 752.64, 733.58, 731.23, 728.11, 722.24, 720.58, 718.62, 716.13, 712.46], atol=1.5)

# Data about hiatuses
nHiatuses = 2 # The number of hiatuses you have data for
hiatus = NewHiatusData(nHiatuses) # Struct to hold data
hiatus.Height         = [-371.5, -405.0 ]
hiatus.Height_sigma   = [   0.0,    0.0 ]
hiatus.Duration       = [  10.0,   12.3 ]
hiatus.Duration_sigma = [   3.1,    2.0 ]

# Run the model. Note the additional `hiatus` arguments
@time (mdl, agedist, hiatusdist, lldist) = StratMetropolis(smpl, hiatus, config); sleep(0.5)

# Test that results match expectation, within some tolerance
@test isa(mdl.Age, Array{Float64,1})
@test isapprox(mdl.Age, [752.68, 736.03, 729.99, 724.31, 720.83, 717.47, 714.02, 711.93, 704.12, 701.93, 700.07], atol=1)
@test isapprox(mdl.Age_025CI, [743.44, 722.35, 718.26, 715.86, 709.78, 706.72, 704.57, 701.67, 695.11, 694.09, 693.27], atol=1.5)
@test isapprox(mdl.Age_975CI, [761.87, 748.6, 743.75, 732.9, 730.92, 728.26, 723.55, 722.31, 714.94, 712.17, 709.13], atol=1.5)


text:
using FastMarching
using Test
using LinearAlgebra

@testset "Test FastMarching" begin
    function testI(n::Integer, endpoint=[1.0, 1.0], stepsize=0.1, T=Float64)
        speedmap = zeros(T, (n, n)) + I .* T(1000) .+ T(0.1)
        source = T.([float(size(speedmap, 1)), float(size(speedmap, 2))])
        distancemap = FastMarching.msfm(speedmap, source, true, true)
        endpoint = T.([1.0, 1.0])
        stepsize = T(stepsize)
        return shortestline = FastMarching.shortestpath(
            distancemap, endpoint, source, stepsize
        )
    end

    endpoint = [1.0, 1.0]
    @testset "testeye" begin
        @testset "size: $t stepsize: $stepsize" for t in 2:2:10,
stepsize in [0.1, 0.01],
T in [Float16, Float32, Float64]

            shortestline = testI(t, endpoint, stepsize, T)
            @test sum(shortestline[:, 2] - shortestline[:, 1]) == 0
            @test sqrt((shortestline[1, 1] - 1.0)^2 - (shortestline[1, 2] - 1.0)^2) <=
                  stepsize
            @test eltype(shortestline) == T
        end
    end

    @testset "correctness" begin
        for N in [2, 5, 10]
            speedimage = ones(N, N)
            sourcepoint = [float(N); float(N)]
            distancemap = FastMarching.msfm(speedimage, sourcepoint, true, true)
            @test distancemap[1, end] ≈ (N - 1)
            @test distancemap[end, 1] ≈ (N - 1)
            @test distancemap[end] ≈ 0
            @test isapprox(distancemap[1], sqrt(2 * (N - 1)^2); atol=0.2)
        end
    end

    include(joinpath(@__DIR__, "multiplestarts.jl"))
end


text:
"""
	dspike(s1::Array{T,1}, s2::Array{T,1}, q) where T <: AbstractFloat

Victor-Purpura metric based on spike location. (Could optimize memory
usage -- only need two rows at a given time.)
"""
function dspike(s1::Array{T,1}, s2::Array{T,1}, q) where T <: AbstractFloat
	l1 = length(s1)
	l2 = length(s2)
	G = zeros(l1,l2)
	G[1,1:l2] .= collect(0:l2-1)
	G[1:l1,1] .= collect(0:l1-1)
	for i ∈ 2:l1
		for j ∈ 2:l2
			G[i,j] = min(G[i-1,j]+1, G[i,j-1]+1, G[i-1,j-1]+q*abs(s1[i]-s2[j]))
		end
	end
	G[l1,l2]
end

"""
	dinterval(s1::Array{T,1}, s2::Array{T,1}, q) where T <: AbstractFloat

Victor-Purpura metric based on spike interval
"""
function dinterval(s1::Array{T,1}, s2::Array{T,1}, q) where T <: AbstractFloat
	sort!(s1); sort!(s2)
	t0 = min(minimum(s1), minimum(s2)) - 0.001
	t1 = max(maximum(s1), maximum(s2)) + 0.001
	intervals1 = zeros(length(s1)+1)
	intervals2 = zeros(length(s2)+1)
	for i ∈ 2:length(s1)
		intervals1[i] = s1[i] - s1[i-1]
	end
	for i ∈ 2:length(s2)
		intervals2[i] = s2[i] - s2[i-1]
	end
	intervals1[1], intervals2[1] = s1[1]-t0, s2[1]-t0
	intervals1[end], intervals2[end] = t1-s1[end], t1-s2[end]
	l1 = length(intervals1)
	l2 = length(intervals2)
	G = zeros(l1,l2)
	G[1,1:l2] .= collect(0:l2-1)
	G[1:l1,1] .= collect(0:l1-1)
	for i ∈ 2:l1
		for j ∈ 2:l2
			G[i,j] = min(G[i-1,j]+1,
						 G[i,j-1]+1,
						 G[i-1,j-1]+q*abs(intervals1[i]-intervals2[j]) )
		end
	end
	G[l1,l2]
end

"""
	Family distances
"""

max_stars_repo_name: analogouscircuit/DelayNetTools

max_issues_repo_name: analogouscircuit/DelayNetTools

max_forks_repo_name: analogouscircuit/DelayNetTools


text:
## indices
import ..ParallelStencil: INDICES, WITHIN_DOC
const ix = INDICES[1];
const ixi = :($ix+1);
## 2nd-order accuracy for first-order derivatives
ix_1=:($ix+1);
macro   d_1(A::Symbol)  esc(:($A[$ix_1+1]-$A[$ix_1])) end
## 8th-order accuracy for first-order derivatives
ix_8=:($ix+3);

macro   d_8(A::Symbol)
    esc(:(1225/1024*($A[$ix_8+1]-$A[$ix_8])-
    245/3072*($A[$ix_8+2]-$A[$ix_8-1])+
    49/5120*($A[$ix_8+3]-$A[$ix_8-2])-
    5/7186*($A[$ix_8+4]-$A[$ix_8-3]) ));
end
## 12th-order accuracy for first-order derivatives
ix_12=:($ix+5);

macro   d_12(A::Symbol)
    esc(:(160083/131072*($A[$ix_12+1]-$A[$ix_12])-
    12705/131072*($A[$ix_12+2]-$A[$ix_12-1])+
    22869/1310720*($A[$ix_12+3]-$A[$ix_12-2])-
    5445/1835008*($A[$ix_12+4]-$A[$ix_12-3])+
    847/2359296*($A[$ix_12+5]-$A[$ix_12-4])-
    63/2883584*($A[$ix_12+6]-$A[$ix_12-5]) ));
end


text:
function seat_id(line)
    arr::Array{Int} = [x in ('B', 'R') ? 1 : 0 for x in line]
    return sum([x * 2^(n - 1) for (n, x) in enumerate(arr[end:-1:1])])
end

function run(s)
    # Your code here
    return maximum(seat_id(line) for line in split(s, '\n'))
end

#########################################

function main()
    res, time, memory = @timed run(ARGS[1])
    println("_duration:$(time * 1000)")
    println(res)
end

main()


text:
# -*- coding: utf-8 -*-
# ---
# jupyter:
#   jupytext:
#     formats: ipynb,jl:light
#     text_representation:
#       extension: .jl
#       format_name: light
#       format_version: '1.4'
#       jupytext_version: 1.2.4
#   kernelspec:
#     display_name: Julia 1.3.1
#     language: julia
#     name: julia-1.3
# ---

# # Prepare data set for clustering project
#
# Code below does the bulk of a workflow that may look something like:
#
# - read variable + metadata
# - interpolate to chosen grid
# - add column to dataframe
# - save dataframe to csv
# - save metadata to md
#
# _Side note: use PARF_

# + {"slideshow": {"slide_type": "slide"}}
using MeshArrays
γ=GridSpec("LatLonCap","GRID_LLC90/")
Γ=GridLoad(γ)

lon=[i for i=-179.5:1.0:179.5, j=-89.5:1.0:89.5]
lat=[j for i=-179.5:1.0:179.5, j=-89.5:1.0:89.5]
(f,i,j,w,_,_,_)=InterpolationFactors(Γ,vec(lon),vec(lat))
λ=Dict("f" => f,"i" => i,"j" => j,"w" => w);

# + {"slideshow": {"slide_type": "slide"}}
using MITgcmTools

fileName="nctiles_climatology/THETA/THETA"
THETA=read_nctiles(fileName,"THETA",γ)
show(THETA)

# + {"slideshow": {"slide_type": "slide"}}
n=length(lon[:])
tmp=vec(fill(NaN,(n*12,1)))
for m=1:12
    k=collect(1:n) .+(m-1)*n
    tmp[k] .= Interpolate(THETA[:,1,m],λ["f"],λ["i"],λ["j"],λ["w"])
end

all=Dict("SST" => tmp)

# + {"slideshow": {"slide_type": "slide"}}
using Plots
SST1=reshape(all["SST"][1:n,1],size(lon))
SST7=reshape(all["SST"][(1:n) .+ n*7,1],size(lon))
heatmap([transpose(SST1) transpose(SST7)])
# -

max_stars_repo_name: gaelforget/MarineEcosystemNotebooks

max_forks_repo_name: gaelforget/MarineEcosystemNotebooks


text:
using Distributions

const m_arr = [3, 5, 6, 6, 5, 3]
const μ_dist = Uniform(0, 1)
const ϕ_dist = Uniform(0, π)

"""
    Quadrupolar

A structure for holding information about the quadrupolar parameters of the NMR
spectra

# Fields
- `qcc::Array{Distribution}`: an array of distributions of the quantum coupling
constant
- `η::Array{Distribution}`: an array of distributions of the asymmetry parameter
- `weights::Array{Float64}`: an array of relative weights of the above
distributions
"""
struct Quadrupolar
    qcc::Array{Distribution}
    η::Array{Distribution}
    weights::Array{Float64}
end

"""
    Quadrupolar(p)

A constructor for the nmr_parameters given an array of floating point numbers.
Order is qcc, σqcc, η, ση, weight, and repeat for each site.

# Examples
```julia-repl
julia> Quadrupolar([5.5, 0.1, 0.12, 0.03, 1.0])
Quadrupolar(Distributions.Distribution[Truncated(Distributions.Normal{Float64}
(μ=5.5, σ=0.1), range=(0.0, Inf))],Distributions.Distribution[Truncated(
Distributions.Normal{Float64}(μ=0.12, σ=0.03), range=(0.0, 1.0))], [1.0])
```
"""
function Quadrupolar(p::Array{Float64})
    sites = length(p) ÷ 5 + 1
    qcc = Array{Distribution}(undef, sites)
    η = Array{Distribution}(undef, sites)
    weights = zeros(sites)

    weights_sum = sum(map(i -> i % 5 == 0 ? p[i] : 0.0, 1:length(p)))
    weights_sum > 1.0 && return missing
    for i in 1:length(p)
        p[i] < 0 && return missing
        (isnan(p[i]) || isinf(p[i])) && return missing
        (isnothing(p[i]) || ismissing(p[i])) && return missing
    end
    for i = 1:sites
        qcc[i] = truncated(Normal(p[5*(i-1)+1], p[5*(i-1)+2]), 0.0, Inf)
        η[i] = truncated(Normal(p[5*(i-1)+3], p[5*(i-1)+4]), 0.0, 1.0)
        weights[i] = i != sites ? p[5*i] : 1 - weights_sum
    end

    return Quadrupolar(qcc, η, weights)
end

"""
    get_ν(qcc, η, μ, λ, m, I, ν0)

Compute the value of ν with the third order perturbation described in

>Jellison Jr, G. E., Feller, S. A., & Bray, P. J. (1977). NMR powder patterns
>for integer spin nuclei in the presence of asymmetric quadrupole effects.
>Journal of Magnetic Resonance (1969), 27(1), 121-132.

# Arguments
- `qcc::Float64`: the quantum coupling constant
- `η::Float64`: the asymmetry parameter (between 0 and 1 inclusive)
- `μ::Float64`: cos(θ), where θ is the spherical coordinate angle
- `λ::Float64`: cos(2ϕ), where ϕ is the spherical coordinate angle
- `m::Int64`: the quantum number m, which can be integers from -I to I - 1
- `I::Int64`: spin (3 in the case of Boron-10)
- `ν0::Float64`: the Larmor frequency

# Examples
```julia-repl
julia> get_ν(5.5, 0.12, 0.1, 0.2, -1, 3, 32.239)
31.8515444235865
```
"""
function get_ν(
    qcc::Float64,
    η::Float64,
    μ::Float64,
    λ::Float64,
    m::Int64,
    I::Int64,
    ν0::Float64,
)
    νQ = 3 * qcc / (2 * I * (2 * I - 1))
    β = νQ / ν0
    a = -(3 * μ^2 - 1 + η * λ - η * λ * μ^2)
    c = (0.5 * ((I + 3 / 2) * (I - 1 / 2) - 3 * (m - 1 / 2)^2)) *
        (μ^4 * (3 - η * λ)^2 + 2 * μ^2 * (-9 + 2 * η^2 - η^2 * λ^2) +
         (3 + η * λ)^2) +
        (4 * ((I + 3 / 2) * (I - 1 / 2) - 6 * (m - 1 / 2)^2)) *
        (μ^4 * (3 - η * λ)^2 + μ^2 * (-9 + η^2 + 6 * η * λ - 2 * η^2 * λ^2) +
         (-(η^2) + η^2 * λ^2))
    e = (12 * I * (I + 1) - 40 * m * (m - 1) - 27) * (μ^6 * (3 - η * λ)^3 +
         μ^4 * (-36 + 3 * η^2 + 42 * η * λ - η^3 * λ - 19 * η^2 * λ^2 +
          3 * η^3 * λ^3) +
         μ^2 * (9 - 4 * η^2 - 15 * η * λ + 2 * η^3 * λ + 11 * η^2 * λ^2 -
          3 * η^3 * λ^3) +
         (η^2 - η^3 * λ - η^2 * λ^2 + η^3 * λ^3)) +
        (1 / 2 * (3 * I * (I + 1) - 5 * m * (m - 1) - 6)) *
        (μ^6 * (3 - η * λ)^3 +
         μ^4 * (-63 + 12 * η^2 + 33 * η * λ - 4 * η^3 * λ - 13 * η^2 * λ^2 +
          3 * η^3 * λ^3) +
         μ^2 *
         (45 - 4 * η^2 - 9 * η * λ + 4 * η^3 * λ - η^2 * λ^2 - 3 * η^3 * λ^3) +
         (-9 + 3 * η * λ + 5 * η^2 * λ^2 + η^3 * λ^3)) +
        (8 * I * (I + 1) - 20 * m * (m - 1) - 15) * (μ^6 * (3 - η * λ)^3 +
         μ^4 * (-54 + 9 * η^2 + 36 * η * λ - 3 * η^3 * λ - 15 * η^2 * λ^2 +
          3 * η^3 * λ^3) +
         μ^2 * (27 - 6 * η^2 - 9 * η * λ + 4 * η^3 * λ + 3 * η^2 * λ^2 -
          3 * η^3 * λ^3) +
         (-3 * η^2 - η^3 * λ + 3 * η^2 * λ^2 + η^3 * λ^3))
    return ν0 + (νQ / 2) * (m - 1 / 2) * a + (νQ * β / 72) * c +
           (νQ * β^2 / 144) * e * (m - 1 / 2)
end

"""
    estimate_powder_pattern(p, N, ν0, I)

Compute N frequencies, whose distribution forms what is referred to as the
powder pattern, for one or more given distributions (found in p) for the quantum
coupling constant (qcc) and asymmetry parameter (η), and constant Larmor
frequency (ν0) and spin (I).

# Examples
```julia-repl
julia> estimate_powder_pattern(Quadrupolar([5.5, 0.1, 0.12, 0.03, 1.0]), 1000, 32.239, 3)
1000-element Array{Float64,1}:
 32.18456766333233
 32.2091872593358
 32.32362143777174
 32.33050236817988
 31.950161601754655
 32.338682082979666
  ⋮
 32.42199530095508
 32.26831269193921
 32.12305522098913
 32.04062886358494
 32.15411486178574
```
"""
function estimate_powder_pattern(
    p::Quadrupolar,
    N::Int64,
    ν0::Float64,
    I::Int64;
    transitions::UnitRange{Int64} = 1:(2*I),
)
    sites = rand(Categorical(p.weights), N)
    powder_pattern = get_ν.(
        rand.(map(i -> p.qcc[i], sites)),
        rand.(map(i -> p.η[i], sites)),
        rand(μ_dist, N),
        cos.(2 .* rand(ϕ_dist, N)),
        rand(Categorical(m_arr[transitions] ./
            sum(m_arr[transitions])), N) .- (length(transitions) ÷ 2),
        I,
        ν0,
    )
    return powder_pattern
end

function get_quadrupolar_starting_values(sites::Int64)
    starting_values = zeros(5 * sites - 1)
    starting_values[1:5:end] = rand(Uniform(0, 3), sites)  # √Qcc
    starting_values[2:5:end] = rand(Uniform(0, 1), sites)  # √σQcc
    starting_values[3:5:end] = rand(Uniform(0, 1), sites)  # √η
    starting_values[4:5:end] = rand(Uniform(0, 1), sites)  # √ση
    if sites > 1
        starting_values[5:5:end] = rand(Uniform(0, 1 / sites), sites - 1)
    end
    return starting_values
end


text:
using TomoForward
# using XfromProjections

include("../src/iterative/util_convexopt.jl")
include("../src/iterative/ctv_primaldual.jl")
using LinearAlgebra

# img = imread("test_data/shepplogan512.png")[:,:,1]
# H, W = 128, 128
# img = imresize(img, H, W)

img1 = zeros(128, 128)
img1[40:60, 40:60] .= 1.0
H, W = size(img1)

img2 = zeros(H, W)
img2[40:60, 40:60] .= 2.0

src_origin = 876.25
det_origin = 352.2525

nangles = 128
angles = deg2rad.(LinRange(0, 360, nangles+1))[1:nangles]

detcount = Int(floor(size(img1,1)*1.4))
proj_geom = ProjGeomFan(0.8, detcount, angles, src_origin, det_origin)

# test line projection model
A = fp_op_fan_line(proj_geom, size(img1, 1), size(img1, 2))
p1_ = A * vec(img1)
p1 = reshape(p1_, nangles, detcount)

p2_ = A * vec(img2)
p2 = reshape(p2_, nangles, detcount)

nchannels = 2
u = zeros(H, W, nchannels)
p = cat(p1, p2, dims=3)

niter=500
w_tnv=1.0

res = recon2d_ctv_primaldual!(u, A, p, niter, 1.0001, "tnv", 1e-6, 1, 0.5)
u = res[1]
res_primals = res[3]
res_duals = res[4]
residuals = res[3] + res[4]

using Plots
plot(res_primals, yaxis=:log)
# plot(res_primals)
plot!(res_duals)
plot!(residuals)
# using PyPlot
# plot(Gray.(u[:,:,1]))

# u0 = zeros(size(img))
# niter=500
# lambdas = [0.01, 0.1, 0.6]
# u = zeros(H, W, 5)

max_stars_repo_name: QPImaging/xfromProjections

max_issues_repo_name: QPImaging/xfromProjections

max_forks_repo_name: QPImaging/xfromProjections


text:
search_range = [(-10.0,10.0), (0.0,2.0), (25.0,40.0)]
n_samples = 6
plan = SurrogateModelOptim.scaled_LHC_sampling_plan(search_range,n_samples,1000;trace=:silent)

@testset "scaled LHC plan" begin
    @test vec(extrema(plan,dims=2)) == search_range
end

@testset "function eval" begin
    @test size(SurrogateModelOptim.f_opt_eval(minimum,plan)) == (1,n_samples)
    samples = mapslices(minimum,plan,dims=1)
    @test size(SurrogateModelOptim.f_opt_eval(minimum,plan,samples)) == (1,n_samples)
end


text:
@testset "LP Based Functions (Takes time...)" begin
    @testset "Zero Sum Games" begin
        @testset "Game" begin

            tol = 0.00001

            mat = [
                -2 6 3
                3 -4 7
                -1 2 4
            ]

            dm = makeDecisionMatrix(mat)
            result = game(dm)

            @test isa(result, GameResult)

            @test result.value == 0.6666666666666661

            @test isapprox(
                result.row_player_probabilities,
                [0.4666667, 0.5333333, 0.0000000],
                atol = tol,
            )

        end

        @testset "Game - Rock & Paper & Scissors" begin

            tol = 0.00001

            mat = [
                0 -1 1
                1 0 -1
                -1 1 0
            ]

            dm = makeDecisionMatrix(mat)
            result = game(dm)

            @test isa(result, GameResult)

            @test result.value == 0.0

            @test isapprox(
                result.row_player_probabilities,
                [0.333333, 0.333333, 0.33333],
                atol = tol,
            )

        end

    end # end of zero sum games

    @testset "Data Envelopment" begin

        tol = 0.00001

        x1 = [96.0, 84, 90, 81, 102, 83, 108, 99, 95]
        x2 = [300.0, 282, 273, 270, 309, 285, 294, 288, 306]

        out = [166.0, 150, 140, 136, 171, 144, 172, 170, 165]
        inp = hcat(x1, x2)

        result::DataEnvelopResult = dataenvelop(inp, out)

        @test isa(result, DataEnvelopResult)

        @test result.orderedcases ==
              [:Case8, :Case2, :Case7, :Case1, :Case9, :Case6, :Case5, :Case4, :Case3]

        @test isapprox(
            result.efficiencies,
            [
                0.9879815986198964,
                0.9999999999999999,
                0.8959653733189055,
                0.9421686746987951,
                0.9659435120753173,
                0.9715662650602411,
                0.9911164465786314,
                1.0,
                0.9841048789857857,
            ],
            atol = tol,
        )

        @test isapprox(
            result.references[:, :Case1],
            [0.0, 0.544106, 0.0, 0.0, 0.0, 0.0, 0.0, 0.496377, 0.0],
            atol = tol,
        )

        @test isapprox(
            result.references[:, :Case2],
            [0.0, 1, 0, 0, 0, 0, 0, 0, 0],
            atol = tol,
        )

        @test isapprox(
            result.references[:, :Case3],
            [0.0, 0.266193, 0, 0, 0, 0, 0, 0.588654, 0],
            atol = tol,
        )

        @test isapprox(
            result.references[:, :Case4],
            [0.0, 0.860241, 0, 0, 0, 0, 0, 0.0409639, 0],
            atol = tol,
        )

        @test isapprox(
            result.references[:, :Case5],
            [0.0, 0.314982, 0, 0, 0, 0, 0, 0.727957, 0],
            atol = tol,
        )

        @test isapprox(
            result.references[:, :Case6],
            [0.0, 0.96, 0, 0, 0, 0, 0, 0, 0],
            atol = tol,
        )

        @test isapprox(
            result.references[:, :Case7],
            [0.0, 0, 0, 0, 0, 0, 0, 1.01176, 0],
            atol = tol,
        )

        @test isapprox(
            result.references[:, :Case8],
            [0.0, 0, 0, 0, 0, 0, 0, 1.0, 0],
            atol = tol,
        )

        @test isapprox(
            result.references[:, :Case9],
            [0.0, 0.774923, 0, 0, 0, 0, 0, 0.286833, 0],
            atol = tol,
        )

    end
end

max_stars_repo_name: drvinceknight/JMcDM

max_issues_repo_name: drvinceknight/JMcDM

max_forks_repo_name: drvinceknight/JMcDM


text:
module CoordinateTransformations

using StaticArrays
using LinearAlgebra

# Core methods
export compose, ∘, transform_deriv, transform_deriv_params, recenter
export Transformation, IdentityTransformation

# 2D coordinate systems and their transformations
export Polar
export PolarFromCartesian, CartesianFromPolar

# 3D coordinate systems and their transformations
export Spherical, Cylindrical
export SphericalFromCartesian, CartesianFromSpherical,
       CylindricalFromCartesian, CartesianFromCylindrical,
       CylindricalFromSpherical, SphericalFromCylindrical

# Common transformations
export AbstractAffineMap
export AffineMap, LinearMap, Translation
export PerspectiveMap, cameramap

include("core.jl")
include("coordinatesystems.jl")
include("affine.jl")
include("perspective.jl")

end # module


text:
for N in [Float64, Rational{Int}, Float32]
    # ==============================
    # Testing box approximation
    # ==============================
    # Box approximation of a 2D square
    b = BallInf(N[1, 1], N(0.1))
    h = box_approximation(b)
    hexp = Hyperrectangle(N[1, 1], N[0.1, 0.1])
    @test h.center ≈ hexp.center
    @test h.radius ≈ hexp.radius

    # Box approximation of a 2D unit ball in the 1-norm
    b = Ball1(N[1, -2], N(0.2))
    h = box_approximation(b)
    hexp = Hyperrectangle(N[1, -2], N[0.2, 0.2])
    @test h.center ≈ hexp.center
    @test h.radius ≈ hexp.radius

    # Box approximation of a 3D unit ball in the 1-norm
    b = Ball1(N[1, 2, 0], N(1))
    h = box_approximation(b)
    hexp = Hyperrectangle(N[1, 2, 0], N[1, 1, 1])
    @test h.center ≈ hexp.center
    @test h.radius ≈ hexp.radius

    # Box approximation of a Hyperrectangle
    hexp = Hyperrectangle(N[0, 0], N[1, 1])
    h = box_approximation(hexp)
    @test h.center ≈ hexp.center
    @test h.radius ≈ hexp.radius

    # empty set
    E = EmptySet{N}()
    @test box_approximation(E) == E

    # rectification
    @test box_approximation(Rectification(EmptySet{N}())) isa EmptySet{N}
    r = Rectification(Ball1(N[0, 0], N(1)))
    @test box_approximation(r) == Hyperrectangle(low=N[0, 0], high=N[1, 1])

    # ===================================================================
    # Testing box_approximation_symmetric (= symmetric interval hull)
    # ===================================================================
    # Box approximation of a 2D square
    b = BallInf(N[1, 1], to_N(N, 0.1))
    h = box_approximation_symmetric(b)
    hexp = Hyperrectangle(N[0, 0], to_N(N, [1.1, 1.1]))
    @test h.center ≈ hexp.center
    @test h.radius ≈ hexp.radius

    # Box approximation of a 2D unit ball in the 1-norm
    b = Ball1(N[1, -2], to_N(N, 0.2))
    h = box_approximation_symmetric(b)
    hexp = Hyperrectangle(N[0, 0], to_N(N, [1.2, 2.2]))
    @test h.center ≈ hexp.center
    @test h.radius ≈ hexp.radius

    # Box approximation of a 3D unit ball in the 1-norm
    b = Ball1(N[1, 2, 0], to_N(N, 0.1))
    h = box_approximation_symmetric(b)
    hexp = Hyperrectangle(N[0, 0, 0], to_N(N, [1.1, 2.1, 0.1]))
    @test h.center ≈ hexp.center
    @test h.radius ≈ hexp.radius

    # Box approximation of a 4D hyperrectangle
    b = Hyperrectangle(to_N(N, [-1.5, -2.5, 2.4, -0.4]),
                       to_N(N, [0.1, 0.2, 0.3, 0.4]))
    h = box_approximation_symmetric(b)
    hexp = Hyperrectangle(zeros(N, 4), to_N(N, [1.6, 2.7, 2.7, 0.8]))
    @test h.center ≈ hexp.center
    @test h.radius ≈ hexp.radius

    # Testing alias symmetric_interval_hull
    h = symmetric_interval_hull(b)

    # empty set
    E = EmptySet{N}()
    @test box_approximation_symmetric(E) == E
end


text:
using Memento

logger = get_logger("bot-logger")
set_level(logger, "debug")

struct Game
    id::String
    botname::String
    initial_game_map::GameMap
    width::Int
    height::Int

    function Game(botname::String)
        id = get_msg()
        setup_logger(botname, id)
        botname = @sprintf("%s-%s", botname, id)

        width, height = map(x -> parse(Int, x), split(get_msg()))

        initial_game_map = GameMap(id, width, height, get_msg())

        new(id, botname, initial_game_map, width, height)
    end
end
GameMap(game::Game, map_string::String) = GameMap(game.id, game.width, game.height, map_string)

"""
    start_game(game)

This function should be used after bot initialization and all preliminary checks and warmsup.
"""
function start_game(game::Game)
    send_msg(game.botname, true)
end

"""
    update_map(game::Game)

Parse the map given by the engine.
"""
function update_map(game::Game)
    GameMap(game, get_msg())
end

"""
    setup_logger(name, id)

Set up and truncate the log. Log name is "{name}-{id}.log".
"""
function setup_logger(name, id)
    add_handler(logger, DefaultHandler(open(@sprintf("%s-%s.log", name, id), "w"), DefaultFormatter("[{date} | {level} | {name}]: {msg}")))
    remove_handler(logger, "console")
end

"""
    get_msg()

Read input from the game.
"""
get_msg() = readline(STDIN)

"""
    send_msg(s, done=false)

Send data to the game. Call `done_msg` once finished or specify `done`=true.
"""
function send_msg(s::String, done::Bool=false)
    if done
        write(STDOUT, s*"\n")
    else
        write(STDOUT, s)
    end
    flush(STDOUT)
end

"""
    done_msg()

Finish sending commands to the game.
"""
done_msg() = send_msg("\n")

"""
    send_command_queue(command_queue::Vector{String})

Issue the given list of commands.
"""
function send_command_queue(command_queue::Vector{String})
    for command in command_queue
        write(STDOUT, command)
    end
    done_msg()
end

max_stars_repo_name: xinnosuke/Halite-II

max_issues_repo_name: xinnosuke/Halite-II

max_forks_repo_name: xinnosuke/Halite-II


text:
export experiments, experiment, sampledata, samplemap, metadata
import DataStructures
import DataFrames
import SummarizedExperiments

"""
    experiments(x)

Return an ordered dictionary containing all experiments in the `MultiAssayExperiment` `x`.

# Examples
```jldoctest
julia> using MultiAssayExperiments

julia> x = exampleobject();

julia> collect(keys(experiments(x)))
2-element Vector{String}:
 "foo"
 "bar"
```
"""
function experiments(x::MultiAssayExperiment)
    return x.experiments
end

"""
    experiment(x[, i]; sampledata = false)

Extract the specified `SummarizedExperiment` from a `MultiAssayExperiment` `x`.
`i` may be a positive integer no greater than the number of experiments in `x`,
or a string specifying the name of the desired experiment.
If `i` is not specified, it defaults to the first experiment in `x`.

If `sampledata = true`, we attempt to add the sample data of `x` to the `coldata` of the returned `SummarizedExperiment`.
This is done by subsetting `sampledata(x)` based on sample mapping to the columns of the returned `SummarizedExperiment` - see [`expandsampledata`](@ref) for more details.
If there are columns in the `sampledata(x)` and the `coldata` of the `SummarizedExperiment` with the same name but different values,
the former are omitted with a warning.

Note that, if `sampledata = true`, the returned `SummarizedExperiment` will be a copy of the relevant experiment in `x`.
If `false`, the returned object will be a reference.

# Examples
```jldoctest
julia> using MultiAssayExperiments;

julia> x = exampleobject();

julia> experiment(x)
100x10 SummarizedExperiments.SummarizedExperiment
  assays(3): foo bar whee
  rownames: Gene1 Gene2 ... Gene99 Gene100
  rowdata(2): name Type
  colnames: foo1 foo2 ... foo9 foo10
  coldata(3): name Treatment Response
  metadata(1): version

julia> experiment(x, 1); # same result

julia> experiment(x, "foo");

julia> experiment(x, "foo", sampledata = true) # add sample data
100x10 SummarizedExperiments.SummarizedExperiment
  assays(3): foo bar whee
  rownames: Gene1 Gene2 ... Gene99 Gene100
  rowdata(2): name Type
  colnames: foo1 foo2 ... foo9 foo10
  coldata(4): name Treatment Response disease
  metadata(1): version
```
"""
function experiment(x::MultiAssayExperiment; sampledata = false)
    return experiment(x, 1; sampledata = sampledata)
end

function safely_add_columns!(host, other, experiment)
    for n in names(other)
        if (n == "name")
            continue # skipping the name.
        end

        src = other[!,n]

        if n in names(host)
            if src != host[!,n]
                @warn "omitting sample data column '" * n * "' with conflict in column data of experiment '" * experiment * "'"
            end
            continue
        end

        host[!,n] = src
    end
end

function experiment(x::MultiAssayExperiment, i::Int; sampledata = false)
    counter = 1
    for (key, val) in experiments(x)
        if (i == counter)
            if !sampledata
                return val
            else
                sd = expandsampledata(x, key)
                val2 = copy(val)
                cd = copy(SummarizedExperiments.coldata(val2))
                safely_add_columns!(cd, sd, key)
                SummarizedExperiments.setcoldata!(val2, cd)
                return val2
            end
        end
        counter += 1
    end
    throw(BoundsError("experiment " * string(i) * " is out of range (" * length(experiments(x)) * " experiments available)"))
end

function experiment(x::MultiAssayExperiment, i::String; sampledata = false)
    val = x.experiments[i]
    if !sampledata
        return val
    else
        sd = expandsampledata(x, i)
        val2 = copy(val)
        cd = copy(SummarizedExperiments.coldata(val2))
        safely_add_columns!(cd, sd, i)
        SummarizedExperiments.setcoldata!(val2, cd)
        return val2
    end
end

"""
    sampledata(x, check = true)

Return a `DataFrame` containing the sample data in the `MultiAssayExperiment` `x`.

The returned object should contain `name` as the first column, containing a vector of unique strings.
If `check = true`, the function will check the validity of the sample data before returning it.

# Examples
```jldoctest
julia> using MultiAssayExperiments

julia> x = exampleobject();

julia> names(sampledata(x))
2-element Vector{String}:
 "name"
 "disease"
```
"""
function sampledata(x::MultiAssayExperiment, check::Bool = true)
    output = x.sampledata
    if check
        check_sampledata(output)
    end
    return output
end

"""
    samplemap(x)

Return an ordered dictionary containing the sample mapping from the `MultiAssayExperiment` `x`.

The returned object should contain the `sample`, `experiment` and `colname` columns in that order.
Each column should contain a vector of strings, and rows should be unique.
If `check = true`, the function will check the validity of the sample data before returning it.

# Examples
```jldoctest
julia> using MultiAssayExperiments

julia> x = exampleobject();

julia> names(samplemap(x))
3-element Vector{String}:
 "sample"
 "experiment"
 "colname"
```
"""
function samplemap(x::MultiAssayExperiment, check::Bool = true)
    output = x.samplemap
    if check
        check_samplemap(output)
    end
    return output
end

"""
    metadata(x)

Return a dictionary containing the metadata from the `MultiAssayExperiment` `x`.

# Examples
```jldoctest
julia> using MultiAssayExperiments

julia> x = exampleobject();

julia> collect(keys(metadata(x)))
1-element Vector{String}:
 "version"
```
"""
function metadata(x::MultiAssayExperiment)
    return x.metadata
end


text:
if basename(pwd()) == "aoc"
    cd("2017/24")
end
include("../../helpers/inherit.jl")

struct Magnet
    charges::Vector{Int}
end
@delegate_base Magnet charges first, firstindex, getindex, last, lastindex, length, setindex!

Magnet(str::AbstractString) = Magnet(parse.(Int, split(str, '/')))
loadmagnets(filename::AbstractString) = Magnet.(eachline(filename))

isattracted(left::Int, right::Magnet) = left == first(right) || left == last(right)
isattracted(left::Magnet, right::Magnet) = isattracted(last(left), right)
isattracted(left) = Base.Fix1(isattracted, left)

strength(magnet::Magnet) = 2 * sum(magnet.charges) - first(magnet) - last(magnet)
strength(magnets) = sum(strength.(magnets))

function maxchain(magnets, chain = Magnet(0))
    indices = findall(isattracted(chain), magnets)
    if !isempty(indices)
        append!(chain,
            first(sort!(
                [
                    begin

                        ms = copy(magnets)
                        c = copy(chain)
                        splice!(ms, i)
                        push!(c, magnets[i])
                        maxchain(ms, c)
                    end
                    for i in indices
                ],
                by = strength
            ))
        )
    end
    chain
end

part1(filename::AbstractString) = part1(loadmagnets(filename))
part1(magnets) = maximum(strength, maxchain(magnets))

# @assert part1("example.txt") == 31

max_stars_repo_name: stellartux/advent-of-code

max_issues_repo_name: stellartux/advent-of-code

max_forks_repo_name: stellartux/advent-of-code


text:
lazy(f; kw...) = delayed(f; kw...)

# If any input is lazy, make the output lazy
maybe_lazy(f, x) = any(x->x isa Union{Thunk, Chunk}, x) ? lazy(f)(x...) : f(x...)

maybe_lazy(f) = (x...) -> maybe_lazy(f, x)

function mapcompute(ctx, xs;
                    cache=false,
                    collect_results=identity,
                    map=map, kw...)
    thunks = []
    map(xs) do x
        if x isa Thunk
            if cache
                x.cache = true
            end
            push!(thunks, x)
        end
        x
    end

    vals = collect_results(compute(ctx, delayed((xs...)->[xs...]; meta=true)(thunks...); kw...))

    i = 0
    map(xs) do x
        # Expression returns vals[i] or x
        if x isa Thunk
            i += 1
            vals[i]
        else
            x
        end
    end
end

function mapexec(ctx, xs; cache=false, map=map)
    mapcompute(ctx, xs;
               map=map,
               cache=cache,
               collect_results=xs -> asyncmap(d -> exec(ctx, d), xs))
end

"""
    compute(tree::FileTree; cache=true)

Compute any lazy values (Thunks) in `tree` and return a new tree where the values refer to
the computed values (maybe on remote processes). The tree still behaves as a Lazy tree. `exec` on it will fetch the values from remote processes.
"""
compute(d::FileTree; cache=true, kw...) = compute(Dagger.Context(), d; cache=cache, kw...)

function compute(ctx, d::FileTree; cache=true, kw...)
    mapcompute(ctx, d, map=((f,t) -> mapvalues(f, t; lazy=false)), cache=cache; kw...)
end

"""
    exec(x)

If `x` is a FileTree, computes any uncomputed `Thunk`s stored as values in it. Returns a new tree with the computed values.
If `x` is a `Thunk` (such as the result of a `reducevalues`), then exec will compute the result.
If `x` is anything else, `exec` just returns the same value.
"""
exec(x) = exec(Dagger.Context(), x)

"""
    exec(ctx, x)

Same as `exec(x)` with a ctx being passed to `Dagger` when computing any `Thunks`.
"""
exec(ctx, x) = x

exec(ctx, d::FileTree) = mapexec(ctx, d, map=(f,t) -> mapvalues(f, t; lazy=false))

exec(ctx, d::Union{Thunk, Chunk}) = collect(ctx, compute(ctx, d))


text:
## Maximum entropy degree distribution of a network with S species and L links

function p_k(k::Int64, S::Int64, L::Int64)
    # k: degree of a species
    # S: number of species in the food web
    # L: number of links in the food web

    # return probability of degree k from MaxEnt distribution
    # p_k = c * r^k

    # constraint of mean
    mean_degree = (2 * L) / S

    # maximum entropy distribution
    c = 1 / (mean_degree - 1)
    r = (mean_degree - 1) / mean_degree

    return c * r ^ k
end

function maxent_dd(S::Int64, L::Int64)
    # S: number of species
    # L: number of links

    # return degree distribution with maximum entropy
    # i.e. probability for each k between 1 and S
    degree_dist = zeros(S)
    for k in 1:S
        degree_dist[k] = p_k(k, S, L)
    end

    return degree_dist
end

max_stars_repo_name: FrancisBanville/Trophic-METE

max_issues_repo_name: FrancisBanville/Trophic-METE

max_forks_repo_name: FrancisBanville/Trophic-METE


text:
# Example for extended source modeling with Flux
# Author: Philipp Witte, pwitte3@gatech.edu
# Date: April 2020
#

using JUDI, SegyIO, JOLI, Flux, JUDI4Flux

# Set up model structure
n = (120, 100)   # (x,y,z) or (x,z)
d = (10., 10.)
o = (0., 0.)

# Velocity [km/s]
v = ones(Float32,n) .+ 0.4f0
v[:, Int(round(end/2)):end] .= 4f0

# Slowness squared [s^2/km^2]
m = (1f0 ./ v).^2

# Setup info and model structure
nsrc = 1	# number of sources
model = Model(n, d, o, m)

# Set up receiver geometry
nxrec = 120
xrec = range(50f0, stop=1150f0, length=nxrec)
yrec = 0f0
zrec = range(50f0, stop=50f0, length=nxrec)

# receiver sampling and recording time
time = 1000f0   # receiver recording time [ms]
dt = 1f0    # receiver sampling interval [ms]

# Set up receiver structure
recGeometry = Geometry(xrec, yrec, zrec; dt=dt, t=time, nsrc=nsrc)

# setup wavelet
f0 = 0.01f0     # MHz
wavelet = ricker_wavelet(time, dt, f0)

# Set up info structure for linear operators
ntComp = get_computational_nt(recGeometry, model)
info = Info(prod(n), nsrc, ntComp)

# return linearized data as Julia array
opt = Options(return_array=true, dt_comp=dt)

# Linear operators
Pr = judiProjection(info, recGeometry)
A_inv = judiModeling(info, model; options=opt)
Pw = judiLRWF(info, wavelet)
F = Pr*A_inv*adjoint(Pw)

# Extended source weight
w = randn(Float32, model.n)

#####################################################################################
# Extended source forward

# Build CNN
G = ExtendedQForward(F)

w = reshape(w, n[1], n[2], 1, 1)
m = reshape(m, n[1], n[2], 1, 1)
y = randn(Float32, recGeometry.nt[1], nxrec, 1, 1)

loss(w, m, y) = Flux.mse(G(w, m), y)

p =  params(w, m, y)
gs = gradient(() -> loss(w, m, y), p)

#####################################################################################
# Extended source adjoint

G = ExtendedQAdjoint(F)

w = reshape(w, n[1], n[2], 1, 1)
m = reshape(m, n[1], n[2], 1, 1)
y = randn(Float32, recGeometry.nt[1], nxrec, 1, 1)

loss(y, m, w) = Flux.mse(G(y, m), w)

p =  params(y, m, w)
gs = gradient(() -> loss(y, m, w), p)


text:
# Autogenerated wrapper script for HepMC3_jll for x86_64-apple-darwin
export libHepMC3, libHepMC3search

JLLWrappers.@generate_wrapper_header("HepMC3")
JLLWrappers.@declare_library_product(libHepMC3, "@rpath/libHepMC3.3.dylib")
JLLWrappers.@declare_library_product(libHepMC3search, "@rpath/libHepMC3search.4.dylib")
function __init__()
    JLLWrappers.@generate_init_header()
    JLLWrappers.@init_library_product(
        libHepMC3,
        "lib/libHepMC3.3.dylib",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@init_library_product(
        libHepMC3search,
        "lib/libHepMC3search.4.dylib",
        RTLD_LAZY | RTLD_DEEPBIND,
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()


text:
"""
    compute_mu_merit

Compute the penalty parameter of merit function

# Arguments
- `df`: evaluation of the objective gradient
- `p`: search direction
- `rho`: parameter in (0,1)
- `norm_E`: norm of constraint violations
- `lambda`: Lagrangian multiplier
"""
function compute_mu_merit(
    df::Tv, p::Tv, rho::Float64, norm_E::T, lambda::Tv
) where {T, Tv<:AbstractArray{T}}
    mu = norm(lambda, Inf) + 1.e-4
    if norm_E > 1.e-10
        return max((df' * p) / ((1 - rho) * norm_E), mu)
    end
    return mu
end

"""
    compute_derivative

Compute and return directional derivative

# Arguments
- `df`: evaluation of the objective gradient
- `p`: search direction
- `mu`: penalty parameter
- `norm_E`: norm of constraint violations
"""
compute_derivative(df::Tv, p::Tv, mu::T, norm_E::T) where {T, Tv<:AbstractArray{T}} = df' * p - mu * norm_E

max_issues_repo_name: exanauts/ActiveSetMethods


text:
function ShapiroInterSatelliteRangeModifier(arg0::jdouble)
    return ShapiroInterSatelliteRangeModifier((jdouble,), arg0)
end

function get_parameters_drivers(obj::ShapiroInterSatelliteRangeModifier)
    return jcall(obj, "getParametersDrivers", List, ())
end

function modify(obj::ShapiroInterSatelliteRangeModifier, arg0::EstimatedMeasurement)
    return jcall(obj, "modify", void, (EstimatedMeasurement,), arg0)
end


text:
using ReinforcementLearningZoo
using Test
using ReinforcementLearningBase
using ReinforcementLearningCore
using ReinforcementLearningEnvironments
using Flux
using Statistics
using Random
using OpenSpiel

@testset "ReinforcementLearningZoo.jl" begin

    @testset "training" begin
        mktempdir() do dir
            for method in (:BasicDQN, :DQN, :PrioritizedDQN, :Rainbow, :IQN, :VPG)
                res = run(Experiment(
                    Val(:JuliaRL),
                    Val(method),
                    Val(:CartPole),
                    nothing;
                    save_dir = joinpath(dir, "CartPole", string(method)),
                ))
                @info "stats for $method" avg_reward = mean(res.hook[1].rewards) avg_fps =
                    1 / mean(res.hook[2].times)
            end

            for method in (:BasicDQN, :DQN)
                res = run(Experiment(
                    Val(:JuliaRL),
                    Val(method),
                    Val(:MountainCar),
                    nothing;
                    save_dir = joinpath(dir, "MountainCar", string(method)),
                ))
                @info "stats for $method" avg_reward = mean(res.hook[1].rewards) avg_fps =
                    1 / mean(res.hook[2].times)
            end

            for method in (:A2C, :A2CGAE, :PPO)
                res = run(Experiment(
                    Val(:JuliaRL),
                    Val(method),
                    Val(:CartPole),
                    nothing;
                    save_dir = joinpath(dir, "CartPole", string(method)),
                ))
                @info "stats for $method" avg_reward =
                    mean(Iterators.flatten(res.hook[1].rewards))
            end

            for method in (:DDPG, :SAC, :TD3)
                res = run(Experiment(
                    Val(:JuliaRL),
                    Val(method),
                    Val(:Pendulum),
                    nothing;
                    save_dir = joinpath(dir, "Pendulum", string(method)),
                ))
                @info "stats for $method" avg_reward =
                    mean(Iterators.flatten(res.hook[1].rewards))
            end
        end
    end

    @testset "run pretrained models" begin
        for x in ("JuliaRL_BasicDQN_CartPole",)
            e = Experiment(x)
            e.agent.policy = load_policy(x)
            Flux.testmode!(e.agent)
            run(e.agent, e.env, StopAfterEpisode(1), e.hook)
            @info "result of evaluating pretrained model: $x for once:" reward =
                e.hook[1].rewards[end]
        end
    end

    @testset "minimax" begin
        e = E`JuliaRL_Minimax_OpenSpiel(tic_tac_toe)`
        run(e)
        @test e.hook[1].rewards[end] == e.hook[2].rewards[end] == 0.0
    end

    @testset "TabularCFR" begin
        e = E`JuliaRL_TabularCFR_OpenSpiel(kuhn_poker)`
        run(e)
        @test isapprox(mean(e.hook[2].rewards), -1 / 18; atol = 0.01)
        @test isapprox(mean(e.hook[3].rewards), 1 / 18; atol = 0.01)

        reset!(e.env)
        expected_values = Dict(expected_policy_values(e.agent, e.env))
        @test isapprox(expected_values[get_role(e.agent[2])], -1 / 18; atol = 0.01)
        @test isapprox(expected_values[get_role(e.agent[3])], 1 / 18; atol = 0.01)
    end
end