text:
function selectPivotIndex(A, left, right)
#=
This function returns an index of pivot.
=#

  # The most simplest way to choose a pivot index: A[1] or A[end]
  pivot_index = left   # A[1]
  #pivot_index = right # A[end]

  return pivot_index

end

function partitionList(A, left, right, pivot_index)
#=
This function reearranges the input list A as follows:
A' = [ (elements smaller than pivot) ,  pivot, ... elements larger than pivot]
In the end, an index of the pivot is returned.
=#

  pivot = A[pivot_index]

  # Move the pivot to the end of the list
  tmp = A[right]
  A[right] = A[pivot_index]
  A[pivot_index] = tmp

  # Move elements which are smaller than the pivot
  store = left
  for idx in left:right-1
    if A[idx] <= pivot

      tmp = A[idx]
      A[idx] = A[store]
      A[store] = tmp

      store = store + 1
    end
  end

  tmp = A[right]
  A[right] = A[store]
  A[store] = tmp

  return store

end

function quickSort(A, left, right)
#=
Quick sort function
=#

  if right <= left
    return
  end

  pivot_index = selectPivotIndex(A,  left,  right)
  pivot_index = partitionList(A, left, right, pivot_index)

  quickSort(A, left,  pivot_index-1)
  quickSort(A, pivot_index+1,  right)

end

function main()

  # list to be sorted
  rng = MersenneTwister(1234);
  A = shuffle(rng, Vector(1:100))
  Aorigin = copy(A)

  # sorting
  n = length(A)
  @time quickSort(A, 1, n)

  print("The original list: ")
  println(Aorigin)

  print("The sorted list: ")
  println(A)

end

if contains(@__FILE__, PROGRAM_FILE)
    main()
end

max_stars_repo_name: szmlb/algorithmsInJulia

max_issues_repo_name: szmlb/algorithmsInJulia

max_forks_repo_name: szmlb/algorithmsInJulia


text:
"""
    PreallocatedUnorderedList <: AbstractVector

    PreallocatedUnorderedList(::Type{T}, maxlen::Int)
    PreallocatedUnorderedList(values::AbstractArray, len::Int)

A very fast fixed-length unordered list. The maximum length is fixed
and the order no specified so that `push!` does not need to allocate memory,
and `pop!` and `deleteat!` do not not remove memory - they just move values
from the end of the array to the specified index and shorten the apparent
array length.
"""
mutable struct PreallocatedUnorderedList{T,A<:AbstractArray{T}} <: AbstractVector{T}
    values::A
    len::Int
end
function PreallocatedUnorderedList(::Type{T}; maxlength::Int) where T
    values = Vector{T}(undef, maxlength)
    PreallocatedUnorderedList(values, 0)
end
PreallocatedUnorderedList(values::AbstractVector) = PreallocatedUnorderedList(values, length(values))
Base.length(list::PreallocatedUnorderedList) = list.len
Base.size(list::PreallocatedUnorderedList) = (length(list),)
Base.@propagate_inbounds function Base.getindex(list::PreallocatedUnorderedList, i)
    @boundscheck checkbounds(list, i)
    @inbounds list.values[i]
end
Base.@propagate_inbounds function Base.setindex!(list::PreallocatedUnorderedList, x, i)
    @boundscheck checkbounds(list, i)
    @inbounds list.values[i] = x
end
function Base.push!(list::PreallocatedUnorderedList, x)
    newlen = list.len + 1
    list.len = newlen
    list.values[newlen] = x
end
function Base.pop!(list::PreallocatedUnorderedList)
    val = list.values[1]
    deleteat!(list, 1)
    return val
end
function Base.deleteat!(list::PreallocatedUnorderedList, i::Int)
    val = list.values[i]
    len = list.len
    list.values[i] = list.values[len]
    list.len = len - oneunit(len)
    return list
end

ext: jl


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

