text:
"""

The exported names are
$(EXPORTS)
"""
module FESpaces

using DocStringExtensions
using Test
using FillArrays
using BlockArrays
using SparseArrays
using LinearAlgebra

using Gridap.Helpers
using Gridap.Algebra
using Gridap.Arrays
using Gridap.Fields
using Gridap.ReferenceFEs
using Gridap.Geometry
using Gridap.CellData
using Gridap.TensorValues

using Gridap.Arrays: BlockArrayCooMap

import Gridap.Fields: gradient
import Gridap.Fields: ∇∇
import Gridap.Arrays: array_cache
import Gridap.Arrays: getindex!
import Gridap.Arrays: return_cache
import Gridap.Arrays: evaluate!
import Gridap.Geometry: get_triangulation
import Gridap.Geometry: get_cell_shapefuns
import Gridap.CellData: attach_constraints_rows
import Gridap.CellData: attach_constraints_cols
import Gridap.CellData: CellField
import Gridap.CellData: get_data
import Gridap.CellData: DomainStyle
import Gridap.CellData: change_domain_skeleton

import Gridap.Algebra: allocate_residual
import Gridap.Algebra: allocate_jacobian
import Gridap.Algebra: residual!
import Gridap.Algebra: jacobian!
import Gridap.Algebra: residual
import Gridap.Algebra: jacobian
import Gridap.Algebra: hessian
import Gridap.Algebra: residual_and_jacobian!
import Gridap.Algebra: residual_and_jacobian
import Gridap.Algebra: zero_initial_guess
import Gridap.Algebra: get_matrix
import Gridap.Algebra: get_vector
import Gridap.Algebra: solve!
import Gridap.Algebra: solve
import Gridap.Algebra: allocate_vector
import Gridap.Algebra: allocate_matrix
import Gridap.Algebra: allocate_matrix_and_vector

export FEFunction
export get_free_dof_values
export get_cell_dof_values
export get_fe_space
export test_fe_function

export FESpace
export ConstraintStyle
export Constrained
export UnConstrained
export num_free_dofs
export get_free_dof_ids
export zero_free_values
export EvaluationFunction
export get_cell_dof_ids
export get_cell_shapefuns
export get_cell_shapefuns_trial
export has_constraints
export get_cell_constraints
export get_cell_isconstrained
export get_cell_is_dirichlet
export get_dof_value_type
export test_fe_space

export SingleFieldFESpace
export SingleFieldFEFunction
export get_cell_dof_basis
export num_dirichlet_dofs
export get_dirichlet_dof_ids
export zero_dirichlet_values
export num_dirichlet_tags
export get_dirichlet_dof_tag
export scatter_free_and_dirichlet_values
export gather_free_and_dirichlet_values!
export gather_dirichlet_values
export gather_dirichlet_values!
export gather_free_values
export gather_free_values!
export test_single_field_fe_space
export get_dirichlet_values
export interpolate
export interpolate!
export interpolate_everywhere
export interpolate_everywhere!
export interpolate_dirichlet
export interpolate_dirichlet!
export compute_dirichlet_values_for_tags
export compute_dirichlet_values_for_tags!

export UnconstrainedFESpace
export CellConformity
export CellFE
export compute_conforming_cell_dofs
export compute_cell_space

export TestFESpace
export TrialFESpace
export TrialFESpace!
export HomogeneousTrialFESpace
export HomogeneousTrialFESpace!

export FEBasis
export BasisStyle

export Assembler
export AssemblyStrategy
export row_map
export col_map
export row_mask
export col_mask
export DefaultAssemblyStrategy
export get_test
export get_trial
export assemble_matrix!
export assemble_matrix_add!
export assemble_matrix
export assemble_vector!
export assemble_vector_add!
export assemble_vector
export assemble_matrix_and_vector!
export assemble_matrix_and_vector_add!
export assemble_matrix_and_vector
export allocate_vector
export allocate_matrix
export allocate_matrix_and_vector
export test_assembler
export collect_cell_matrix
export collect_cell_vector
export collect_cell_matrix_and_vector
export get_matrix_type
export get_vector_type
export SparseMatrixAssembler
export GenericSparseMatrixAssembler
export symbolic_loop_matrix!
export symbolic_loop_vector!
export symbolic_loop_matrix_and_vector!
export numeric_loop_matrix!
export numeric_loop_vector!
export numeric_loop_matrix_and_vector!
export test_sparse_matrix_assembler

export FEOperator
export AffineFEOperator
export test_fe_operator
export get_algebraic_operator

export FESolver
export test_fe_solver
export LinearFESolver
export NonlinearFESolver

