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

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

function _swaggerinternal_createAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", IoK8sApiAdmissionregistrationV1MutatingWebhookConfiguration, "/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations", ["BearerToken"], body)
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldManager", fieldManager)  # type String
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

create a MutatingWebhookConfiguration
Param: body::IoK8sApiAdmissionregistrationV1MutatingWebhookConfiguration (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiAdmissionregistrationV1MutatingWebhookConfiguration
"""
function createAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_createAdmissionregistrationV1MutatingWebhookConfiguration(_api, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function createAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_createAdmissionregistrationV1MutatingWebhookConfiguration(_api, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_createAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "POST", IoK8sApiAdmissionregistrationV1ValidatingWebhookConfiguration, "/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations", ["BearerToken"], body)
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldManager", fieldManager)  # type String
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

create a ValidatingWebhookConfiguration
Param: body::IoK8sApiAdmissionregistrationV1ValidatingWebhookConfiguration (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiAdmissionregistrationV1ValidatingWebhookConfiguration
"""
function createAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_createAdmissionregistrationV1ValidatingWebhookConfiguration(_api, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function createAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_createAdmissionregistrationV1ValidatingWebhookConfiguration(_api, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_deleteAdmissionregistrationV1CollectionMutatingWebhookConfiguration(_api::AdmissionregistrationV1Api; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "DELETE", IoK8sApimachineryPkgApisMetaV1Status, "/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations", ["BearerToken"], body)
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "gracePeriodSeconds", gracePeriodSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "orphanDependents", orphanDependents)  # type Bool
    Swagger.set_param(_ctx.query, "propagationPolicy", propagationPolicy)  # type String
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

delete collection of MutatingWebhookConfiguration
Param: pretty::String
Param: allowWatchBookmarks::Bool
Param: body::IoK8sApimachineryPkgApisMetaV1DeleteOptions
Param: __continue__::String
Param: dryRun::String
Param: fieldSelector::String
Param: gracePeriodSeconds::Int32
Param: labelSelector::String
Param: limit::Int32
Param: orphanDependents::Bool
Param: propagationPolicy::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1Status
"""
function deleteAdmissionregistrationV1CollectionMutatingWebhookConfiguration(_api::AdmissionregistrationV1Api; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_deleteAdmissionregistrationV1CollectionMutatingWebhookConfiguration(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, body=body, __continue__=__continue__, dryRun=dryRun, fieldSelector=fieldSelector, gracePeriodSeconds=gracePeriodSeconds, labelSelector=labelSelector, limit=limit, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function deleteAdmissionregistrationV1CollectionMutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_deleteAdmissionregistrationV1CollectionMutatingWebhookConfiguration(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, body=body, __continue__=__continue__, dryRun=dryRun, fieldSelector=fieldSelector, gracePeriodSeconds=gracePeriodSeconds, labelSelector=labelSelector, limit=limit, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_deleteAdmissionregistrationV1CollectionValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "DELETE", IoK8sApimachineryPkgApisMetaV1Status, "/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations", ["BearerToken"], body)
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "gracePeriodSeconds", gracePeriodSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "orphanDependents", orphanDependents)  # type Bool
    Swagger.set_param(_ctx.query, "propagationPolicy", propagationPolicy)  # type String
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

delete collection of ValidatingWebhookConfiguration
Param: pretty::String
Param: allowWatchBookmarks::Bool
Param: body::IoK8sApimachineryPkgApisMetaV1DeleteOptions
Param: __continue__::String
Param: dryRun::String
Param: fieldSelector::String
Param: gracePeriodSeconds::Int32
Param: labelSelector::String
Param: limit::Int32
Param: orphanDependents::Bool
Param: propagationPolicy::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1Status
"""
function deleteAdmissionregistrationV1CollectionValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_deleteAdmissionregistrationV1CollectionValidatingWebhookConfiguration(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, body=body, __continue__=__continue__, dryRun=dryRun, fieldSelector=fieldSelector, gracePeriodSeconds=gracePeriodSeconds, labelSelector=labelSelector, limit=limit, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function deleteAdmissionregistrationV1CollectionValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel; pretty=nothing, allowWatchBookmarks=nothing, body=nothing, __continue__=nothing, dryRun=nothing, fieldSelector=nothing, gracePeriodSeconds=nothing, labelSelector=nothing, limit=nothing, orphanDependents=nothing, propagationPolicy=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_deleteAdmissionregistrationV1CollectionValidatingWebhookConfiguration(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, body=body, __continue__=__continue__, dryRun=dryRun, fieldSelector=fieldSelector, gracePeriodSeconds=gracePeriodSeconds, labelSelector=labelSelector, limit=limit, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_deleteAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "DELETE", IoK8sApimachineryPkgApisMetaV1Status, "/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations/{name}", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "gracePeriodSeconds", gracePeriodSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "orphanDependents", orphanDependents)  # type Bool
    Swagger.set_param(_ctx.query, "propagationPolicy", propagationPolicy)  # type String
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

delete a MutatingWebhookConfiguration
Param: name::String (required)
Param: pretty::String
Param: body::IoK8sApimachineryPkgApisMetaV1DeleteOptions
Param: dryRun::String
Param: gracePeriodSeconds::Int32
Param: orphanDependents::Bool
Param: propagationPolicy::String
Return: IoK8sApimachineryPkgApisMetaV1Status
"""
function deleteAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_deleteAdmissionregistrationV1MutatingWebhookConfiguration(_api, name; pretty=pretty, body=body, dryRun=dryRun, gracePeriodSeconds=gracePeriodSeconds, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function deleteAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel, name::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_deleteAdmissionregistrationV1MutatingWebhookConfiguration(_api, name; pretty=pretty, body=body, dryRun=dryRun, gracePeriodSeconds=gracePeriodSeconds, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_deleteAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "DELETE", IoK8sApimachineryPkgApisMetaV1Status, "/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations/{name}", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "gracePeriodSeconds", gracePeriodSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "orphanDependents", orphanDependents)  # type Bool
    Swagger.set_param(_ctx.query, "propagationPolicy", propagationPolicy)  # type String
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

delete a ValidatingWebhookConfiguration
Param: name::String (required)
Param: pretty::String
Param: body::IoK8sApimachineryPkgApisMetaV1DeleteOptions
Param: dryRun::String
Param: gracePeriodSeconds::Int32
Param: orphanDependents::Bool
Param: propagationPolicy::String
Return: IoK8sApimachineryPkgApisMetaV1Status
"""
function deleteAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_deleteAdmissionregistrationV1ValidatingWebhookConfiguration(_api, name; pretty=pretty, body=body, dryRun=dryRun, gracePeriodSeconds=gracePeriodSeconds, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function deleteAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel, name::String; pretty=nothing, body=nothing, dryRun=nothing, gracePeriodSeconds=nothing, orphanDependents=nothing, propagationPolicy=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_deleteAdmissionregistrationV1ValidatingWebhookConfiguration(_api, name; pretty=pretty, body=body, dryRun=dryRun, gracePeriodSeconds=gracePeriodSeconds, orphanDependents=orphanDependents, propagationPolicy=propagationPolicy, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_getAdmissionregistrationV1APIResources(_api::AdmissionregistrationV1Api; _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1APIResourceList, "/apis/admissionregistration.k8s.io/v1/", ["BearerToken"])
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"] : [_mediaType])
    return _ctx
end

"""

get available resources
Return: IoK8sApimachineryPkgApisMetaV1APIResourceList
"""
function getAdmissionregistrationV1APIResources(_api::AdmissionregistrationV1Api; _mediaType=nothing)
    _ctx = _swaggerinternal_getAdmissionregistrationV1APIResources(_api; _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function getAdmissionregistrationV1APIResources(_api::AdmissionregistrationV1Api, response_stream::Channel; _mediaType=nothing)
    _ctx = _swaggerinternal_getAdmissionregistrationV1APIResources(_api; _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_listAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiAdmissionregistrationV1MutatingWebhookConfigurationList, "/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations", ["BearerToken"])
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

list or watch objects of kind MutatingWebhookConfiguration
Param: pretty::String
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApiAdmissionregistrationV1MutatingWebhookConfigurationList
"""
function listAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_listAdmissionregistrationV1MutatingWebhookConfiguration(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function listAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_listAdmissionregistrationV1MutatingWebhookConfiguration(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_listAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiAdmissionregistrationV1ValidatingWebhookConfigurationList, "/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations", ["BearerToken"])
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

list or watch objects of kind ValidatingWebhookConfiguration
Param: pretty::String
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApiAdmissionregistrationV1ValidatingWebhookConfigurationList
"""
function listAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_listAdmissionregistrationV1ValidatingWebhookConfiguration(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function listAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel; pretty=nothing, allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_listAdmissionregistrationV1ValidatingWebhookConfiguration(_api; pretty=pretty, allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_patchAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PATCH", IoK8sApiAdmissionregistrationV1MutatingWebhookConfiguration, "/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations/{name}", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldManager", fieldManager)  # type String
    Swagger.set_param(_ctx.query, "force", force)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json-patch+json", "application/merge-patch+json", "application/strategic-merge-patch+json", "application/apply-patch+yaml"] : [_mediaType])
    return _ctx
end

"""

partially update the specified MutatingWebhookConfiguration
Param: name::String (required)
Param: body::IoK8sApimachineryPkgApisMetaV1Patch (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Param: force::Bool
Return: IoK8sApiAdmissionregistrationV1MutatingWebhookConfiguration
"""
function patchAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_patchAdmissionregistrationV1MutatingWebhookConfiguration(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function patchAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_patchAdmissionregistrationV1MutatingWebhookConfiguration(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_patchAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PATCH", IoK8sApiAdmissionregistrationV1ValidatingWebhookConfiguration, "/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations/{name}", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldManager", fieldManager)  # type String
    Swagger.set_param(_ctx.query, "force", force)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["application/json-patch+json", "application/merge-patch+json", "application/strategic-merge-patch+json", "application/apply-patch+yaml"] : [_mediaType])
    return _ctx
end

"""

partially update the specified ValidatingWebhookConfiguration
Param: name::String (required)
Param: body::IoK8sApimachineryPkgApisMetaV1Patch (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Param: force::Bool
Return: IoK8sApiAdmissionregistrationV1ValidatingWebhookConfiguration
"""
function patchAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_patchAdmissionregistrationV1ValidatingWebhookConfiguration(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function patchAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, force=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_patchAdmissionregistrationV1ValidatingWebhookConfiguration(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, force=force, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_readAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiAdmissionregistrationV1MutatingWebhookConfiguration, "/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations/{name}", ["BearerToken"])
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "exact", exact)  # type Bool
    Swagger.set_param(_ctx.query, "export", __export__)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

read the specified MutatingWebhookConfiguration
Param: name::String (required)
Param: pretty::String
Param: exact::Bool
Param: __export__::Bool
Return: IoK8sApiAdmissionregistrationV1MutatingWebhookConfiguration
"""
function readAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_readAdmissionregistrationV1MutatingWebhookConfiguration(_api, name; pretty=pretty, exact=exact, __export__=__export__, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function readAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel, name::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_readAdmissionregistrationV1MutatingWebhookConfiguration(_api, name; pretty=pretty, exact=exact, __export__=__export__, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_readAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApiAdmissionregistrationV1ValidatingWebhookConfiguration, "/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations/{name}", ["BearerToken"])
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "exact", exact)  # type Bool
    Swagger.set_param(_ctx.query, "export", __export__)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

read the specified ValidatingWebhookConfiguration
Param: name::String (required)
Param: pretty::String
Param: exact::Bool
Param: __export__::Bool
Return: IoK8sApiAdmissionregistrationV1ValidatingWebhookConfiguration
"""
function readAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_readAdmissionregistrationV1ValidatingWebhookConfiguration(_api, name; pretty=pretty, exact=exact, __export__=__export__, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function readAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel, name::String; pretty=nothing, exact=nothing, __export__=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_readAdmissionregistrationV1ValidatingWebhookConfiguration(_api, name; pretty=pretty, exact=exact, __export__=__export__, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_replaceAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PUT", IoK8sApiAdmissionregistrationV1MutatingWebhookConfiguration, "/apis/admissionregistration.k8s.io/v1/mutatingwebhookconfigurations/{name}", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldManager", fieldManager)  # type String
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

replace the specified MutatingWebhookConfiguration
Param: name::String (required)
Param: body::IoK8sApiAdmissionregistrationV1MutatingWebhookConfiguration (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiAdmissionregistrationV1MutatingWebhookConfiguration
"""
function replaceAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_replaceAdmissionregistrationV1MutatingWebhookConfiguration(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function replaceAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_replaceAdmissionregistrationV1MutatingWebhookConfiguration(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_replaceAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "PUT", IoK8sApiAdmissionregistrationV1ValidatingWebhookConfiguration, "/apis/admissionregistration.k8s.io/v1/validatingwebhookconfigurations/{name}", ["BearerToken"], body)
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "dryRun", dryRun)  # type String
    Swagger.set_param(_ctx.query, "fieldManager", fieldManager)  # type String
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

replace the specified ValidatingWebhookConfiguration
Param: name::String (required)
Param: body::IoK8sApiAdmissionregistrationV1ValidatingWebhookConfiguration (required)
Param: pretty::String
Param: dryRun::String
Param: fieldManager::String
Return: IoK8sApiAdmissionregistrationV1ValidatingWebhookConfiguration
"""
function replaceAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_replaceAdmissionregistrationV1ValidatingWebhookConfiguration(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function replaceAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel, name::String, body; pretty=nothing, dryRun=nothing, fieldManager=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_replaceAdmissionregistrationV1ValidatingWebhookConfiguration(_api, name, body; pretty=pretty, dryRun=dryRun, fieldManager=fieldManager, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_watchAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1WatchEvent, "/apis/admissionregistration.k8s.io/v1/watch/mutatingwebhookconfigurations/{name}", ["BearerToken"])
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

watch changes to an object of kind MutatingWebhookConfiguration. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter.
Param: name::String (required)
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: pretty::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1WatchEvent
"""
function watchAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchAdmissionregistrationV1MutatingWebhookConfiguration(_api, name; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function watchAdmissionregistrationV1MutatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel, name::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchAdmissionregistrationV1MutatingWebhookConfiguration(_api, name; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_watchAdmissionregistrationV1MutatingWebhookConfigurationList(_api::AdmissionregistrationV1Api; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1WatchEvent, "/apis/admissionregistration.k8s.io/v1/watch/mutatingwebhookconfigurations", ["BearerToken"])
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

watch individual changes to a list of MutatingWebhookConfiguration. deprecated: use the 'watch' parameter with a list operation instead.
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: pretty::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1WatchEvent
"""
function watchAdmissionregistrationV1MutatingWebhookConfigurationList(_api::AdmissionregistrationV1Api; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchAdmissionregistrationV1MutatingWebhookConfigurationList(_api; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function watchAdmissionregistrationV1MutatingWebhookConfigurationList(_api::AdmissionregistrationV1Api, response_stream::Channel; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchAdmissionregistrationV1MutatingWebhookConfigurationList(_api; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_watchAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1WatchEvent, "/apis/admissionregistration.k8s.io/v1/watch/validatingwebhookconfigurations/{name}", ["BearerToken"])
    Swagger.set_param(_ctx.path, "name", name)  # type String
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

watch changes to an object of kind ValidatingWebhookConfiguration. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter.
Param: name::String (required)
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: pretty::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1WatchEvent
"""
function watchAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, name::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchAdmissionregistrationV1ValidatingWebhookConfiguration(_api, name; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function watchAdmissionregistrationV1ValidatingWebhookConfiguration(_api::AdmissionregistrationV1Api, response_stream::Channel, name::String; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchAdmissionregistrationV1ValidatingWebhookConfiguration(_api, name; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

function _swaggerinternal_watchAdmissionregistrationV1ValidatingWebhookConfigurationList(_api::AdmissionregistrationV1Api; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = Swagger.Ctx(_api.client, "GET", IoK8sApimachineryPkgApisMetaV1WatchEvent, "/apis/admissionregistration.k8s.io/v1/watch/validatingwebhookconfigurations", ["BearerToken"])
    Swagger.set_param(_ctx.query, "allowWatchBookmarks", allowWatchBookmarks)  # type Bool
    Swagger.set_param(_ctx.query, "continue", __continue__)  # type String
    Swagger.set_param(_ctx.query, "fieldSelector", fieldSelector)  # type String
    Swagger.set_param(_ctx.query, "labelSelector", labelSelector)  # type String
    Swagger.set_param(_ctx.query, "limit", limit)  # type Int32
    Swagger.set_param(_ctx.query, "pretty", pretty)  # type String
    Swagger.set_param(_ctx.query, "resourceVersion", resourceVersion)  # type String
    Swagger.set_param(_ctx.query, "timeoutSeconds", timeoutSeconds)  # type Int32
    Swagger.set_param(_ctx.query, "watch", watch)  # type Bool
    Swagger.set_header_accept(_ctx, ["application/json", "application/yaml", "application/vnd.kubernetes.protobuf", "application/json;stream=watch", "application/vnd.kubernetes.protobuf;stream=watch"])
    Swagger.set_header_content_type(_ctx, (_mediaType === nothing) ? ["*/*"] : [_mediaType])
    return _ctx
end

"""

watch individual changes to a list of ValidatingWebhookConfiguration. deprecated: use the 'watch' parameter with a list operation instead.
Param: allowWatchBookmarks::Bool
Param: __continue__::String
Param: fieldSelector::String
Param: labelSelector::String
Param: limit::Int32
Param: pretty::String
Param: resourceVersion::String
Param: timeoutSeconds::Int32
Param: watch::Bool
Return: IoK8sApimachineryPkgApisMetaV1WatchEvent
"""
function watchAdmissionregistrationV1ValidatingWebhookConfigurationList(_api::AdmissionregistrationV1Api; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchAdmissionregistrationV1ValidatingWebhookConfigurationList(_api; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx)
end

function watchAdmissionregistrationV1ValidatingWebhookConfigurationList(_api::AdmissionregistrationV1Api, response_stream::Channel; allowWatchBookmarks=nothing, __continue__=nothing, fieldSelector=nothing, labelSelector=nothing, limit=nothing, pretty=nothing, resourceVersion=nothing, timeoutSeconds=nothing, watch=nothing, _mediaType=nothing)
    _ctx = _swaggerinternal_watchAdmissionregistrationV1ValidatingWebhookConfigurationList(_api; allowWatchBookmarks=allowWatchBookmarks, __continue__=__continue__, fieldSelector=fieldSelector, labelSelector=labelSelector, limit=limit, pretty=pretty, resourceVersion=resourceVersion, timeoutSeconds=timeoutSeconds, watch=watch, _mediaType=_mediaType)
    Swagger.exec(_ctx, response_stream)
end

export createAdmissionregistrationV1MutatingWebhookConfiguration, createAdmissionregistrationV1ValidatingWebhookConfiguration, deleteAdmissionregistrationV1CollectionMutatingWebhookConfiguration, deleteAdmissionregistrationV1CollectionValidatingWebhookConfiguration, deleteAdmissionregistrationV1MutatingWebhookConfiguration, deleteAdmissionregistrationV1ValidatingWebhookConfiguration, getAdmissionregistrationV1APIResources, listAdmissionregistrationV1MutatingWebhookConfiguration, listAdmissionregistrationV1ValidatingWebhookConfiguration, patchAdmissionregistrationV1MutatingWebhookConfiguration, patchAdmissionregistrationV1ValidatingWebhookConfiguration, readAdmissionregistrationV1MutatingWebhookConfiguration, readAdmissionregistrationV1ValidatingWebhookConfiguration, replaceAdmissionregistrationV1MutatingWebhookConfiguration, replaceAdmissionregistrationV1ValidatingWebhookConfiguration, watchAdmissionregistrationV1MutatingWebhookConfiguration, watchAdmissionregistrationV1MutatingWebhookConfigurationList, watchAdmissionregistrationV1ValidatingWebhookConfiguration, watchAdmissionregistrationV1ValidatingWebhookConfigurationList


text:
import Pkg

#println("pre instantiate")
Pkg.instantiate()
#println("post instantiate")

using Test
#using LinearAlgebra
using Utilities

tests = ["toy_check"]

for t in tests
    @testset "$t" begin
        include("$(t).jl")
    end
end

ext: jl

max_stars_repo_name: RoyCCWang/RWJuliaUtilities

max_issues_repo_name: RoyCCWang/RWJuliaUtilities

max_forks_repo_name: RoyCCWang/RWJuliaUtilities


text:
VERSION >= v"0.4.0-dev+6521" && __precompile__()

"""
The NBInclude module allow you to include and execute Julia code from
IJulia Jupyter notebooks.  Analogous to `include("myfile.jl")`, just do

    using NBInclude
    nbinclude("myfile.ipynb")

to include the Julia code from the notebook `myfile.ipynb`.  Like `include`,
the value of the last evaluated expression is returned.
"""
module NBInclude

using Compat, JSON
export nbinclude

"""
    my_include_string(s::AbstractString, path::AbstractString, prev)

Like include_string, but also change the current source path just
as `include(filename)` would do.   We are hacking undocumented internals
of Julia here (see `base/loading.jl:include_from_node1`), but it hasn't
changed from Julia 0.2 to Julia 0.4 so it's not too crazy.  `prev`
should be the previous path returned by `Base.source_path`.
"""
function my_include_string(s::AbstractString, path::AbstractString, prev)
    tls = task_local_storage()
    tls[:SOURCE_PATH] = path
    try
        return include_string(s, path)
    finally
        if prev === nothing
            delete!(tls, :SOURCE_PATH)
        else
            tls[:SOURCE_PATH] = prev
        end
    end
end

"""
    nbinclude(path::AbstractString; renumber::Bool=false)

Include the IJulia Jupyter notebook at `path` and execute the code
cells (in the order that they appear in the file), returning the
result of the last expression in the last code cell.

Similarly to `include(path)` for `.jl` files, the `path` is relative
to the path of the current file (if any), and nested calls to
`include` or `nbinclude` are relative to the path of the notebook file.

For code in the `N`-th input cell of the notebook, the `@__FILE__` macro
(and other code that uses the file name, e.g. exception backtraces)
returns `path:In[N]`, where `N` is the cell number saved in the notebook.
If the cell has no number (e.g. if it hasn't been evaluated yet), then
it is assigned a number `+N` for the `N`-th nonempty cell.  If `renumber`
is set to `true`, then the cell numbers saved in the notebook are ignored
and each cell is assigned a consecutive number `N`.
"""
function nbinclude(path::AbstractString; renumber::Bool=false)
    # act like include(path), in that path is relative to current file:
    prev = Base.source_path(nothing)
    path = (prev == nothing) ? abspath(path) : joinpath(dirname(prev),path)

    # for precompilation, invalidate the cache if the notebook changes:
    include_dependency(path)

    # similar to base/loading.jl, handle nbinclude calls from worker
    # nodes that may not have filesystem access by fetching the file
    # contents from node 1.
    nb = if myid() == 1
        # sleep a bit to process file requests from other nodes
        nprocs()>1 && sleep(0.005)
        open(JSON.parse, path, "r")
    else
        JSON.parse(remotecall_fetch(readall, 1, path))
    end

    # check for an acceptable notebook:
    nb["nbformat"] == 4 || error("unrecognized notebook format ", nb["nbformat"])
    lang = lowercase(nb["metadata"]["language_info"]["name"])
    lang == "julia" || error("notebook is for unregognized language $lang")

    shell_or_help = r"^\s*[;?]" # pattern for shell command or help

    ret = nothing
    counter = 0 # keep our own cell counter to handle un-executed notebooks.
    for cell in nb["cells"]
        if cell["cell_type"] == "code" && !isempty(cell["source"])
            s = join(cell["source"])
            isempty(strip(s)) && continue # Jupyter doesn't number empty cells
            counter += 1
            ismatch(shell_or_help, s) && continue
            cellnum = renumber ? string(counter) :
                      cell["execution_count"] == nothing ? string('+',counter) :
                      string(cell["execution_count"])
            ret = my_include_string(s, string(path, ":In[", cellnum, "]"), prev)
        end
    end
    return ret
end

end # module


text:
function init(start_time, m::JuniperProblem; incumbent = nothing)
    hash_val = string(hash(hcat(m.l_var,m.u_var)))
    node = BnBNode(1, 1, m.l_var, m.u_var, m.relaxation_solution, 0, :Branch, m.relaxation_status, m.relaxation_objval,[],hash_val)
    obj_gain_m = zeros(m.num_disc_var)
    obj_gain_p = zeros(m.num_disc_var)
    obj_gain_mc = zeros(Int64, m.num_disc_var)
    obj_gain_pc = zeros(Int64, m.num_disc_var)
    obj_gain_inf = zeros(Int64, m.num_disc_var)
    obj_gain = GainObj(obj_gain_m, obj_gain_p, obj_gain_mc, obj_gain_pc, obj_gain_inf)
    disc2var_idx = zeros(m.num_disc_var)
    var2disc_idx = zeros(m.num_var)
    disc_i = 1
    for i=1:m.num_var
        if m.var_type[i] != :Cont
            disc2var_idx[disc_i] = i
            var2disc_idx[i] = disc_i
            disc_i += 1
        end
    end
    factor = 1
    if m.obj_sense == :Min
        factor = -1
    end
    bnbTree = BnBTreeObj()
    bnbTree.m           = m
    bnbTree.obj_gain    = obj_gain
    bnbTree.disc2var_idx = disc2var_idx
    bnbTree.var2disc_idx = var2disc_idx
    bnbTree.options     = m.options
    bnbTree.obj_fac     = factor
    bnbTree.start_time  = start_time
    bnbTree.nsolutions  = 0
    bnbTree.branch_nodes = [node]
    bnbTree.best_bound  = m.relaxation_objval
    bnbTree.limit = :None
    bnbTree.global_solver = is_global_status(m.status)

    if incumbent !== nothing
        bnbTree.incumbent = incumbent
        bnbTree.nsolutions += 1
        if m.options.incumbent_constr
            add_incumbent_constr(m,bnbTree.incumbent)
            m.ncuts += 1
        end
    end

    return bnbTree
end

function new_default_node(idx, level, l_var, u_var, solution;
                            var_idx=0, state=:Solve, relaxation_state=MOI.OPTIMIZE_NOT_CALLED, best_bound=NaN, path=[])

    l_var = copy(l_var)
    u_var = copy(u_var)
    solution = copy(solution)
    hash_val = string(hash(hcat(l_var,u_var)))
    return BnBNode(idx, level, l_var, u_var, solution, var_idx, state, relaxation_state, best_bound, path, hash_val)
end

function new_left_node(node, u_var;
                       var_idx=0, state=:Solve, relaxation_state=MOI.OPTIMIZE_NOT_CALLED, best_bound=NaN, path=[])
    l_var = copy(node.l_var)
    u_var = copy(u_var)
    solution = NaN*ones(length(node.solution))
    hash_val = string(hash(hcat(l_var,u_var)))
    return BnBNode(node.idx*2, node.level+1, l_var, u_var, solution, var_idx, state, relaxation_state, best_bound, path, hash_val)
end

function new_right_node(node, l_var;
                       var_idx=0, state=:Solve, relaxation_state=MOI.OPTIMIZE_NOT_CALLED, best_bound=NaN, path=[])
    l_var = copy(l_var)
    u_var = copy(node.u_var)
    solution = NaN*ones(length(node.solution))
    hash_val = string(hash(hcat(l_var,u_var)))
    return BnBNode(node.idx*2+1, node.level+1, l_var, u_var, solution, var_idx, state, relaxation_state, best_bound, path, hash_val)
end

function init_time_obj()
    return TimeObj(0.0,0.0,0.0,0.0,0.0)
end

function new_default_step_obj(m,node)
    gains_m = zeros(m.num_disc_var)
    gains_mc = zeros(Int64, m.num_disc_var)
    gains_p = zeros(m.num_disc_var)
    gains_pc = zeros(Int64, m.num_disc_var)
    gains_inf = zeros(Int64, m.num_disc_var)
    gains = GainObj(gains_m, gains_p, gains_mc, gains_pc, gains_inf)
    idx_time = 0.0
    node_idx_time = 0.0
    upd_gains_time = 0.0
    node_branch_time = 0.0
    branch_time = 0.0
    step_obj = StepObj()
    step_obj.node             = node
    step_obj.var_idx          = 0
    step_obj.state            = :None
    step_obj.nrestarts        = 0
    step_obj.gain_gap         = 0.0
    step_obj.obj_gain         = gains
    step_obj.idx_time         = idx_time
    step_obj.node_idx_time    = node_idx_time
    step_obj.upd_gains_time   = upd_gains_time
    step_obj.node_branch_time = node_branch_time
    step_obj.branch_time      = branch_time
    step_obj.integral         = []
    step_obj.branch           = []
    step_obj.counter          = 0
    step_obj.upd_gains        = :None
    step_obj.strong_disc_vars = Int64[]
    step_obj.branch_strategy  = :None
    step_obj.strong_branching = nothing
    return step_obj
end

function init_juniper_problem!(jp::JuniperProblem, model::MOI.AbstractOptimizer)
    num_variables = length(model.variable_info)
    num_linear_le_constraints = length(model.linear_le_constraints)
    num_linear_ge_constraints = length(model.linear_ge_constraints)
    num_linear_eq_constraints = length(model.linear_eq_constraints)
    num_quadratic_le_constraints = length(model.quadratic_le_constraints)
    num_quadratic_ge_constraints = length(model.quadratic_ge_constraints)
    num_quadratic_eq_constraints = length(model.quadratic_eq_constraints)

    jp.status = MOI.OPTIMIZE_NOT_CALLED
    jp.relaxation_status = MOI.OPTIMIZE_NOT_CALLED
    jp.has_nl_objective = model.nlp_data.has_objective
    jp.nlp_evaluator = model.nlp_data.evaluator
    jp.objective = model.objective

    jp.objval = NaN
    jp.best_bound = NaN
    jp.solution = fill(NaN, num_variables)
    jp.nsolutions = 0
    jp.solutions = []
    jp.num_disc_var = 0
    jp.nintvars = 0
    jp.nbinvars = 0
    jp.nnodes = 1 # is set to one for the root node
    jp.ncuts = 0
    jp.nbranches = 0
    jp.nlevels = 1
    jp.relaxation_time = 0.0

    jp.start_time = time()

    jp.nl_solver = model.options.nl_solver
    nl_vec_opts = Vector{Pair}()
    if isa(jp.nl_solver, MOI.OptimizerWithAttributes)
        for arg in model.options.nl_solver.params
            push!(nl_vec_opts, arg)
        end
    end

    jp.nl_solver_options = nl_vec_opts

    if model.options.mip_solver !== nothing
        jp.mip_solver = model.options.mip_solver
        mip_vec_opts = Vector{Pair}()
        if isa(jp.mip_solver, MOI.OptimizerWithAttributes)
            for arg in model.options.mip_solver.params
                push!(mip_vec_opts, arg)
            end
        end

        jp.mip_solver_options = mip_vec_opts
    end
    jp.options = model.options
    if model.sense == MOI.MIN_SENSE
        jp.obj_sense = :Min
    else
        jp.obj_sense = :Max
    end
    jp.l_var = info_array_of_variables(model.variable_info, :lower_bound)
    jp.u_var = info_array_of_variables(model.variable_info, :upper_bound)
    integer_bool_arr = info_array_of_variables(model.variable_info, :is_integer)
    binary_bool_arr = info_array_of_variables(model.variable_info, :is_binary)
    primal_start_arr = info_array_of_variables(model.variable_info, :start)
    jp.primal_start = primal_start_arr
    jp.nintvars = sum(integer_bool_arr)
    jp.nbinvars = sum(binary_bool_arr)
    jp.num_disc_var = sum(integer_bool_arr)+sum(binary_bool_arr)
    jp.num_var = length(model.variable_info)
    jp.var_type = [:Cont for i in 1:jp.num_var]
    jp.var_type[integer_bool_arr .== true] .= :Int
    jp.var_type[binary_bool_arr .== true] .= :Bin
    jp.disc2var_idx = zeros(jp.num_disc_var)
    jp.var2disc_idx = zeros(jp.num_var)
    int_i = 1
    for i=1:jp.num_var
        if jp.var_type[i] != :Cont
            jp.disc2var_idx[int_i] = i
            jp.var2disc_idx[i] = int_i
            int_i += 1
        end
    end
    jp.num_l_constr = num_linear_le_constraints+num_linear_ge_constraints+num_linear_eq_constraints
    jp.num_q_constr = num_quadratic_le_constraints+num_quadratic_ge_constraints+num_quadratic_eq_constraints
    jp.num_nl_constr = length(model.nlp_data.constraint_bounds)
    jp.num_constr = jp.num_l_constr+jp.num_q_constr+jp.num_nl_constr
end

function new_default_strong_branch_step_obj(var_idx)
    strong_step_obj = StrongBranchStep()
    strong_step_obj.var_idx                 = var_idx
    strong_step_obj.l_relaxation_state      = MOI.OPTIMIZE_NOT_CALLED
    strong_step_obj.r_relaxation_state      = MOI.OPTIMIZE_NOT_CALLED
    strong_step_obj.init_restart            = false
    return strong_step_obj
end


text:
# ------------------------------------------------------------
# Scaling functions

@doc """
	HaarScaling( xi[, J, k] ) -> Float

The Haar scaling function evaluated in `xi` at level `J` and translation `k`.
By default, `J=0` and `k=0`.
"""->
function HaarScaling(xi::Real)
	zero(xi) <= xi < one(xi) ? 1.0 : 0.0
end

@doc """
	DaubScaling(p, R) -> x, y

A Daubechies `p` scaling function evaluated in the dyadic rationals at resolution `R`.
"""->
function DaubScaling(p::Integer, R::Integer, symmlet::Bool=true)
	IF = ifilter(p, symmlet)
	supp = support(IF)
	x = dyadic_rationals(supp, R)
	phi = DaubScaling( IF, R )

	return x, phi
end

@doc """
	dyadic_dil_matrix(C::Vector) -> Matrix

The "dyadic dilation matrix" `D` of the filter `C`:
`D[i,j] = C[2i-j]`.
"""->
function dyadic_dil_matrix(C::Vector{Float64})
	NC = length(C)
	sz = NC - 2
	dydil_mat = zeros(Float64, sz, sz)

	for nj in 1:sz, ni in 1:sz
		Cidx = 2*ni - nj + 1
		if 1 <= Cidx <= NC
			dydil_mat[ni, nj] = sqrt2*C[Cidx]
		end
	end

	return dydil_mat
end

#=
	DaubScaling(IF::InteriorFilter) -> Vector

Compute function values of the scaling function defined by the filter `IF` at the integers in the support.
=#
function DaubScaling(IF::InteriorFilter)
	if van_moment(IF) == 1
		return [1.0; 0.0]
	end

	C = coef(IF)
	L = dyadic_dil_matrix( C )

	# Eigenvector of eigenvalue 1:
	E = zeros(Float64, length(C))
	E[2:end-1] = eigval1(L)

	# Normalize scaling function in L2
	scale!(E, 1/sum(E))

	return E
end

@doc """
	DaubScaling(C::InteriorFilter, R::Int) -> Vector

Compute function values of the scaling function defined by the filter
`C` at the dyadic rationals of resolution `R` in the support.
"""->
function DaubScaling(IF::InteriorFilter, R::Integer)
	supp = support(IF)
	# There are 2^R points on each unit + endpoint
	Nx = length(supp)*2^R + 1
	phi = zeros(Float64, Nx)

	# Base level
	cur_idx = dyadic_rationals(supp, R, 0)
	phi[cur_idx] = DaubScaling(IF)

	# Recursion: Fill remaining levels
	coeff = coef(IF)
	Lsupp = left(supp)
	Rsupp = right(supp)
	for L in 1:R
		# Indices of x values on scale L
		cur_idx = dyadic_rationals(supp, R, L)

		for xindex in cur_idx
			twox = 2*index2x( xindex, supp, R )

			for k in Lsupp:Rsupp
				if isinside(twox-k, supp)
					twox_index = x2index( twox-k, supp, R )
					phi[xindex] += sqrt2 * coeff[k-Lsupp+1] * phi[twox_index]
				end
			end
		end
	end

	return phi
end


text:
function centre_dual!(point::Class_point, comp_feas::Float64)
  y_c = point.mu ./ point.s

  point.y = min( y_c / comp_feas, max(point.y, comp_feas * y_c))
end

function dual_scale(iter::Class_iterate, pars::Class_parameters)
    if pars.term.dual_scale_mode == :ipopt
      return pars.term.dual_scale_threshold / max(mean(get_y(iter)), pars.term.dual_scale_threshold)
    elseif pars.term.dual_scale_mode == :max_dual
      return pars.term.dual_scale_threshold / max(norm(get_y(iter),Inf), pars.term.dual_scale_threshold)
    elseif pars.term.dual_scale_mode == :sqrt
      return pars.term.dual_scale_threshold / max(sqrt(norm(get_y(iter), Inf)), pars.term.dual_scale_threshold)
    elseif pars.term.dual_scale_mode == :exact
      return 1.0
    elseif pars.term.dual_scale_mode == :primal_dual
      return pars.term.dual_scale_threshold / max(sqrt(norm(get_y(iter), Inf) * norm(get_s(iter), Inf)), + pars.term.dual_scale_threshold)
    else
      throw("dual scale type does not exist")
    end
end

function scaled_dual_feas(iter::Class_iterate, pars::Class_parameters)
    return scaled_dual_feas(iter, iter.point.mu, pars)
end

function scaled_dual_feas(iter::Class_iterate, mu::Float64, pars::Class_parameters)
    return norm(eval_grad_lag(iter, mu),Inf) * dual_scale(iter, pars)
end

function check_for_nan(point::Class_point)
  if isbad(point.s)
    error("NaN in s")
  end

  if isbad(point.y)
    #@show point.y, point.s
    error("NaN in y")
  end

  if isbad(point.x)
    error("NaN in x")
  end

  if isbad(point.mu)
    error("NaN in mu")
  end
end

function is_feasible(it::Class_iterate, comp_feas::Float64)
    check_for_nan(it.point)

    mu = get_mu(it);
    s =  get_s(it)
    y =  get_y(it)

    Sy = s .* y
    if length(Sy) > 0
      return all(s .> 0.0) && all(y .> 0.0) && maximum(Sy) / mu  <= 1.0 / comp_feas && minimum(Sy) / mu >= comp_feas
    else
      return true
    end
end


text:
mutable struct SumProductNetwork
    "The root node of the SPN."
    root::Node
    "The order in which the nodes of the SPN are evaluated."
    order::Vector{Node}

    """
    Creates a new SPN from an existing graph of nodes.
    """
    function SumProductNetwork(root::Node; recursive=true)
        order = computeOrder(root, recursive=recursive)
        new(root, order)
    end
end

#=
"""
    computeOrder(root::Node) -> Vector{Node}

Computes a topological ordering of the nodes of an SPN rooted at `root`.
Uses depth first search.
"""
function computeOrder(root::Node)
    root.state = temporary
    stack = Node[root]
    order = Node[]
    while ! isempty(stack)
        node = stack[end]
        @assert node.state == temporary
        # remove node from stack and add it to order:
        node.state = permanently
        pop!(stack)
        push!(order, node)

        # add all children to stack that are not on
        # the stack or in the order list:
        if typeof(node) <: InnerNode
            for child in node.children
                if child.state == unmarked
                    push!(stack, child)
                    child.state = temporary
                end
            end
        end
    end

    # reset state of nodes:
    for node in order
        node.state = unmarked
    end

    return order
end
=#

"""
    computeOrder(root::Node) -> Vector{Node}

Computes a topological ordering of the nodes of an SPN
rooted at `root` by performing a post-order traversal
of the network.
"""
function computeOrder(root::Node; recursive=true)
    if recursive
        return computeOrderRecursive(root)
    else
        return computeOrderStack(root)
    end
end

"""
Recursively compute topological order. Might probably be slow.
"""
function computeOrderRecursive(root::Node)
    order = Node[]

    """
    Post-order traversal for inner nodes.
    """
    function postOrder(n::InnerNode)
        n.state = temporary
        for child in n.children
            if child.state == unmarked
                postOrder(child)
            elseif child.state == temporary
                error("network contains cycle. Not a DAG.")
            end
        end
        n.state = permanently
        push!(order, n)
    end

    """
    Post-order traversal for leaf nodes.
    """
    function postOrder(l::LeafNode)
        push!(order, l)
        l.state = permanently
    end

    postOrder(root)

    # reset state of nodes:
    for node in order
        node.state = unmarked
    end

    return order
end

"""
Computes order non-recursive, using a stack.
"""
function computeOrderStack(root::Node)
    order = Vector{Node}()
    stack = Vector{Node}()
    push!(stack, root)

    while ! isempty(stack)

        node = pop!(stack)

        # all children have been visited:
        if node.state == temporary
            push!(order, node)
            node.state = permanently
            continue
        end

        node.state = temporary

        push!(stack, node)

        if typeof(node) <: InnerNode
            for child in node.children
                if child.state == unmarked
                    push!(stack, child)
                elseif child.state == temporary
                    error("network contains cycle. Not a DAG.")
                end
            end
        end
    end

    # reset state of nodes:
    for node in order
        node.state = unmarked
    end

    return order
end

#=
function computeOrderStack(root::Node)
    order = Vector{Node}()
    stack = Vector{ Tuple{Bool, Node} }()
    push!(stack, (false, root))

    while ! isempty(stack)

        (complete, node) = pop!(stack)

        # all children have been visited:
        if complete
            push!(order, node)
            node.state = permanently
            continue
        end

        node.state = temporary

        push!(stack, (true, node))

        if typeof(node) <: InnerNode
            for child in node.children
                if child.state == unmarked
                    push!(stack, (false, child))
                elseif child.state == temporary
                    error("network contains cycle. Not a DAG.")
                end
            end
        end
    end

    return order
end
=#

"""
    setInput!(spn::SumProductNetwork, x::AbstractVector, e::BitVector)

Sets the logval of all leaf nodes of the SPN according to the input.
"""
function setInput!(spn::SumProductNetwork, x::AbstractVector, e::BitVector=trues(length(x)))
    for node in spn.order
        if typeof(node) <: LeafNode
            setInput!(node, x, e)
        end
    end
end

"""
    eval!(spn::SumProductNetwork) -> Float64

Evaluates all nodes of an SPN on the current input. Returns the
logval of the root node.
"""
function eval!(spn::SumProductNetwork; max=false)
    for node in spn.order
        eval!(node, max=max)
    end
    return spn.root.logval
end

"""
Sets the `logdrv` field of every node to -Inf.
"""
function initDerivatives!(spn::SumProductNetwork)
    for node in spn.order
        node.logdrv = -Inf
    end
end

"""
Computes the log derivative of the likelihood w.r.t. all
nodes in the SPN.
Performs a top-down pass through the network (backpropagation).
"""
function computeDerivatives!(spn::SumProductNetwork)

    # root derivative is log(1)=0:
    spn.root.logdrv = 0.0

    for node in reverse(spn.order)
        if typeof(node) <: InnerNode
            passDerivative!(node)
        end
    end
end

"""
   numNodes(spn::SumProductNetwork) -> Int

The total number of nodes in the SPN.
"""
function numNodes(spn::SumProductNetwork)
    return length(spn.order)
end

"""
   numSumNodes(spn::SumProductNetwork) -> Int

The number of sum nodes in the SPN.
"""
function numSumNodes(spn::SumProductNetwork)
    return numNodes(spn, SumNode)
end

"""
   numProdNodes(spn::SumProductNetwork) -> Int

The number of product nodes in the SPN.
"""
function numProdNodes(spn::SumProductNetwork)
    return numNodes(spn, ProdNode)
end

"""
   numLeafNodes(spn::SumProductNetwork) -> Int

The number of leaf nodes in the SPN.
"""
function numLeafNodes(spn::SumProductNetwork)
    return numNodes(spn, LeafNode)
end

"""
    numNodes(spn::SumProductNetwork, t::Type) -> Int

The number of nodes in the SPN that are of type `t`.
The type `t` can be concrete or abstract. In the latter case the number
of nodes that are of a subtype of `t` are counted.
"""
function numNodes(spn::SumProductNetwork, t::Type{T}) where T <: Node
    cnt = 0
    for node in spn.order
        if typeof(node) <: t
            cnt += 1
        end
    end
    return cnt
end

"""
Display a SumProductNetwork object.
"""
function Base.show(io::IO, spn::SumProductNetwork)
    print(io, "SumProductNetwork(size=$(length(spn)))")
end

"""
The number of nodes of the SumProductNetwork.
"""
function Base.length(spn::SumProductNetwork)
    return numNodes(spn)
end

"""
    normalize!(spn::SumProductNetwork)

Normalizes the SPN. All edge weights emanating from a sum node sum up to 1.
"""
function Base.normalize!(spn::SumProductNetwork)
    for node in spn.order
        if typeof(node) == SumNode
            SPN.normalize!(node)
        end
    end
end

"""
    resetCounts!(spn::SumProductNetwork)

Sets the counts for each child of every `SumNode` to 0.
"""
function resetCounts!(spn::SumProductNetwork)
    for node in spn.order
        if typeof(node) == SumNode
            resetCounts!(node)
        end
    end
end


text:
using Stochy

@pp function f()
    local x = flip()
    local y = flip()
    local z = flip()
    factor(x||y ? 0 : -1)
    x+y+z
end

p = @pp enum(f)
println("Exact:")
println(p)

q = @pp enum(variational(f, 10, 10000))
println("Variational approximation:")
println(q)

k = kl(p,q)
println("KL divergence: $k")

# Exact:
# 2 | 0.445384113713482
# 1 | 0.3515386287621726
# 3 | 0.14846137123782735
# 0 | 0.05461588628651796
# INFO: Variational inference converged after 4841 steps.
# Variational approximation:
# 2 | 0.4146164710210265
# 1 | 0.32919181385372215
# 3 | 0.17045227764404255
# 0 | 0.08573943748120881
# KL divergence: 0.009832540321298086


text:
using Documenter, TensorBoardLogger

makedocs(
    modules   = [TensorBoardLogger],
    sitename  = "TensorBoardLogger.jl",
    authors   = "Filippo Vicentini",
    pages     = [
            "Home"          => "index.md",
            "Manual"        => Any[
                "Backends"     =>  "custom_behaviour.md",
                "Reading back data" => "deserialization.md",
                "Extending"    =>  "extending_behaviour.md",
                "Explicit Interface" => "explicit_interface.md"
            ],
            "Examples"      => Any[
                "Flux.jl"  => "examples/flux.md"
                "Optim.jl"  => "examples/optim.md"
            ]
    ],
    format    = Documenter.HTML(
                prettyurls = haskey(ENV, "CI"))
)

deploydocs(
    repo   = "github.com/PhilipVinc/TensorBoardLogger.jl.git",
    target = "build")


text:
#!/usr/bin/env julia

using SparseArrays
using Base.Iterators
using ArgParse

function printml(arg)
    show(IOContext(stdout), "text/plain", arg)
    println()
end

function make_rebin_matrix_1d(sizein::T, ntogroup::T) where T
    sizeout = sizein÷ntogroup
    @assert sizein%ntogroup==0

    Kblock = sparse(ones(Int64, (ntogroup,1)))
    # println("Kblock: $(Array(Kblock))")

    blockdiag(repeated(Kblock, sizeout)...)
end

function make_rebin_matrices_2d(shapein::Tuple{T,T}, ntogroup::Tuple{T,T}) where T
    Kleft  = make_rebin_matrix_1d(shapein[1], ntogroup[1])'
    Kright = make_rebin_matrix_1d(shapein[2], ntogroup[2])

    Kleft, Kright
end

function check1d(; verbose::Bool)
    sizein=12::Int64
    ngroup=4::Int64

    K = make_rebin_matrix_1d(sizein, ngroup)
    @time K = make_rebin_matrix_1d(sizein, ngroup)
    if verbose
        println("Size in: $sizein")
        println("N to group: $ngroup")
        println("Shape K: $(size(K))")
        println("K: $(Array(K))")
        println()
    end

    arrin1  = ones(Float64, (1,sizein))

    arrout1 = arrin1*K

    arrin2 = ones(Float64, (3,sizein))
    arrin2[2,:].*=2
    arrin2[3,:].*=3

    arrout2 = arrin2*K

    if verbose
        println("Shape1 in: $(size(arrin1))")
        println("Shape1 out: $(size(arrout1))")
        println("Arr1 in: $arrin1")
        println("Arr1 out: $arrout1")
        println()
        println("Shape2 in: $(size(arrin2))")
        println("Shape2 out: $(size(arrout2))")
        println("Arr2 in: $arrin2")
        println("Arr2 out: $arrout2")
        println()
    end

end

function check2d(; verbose::Bool)
    verbose = Bool(verbose)
    shapein=(6, 4)
    ngroup=(3, 2)

    Kleft, Kright = make_rebin_matrices_2d(shapein, ngroup)
    @time Kleft, Kright = make_rebin_matrices_2d(shapein, ngroup)

    if verbose
        println("N to group: $ngroup")
        println("Shape K left: $(size(Kleft))")
        println("Shape in: $shapein")
        println("Shape K right: $(size(Kright))")
        println("K left:")
        println(Kleft)
        println("K right:")
        printml(Array(Kright))
        println()
    end

    arrin1 = reshape(Array(range(0, length=prod(shapein))), reverse(shapein))'

    arrout1 = Kleft*arrin1*Kright

    arrin2 = ones(Float64, shapein)
    arrin2[begin:3, begin:2] .= 1.0
    arrin2[begin:3, 3:end]   .= 2.0
    arrin2[4:end, begin:2]   .= 3.0
    arrin2[4:end, 3:end]     .= 4.0

    arrout2 = Kleft*arrin2*Kright

    if verbose
        println("Shape1 in: $(size(arrin1))")
        println("Shape1 out: $(size(arrout1))")
        println("Arr1 in:")
        printml(arrin1)
        println("Arr1 out:")
        printml(arrout1)
        println()
        println("Shape2 in: $(size(arrin2))")
        println("Shape2 out: $(size(arrout2))")
        println("Arr2 in:")
        printml(arrin2)
        println("Arr2 out:")
        printml(arrout2)
    end
end

function parse_commandline()
    s = ArgParseSettings()

    @add_arg_table! s begin
        "--verbose", "-v"
            help = "print data"
            action = :store_true
    end

    return parse_args(s, as_symbols=true)
end

function main()
    opts = parse_commandline()
    check1d(; opts...)
    check2d(; opts...)
end

main()

max_stars_repo_name: gnafit/gna

max_issues_repo_name: gnafit/gna

max_forks_repo_name: gnafit/gna


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

@doc raw"""PodsMetricStatus indicates the current value of a metric describing each pod in the current scale target (for example, transactions-processed-per-second).

    IoK8sApiAutoscalingV2beta2PodsMetricStatus(;
        current=nothing,
        metric=nothing,
    )

    - current::IoK8sApiAutoscalingV2beta2MetricValueStatus : current contains the current value for the given metric
    - metric::IoK8sApiAutoscalingV2beta2MetricIdentifier : metric identifies the target metric by name and selector
"""
mutable struct IoK8sApiAutoscalingV2beta2PodsMetricStatus <: SwaggerModel
    current::Any # spec type: Union{ Nothing, IoK8sApiAutoscalingV2beta2MetricValueStatus } # spec name: current
    metric::Any # spec type: Union{ Nothing, IoK8sApiAutoscalingV2beta2MetricIdentifier } # spec name: metric

    function IoK8sApiAutoscalingV2beta2PodsMetricStatus(;current=nothing, metric=nothing)
        o = new()
        validate_property(IoK8sApiAutoscalingV2beta2PodsMetricStatus, Symbol("current"), current)
        setfield!(o, Symbol("current"), current)
        validate_property(IoK8sApiAutoscalingV2beta2PodsMetricStatus, Symbol("metric"), metric)
        setfield!(o, Symbol("metric"), metric)
        o
    end
end # type IoK8sApiAutoscalingV2beta2PodsMetricStatus

const _property_map_IoK8sApiAutoscalingV2beta2PodsMetricStatus = Dict{Symbol,Symbol}(Symbol("current")=>Symbol("current"), Symbol("metric")=>Symbol("metric"))
const _property_types_IoK8sApiAutoscalingV2beta2PodsMetricStatus = Dict{Symbol,String}(Symbol("current")=>"IoK8sApiAutoscalingV2beta2MetricValueStatus", Symbol("metric")=>"IoK8sApiAutoscalingV2beta2MetricIdentifier")
Base.propertynames(::Type{ IoK8sApiAutoscalingV2beta2PodsMetricStatus }) = collect(keys(_property_map_IoK8sApiAutoscalingV2beta2PodsMetricStatus))
Swagger.property_type(::Type{ IoK8sApiAutoscalingV2beta2PodsMetricStatus }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiAutoscalingV2beta2PodsMetricStatus[name]))}
Swagger.field_name(::Type{ IoK8sApiAutoscalingV2beta2PodsMetricStatus }, property_name::Symbol) =  _property_map_IoK8sApiAutoscalingV2beta2PodsMetricStatus[property_name]

function check_required(o::IoK8sApiAutoscalingV2beta2PodsMetricStatus)
    (getproperty(o, Symbol("current")) === nothing) && (return false)
    (getproperty(o, Symbol("metric")) === nothing) && (return false)
    true
end

function validate_property(::Type{ IoK8sApiAutoscalingV2beta2PodsMetricStatus }, name::Symbol, val)
end


text:
using MySQL, Tables

host = "127.0.0.1"
user = "root"
passwd = "test"
conn = DBInterface.connect(MySQL.Connection, host, user, passwd)

DBInterface.execute(conn, "drop database if exists foo")
DBInterface.execute(conn, "create database foo")
DBInterface.execute(conn, "create table foo.bar (id int, name varchar(255))")
DBInterface.execute(conn, "insert into foo.bar values (1, 'foo'), (2, 'bar')")
cursor = DBInterface.execute(conn, "select * from foo.bar")

for row in Tables.rows(cursor)
    println(row)
end
# MySQL.TextRow{true}:
# :id    1
# :name   "foo"
# MySQL.TextRow{true}:
# :id    2
# :name   "bar"


text:
export hadamard_test, hadamard_test_circuit, swap_test, swap_test_circuit, singlet_block, state_overlap_circuit

"""
see WiKi.
"""
function hadamard_test_circuit(U::MatrixBlock{N}) where N
    chain(N+1, put(N+1, 1=>H),
        control(N+1, 1, 2:N+1=>U),  # get matrix first, very inefficient
        put(N+1, 1=>H)
        )
end

function hadamard_test(U::MatrixBlock{N}, reg::AbstractRegister) where N
    c = hadamard_test_circuit(U)
    reg = join(reg, zero_state(1))
    expect(put(N+1, 1=>Z), reg |> c)
end

swap_test_circuit() = hadamard_test_circuit(SWAP)
swap_test(reg::AbstractRegister) = hadamard_test(SWAP, reg)

function singlet_block(::Type{T}, nbit::Int, i::Int, j::Int) where T
    unit = chain(nbit)
    push!(unit, put(nbit, i=>chain(XGate{T}(), HGate{T}())))
    push!(unit, control(nbit, -i, j=>XGate{T}()))
end

singlet_block(nbit::Int, i::Int, j::Int) = singlet_block(ComplexF64, nbit, i, j)
singlet_block() = singlet_block(2,1,2)

"""
Estimation of overlap between multiple density matrices.

PRL 88.217901
"""
function state_overlap_circuit(nbit::Int, nstate::Int, ϕ::Real)
    N = nstate*nbit + 1

    chain(N, put(N, 1=>H),
        put(N, 1=>shift(ϕ)),
        chain(N, [chain(N, [control(N, 1, (i+(k*nbit-nbit)+1, i+k*nbit+1)=>SWAP) for i=1:nbit]) for k=1:nstate-1]),  # get matrix first, very inefficient
        put(N, 1=>H)
        )
end

Yao.mat(ρ::DensityMatrix{1}) = dropdims(state(ρ), dims=3)


text:
mutable struct GeneralDataType <: MyXMLElement
    el::XMLOrNothing
    states::Vector{Int}
    id::String

    function GeneralDataType(states::Vector{Int}, id::String)
        return new(nothing, states, id::String)
    end
end

function GeneralDataType(n::Int; id::String = "discreteStates")
    return GeneralDataType(collect(0:(n - 1)), id)
end

function name(::GeneralDataType)
    return bn.GENERAL_DATA_TYPE
end

function make_xml(gdt::GeneralDataType)
    el = new_element(name(gdt))
    set_attribute(el, bn.ID, gdt.id)

    for i = 1:length(gdt.states)
        state_el = new_child(el, bn.STATE)
        set_attribute(state_el, bn.CODE, gdt.states[i])
    end

    gdt.el = el
    return el
end

################################################################################
## aligments
################################################################################

const MISSING_SEQUENCE = 9

mutable struct Alignment <: MyXMLElement
    el::XMLOrNothing
    data_type::MyXMLElement
    taxa::Vector{<:AbstractString}
    sequences::Matrix{Int}
    id::String

    function Alignment(data_type::MyXMLElement,
                        taxa::Vector{<:AbstractString},
                        sequences::Matrix{Int};
                        id::String = bn.ALIGNMENT)
        @assert length(taxa) == size(sequences, 1)
        return new(nothing, data_type, taxa, sequences, id)
    end
end

function name(::Alignment)
    return bn.ALIGNMENT
end

function make_xml(al::Alignment)
    el = new_element(name(al))
    set_attribute(el, bn.ID, al.id)
    add_ref_el(el, al.data_type)
    for i = 1:size(al.sequences, 1)
        seq_el = new_child(el, bn.SEQUENCE)
        taxon_el = new_child(seq_el, bn.TAXON)
        set_attribute(taxon_el, bn.IDREF, al.taxa[i])
        seq_text = join(al.sequences[i, :], ' ')
        add_text(seq_el, seq_text)
    end

    al.el = el
    return el
end

function get_num_classes(alignment::Alignment)
    @unpack sequences = alignment
    p = size(alignment.sequences, 2)
    return length.([setdiff(unique(sequences[:, i]), MISSING_SEQUENCE) for i = 1:p])
end

################################################################################
## patterns
################################################################################

mutable struct Patterns <: MyXMLElement
    el::XMLOrNothing
    alignment::Alignment
    id::String

    function Patterns(alignment::Alignment; id::String = bn.PATTERNS)
        return new(nothing, alignment, id)
    end
end

function name(::Patterns)
    return bn.PATTERNS
end

function make_xml(patterns::Patterns)
    @unpack alignment, id = patterns

    el = new_element(name(patterns))
    set_attribute(el, bn.ID, id)
    set_attribute(el, bn.FROM, "1")
    set_attribute(el, bn.UNIQUE, bn.FALSE)
    add_ref_el(el, alignment)
    patterns.el = el

    return el
end

function get_num_classes(patterns::Patterns)
    return get_num_classes(patterns.alignment)
end

################################################################################
## likelihood
################################################################################

mutable struct OrderedLatentLiability <: MyXMLElement
    el::XMLOrNothing
    patterns::Patterns
    treeModel::TreeModelXMLElement
    threshold::CompoundParameter
    id::String
    trait_name::String

    function OrderedLatentLiability(patterns::Patterns,
                                    treeModel::TreeModelXMLElement,
                                    threshold::CompoundParameter;
                                    id::String = bn.ORDERED_LATENT_LIABILITY,
                                    trait_name::String = treeModel.param_names[1])

        return new(nothing, patterns, treeModel, threshold, id, trait_name)
    end
end

function OrderedLatentLiability(patterns::Patterns,
                                treeModel::TreeModelXMLElement;
                                id::String = bn.ORDERED_LATENT_LIABILITY,
                                trait_name::String = treeModel.param_names[1])
    n_states = get_num_classes(patterns)
    need_thresh = findall(x -> x > 2, n_states)

    params = Parameter[]
    if length(need_thresh) == 0
        push!(params, Parameter([0.0]))
    else
        for ind in need_thresh
            p_id = "$trait_name$ind.threshold"
            thresholds = default_thresholds(n_states[ind])
            push!(params, Parameter(thresholds, p_id, lower=0.0))
        end
    end

    cp = CompoundParameter(params, "$trait_name.threshold")
    return OrderedLatentLiability(patterns, treeModel, cp, id = id, trait_name = trait_name)

end

function name(::OrderedLatentLiability)
    return bn.ORDERED_LATENT_LIABILITY
end

function make_xml(oll::OrderedLatentLiability)
    @unpack patterns, treeModel, threshold, id = oll
    el = new_element(name(oll))
    add_ref_el(el, patterns)
    add_ref_el(el, treeModel)
    tip_el = new_child(el, bn.TIP_TRAIT)
    add_ref_el(tip_el, Parameter(Float64[], oll.trait_name))

    thresh_el = new_child(el, bn.THRESHOLD)
    add_child(thresh_el, make_xml(threshold))

    classes_el = new_child(el, bn.NUM_CLASSES)
    classes = get_num_classes(patterns)
    class_param = Parameter(Float64.(classes))
    add_child(classes_el, make_xml(class_param))

    set_attribute(el, bn.N_TRAITS, string(length(classes)))
    set_attribute(el, bn.N_DATA, "1")
    set_attribute(el, bn.ID, oll.id)

    oll.el = el
    return el
end

################################################################################
## operator
################################################################################

mutable struct ExtendedLatendLiabilityOperator <: OperatorXMLElement
    el::XMLOrNothing
    trait_likelihood::TraitLikelihoodXMLElement
    latent_liability::OrderedLatentLiability
    weight::Float64

    function ExtendedLatendLiabilityOperator(
            trait_likelihood::TraitLikelihoodXMLElement,
            latent_liability::OrderedLatentLiability;
            weight::Float64 = 1.0)

        return new(nothing, trait_likelihood, latent_liability, weight)
    end

end

function name(::ExtendedLatendLiabilityOperator)
    return bn.EXTENDED_GIBBS_OPERATOR
end

function make_xml(elo::ExtendedLatendLiabilityOperator)
    el = new_element(name(elo))

    set_attribute(el, bn.WEIGHT, elo.weight)
    add_ref_el(el, elo.trait_likelihood)
    add_ref_el(el, elo.latent_liability)
    elo.el = el
    return el
end

################################################################################
## helpers
################################################################################

function default_thresholds(states::Int)
    return convert.(Float64, collect(1:(states - 2)))
end

function find_state(x::Float64, thresholds::Vector{Float64})
    n = length(thresholds)

    if isnan(x)
        if n >= MISSING_SEQUENCE
            error("Cannot accomodate more than $MISSING_SEQUENCE patterns current missing code.")
        end
        return MISSING_SEQUENCE
    end

    state = 0
    for i = 1:n
        if x < thresholds[i]
            return i - 1
        end
    end
    return n
end

function data_to_alignment(data::Matrix{Float64}, states::Vector{Int};
            thresholds::Vector{Vector{Float64}} = default_thresholds.(states),
            bin_discrete::Bool = false)

    n, p = size(data)
    sequences = zeros(Int, n, p)

    for j = 1:p
        n_states = states[j]
        if n_states > 1
            if bin_discrete
                for i = 1:n
                    sequences[i, j] = find_state(data[i, j], thresholds[j])
                end
            else
                for i = 1:n
                    if isnan(data[i, j])
                        sequences[i, j] = MISSING_SEQUENCE
                    else
                        sequences[i, j] = Int(data[i, j])
                    end
                end
            end
        end
    end

    return sequences

end

################################################################################
## latent liability
################################################################################

function add_latent_liability(bx::BEASTXMLElement, trait_names::Vector{String}, states::Vector{Int})
    m = length(trait_names)
    gdt = GeneralDataType(maximum(states))
    ops_ind = find_element_ind(bx, OperatorsXMLElement)

    add_child(bx, gdt, ops_ind)

    for nm in trait_names
        latent_liablity = latent_liablity_elements(bx, nm, states, gdt)
    end
end

function add_latent_liability(bx::BEASTXMLElement, discrete_inds::Vector{Int})

    if length(discrete_inds) == 0
        return nothing
    end

    data_el = find_element(bx, DataXMLElement)
    @unpack data_mats = data_el
    ps = [size(x, 2) for x in data_mats]
    @assert length(unique(ps)) == 1
    p = ps[1]
    states = ones(Int, p)

    for data in data_el.data_mats
        for ind in discrete_inds
            ind_states = setdiff(unique(@view data[:, ind]), NaN)
            states[ind] = max(Int(maximum(ind_states)) + 1, states[ind])
        end
    end

    set_factor_precision_indices(bx, setdiff(1:p, discrete_inds))

    add_latent_liability(bx, data_el.trait_names, states)
end

function latent_liablity_elements(bx::BEASTXMLElement, trait_name::String, states::Vector{Int}, gdt::GeneralDataType)

    data_el = find_element(bx, DataXMLElement)
    treeModel = find_element(bx, TreeModelXMLElement)
    trait_likelihood = find_element(bx, TraitLikelihoodXMLElement)
    int_fac = trait_likelihood.extension_el

    if BEASTXMLConstructor.get_trait_name(int_fac) != trait_name
        flpd = find_element(bx, FactorLogPredictiveDensity)
        trait_likelihood = flpd.like
    end

    @assert BEASTXMLConstructor.get_trait_name(trait_likelihood.extension_el) == trait_name

    precs = get_precision(int_fac)
    set_value(precs, fill(2.0, length(precs)))

    taxa = data_el.taxa
    trait_ind = findfirst(isequal(trait_name), data_el.trait_names)
    data = data_el.data_mats[trait_ind]

    sequence = data_to_alignment(data, states)
    alignment = Alignment(gdt, taxa, sequence, id=trait_name * ".alignment")
    pattern = Patterns(alignment, id=trait_name * ".patterns")

    param_name = treeModel.param_names[findfirst(isequal(trait_name), treeModel.node_traits)]

    likelihood = OrderedLatentLiability(pattern, treeModel, id = trait_name * ".latentLiability", trait_name = param_name)

    operator = ExtendedLatendLiabilityOperator(trait_likelihood, likelihood)
    thresh_ops = MyXMLElement[]
    if (maximum(get_num_classes(likelihood.patterns)) > 2)
        for param in likelihood.threshold.parameters
            push!(thresh_ops, ScaleOperator(param))
        end
    end
    # threshold_operator = ScaleOperator(likelihood.threshold)

    ops_ind = find_element_ind(bx, OperatorsXMLElement)
    operators = bx.components[ops_ind]
    for el in [alignment, pattern, likelihood]
        add_child(bx, el, ops_ind)
        ops_ind += 1
    end

    push!(operators.els, operator)
    for op in thresh_ops
        push!(operators.els, op)
    end

    mcmc_el = find_element(bx, MCMCXMLElement)
    BEASTXMLConstructor.add_likelihood!(mcmc_el, likelihood)
    BEASTXMLConstructor.add_loggable(bx, likelihood.threshold, already_made = true)
    BEASTXMLConstructor.add_loggable(bx, Parameter(Float64[], param_name), already_made = true)

    return likelihood
end