include("model_IoK8sApiAdmissionregistrationV1beta1MutatingWebhookConfiguration.jl")
include("model_IoK8sApiAdmissionregistrationV1beta1MutatingWebhookConfigurationList.jl")
include("model_IoK8sApiAdmissionregistrationV1beta1RuleWithOperations.jl")
include("model_IoK8sApiAdmissionregistrationV1beta1ServiceReference.jl")
include("model_IoK8sApiAdmissionregistrationV1beta1ValidatingWebhookConfiguration.jl")
include("model_IoK8sApiAdmissionregistrationV1beta1ValidatingWebhookConfigurationList.jl")
include("model_IoK8sApiAdmissionregistrationV1beta1Webhook.jl")
include("model_IoK8sApiAdmissionregistrationV1beta1WebhookClientConfig.jl")
include("model_IoK8sApiAppsV1ControllerRevision.jl")
include("model_IoK8sApiAppsV1ControllerRevisionList.jl")
include("model_IoK8sApiAppsV1DaemonSet.jl")
include("model_IoK8sApiAppsV1DaemonSetCondition.jl")
include("model_IoK8sApiAppsV1DaemonSetList.jl")
include("model_IoK8sApiAppsV1DaemonSetSpec.jl")
include("model_IoK8sApiAppsV1DaemonSetStatus.jl")
include("model_IoK8sApiAppsV1DaemonSetUpdateStrategy.jl")
include("model_IoK8sApiAppsV1Deployment.jl")
include("model_IoK8sApiAppsV1DeploymentCondition.jl")
include("model_IoK8sApiAppsV1DeploymentList.jl")
include("model_IoK8sApiAppsV1DeploymentSpec.jl")
include("model_IoK8sApiAppsV1DeploymentStatus.jl")
include("model_IoK8sApiAppsV1DeploymentStrategy.jl")
include("model_IoK8sApiAppsV1ReplicaSet.jl")
include("model_IoK8sApiAppsV1ReplicaSetCondition.jl")
include("model_IoK8sApiAppsV1ReplicaSetList.jl")
include("model_IoK8sApiAppsV1ReplicaSetSpec.jl")
include("model_IoK8sApiAppsV1ReplicaSetStatus.jl")
include("model_IoK8sApiAppsV1RollingUpdateDaemonSet.jl")
include("model_IoK8sApiAppsV1RollingUpdateDeployment.jl")
include("model_IoK8sApiAppsV1RollingUpdateStatefulSetStrategy.jl")
include("model_IoK8sApiAppsV1StatefulSet.jl")
include("model_IoK8sApiAppsV1StatefulSetCondition.jl")
include("model_IoK8sApiAppsV1StatefulSetList.jl")
include("model_IoK8sApiAppsV1StatefulSetSpec.jl")
include("model_IoK8sApiAppsV1StatefulSetStatus.jl")
include("model_IoK8sApiAppsV1StatefulSetUpdateStrategy.jl")
include("model_IoK8sApiAppsV1beta1ControllerRevision.jl")
include("model_IoK8sApiAppsV1beta1ControllerRevisionList.jl")
include("model_IoK8sApiAppsV1beta1Deployment.jl")
include("model_IoK8sApiAppsV1beta1DeploymentCondition.jl")
include("model_IoK8sApiAppsV1beta1DeploymentList.jl")
include("model_IoK8sApiAppsV1beta1DeploymentRollback.jl")
include("model_IoK8sApiAppsV1beta1DeploymentSpec.jl")
include("model_IoK8sApiAppsV1beta1DeploymentStatus.jl")
include("model_IoK8sApiAppsV1beta1DeploymentStrategy.jl")
include("model_IoK8sApiAppsV1beta1RollbackConfig.jl")
include("model_IoK8sApiAppsV1beta1RollingUpdateDeployment.jl")
include("model_IoK8sApiAppsV1beta1RollingUpdateStatefulSetStrategy.jl")
include("model_IoK8sApiAppsV1beta1Scale.jl")
include("model_IoK8sApiAppsV1beta1ScaleSpec.jl")
include("model_IoK8sApiAppsV1beta1ScaleStatus.jl")
include("model_IoK8sApiAppsV1beta1StatefulSet.jl")
include("model_IoK8sApiAppsV1beta1StatefulSetCondition.jl")
include("model_IoK8sApiAppsV1beta1StatefulSetList.jl")
include("model_IoK8sApiAppsV1beta1StatefulSetSpec.jl")
include("model_IoK8sApiAppsV1beta1StatefulSetStatus.jl")
include("model_IoK8sApiAppsV1beta1StatefulSetUpdateStrategy.jl")
include("model_IoK8sApiAppsV1beta2ControllerRevision.jl")
include("model_IoK8sApiAppsV1beta2ControllerRevisionList.jl")
include("model_IoK8sApiAppsV1beta2DaemonSet.jl")
include("model_IoK8sApiAppsV1beta2DaemonSetCondition.jl")
include("model_IoK8sApiAppsV1beta2DaemonSetList.jl")
include("model_IoK8sApiAppsV1beta2DaemonSetSpec.jl")
include("model_IoK8sApiAppsV1beta2DaemonSetStatus.jl")
include("model_IoK8sApiAppsV1beta2DaemonSetUpdateStrategy.jl")
include("model_IoK8sApiAppsV1beta2Deployment.jl")
include("model_IoK8sApiAppsV1beta2DeploymentCondition.jl")
include("model_IoK8sApiAppsV1beta2DeploymentList.jl")
include("model_IoK8sApiAppsV1beta2DeploymentSpec.jl")
include("model_IoK8sApiAppsV1beta2DeploymentStatus.jl")
include("model_IoK8sApiAppsV1beta2DeploymentStrategy.jl")
include("model_IoK8sApiAppsV1beta2ReplicaSet.jl")
include("model_IoK8sApiAppsV1beta2ReplicaSetCondition.jl")
include("model_IoK8sApiAppsV1beta2ReplicaSetList.jl")
include("model_IoK8sApiAppsV1beta2ReplicaSetSpec.jl")
include("model_IoK8sApiAppsV1beta2ReplicaSetStatus.jl")
include("model_IoK8sApiAppsV1beta2RollingUpdateDaemonSet.jl")
include("model_IoK8sApiAppsV1beta2RollingUpdateDeployment.jl")
include("model_IoK8sApiAppsV1beta2RollingUpdateStatefulSetStrategy.jl")
include("model_IoK8sApiAppsV1beta2Scale.jl")
include("model_IoK8sApiAppsV1beta2ScaleSpec.jl")
include("model_IoK8sApiAppsV1beta2ScaleStatus.jl")
include("model_IoK8sApiAppsV1beta2StatefulSet.jl")
include("model_IoK8sApiAppsV1beta2StatefulSetCondition.jl")
include("model_IoK8sApiAppsV1beta2StatefulSetList.jl")
include("model_IoK8sApiAppsV1beta2StatefulSetSpec.jl")
include("model_IoK8sApiAppsV1beta2StatefulSetStatus.jl")
include("model_IoK8sApiAppsV1beta2StatefulSetUpdateStrategy.jl")
include("model_IoK8sApiAuditregistrationV1alpha1AuditSink.jl")
include("model_IoK8sApiAuditregistrationV1alpha1AuditSinkList.jl")
include("model_IoK8sApiAuditregistrationV1alpha1AuditSinkSpec.jl")
include("model_IoK8sApiAuditregistrationV1alpha1Policy.jl")
include("model_IoK8sApiAuditregistrationV1alpha1ServiceReference.jl")
include("model_IoK8sApiAuditregistrationV1alpha1Webhook.jl")
include("model_IoK8sApiAuditregistrationV1alpha1WebhookClientConfig.jl")
include("model_IoK8sApiAuditregistrationV1alpha1WebhookThrottleConfig.jl")
include("model_IoK8sApiAuthenticationV1TokenReview.jl")
include("model_IoK8sApiAuthenticationV1TokenReviewSpec.jl")
include("model_IoK8sApiAuthenticationV1TokenReviewStatus.jl")
include("model_IoK8sApiAuthenticationV1UserInfo.jl")
include("model_IoK8sApiAuthenticationV1beta1TokenReview.jl")
include("model_IoK8sApiAuthenticationV1beta1TokenReviewSpec.jl")
include("model_IoK8sApiAuthenticationV1beta1TokenReviewStatus.jl")
include("model_IoK8sApiAuthenticationV1beta1UserInfo.jl")
include("model_IoK8sApiAuthorizationV1LocalSubjectAccessReview.jl")
include("model_IoK8sApiAuthorizationV1NonResourceAttributes.jl")
include("model_IoK8sApiAuthorizationV1NonResourceRule.jl")
include("model_IoK8sApiAuthorizationV1ResourceAttributes.jl")
include("model_IoK8sApiAuthorizationV1ResourceRule.jl")
include("model_IoK8sApiAuthorizationV1SelfSubjectAccessReview.jl")
include("model_IoK8sApiAuthorizationV1SelfSubjectAccessReviewSpec.jl")
include("model_IoK8sApiAuthorizationV1SelfSubjectRulesReview.jl")
include("model_IoK8sApiAuthorizationV1SelfSubjectRulesReviewSpec.jl")
include("model_IoK8sApiAuthorizationV1SubjectAccessReview.jl")
include("model_IoK8sApiAuthorizationV1SubjectAccessReviewSpec.jl")
include("model_IoK8sApiAuthorizationV1SubjectAccessReviewStatus.jl")
include("model_IoK8sApiAuthorizationV1SubjectRulesReviewStatus.jl")
include("model_IoK8sApiAuthorizationV1beta1LocalSubjectAccessReview.jl")
include("model_IoK8sApiAuthorizationV1beta1NonResourceAttributes.jl")
include("model_IoK8sApiAuthorizationV1beta1NonResourceRule.jl")
include("model_IoK8sApiAuthorizationV1beta1ResourceAttributes.jl")
include("model_IoK8sApiAuthorizationV1beta1ResourceRule.jl")
include("model_IoK8sApiAuthorizationV1beta1SelfSubjectAccessReview.jl")
include("model_IoK8sApiAuthorizationV1beta1SelfSubjectAccessReviewSpec.jl")
include("model_IoK8sApiAuthorizationV1beta1SelfSubjectRulesReview.jl")
include("model_IoK8sApiAuthorizationV1beta1SelfSubjectRulesReviewSpec.jl")
include("model_IoK8sApiAuthorizationV1beta1SubjectAccessReview.jl")
include("model_IoK8sApiAuthorizationV1beta1SubjectAccessReviewSpec.jl")
include("model_IoK8sApiAuthorizationV1beta1SubjectAccessReviewStatus.jl")
include("model_IoK8sApiAuthorizationV1beta1SubjectRulesReviewStatus.jl")
include("model_IoK8sApiAutoscalingV1CrossVersionObjectReference.jl")
include("model_IoK8sApiAutoscalingV1HorizontalPodAutoscaler.jl")
include("model_IoK8sApiAutoscalingV1HorizontalPodAutoscalerList.jl")
include("model_IoK8sApiAutoscalingV1HorizontalPodAutoscalerSpec.jl")
include("model_IoK8sApiAutoscalingV1HorizontalPodAutoscalerStatus.jl")
include("model_IoK8sApiAutoscalingV1Scale.jl")
include("model_IoK8sApiAutoscalingV1ScaleSpec.jl")
include("model_IoK8sApiAutoscalingV1ScaleStatus.jl")
include("model_IoK8sApiAutoscalingV2beta1CrossVersionObjectReference.jl")
include("model_IoK8sApiAutoscalingV2beta1ExternalMetricSource.jl")
include("model_IoK8sApiAutoscalingV2beta1ExternalMetricStatus.jl")
include("model_IoK8sApiAutoscalingV2beta1HorizontalPodAutoscaler.jl")
include("model_IoK8sApiAutoscalingV2beta1HorizontalPodAutoscalerCondition.jl")
include("model_IoK8sApiAutoscalingV2beta1HorizontalPodAutoscalerList.jl")
include("model_IoK8sApiAutoscalingV2beta1HorizontalPodAutoscalerSpec.jl")
include("model_IoK8sApiAutoscalingV2beta1HorizontalPodAutoscalerStatus.jl")
include("model_IoK8sApiAutoscalingV2beta1MetricSpec.jl")
include("model_IoK8sApiAutoscalingV2beta1MetricStatus.jl")
include("model_IoK8sApiAutoscalingV2beta1ObjectMetricSource.jl")
include("model_IoK8sApiAutoscalingV2beta1ObjectMetricStatus.jl")
include("model_IoK8sApiAutoscalingV2beta1PodsMetricSource.jl")
include("model_IoK8sApiAutoscalingV2beta1PodsMetricStatus.jl")
include("model_IoK8sApiAutoscalingV2beta1ResourceMetricSource.jl")
include("model_IoK8sApiAutoscalingV2beta1ResourceMetricStatus.jl")
include("model_IoK8sApiAutoscalingV2beta2CrossVersionObjectReference.jl")
include("model_IoK8sApiAutoscalingV2beta2ExternalMetricSource.jl")
include("model_IoK8sApiAutoscalingV2beta2ExternalMetricStatus.jl")
include("model_IoK8sApiAutoscalingV2beta2HorizontalPodAutoscaler.jl")
include("model_IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerCondition.jl")
include("model_IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerList.jl")
include("model_IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerSpec.jl")
include("model_IoK8sApiAutoscalingV2beta2HorizontalPodAutoscalerStatus.jl")
include("model_IoK8sApiAutoscalingV2beta2MetricIdentifier.jl")
include("model_IoK8sApiAutoscalingV2beta2MetricSpec.jl")
include("model_IoK8sApiAutoscalingV2beta2MetricStatus.jl")
include("model_IoK8sApiAutoscalingV2beta2MetricTarget.jl")
include("model_IoK8sApiAutoscalingV2beta2MetricValueStatus.jl")
include("model_IoK8sApiAutoscalingV2beta2ObjectMetricSource.jl")
include("model_IoK8sApiAutoscalingV2beta2ObjectMetricStatus.jl")
include("model_IoK8sApiAutoscalingV2beta2PodsMetricSource.jl")
include("model_IoK8sApiAutoscalingV2beta2PodsMetricStatus.jl")
include("model_IoK8sApiAutoscalingV2beta2ResourceMetricSource.jl")
include("model_IoK8sApiAutoscalingV2beta2ResourceMetricStatus.jl")
include("model_IoK8sApiBatchV1Job.jl")
include("model_IoK8sApiBatchV1JobCondition.jl")
include("model_IoK8sApiBatchV1JobList.jl")
include("model_IoK8sApiBatchV1JobSpec.jl")
include("model_IoK8sApiBatchV1JobStatus.jl")
include("model_IoK8sApiBatchV1beta1CronJob.jl")
include("model_IoK8sApiBatchV1beta1CronJobList.jl")
include("model_IoK8sApiBatchV1beta1CronJobSpec.jl")
include("model_IoK8sApiBatchV1beta1CronJobStatus.jl")
include("model_IoK8sApiBatchV1beta1JobTemplateSpec.jl")
include("model_IoK8sApiBatchV2alpha1CronJob.jl")
include("model_IoK8sApiBatchV2alpha1CronJobList.jl")
include("model_IoK8sApiBatchV2alpha1CronJobSpec.jl")
include("model_IoK8sApiBatchV2alpha1CronJobStatus.jl")
include("model_IoK8sApiBatchV2alpha1JobTemplateSpec.jl")
include("model_IoK8sApiCertificatesV1beta1CertificateSigningRequest.jl")
include("model_IoK8sApiCertificatesV1beta1CertificateSigningRequestCondition.jl")
include("model_IoK8sApiCertificatesV1beta1CertificateSigningRequestList.jl")
include("model_IoK8sApiCertificatesV1beta1CertificateSigningRequestSpec.jl")
include("model_IoK8sApiCertificatesV1beta1CertificateSigningRequestStatus.jl")
include("model_IoK8sApiCoordinationV1Lease.jl")
include("model_IoK8sApiCoordinationV1LeaseList.jl")
include("model_IoK8sApiCoordinationV1LeaseSpec.jl")
include("model_IoK8sApiCoordinationV1beta1Lease.jl")
include("model_IoK8sApiCoordinationV1beta1LeaseList.jl")
include("model_IoK8sApiCoordinationV1beta1LeaseSpec.jl")
include("model_IoK8sApiCoreV1AWSElasticBlockStoreVolumeSource.jl")
include("model_IoK8sApiCoreV1Affinity.jl")
include("model_IoK8sApiCoreV1AttachedVolume.jl")
include("model_IoK8sApiCoreV1AzureDiskVolumeSource.jl")
include("model_IoK8sApiCoreV1AzureFilePersistentVolumeSource.jl")
include("model_IoK8sApiCoreV1AzureFileVolumeSource.jl")
include("model_IoK8sApiCoreV1Binding.jl")
include("model_IoK8sApiCoreV1CSIPersistentVolumeSource.jl")
include("model_IoK8sApiCoreV1CSIVolumeSource.jl")
include("model_IoK8sApiCoreV1Capabilities.jl")
include("model_IoK8sApiCoreV1CephFSPersistentVolumeSource.jl")
include("model_IoK8sApiCoreV1CephFSVolumeSource.jl")
include("model_IoK8sApiCoreV1CinderPersistentVolumeSource.jl")
include("model_IoK8sApiCoreV1CinderVolumeSource.jl")
include("model_IoK8sApiCoreV1ClientIPConfig.jl")
include("model_IoK8sApiCoreV1ComponentCondition.jl")
include("model_IoK8sApiCoreV1ComponentStatus.jl")
include("model_IoK8sApiCoreV1ComponentStatusList.jl")
include("model_IoK8sApiCoreV1ConfigMap.jl")
include("model_IoK8sApiCoreV1ConfigMapEnvSource.jl")
include("model_IoK8sApiCoreV1ConfigMapKeySelector.jl")
include("model_IoK8sApiCoreV1ConfigMapList.jl")
include("model_IoK8sApiCoreV1ConfigMapNodeConfigSource.jl")
include("model_IoK8sApiCoreV1ConfigMapProjection.jl")
include("model_IoK8sApiCoreV1ConfigMapVolumeSource.jl")
include("model_IoK8sApiCoreV1Container.jl")
include("model_IoK8sApiCoreV1ContainerImage.jl")
include("model_IoK8sApiCoreV1ContainerPort.jl")
include("model_IoK8sApiCoreV1ContainerState.jl")
include("model_IoK8sApiCoreV1ContainerStateRunning.jl")
include("model_IoK8sApiCoreV1ContainerStateTerminated.jl")
include("model_IoK8sApiCoreV1ContainerStateWaiting.jl")
include("model_IoK8sApiCoreV1ContainerStatus.jl")
include("model_IoK8sApiCoreV1DaemonEndpoint.jl")
include("model_IoK8sApiCoreV1DownwardAPIProjection.jl")
include("model_IoK8sApiCoreV1DownwardAPIVolumeFile.jl")
include("model_IoK8sApiCoreV1DownwardAPIVolumeSource.jl")
include("model_IoK8sApiCoreV1EmptyDirVolumeSource.jl")
include("model_IoK8sApiCoreV1EndpointAddress.jl")
include("model_IoK8sApiCoreV1EndpointPort.jl")
include("model_IoK8sApiCoreV1EndpointSubset.jl")
include("model_IoK8sApiCoreV1Endpoints.jl")
include("model_IoK8sApiCoreV1EndpointsList.jl")
include("model_IoK8sApiCoreV1EnvFromSource.jl")
include("model_IoK8sApiCoreV1EnvVar.jl")
include("model_IoK8sApiCoreV1EnvVarSource.jl")
include("model_IoK8sApiCoreV1Event.jl")
include("model_IoK8sApiCoreV1EventList.jl")
include("model_IoK8sApiCoreV1EventSeries.jl")
include("model_IoK8sApiCoreV1EventSource.jl")
include("model_IoK8sApiCoreV1ExecAction.jl")
include("model_IoK8sApiCoreV1FCVolumeSource.jl")
include("model_IoK8sApiCoreV1FlexPersistentVolumeSource.jl")
include("model_IoK8sApiCoreV1FlexVolumeSource.jl")
include("model_IoK8sApiCoreV1FlockerVolumeSource.jl")
include("model_IoK8sApiCoreV1GCEPersistentDiskVolumeSource.jl")
include("model_IoK8sApiCoreV1GitRepoVolumeSource.jl")
include("model_IoK8sApiCoreV1GlusterfsPersistentVolumeSource.jl")
include("model_IoK8sApiCoreV1GlusterfsVolumeSource.jl")
include("model_IoK8sApiCoreV1HTTPGetAction.jl")
include("model_IoK8sApiCoreV1HTTPHeader.jl")
include("model_IoK8sApiCoreV1Handler.jl")
include("model_IoK8sApiCoreV1HostAlias.jl")
include("model_IoK8sApiCoreV1HostPathVolumeSource.jl")
include("model_IoK8sApiCoreV1ISCSIPersistentVolumeSource.jl")
include("model_IoK8sApiCoreV1ISCSIVolumeSource.jl")
include("model_IoK8sApiCoreV1KeyToPath.jl")
include("model_IoK8sApiCoreV1Lifecycle.jl")
include("model_IoK8sApiCoreV1LimitRange.jl")
include("model_IoK8sApiCoreV1LimitRangeItem.jl")
include("model_IoK8sApiCoreV1LimitRangeList.jl")
include("model_IoK8sApiCoreV1LimitRangeSpec.jl")
include("model_IoK8sApiCoreV1LoadBalancerIngress.jl")
include("model_IoK8sApiCoreV1LoadBalancerStatus.jl")
include("model_IoK8sApiCoreV1LocalObjectReference.jl")
include("model_IoK8sApiCoreV1LocalVolumeSource.jl")
include("model_IoK8sApiCoreV1NFSVolumeSource.jl")
include("model_IoK8sApiCoreV1Namespace.jl")
include("model_IoK8sApiCoreV1NamespaceList.jl")
include("model_IoK8sApiCoreV1NamespaceSpec.jl")
include("model_IoK8sApiCoreV1NamespaceStatus.jl")
include("model_IoK8sApiCoreV1Node.jl")
include("model_IoK8sApiCoreV1NodeAddress.jl")
include("model_IoK8sApiCoreV1NodeAffinity.jl")
include("model_IoK8sApiCoreV1NodeCondition.jl")
include("model_IoK8sApiCoreV1NodeConfigSource.jl")
include("model_IoK8sApiCoreV1NodeConfigStatus.jl")
include("model_IoK8sApiCoreV1NodeDaemonEndpoints.jl")
include("model_IoK8sApiCoreV1NodeList.jl")
include("model_IoK8sApiCoreV1NodeSelector.jl")
include("model_IoK8sApiCoreV1NodeSelectorRequirement.jl")
include("model_IoK8sApiCoreV1NodeSelectorTerm.jl")
include("model_IoK8sApiCoreV1NodeSpec.jl")
include("model_IoK8sApiCoreV1NodeStatus.jl")
include("model_IoK8sApiCoreV1NodeSystemInfo.jl")
include("model_IoK8sApiCoreV1ObjectFieldSelector.jl")
include("model_IoK8sApiCoreV1ObjectReference.jl")
include("model_IoK8sApiCoreV1PersistentVolume.jl")
include("model_IoK8sApiCoreV1PersistentVolumeClaim.jl")
include("model_IoK8sApiCoreV1PersistentVolumeClaimCondition.jl")
include("model_IoK8sApiCoreV1PersistentVolumeClaimList.jl")
include("model_IoK8sApiCoreV1PersistentVolumeClaimSpec.jl")
include("model_IoK8sApiCoreV1PersistentVolumeClaimStatus.jl")
include("model_IoK8sApiCoreV1PersistentVolumeClaimVolumeSource.jl")
include("model_IoK8sApiCoreV1PersistentVolumeList.jl")
include("model_IoK8sApiCoreV1PersistentVolumeSpec.jl")
include("model_IoK8sApiCoreV1PersistentVolumeStatus.jl")
include("model_IoK8sApiCoreV1PhotonPersistentDiskVolumeSource.jl")
include("model_IoK8sApiCoreV1Pod.jl")
include("model_IoK8sApiCoreV1PodAffinity.jl")
include("model_IoK8sApiCoreV1PodAffinityTerm.jl")
include("model_IoK8sApiCoreV1PodAntiAffinity.jl")
include("model_IoK8sApiCoreV1PodCondition.jl")
include("model_IoK8sApiCoreV1PodDNSConfig.jl")
include("model_IoK8sApiCoreV1PodDNSConfigOption.jl")
include("model_IoK8sApiCoreV1PodList.jl")
include("model_IoK8sApiCoreV1PodReadinessGate.jl")
include("model_IoK8sApiCoreV1PodSecurityContext.jl")
include("model_IoK8sApiCoreV1PodSpec.jl")
include("model_IoK8sApiCoreV1PodStatus.jl")
include("model_IoK8sApiCoreV1PodTemplate.jl")
include("model_IoK8sApiCoreV1PodTemplateList.jl")
include("model_IoK8sApiCoreV1PodTemplateSpec.jl")
include("model_IoK8sApiCoreV1PortworxVolumeSource.jl")
include("model_IoK8sApiCoreV1PreferredSchedulingTerm.jl")
include("model_IoK8sApiCoreV1Probe.jl")
include("model_IoK8sApiCoreV1ProjectedVolumeSource.jl")
include("model_IoK8sApiCoreV1QuobyteVolumeSource.jl")
include("model_IoK8sApiCoreV1RBDPersistentVolumeSource.jl")
include("model_IoK8sApiCoreV1RBDVolumeSource.jl")
include("model_IoK8sApiCoreV1ReplicationController.jl")
include("model_IoK8sApiCoreV1ReplicationControllerCondition.jl")
include("model_IoK8sApiCoreV1ReplicationControllerList.jl")
include("model_IoK8sApiCoreV1ReplicationControllerSpec.jl")
include("model_IoK8sApiCoreV1ReplicationControllerStatus.jl")
include("model_IoK8sApiCoreV1ResourceFieldSelector.jl")
include("model_IoK8sApiCoreV1ResourceQuota.jl")
include("model_IoK8sApiCoreV1ResourceQuotaList.jl")
include("model_IoK8sApiCoreV1ResourceQuotaSpec.jl")
include("model_IoK8sApiCoreV1ResourceQuotaStatus.jl")
include("model_IoK8sApiCoreV1ResourceRequirements.jl")
include("model_IoK8sApiCoreV1SELinuxOptions.jl")
include("model_IoK8sApiCoreV1ScaleIOPersistentVolumeSource.jl")
include("model_IoK8sApiCoreV1ScaleIOVolumeSource.jl")
include("model_IoK8sApiCoreV1ScopeSelector.jl")
include("model_IoK8sApiCoreV1ScopedResourceSelectorRequirement.jl")
include("model_IoK8sApiCoreV1Secret.jl")
include("model_IoK8sApiCoreV1SecretEnvSource.jl")
include("model_IoK8sApiCoreV1SecretKeySelector.jl")
include("model_IoK8sApiCoreV1SecretList.jl")
include("model_IoK8sApiCoreV1SecretProjection.jl")
include("model_IoK8sApiCoreV1SecretReference.jl")
include("model_IoK8sApiCoreV1SecretVolumeSource.jl")
include("model_IoK8sApiCoreV1SecurityContext.jl")
include("model_IoK8sApiCoreV1Service.jl")
include("model_IoK8sApiCoreV1ServiceAccount.jl")
include("model_IoK8sApiCoreV1ServiceAccountList.jl")
include("model_IoK8sApiCoreV1ServiceAccountTokenProjection.jl")
include("model_IoK8sApiCoreV1ServiceList.jl")
include("model_IoK8sApiCoreV1ServicePort.jl")
include("model_IoK8sApiCoreV1ServiceSpec.jl")
include("model_IoK8sApiCoreV1ServiceStatus.jl")
include("model_IoK8sApiCoreV1SessionAffinityConfig.jl")
include("model_IoK8sApiCoreV1StorageOSPersistentVolumeSource.jl")
include("model_IoK8sApiCoreV1StorageOSVolumeSource.jl")
include("model_IoK8sApiCoreV1Sysctl.jl")
include("model_IoK8sApiCoreV1TCPSocketAction.jl")
include("model_IoK8sApiCoreV1Taint.jl")
include("model_IoK8sApiCoreV1Toleration.jl")
include("model_IoK8sApiCoreV1TopologySelectorLabelRequirement.jl")
include("model_IoK8sApiCoreV1TopologySelectorTerm.jl")
include("model_IoK8sApiCoreV1TypedLocalObjectReference.jl")
include("model_IoK8sApiCoreV1Volume.jl")
include("model_IoK8sApiCoreV1VolumeDevice.jl")
include("model_IoK8sApiCoreV1VolumeMount.jl")
include("model_IoK8sApiCoreV1VolumeNodeAffinity.jl")
include("model_IoK8sApiCoreV1VolumeProjection.jl")
include("model_IoK8sApiCoreV1VsphereVirtualDiskVolumeSource.jl")
include("model_IoK8sApiCoreV1WeightedPodAffinityTerm.jl")
include("model_IoK8sApiEventsV1beta1Event.jl")
include("model_IoK8sApiEventsV1beta1EventList.jl")
include("model_IoK8sApiEventsV1beta1EventSeries.jl")
include("model_IoK8sApiExtensionsV1beta1AllowedCSIDriver.jl")
include("model_IoK8sApiExtensionsV1beta1AllowedFlexVolume.jl")
include("model_IoK8sApiExtensionsV1beta1AllowedHostPath.jl")
include("model_IoK8sApiExtensionsV1beta1DaemonSet.jl")
include("model_IoK8sApiExtensionsV1beta1DaemonSetCondition.jl")
include("model_IoK8sApiExtensionsV1beta1DaemonSetList.jl")
include("model_IoK8sApiExtensionsV1beta1DaemonSetSpec.jl")
include("model_IoK8sApiExtensionsV1beta1DaemonSetStatus.jl")
include("model_IoK8sApiExtensionsV1beta1DaemonSetUpdateStrategy.jl")
include("model_IoK8sApiExtensionsV1beta1Deployment.jl")
include("model_IoK8sApiExtensionsV1beta1DeploymentCondition.jl")
include("model_IoK8sApiExtensionsV1beta1DeploymentList.jl")
include("model_IoK8sApiExtensionsV1beta1DeploymentRollback.jl")
include("model_IoK8sApiExtensionsV1beta1DeploymentSpec.jl")
include("model_IoK8sApiExtensionsV1beta1DeploymentStatus.jl")
include("model_IoK8sApiExtensionsV1beta1DeploymentStrategy.jl")
include("model_IoK8sApiExtensionsV1beta1FSGroupStrategyOptions.jl")
include("model_IoK8sApiExtensionsV1beta1HTTPIngressPath.jl")
include("model_IoK8sApiExtensionsV1beta1HTTPIngressRuleValue.jl")
include("model_IoK8sApiExtensionsV1beta1HostPortRange.jl")
include("model_IoK8sApiExtensionsV1beta1IDRange.jl")
include("model_IoK8sApiExtensionsV1beta1IPBlock.jl")
include("model_IoK8sApiExtensionsV1beta1Ingress.jl")
include("model_IoK8sApiExtensionsV1beta1IngressBackend.jl")
include("model_IoK8sApiExtensionsV1beta1IngressList.jl")
include("model_IoK8sApiExtensionsV1beta1IngressRule.jl")
include("model_IoK8sApiExtensionsV1beta1IngressSpec.jl")
include("model_IoK8sApiExtensionsV1beta1IngressStatus.jl")
include("model_IoK8sApiExtensionsV1beta1IngressTLS.jl")
include("model_IoK8sApiExtensionsV1beta1NetworkPolicy.jl")
include("model_IoK8sApiExtensionsV1beta1NetworkPolicyEgressRule.jl")
include("model_IoK8sApiExtensionsV1beta1NetworkPolicyIngressRule.jl")
include("model_IoK8sApiExtensionsV1beta1NetworkPolicyList.jl")
include("model_IoK8sApiExtensionsV1beta1NetworkPolicyPeer.jl")
include("model_IoK8sApiExtensionsV1beta1NetworkPolicyPort.jl")
include("model_IoK8sApiExtensionsV1beta1NetworkPolicySpec.jl")
include("model_IoK8sApiExtensionsV1beta1PodSecurityPolicy.jl")
include("model_IoK8sApiExtensionsV1beta1PodSecurityPolicyList.jl")
include("model_IoK8sApiExtensionsV1beta1PodSecurityPolicySpec.jl")
include("model_IoK8sApiExtensionsV1beta1ReplicaSet.jl")
include("model_IoK8sApiExtensionsV1beta1ReplicaSetCondition.jl")
include("model_IoK8sApiExtensionsV1beta1ReplicaSetList.jl")
include("model_IoK8sApiExtensionsV1beta1ReplicaSetSpec.jl")
include("model_IoK8sApiExtensionsV1beta1ReplicaSetStatus.jl")
include("model_IoK8sApiExtensionsV1beta1RollbackConfig.jl")
include("model_IoK8sApiExtensionsV1beta1RollingUpdateDaemonSet.jl")
include("model_IoK8sApiExtensionsV1beta1RollingUpdateDeployment.jl")
include("model_IoK8sApiExtensionsV1beta1RunAsGroupStrategyOptions.jl")
include("model_IoK8sApiExtensionsV1beta1RunAsUserStrategyOptions.jl")
include("model_IoK8sApiExtensionsV1beta1SELinuxStrategyOptions.jl")
include("model_IoK8sApiExtensionsV1beta1Scale.jl")
include("model_IoK8sApiExtensionsV1beta1ScaleSpec.jl")
include("model_IoK8sApiExtensionsV1beta1ScaleStatus.jl")
include("model_IoK8sApiExtensionsV1beta1SupplementalGroupsStrategyOptions.jl")
include("model_IoK8sApiNetworkingV1IPBlock.jl")
include("model_IoK8sApiNetworkingV1NetworkPolicy.jl")
include("model_IoK8sApiNetworkingV1NetworkPolicyEgressRule.jl")
include("model_IoK8sApiNetworkingV1NetworkPolicyIngressRule.jl")
include("model_IoK8sApiNetworkingV1NetworkPolicyList.jl")
include("model_IoK8sApiNetworkingV1NetworkPolicyPeer.jl")
include("model_IoK8sApiNetworkingV1NetworkPolicyPort.jl")
include("model_IoK8sApiNetworkingV1NetworkPolicySpec.jl")
include("model_IoK8sApiNetworkingV1beta1HTTPIngressPath.jl")
include("model_IoK8sApiNetworkingV1beta1HTTPIngressRuleValue.jl")
include("model_IoK8sApiNetworkingV1beta1Ingress.jl")
include("model_IoK8sApiNetworkingV1beta1IngressBackend.jl")
include("model_IoK8sApiNetworkingV1beta1IngressList.jl")
include("model_IoK8sApiNetworkingV1beta1IngressRule.jl")
include("model_IoK8sApiNetworkingV1beta1IngressSpec.jl")
include("model_IoK8sApiNetworkingV1beta1IngressStatus.jl")
include("model_IoK8sApiNetworkingV1beta1IngressTLS.jl")
include("model_IoK8sApiNodeV1alpha1RuntimeClass.jl")
include("model_IoK8sApiNodeV1alpha1RuntimeClassList.jl")
include("model_IoK8sApiNodeV1alpha1RuntimeClassSpec.jl")
include("model_IoK8sApiNodeV1beta1RuntimeClass.jl")
include("model_IoK8sApiNodeV1beta1RuntimeClassList.jl")
include("model_IoK8sApiPolicyV1beta1AllowedCSIDriver.jl")
include("model_IoK8sApiPolicyV1beta1AllowedFlexVolume.jl")
include("model_IoK8sApiPolicyV1beta1AllowedHostPath.jl")
include("model_IoK8sApiPolicyV1beta1Eviction.jl")
include("model_IoK8sApiPolicyV1beta1FSGroupStrategyOptions.jl")
include("model_IoK8sApiPolicyV1beta1HostPortRange.jl")
include("model_IoK8sApiPolicyV1beta1IDRange.jl")
include("model_IoK8sApiPolicyV1beta1PodDisruptionBudget.jl")
include("model_IoK8sApiPolicyV1beta1PodDisruptionBudgetList.jl")
include("model_IoK8sApiPolicyV1beta1PodDisruptionBudgetSpec.jl")
include("model_IoK8sApiPolicyV1beta1PodDisruptionBudgetStatus.jl")
include("model_IoK8sApiPolicyV1beta1PodSecurityPolicy.jl")
include("model_IoK8sApiPolicyV1beta1PodSecurityPolicyList.jl")
include("model_IoK8sApiPolicyV1beta1PodSecurityPolicySpec.jl")
include("model_IoK8sApiPolicyV1beta1RunAsGroupStrategyOptions.jl")
include("model_IoK8sApiPolicyV1beta1RunAsUserStrategyOptions.jl")
include("model_IoK8sApiPolicyV1beta1SELinuxStrategyOptions.jl")
include("model_IoK8sApiPolicyV1beta1SupplementalGroupsStrategyOptions.jl")
include("model_IoK8sApiRbacV1AggregationRule.jl")
include("model_IoK8sApiRbacV1ClusterRole.jl")
include("model_IoK8sApiRbacV1ClusterRoleBinding.jl")
include("model_IoK8sApiRbacV1ClusterRoleBindingList.jl")
include("model_IoK8sApiRbacV1ClusterRoleList.jl")
include("model_IoK8sApiRbacV1PolicyRule.jl")
include("model_IoK8sApiRbacV1Role.jl")
include("model_IoK8sApiRbacV1RoleBinding.jl")
include("model_IoK8sApiRbacV1RoleBindingList.jl")
include("model_IoK8sApiRbacV1RoleList.jl")
include("model_IoK8sApiRbacV1RoleRef.jl")
include("model_IoK8sApiRbacV1Subject.jl")
include("model_IoK8sApiRbacV1alpha1AggregationRule.jl")
include("model_IoK8sApiRbacV1alpha1ClusterRole.jl")
include("model_IoK8sApiRbacV1alpha1ClusterRoleBinding.jl")
include("model_IoK8sApiRbacV1alpha1ClusterRoleBindingList.jl")
include("model_IoK8sApiRbacV1alpha1ClusterRoleList.jl")
include("model_IoK8sApiRbacV1alpha1PolicyRule.jl")
include("model_IoK8sApiRbacV1alpha1Role.jl")
include("model_IoK8sApiRbacV1alpha1RoleBinding.jl")
include("model_IoK8sApiRbacV1alpha1RoleBindingList.jl")
include("model_IoK8sApiRbacV1alpha1RoleList.jl")
include("model_IoK8sApiRbacV1alpha1RoleRef.jl")
include("model_IoK8sApiRbacV1alpha1Subject.jl")
include("model_IoK8sApiRbacV1beta1AggregationRule.jl")
include("model_IoK8sApiRbacV1beta1ClusterRole.jl")
include("model_IoK8sApiRbacV1beta1ClusterRoleBinding.jl")
include("model_IoK8sApiRbacV1beta1ClusterRoleBindingList.jl")
include("model_IoK8sApiRbacV1beta1ClusterRoleList.jl")
include("model_IoK8sApiRbacV1beta1PolicyRule.jl")
include("model_IoK8sApiRbacV1beta1Role.jl")
include("model_IoK8sApiRbacV1beta1RoleBinding.jl")
include("model_IoK8sApiRbacV1beta1RoleBindingList.jl")
include("model_IoK8sApiRbacV1beta1RoleList.jl")
include("model_IoK8sApiRbacV1beta1RoleRef.jl")
include("model_IoK8sApiRbacV1beta1Subject.jl")
include("model_IoK8sApiSchedulingV1PriorityClass.jl")
include("model_IoK8sApiSchedulingV1PriorityClassList.jl")
include("model_IoK8sApiSchedulingV1alpha1PriorityClass.jl")
include("model_IoK8sApiSchedulingV1alpha1PriorityClassList.jl")
include("model_IoK8sApiSchedulingV1beta1PriorityClass.jl")
include("model_IoK8sApiSchedulingV1beta1PriorityClassList.jl")
include("model_IoK8sApiSettingsV1alpha1PodPreset.jl")
include("model_IoK8sApiSettingsV1alpha1PodPresetList.jl")
include("model_IoK8sApiSettingsV1alpha1PodPresetSpec.jl")
include("model_IoK8sApiStorageV1StorageClass.jl")
include("model_IoK8sApiStorageV1StorageClassList.jl")
include("model_IoK8sApiStorageV1VolumeAttachment.jl")
include("model_IoK8sApiStorageV1VolumeAttachmentList.jl")
include("model_IoK8sApiStorageV1VolumeAttachmentSource.jl")
include("model_IoK8sApiStorageV1VolumeAttachmentSpec.jl")
include("model_IoK8sApiStorageV1VolumeAttachmentStatus.jl")
include("model_IoK8sApiStorageV1VolumeError.jl")
include("model_IoK8sApiStorageV1alpha1VolumeAttachment.jl")
include("model_IoK8sApiStorageV1alpha1VolumeAttachmentList.jl")
include("model_IoK8sApiStorageV1alpha1VolumeAttachmentSource.jl")
include("model_IoK8sApiStorageV1alpha1VolumeAttachmentSpec.jl")
include("model_IoK8sApiStorageV1alpha1VolumeAttachmentStatus.jl")
include("model_IoK8sApiStorageV1alpha1VolumeError.jl")
include("model_IoK8sApiStorageV1beta1CSIDriver.jl")
include("model_IoK8sApiStorageV1beta1CSIDriverList.jl")
include("model_IoK8sApiStorageV1beta1CSIDriverSpec.jl")
include("model_IoK8sApiStorageV1beta1CSINode.jl")
include("model_IoK8sApiStorageV1beta1CSINodeDriver.jl")
include("model_IoK8sApiStorageV1beta1CSINodeList.jl")
include("model_IoK8sApiStorageV1beta1CSINodeSpec.jl")
include("model_IoK8sApiStorageV1beta1StorageClass.jl")
include("model_IoK8sApiStorageV1beta1StorageClassList.jl")
include("model_IoK8sApiStorageV1beta1VolumeAttachment.jl")
include("model_IoK8sApiStorageV1beta1VolumeAttachmentList.jl")
include("model_IoK8sApiStorageV1beta1VolumeAttachmentSource.jl")
include("model_IoK8sApiStorageV1beta1VolumeAttachmentSpec.jl")
include("model_IoK8sApiStorageV1beta1VolumeAttachmentStatus.jl")
include("model_IoK8sApiStorageV1beta1VolumeError.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceColumnDefinition.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceConversion.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceDefinition.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceDefinitionCondition.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceDefinitionList.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceDefinitionNames.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceDefinitionSpec.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceDefinitionStatus.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceDefinitionVersion.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceScale.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresources.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceValidation.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1ExternalDocumentation.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1JSON.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1JSONSchemaProps.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1JSONSchemaPropsOrArray.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1JSONSchemaPropsOrBool.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1JSONSchemaPropsOrStringArray.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1ServiceReference.jl")
include("model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1WebhookClientConfig.jl")
include("model_IoK8sApimachineryPkgApiResourceQuantity.jl")
include("model_IoK8sApimachineryPkgApisMetaV1APIGroup.jl")
include("model_IoK8sApimachineryPkgApisMetaV1APIGroupList.jl")
include("model_IoK8sApimachineryPkgApisMetaV1APIResource.jl")
include("model_IoK8sApimachineryPkgApisMetaV1APIResourceList.jl")
include("model_IoK8sApimachineryPkgApisMetaV1APIVersions.jl")
include("model_IoK8sApimachineryPkgApisMetaV1DeleteOptions.jl")
include("model_IoK8sApimachineryPkgApisMetaV1Fields.jl")
include("model_IoK8sApimachineryPkgApisMetaV1GroupVersionForDiscovery.jl")
include("model_IoK8sApimachineryPkgApisMetaV1Initializer.jl")
include("model_IoK8sApimachineryPkgApisMetaV1Initializers.jl")
include("model_IoK8sApimachineryPkgApisMetaV1LabelSelector.jl")
include("model_IoK8sApimachineryPkgApisMetaV1LabelSelectorRequirement.jl")
include("model_IoK8sApimachineryPkgApisMetaV1ListMeta.jl")
include("model_IoK8sApimachineryPkgApisMetaV1ManagedFieldsEntry.jl")
include("model_IoK8sApimachineryPkgApisMetaV1MicroTime.jl")
include("model_IoK8sApimachineryPkgApisMetaV1ObjectMeta.jl")
include("model_IoK8sApimachineryPkgApisMetaV1OwnerReference.jl")
include("model_IoK8sApimachineryPkgApisMetaV1Patch.jl")
include("model_IoK8sApimachineryPkgApisMetaV1Preconditions.jl")
include("model_IoK8sApimachineryPkgApisMetaV1ServerAddressByClientCIDR.jl")
include("model_IoK8sApimachineryPkgApisMetaV1Status.jl")
include("model_IoK8sApimachineryPkgApisMetaV1StatusCause.jl")
include("model_IoK8sApimachineryPkgApisMetaV1StatusDetails.jl")
include("model_IoK8sApimachineryPkgApisMetaV1Time.jl")
include("model_IoK8sApimachineryPkgApisMetaV1WatchEvent.jl")
include("model_IoK8sApimachineryPkgRuntimeRawExtension.jl")
include("model_IoK8sApimachineryPkgUtilIntstrIntOrString.jl")
include("model_IoK8sApimachineryPkgVersionInfo.jl")
include("model_IoK8sKubeAggregatorPkgApisApiregistrationV1APIService.jl")
include("model_IoK8sKubeAggregatorPkgApisApiregistrationV1APIServiceCondition.jl")
include("model_IoK8sKubeAggregatorPkgApisApiregistrationV1APIServiceList.jl")
include("model_IoK8sKubeAggregatorPkgApisApiregistrationV1APIServiceSpec.jl")
include("model_IoK8sKubeAggregatorPkgApisApiregistrationV1APIServiceStatus.jl")
include("model_IoK8sKubeAggregatorPkgApisApiregistrationV1ServiceReference.jl")
include("model_IoK8sKubeAggregatorPkgApisApiregistrationV1beta1APIService.jl")
include("model_IoK8sKubeAggregatorPkgApisApiregistrationV1beta1APIServiceCondition.jl")
include("model_IoK8sKubeAggregatorPkgApisApiregistrationV1beta1APIServiceList.jl")
include("model_IoK8sKubeAggregatorPkgApisApiregistrationV1beta1APIServiceSpec.jl")
include("model_IoK8sKubeAggregatorPkgApisApiregistrationV1beta1APIServiceStatus.jl")
include("model_IoK8sKubeAggregatorPkgApisApiregistrationV1beta1ServiceReference.jl")