export FESpaceWithConstantFixed
export ZeroMeanFESpace
export CLagrangianFESpace
export DirichletFESpace
export FESpaceWithLinearConstraints

export FiniteElements

include("FESpaceInterface.jl")

include("SingleFieldFESpaces.jl")

include("UnconstrainedFESpaces.jl")

include("ConformingFESpaces.jl")

include("FESpaceFactories.jl")

include("PhysicalFEs.jl")

include("TrialFESpaces.jl")

include("Assemblers.jl")

include("SparseMatrixAssemblers.jl")

include("FEOperators.jl")

include("AffineFEOperators.jl")

include("FEOperatorsFromWeakForm.jl")

include("FESolvers.jl")

include("FEAutodiff.jl")

include("DiscontinuousFESpaces.jl")

include("FESpacesWithConstantFixed.jl")

include("ZeroMeanFESpaces.jl")

include("CLagrangianFESpaces.jl")

include("DirichletFESpaces.jl")

include("ExtendedFESpaces.jl")

include("FESpacesWithLinearConstraints.jl")

end # module


text:
################################################################################
#  Copyright 2020, Marta Vanin, Tom Van Acker                                  #
################################################################################
# PowerModelsDistributionStateEstimation.jl                                    #
# An extention package of PowerModels(Distribution).jl for Static Power System #
# State Estimation.                                                            #
################################################################################

## Error calculation
function convert_lifted_to_polar!(sol::Dict, name)
    if name == "w"
        for (_,bus) in sol["bus"]
            bus["vm"] = sqrt.(bus[name])
        end
    elseif name == "Wr"
        for (_,bus) in sol["bus"]
            bus["vm"] = [sqrt(bus[name][c,c]) for c in 1:size(bus[name])[1]]
        end
    end
end

convert_rectangular_to_polar!(sol::Dict) =
    for (_,bus) in sol["bus"]
        bus["vm"] = sqrt.(bus["vi"].^2+bus["vr"].^2)
    end
"""
    calculate_voltage_magnitude_error(se_sol::Dict, pf_sol::Dict)

Function to determine the difference, maximum difference and mean difference
between the voltage magnitude on the busses between a power flow `pf_sol` and a
state estimation `se_sol`.
"""
function calculate_voltage_magnitude_error(se_result::Dict, pf_result::Dict)
    # check whether both se and pf have been solved
    (haskey(se_result, "solution") && haskey(pf_result, "solution")) || return false
    pf_sol, se_sol = pf_result["solution"], se_result["solution"]

    # convert the voltage magnitude variable to polar space
    if haskey(pf_sol["bus"]["1"], "Wr") convert_lifted_to_polar!(pf_sol, "Wr") end
    if haskey(se_sol["bus"]["1"], "Wr") convert_lifted_to_polar!(se_sol, "Wr") end
    if haskey(pf_sol["bus"]["1"], "vr") convert_rectangular_to_polar!(pf_sol) end
    if haskey(se_sol["bus"]["1"], "vr") convert_rectangular_to_polar!(se_sol) end
    if haskey(pf_sol["bus"]["1"], "w") convert_lifted_to_polar!(pf_sol, "w") end
    if haskey(se_sol["bus"]["1"], "w") convert_lifted_to_polar!(se_sol, "w") end

    # determine the difference between the se and pf
    delta = Float64[]
    for (b,bus) in pf_sol["bus"] for cond in 1:length(bus["vm"])
        push!(delta, abs(bus["vm"][cond]-se_sol["bus"][b]["vm"][cond]))
    end end

    return delta, maximum(delta), _STT.mean(delta)
end
"""
    calculate_voltage_magnitude_error_perphase(se_sol::Dict, pf_sol::Dict)
Like _PMDSE.calculate_voltage_magnitude_error(se_sol::Dict, pf_sol::Dict) but the errors
are per phase instead of the average values over the three pahses.
"""
function calculate_voltage_magnitude_error_perphase(se_result::Dict, pf_result::Dict)

    (haskey(se_result, "solution") && haskey(pf_result, "solution")) || return false
    pf_sol, se_sol = pf_result["solution"], se_result["solution"]

    # convert the voltage magnitude variable to polar space
    if haskey(pf_sol["bus"]["1"], "Wr") _PMDSE.convert_lifted_to_polar!(pf_sol, "Wr") end
    if haskey(se_sol["bus"]["1"], "Wr") _PMDSE.convert_lifted_to_polar!(se_sol, "Wr") end
    if haskey(pf_sol["bus"]["1"], "vr") _PMDSE.convert_rectangular_to_polar!(pf_sol) end
    if haskey(se_sol["bus"]["1"], "vr") _PMDSE.convert_rectangular_to_polar!(se_sol) end
    if haskey(pf_sol["bus"]["1"], "w")  _PMDSE.convert_lifted_to_polar!(pf_sol, "w") end
    if haskey(se_sol["bus"]["1"], "w")  _PMDSE.convert_lifted_to_polar!(se_sol, "w") end

    # determine the difference between the se and pf
    delta_1 = []
    delta_2 = []
    delta_3 = []
    for (b,bus) in pf_sol["bus"] for cond in 1:length(bus["vm"])
        if cond == 1
            push!(delta_1, abs(bus["vm"][cond]-se_sol["bus"][b]["vm"][cond]))
        elseif cond == 2
            push!(delta_2, abs(bus["vm"][cond]-se_sol["bus"][b]["vm"][cond]))
        else
            push!(delta_3, abs(bus["vm"][cond]-se_sol["bus"][b]["vm"][cond]))
        end
    end end

    return delta_1, delta_2, delta_3, maximum(delta_1), maximum(delta_2), maximum(delta_3), _STT.mean(delta_1), _STT.mean(delta_2), _STT.mean(delta_3)