text:
abstract type BinaryModel end
abstract type BitModel <: BinaryModel end
abstract type SpinModel <: BinaryModel end

abstract type AbstractVariable end
abstract type AbstractBitVariable <: AbstractVariable end
abstract type AbstractSpinVariable <: AbstractVariable end


text:
export TimeBasedSamplingModel

using Random
import StatsBase: sample

"""
    TimeBasedSamplingModel(n_actions::Int, κ::Float64 = 1e-4)
"""
Base.@kwdef mutable struct TimeBasedSamplingModel{R} <: AbstractEnvironmentModel
    experiences::Dict{Any,Dict{Any,Any}} = Dict{Any,Dict{Any,Any}}()
    n_actions::Int
    κ::Float64 = 1e-4
    t::Int = 0
    last_visit::Dict{Tuple{Any,Any},Int} = Dict{Tuple{Any,Any},Int}()
    rng::R = Random.GLOBAL_RNG
end

function RLBase.update!(
    m::TimeBasedSamplingModel,
    t::Any,
    ::AbstractPolicy,
    ::AbstractEnv,
    ::Union{PreActStage,PostEpisodeStage},
)
    if length(t[:terminal]) > 0
        transition = (
            t[:state][end-1],
            t[:action][end-1],
            t[:reward][end],
            t[:terminal][end],
            t[:state][end],
        )
        update!(m, transition)
    end