end

ext: jl


text:
JSON.lower(g::Granularity) = non_nothing_dict(g)

"""
    SimpleGranularity(name::String)

One of the simple predefined granularities of Druid.
"""
struct SimpleGranularity <: Granularity
    name::String
    function SimpleGranularity(name)
        name = lowercase(name)
        name ∈ [
            "all", "none", "second", "minute", "fifteen_minute", "thirty_minute",
            "hour", "day", "week", "month", "quarter", "year"
        ] || error("Unknown type of simple granularity")
        new(name)
    end
end

JSON.lower(sg::SimpleGranularity) = sg.name

"""
    DurationGranularity(duration::UInt64; origin=nothing)

Duration type granularity where the duration is specified as milliseconds since
origin.

Specifying origin is not required (defaults to Druid's default), but should be a
ISO8601 datetime string if you do specify it.
"""
struct DurationGranularity <: Granularity
    type::String
    duration::UInt64
    origin
    function DurationGranularity(duration; origin=nothing)
        nothing_or_type(origin, String)
        new("duration", duration, origin)
    end
end

"""
    PeriodGranularity(period::String; origin=nothing, timezone=nothing)

Period type granularity where the period is specified as an ISO8601 period
string. Period starts on origin in the timezone.

Specifying origin and timezone is not required (defaults to Druid's default).
But if you do specify them, origin should be a ISO8601 datetime string and
timezone should be one of those [supported by
Druid](https://druid.apache.org/docs/latest/querying/granularities.html#supported-time-zones).
"""
struct PeriodGranularity <: Granularity
    type::String
    period::String
    origin
    timeZone
    function PeriodGranularity(period; origin=nothing, timezone=nothing)
        nothing_or_type(origin, String)
        nothing_or_type(timezone, String)
        new("period", period, origin, timezone)
    end
end


text:
function heapsort!(a::Vector, isless=(x,y)->isless(y,x))
    heap = BinaryHeap(a, isless)
    for i = 1:length(heap)
        remove!(heap)
    end
    heap.tree.data
end


text:
using CSV, DataFrames, DataFramesMeta
using LinearAlgebra
using Parameters

## Loading Data

function load_data(file)

    # Reading data
    data=CSV.read(file, DataFrame)
    # Getting prices from data
    p = @linq data |>
         where(:year.<2009) |>
         select(:oilpricereal2009)
    p=p./100 # Transforming price to price per 100 barrels

    #Transforming data into long form to get Quantities
    ld=stack(data, Between(:algeria, :uk))
    #Getting market shares
    @transform!(ld,q=:value ./ :totalworld)
    # Transforming data into wide form keeping quantities and time variables
    df=unstack(ld, [:year,:month], :variable, :q, allowduplicates=true)

    # Keeping only full years
    q = @linq df |>
            where(:year.<2009)

    # Dropping time variables
    q = q[:,Between(:algeria, :uk)]

    return Array(p), Array(q)
    println("Data is ready.")
end

function load_data_select(file;select=[:saudiarabia, :unitedstates, :iran, :china, :mexico, :venezuela])

    # Reading data
    data=CSV.read(file, DataFrame)

    # # Transforming data to wide form to get Prices
    # p=unstack(data[data.year.<2009,:], :year, :month, :oilpricereal2009)
    # # Price array p: 36 years x 12 months
    # p=Array(p[:,Not(:year)]./100)

    p = @linq data |>
         where(:year.<2009) |>
         select(:oilpricereal2009)
    p=p./100 #
    #Transforming data into long form to get Quantities
    ld=stack(data, Between(:algeria, :uk))
    #Getting market shares
    @transform!(ld,q=:value ./ :totalworld)
    #Transforming data into wide form to get market shares only
    # df=unstack(ld, [:year,:variable], :month, :q, allowduplicates=true)
    df=unstack(ld, [:year,:month], :variable, :q, allowduplicates=true)
    # Quantities array, q: 12 months x 19 countries x 36 years
    # q=reshape(Array(ld[ld.year.<2009,:q]),M,N,T)

    q = @linq df |>
            where(:year.<2009)

    q = q[:,select]

    println("Data is ready.")
    return Array(p), Array(q)
end

## Defining centering moment condition

function gM(p, W)
    T, N = size(W)

    g=[p⋅W[:,i] for i=1:N]

    return g
end

## mystars
function mystars(x)
    if x < 0.001
        y = "***"
    elseif x < 0.05
        y = "**"
    elseif x < 0.10
        y =  "*"
    else
        y = ""
    end
end

max_stars_repo_name: hans-mtz/SCR

max_issues_repo_name: hans-mtz/SCR

max_forks_repo_name: hans-mtz/SCR


text:
using Test, Documenter, Simulation73
#DocMeta.setdocmeta!(Simulation73, :DocTestSetup, :(using Simulation73); recursive=true)
#doctest(Simulation73)

# Too unreliable between julia versions
#include("src/test_sanity.jl")

n_points_dx1 = 1001
extent_dx1 = 300.0
dx = extent_dx1 / n_points_dx1
mid_point = floor(Int, n_points_dx1 / 2) + (n_points_dx1 % 2)
circle_dx1 = PeriodicLattice{Float64,1}(; n_points=(n_points_dx1,), extent=(extent_dx1,))
line_dx1 = CompactLattice{Float64,1}(; n_points=(n_points_dx1,), extent=(extent_dx1,))
empty_circle_dx1 = zeros(size(circle_dx1)...)
empty_line_dx1 = zeros(size(line_dx1)...)

@testset "Stimulus" begin
    @testset "Non-stimulus" begin
        nostim = NoStimulusParameter{Float64}()
        nostim_action = nostim(circle_dx1)
        empty_circle_nostim_test = copy(empty_circle_dx1)
        nostim_action(empty_circle_nostim_test)
        @test all(empty_circle_nostim_test .== empty_circle_dx1)
    end
end
@testset "Populations" begin
    @testset "Initializing" begin
        single_pop = copy(empty_line_dx1)
        two_pops = population_repeat(single_pop, 2)
        derived_single_pop = population(two_pops, 1)
        @test all(size(derived_single_pop) .== size(single_pop))
    end
    @testset "Non-stimuli" begin
        nostim1 = NoStimulusParameter{Float64}()
        nostim2 = NoStimulusParameter{Float64}()
        nostim_pops = PopulationActionsParameters(nostim1, nostim2)
        nostim_actions = nostim_pops(line_dx1)
        single_pop = copy(empty_line_dx1)
        two_pops = population_repeat(single_pop, 2)
        @test nostim_actions(two_pops, two_pops, 1.0) != 0
    end
    @testset "Meta-parameters" begin
        nostim1 = NoStimulusParameter{Float64}()
        nostim2 = NoStimulusParameter{Float64}()
        nostim_pops = PopulationActionsParameters(nostim1, nostim2)
        nullstim_pops = NullifyParameter(nostim_pops)
        nullstim_actions = nullstim_pops(line_dx1)
        single_pop = copy(empty_line_dx1)
        two_pops = population_repeat(single_pop, 2)
        @test nullstim_actions(two_pops, two_pops, 0.0) != 0
    end
    # TODO: need population interactions tests
    struct CrossMultiply{T} <: AbstractInteraction{T}
        mul::T
    end
    CrossMultiply(; mul) = CrossMultiply(mul)
    (c::CrossMultiply)(inplace, source, t) = inplace .+= source .* c.mul
    @testset "Interactions" begin
        mult1 = CrossMultiply(5.0)
        mult_input = ones(10)
        mult_output = ones(10) .* 2
        mult1(mult_output, mult_input, 0.0)
        @assert all(mult_output .== (2.0 .+ 5.0 .* mult_input))
        @assert all(mult_input .== ones(10))

        pop_inputs = ones(10, 2)
        pop_inputs[:,2] .= 31.0
        pop_outputs = zeros(10, 2)
        pop_outputs[:,2] .= 2.0
        pop_mult = pops(CrossMultiply; mul=[2.0 -7.0; 5.0 -17.0])

        theoretical_result = zeros(10,2)
        theoretical_result[:,1] .= (2.0) - (7.0 * 31.0)
        theoretical_result[:,2] .= 2.0 + (5.0) - (17.0 * 31.0)

        pop_mult(pop_outputs, pop_inputs, 0.0)
        same_input = ones(10,2)
        same_input[:,2] .= 31.0
        @test all(same_input .== pop_inputs)

        @show pop_outputs
        @show theoretical_result
        @test all(pop_outputs .== theoretical_result)
    end