end

function RLBase.update!(m::TimeBasedSamplingModel, transition::Tuple)
    s, a, r, d, s′ = transition
    if haskey(m.experiences, s)
        m.experiences[s][a] = (reward = r, terminal = d, nextstate = s′)
    else
        m.experiences[s] = Dict(a => (reward = r, terminal = d, nextstate = s′))
    end
    m.t += 1
    m.last_visit[(s, a)] = m.t
end

sample(model::TimeBasedSamplingModel) = sample(model.rng, model)

function sample(rng::AbstractRNG, m::TimeBasedSamplingModel)
    if length(m.experiences) > 0
        s = rand(rng, keys(m.experiences))
        a = rand(rng, 1:m.n_actions)
        r, d, s′ = get(m.experiences[s], a, (0.0, false, s))
        r += m.κ * sqrt(m.t - get(m.last_visit, (s, a), 0))
        s, a, r, d, s′
    else
        nothing
    end
end


text:
include("TypeDef.jl")
include("TypeUtil.jl")
include("Constructor.jl")

max_stars_repo_name: dcelisgarza/DDD

max_forks_repo_name: dcelisgarza/DDD


text:
HEIGHT = 600
WIDTH = 600
BACKGROUND = colorant"black"
num_humans = 40
chance_to_die = 0.25
movement_rate = 3

mutable struct Human       # Create new type to store each human and its attributes
    c::Circle              # Circle – part that is rendered on-screen, stores position
    state::Int             # State – 0 - normal, 1 - infected, 2 - recovered, 3 - dead
    timetocure::Int        # Timetocure – goes down if infected, recover when cure
end

humans = Human[]    # Array to store the population

for human_num in 1:num_humans   # Create population
    push!(humans, Human(
                Circle(rand(20:WIDTH - 20),rand(20:HEIGHT - 20), 5),    # Random position on-screen
                0,  # Start as normal
                2000    # 2000 frames to recover (or die)
                )
            )
end

humans[rand(1:num_humans)].state = 1    # Patient 0

function update()
    for i in 1:num_humans
        for j in 1:i
            if collide(humans[i].c, humans[j].c)    # Potential infection
                if humans[i].state == 1 && humans[j].state == 0     # One object in the circle must be infected, and the other must be normal
                    humans[j].state = 1 # Set the normal one to infected
                elseif humans[j].state == 1 && humans[i].state == 0
                    humans[i].state = 1 # Set the normal one to infected
                end
            end
        end
        if humans[i].state != 3     # Only move if not dead
            humans[i].c.x += rand(-movement_rate:3:movement_rate)
            humans[i].c.y += rand(-movement_rate:3:movement_rate)
        end
        if humans[i].state == 1    # Only reduce timetocure if infected
            humans[i].timetocure += -1
        end
        if humans[i].timetocure < 0 && humans[i].state == 1     # Recover or die
            if rand() > chance_to_die
                humans[i].state = 2     # Recover
            else
                humans[i].state = 3     # Die
            end
        end
        if humans[i].c.left <= 0 || humans[i].c.right >= WIDTH ||
                humans[i].c.top <= 0 || humans[i].c.bottom >= HEIGHT  # THEY MUST NOT LEAVE
            humans[i].c.x = rand(20:WIDTH - 20)     # Teleport to random x
            humans[i].c.y = rand(20:HEIGHT - 20)    # Teleport to random y
        end
    end
end

function draw()
    clear()
    for human in humans
        if human.state == 3
            draw(human.c, colorant"grey", fill=false)   # Dead – Grey ring
        elseif human.state == 2
            draw(human.c, colorant"green", fill=true)   # Recovered – Green circle
        elseif human.state == 1
            draw(human.c, colorant"red", fill=true)     # Infected – Red circle
        else
            draw(human.c, colorant"white", fill=true)   # Normal – White circle
        end
    end
end

max_stars_repo_name: kantel/julia

max_issues_repo_name: kantel/julia

max_forks_repo_name: kantel/julia