end


text:
using SignalBase
using SignalBase.Units
using Unitful
using Test

@testset "SignalBase.jl" begin
    @test inframes(1s,44.1kHz) == 44100
    @test inframes(Int,0.5s,44.1kHz) == 22050
    @test inframes(Int,5frames) == 5
    @test inframes(Int,5) == 5
    @test inframes(5) == 5
    @test inframes(1.0s,44.1kHz) isa Float64
    @test ismissing(inframes(missing))
    @test ismissing(inframes(Int,missing))
    @test ismissing(inframes(Int,missing,5))
    @test ismissing(inframes(missing,5))
    @test ismissing(inframes(10s))

    @test inHz(10) === 10
    @test inHz(10Hz) === 10
    @test inHz(Float64,10Hz) === 10.0
    @test inHz(Int,10.5Hz) === 10
    @test ismissing(inHz(missing))

    @test inseconds(50ms) == 1//20
    @test inseconds(50ms,10Hz) == 1//20
    @test inseconds(10frames,10Hz) == 1
    @test inseconds(1s,44.1kHz) == 1
    @test inseconds(1,44.1kHz) == 1
    @test inseconds(1) == 1
    @test ismissing(inseconds(missing))

    @test inradians(15) == 15
    @test_throws Unitful.DimensionError inradians(15frames)
    @test inradians(180°) ≈ π
    @test ismissing(inseconds(2frames))
end


text:
# Rolling dice game in Julia

function rolling_dice()

    # Number of sides for dice
    num_sides_dice = 6

    # While the user wants to roll a dice, continue to generate a number between 1 and the number of sides
    while true
        print("Do you want to roll a dice? (1=Yes/0=No): ")
        guess = parse(Int64, readline())
        # Convert the string value input to a number

        if guess == 1
            println("Rolling dice")
            current_side = rand(1:num_sides_dice)
            println("Dice has number $current_side")
        elseif guess == 0
            println("Exiting")
            break # Stop the while loop if the user decides to do so
        else
            println("Invalid input, please try again")
        end
    end

end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

struct VirtualMachineExtensionsApi <: SwaggerApi
    client::Swagger.Client
end

"""

The operation to create or update the extension.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: vmExtensionName::String (required)
Param: extensionParameters::VirtualMachineExtension (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: VirtualMachineExtension
"""
function virtualMachineExtensionsCreateOrUpdate(_api::VirtualMachineExtensionsApi, resourceGroupName::String, vmName::String, vmExtensionName::String, extensionParameters, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PUT", VirtualMachineExtension, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}", ["azure_auth"], extensionParameters)
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "vmExtensionName", vmExtensionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

The operation to delete the extension.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: vmExtensionName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Return: OperationStatusResponse
"""
function virtualMachineExtensionsDelete(_api::VirtualMachineExtensionsApi, resourceGroupName::String, vmName::String, vmExtensionName::String, api_version::String, subscriptionId::String; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "DELETE", OperationStatusResponse, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "vmExtensionName", vmExtensionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

"""

The operation to get the extension.
Param: resourceGroupName::String (required)
Param: vmName::String (required)
Param: vmExtensionName::String (required)
Param: api_version::String (required)
Param: subscriptionId::String (required)
Param: expand::String
Return: VirtualMachineExtension
"""
function virtualMachineExtensionsGet(_api::VirtualMachineExtensionsApi, resourceGroupName::String, vmName::String, vmExtensionName::String, api_version::String, subscriptionId::String; expand=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", VirtualMachineExtension, "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/extensions/{vmExtensionName}", ["azure_auth"])
    Swagger.set_param(_ctx.path, "resourceGroupName", resourceGroupName)  # type String
    Swagger.set_param(_ctx.path, "vmName", vmName)  # type String
    Swagger.set_param(_ctx.path, "vmExtensionName", vmExtensionName)  # type String
    Swagger.set_param(_ctx.path, "subscriptionId", subscriptionId)  # type String
    Swagger.set_param(_ctx.query, "\$expand", expand)  # type String
    Swagger.set_param(_ctx.query, "api-version", api_version)  # type String
    Swagger.set_header_accept(_ctx, ["application/json"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json"] : [_mediaType])
    Swagger.exec(_ctx)
end

export virtualMachineExtensionsCreateOrUpdate, virtualMachineExtensionsDelete, virtualMachineExtensionsGet


text:
# This file was generated, do not modify it. # hide
x = exp(im*π) + 1

max_stars_repo_name: mcognetta/franklindocs

max_issues_repo_name: mcognetta/franklindocs

max_forks_repo_name: mcognetta/franklindocs


text:
const new_package_title_regex = r"^New package: (\w*?) v(\S*?)$"

const new_version_title_regex = r"^New version: (\w*?) v(\S*?)$"

const commit_regex = r"(?:^|\n|\r\n)(?:\-|\*) Commit: (\w*?)(?:$|\n|\r\n)"

function is_new_package(pull_request::GitHub.PullRequest)
    return occursin(new_package_title_regex, title(pull_request))
end

function is_new_version(pull_request::GitHub.PullRequest)
    return occursin(new_version_title_regex, title(pull_request))
end

function check_authorization(
    pkg,
    pr_author_login,
    authorized_authors,
    authorized_authors_special_jll_exceptions,
    error_exit_if_automerge_not_applicable,
)
    if pr_author_login ∉ vcat(authorized_authors, authorized_authors_special_jll_exceptions)
        throw_not_automerge_applicable(
            AutoMergeAuthorNotAuthorized,
            "Author $(pr_author_login) is not authorized to automerge. Exiting...";
            error_exit_if_automerge_not_applicable=error_exit_if_automerge_not_applicable,
        )
        return :not_authorized
    end

    # A JLL-only author (e.g. `jlbuild`) is not allowed to register
    # non-JLL packages.
    this_is_jll_package = is_jll_name(pkg)
    if (!this_is_jll_package && pr_author_login ∉ authorized_authors)
        throw_not_automerge_applicable(
            AutoMergeAuthorNotAuthorized,
            "This package is not a JLL package. Author $(pr_author_login) is not authorized to register non-JLL packages. Exiting...";
            error_exit_if_automerge_not_applicable=error_exit_if_automerge_not_applicable,
        )
        return :not_authorized
    end

    if pr_author_login ∈ authorized_authors_special_jll_exceptions
        return :jll
    end

    return :normal
end

function parse_pull_request_title(::NewVersion, pull_request::GitHub.PullRequest)
    m = match(new_version_title_regex, title(pull_request))
    pkg = convert(String, m.captures[1])::String
    version = VersionNumber(m.captures[2])
    return pkg, version
end

function commit_from_pull_request_body(pull_request::GitHub.PullRequest)
    pr_body = body(pull_request)
    m = match(commit_regex, pr_body)
    return convert(String, m.captures[1])::String
end

function parse_pull_request_title(::NewPackage, pull_request::GitHub.PullRequest)
    m = match(new_package_title_regex, title(pull_request))
    pkg = convert(String, m.captures[1])::String
    version = VersionNumber(m.captures[2])
    return pkg, version
end

function pull_request_build(
    api::GitHub.GitHubAPI,
    pr_number::Integer,
    current_pr_head_commit_sha::String,
    registry::GitHub.Repo,
    registry_head::String;
    whoami::String,
    auth::GitHub.Authorization,
    authorized_authors::Vector{String},
    authorized_authors_special_jll_exceptions::Vector{String},
    error_exit_if_automerge_not_applicable=error_exit_if_automerge_not_applicable,
    master_branch::String,
    master_branch_is_default_branch::Bool,
    suggest_onepointzero::Bool,
    registry_deps::Vector{<:AbstractString}=String[],
    check_license::Bool,
    public_registries::Vector{<:AbstractString}=String[],
    read_only::Bool,
)::Nothing
    pr = my_retry(() -> GitHub.pull_request(api, registry, pr_number; auth=auth))
    _github_api_pr_head_commit_sha = pull_request_head_sha(pr)
    if current_pr_head_commit_sha != _github_api_pr_head_commit_sha
        throw(
            AutoMergeShaMismatch(
                "Current commit sha (\"$(current_pr_head_commit_sha)\") does not match what the GitHub API tells us (\"$(_github_api_pr_head_commit_sha)\")",
            ),
        )
    end

    # 1. Check if the PR is open, if not quit.
    # 2. Determine if it is a new package or new version of an
    #    existing package, if neither quit.
    # 3. Check if the author is authorized, if not quit.
    # 4. Call the appropriate method for new package or new version.
    if !is_open(pr)
        throw_not_automerge_applicable(
            AutoMergePullRequestNotOpen,
            "The pull request is not open. Exiting...";
            error_exit_if_automerge_not_applicable=error_exit_if_automerge_not_applicable,
        )
        return nothing
    end

    if is_new_package(pr)
        registration_type = NewPackage()
    elseif is_new_version(pr)
        registration_type = NewVersion()
    else
        throw_not_automerge_applicable(
            AutoMergeNeitherNewPackageNorNewVersion,
            "Neither a new package nor a new version. Exiting...";
            error_exit_if_automerge_not_applicable=error_exit_if_automerge_not_applicable,
        )
        return nothing
    end

    pkg, version = parse_pull_request_title(registration_type, pr)
    pr_author_login = author_login(pr)
    authorization = check_authorization(
        pkg,
        pr_author_login,
        authorized_authors,
        authorized_authors_special_jll_exceptions,
        error_exit_if_automerge_not_applicable,
    )

    if authorization == :not_authorized
        return nothing
    end

    registry_master = clone_repo(registry)
    if !master_branch_is_default_branch
        checkout_branch(registry_master, master_branch)
    end
    data = GitHubAutoMergeData(;
        api=api,
        registration_type=registration_type,
        pr=pr,
        pkg=pkg,
        version=version,
        current_pr_head_commit_sha=current_pr_head_commit_sha,
        registry=registry,
        auth=auth,
        authorization=authorization,
        registry_head=registry_head,
        registry_master=registry_master,
        suggest_onepointzero=suggest_onepointzero,
        whoami=whoami,
        registry_deps=registry_deps,
        public_registries=public_registries,
        read_only=read_only,
    )
    pull_request_build(data; check_license=check_license)
    rm(registry_master; force=true, recursive=true)
    return nothing
end

function pull_request_build(data::GitHubAutoMergeData; check_license)::Nothing
    kind = package_or_version(data.registration_type)
    this_is_jll_package = is_jll_name(data.pkg)
    @info(
        "This is a new $kind pull request",
        pkg = data.pkg,
        version = data.version,
        this_is_jll_package
    )

    update_status(
        data;
        state="pending",
        context="automerge/decision",
        description="New $kind. Pending.",
    )

    this_pr_can_use_special_jll_exceptions =
        this_is_jll_package && data.authorization == :jll

    guidelines = get_automerge_guidelines(
        data.registration_type;
        check_license=check_license,
        this_is_jll_package=this_is_jll_package,
        this_pr_can_use_special_jll_exceptions=this_pr_can_use_special_jll_exceptions,
    )
    checked_guidelines = Guideline[]

    for (guideline, applicable) in guidelines
        applicable || continue
        if guideline == :update_status
            if !all(passed, checked_guidelines)
                update_status(
                    data;
                    state="failure",
                    context="automerge/decision",
                    description="New version. Failed.",
                )
            end
        else
            check!(guideline, data)
            @info(
                guideline.info,
                meets_this_guideline = passed(guideline),
                message = message(guideline)
            )
            push!(checked_guidelines, guideline)
        end
    end

    if all(passed, checked_guidelines) # success
        description = "New $kind. Approved. name=\"$(data.pkg)\". sha=\"$(data.current_pr_head_commit_sha)\""
        update_status(
            data; state="success", context="automerge/decision", description=description
        )
        this_pr_comment_pass = comment_text_pass(
            data.registration_type,
            data.suggest_onepointzero,
            data.version,
            this_pr_can_use_special_jll_exceptions,
        )
        my_retry(() -> update_automerge_comment!(data, this_pr_comment_pass))
    else # failure
        update_status(
            data;
            state="failure",
            context="automerge/decision",
            description="New $kind. Failed.",
        )
        failing_messages = message.(filter(!passed, checked_guidelines))
        this_pr_comment_fail = comment_text_fail(
            data.registration_type,
            failing_messages,
            data.suggest_onepointzero,
            data.version,
        )
        my_retry(() -> update_automerge_comment!(data, this_pr_comment_fail))
        throw(AutoMergeGuidelinesNotMet("The automerge guidelines were not met."))
    end
    return nothing
end

package_or_version(::NewPackage) = "package"
package_or_version(::NewVersion) = "version"


text:
using Test
using GeoParams

@testset "DislocationCreepLaws" begin

# This tests the MaterialParameters structure
CharUnits_GEO   =   GEO_units(viscosity=1e19, length=1000km);

# Define a linear viscous creep law ---------------------------------
x1      =   DislocationCreep()
@test isbits(x1)
@test x1.n.val == 1.0
@test x1.A.val == 1.5MPa^-1*s^-1

x2      =   DislocationCreep(n=3)
@test x2.A.val == 1.5MPa^-3*s^-1

# perform a computation with the dislocation creep laws
    # Calculate EpsII, using a set of pre-defined values
CharDim = GEO_units()
EpsII  = GeoUnit(0s^-1)
        Nondimensionalize!(EpsII,CharDim)
TauII   = GeoUnit(100MPa)
        Nondimensionalize!(TauII,CharDim)
P       = GeoUnit(100MPa)
        Nondimensionalize!(P,CharDim)
T       = GeoUnit(500C)
        Nondimensionalize!(T,CharDim)
f       = GeoUnit(50MPa)
        Nondimensionalize!(f,CharDim)
p       = CreepLawVariables(P=P,T=T,f=f)
Phase   = SetMaterialParams(Name="Viscous Matrix", Phase=2,
                                     Density   = ConstantDensity(),
                                     CreepLaws = DislocationCreep(n=3NoUnits, r=1NoUnits), CharDim = CharDim)

EpsII.val = computeCreepLaw_EpsII(TauII,Phase.CreepLaws[1],p)
@test EpsII.val  ≈ 2.1263214994323903e-11 rtol = 1e-8

# Check that once inverted, we get back the TauII that we used to calculate EpsII
NewTau = computeCreepLaw_EpsII(EpsII,Phase.CreepLaws[1],p)
@test NewTau ≈ TauII.val

# Given stress
#@test computeCreepLaw_EpsII(1e6Pa, x1, CreepLawParams())==5e-13/s                # dimensional input

# Given strainrate
#@test computeCreepLaw_EpsII(1e-13/s, x1, CreepLawParams())==1e18*2*1e-13Pa       # dimensional input
# -------------------------------------------------------------------

end


text:
using Optim, HTTP, GLM, LinearAlgebra, Random, Statistics, DataFrames, DataFramesMeta, CSV, MultivariateStats
#Worked with Ahmed and Aleeze
include("lgwt.jl")
function ps8()
#1
    url = "https://raw.githubusercontent.com/OU-PhD-Econometrics/fall-2020/master/ProblemSets/PS8-factor/nlsy.csv"
	df = CSV.read(HTTP.get(url).body, DataFrames)

	rgrsn = lm(@formula(logwage ~ black + hispanic + female + schoolt + gradHS + grad4yr), df)
	print(rgrsn)
    #print(coef(rgrsn))

#2
asvab=convert(Matrix,df[:,r"asvab"])
	correlation=cor(asvab)
	#for all variables:
	#cor(convert(Matrix,df))

	println(correlation)

#3
2rgrsn = lm(@formula(logwage ~ black + hispanic + female + schoolt + gradHS + grad4yr+asvabAR+asvabCS+asvabMK+asvabNO+asvabPC+asvabWK), df)
	print(2rgrsn)
#These serve as proxies for the response. Keeping them results in measurement error;however, leaving them out causes omitted variable bias. I would believe they're all correlated to each other?

#4
M = fit(PCA, asvabMat'; maxoutdim=1)

asvabPCA = MultivariateStats.transform(M, asvabMat')
print(asvabPCA)

#5
M = fit(FactorAnalysis, asvabMat'; maxoutdim=1)
	asvabFCTRA = MultivariateStats.transform(M, asvabMat')

	print(asvabFCTRA)

#6

#Question 6
#I'm sorry I ran into a bit of trouble on this problem. I had to eventually be done.
	z=rand(Normal(0,1),size(df,1))
	A=df[:logwage]
	X=df[:,[:black,:hispanic,:female,:schoolt,:gradHS,:grad4yr]]
	asvab=df[:,[:asvabAR, :asvabCS, :asvabMK, :asvabNO, :asvabPC, :asvabWK]]

	function loglike(sigma,m,z,y,x,asv)
	    S=size(A,1)
		T=size(asv,2)

		rez=zeros(S,T)
		for i=1:T
			rez[:,i]=residuals(lm(@formula(x1 ~ black + hispanic + female +x1_1),hcat(x,asvab[i],z,makeunique=true)))
		end

		w=residuals(lm(@formula(x1 ~ black + hispanic + female + schoolt + gradHS + grad4yr+x1_1), hcat(x,y,z,makeunique=true)))

		return
	end
end
ps8()


text:
#=
  Euler #20 in Julia.

  Problem 20:
  """
  n! means n (n 1) ... 3 2 1

  Find the sum of the digits in the number 100!")
  """

  This Julia program was created by Hakan Kjellerstrand, hakank@gmail.com
  See also my Julia page: http://www.hakank.org/julia/

=#

include("Euler.jl")

# 0.00029684s
function euler20a()
    return sum(split(factorial(BigInt(100))|>string,"").|>j->parse(Int,j))
end

# 0.00031793s
function euler20b()
    return sum(digits(factorial(BigInt(100))))
end

# 0.00032192s
function euler20c()
    return factorial(BigInt(100))|>digits|>sum
end

run_euler(euler20a)
# run_euler(euler20b)
# run_euler(euler20c)

max_stars_repo_name: Wikunia/hakank

max_issues_repo_name: Wikunia/hakank

max_forks_repo_name: Wikunia/hakank