text:
# Test on DSGE
m = AnSchorfheide()
m <= Setting(:impulse_response_horizons, 10)
paras = map(x -> x.value, m.parameters)
Random.seed!(1793)
paras = convert(Matrix{Float64}, hcat(paras, paras + vcat(randn(2) ./ 100, zeros(14)))')
observables = [:obs_gdp, :obs_nominalrate, :z_t]

shocks = collect(keys(m.exogenous_shocks))
fp = dirname(@__FILE__)
jlddata = load(joinpath(fp, "../../reference/var_approx_dsge_irfs.jld2"))

@testset "Identified impulse responses from shocks to observables for a DSGE" begin
    out1 = impulse_responses(m, paras, :full, :cholesky, 4, observables, shocks, 1)
    out2 = impulse_responses(m, paras, :full, :choleskyLR, 4, observables, shocks, 1)
    out3 = impulse_responses(m, paras, :full, :maximum_business_cycle_variance, 4,
                             observables, shocks, 1)
    out4 = impulse_responses(m, paras, :full, :cholesky_long_run, 4, observables, shocks, 1)
    out5 = impulse_responses(m, paras, :full, :maxBC, 4, observables, shocks, 1)
    out6 = impulse_responses(m, paras, :full, :cholesky, 4, observables, shocks, 1,
                             flip_shocks = true)
    out7 = impulse_responses(m, paras, :full, :choleskyLR, 4, observables, shocks, 1,
                             flip_shocks = true)
    out8 = impulse_responses(m, paras, :full, :maxBC, 4, observables, shocks, 1,
                             flip_shocks = true)

    out9 = impulse_responses(m, paras, :full, :cholesky, 4, observables, shocks, 1,
                             use_intercept = true)
    out10 = impulse_responses(m, paras, :full, :choleskyLR, 4, observables, shocks, 1,
                              use_intercept = true)
    out11 = impulse_responses(m, paras, :full, :maxBC, 4, observables, shocks, 1,
                              use_intercept = true)
    out12 = impulse_responses(m, paras, :full, :cholesky, 4, observables, shocks, 1,
                              use_intercept = true, flip_shocks = true)
    out13 = impulse_responses(m, paras, :full, :choleskyLR, 4, observables, shocks, 1,
                              use_intercept = true, flip_shocks = true)
    out14 = impulse_responses(m, paras, :full, :maxBC, 4, observables, shocks, 1,
                              use_intercept = true, flip_shocks = true)

    out15 = impulse_responses(m, paras, :full, :cholesky, 4, observables, shocks, 1,
                              parallel = true)
    out16 = impulse_responses(m, paras, :full, :choleskyLR, 4, observables, shocks, 1,
                              parallel = true)
    out17 = impulse_responses(m, paras, :full, :maxBC, 4, observables, shocks, 1,
                              parallel = true)

    out18 = impulse_responses(m, paras[1, :], :mode, :cholesky, 4, observables, shocks, 1)
    out19 = impulse_responses(m, paras[1, :], :mode, :choleskyLR, 4, observables, shocks, 1)
    out20 = impulse_responses(m, paras[1, :], :mode, :maximum_business_cycle_variance, 4,
                              observables, shocks, 1)

    @test @test_matrix_approx_eq jlddata["exp_cholesky"] out1
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR"] out2
    @test @test_matrix_approx_eq jlddata["exp_maxBC"] out3
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR"] out4
    @test @test_matrix_approx_eq jlddata["exp_maxBC"] out5
    @test @test_matrix_approx_eq jlddata["exp_cholesky"] -out6
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR"] -out7
    @test @test_matrix_approx_eq jlddata["exp_maxBC"] -out8

    @test @test_matrix_approx_eq jlddata["exp_cholesky_int"] out9
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR_int"] out10
    @test @test_matrix_approx_eq jlddata["exp_maxBC_int"] out11
    @test @test_matrix_approx_eq jlddata["exp_cholesky_int"] -out12
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR_int"] -out13
    @test @test_matrix_approx_eq jlddata["exp_maxBC_int"] -out14

    @test @test_matrix_approx_eq jlddata["exp_cholesky"] out15
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR"] out16
    @test @test_matrix_approx_eq jlddata["exp_maxBC"] out17

    @test @test_matrix_approx_eq jlddata["exp_cholesky"][:, :, 1] out18
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR"][:, :, 1] out19
    @test @test_matrix_approx_eq jlddata["exp_maxBC"][:, :, 1] out20
end

# Test on a DSGEVAR.
dsgevar = DSGEVAR(m, shocks, "ss0")
DSGE.update!(dsgevar, lags = 4, observables = observables, λ = 1.)

@testset "Impulse responses identified from shocks to observables for a DSGE when using a DSGEVAR" begin
    out1 = impulse_responses(dsgevar, paras, :full, :cholesky, 1)
    out2 = impulse_responses(dsgevar, paras, :full, :choleskyLR, 1)
    out3 = impulse_responses(dsgevar, paras, :full, :maximum_business_cycle_variance, 1)
    out4 = impulse_responses(dsgevar, paras, :full, :cholesky_long_run, 1)
    out5 = impulse_responses(dsgevar, paras, :full, :maxBC, 1)
    out6 = impulse_responses(dsgevar, paras, :full, :cholesky, 1,
                             flip_shocks = true)
    out7 = impulse_responses(dsgevar, paras, :full, :choleskyLR, 1,
                             flip_shocks = true)
    out8 = impulse_responses(dsgevar, paras, :full, :maxBC, 1,
                             flip_shocks = true)

    out9 = impulse_responses(dsgevar, paras, :full, :cholesky, 1,
                             use_intercept = true)
    out10 = impulse_responses(dsgevar, paras, :full, :choleskyLR, 1,
                              use_intercept = true)
    out11 = impulse_responses(dsgevar, paras, :full, :maxBC, 1,
                              use_intercept = true)
    out12 = impulse_responses(dsgevar, paras, :full, :cholesky, 1,
                              use_intercept = true, flip_shocks = true)
    out13 = impulse_responses(dsgevar, paras, :full, :choleskyLR, 1,
                              use_intercept = true, flip_shocks = true)
    out14 = impulse_responses(dsgevar, paras, :full, :maxBC, 1,
                              use_intercept = true, flip_shocks = true)

    out15 = impulse_responses(dsgevar, paras, :full, :cholesky, 1,
                              parallel = true)
    out16 = impulse_responses(dsgevar, paras, :full, :choleskyLR, 1,
                              parallel = true)
    out17 = impulse_responses(dsgevar, paras, :full, :maxBC, 1,
                              parallel = true)

    out18 = impulse_responses(dsgevar, paras[1, :], :mode, :cholesky, 1)
    out19 = impulse_responses(dsgevar, paras[1, :], :mode, :choleskyLR, 1)
    out20 = impulse_responses(dsgevar, paras[1, :], :mode, :maxBC, 1)

    out21 = impulse_responses(dsgevar, paras, :full, :cholesky, 4,
                              observables, shocks, 1)
    out22 = impulse_responses(dsgevar, paras, :full, :choleskyLR, 4,
                              observables, shocks, 1)
    out23 = impulse_responses(dsgevar, paras, :full, :maxBC, 4,
                              observables, shocks, 1)

    out24 = impulse_responses(dsgevar, paras[1, :], :mode, :cholesky, 4,
                              observables, shocks, 1)
    out25 = impulse_responses(dsgevar, paras[1, :], :mode, :choleskyLR, 4,
                              observables, shocks, 1)
    out26 = impulse_responses(dsgevar, paras[1, :], :mode, :maxBC, 4,
                              observables, shocks, 1)

    # Not testing but just checking for no errors when creating a MeansBands
    mb = impulse_responses(dsgevar, paras, :full, :cholesky, 1,
                           create_meansbands = true, test_meansbands = true)
    mb = impulse_responses(dsgevar, paras, :full, :choleskyLR, 1,
                           create_meansbands = true, test_meansbands = true)
    mb = impulse_responses(dsgevar, paras, :full, :maxBC, 1,
                           create_meansbands = true, test_meansbands = true)

    @test @test_matrix_approx_eq jlddata["exp_cholesky"] out1
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR"] out2
    @test @test_matrix_approx_eq jlddata["exp_maxBC"] out3
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR"] out4
    @test @test_matrix_approx_eq jlddata["exp_maxBC"] out5
    @test @test_matrix_approx_eq jlddata["exp_cholesky"] -out6
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR"] -out7
    @test @test_matrix_approx_eq jlddata["exp_maxBC"] -out8

    @test @test_matrix_approx_eq jlddata["exp_cholesky_int"] out9
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR_int"] out10
    @test @test_matrix_approx_eq jlddata["exp_maxBC_int"] out11
    @test @test_matrix_approx_eq jlddata["exp_cholesky_int"] -out12
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR_int"] -out13
    @test @test_matrix_approx_eq jlddata["exp_maxBC_int"] -out14

    @test @test_matrix_approx_eq jlddata["exp_cholesky"] out15
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR"] out16
    @test @test_matrix_approx_eq jlddata["exp_maxBC"] out17

    @test @test_matrix_approx_eq jlddata["exp_cholesky"][:, :, 1] out18
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR"][:, :, 1] out19
    @test @test_matrix_approx_eq jlddata["exp_maxBC"][:, :, 1] out20

    @test @test_matrix_approx_eq jlddata["exp_cholesky"] out21
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR"] out22
    @test @test_matrix_approx_eq jlddata["exp_maxBC"] out23

    @test @test_matrix_approx_eq jlddata["exp_cholesky"][:, :, 1] out24
    @test @test_matrix_approx_eq jlddata["exp_choleskyLR"][:, :, 1] out25
    @test @test_matrix_approx_eq jlddata["exp_maxBC"][:, :, 1] out26
end


text:
include("model_TokenBucket.jl")
include("model_RateLimiter.jl")
include("model_Drive.jl")
include("model_Error.jl")
include("model_NetworkInterface.jl")
include("model_InstanceActionInfo.jl")
include("model_Logger.jl")
include("model_InstanceInfo.jl")
include("model_BootSource.jl")
include("model_CpuTemplate.jl")
include("model_MachineConfiguration.jl")
include("model_PartialDrive.jl")


text:
using Base.Test
using CUDArt
using CUDNN

include("pool.jl")

using CUDNN: PD, cudnnPoolingForward, CUDNN_POOLING_MAX
psize = 2
pd = PD(2, psize, 0, 1, CUDNN_POOLING_MAX)
x = reshape(Float32[1:20;], 5, 4, 1, 1); tx = CudaArray(x); @show x
y = zeros(Float32, cudnnGetPoolingNdForwardOutputDim(pd, tx)); ty = CudaArray(y); @show y

# y = to_host(cudnnPoolingForward(tx, ty; pd=pd)); @show y
y = to_host(cudnnPoolingForward(tx, ty; pd=pd)); @show y
y2 = kudnnPoolingForward(x,y; window=psize)
@test_approx_eq y y2

using CUDNN: cudnnPoolingBackward
dx = zeros(Float32, size(x)); tdx = CudaArray(dx);
dy = rand(Float32, size(y)); tdy = CudaArray(dy); @show dy
dx = to_host(cudnnPoolingBackward(ty, tdy, tx, tdx; pd=pd)); @show dx
dx2 = kudnnPoolingBackward(y, dy, x, dx; window=psize); @show dx2
@test_approx_eq dx dx2

psize = 8
pd = PD(2, psize, 0, 1, CUDNN_POOLING_MAX)
x = rand(Float32,64,64,3,128); tx = CudaArray(x)
y = zeros(Float32, cudnnGetPoolingNdForwardOutputDim(pd, tx)); ty = CudaArray(y);
y = to_host(cudnnPoolingForward(tx, ty; pd=pd));
y2 = kudnnPoolingForward(x,y; window=psize)
@test_approx_eq y y2

dx = zeros(Float32, size(x)); tdx = CudaArray(dx);
dy = rand(Float32, size(y)); tdy = CudaArray(dy);
dx = to_host(cudnnPoolingBackward(ty, tdy, tx, tdx; pd=pd));
dx2 = kudnnPoolingBackward(y, dy, x, dx; window=psize);
@test_approx_eq dx dx2


text:
import .Unitful: Quantity, FreeUnits

function to_num_str(p::AbstractParticles{T}, d=3, ds=d-1) where T <: Quantity
    s = pstd(p)
    if s.val < eps(p)
        string(pmean(p))
    else
        string(pmean(p), " ± ", s)
    end
end

for PT in ParticleSymbols

    @eval begin
        function Base.promote_rule(::Type{Quantity{S,D,U}}, ::Type{$PT{T,N}}) where {S, D, U, T, N}
            NT = promote_type(Quantity{S,D,U},T)
            $PT{NT,N}
        end

        function Base.convert(::Type{$PT{Quantity{S,D,U},N}}, y::Quantity) where {S, D, U, T, N}
            $PT{Quantity{S,D,U},N}(fill(y, N))
        end

        function Unitful.uconvert(a::Unitful.FreeUnits, y::$PT)
            $PT(Unitful.uconvert.(a, y.particles))
        end
    end

    for op in (*, /)
        f = nameof(op)
        @eval begin
            function Base.$f(p::$PT{T,N}, y::Quantity{S,D,U}) where {S, D, U, T, N}
                NT = promote_type(T, S)
                $PT{Quantity{NT,D,U},N}($(op).(p.particles , y))
            end

            function Base.$f(p::$PT{T,N}, y::Quantity{S,D,U}) where {S, D, U, T <: Quantity, N}
                QT = Base.promote_op($op, T, typeof(y))
                $PT{QT,N}($(op).(p.particles, y))
            end

            # Below is just the reverse signature of above
            function Base.$f(y::Quantity{S,D,U}, p::$PT{T,N}) where {S, D, U, T <: Quantity, N}
                QT = Base.promote_op($op, typeof(y), T)
                $PT{QT,N}($(op).(y, p.particles))
            end

            function Base.$f(p::$PT, y::FreeUnits)
                $PT($(op).(p.particles, y))
            end
        end

    end
end


text:
module ParticleAttractor

import Gloria: onevent!, render!, update!
using Gloria: Gloria, Window, AbstractObject, Event, Layer, Scene

struct Controls <: AbstractObject end

struct World <: AbstractObject
    action::Ref{Int}
    objects::Vector{AbstractObject}
end

mutable struct Particle <: AbstractObject
    x::Float64
    y::Float64
    vx::Float64
    vy::Float64
    accel::Float64
    resistance::Float64
end

function Gloria.onevent!(::Controls, e::Event{:mousebutton_down})
    world.action[] += 2 - e.button
end
function Gloria.onevent!(::Controls, e::Event{:mousebutton_up})
    world.action[] -= 2 - e.button
end
function Gloria.onevent!(::Controls, e::Event{:key_down})
    Gloria.iskey(e, "escape") && Gloria.quit!(window, e)
end

function Gloria.update!(world::World, ::Gloria.AbstractLayer, t, dt)
    mouse = Gloria.getmousestate()

    # for obj1 in world.objects, obj2 in world.objects
    #     Gloria.update!(obj1, obj2, t, dt)
    # end
    for obj in world.objects
        Gloria.update!(obj, mouse, t, dt)
    end
end

function Gloria.update!(obj::Particle, mouse, t, dt)
    Δx, Δy = mouse.x - obj.x, mouse.y - obj.y
    obj.vx += dt * (world.action[] * obj.accel * Δx / (Δx^2 + Δy^2 + 1) - obj.vx * obj.resistance)
    obj.vy += dt * (world.action[] * obj.accel * Δy / (Δx^2 + Δy^2 + 1) - obj.vy * obj.resistance)
    obj.x += obj.vx
    obj.y += obj.vy
    obj.x = mod(obj.x, width)
    obj.y = mod(obj.y, height)
end

@fastmath function Gloria.update!(obj1::Particle, obj2::Particle, t, dt)
    Δx, Δy = obj1.x - obj2.x, obj1.y - obj2.y
    f = 1e-2 * dt * (obj1.accel / (Δx^2 + Δy^2 + 1))
    obj1.vx += f*Δx
    obj1.vy += f*Δy
end

function Gloria.render!(::Layer, obj::World, frame, fps)
    Gloria.render!(window, obj, frame, fps)
end
function Gloria.render!(window::Window, world::World, frame, fps)
    Gloria.setcolor!(window, 100, 100, 100, 255)
    Gloria.clear!(window)
    for obj in world.objects
        Gloria.render!(window, obj, frame, fps)
    end
    Gloria.present!(window)
end

function Gloria.render!(window::Window, obj::Particle, frame, fps)
    Gloria.setcolor!(window, 255, 255, 255, 255)
    Gloria.drawpoint!(window, Int(floor(obj.x)), Int(floor(obj.y)))
    # Gloria.Graphics.fillrect(window, Int(floor(obj.x)), Int(floor(obj.y)), 20, 20)
    # Gloria.Graphics.setcolor(window, 0, 0, 0, 255)
    # Gloria.Graphics.drawrect(window, Int(floor(obj.x)), Int(floor(obj.y)), 20, 20)
end

function main(; keepalive=true)
    @eval begin
        const width, height = 1600, 1000
        const world = World(
            Ref{Int}(false),
            AbstractObject[Particle(
                width/2 + 50*(rand() - 0.5), height/2 + 50*(rand() - 0.5),
                0, 0,
                200, 0.5
            ) for _ in 1:15000]
        )
        const controls_layer = Layer([Controls()], show=false)
        const scene = Scene(Layer([world]), controls_layer)
        const window = Window("Particle Attractor", width, height, scene, fullscreen=false)
    end

    Gloria.run!(window)
    keepalive && wait(window)
end

end # module


text:
export ARC_step_computation

function ARC_step_computation(h::Float64,
                              g::Float64,
                              Δ::Float64;
                              kwargs...)

    discr1 = (h)^2-4(g/Δ)
    discr2 = (h)^2+4(g/Δ)

    if h>0
      if g>0
        d=(-2*g)/(h+sqrt(discr2))
      else
        d=(-2*g)/(h+sqrt(discr1))
      end
    else
      if g<0
        d=(-h+sqrt(discr1))/(2/Δ)
      else
        d=(-h+sqrt(discr2))/(-2/Δ)
      end
    end

    return d
  end


text:
# Note this is an altered verion of the file from

#  http://marcusps.github.com
#  Specifically from  https://github.com/BBN-Q/QuantumInfo.jl/blob/master/src/open-systems.jl
#  Original authors: Blake Johnson and Marcus da Silva

# Altered by Robin Harper.

# Original Copyright Notice for QuantumInfo.jl stuff

#Copyright (c) 2014: Raytheon BBN Technologies.

# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# With respect to changes made and stuff added:

# Copyright Robin Harper 2015-2020

## I needed to make a few changes and just did it locally. See below.
## I have also decoupled it from using the "Cliffords" package as I don't actually need that one.

#import Base.writemime

import Base.show

# Changed slightly from the version on BitBucket (i.e. the original author's version)
# I added a translate in the pauliliou conversion functions, so that the basis was IXYZ (rather than IXZY)
# I removed a division by d when converting from liou 2 choi (and vice versa) (slightly different conventions)
# The choi2liou uses a different involution - keeping as column stacked.
# There is also a dimensional factor depending on which convention we use.

mat( v::Vector, r=round(Int,sqrt(length(v))), c=round(Int,sqrt(length(v))) ) = reshape( v, r, c )

liou( left::T, right::T ) where T<:AbstractMatrix = kron( transpose(right), left )

## So conj, which equals transpose(m'), ie the liou of m is based on := m \rho m' = kron(conj(m),m) * vec(\rho)
liou( m::T ) where T<:AbstractMatrix = kron( conj(m), m )
using SparseArrays

# This violates a large number of programming principles, esp no repetition, but it should be clear.
# The purpose behind the repl style dots is in case you mistakenly try and print say a 1000x1000 Matrix
# At least on my computer this would hang Jupyter.
function latexArray(m)
  todisplay = 20
  if size(m)[1] < 20
    todisplay =size(m)[2]
  end
  start = string("\\left(\\begin{array}{*{$todisplay}c}")
  if ndims(m) == 2
      (a,b) = size(m)
      if b > 20
        if a > 20
            for i = 1:6
              for j = 1:6
                  start = "$start $(m[i,j]) &"
              end
              if i==2
                start = "$start \\cdots &"
              else
                start = "$start  &"
              end
              for j = (b-5):b-1
                  start = "$start $(m[i,j]) &"
              end
              for j = b:b
                  start = "$start $(m[i,j])"
              end
              start= "$start \\\\"
            end
            start = "$start & \\vdots & & & & & \\ddots & & & & & \\vdots\\\\ "
            for i = a-5:a
              for j = 1:6
                  start = "$start $(m[i,j]) &"
              end
              if i==a-1
                start = "$start \\cdots &"
              else
                start = "$start  &"
              end
              for j = (b-5):b-1
                  start = "$start $(m[i,j]) &"
              end
              for j = b:b
                  start = "$start $(m[i,j])"
              end
              start= "$start \\\\"
            end
            start = "$start \\end{array}\\right)"

        else # a < 20 b > 20
            for i = 1:a
              for j = 1:6
                  start = "$start $(m[i,j]) &"
              end
              if i == 2 || i == a-1
                start = "$start \\cdots &"
              else
                start = "$start  &"
              end
              for j = (b-5):b-1
                  start = "$start $(m[i,j]) &"
              end
              for j = b:b
                  start = "$start $(m[i,j])"
              end
              start= "$start \\\\"
            end
            start = "$start \\end{array}\\right)"
         end
      else
        if a > 20 # b < 20
          for i = 1:6
              for j = 1:b
                  start = "$start $(m[i,j]) &"
              end
              start= "$start \\\\"
          end
          start = "$start &  \\vdots "

          for i = 1:b-3
              start = "$start & "
          end
          start = "$start \\vdots \\\\"
          for i = a-5:a
               for j = 1:b-1
                  start = "$start $(m[i,j]) &"
              end
              for j = b:b
                 start = "$start $(m[i,j]) "
              end
              start= "$start \\\\"
            end
            start = "$start \\end{array}\\right)"
        else
        for i = 1:size(m,1)
          for j = 1:size(m,2)-1
            start = "$start $(m[i,j]) &"
          end
          for j = size(m,2):size(m,2)
            start = "$start $(m[i,j])"
          end
          start= "$start \\\\"
        end
        start = "$start \\end{array}\\right)"
      end
    end
    return start
  end
  return "NOT A MATRIX?"
end

function nicePrint(m)
  start = string("\\begin{equation*} ")
  start = start*latexArray(m)
  start = start*string("\\\\\\end{equation*}")
  return start
end

show(stream, ::MIME"text/latex", x::AbstractMatrix) = write(stream, nicePrint(x))

#writemime(io, ::MIME"text/latex", x::Matrix) = write(io, nicePrint(x))

# NOTE USING the Rc involution. 1,3,2,4 or 4,2,1,3?
function choi_liou_involution( r::Matrix )
  d = round(Int, sqrt(size(r,1)) )
  rl = reshape( r, (d, d, d, d) )
  rl = permutedims( rl, [1,3,2,4] )
  reshape( rl, size(r) )
end

# RH changed again: this was 3, 4, 1 2 - changed to 2, 1, 4, 3 i.e. L(x \otimes y)->L(y \otimes x)
function swap_involution( r::Matrix )
  d = round(Int, sqrt(size(r,1)) )
  rl = reshape( r, (d, d, d, d) )
  rl = permutedims( rl, [2,1,4,3] )
  reshape( rl, size(r) )
end

"""
  choi2liou

  Takes a superoperator in choi matrix form and returns the liouville superoperator (computational basis)
"""
function choi2liou( r::Matrix  )
  choi_liou_involution( r )
end

"""
  liou2choi

  Take a liouville superoperator (computational basis) and return the choi matrix
"""
function liou2choi( r::Matrix )
  choi_liou_involution( r )
end

"""
  takes a liouville superoperator (computational basis) and returns the Chi matrix
  (basically the choi matrix in Pauli basis)
"""
function liou2choiX(r::Matrix)
  d = round(Int, sqrt(size(r,1)) )
  rl = reshape( r, (d, d, d, d) )
  rl = permutedims( rl, [3,1,4,2] )
  reshape( rl, size(r) )'
end

"""
  takes the Chi matrix (Choi matrix in Pauli basis) and return the liouville superoperator, computaitonal basis
"""
function choiX2liou(r::Matrix)
  d = round(Int, sqrt(size(r,1)) )
  rl = reshape( r, (d, d, d, d) )
  rl = permutedims( rl, [3,1,4,2] )
  reshape( rl, size(r) )
end

"""
  takes the choi matrix and returns the kraus operators.
   This stays the same, save that we need to take into account dimensional factors.
   Note slight negative eigenvalue (rounding can cause problems). Here I round to 15 digits.
"""
function choi2kraus(r::Matrix{T}) where T
  d = sqrt(size(r,1))
  (vals,vecs) = eigen( d*r )
  #vals = eigvals( sqrt(size(r,1))*r )
  kraus_ops = Matrix{T}[]
  for i in 1:length(vals)
    push!(kraus_ops, sqrt(round(vals[i],digits=15,RoundToZero))*mat(vecs[:,i]))
  end
  factor = tr(sum([k'*k for k in kraus_ops]))
  kraus_ops = kraus_ops/sqrt(factor/d)
  kraus_ops
end

"""
  Takes a vector of kraus operators (matrices) and
  converts them to a liouville superoperator (computational basis)
"""
function kraus2liou( k::Vector{Matrix{T}}) where T
  l = zeros(T,map(x->x^2,size(k[1])))
  for i in 1:length(k)
    # The Adjoint is now lazy, so we need to copy it.
    l = l + liou(k[i],copy(k[i]'))
  end
  l
end

"""
  Takes a liouville superoperator (computational basis) and
  returns a vector of the equivalen Krawu vectors
"""
function liou2kraus( l::Matrix )
  choi2kraus( liou2choi( l ) )
end

"""
  Takes a vector of kraus operators and returns the choi matrix
"""
function kraus2choi(k::Vector{Matrix{T}} ) where T
  liou2choi(kraus2liou(k))
  # Seems to fail for some kraus vectors.
  #c = zeros(T,map(x->x^2,size(k[1])))
  #for i in 1:length(k)
  #  c = vec(k[i])*vec(k[i])'
  #end
  #c/sqrt(size(c,1))
end

_translate(v) = [x==2 ? 3 : x== 3 ? 2 : x for x in v]

_Paulis = [ [1 0im;0 1],[0im 1;1 0],[0 -im;im 0],[1 0im;0 -1]]

_num2quat(n,l) = map(s->parse(Int,s),collect(string(n,base=4,pad=l)))

_toPauli(p) = reduce(kron,[_Paulis[x+1] for x in p])

"""
  Converts a liouville superoperator in the Pauli basis
  to one in the computational basis. Order of Paulis is I,X,Y and Z.
"""
function pauliliou2liou( m::Matrix )
  if size(m,1) != size(m,2)
    error("Only square matrices supported")
  elseif size(m,1) != 4^(floor(log2(size(m,1))/2))
    error("Only matrices with dimension 4^n supported.")
  end
  dsq = size(m,1)
  res = zeros(ComplexF64,size(m))
  l = round(Int,log2(dsq)/2)
  for i=1:dsq
    for j=1:dsq
      res += m[i,j] * vec(_toPauli(_num2quat(i-1,l))) * vec(_toPauli(_num2quat(j-1,l)))' / sqrt(dsq)
    end
  end
  res
end

"""
  Converts a liouville superoperator in the computaional basis
  to one in the pauli basis. Order of Paulis is I,X,Y and Z.
"""
function liou2pauliliou( m::Matrix{T} ) where T
  if size(m,1) != size(m,2)
    error("Only square matrices supported")
  elseif size(m,1) != 4^(floor(log2(size(m,1))/2))
    error("Only matrices with dimension 4^n supported.")
  end
  dsq = size(m,1)
  res = zeros(ComplexF64,size(m))
  l = round(Int,log2(dsq)/2)
  m = sparse(m)
  Pvecs = [sparse(vec(Juqst._toPauli(Juqst._num2quat(i-1,l)))) for i=1:dsq]
  Pvecd = [x' for x in Pvecs]
  sqr = sqrt(dsq)
  for i=1:dsq
    for j=1:dsq
      res[i,j] = Pvecd[i] * m * Pvecs[j]  / sqr
    end
  end
  return res
end

""" Takes a choi matrix and returns the Chi Matrix
  Note the basis here has changed from marcusps version,
 The rightmost paulis are varying the quickest.
  Also note the transpose ( .' ) - this makes it ROW stacking
  So for instance
  (0 -im//im 0) vectorises as (0 -im im 0) (unlike column used elsewhere where its (0 im -im 0))
"""
function choi2chi( m::Matrix{T} ) where T
  if size(m,1) != size(m,2)
    error("Only square matrices supported")
  elseif size(m,1) != 4^(floor(log2(size(m,1))/2))
    error("Only matrices with dimension 4^n supported.")
  end

  dsq = size(m,1)
  dim = round(Int(log2(dsq)/2))
  pauliTranslate=vec(_toPauli(_num2quat(0,dim)))
  for i = 2:dsq
    pauliTranslate=hcat(pauliTranslate,vec(transpose(_toPauli(_num2quat(i-1,dim)))))
  end
  pauliTranslate'*m*pauliTranslate
end

function pauliliou2chi( m::Matrix{T}) where T
  choi2chi(liou2choi(pauliliou2liou(m)))
end

#"""
#Returns a superoperator that replaces the input with a maximally
#mixed state with probability p, and leaves it unchanged with probability (1-p).
#"""
#function depol( d::Int, p=1.0 )
#  choi2liou( p * Matrix(I,d^2,d^2)/d^2 + (1-p) * projector(_max_entangled_state(d)) )
#end

"""
Given a superoperator, it extracts the closest superoperator (in Frobenius norm)
that is unital. The result may not be completely positive.
"""
function unitalproj( m::Matrix{T} ) where T
  d2 = size(m,1)
  d  = round(Int,sqrt(d2))
  id = projector(normalize(vec(eye(d))))
  id*m*id + (I-id)*m*(I-id)
end

# tweaked to increase eps slightly was getting a trivial false !cp right on the boundary.
"""
  iscp(m;tol)

  Returns whether is completely positivel.
  Assumes input is in liouville basis (not pauli-liouville - use pauliliou2liou)
  Converts to choi and checks the eigenvalues.
  -- tweaked to increase eps slightly was getting a trivial false !cp right on the boundary.
"""
function iscp(m; tol=0.0)
    evs = eigvals(liou2choi(m))
    tol = tol==0.0 ? 1.01*eps(abs.(one(eltype(m)))) : tol
    all(real(evs) .> -tol) && all(abs.(imag(evs)) .< tol)
end

"""
  istp(m;tol)

  Returns whether is trace perserving..
  Assumes input is in liouville basis (not pauli-liouville - use pauliliou2liou)
"""
function istp(m; tol=0.0)
    tol = tol==0.0 ? eps(abs.(one(eltype(m)))) : tol
    dsq = size(m,1)
    d = round(Int,sqrt(dsq))
    norm(m'*vec(eye(d))-vec(eye(d)),Inf) < tol
end

"""
  ischannel(m;tol)

  Returns whether is the liouville superoperator is trace perserving and completely positive.
  Assumes input is in liouville basis (not pauli-liouville - use pauliliou2liou)
"""
function ischannel(m; tol=0.0)
    #println(iscp(m,tol=tol))
    #println(istp(m,tol=tol))
    iscp(m,tol=tol) && istp(m,tol=tol)
end

"""
  unital(m;tol)

  Returns whether is the liouville superoperator is unital.
  Assumes input is in liouville basis (not pauli-liouville - use pauliliou2liou)
"""
function isunital(m; tol=0.0)
    tol = tol==0.0 ? eps(abs(one(eltype(m)))) : tol
    dsq = size(m,1)
    d = round(Int,sqrt(dsq))
    norm(m*vec(eye(d))-vec(eye(d)),Inf) < tol
end

"""
Computes the unitary CP map closest (interferometrically) to a given CP map.
See D. Oi, [Phys. Rev. Lett. 91, 067902 (2003)](http://journals.aps.org/prl/abstract/10.1103/PhysRevLett.91.067902)
"""
function nearestu(l)
    c = liou2choi(l)
    vals,vecs = eig(Hermitian(c))
    imax = indmax(vals)
    Λ = mat(vecs[:,imax])
    U,Σ,V = svd(Λ)
    W = U*V'
    return kron(conj(W),W)
end

"""
function makeSuper(u)

Takes an operator and turns into a superoperator. Pauli basis.
"""
function makeSuper(u)
    return round.(real(liou2pauliliou(liou(u))),digits=10)
end

# Some more stuff just to make life easier.

starting=[[1 0],[0 1]]
⊗ = kron
"""
  pass in a qubit up/down state e.g. [0 0] for two qubits both in |0> state
  returns a vector of the qubits (in this case [1 0]⊗[1 0])
"""
function buildvec(ar)
    foldl(⊗,map(x->starting[x+1],ar))
end

"""
  pass in a qubit up/down state e.g. [0 0] for two qubits both in |0> state
  returns a density matrix of the qubits (in this case ([1 0]⊗[1 0])'*([1 0]⊗[1 0]))
"""
function buildDensity(ar)
    v = buildvec(ar)
    v'*v
end

"""
  pass in a density matrix, gives you the super vector that corresponds to it
"""
function getSuperVec(density)
    d = size(density,1)
    l = round(Int,log2(d))
    real(vec([(tr(Juqst._toPauli(Juqst._num2quat(i,l))*(density))) for i = 0:(d^2-1)]))
end

_num2bin(n,l) = map(s->parse(Int,s),collect(string(n,base=2,pad=l)))
"""
  returns an array of the 'measurement' operators that extract each of the z measurements
  e.g. for two qubits will return the II, IZ, ZI and ZZ measurements
"""
function genZs(noQubits)
    return map(x->getSuperVec(buildDensity(x)),[_num2bin(i,noQubits) for i=0:(2^noQubits-1)]);
end

"""
  Helper function for labeling graphs, pass in the qubits get the string of Is and Zs
  e.g. with two you get ["00","01","10","11"]
"""
function genLabels(noQubits)
    return [string(n,base=2,pad=noQubits) for n = 0:(noQubits^2-1)];
end

"""
  Helper function
  Pass in the state, the noise (superOperator) and the measurements - use allZs to generate)
  returns the mapped function.
"""
function measure(s,measureNoise,allZs)
    map(x->x'*measureNoise*s,allZs)
end
using Combinatorics

pn=["I","X","Y","Z"]
ttn=["↑","↓"]

"""
  Helper function (chart axis)
  return all the paulis for a certain number of qubits as a list of strings
"""
 function genPauliLabels(noQubits)
    return  map(x->foldl(*,map(y->pn[parse(Int,y)+1],x)),[collect(string(i,base=4,pad=noQubits)) for i=0:(4^noQubits-1)])
end

"""
  Helper function (chart axis)
  return all the ups and downs for a certain number of qubits as a list of strings
"""
function genArrows(noQubits)
    return map(x->foldl(*,map(y->ttn[parse(Int,y)+1],x)),[collect(string(i,base=2,pad=noQubits)) for i=0:(2^noQubits-1)])
end


text:
function rcond(A::LowerTriangular{Float64, Matrix{Float64}})
    n = LinAlg.checksquare(A)
    n == 1 && return A[1,1] == 0 ? 0.0 : 1.0
    work = Array(Float64, (3n,))
    iwork = Array(Int, (n,))
    info = zeros(Int, 1)
    rc = zeros(1)
    ccall(("dtrcon_", Base.liblapack_name), Void,
        (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ref{Int}, Ptr{Float64}, Ref{Int}, Ptr{Float64},
        Ptr{Float64}, Ptr{Int}, Ptr{Int}),
        "1", "L", "N", n, A.data, n, rc, work, iwork, info)
    info[1] == 0 || error("dtrcon_ returned error code $(info[1])")
    return rc[1]
end

max_stars_repo_name: dmbates/MixedMod

max_issues_repo_name: dmbates/MixedMod

max_forks_repo_name: dmbates/MixedMod


text:
module WaveNN

using LibSndFile

end


text:
using BinaryBuilder

name = "LMDB"
version = v"0.9.27"

# No sources, we're just building the testsuite
sources = [
    ArchiveSource("https://git.openldap.org/openldap/openldap/-/archive/LMDB_$(version)/openldap-LMDB_$(version).tar.gz",
                  "752a3ebd4bbfa1830dff2ca4f5ff4c4be97da843810626d5dd9e2e4e5484a399"),
]

# Bash recipe for building across all platforms
# - CC: mdb_env_close0 segfaults on MacOS because CC is set to gcc in Makefile
# - rm: remove man files (it does not make sense)
# - exeext: Makefile does not support extensions - need to rename execuables manually
script = raw"""
cd ${WORKSPACE}/srcdir/openldap-*/libraries/liblmdb
make CC=${CC} SOEXT=.${dlext} -j${nproc}
make CC=${CC} SOEXT=.${dlext} ILIBS=liblmdb.${dlext} prefix=${prefix} install
rm -rf ${prefix}/share
if [ -n "${exeext}" ]; then
    for f in ${bindir}/mdb_*; do
        mv "${f}" "${f}${exeext}"
    done
fi
install_license ${WORKSPACE}/srcdir/openldap-*/libraries/liblmdb/LICENSE
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = supported_platforms()

# The products that we will ensure are always built
products = [
    ExecutableProduct("mdb_copy", :mdb_copy),
    ExecutableProduct("mdb_dump", :mdb_dump),
    ExecutableProduct("mdb_load", :mdb_load),
    ExecutableProduct("mdb_stat", :mdb_stat),
    LibraryProduct("liblmdb", :liblmdb),
]

# Dependencies that must be installed before this package can be built
dependencies = [
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)

max_stars_repo_name: sharanry/Yggdrasil

max_issues_repo_name: sharanry/Yggdrasil

max_forks_repo_name: sharanry/Yggdrasil


text:
# please instantiate ./test/Manifest.toml for this

using JLD2, RollingFunctions
import Statistics

# ========================================
# Asymmetric Truncated Fuzz Test Fixtures
# ========================================

# format: [(values, window_size, expected_medians)]

asym_trunc_fixtures = Vector{Tuple{Vector{Float64}, Integer, Vector{Float64}}}(undef, 0)

function naive_asymmetric_truncated_median(input, window_size)
    if window_size > length(input)
        window_size = length(input)
    end

    if window_size |> iseven
        alpha = (window_size / 2 + 1) |> Int
    else
        alpha = ((window_size + 1) / 2) |> Int
    end
    growing_phase_inds = [1:k for k in alpha:window_size]
    rolling_phase_inds = [k:k + window_size - 1 for k in 2:(length(input) - window_size + 1)]
    shrinking_phase_inds = [length(input) - k + 1:length(input) for k in window_size - 1:-1:alpha]
    phase_inds = [growing_phase_inds; rolling_phase_inds; shrinking_phase_inds]
    output = [Statistics.median(input[inds]) for inds in phase_inds]
    return output
end

for i in 1:100
    N = rand(1:40)
    window_size = rand(1:50)
    values = rand(N)
    expected_medians = naive_asymmetric_truncated_median(values, window_size)
    push!(asym_trunc_fixtures, (values, window_size, expected_medians))
end

asym_trunc_filename = dirname(@__FILE__) * "/asym_trunc.jld2"
@save asym_trunc_filename asym_trunc_fixtures

max_stars_repo_name: Firionus/FastRunningMedian

max_issues_repo_name: Firionus/FastRunningMedian


text:
"""
    SubDataset{<:Dataset, <:AbstractIndex, <:AbstractVector{Int}} <: Dataset

A view of a `Dataset`. It is returned by a call to the `view` function
on an `Dataset` if a collections of rows and columns are specified.

View of a data set preserves the `format` of columns.

# Examples
```jldoctest
julia> ds = Dataset(a = repeat([1, 2, 3, 4], outer=[2]),
                             b = repeat([2, 1], outer=[4]),
                             c = 1:8)
8×3 Dataset
 Row │ a         b         c
     │ identity  identity  identity
     │ Int64?    Int64?    Int64?
─────┼──────────────────────────────
   1 │        1         2         1
   2 │        2         1         2
   3 │        3         2         3
   4 │        4         1         4
   5 │        1         2         5
   6 │        2         1         6
   7 │        3         2         7
   8 │        4         1         8

julia> sds1 = view(ds, :, 2:3) # column subsetting
8×2 SubDataset
Row │ b         c
    │ identity  identity
    │ Int64?    Int64?
────┼────────────────────
  1 │        2         1
  2 │        1         2
  3 │        2         3
  4 │        1         4
  5 │        2         5
  6 │        1         6
  7 │        2         7
  8 │        1         8

julia> sds2 = @view ds[end:-1:1, [1, 3]]
8×2 SubDataset
Row │ a         c
    │ identity  identity
    │ Int64?    Int64?
────┼────────────────────
  1 │        4         8
  2 │        3         7
  3 │        2         6
  4 │        1         5
  5 │        4         4
  6 │        3         3
  7 │        2         2
  8 │        1         1

julia> setformat!(ds, 1=>iseven)
8×3 Dataset
 Row │ a       b         c
     │ iseven  identity  identity
     │ Int64?  Int64?    Int64?
─────┼────────────────────────────
   1 │  false         2         1
   2 │   true         1         2
   3 │  false         2         3
   4 │   true         1         4
   5 │  false         2         5
   6 │   true         1         6
   7 │  false         2         7
   8 │   true         1         8

julia> view(ds, 8:-1:1, [1,3])
8×2 SubDataset
 Row │ a       c
     │ iseven  identity
     │ Int64?  Int64?
─────┼──────────────────
   1 │   true         8
   2 │  false         7
   3 │   true         6
   4 │  false         5
   5 │   true         4
   6 │  false         3
   7 │   true         2
   8 │  false         1
```
"""
struct SubDataset{D<:AbstractDataset, S<:AbstractIndex, T<:AbstractVector{Int}} <: AbstractDataset
    parent::D
    colindex::S
    rows::T # maps from subds row indexes to parent row indexes
end

_attributes(sds::SubDataset) = getfield(parent(sds), :attributes)

# Experimental
function _columns(sds::SubDataset)
    allcols = AbstractArray[]
    colsidx = parentcols(index(sds))
    for j in 1:length(colsidx)
        push!(allcols, view(_columns(parent(sds))[colsidx[j]], rows(sds)))
    end
    allcols
end

Base.@propagate_inbounds function SubDataset(parent::Dataset, rows::AbstractVector{Int}, cols)
    @boundscheck if !checkindex(Bool, axes(parent, 1), rows)
        throw(BoundsError(parent, (rows, cols)))
    end
    SubDataset(parent, SubIndex(index(parent), cols), rows)
end
Base.@propagate_inbounds SubDataset(parent::Dataset, ::Colon, cols) =
    SubDataset(parent, axes(parent, 1), cols)
@inline SubDataset(parent::Dataset, row::Integer, cols) =
    throw(ArgumentError("invalid row index: $row of type $(typeof(row))"))

Base.@propagate_inbounds function SubDataset(parent::Dataset, rows::AbstractVector{<:Integer}, cols)
    if any(x -> x isa Bool, rows)
        throw(ArgumentError("invalid row index of type `Bool`"))
    end
    return SubDataset(parent, convert(Vector{Int}, rows), cols)
end

Base.@propagate_inbounds function SubDataset(parent::Dataset, rows::AbstractVector{Bool}, cols)
    if length(rows) != nrow(parent)
        throw(ArgumentError("invalid length of `AbstractVector{Bool}` row index " *
                            "(got $(length(rows)), expected $(nrow(parent)))"))
    end
    return SubDataset(parent, _findall(rows), cols)
end

Base.@propagate_inbounds function SubDataset(parent::Dataset, rows::AbstractVector, cols)
    if !all(x -> (x isa Integer) && !(x isa Bool), rows)
        throw(ArgumentError("only `Integer` indices are accepted in `rows`"))
    end
    return SubDataset(parent, convert(Vector{Int}, rows), cols)
end

Base.@propagate_inbounds SubDataset(sds::SubDataset, rowind, cols) =
    SubDataset(parent(sds), rows(sds)[rowind], parentcols(index(sds), cols))
Base.@propagate_inbounds SubDataset(sds::SubDataset, rowind::Bool, cols) =
    throw(ArgumentError("invalid row index of type Bool"))

# TODO needs some extra work
# Base.@propagate_inbounds SubDataset(sds::SubDataset, rowind, ::Colon) =
    # if index(sds) isa Index # sds was created using : as row selector
    #     SubDataset(parent(sds), rows(sds)[rowind], :)
    # else
    #     SubDataset(parent(sds), rows(sds)[rowind], parentcols(index(sds), :))
    # end
Base.@propagate_inbounds SubDataset(sds::SubDataset, rowind::Bool, ::Colon) =
    throw(ArgumentError("invalid row index of type Bool"))
Base.@propagate_inbounds SubDataset(sds::SubDataset, ::Colon, cols) =
    SubDataset(parent(sds), rows(sds), parentcols(index(sds), cols))
@inline SubDataset(sds::SubDataset, ::Colon, ::Colon) = sds

# just for showing SubDataset
function _getformats_for_show(ds::SubDataset)
    res = Dict{Int, Function}()
    idx = index(ds)
    for i in 1:length(idx.cols)
        if haskey(idx.parent.format, idx.cols[i])
            push!(res, i => idx.parent.format[idx.cols[i]])
        end
    end
    res
end

rows(sds::SubDataset) = getfield(sds, :rows)
Base.parent(sds::SubDataset) = getfield(sds, :parent)
Base.parentindices(sds::SubDataset) = (rows(sds), parentcols(index(sds)))

function Base.view(ds::Dataset, rowinds, colind::ColumnIndex)
    idx = index(ds)[colind]
    SubDatasetColumn(idx, ds, _columns(ds)[idx], rowinds)
end

function Base.view(ds::Dataset, ::typeof(!), colind::ColumnIndex)
    idx = index(ds)[colind]
    SubDatasetColumn(idx, ds, _columns(ds)[idx], :)
end
function Base.view(dc::DatasetColumn, rowinds)
    SubDatasetColumn(dc.col, dc.ds, dc.val, rowinds)
end
function Base.view(sdc::SubDatasetColumn, rowinds)
    SubDatasetColumn(sdc.col, sdc.ds, sdc.val, sdc.selected_index[rowinds])
end

Base.@propagate_inbounds Base.view(ads::AbstractDataset, rowinds, colind::ColumnIndex) =
    view(ads[!, colind], rowinds)
Base.@propagate_inbounds Base.view(ads::AbstractDataset, ::typeof(!), colind::ColumnIndex) =
    view(ads[!, colind], :)

@inline Base.view(ads::AbstractDataset, rowinds, colind::Bool) =
    throw(ArgumentError("invalid column index $colind of type `Bool`"))
Base.@propagate_inbounds Base.view(ads::AbstractDataset, rowinds,
                                   colinds::MultiColumnIndex) =
    SubDataset(ads, rowinds, colinds)
Base.@propagate_inbounds Base.view(ads::AbstractDataset, rowinds::typeof(!),
                                   colinds::MultiColumnIndex) =
    SubDataset(ads, :, colinds)
Base.@propagate_inbounds Base.view(ads::AbstractDataset, rowinds::Not,
                                   colinds::MultiColumnIndex) =
    SubDataset(ads, axes(ads, 1)[rowinds], colinds)

##############################################################################
##
## AbstractDataset interface
##
##############################################################################

index(sds::SubDataset) = getfield(sds, :colindex)

nrow(sds::SubDataset) = ncol(sds) > 0 ? length(rows(sds))::Int : 0
ncol(sds::SubDataset) = length(index(sds))

Base.@propagate_inbounds Base.getindex(sds::SubDataset, rowind::Integer, colind::ColumnIndex) =
    parent(sds)[rows(sds)[rowind], parentcols(index(sds), colind)]
Base.@propagate_inbounds Base.getindex(sds::SubDataset, rowind::Bool, colind::ColumnIndex) =
    throw(ArgumentError("invalid row index of type Bool"))

Base.@propagate_inbounds Base.getindex(sds::SubDataset, rowinds::Union{AbstractVector, Not},
                                       colind::ColumnIndex; mapformats = false) =
    getindex(parent(sds), rows(sds)[rowinds], parentcols(index(sds), colind); mapformats = mapformats)
Base.@propagate_inbounds Base.getindex(sds::SubDataset, ::Colon, colind::ColumnIndex; mapformats = false) =
    getindex(parent(sds), rows(sds), parentcols(index(sds), colind); mapformats = mapformats)
Base.@propagate_inbounds Base.getindex(sds::SubDataset, ::typeof(!), colind::ColumnIndex) =
    view(parent(sds), rows(sds), parentcols(index(sds), colind))

Base.@propagate_inbounds Base.getindex(sds::SubDataset, rowinds::Union{AbstractVector, Not},
                                       colinds::MultiColumnIndex) =
    parent(sds)[rows(sds)[rowinds], parentcols(index(sds), colinds)]
Base.@propagate_inbounds Base.getindex(sds::SubDataset, ::Colon,
                                       colinds::MultiColumnIndex) =
    parent(sds)[rows(sds), parentcols(index(sds), colinds)]
Base.@propagate_inbounds Base.getindex(ds::SubDataset, row_ind::typeof(!),
                                       col_inds::MultiColumnIndex) =
    view(ds, :,  col_inds)

Base.@propagate_inbounds function Base.setindex!(sds::SubDataset, val::Any, idx::CartesianIndex{2})
    setindex!(sds, val, idx[1], idx[2])
end
Base.@propagate_inbounds function Base.setindex!(sds::SubDataset, val::Any, ::Colon, colinds::Any)
    parent(sds)[rows(sds), parentcols(index(sds), colinds)] = val
    return sds
end
Base.@propagate_inbounds function Base.setindex!(sds::SubDataset, val::Any, ::typeof(!), colinds::Any)
    throw(ArgumentError("setting index of SubDataset using ! as row selector is not allowed"))
end
Base.@propagate_inbounds function Base.setindex!(sds::SubDataset, val::Any, rowinds::Any, colinds::Any)
    parent(sds)[rows(sds)[rowinds], parentcols(index(sds), colinds)] = val
    return sds
end
Base.@propagate_inbounds Base.setindex!(sds::SubDataset, val::Any, rowinds::Bool, colinds::Any) =
    throw(ArgumentError("invalid row index of type Bool"))

Base.setproperty!(::SubDataset, ::Symbol, ::Any) =
    throw(ArgumentError("Replacing or adding of columns of a SubDataset is not allowed. " *
                        "Instead use `ds[:, col_ind] = v` or `ds[:, col_ind] .= v` " *
                        "to perform an in-place assignment."))
Base.setproperty!(::SubDataset, ::AbstractString, ::Any) =
    throw(ArgumentError("Replacing or adding of columns of a SubDataset is not allowed. " *
                        "Instead use `ds[:, col_ind] = v` or `ds[:, col_ind] .= v` " *
                        "to perform an in-place assignment."))

##############################################################################
##
## Miscellaneous
##
##############################################################################

Base.copy(sds::SubDataset) = parent(sds)[rows(sds), parentcols(index(sds), :)]

Base.deleteat!(ds::SubDataset, ind) =
    throw(ArgumentError("SubDataset does not support deleting rows"))

function Dataset(sds::SubDataset)

    newds = sds[:, :]
    setinfo!(newds, _attributes(sds).meta.info[])
    newds
end

Base.convert(::Type{Dataset}, sds::SubDataset) = Dataset(sds)


text:
abstract type AbstractData end

y_values(data::AbstractData) = data.y
x_values(data::AbstractData) = data.x


text:
# run all tests
include("test_advance.jl")
include("test_debug.jl")
include("test_geometry.jl")
include("test_leapfrog2d.jl")
include("test_leapfrog2d_2.jl")
include("test_plottools.jl")
include("test_ring2d.jl")
include("test_rings2d.jl")


text:
#######################################################
# Constrained to unconstrained distribution bijectors #
#######################################################
struct TruncatedBijector{T} <: Bijector{0}
    lb::T
    ub::T
end

function (b::TruncatedBijector)(x::Real)
    a, b = b.lb, b.ub
    lowerbounded, upperbounded = isfinite(a), isfinite(b)
    if lowerbounded && upperbounded
        return StatsFuns.logit((x - a) / (b - a))
    elseif lowerbounded
        return log(x - a)
    elseif upperbounded
        return log(b - x)
    else
        return x
    end
end

function (b::TruncatedBijector)(x::AbstractVector{<:Real})
    a, b = b.lb, b.ub
    lowerbounded, upperbounded = isfinite(a), isfinite(b)
    if lowerbounded && upperbounded
        return @. StatsFuns.logit((x - a) / (b - a))
    elseif lowerbounded
        return log.(x - a)
    elseif upperbounded
        return log.(b - x)
    else
        return x
    end
end

function (ib::Inversed{<:TruncatedBijector})(y::Real)
    a, b = ib.orig.lb, ib.orig.ub
    lowerbounded, upperbounded = isfinite(a), isfinite(b)
    if lowerbounded && upperbounded
        return (b - a) * StatsFuns.logistic(y) + a
    elseif lowerbounded
        return exp(y) + a
    elseif upperbounded
        return b - exp(y)
    else
        return y
    end
end

function (ib::Inversed{<:TruncatedBijector})(y::AbstractVector{<:Real})
    a, b = ib.orig.lb, ib.orig.ub
    lowerbounded, upperbounded = isfinite(a), isfinite(b)
    if lowerbounded && upperbounded
        return @. (b - a) * StatsFuns.logistic(y) + a
    elseif lowerbounded
        return @. exp(y) + a
    elseif upperbounded
        return @. b - exp(y)
    else
        return y
    end
end

function logabsdetjac(b::TruncatedBijector, x::Real)
    a, b = b.lb, b.ub
    lowerbounded, upperbounded = isfinite(a), isfinite(b)
    if lowerbounded && upperbounded
        return - log((x - a) * (b - x) / (b - a))
    elseif lowerbounded
        return - log(x - a)
    elseif upperbounded
        return - log(b - x)
    else
        return zero(x)
    end
end

function logabsdetjac(b::TruncatedBijector, x::AbstractVector{<:Real})
    a, b = b.lb, b.ub
    lowerbounded, upperbounded = isfinite(a), isfinite(b)
    if lowerbounded && upperbounded
        return @. - log((x - a) * (b - x) / (b - a))
    elseif lowerbounded
        return @. - log(x - a)
    elseif upperbounded
        return @. - log(b - x)
    else
        return zero(x)
    end
end


text:
function kmeans_algorithm{T <: Real}(coords::Array{T, 2}, k::Int64)
    nochanges = 0
    n = size(coords, 1)
    @assert n >= k "Number of observations must not be greater than number of clusters"

    coords = hcat(coords, zeros(n))
    init = convert(Array{Int64, 1}, ceil(rand(k) * n))
    centroids = coords[init, 1:2]

    while nochanges < 2

        # for each data point
        for i in 1:n
            closest = Inf
            mindist = Inf

            # get the cluster from which the distance is smallest
            for j in 1:k
                d = abs(centroids[j, 1:2] - coords[i, 1:2])
                distance = √(d * d')[1]

                if distance < mindist
                    mindist = distance
                    closest = j
                end
            end

            # TODO: wrong termination step
            if coords[i, 3] == closest
                nochanges += 1
            else
                coords[i, 3] = closest
                nochanges = 0
            end

        end

        # recompute clusters
        for j in 1:k
            centroids[j, :] = mean(coords[coords[:, 3] .== j, 1:2], 1)
        end
    end

    coords
end

function kmeans{T <: Real}(x::Array{T, 1}, y::Array{T, 1}; k::Int64 = 1)
    kmeans_algorithm(hcat(x, y), k)
end

function kmeans{T <: Real}(coords::Array{T, 2}; k::Int64 = 1)
    @assert size(coords, 2) == 2
    kmeans_algorithm(coords, k)
end

dat = [
1 1
1.5 2
3 4
5 7
3.5 5
4.5 5
3.5 4.5]


text:
function update_mu!(state::State, data::Data, prior::Prior)
  m_mu, s_mu = params(prior.mu)

  vkernels = zero.(state.mu)
  mkernels = zero.(state.mu)

  for i in samplenames
    yfinite = ref_yfinite(data, i)
    lambda = ref_lambda(state, i)
    zeta = ref_zeta(state, i)
    v = ref_v(state, i)
    for n in eachindex(lambda)
      k = lambda[n]
      vkernels[k] += v[n]
      mkernels[k] += (yfinite[n] - state.psi[k] * zeta[n]) * v[n]
    end
  end

  vnew = 1 ./ (s_mu^-2 .+ vkernels ./ state.omega)
  mnew = vnew .* (m_mu/(s_mu^2) .+ mkernels ./ state.omega)

  state.mu .= randn(prior.K) .* sqrt.(vnew) + mnew
end

max_stars_repo_name: luiarthur/CytofDensityEstimation

max_issues_repo_name: luiarthur/CytofDensityEstimation

max_forks_repo_name: luiarthur/CytofDensityEstimation