@ Suppress ( "<STR_LIT:FunctionName>" , "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public fun < T > MutableSharedFlow ( replay : Int = <NUM_LIT:0> , extraBufferCapacity : Int = <NUM_LIT:0> , onBufferOverflow : BufferOverflow = BufferOverflow . SUSPEND ) : MutableSharedFlow < T >

{ <EOL> require ( replay >= <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> require ( extraBufferCapacity >= <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> require ( replay > <NUM_LIT:0> || extraBufferCapacity > <NUM_LIT:0> || onBufferOverflow == BufferOverflow . SUSPEND ) { <EOL> "<STR_LIT>" <EOL> } <EOL> val bufferCapacity0 = replay + extraBufferCapacity <EOL> val bufferCapacity = if ( bufferCapacity0 < <NUM_LIT:0> ) Int . MAX_VALUE else bufferCapacity0 <EOL> return SharedFlowImpl ( replay , bufferCapacity , onBufferOverflow ) <EOL> }

/**
 * Creates a [MutableSharedFlow] with the given configuration parameters.
 *
 * This function throws [IllegalArgumentException] on unsupported values of parameters or combinations thereof.
 *
 * @param replay the number of values replayed to new subscribers (cannot be negative, defaults to zero).
 * @param extraBufferCapacity the number of values buffered in addition to `replay`.
 * [emit][MutableSharedFlow.emit] does not suspend while there is a buffer space remaining (optional, cannot be negative, defaults to zero).
 * @param onBufferOverflow configures an [emit][MutableSharedFlow.emit] action on buffer overflow. Optional, defaults to
 * [suspending][BufferOverflow.SUSPEND] attempts to emit a value.
 * Values other than [BufferOverflow.SUSPEND] are supported only when `replay > 0` or `extraBufferCapacity > 0`.
 * **Buffer overflow can happen only when there is at least one subscriber that is not ready to accept
 * the new value.** In the absence of subscribers only the most recent [replay] values are stored and
 * the buffer overflow behavior is never triggered and has no effect.
 */


{ <EOL> if ( tryEmit ( value ) ) return <EOL> emitSuspend ( value ) <EOL> }

/**
 * Emits a [value] to this shared flow, suspending on buffer overflow.
 *
 * This call can suspend only when the [BufferOverflow] strategy is
 * [SUSPEND][BufferOverflow.SUSPEND] **and** there are subscribers collecting this shared flow.
 *
 * If there are no subscribers, the buffer is not used.
 * Instead, the most recently emitted value is simply stored into
 * the replay cache if one was configured, displacing the older elements there,
 * or dropped if no replay cache was configured.
 *
 * See [tryEmit] for a non-suspending variant of this function.
 *
 * This method is **thread-safe** and can be safely invoked from concurrent coroutines without
 * external synchronization.
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun getOrElse ( key : K , orElse : ( ) -> V ) : V

= <EOL> when ( val value = map [ key ] ) { <EOL> null -> orElse ( ) <EOL> NullValue -> null <EOL> else -> value <EOL> } as V

/**
 * Get value if it is present in map
 * Execute [orElse] otherwise and return it result,
 * [orElse] can modify the map inside
 */


fun LexicalScope . getImplicitReceiversHierarchy ( ) : List < ReceiverParameterDescriptor >

= collectFromMeAndParent { <EOL> if ( it is LexicalScope ) listOfNotNull ( it . implicitReceiver ) + it . contextReceiversGroup else null <EOL> } . flatten ( )

/**
 * Adds receivers to the list in order of locality, so that the closest (the most local) receiver goes first
 */


public fun < T > publish ( context : CoroutineContext = EmptyCoroutineContext , @ BuilderInference block : suspend ProducerScope < T > . ( ) -> Unit ) : Publisher < T >

{ <EOL> require ( context [ Job ] === null ) { "<STR_LIT>" + <EOL> "<STR_LIT>" } <EOL> return publishInternal ( GlobalScope , context , DEFAULT_HANDLER , block ) <EOL> }

/**
 * Creates a cold reactive [Publisher] that runs a given [block] in a coroutine.
 *
 * Every time the returned flux is subscribed, it starts a new coroutine in the specified [context].
 * The coroutine emits (via [Subscriber.onNext]) values with [send][ProducerScope.send],
 * completes (via [Subscriber.onComplete]) when the coroutine completes or channel is explicitly closed, and emits
 * errors (via [Subscriber.onError]) if the coroutine throws an exception or closes channel with a cause.
 * Unsubscribing cancels the running coroutine.
 *
 * Invocations of [send][ProducerScope.send] are suspended appropriately when subscribers apply back-pressure and to
 * ensure that [onNext][Subscriber.onNext] is not invoked concurrently.
 *
 * Coroutine context can be specified with [context] argument.
 * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is
 * used.
 *
 * **Note: This is an experimental api.** Behaviour of publishers that work as children in a parent scope with respect
 * to cancellation and error handling may change in the future.
 *
 * @throws IllegalArgumentException if the provided [context] contains a [Job] instance.
 */


@ InternalCoroutinesApi <EOL> public fun < T > publishInternal ( scope : CoroutineScope , context : CoroutineContext , exceptionOnCancelHandler : ( Throwable , CoroutineContext ) -> Unit , block : suspend ProducerScope < T > . ( ) -> Unit ) : Publisher < T >

= Publisher { subscriber -> <EOL> if ( subscriber == null ) throw NullPointerException ( "<STR_LIT>" ) <EOL> val newContext = scope . newCoroutineContext ( context ) <EOL> val coroutine = PublisherCoroutine ( newContext , subscriber , exceptionOnCancelHandler ) <EOL> subscriber . onSubscribe ( coroutine ) <EOL> coroutine . start ( CoroutineStart . DEFAULT , coroutine , block ) <EOL> }

/** @suppress For internal use from other reactive integration modules only */


private fun doLockedNext ( elem : T ) : Throwable ?

{ <EOL> if ( elem == null ) { <EOL> unlockAndCheckCompleted ( ) <EOL> throw NullPointerException ( "<STR_LIT>" ) <EOL> } <EOL> if ( ! isActive ) { <EOL> unlockAndCheckCompleted ( ) <EOL> return getCancellationException ( ) <EOL> } <EOL> try { <EOL> subscriber . onNext ( elem ) <EOL> } catch ( cause : Throwable ) { <EOL> cancelled = true <EOL> val causeDelivered = close ( cause ) <EOL> unlockAndCheckCompleted ( ) <EOL> return if ( causeDelivered ) { <EOL> cause <EOL> } else { <EOL> exceptionOnCancelHandler ( cause , context ) <EOL> getCancellationException ( ) <EOL> } <EOL> } <EOL> while ( true ) { <EOL> val current = _nRequested . value <EOL> if ( current < <NUM_LIT:0> ) break <EOL> if ( current == Long . MAX_VALUE ) break <EOL> val updated = current - <NUM_LIT:1> <EOL> if ( _nRequested . compareAndSet ( current , updated ) ) { <EOL> if ( updated == <NUM_LIT:0L> ) { <EOL> return null <EOL> } <EOL> break <EOL> } <EOL> } <EOL> unlockAndCheckCompleted ( ) <EOL> return null <EOL> }

/**
 * Attempts to emit a value to the subscriber and, if back-pressure permits this, unlock the mutex.
 *
 * Requires that the caller has locked the mutex before this invocation.
 *
 * If the channel is closed, returns the corresponding [Throwable]; otherwise, returns `null` to denote success.
 *
 * @throws NullPointerException if the passed element is `null`
 */


fun < T : Number > exp ( x : KtNDArray < T > ) : KtNDArray < Double >

= callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( x ) )

/**
 * Calculate the exponential of all elements in the input array.
 */


fun < T : Number > expm1 ( x : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Calculate exp(x) - 1 for all elements in the array.
 */


fun < T : Number > exp2 ( x : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Calculate 2**p for all p in the input array.
 */


fun < T : Number > log ( x : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Natural logarithm, element-wise.
 */


fun < T : Number > log10 ( x : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Return the base 10 logarithm of the input array, element-wise.
 */


fun < T : Number > log2 ( x : KtNDArray < T > ) : KtNDArray < Double >


fun < T : Number > log1p ( x : KtNDArray < T > ) : KtNDArray < Double >

/**
 * Return the natural logarithm of one plus the input array, element-wise.
 */


fun < T : Number , E : Number > logaddexp ( x1 : KtNDArray < T > , x2 : KtNDArray < E > ) : KtNDArray < Double >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( x1 , x2 ) )

/**
 * Logarithm of the sum of exponentiations of the inputs.
 */


fun < T : Number , E : Number > logaddexp2 ( x1 : KtNDArray < T > , x2 : KtNDArray < E > ) : KtNDArray < Double >

/**
 * Logarithm of the sum of exponentiations of the inputs in base-2.
 */


@ JvmStatic <EOL> @ Synchronized <EOL> internal fun initStatsService ( project : Project )

{ <EOL> runMetricMethodSafely ( logger , "<STR_LIT>" ) { <EOL> val gradle = project . gradle <EOL> val configurationTimePropertiesAccessor = project . configurationTimePropertiesAccessor <EOL> val statisticsIsEnabled = checkStatisticsEnabled ( gradle , project . providers , configurationTimePropertiesAccessor ) <EOL> if ( ! statisticsIsEnabled ) { <EOL> null <EOL> } else { <EOL> val registry = kotlinBuildStatsServicesRegistry ? : KotlinBuildStatsServicesRegistry ( ) . also { <EOL> kotlinBuildStatsServicesRegistry = it <EOL> } <EOL> registry . registerServices ( project ) <EOL> } <EOL> } <EOL> }

/**
 * Method for creating new instance of [StatisticsValuesConsumer]
 * It could be invoked only when applying Kotlin gradle plugin.
 * When executed, this method checks, whether it is already executed in the current build (whether it was already executed
 * in the same classpath (i.e., with the same version of Kotlin plugin)).
 * If it was not executed, the new instance of StatisticsValuesConsumer is created
 *
 * [closeServices] must be called at the end of the build in order to release resources.
 */


public fun readOpenApi ( uri : String , name : String , auth : List < AuthorizationValue > ? = null , options : ParseOptions ? = null , extensionProperties : Boolean , generateHelperCompanionObject : Boolean , visibility : MarkerVisibility = MarkerVisibility . IMPLICIT_PUBLIC , ) : Code

{ <EOL> require ( isOpenApi ( uri ) ) { "<STR_LIT>" } <EOL> return readOpenApi ( swaggerParseResult = OpenAPIParser ( ) . readLocation ( uri , auth , options ) , name = name , extensionProperties = extensionProperties , visibility = visibility , generateHelperCompanionObject = generateHelperCompanionObject , ) <EOL> }

/** Parse and read OpenApi specification to [DataSchema] interfaces. */


public fun readOpenApiAsString ( openApiAsString : String , name : String , auth : List < AuthorizationValue > ? = null , options : ParseOptions ? = null , extensionProperties : Boolean , generateHelperCompanionObject : Boolean , visibility : MarkerVisibility = MarkerVisibility . IMPLICIT_PUBLIC , ) : Code

{ <EOL> require ( isOpenApiStr ( openApiAsString ) ) { "<STR_LIT>" } <EOL> return readOpenApi ( swaggerParseResult = OpenAPIParser ( ) . readContents ( openApiAsString , auth , options ) , name = name , extensionProperties = extensionProperties , visibility = visibility , generateHelperCompanionObject = generateHelperCompanionObject , ) <EOL> }


private fun readOpenApi ( swaggerParseResult : SwaggerParseResult , name : String , extensionProperties : Boolean , generateHelperCompanionObject : Boolean , visibility : MarkerVisibility = MarkerVisibility . IMPLICIT_PUBLIC , ) : Code

{ <EOL> val openApi = swaggerParseResult . openAPI <EOL> ? : error ( "<STR_LIT>" ) <EOL> val topInterfaceName = ValidFieldName . of ( name ) <EOL> val result = openApi . components ? . schemas <EOL> ? . toMap ( ) <EOL> ? . toMarkers ( topInterfaceName ) <EOL> ? . toList ( ) <EOL> ? : emptyList ( ) <EOL> val codeGenerator = CodeGenerator . create ( useFqNames = true ) <EOL> fun toCode ( marker : OpenApiMarker ) : Code = <EOL> codeGenerator . generate ( marker = marker . withVisibility ( visibility ) . withName ( name = marker . name . withoutTopInterfaceName ( topInterfaceName ) , prependTopInterfaceName = false , ) , interfaceMode = when ( marker ) { <EOL> is OpenApiMarker . Enum -> InterfaceGenerationMode . Enum <EOL> is OpenApiMarker . Interface -> InterfaceGenerationMode . WithFields <EOL> is OpenApiMarker . TypeAlias , is OpenApiMarker . MarkerAlias -> InterfaceGenerationMode . TypeAlias <EOL> } , extensionProperties = false , readDfMethod = if ( marker is OpenApiMarker . Interface ) DefaultReadOpenApiMethod else null , ) . declarations <EOL> fun Code . merge ( other : Code ) : Code = "<STR_LIT>" <EOL> fun toExtensionProperties ( marker : OpenApiMarker ) : Code = <EOL> if ( marker !is OpenApiMarker . Interface ) "<STR_LIT>" <EOL> else codeGenerator . generate ( marker = marker . withVisibility ( visibility ) , interfaceMode = InterfaceGenerationMode . None , extensionProperties = true , readDfMethod = null , ) . declarations <EOL> val ( typeAliases , markers ) = result <EOL> . partition { it is OpenApiMarker . TypeAlias || it is OpenApiMarker . MarkerAlias } <EOL> val generatedMarkers = markers <EOL> . map ( :: toCode ) <EOL> . reduceOrNull ( Code :: merge ) <EOL> ? : "<STR_LIT>" <EOL> val generatedTypeAliases = typeAliases <EOL> . map ( :: toCode ) <EOL> . reduceOrNull ( Code :: merge ) <EOL> ? : "<STR_LIT>" <EOL> val generatedExtensionProperties = <EOL> if ( ! extensionProperties ) "<STR_LIT>" <EOL> else result <EOL> . map ( :: toExtensionProperties ) <EOL> . reduceOrNull ( Code :: merge ) <EOL> ? : "<STR_LIT>" <EOL> val helperCompanionObject = <EOL> if ( ! generateHelperCompanionObject ) "<STR_LIT>" <EOL> else { <EOL> val accessors = markers <EOL> . filterIsInstance < OpenApiMarker . Interface > ( ) <EOL> . joinToString ( "<STR_LIT>" ) { <EOL> "<STR_LIT>" <EOL> } <EOL> """<STR_LIT>""" <EOL> } <EOL> return """<STR_LIT>""" . trimMargin ( ) <EOL> }

/**
 * Converts a parsed OpenAPI specification into [Code] consisting of [DataSchema] interfaces.
 *
 * @param swaggerParseResult the result of parsing an OpenAPI specification, created using [readOpenApi] or [readOpenApiAsString].
 * @param extensionProperties whether to add extension properties to the generated interfaces. This is usually not
 * necessary, since both the KSP- and the Gradle plugin, will add extension properties to the generated code.
 * @param visibility the visibility of the generated marker classes.
 *
 * @return a [Code] object, representing the generated code.
 */


private fun Map < String , Schema < * > > . toMarkers ( topInterfaceName : ValidFieldName ) : List < OpenApiMarker >

{ <EOL> val retrievableMarkers = mapValues { ( typeName , value ) -> <EOL> RetrievableMarker { getRefMarker , produceAdditionalMarker -> <EOL> value . toMarker ( typeName = typeName , getRefMarker = getRefMarker , produceAdditionalMarker = produceAdditionalMarker , topInterfaceName = topInterfaceName , ) <EOL> } <EOL> } . toMutableMap ( ) <EOL> val markers = mutableMapOf < String , OpenApiMarker > ( ) <EOL> val getRefMarker = GetRefMarker { MarkerResult . fromNullable ( markers [ it ] ) } <EOL> while ( retrievableMarkers . isNotEmpty ( ) ) try { <EOL> retrievableMarkers . entries . first { ( name , retrieveMarker ) -> <EOL> val additionalMarkers = mutableMapOf < String , OpenApiMarker > ( ) <EOL> val produceAdditionalMarker = ProduceAdditionalMarker { validName , marker , _ -> <EOL> var result = ValidFieldName . of ( validName . unquoted ) <EOL> val baseName = result <EOL> var attempt = <NUM_LIT:1> <EOL> while ( result . quotedIfNeeded in markers || result . quotedIfNeeded in additionalMarkers ) { <EOL> result = ValidFieldName . of ( baseName . unquoted + ( if ( result . needsQuote ) "<STR_LIT>" else "<STR_LIT>" ) ) <EOL> attempt ++ <EOL> } <EOL> additionalMarkers [ result . quotedIfNeeded ] = marker . withName ( result . quotedIfNeeded ) <EOL> result . quotedIfNeeded <EOL> } <EOL> val res = retrieveMarker ( getRefMarker = getRefMarker , produceAdditionalMarker = produceAdditionalMarker , ) <EOL> when ( res ) { <EOL> is MarkerResult . OpenApiMarker -> { <EOL> markers [ name ] = res . marker <EOL> markers += additionalMarkers <EOL> retrievableMarkers -= name <EOL> true <EOL> } <EOL> is MarkerResult . CannotFindRefMarker -> <EOL> false <EOL> } <EOL> } <EOL> } catch ( e : NoSuchElementException ) { <EOL> throw IllegalStateException ( "<STR_LIT>" , e , ) <EOL> } <EOL> return markers . values . toList ( ) <EOL> }

/**
 * Converts named OpenApi schemas to a list of [OpenApiMarker]s.
 * Will cause an exception for circular references, however they shouldn't occur in OpenApi specs.
 *
 * Some explanation:
 * OpenApi provides schemas for all the types used. For each type, we want to generate a [Marker]
 * (Which can be an interface, enum or typealias). However, the OpenApi schema is not ordered per se,
 * so when we are reading the schema it might be that we have a reference to a (super)type
 * (which are queried using `getRefMarker`) for which we have not yet created a [Marker].
 * In that case, we "pause" that one (by returning `CannotFindRefMarker`) and try to read another type schema first.
 * Circular references cannot exist since it's encoded in JSON, so we never get stuck in an infinite loop.
 * When all markers are "retrieved" (so turned from a [RetrievableMarker] to a [MarkerResult.OpenApiMarker]),
 * we're done and have converted everything!
 * As for `produceAdditionalMarker`: In OpenAPI not all enums/objects have to be defined as a separate schema.
 * Although recommended, you can still define an object anonymously directly as a type. For this, we have
 * `produceAdditionalMarker` since during the conversion of a schema -> [Marker] we get an additional new [Marker].
 */


private fun Schema < * > . toMarker ( typeName : String , getRefMarker : GetRefMarker , produceAdditionalMarker : ProduceAdditionalMarker , topInterfaceName : ValidFieldName , required : List < String > = emptyList ( ) , ) : MarkerResult

{ <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> val required = ( this . required ? : emptyList ( ) ) + required <EOL> val nullable = nullable ? : false <EOL> return when { <EOL> allOf != null -> { <EOL> val allOfSchemas = allOf ! ! . associateWith { <EOL> it . toOpenApiType ( getRefMarker = getRefMarker ) <EOL> } <EOL> val requiredFields = <EOL> ( allOfSchemas . keys . flatMap { it . required ? : emptyList ( ) } + required ) . distinct ( ) <EOL> val superMarkers = mutableListOf < Marker > ( ) <EOL> val fields = mutableListOf < GeneratedField > ( ) <EOL> val additionalPropertyPaths = mutableListOf < JsonPath > ( ) <EOL> for ( ( schema , openApiTypeResult ) in allOfSchemas ) <EOL> when ( openApiTypeResult ) { <EOL> is OpenApiTypeResult . CannotFindRefMarker -> <EOL> return MarkerResult . CannotFindRefMarker <EOL> is OpenApiTypeResult . UsingRef -> { <EOL> val superMarker = openApiTypeResult . marker <EOL> superMarkers += superMarker <EOL> additionalPropertyPaths += superMarker . additionalPropertyPaths <EOL> val allSuperFields = <EOL> ( superMarker . fields + superMarker . allSuperMarkers . values . flatMap { it . fields } ) <EOL> . distinctBy { it . fieldName . unquoted } <EOL> fields += allSuperFields <EOL> . filter { <EOL> it . fieldName . unquoted in requiredFields && it . fieldType . isNullable ( ) <EOL> } . map { <EOL> generatedFieldOf ( fieldName = it . fieldName , columnName = it . columnName , fieldType = it . fieldType . toNotNullable ( ) , overrides = true , ) <EOL> } <EOL> } <EOL> is OpenApiTypeResult . Enum -> error ( "<STR_LIT>" ) <EOL> is OpenApiTypeResult . OpenApiType -> { <EOL> val ( openApiType , nullable ) = openApiTypeResult <EOL> openApiType as OpenApiType . Object <EOL> var tempMarker : OpenApiMarker ? = null <EOL> val fieldTypeResult = openApiType . toFieldType ( schema = schema , schemaName = typeName , nullable = nullable , getRefMarker = getRefMarker , produceAdditionalMarker = { name , marker , isTopLevelObject -> <EOL> if ( isTopLevelObject ) { <EOL> tempMarker = marker <EOL> name . quotedIfNeeded <EOL> } else { <EOL> produceAdditionalMarker ( name , marker , false ) <EOL> } <EOL> } , required = required , topInterfaceName = topInterfaceName , ) <EOL> when ( fieldTypeResult ) { <EOL> is FieldTypeResult . CannotFindRefMarker -> { <EOL> return MarkerResult . CannotFindRefMarker <EOL> } <EOL> is FieldTypeResult . FieldType -> { <EOL> fields += tempMarker ! ! . fields <EOL> additionalPropertyPaths += fieldTypeResult . additionalPropertyPaths <EOL> } <EOL> } <EOL> } <EOL> } <EOL> MarkerResult . OpenApiMarker ( OpenApiMarker . Interface ( nullable = nullable , name = typeName , fields = fields , superMarkers = superMarkers , additionalPropertyPaths = additionalPropertyPaths , topInterfaceName = topInterfaceName , ) ) <EOL> } <EOL> enum != null -> { <EOL> val openApiTypeResult = toOpenApiType ( getRefMarker = getRefMarker , ) as OpenApiTypeResult . Enum <EOL> val enumMarker = produceNewEnum ( name = typeName , topInterfaceName = topInterfaceName , values = openApiTypeResult . values , nullable = openApiTypeResult . nullable , produceAdditionalMarker = ProduceAdditionalMarker . NOOP , ) <EOL> MarkerResult . OpenApiMarker ( enumMarker ) <EOL> } <EOL> type == "<STR_LIT:object>" -> when { <EOL> properties != null -> { <EOL> if ( additionalProperties != null && additionalProperties != false ) { <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> val keyValuePaths = mutableListOf < JsonPath > ( ) <EOL> val fields = buildList { <EOL> for ( ( name , property ) in ( properties ? : emptyMap ( ) ) ) { <EOL> val isRequired = name in required <EOL> val openApiTypeResult = property . toOpenApiType ( getRefMarker = getRefMarker , ) <EOL> when ( openApiTypeResult ) { <EOL> is OpenApiTypeResult . CannotFindRefMarker -> <EOL> return MarkerResult . CannotFindRefMarker <EOL> is OpenApiTypeResult . UsingRef -> { <EOL> keyValuePaths += openApiTypeResult . marker <EOL> . additionalPropertyPaths <EOL> . map { it . prepend ( name ) } <EOL> val validName = ValidFieldName . of ( name . snakeToLowerCamelCase ( ) ) <EOL> val fieldType = openApiTypeResult . marker . toFieldType ( ) <EOL> . let { if ( ! isRequired ) it . toNullable ( ) else it } <EOL> this += generatedFieldOf ( overrides = false , fieldName = validName , columnName = name , fieldType = fieldType , ) <EOL> } <EOL> is OpenApiTypeResult . Enum -> { <EOL> val enumMarker = produceNewEnum ( name = name , topInterfaceName = topInterfaceName , values = openApiTypeResult . values , produceAdditionalMarker = produceAdditionalMarker , nullable = openApiTypeResult . nullable , ) <EOL> this += generatedFieldOf ( overrides = false , fieldName = ValidFieldName . of ( name . snakeToLowerCamelCase ( ) ) , columnName = name , fieldType = FieldType . ValueFieldType ( typeFqName = enumMarker . name + if ( enumMarker . nullable || ! isRequired ) "<STR_LIT:?>" else "<STR_LIT>" , ) , ) <EOL> } <EOL> is OpenApiTypeResult . OpenApiType -> { <EOL> val ( openApiType , nullable ) = openApiTypeResult <EOL> val fieldTypeResult = openApiType . toFieldType ( schema = property , schemaName = name , nullable = nullable , getRefMarker = getRefMarker , produceAdditionalMarker = produceAdditionalMarker , required = required , topInterfaceName = topInterfaceName , ) <EOL> when ( fieldTypeResult ) { <EOL> is FieldTypeResult . CannotFindRefMarker -> <EOL> return MarkerResult . CannotFindRefMarker <EOL> is FieldTypeResult . FieldType -> { <EOL> val validName = ValidFieldName . of ( name . snakeToLowerCamelCase ( ) ) <EOL> keyValuePaths += fieldTypeResult <EOL> . additionalPropertyPaths <EOL> . map { it . prepend ( name ) } <EOL> this += generatedFieldOf ( overrides = false , fieldName = validName , columnName = name , fieldType = fieldTypeResult . fieldType . let { <EOL> if ( ! isRequired ) it . toNullable ( ) else it <EOL> } , ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> MarkerResult . OpenApiMarker ( OpenApiMarker . Interface ( nullable = nullable , name = typeName , fields = fields , superMarkers = emptyList ( ) , additionalPropertyPaths = keyValuePaths , topInterfaceName = topInterfaceName , ) ) <EOL> } <EOL> properties == null && additionalProperties != null && additionalProperties != false -> { <EOL> val openApiTypeResult = ( additionalProperties as? Schema < * > ) <EOL> ? . toOpenApiType ( getRefMarker = getRefMarker ) <EOL> val additionalPropertyPaths = mutableListOf < JsonPath > ( ) <EOL> val valueType = when ( openApiTypeResult ) { <EOL> is OpenApiTypeResult . CannotFindRefMarker -> <EOL> return MarkerResult . CannotFindRefMarker <EOL> is OpenApiTypeResult . UsingRef -> { <EOL> val marker = openApiTypeResult . marker <EOL> additionalPropertyPaths += marker . additionalPropertyPaths . map { <EOL> it . prependWildcard ( ) <EOL> } <EOL> marker . toFieldType ( ) <EOL> } <EOL> is OpenApiTypeResult . OpenApiType -> { <EOL> val fieldTypeResult = openApiTypeResult <EOL> . openApiType <EOL> . toFieldType ( schema = this , schemaName = typeName , nullable = openApiTypeResult . nullable , getRefMarker = getRefMarker , produceAdditionalMarker = produceAdditionalMarker , required = required , topInterfaceName = topInterfaceName , ) <EOL> when ( fieldTypeResult ) { <EOL> FieldTypeResult . CannotFindRefMarker -> <EOL> return MarkerResult . CannotFindRefMarker <EOL> is FieldTypeResult . FieldType -> { <EOL> additionalPropertyPaths += fieldTypeResult . additionalPropertyPaths . map { <EOL> it . prependWildcard ( ) <EOL> } <EOL> fieldTypeResult . fieldType <EOL> } <EOL> } <EOL> } <EOL> is OpenApiTypeResult . Enum -> { <EOL> val enumMarker = produceNewEnum ( name = name , topInterfaceName = topInterfaceName , values = openApiTypeResult . values , produceAdditionalMarker = produceAdditionalMarker , nullable = openApiTypeResult . nullable , ) <EOL> FieldType . ValueFieldType ( typeFqName = enumMarker . name + if ( enumMarker . nullable ) "<STR_LIT:?>" else "<STR_LIT>" , ) <EOL> } <EOL> null -> FieldType . ValueFieldType ( typeFqName = typeOf < Any ? > ( ) . toString ( ) , ) <EOL> } <EOL> MarkerResult . OpenApiMarker ( OpenApiMarker . AdditionalPropertyInterface ( nullable = nullable , valueType = valueType , name = ValidFieldName . of ( typeName ) . quotedIfNeeded , additionalPropertyPaths = additionalPropertyPaths , topInterfaceName = topInterfaceName , ) ) <EOL> } <EOL> else -> MarkerResult . OpenApiMarker ( OpenApiMarker . Interface ( nullable = nullable , name = typeName , fields = emptyList ( ) , superMarkers = emptyList ( ) , additionalPropertyPaths = emptyList ( ) , topInterfaceName = topInterfaceName , ) ) <EOL> } <EOL> else -> { <EOL> val openApiTypeResult = toOpenApiType ( getRefMarker = getRefMarker , ) <EOL> val typeAliasMarker = when ( openApiTypeResult ) { <EOL> is OpenApiTypeResult . CannotFindRefMarker -> <EOL> return MarkerResult . CannotFindRefMarker <EOL> is OpenApiTypeResult . UsingRef -> OpenApiMarker . MarkerAlias ( name = ValidFieldName . of ( typeName ) . quotedIfNeeded , superMarker = openApiTypeResult . marker , topInterfaceName = topInterfaceName , nullable = nullable , ) <EOL> is OpenApiTypeResult . OpenApiType -> { <EOL> val typeResult = openApiTypeResult <EOL> . openApiType <EOL> . toFieldType ( schema = this , schemaName = typeName , nullable = false , getRefMarker = getRefMarker , produceAdditionalMarker = produceAdditionalMarker , required = required , topInterfaceName = topInterfaceName , ) <EOL> val superMarkerName = when ( typeResult ) { <EOL> is FieldTypeResult . CannotFindRefMarker -> <EOL> return MarkerResult . CannotFindRefMarker <EOL> is FieldTypeResult . FieldType -> <EOL> when ( typeResult . fieldType ) { <EOL> is FieldType . ValueFieldType , is FieldType . GroupFieldType -> <EOL> typeResult . fieldType . name <EOL> is FieldType . FrameFieldType -> <EOL> "<STR_LIT>" <EOL> } <EOL> } <EOL> OpenApiMarker . TypeAlias ( nullable = nullable , name = ValidFieldName . of ( typeName ) . quotedIfNeeded , superMarkerName = superMarkerName , additionalPropertyPaths = typeResult . additionalPropertyPaths , topInterfaceName = topInterfaceName , ) <EOL> } <EOL> is OpenApiTypeResult . Enum -> error ( "<STR_LIT>" ) <EOL> } <EOL> MarkerResult . OpenApiMarker ( typeAliasMarker ) <EOL> } <EOL> } <EOL> }

/**
 * Converts a single OpenApi object type schema to an [OpenApiMarker] if successful.
 *
 * Can handle the following cases:
 * - `allOf:` combining multiple objects into one with inheritance.
 * - `enum:` creating an enum of any type.
 * - `type: object`
 * - `properties:` (`additionalProperties` are ignored) creating an [OpenApiMarker.Interface] using the fields in the properties.
 * - `additionalProperties:` (if `properties` is not present) creating an [OpenApiMarker.AdditionalPropertiesInterface] using the additionalProperties schema as type of `value`.
 * - `type:` if type is something else, generating a type alias for it. This can be a [OpenApiMarker.TypeAlias] or a [OpenApiMarker.MarkerAlias].
 *
 * @param typeName The name of the schema / type to convert.
 * @param getRefMarker Function to retrieve a [Marker] for a given reference name.
 * @param produceAdditionalMarker Function to produce an additional [Marker] on the fly, such as for
 * inline enums/classes in arrays.
 * @param required Optional list of required properties for this schema.
 *
 * @return A [MarkerResult.OpenApiMarker] if successful, otherwise [MarkerResult.CannotFindRefMarker].
 */


private fun Schema < * > . toOpenApiType ( getRefMarker : GetRefMarker , ) : OpenApiTypeResult

{ <EOL> val nullable = nullable ? : false <EOL> if ( `$ref` != null ) { <EOL> val typeName = `$ref` . takeLastWhile { it != '<CHAR_LIT:/>' } <EOL> return when ( val it = getRefMarker ( typeName ) ) { <EOL> is MarkerResult . CannotFindRefMarker -> <EOL> OpenApiTypeResult . CannotFindRefMarker <EOL> is MarkerResult . OpenApiMarker -> <EOL> OpenApiTypeResult . UsingRef ( it . marker ) <EOL> } <EOL> } <EOL> if ( enum != null ) { <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> val nullable = enum . any { it == null } <EOL> return OpenApiTypeResult . Enum ( values = enum . filterNotNull ( ) . map { it . toString ( ) } , nullable = nullable , ) <EOL> } <EOL> var openApiType = OpenApiType . fromStringOrNull ( type ) <EOL> if ( openApiType == null || openApiType is OpenApiType . Any ) { <EOL> val anyOf = ( ( anyOf ? : emptyList ( ) ) + ( oneOf ? : emptyList ( ) ) ) <EOL> val anyOfRefs = anyOf . mapNotNull { it . `$ref` } . map { ref -> <EOL> val typeName = ref . takeLastWhile { it != '<CHAR_LIT:/>' } <EOL> when ( val it = getRefMarker ( typeName ) ) { <EOL> is MarkerResult . CannotFindRefMarker -> <EOL> return OpenApiTypeResult . CannotFindRefMarker <EOL> is MarkerResult . OpenApiMarker -> it . marker <EOL> } <EOL> } <EOL> val anyOfTypes = anyOf . mapNotNull { it . type } <EOL> . mapNotNull ( OpenApiType . Companion :: fromStringOrNull ) <EOL> . distinct ( ) <EOL> val allTypes = anyOfTypes + anyOfRefs <EOL> openApiType = when { <EOL> anyOfTypes . size == <NUM_LIT:1> && anyOfRefs . isEmpty ( ) -> anyOfTypes . first ( ) <EOL> anyOfTypes . size == <NUM_LIT:2> && anyOfRefs . isEmpty ( ) && anyOfTypes . containsAll ( listOf ( OpenApiType . Number , OpenApiType . Integer ) ) -> OpenApiType . Number <EOL> ! anyOfTypes . any { it . isObject } && anyOfRefs . isEmpty ( ) -> OpenApiType . Any <EOL> anyOfTypes . isEmpty ( ) && anyOfRefs . size == <NUM_LIT:1> -> <EOL> return OpenApiTypeResult . UsingRef ( anyOfRefs . first ( ) ) <EOL> anyOfTypes . isEmpty ( ) && anyOfRefs . isNotEmpty ( ) -> { <EOL> val commonSuperMarker = anyOfRefs . map { it . allSuperMarkers . values . toSet ( ) } <EOL> . reduce ( Set < Marker > :: intersect ) <EOL> . firstOrNull ( ) as? OpenApiMarker ? <EOL> if ( commonSuperMarker != null ) { <EOL> return OpenApiTypeResult . UsingRef ( commonSuperMarker ) <EOL> } else { <EOL> OpenApiType . AnyObject <EOL> } <EOL> } <EOL> allTypes . isNotEmpty ( ) && allTypes . all { it . isObject } -> OpenApiType . AnyObject <EOL> not != null -> OpenApiType . Any <EOL> else -> OpenApiType . Any <EOL> } <EOL> } <EOL> return OpenApiTypeResult . OpenApiType ( openApiType , nullable ) <EOL> }

/**
 * Converts a single property of an OpenApi type schema to [OpenApiTypeResult] representing a single type for DataFrame.
 * It must either have `$ref`, `type`, `enum`, `oneOf`, `anyOf`, or `not` defined.
 * It can become an [OpenApiType], [OpenApiMarker] reference or unresolved reference (if `$ref:` is set), enum (if `enum:` is set).
 * `anyOf` and `oneOf` types are merged.
 *
 * These results still have to be converted to [FieldType]s to be able to generate [OpenApiMarker]s from it
 * (unless it's a [OpenApiTypeResult.UsingRef] of course).
 *
 * @receiver Single property of an OpenApi type schema to convert.
 * @param getRefMarker function to attempt to resolve a reference.
 * @return [OpenApiTypeResult]
 */


private fun OpenApiType . toFieldType ( schema : Schema < * > , schemaName : String , nullable : Boolean , getRefMarker : GetRefMarker , produceAdditionalMarker : ProduceAdditionalMarker , required : List < String > , topInterfaceName : ValidFieldName , ) : FieldTypeResult

= when ( this ) { <EOL> is OpenApiType . Any -> FieldTypeResult . FieldType ( getType ( nullable ) ) <EOL> is OpenApiType . Boolean -> FieldTypeResult . FieldType ( getType ( nullable ) ) <EOL> is OpenApiType . Integer -> FieldTypeResult . FieldType ( getType ( nullable = nullable , format = OpenApiIntegerFormat . fromStringOrNull ( schema . format ) , ) ) <EOL> is OpenApiType . Number -> FieldTypeResult . FieldType ( getType ( nullable = nullable , format = OpenApiNumberFormat . fromStringOrNull ( schema . format ) , ) ) <EOL> is OpenApiType . String -> FieldTypeResult . FieldType ( getType ( nullable = nullable , format = OpenApiStringFormat . fromStringOrNull ( schema . format ) , ) ) <EOL> is OpenApiType . AnyObject -> FieldTypeResult . FieldType ( getType ( nullable = nullable , ) ) <EOL> is OpenApiType . Array -> { <EOL> schema as ArraySchema <EOL> if ( schema . items == null ) { <EOL> FieldTypeResult . FieldType ( getTypeAsList ( nullableArray = nullable , typeFqName = OpenApiType . Any . getType ( nullable = true ) . typeFqName ) ) <EOL> } else { <EOL> val arrayTypeResult = schema <EOL> . items ! ! <EOL> . toOpenApiType ( getRefMarker = getRefMarker ) <EOL> when ( arrayTypeResult ) { <EOL> is OpenApiTypeResult . CannotFindRefMarker -> <EOL> FieldTypeResult . CannotFindRefMarker <EOL> is OpenApiTypeResult . UsingRef -> <EOL> when { <EOL> arrayTypeResult . marker is OpenApiMarker . AdditionalPropertyInterface -> <EOL> FieldTypeResult . FieldType ( fieldType = getTypeAsFrameList ( nullable = arrayTypeResult . marker . nullable , nullableArray = nullable , markerName = arrayTypeResult . marker . name , ) , additionalPropertyPaths = arrayTypeResult . marker . additionalPropertyPaths . map { <EOL> it . prependArrayWithWildcard ( ) <EOL> } , ) <EOL> arrayTypeResult . marker . isObject -> <EOL> FieldTypeResult . FieldType ( fieldType = getTypeAsFrame ( nullable = nullable || arrayTypeResult . marker . nullable , markerName = arrayTypeResult . marker . name , ) , additionalPropertyPaths = arrayTypeResult . marker . additionalPropertyPaths . map { <EOL> it . prependArrayWithWildcard ( ) <EOL> } , ) <EOL> else -> <EOL> FieldTypeResult . FieldType ( fieldType = getTypeAsList ( nullableArray = nullable || arrayTypeResult . marker . nullable , typeFqName = arrayTypeResult . marker . name , ) , additionalPropertyPaths = arrayTypeResult . marker . additionalPropertyPaths . map { <EOL> it . prependArrayWithWildcard ( ) <EOL> } , ) <EOL> } <EOL> is OpenApiTypeResult . OpenApiType -> { <EOL> val arrayTypeSchemaResult = arrayTypeResult <EOL> . openApiType <EOL> . toFieldType ( schema = schema . items ! ! , schemaName = schemaName + "<STR_LIT>" , nullable = arrayTypeResult . nullable , getRefMarker = getRefMarker , produceAdditionalMarker = produceAdditionalMarker , required = emptyList ( ) , topInterfaceName = topInterfaceName , ) <EOL> when ( arrayTypeSchemaResult ) { <EOL> is FieldTypeResult . CannotFindRefMarker -> <EOL> FieldTypeResult . CannotFindRefMarker <EOL> is FieldTypeResult . FieldType -> { <EOL> val fieldType = arrayTypeSchemaResult . fieldType <EOL> val additionalPropertyPaths = arrayTypeSchemaResult <EOL> . additionalPropertyPaths <EOL> . map { it . prependArrayWithWildcard ( ) } <EOL> FieldTypeResult . FieldType ( fieldType = when { <EOL> fieldType is FieldType . GroupFieldType && <EOL> fieldType . name == typeOf < DataRow < Any > > ( ) . toString ( ) -> <EOL> getTypeAsFrame ( nullable = nullable , markerName = typeOf < Any > ( ) . toString ( ) , ) <EOL> fieldType is FieldType . GroupFieldType && <EOL> fieldType . name == typeOf < DataRow < Any ? > > ( ) . toString ( ) -> <EOL> getTypeAsFrame ( nullable = nullable , markerName = typeOf < Any ? > ( ) . toString ( ) , ) <EOL> fieldType is FieldType . GroupFieldType -> <EOL> getTypeAsFrame ( nullable = nullable , markerName = fieldType . name , ) <EOL> fieldType is FieldType . FrameFieldType -> <EOL> getTypeAsList ( nullableArray = nullable , typeFqName = "<STR_LIT>" , ) <EOL> fieldType is FieldType . ValueFieldType -> <EOL> getTypeAsList ( nullableArray = nullable , typeFqName = fieldType . name , ) <EOL> else -> error ( "<STR_LIT>" ) <EOL> } , additionalPropertyPaths = additionalPropertyPaths , ) <EOL> } <EOL> } <EOL> } <EOL> is OpenApiTypeResult . Enum -> { <EOL> val enumMarker = produceNewEnum ( name = schemaName , topInterfaceName = topInterfaceName , values = arrayTypeResult . values , produceAdditionalMarker = produceAdditionalMarker , nullable = arrayTypeResult . nullable , ) <EOL> FieldTypeResult . FieldType ( getTypeAsList ( nullableArray = nullable , typeFqName = enumMarker . name + if ( enumMarker . nullable ) "<STR_LIT:?>" else "<STR_LIT>" , ) ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> is OpenApiType . Object -> { <EOL> val dataFrameSchemaResult = schema . toMarker ( typeName = schemaName . snakeToUpperCamelCase ( ) , getRefMarker = getRefMarker , produceAdditionalMarker = { validName , marker , _ -> <EOL> produceAdditionalMarker ( validName , marker , isTopLevelObject = false ) <EOL> } , required = required , topInterfaceName = topInterfaceName , ) <EOL> when ( dataFrameSchemaResult ) { <EOL> is MarkerResult . CannotFindRefMarker -> <EOL> FieldTypeResult . CannotFindRefMarker <EOL> is MarkerResult . OpenApiMarker -> { <EOL> val newName = produceAdditionalMarker ( validName = ValidFieldName . of ( schemaName . snakeToUpperCamelCase ( ) ) , marker = dataFrameSchemaResult . marker , isTopLevelObject = true , ) <EOL> when ( val marker = dataFrameSchemaResult . marker . withName ( newName ) ) { <EOL> is OpenApiMarker . AdditionalPropertyInterface -> <EOL> FieldTypeResult . FieldType ( fieldType = OpenApiType . Array . getTypeAsFrame ( nullable = nullable , markerName = marker . name , ) , additionalPropertyPaths = marker . additionalPropertyPaths , ) <EOL> else -> FieldTypeResult . FieldType ( fieldType = getType ( nullable = nullable , marker = marker , ) , additionalPropertyPaths = marker . additionalPropertyPaths , ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Converts an [OpenApiType] with [schema] to a [FieldType] if successful.
 *
 * @receiver OpenApiType to convert.
 * @param schema Schema of the property that the [OpenApiType] belongs to.
 * Used to get extra information if needed (for arrays / objects / format etc.).
 * @param schemaName Name of the schema that the property belongs to. Used in the name generation of the
 * additionally produced [Marker]s.
 * @param nullable Whether the [FieldType] is supposed to be nullable.
 * @param getRefMarker Function to attempt to resolve a reference.
 * @param produceAdditionalMarker Function to produce additional [Marker]s if needed.
 * @param required List of required properties. Passed down into child objects.
 * @return [FieldTypeResult]
 */


fun DokkaPluginParametersContainer . pluginParameters ( pluginFqn : String , configure : DokkaPluginParametersBuilder . ( ) -> Unit )

{ <EOL> containerWithType ( DokkaPluginParametersBuilder :: class ) <EOL> . maybeCreate ( pluginFqn ) <EOL> . configure ( ) <EOL> }

/**
 * Dynamically create some configuration to control the behaviour of a Dokka Plugin.
 *
 * @param[pluginFqn] The fully-qualified name of a Dokka Plugin. For example, the FQN of the
 * [Dokka Base plugin](https://github.com/Kotlin/dokka/tree/master/plugins/base#readme)
 * is `org.jetbrains.dokka.base.DokkaBase`
 */


private fun File ? . convertToJson ( ) : JsonPrimitive

= <EOL> JsonPrimitive ( this ? . canonicalFile ? . invariantSeparatorsPath )

/** Creates a [JsonPrimitive] from the given [File]. */


fun createModule ( testModule : TestModule , contextModule : KtTestModule ? , dependencyBinaryRoots : Collection < Path > , testServices : TestServices , project : Project , ) : KtTestModule

/**
 * Creates a [KtTestModule] for the given [testModule].
 *
 * @param contextModule a module to use as a context module. Some kinds of modules (such as dangling file modules) require a
 * context module. Modules representing code fragments also require a context element. That is why the [KtTestModule] is passed
 * instead of a plain [KtModule][org.jetbrains.kotlin.analysis.project.structure.KtModule].
 * @param dependencyBinaryRoots The binary roots of [testModule]'s binary library dependencies. This allows avoiding unresolved symbol
 * issues when compiling test binary libraries that depend on other test binary libraries.
 */


fun TestServices . getKtModuleFactoryForTestModule ( testModule : TestModule ) : KtTestModuleFactory

= when ( testModule . explicitTestModuleKind ) { <EOL> TestModuleKind . Source -> KtSourceTestModuleFactory <EOL> TestModuleKind . LibraryBinary -> KtLibraryBinaryTestModuleFactory <EOL> TestModuleKind . LibraryBinaryDecompiled -> KtLibraryBinaryDecompiledTestModuleFactory <EOL> TestModuleKind . LibrarySource -> KtLibrarySourceTestModuleFactory <EOL> TestModuleKind . ScriptSource -> KtScriptTestModuleFactory <EOL> TestModuleKind . CodeFragment -> KtCodeFragmentTestModuleFactory <EOL> TestModuleKind . NotUnderContentRoot -> error ( "<STR_LIT>" ) <EOL> else -> ktTestModuleFactory <EOL> }

/**
 * Returns the appropriate [KtTestModuleFactory] to build a [KtModule][org.jetbrains.kotlin.analysis.project.structure.KtModule] for the given
 * [testModule].
 *
 * By default, the [KtTestModuleFactory] registered with these [TestServices] is returned. It may be overruled by the
 * [MODULE_KIND][org.jetbrains.kotlin.analysis.test.framework.AnalysisApiTestDirectives.MODULE_KIND] directive for a specific test module.
 *
 * [DependencyKindModuleStructureTransformer][org.jetbrains.kotlin.analysis.test.framework.services.DependencyKindModuleStructureTransformer]
 * should be used to properly set up the [DependencyKind][org.jetbrains.kotlin.test.model.DependencyKind] for module dependencies.
 *
 * @see org.jetbrains.kotlin.analysis.test.framework.services.DependencyKindModuleStructureTransformer
 */


private fun ResolveSession . resolveNearestPackageDescriptor ( fqLink : String ) : LazyPackageDescriptor ?

{ <EOL> val isRootPackage = ! fqLink . contains ( '<CHAR_LIT:.>' ) <EOL> val supposedPackageName = if ( isRootPackage ) "<STR_LIT>" else fqLink . substringBeforeLast ( "<STR_LIT:.>" ) <EOL> val packageDescriptor = this . getPackageFragment ( FqName ( supposedPackageName ) ) <EOL> if ( packageDescriptor != null ) { <EOL> return packageDescriptor <EOL> } <EOL> dokkaLogger . debug ( "<STR_LIT>" ) <EOL> if ( isRootPackage ) { <EOL> return null <EOL> } <EOL> return resolveNearestPackageDescriptor ( supposedPackageName . substringBeforeLast ( "<STR_LIT:.>" ) ) <EOL> }

/**
 * Tries to resolve [fqLink]'s package.
 *
 * Since [fqLink] can be both a link to a top-level function and a link to a function within a class,
 * we cannot tell for sure if [fqLink] contains a class name or not (relying on case letters is error-prone,
 * there are exceptions). But we know for sure that the last element in the link is the function.
 *
 * So we start with what we think is the deepest package path, and if we cannot find a package descriptor
 * for it - we drop one level and try again, until we find something or reach root.
 *
 * This function should also account for links to declarations within the root package (`""`).
 *
 * Here are some examples:
 *
 * Given [fqLink] = `com.example.ClassName.functionName`:
 * 1) First pass, trying to resolve package `com.example.ClassName`. Failure.
 * 2) Second pass, trying to resolve package `com.example`. Success.
 *
 * Given [fqLink] = `com.example.functionName`:
 * 1) First pass, trying to resolve package `com.example`. Success.
 *
 * Given [fqLink] = `ClassName.functionName` (root package):
 * 1) First pass, trying to resolve package `ClassName`. Failure.
 * 2) Second pass, trying to resolve package `""`. Success.
 */


public inline fun LayerCollectorContext . points ( block : PointsContext . ( ) -> Unit )

{ <EOL> addLayer ( PointsContext ( this ) . apply ( block ) ) <EOL> }

/**
 * Adds a new `points` layer to the plot.
 *
 * The `points` layer represents observations in your data through individual points in a Cartesian coordinate system.
 *
 * This function provides a context where you can define aesthetic mappings (`aes`) and aesthetic constants for the layer.
 * - Mappings are specified by calling methods that have names corresponding to aesthetic names (`aes`).
 * - Constants are set directly using properties with names that correspond to aesthetics.
 * For positional aesthetics, you can use the `.constant()` method.
 *
 * ## Points Aesthetics
 * * **`x`** - The x-coordinate of the point.
 * * **`y`** - The y-coordinate of the point.
 * * **`color`** - The color of the point.
 * * **`symbol`** - The symbol used to represent the point.
 * * **`size`** - The size of the point.
 * * **`alpha`** - The transparency of the point.
 * * **`fillColor`** - The fill color for symbols that have a fill.
 * * **`stroke`** - width of the shape border. Applied only to the shapes having border.
 *
 * ## Example
 *
 * ```kotlin
 * val months = listOf("Jan", "Feb", "Mar", "Apr", "May", "Jun")
 * val sales = listOf(10000, 15000, 18000, 25000, 22000, 20000)
 * val customerCounts = listOf(80, 120, 150, 200, 180, 160)
 *
 * plot {
 * points {
 * // Positional mapping
 * x(months) // Categories on the x-axis
 * y(sales) // Numerical values on the y-axis
 *
 * // Non-positional settings
 * color = Color.BLUE // Set a constant color for the points
 * alpha = 0.7 // Set a constant transparency for the points
 * fillColor = Color.GREEN // Set a fill color for the points (for filled symbols)
 * stroke = 3
 *
 * // Map 'customerCounts' to 'size' to represent the number of customers as the size of the point
 * size(customerCounts) {
 * // Additional mapping parameters if necessary
 * // For example, you might want to normalize or scale the sizes
 * }
 * }
 * }
 * ```
 */


internal fun mean ( tf : Ops , x : Operand < Float > ) : Operand < Float >

{ <EOL> return mean ( tf , x , null , false ) <EOL> }


internal fun mean ( tf : Ops , x : Operand < Float > , axis : Operand < Int > ) : Operand < Float >

{ <EOL> return mean ( tf , x , axis , false ) <EOL> }


internal fun mean ( tf : Ops , x : Operand < Float > , keepDims : Boolean ) : Operand < Float >

{ <EOL> return mean ( tf , x , null , keepDims ) <EOL> }


internal fun mean ( tf : Ops , x : Operand < Float > , axis : Operand < Int > ? , keepDims : Boolean ) : Operand < Float >

{ <EOL> var localAxis = axis <EOL> if ( localAxis == null ) { <EOL> val rank : Int = x . asOutput ( ) . shape ( ) . numDimensions ( ) <EOL> val ranks = IntArray ( rank ) <EOL> for ( i in <NUM_LIT:0> until rank ) { <EOL> ranks [ i ] = i <EOL> } <EOL> localAxis = tf . constant ( ranks ) <EOL> } <EOL> return tf . math . mean ( x , localAxis , Mean . keepDims ( keepDims ) ) <EOL> }


public fun appendBatch ( batch : Int , lossValue : Double , metricValues : List < Double > )

{ <EOL> val newEvent = BatchEvent ( batch , lossValue , metricValues ) <EOL> addNewBatchEvent ( newEvent , batch ) <EOL> }

/**
 * Appends tracked data from one batch event.
 */


public fun appendBatch ( batchEvent : BatchEvent )

{ <EOL> addNewBatchEvent ( batchEvent , batchEvent . batchIndex ) <EOL> }


public fun lastBatchEvent ( ) : BatchEvent

{ <EOL> return historyByBatch . lastEntry ( ) . value <EOL> }


fun lenetOnMnistDatasetExportImportToTxt ( )

{ <EOL> val ( train , test ) = mnist ( ) <EOL> val ( newTrain , validation ) = train . split ( <NUM_LIT> ) <EOL> val imageId1 = <NUM_LIT:0> <EOL> val imageId2 = <NUM_LIT:1> <EOL> val imageId3 = <NUM_LIT:2> <EOL> val lenet5 = lenet5 ( ) <EOL> lenet5 . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . fit ( trainingDataset = newTrain , validationDataset = validation , epochs = EPOCHS , trainBatchSize = TRAINING_BATCH_SIZE , validationBatchSize = TEST_BATCH_SIZE ) <EOL> println ( it . kGraph ) <EOL> it . save ( File ( PATH_TO_MODEL ) , writingMode = WritingMode . OVERRIDE ) <EOL> val prediction = it . predictLabel ( train . getX ( imageId1 ) ) <EOL> println ( "<STR_LIT>" ) <EOL> val prediction2 = it . predictLabel ( train . getX ( imageId2 ) ) <EOL> println ( "<STR_LIT>" ) <EOL> val prediction3 = it . predictLabel ( train . getX ( imageId3 ) ) <EOL> println ( "<STR_LIT>" ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> val inferenceModel = TensorFlowInferenceModel . load ( File ( PATH_TO_MODEL ) , loadOptimizerState = true ) <EOL> inferenceModel . use { <EOL> val prediction = it . predict ( train . getX ( imageId1 ) ) <EOL> println ( "<STR_LIT>" ) <EOL> val prediction2 = it . predict ( train . getX ( imageId2 ) ) <EOL> println ( "<STR_LIT>" ) <EOL> val prediction3 = it . predict ( train . getX ( imageId3 ) ) <EOL> println ( "<STR_LIT>" ) <EOL> var accuracy = <NUM_LIT:0.0> <EOL> val amountOfTestSet = <NUM_LIT> <EOL> for ( imageId in <NUM_LIT:0> .. amountOfTestSet ) { <EOL> val pred = it . predict ( train . getX ( imageId ) ) <EOL> if ( pred == train . getY ( imageId ) . toInt ( ) ) <EOL> accuracy += ( <NUM_LIT:1.0> / amountOfTestSet ) <EOL> } <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This examples demonstrates model and model weights export and import back:
 * - Model is exported as graph in .pb format, weights are exported in custom (txt) format.
 * - Model is trained on Mnist dataset.
 * - It saves all the data to the project root directory.
 * - [TensorFlowInferenceModel] is created via graph and weights loading.
 * - [TensorFlowInferenceModel] is reshaped and evaluated on first 10'000 images.
 */


= lenetOnMnistDatasetExportImportToTxt ( )


public inline fun LayerCollectorContext . area ( block : AreaContext . ( ) -> Unit )

{ <EOL> addLayer ( AreaContext ( this ) . apply ( block ) ) <EOL> }

/**
 * Adds a new `area` layer to the plot.
 *
 * The `area` layer is designed to visualize an area under a curve in a Cartesian coordinate system.
 * The layer fills the area between the X-axis and the curve defined by the mapped values of X and Y.
 *
 * This function creates a context where you can set aesthetic mappings (`aes`) or aesthetic constants.
 *
 * - Mappings are specified by calling methods that correspond to aesthetic names (`aes`).
 * - Constants are directly assigned using properties with the names corresponding to aesthetics.
 * For positional aesthetics, you can use the `.constant()` method.
 *
 * ## Area Aesthetics
 * * `x` - The X-coordinate of the area.
 * * `y` - The Y-coordinate of the area.
 * * `fillColor` - The fill color of the area.
 * * `alpha` - The transparency of the area.
 * * `borderLine.color` - Color of the area's borderline.
 * * `borderLine.width` - Width of the area's borderline.
 * * `borderLine.type` - Type of the area's borderline.
 *
 * ## Example
 *
 * ```kotlin
 * plot {
 * area {
 * // Positional mapping
 * x(listOf("January", "February", "March", "April", "May")) {
 * axis.name = "months"
 * }
 * y(listOf(200, 150, 300, 250, 420)) {
 * axis.name = "sales"
 * scale = continuous(min = 100, max = 500)
 * }
 *
 * // Non-positional settings
 * alpha = 0.5
 *
 * // Non-positional mapping with constant fillColor
 * fillColor = Color.BLUE
 *
 * // BorderLine settings
 * borderLine {
 * color = Color.BLACK
 * width = 1.5
 * }
 * }
 * }
 * ```
 */


= print ( "<STR_LIT>" )


internal fun AttributeContainer . toMap ( ) : Map < Attribute < * > , Any ? >

{ <EOL> val result = mutableMapOf < Attribute < * > , Any ? > ( ) <EOL> for ( key in keySet ( ) ) { <EOL> result [ key ] = getAttribute ( key ) <EOL> } <EOL> return result <EOL> }

/**
 * KGP's internal analog of [org.gradle.api.internal.attributes.AttributeContainerInternal.asMap]
 * Can be used to compare attributes
 */


internal fun < T : Any > HasAttributes . setAttribute ( key : Attribute < T > , value : T )

{ <EOL> attributes . attribute ( key , value ) <EOL> }

/**
 * Should only be used to configure simple attributes values!
 *
 * When in doubt, prefer lazy method overload.
 */


internal fun LazyResolvedConfiguration . dependencyArtifactsOrNull ( dependency : ResolvedDependencyResult ) : List < ResolvedArtifactResult > ?

= <EOL> try { <EOL> getArtifacts ( dependency ) <EOL> } catch ( _ : ResolveException ) { <EOL> null <EOL> }

/**
 * Same as [LazyResolvedConfiguration.getArtifacts] except it returns null for cases when dependency is resolved
 * but artifact is not available. For example when host-specific part of the library is not yet published
 */


fun < T > Collection < T > . atMostOne ( ) : T ?

{ <EOL> return when ( size ) { <EOL> <NUM_LIT:0> -> null <EOL> <NUM_LIT:1> -> this . iterator ( ) . next ( ) <EOL> else -> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Returns the single element of the collection if it contains at most one element.
 *
 * If the collection is empty, returns `null`.
 *
 * If the collection contains exactly one element, returns that element.
 *
 * If the collection contains more than one element, throws an exception.
 */


inline fun < T > Iterable < T > . atMostOne ( predicate : ( T ) -> Boolean ) : T ?

= this . filter ( predicate ) . atMostOne ( )

/**
 * Returns at most one element from the iterable that satisfies the given predicate.
 *
 * If there are no elements that satisfy [predicate], returns `null`.
 *
 * If there is exactly one element that satisfies [predicate], returns that element.
 *
 * If there are more such elements, throws an exception.
 */


protected open fun shouldSkipValidityCheck ( session : SESSION ) : Boolean

= false

/**
 * In some cases, it might be legal for a session cache to evict sessions which are still valid. Such sessions would fail the validity
 * check (see [checkSessionsMarkedInvalid]) and should be skipped.
 */


private inline fun < reified T : FirCallableDeclaration > T . unwrapSubstitutionOverrideIfNeeded ( ) : T ?

{ <EOL> unwrapUseSiteSubstitutionOverride ( ) ? . let { return it } <EOL> unwrapInheritanceSubstitutionOverrideIfNeeded ( ) ? . let { return it } <EOL> return null <EOL> }

/**
 * N.B. This functions lifts only a single layer of SUBSTITUTION_OVERRIDE at a time.
 */


private inline fun < reified T : FirCallableDeclaration > T . unwrapUseSiteSubstitutionOverride ( ) : T ?

{ <EOL> val originalDeclaration = originalForSubstitutionOverride ? : return null <EOL> return originalDeclaration . takeIf { this . origin is FirDeclarationOrigin . SubstitutionOverride . CallSite } <EOL> }

/**
 * Use-site substitution override happens in situations like this:
 *
 * ```
 * interface List<A> { fun get(i: Int): A }
 *
 * fun take(list: List<String>) {
 * list.get(10) // this call
 * }
 * ```
 *
 * In FIR, `List::get` symbol in the example will be a substitution override with a `String` instead of `A`.
 * We want to lift such substitution overrides.
 *
 * @receiver A declaration that needs to be unwrapped.
 * @return An unsubstituted declaration ([originalForSubstitutionOverride]]) if [this] is a use-site substitution override.
 */


private inline fun < reified T : FirCallableDeclaration > T . unwrapInheritanceSubstitutionOverrideIfNeeded ( ) : T ?

{ <EOL> val containingClass = getContainingClass ( rootSession ) ? : return null <EOL> val originalDeclaration = originalForSubstitutionOverride ? : return null <EOL> val allowedTypeParameters = buildSet { <EOL> originalDeclaration . typeParameters . mapTo ( this ) { it . symbol . toLookupTag ( ) } <EOL> containingClass . typeParameters . mapNotNullTo ( this ) { <EOL> ( it as? FirOuterClassTypeParameterRef ) ? . symbol ? . toLookupTag ( ) <EOL> } <EOL> } <EOL> val usedTypeParameters = collectReferencedTypeParameters ( originalDeclaration ) <EOL> return if ( allowedTypeParameters . containsAll ( usedTypeParameters ) ) { <EOL> originalDeclaration <EOL> } else { <EOL> null <EOL> } <EOL> }

/**
 * We want to unwrap a SUBSTITUTION_OVERRIDE wrapper if it doesn't affect the declaration's signature in any way. If the signature
 * is somehow changed, then we want to keep the wrapper.
 *
 * Such substitute overrides happen because of inheritance.
 *
 * If the declaration references only its own type parameters, or parameters from the outer declarations, then
 * we consider that it's signature will not be changed by the SUBSTITUTION_OVERRIDE, so the wrapper can be unwrapped.
 *
 * This have a few caveats when it comes to the inner classes. TODO Provide a reference to some more in-detail description of that.
 *
 * @receiver A declaration that needs to be unwrapped.
 * @return An unsubstituted declaration ([originalForSubstitutionOverride]]) if it exists and if it does not have any change
 * in signature; `null` otherwise.
 */


fun setupTransform ( project : Project )

{ <EOL> project . dependencies . artifactTypes . maybeCreate ( KLIB_COLLECTION_DIR ) . also { artifactType -> <EOL> artifactType . attributes . setAttribute ( attribute , KLIB_COLLECTION_DIR ) <EOL> } <EOL> project . dependencies . artifactTypes . maybeCreate ( KLIB ) . also { artifactType -> <EOL> artifactType . attributes . setAttribute ( attribute , KLIB ) <EOL> } <EOL> project . dependencies . registerTransform ( KlibCollectionDirTransform :: class . java ) { transform -> <EOL> transform . from . setAttribute ( attribute , KLIB_COLLECTION_DIR ) <EOL> transform . to . setAttribute ( attribute , KLIB ) <EOL> } <EOL> }

/**
 * Set up a transformation from artifacts of type 'collection dir' to a set of klibs.
 */


public operator fun plus ( other : Int ) : Pointer

= <EOL> Pointer ( address + other . toUInt ( ) )

/** Adds an [Int] to the address of this [Pointer] */


public operator fun minus ( other : Int ) : Pointer

= <EOL> Pointer ( address - other . toUInt ( ) )

/** Subtracts an [Int] from the address of this [Pointer] */


public operator fun plus ( other : UInt ) : Pointer

= <EOL> Pointer ( address + other )

/** Adds an [UInt] to the address of this [Pointer] */


public operator fun minus ( other : UInt ) : Pointer

= <EOL> Pointer ( address - other )

/** Subtracts an [UInt] from the address of this [Pointer] */


@ WasmOp ( WasmOp . I32_LOAD8_S ) <EOL> public fun loadByte ( ) : Byte

= <EOL> implementedAsIntrinsic


@ WasmOp ( WasmOp . I32_LOAD16_S ) <EOL> public fun loadShort ( ) : Short

= <EOL> implementedAsIntrinsic


@ WasmOp ( WasmOp . I32_LOAD ) <EOL> public fun loadInt ( ) : Int

= <EOL> implementedAsIntrinsic


@ WasmOp ( WasmOp . I64_LOAD ) <EOL> public fun loadLong ( ) : Long

= <EOL> implementedAsIntrinsic


@ Suppress ( "<STR_LIT:UNUSED_PARAMETER>" ) <EOL> @ WasmOp ( WasmOp . I32_STORE8 ) <EOL> public fun storeByte ( value : Byte ) : Unit

= <EOL> implementedAsIntrinsic


@ Suppress ( "<STR_LIT:UNUSED_PARAMETER>" ) <EOL> @ WasmOp ( WasmOp . I32_STORE16 ) <EOL> public fun storeShort ( value : Short ) : Unit

= <EOL> implementedAsIntrinsic


@ Suppress ( "<STR_LIT:UNUSED_PARAMETER>" ) <EOL> @ WasmOp ( WasmOp . I32_STORE ) <EOL> public fun storeInt ( value : Int ) : Unit

= <EOL> implementedAsIntrinsic


@ Suppress ( "<STR_LIT:UNUSED_PARAMETER>" ) <EOL> @ WasmOp ( WasmOp . I64_STORE ) <EOL> public fun storeLong ( value : Long ) : Unit

= <EOL> implementedAsIntrinsic


protected abstract fun getSize ( v : InstructionAdapter )

/**
 * Stack before: collection
 * Stack after: size
 */


protected abstract fun getIterator ( v : InstructionAdapter )

/**
 * Stack before: collection
 * Stack after: iterator
 */


protected abstract fun doWriteValue ( v : InstructionAdapter )

/**
 * Stack before: parcel, obj
 * Stack after: <empty>
 */


protected abstract fun doReadValue ( v : InstructionAdapter )

/**
 * Stack before: collection, parcel
 * Stack after: <empty>
 */


= Long ( value , if ( value < <NUM_LIT:0> ) - <NUM_LIT:1> else <NUM_LIT:0> )

/**
 * Returns a Long representing the given (32-bit) integer value.
 * @param {number} value The 32-bit integer in question.
 * @return {!Kotlin.Long} The corresponding Long value.
 */


internal fun fromNumber ( value : Double ) : Long

{ <EOL> if ( value . isNaN ( ) ) { <EOL> return ZERO ; <EOL> } else if ( value <= - TWO_PWR_63_DBL_ ) { <EOL> return MIN_VALUE ; <EOL> } else if ( value + <NUM_LIT:1> >= TWO_PWR_63_DBL_ ) { <EOL> return MAX_VALUE ; <EOL> } else if ( value < <NUM_LIT:0> ) { <EOL> return fromNumber ( - value ) . negate ( ) ; <EOL> } else { <EOL> val twoPwr32 = TWO_PWR_32_DBL_ <EOL> return Long ( jsBitwiseOr ( value . rem ( twoPwr32 ) , <NUM_LIT:0> ) , jsBitwiseOr ( value / twoPwr32 , <NUM_LIT:0> ) ) <EOL> } <EOL> }

/**
 * Converts this [Double] value to [Long].
 * The fractional part, if any, is rounded down towards zero.
 * Returns zero if this `Double` value is `NaN`, [Long.MIN_VALUE] if it's less than `Long.MIN_VALUE`,
 * [Long.MAX_VALUE] if it's bigger than `Long.MAX_VALUE`.
 */


@ ExperimentalSerializationApi <EOL> public fun < T > Json . encodeToBufferedSink ( serializer : SerializationStrategy < T > , value : T , sink : BufferedSink )

{ <EOL> val writer = JsonToOkioStreamWriter ( sink ) <EOL> try { <EOL> encodeByWriter ( this , writer , serializer , value ) <EOL> } finally { <EOL> writer . release ( ) <EOL> } <EOL> }

/**
 * Serializes the [value] with [serializer] into a [sink] using JSON format and UTF-8 encoding.
 *
 * @throws [SerializationException] if the given value cannot be serialized to JSON.
 * @throws [okio.IOException] If an I/O error occurs and sink can't be written to.
 */


@ ExperimentalSerializationApi <EOL> public inline fun < reified T > Json . encodeToBufferedSink ( value : T , sink : BufferedSink ) : Unit

= encodeToBufferedSink ( serializersModule . serializer ( ) , value , sink )

/**
 * Serializes given [value] to a [sink] using UTF-8 encoding and serializer retrieved from the reified type parameter.
 *
 * @throws [SerializationException] if the given value cannot be serialized to JSON.
 * @throws [okio.IOException] If an I/O error occurs and sink can't be written to.
 */


@ ExperimentalSerializationApi <EOL> public fun < T > Json . decodeFromBufferedSource ( deserializer : DeserializationStrategy < T > , source : BufferedSource ) : T

{ <EOL> return decodeByReader ( this , deserializer , OkioSerialReader ( source ) ) <EOL> }

/**
 * Deserializes JSON from [source] using UTF-8 encoding to a value of type [T] using [deserializer].
 *
 * Note that this functions expects that exactly one object would be present in the source
 * and throws an exception if there are any dangling bytes after an object.
 *
 * @throws [SerializationException] if the given JSON input cannot be deserialized to the value of type [T].
 * @throws [okio.IOException] If an I/O error occurs and source can't be read from.
 */


@ ExperimentalSerializationApi <EOL> public inline fun < reified T > Json . decodeFromBufferedSource ( source : BufferedSource ) : T

= <EOL> decodeFromBufferedSource ( serializersModule . serializer ( ) , source )

/**
 * Deserializes the contents of given [source] to the value of type [T] using UTF-8 encoding and
 * deserializer retrieved from the reified type parameter.
 *
 * Note that this functions expects that exactly one object would be present in the stream
 * and throws an exception if there are any dangling bytes after an object.
 *
 * @throws [SerializationException] if the given JSON input cannot be deserialized to the value of type [T].
 * @throws [okio.IOException] If an I/O error occurs and source can't be read from.
 */


@ ExperimentalSerializationApi <EOL> public fun < T > Json . decodeBufferedSourceToSequence ( source : BufferedSource , deserializer : DeserializationStrategy < T > , format : DecodeSequenceMode = DecodeSequenceMode . AUTO_DETECT ) : Sequence < T >

{ <EOL> return decodeToSequenceByReader ( this , OkioSerialReader ( source ) , deserializer , format ) <EOL> }

/**
 * Transforms the given [source] into lazily deserialized sequence of elements of type [T] using UTF-8 encoding and [deserializer].
 * Unlike [decodeFromBufferedSource], [source] is allowed to have more than one element, separated as [format] declares.
 *
 * Elements must all be of type [T].
 * Elements are parsed lazily when resulting [Sequence] is evaluated.
 * Resulting sequence is tied to the stream and can be evaluated only once.
 *
 * **Resource caution:** this method neither closes the [source] when the parsing is finished nor provides a method to close it manually.
 * It is a caller responsibility to hold a reference to a source and close it. Moreover, because source is parsed lazily,
 * closing it before returned sequence is evaluated completely will result in [Exception] from decoder.
 *
 * @throws [SerializationException] if the given JSON input cannot be deserialized to the value of type [T].
 * @throws [okio.IOException] If an I/O error occurs and source can't be read from.
 */


@ ExperimentalSerializationApi <EOL> public inline fun < reified T > Json . decodeBufferedSourceToSequence ( source : BufferedSource , format : DecodeSequenceMode = DecodeSequenceMode . AUTO_DETECT ) : Sequence < T >

= decodeBufferedSourceToSequence ( source , serializersModule . serializer ( ) , format )

/**
 * Transforms the given [source] into lazily deserialized sequence of elements of type [T] using UTF-8 encoding and deserializer retrieved from the reified type parameter.
 * Unlike [decodeFromBufferedSource], [source] is allowed to have more than one element, separated as [format] declares.
 *
 * Elements must all be of type [T].
 * Elements are parsed lazily when resulting [Sequence] is evaluated.
 * Resulting sequence is tied to the stream and constrained to be evaluated only once.
 *
 * **Resource caution:** this method does not close [source] when the parsing is finished neither provides method to close it manually.
 * It is a caller responsibility to hold a reference to a source and close it. Moreover, because source is parsed lazily,
 * closing it before returned sequence is evaluated fully would result in [Exception] from decoder.
 *
 * @throws [SerializationException] if the given JSON input cannot be deserialized to the value of type [T].
 * @throws [okio.IOException] If an I/O error occurs and source can't be read from.
 */


public fun suite ( name : String , ignored : Boolean , suiteFn : ( ) -> Unit )

/**
 * Declares a test suite.
 *
 * @param name the name of the test suite, e.g. a class name
 * @param ignored whether the test suite is ignored, e.g. marked with [Ignore] annotation
 * @param suiteFn defines nested suites by calling [kotlin.test.suite] and tests by calling [kotlin.test.test]
 */


public fun test ( name : String , ignored : Boolean , testFn : ( ) -> Any ? )

/**
 * Declares a test.
 *
 * @param name the test name.
 * @param ignored whether the test is ignored
 * @param testFn contains test body invocation
 */


private fun IrExpressionBody . transformDefaultValue ( originalFunction : IrFunction , newFunction : IrFunction )

{ <EOL> transformChildrenVoid ( object : IrElementTransformerVoid ( ) { <EOL> override fun visitGetValue ( expression : IrGetValue ) : IrExpression { <EOL> val original = super . visitGetValue ( expression ) <EOL> val valueParameter = <EOL> ( expression . symbol . owner as? IrValueParameter ) ? : return original <EOL> val parameterIndex = valueParameter . index <EOL> if ( parameterIndex < <NUM_LIT:0> || valueParameter . parent != originalFunction ) { <EOL> return super . visitGetValue ( expression ) <EOL> } <EOL> return irGet ( newFunction . valueParameters [ parameterIndex ] ) <EOL> } <EOL> } ) <EOL> }

/**
 * Expressions for default values can use other parameters.
 * In such cases we need to ensure that default values expressions use parameters of the new
 * function (new/copied value parameters).
 *
 * Example:
 * fun Foo(a: String, b: String = a) {...}
 */


fun additionalTrainingAndNewTopDenseLayers ( )

{ <EOL> val ( train , test ) = fashionMnist ( ) <EOL> val jsonConfigFile = getJSONConfigFile ( ) <EOL> val ( input , otherLayers ) = Sequential . loadModelLayersFromConfiguration ( jsonConfigFile ) <EOL> val layers = mutableListOf < Layer > ( ) <EOL> layers . add ( input ) <EOL> for ( layer in otherLayers ) { <EOL> if ( layer is Conv2D || layer is MaxPool2D ) { <EOL> layer . freeze ( ) <EOL> layers . add ( layer ) <EOL> } <EOL> } <EOL> layers . add ( Flatten ( "<STR_LIT>" ) ) <EOL> layers . add ( Dense ( name = "<STR_LIT>" , kernelInitializer = HeNormal ( SEED ) , biasInitializer = HeNormal ( SEED ) , outputSize = <NUM_LIT> , activation = Activations . Relu ) ) <EOL> layers . add ( Dense ( name = "<STR_LIT>" , kernelInitializer = HeNormal ( SEED ) , biasInitializer = HeNormal ( SEED ) , outputSize = <NUM_LIT> , activation = Activations . Relu ) ) <EOL> layers . add ( Dense ( name = "<STR_LIT>" , kernelInitializer = HeNormal ( SEED ) , biasInitializer = HeNormal ( SEED ) , outputSize = <NUM_LIT> , activation = Activations . Relu ) ) <EOL> layers . add ( Dense ( name = "<STR_LIT>" , kernelInitializer = HeNormal ( SEED ) , biasInitializer = HeNormal ( SEED ) , outputSize = <NUM_LIT:10> , activation = Activations . Linear ) ) <EOL> val model = Sequential . of ( layers ) <EOL> model . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> val hdfFile = getWeightsFile ( ) <EOL> it . loadWeightsForFrozenLayers ( hdfFile ) <EOL> val accuracyBefore = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> it . fit ( dataset = train , validationRate = <NUM_LIT> , epochs = <NUM_LIT:5> , trainBatchSize = <NUM_LIT> , validationBatchSize = <NUM_LIT:100> ) <EOL> val accuracyAfterTraining = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example demonstrates the transfer learning concept:
 * - Weights are loaded from .h5 file, configuration is loaded from .json file.
 * - Conv2D layer is added to the new Neural Network, its weights are frozen.
 * - Flatten and new Dense layers are added and initialized via defined initializers.
 *
 * NOTE: Model and weights are resources in `examples` module.
 */


= additionalTrainingAndNewTopDenseLayers ( )


private fun IrModuleFragment . cleanUpFromExpectDeclarations ( )

{ <EOL> val languageVersionSettings = myEnvironment . configuration . languageVersionSettings <EOL> val multiPlatformProjects = languageVersionSettings . getFeatureSupport ( LanguageFeature . MultiPlatformProjects ) <EOL> if ( multiPlatformProjects != LanguageFeature . State . ENABLED ) <EOL> return <EOL> acceptVoid ( object : IrElementVisitorVoid { <EOL> override fun visitElement ( element : IrElement ) = element . acceptChildrenVoid ( this ) <EOL> override fun visitPackageFragment ( declaration : IrPackageFragment ) = visitDeclarationContainer ( declaration ) <EOL> override fun visitClass ( declaration : IrClass ) = visitDeclarationContainer ( declaration ) <EOL> private fun visitDeclarationContainer ( container : IrDeclarationContainer ) { <EOL> container . declarations . removeIf ( IrDeclaration :: isExpect ) <EOL> visitElement ( container ) <EOL> } <EOL> } ) <EOL> }

/**
 * In multiplatform projects there may be `expect` declarations. Such declarations do not survive during KLIB serialization.
 * So, it's necessary to explicitly filter them out from the [IrModuleFragment] in order for tests that compare dumped IR
 * before and after serialization to pass successfully.
 */


private fun Project . applyTransformationToLegacyDependenciesMetadataConfiguration ( configuration : Configuration , transformation : GranularMetadataTransformation )

{ <EOL> configuration . withDependencies { <EOL> val ( unrequested , requested ) = transformation . metadataDependencyResolutions <EOL> . partition { it is MetadataDependencyResolution . Exclude } <EOL> unrequested . forEach { <EOL> val ( group , name ) = it . projectDependency ( project ) ? . run { <EOL> ModuleDependencyIdentifier ( group . toString ( ) , name ) <EOL> } ? : ModuleIds . fromComponent ( project , it . dependency ) <EOL> configuration . exclude ( mapOf ( "<STR_LIT>" to group , "<STR_LIT>" to name ) ) <EOL> } <EOL> requested . filter { it . dependency !in currentBuild } . forEach { <EOL> val ( group , name ) = ModuleIds . fromComponent ( project , it . dependency ) <EOL> val notation = listOfNotNull ( group . orEmpty ( ) , name , it . dependency . moduleVersion ? . version ) . joinToString ( "<STR_LIT::>" ) <EOL> configuration . resolutionStrategy . force ( notation ) <EOL> } <EOL> } <EOL> }

/**
 *
 * This method is only intended to be called on deprecated DependenciesMetadata configurations to ensure
 * correct behaviour in import.
 *
 * KGP based dependency resolution is therefore unaffected.
 *
 * Ensure that the [configuration] excludes the dependencies that are classified by this [GranularMetadataTransformation] as
 * [MetadataDependencyResolution.Exclude], and uses exactly the same versions as were resolved for the requested
 * dependencies during the transformation.
 */


public fun ModelSummary . print ( out : PrintStream = System . out ) : Unit

= <EOL> format ( ) . forEach ( out :: println )

/**
 * Formats and prints model summary to output stream
 * By defaults prints to console
 */


public fun ModelWithSummary . printSummary ( out : PrintStream = System . out ) : Unit

= <EOL> summary ( ) . print ( out )


{ <EOL> return Field ( field . width , field . height ) { i , j -> <EOL> val n = field . liveNeighbors ( i , j ) <EOL> if ( field [ i , j ] ) <EOL> n in <NUM_LIT:2> .. <NUM_LIT:3> <EOL> else <EOL> n == <NUM_LIT:3> <EOL> } <EOL> }

/**
 * This function takes the present state of the field
 * and return a new field representing the next moment of time
 */


{ <EOL> printField ( "<STR_LIT>" , <NUM_LIT:3> ) <EOL> printField ( """<STR_LIT>""" , <NUM_LIT:10> ) <EOL> printField ( """<STR_LIT>""" , <NUM_LIT:3> ) <EOL> printField ( """<STR_LIT>""" , <NUM_LIT:3> ) <EOL> printField ( """<STR_LIT>""" , <NUM_LIT:6> ) <EOL> printField ( """<STR_LIT>""" , <NUM_LIT:10> ) <EOL> }


fun findLongestExistingPackage ( symbolProvider : FirSymbolProvider , fqName : FqName ) : PackageAndClass

{ <EOL> var currentPackage = fqName <EOL> val pathSegments = fqName . pathSegments ( ) <EOL> var prefixSize = pathSegments . size <EOL> while ( ! currentPackage . isRoot && prefixSize > <NUM_LIT:0> ) { <EOL> if ( symbolProvider . getPackage ( currentPackage ) != null ) { <EOL> break <EOL> } <EOL> currentPackage = currentPackage . parent ( ) <EOL> prefixSize -- <EOL> } <EOL> if ( currentPackage == fqName ) return PackageAndClass ( currentPackage , relativeClassFqName = null ) <EOL> val relativeClassFqName = FqName . fromSegments ( ( prefixSize until pathSegments . size ) . map { pathSegments [ it ] . asString ( ) } ) <EOL> return PackageAndClass ( currentPackage , relativeClassFqName ) <EOL> }

/**
 * Compared to [resolveToPackageOrClass], does not perform the actual resolve.
 *
 * Instead of it, it just looks for the longest existing package name prefix in the [fqName],
 * and assumes that the rest of the name (if present) is a relative class name.
 *
 * Given that [FqName.ROOT] package is always present in any [FirSymbolProvider],
 * this function **can never fail**.
 */


private fun String . parseWithNormalisedSpaces ( renderWhiteCharactersAsSpaces : Boolean ) : List < DocTag >

{ <EOL> if ( ! requiresHtmlEncoding ( ) ) { <EOL> return parseHtmlEncodedWithNormalisedSpaces ( renderWhiteCharactersAsSpaces ) <EOL> } <EOL> return Jsoup . parseBodyFragment ( this ) . body ( ) . wholeText ( ) . parseHtmlEncodedWithNormalisedSpaces ( renderWhiteCharactersAsSpaces ) <EOL> }

/**
 * Parses string into [Text] doc tags that can have either value of the string or html-encoded value with content-type=html parameter.
 * Content type is added when dealing with html entries like ` `
 */


@ K2Only <EOL> abstract fun < R > withTypeVariablesThatAreCountedAsProperTypes ( typeVariables : Set < TypeConstructorMarker > , block : ( ) -> R ) : R

/**
 * @see [org.jetbrains.kotlin.resolve.calls.inference.components.VariableFixationFinder.Context.typeVariablesThatAreNotCountedAsProperTypes]
 * @see [org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.FirDeclarationsResolveTransformer.fixInnerVariablesForProvideDelegateIfNeeded]
 */


fun AppleConfigurables . platformName ( ) : String

= when ( target . family ) { <EOL> Family . OSX -> "<STR_LIT>" <EOL> Family . IOS -> if ( targetTriple . isSimulator ) { <EOL> "<STR_LIT>" <EOL> } else { <EOL> "<STR_LIT>" <EOL> } <EOL> Family . TVOS -> if ( targetTriple . isSimulator ) { <EOL> "<STR_LIT>" <EOL> } else { <EOL> "<STR_LIT>" <EOL> } <EOL> Family . WATCHOS -> if ( targetTriple . isSimulator ) { <EOL> "<STR_LIT>" <EOL> } else { <EOL> "<STR_LIT>" <EOL> } <EOL> else -> error ( "<STR_LIT>" ) <EOL> }

/**
 * Name of an Apple platform as in Xcode.app/Contents/Developer/Platforms.
 */


fun fakeOverrideMember ( superType : IrType , member : IrOverridableMember , clazz : IrClass ) : IrOverridableMember ?

{ <EOL> return if ( isVisibleForOverrideInClass ( member , clazz ) ) <EOL> buildFakeOverrideMember ( superType , member , clazz , unimplementedOverridesStrategy ) <EOL> else <EOL> null <EOL> }

/**
 * Creates a fake override for [member] from [superType] to be added to the class [clazz] or returns null,
 * if no fake override should be created for this member
 */


fun postProcessGeneratedFakeOverride ( fakeOverride : IrOverridableMember , clazz : IrClass )

{ <EOL> unimplementedOverridesStrategy . postProcessGeneratedFakeOverride ( fakeOverride as IrOverridableDeclaration < * > , clazz ) <EOL> }

/**
 * This function is a callback for fake override creation finish.
 *
 * It can modify the created fake override, if needed.
 */


fun linkFakeOverride ( fakeOverride : IrOverridableMember , compatibilityMode : Boolean )

{ <EOL> when ( fakeOverride ) { <EOL> is IrFunctionWithLateBinding -> linkFunctionFakeOverride ( fakeOverride , compatibilityMode ) <EOL> is IrPropertyWithLateBinding -> linkPropertyFakeOverride ( fakeOverride , compatibilityMode ) <EOL> else -> error ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Create a symbol for the fake override.
 */


abstract fun < R > inFile ( file : IrFile ? , block : ( ) -> R ) : R

/**
 * Most implementations need [file] in which they are working now.
 *
 * It should be avoided in the future, but for now it's like this.
 * For now, it's called with class file when class processing is started.
 *
 * Contract:
 * * must call [block] exactly once.
 */


protected abstract fun linkFunctionFakeOverride ( function : IrFunctionWithLateBinding , manglerCompatibleMode : Boolean )

/**
 * Callback for creating a symbol for fake override function.
 *
 * Contract:
 * * [IrFunctionWithLateBinding.acquireSymbol] must be called inside on [function] argument
 */


protected abstract fun linkPropertyFakeOverride ( property : IrPropertyWithLateBinding , manglerCompatibleMode : Boolean )

/**
 * Callback for creating a symbol for fake override property.
 *
 * Also, must create symbols for property's getter and setter.
 *
 * Contract:
 * * [IrPropertyWithLateBinding.acquireSymbol] must be called inside on [property] argument
 * * [IrFunctionWithLateBinding.acquireSymbol] must be called inside on getter and setter of [property] argument, if they exist
 */


@ Test <EOL> fun testRunBlockingInTerminatedWorker ( )

{ <EOL> val workerInRunBlocking = Channel < Unit > ( ) <EOL> val workerTerminated = Channel < Unit > ( ) <EOL> val checkResumption = Channel < Unit > ( ) <EOL> val finished = Channel < Unit > ( ) <EOL> val worker = Worker . start ( ) <EOL> worker . executeAfter ( <NUM_LIT:0> ) { <EOL> runBlocking { <EOL> workerInRunBlocking . send ( Unit ) <EOL> workerTerminated . receive ( ) <EOL> checkResumption . receive ( ) <EOL> finished . send ( Unit ) <EOL> } <EOL> } <EOL> runBlocking { <EOL> workerInRunBlocking . receive ( ) <EOL> worker . requestTermination ( ) <EOL> workerTerminated . send ( Unit ) <EOL> checkResumption . send ( Unit ) <EOL> finished . receive ( ) <EOL> } <EOL> }

/**
 * Test that [runBlocking] does not crash after [Worker.requestTermination] is called on the worker that runs it.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun Random . nextUInt ( ) : UInt

= nextInt ( ) . toUInt ( )

/**
 * Gets the next random [UInt] from the random number generator.
 *
 * Generates a [UInt] random value uniformly distributed between [UInt.MIN_VALUE] and [UInt.MAX_VALUE] (inclusive).
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun Random . nextUInt ( until : UInt ) : UInt

= nextUInt ( <NUM_LIT> , until )

/**
 * Gets the next random [UInt] from the random number generator less than the specified [until] bound.
 *
 * Generates a [UInt] random value uniformly distributed between `0` (inclusive) and the specified [until] bound (exclusive).
 *
 * @throws IllegalArgumentException if [until] is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun Random . nextUInt ( from : UInt , until : UInt ) : UInt

{ <EOL> checkUIntRangeBounds ( from , until ) <EOL> val signedFrom = from . toInt ( ) xor Int . MIN_VALUE <EOL> val signedUntil = until . toInt ( ) xor Int . MIN_VALUE <EOL> val signedResult = nextInt ( signedFrom , signedUntil ) xor Int . MIN_VALUE <EOL> return signedResult . toUInt ( ) <EOL> }

/**
 * Gets the next random [UInt] from the random number generator in the specified range.
 *
 * Generates a [UInt] random value uniformly distributed between the specified [from] (inclusive) and [until] (exclusive) bounds.
 *
 * @throws IllegalArgumentException if [from] is greater than or equal to [until].
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun Random . nextUInt ( range : UIntRange ) : UInt

= when { <EOL> range . isEmpty ( ) -> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> range . last < UInt . MAX_VALUE -> nextUInt ( range . first , range . last + <NUM_LIT:1u> ) <EOL> range . first > UInt . MIN_VALUE -> nextUInt ( range . first - <NUM_LIT:1u> , range . last ) + <NUM_LIT:1u> <EOL> else -> nextUInt ( ) <EOL> }

/**
 * Gets the next random [UInt] from the random number generator in the specified [range].
 *
 * Generates a [UInt] random value uniformly distributed in the specified [range]:
 * from `range.start` inclusive to `range.endInclusive` inclusive.
 *
 * @throws IllegalArgumentException if [range] is empty.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun Random . nextULong ( ) : ULong

= nextLong ( ) . toULong ( )

/**
 * Gets the next random [ULong] from the random number generator.
 *
 * Generates a [ULong] random value uniformly distributed between [ULong.MIN_VALUE] and [ULong.MAX_VALUE] (inclusive).
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun Random . nextULong ( until : ULong ) : ULong

= nextULong ( <NUM_LIT> , until )

/**
 * Gets the next random [ULong] from the random number generator less than the specified [until] bound.
 *
 * Generates a [ULong] random value uniformly distributed between `0` (inclusive) and the specified [until] bound (exclusive).
 *
 * @throws IllegalArgumentException if [until] is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun Random . nextULong ( from : ULong , until : ULong ) : ULong

{ <EOL> checkULongRangeBounds ( from , until ) <EOL> val signedFrom = from . toLong ( ) xor Long . MIN_VALUE <EOL> val signedUntil = until . toLong ( ) xor Long . MIN_VALUE <EOL> val signedResult = nextLong ( signedFrom , signedUntil ) xor Long . MIN_VALUE <EOL> return signedResult . toULong ( ) <EOL> }

/**
 * Gets the next random [ULong] from the random number generator in the specified range.
 *
 * Generates a [ULong] random value uniformly distributed between the specified [from] (inclusive) and [until] (exclusive) bounds.
 *
 * @throws IllegalArgumentException if [from] is greater than or equal to [until].
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalUnsignedTypes :: class ) <EOL> public fun Random . nextULong ( range : ULongRange ) : ULong

= when { <EOL> range . isEmpty ( ) -> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> range . last < ULong . MAX_VALUE -> nextULong ( range . first , range . last + <NUM_LIT:1u> ) <EOL> range . first > ULong . MIN_VALUE -> nextULong ( range . first - <NUM_LIT:1u> , range . last ) + <NUM_LIT:1u> <EOL> else -> nextULong ( ) <EOL> }

/**
 * Gets the next random [ULong] from the random number generator in the specified [range].
 *
 * Generates a [ULong] random value uniformly distributed in the specified [range]:
 * from `range.start` inclusive to `range.endInclusive` inclusive.
 *
 * @throws IllegalArgumentException if [range] is empty.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public fun Random . nextUBytes ( array : UByteArray ) : UByteArray

{ <EOL> nextBytes ( array . asByteArray ( ) ) <EOL> return array <EOL> }

/**
 * Fills the specified unsigned byte [array] with random bytes and returns it.
 *
 * @return [array] filled with random bytes.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public fun Random . nextUBytes ( size : Int ) : UByteArray

= nextBytes ( size ) . asUByteArray ( )

/**
 * Creates an unsigned byte array of the specified [size], filled with random bytes.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public fun Random . nextUBytes ( array : UByteArray , fromIndex : Int = <NUM_LIT:0> , toIndex : Int = array . size ) : UByteArray

{ <EOL> nextBytes ( array . asByteArray ( ) , fromIndex , toIndex ) <EOL> return array <EOL> }

/**
 * Fills a subrange of the specified `UByte` [array] starting from [fromIndex] inclusive and ending [toIndex] exclusive with random UBytes.
 *
 * @return [array] with the subrange filled with random bytes.
 */


{ <EOL> val ( train , test ) = prepareDataset ( ) . split ( <NUM_LIT> ) <EOL> model . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . MAE , metric = Metrics . MAE ) <EOL> it . logSummary ( ) <EOL> it . fit ( dataset = train , epochs = EPOCHS , batchSize = TRAINING_BATCH_SIZE ) <EOL> val evaluationResult = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) <EOL> println ( "<STR_LIT>" ) <EOL> println ( "<STR_LIT>" + it . getLayer ( "<STR_LIT>" ) . weights [ "<STR_LIT>" ] . contentDeepToString ( ) ) <EOL> println ( "<STR_LIT>" + it . getLayer ( "<STR_LIT>" ) . weights [ "<STR_LIT>" ] . contentDeepToString ( ) ) <EOL> repeat ( <NUM_LIT:100> ) { id -> <EOL> val xReal = test . getX ( id ) <EOL> val yReal = test . getY ( id ) <EOL> val yPred = it . predictSoftly ( xReal ) <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> }

/**
 * This example shows how to do regression from scratch, starting from generated dataset, using simple Dense-based [model] with 1 neuron.
 *
 * It includes:
 * - dataset creation
 * - dataset splitting
 * - model compilation
 * - model training
 * - model evaluation
 * - model weights printing
 */


= sineRegression ( )


private fun copySourcesToBatch ( src : Array < D > , start : Int , length : Int ) : Pair < Array < FloatArray > , TensorShape >

{ <EOL> return dataLoader . prepareX ( src , start , length ) <EOL> }

/** Converts [src] to [FloatBuffer] from [start] position for the next [length] positions. */


private fun copyLabelsToBatch ( src : FloatArray , start : Int , length : Int ) : FloatArray

{ <EOL> return FloatArray ( length ) { src [ start + it ] } <EOL> }


override fun split ( splitRatio : Double ) : Pair < OnFlyImageDataset < D > , OnFlyImageDataset < D > >

{ <EOL> require ( splitRatio in <NUM_LIT:0.0> .. <NUM_LIT:1.0> ) { "<STR_LIT>" } <EOL> val trainDatasetLastIndex = truncate ( x . size * splitRatio ) . toInt ( ) <EOL> val train = OnFlyImageDataset ( x . copyOfRange ( <NUM_LIT:0> , trainDatasetLastIndex ) , y . copyOfRange ( <NUM_LIT:0> , trainDatasetLastIndex ) , dataLoader ) <EOL> val test = OnFlyImageDataset ( x . copyOfRange ( trainDatasetLastIndex , x . size ) , y . copyOfRange ( trainDatasetLastIndex , y . size ) , dataLoader ) <EOL> return Pair ( train , test ) <EOL> }

/** Splits datasets on two sub-datasets according [splitRatio].*/


{ <EOL> return x . size <EOL> }


override fun getX ( idx : Int ) : FloatData

{ <EOL> return dataLoader . load ( x [ idx ] ) <EOL> }


{ <EOL> return y [ idx ] <EOL> }

/** Returns label as [FloatArray] by index [idx]. */


@ JvmStatic <EOL> public fun toOneHotVector ( numClasses : Int , label : Byte ) : FloatArray

{ <EOL> val ret = FloatArray ( numClasses ) <EOL> ret [ label . toInt ( ) and SHIFT_NUMBER ] = <NUM_LIT> <EOL> return ret <EOL> }

/** Creates binary vector with size [numClasses] from [label]. */


@ JvmStatic <EOL> public fun toNormalizedVector ( bytes : ByteArray ) : FloatArray

{ <EOL> return FloatArray ( bytes . size ) { ( ( bytes [ it ] . toInt ( ) and SHIFT_NUMBER ) ) / <NUM_LIT> } <EOL> }

/** Normalizes [bytes] via division on 255 to get values in range '[0; 1)'.*/


@ JvmStatic <EOL> public fun toRawVector ( bytes : ByteArray ) : FloatArray

{ <EOL> return FloatArray ( bytes . size ) { ( ( bytes [ it ] . toInt ( ) and SHIFT_NUMBER ) . toFloat ( ) ) } <EOL> }

/** Converts [bytes] to [FloatArray]. */


@ JvmStatic <EOL> @ Throws ( IOException :: class ) <EOL> public fun create ( pathToData : File , labels : FloatArray , preprocessing : Operation < BufferedImage , FloatData > = ConvertToFloatArray ( ) ) : OnFlyImageDataset < File >

{ <EOL> return OnFlyImageDataset ( OnHeapDataset . prepareFileNames ( pathToData ) , labels , preprocessing . fileLoader ( ) ) <EOL> }

/**
 * Create dataset [OnFlyImageDataset] from [pathToData] and [labels] using [preprocessing] to prepare images.
 */


@ JvmStatic <EOL> @ Throws ( IOException :: class ) <EOL> public fun create ( pathToData : File , labelGenerator : LabelGenerator < File > , preprocessing : Operation < BufferedImage , FloatData > = ConvertToFloatArray ( ) ) : OnFlyImageDataset < File >

{ <EOL> val xFiles = OnHeapDataset . prepareFileNames ( pathToData ) <EOL> val y = labelGenerator . prepareY ( xFiles ) <EOL> return OnFlyImageDataset ( xFiles , y , preprocessing . fileLoader ( ) ) <EOL> }

/**
 * Create dataset [OnFlyImageDataset] from [pathToData] and [labelGenerator]
 * using [preprocessing] to prepare images.
 */


fun BuildResult . assertTasksAreNotInTaskGraph ( vararg taskPaths : String )

{ <EOL> val presentTasks = taskPaths . filter { task ( it ) != null } <EOL> assert ( presentTasks . isEmpty ( ) ) { <EOL> printBuildOutput ( ) <EOL> val allTaskPaths = taskPaths . joinToString ( prefix = "<STR_LIT:[>" , postfix = "<STR_LIT:]>" ) <EOL> "<STR_LIT>" <EOL> } <EOL> }

/**
 * Asserts given tasks are not present in the build task graph.
 *
 * (Note: 'not in task graph' has a different meaning to 'not executed'.
 * Tasks with outcomes [TaskOutcome.SKIPPED] and [TaskOutcome.UP_TO_DATE] will be in the task graph, but
 * are not considered 'executed').
 */


fun BuildResult . findTasksByPattern ( pattern : Regex ) : Set < String >

{ <EOL> return tasks . map { it . path } . filter { taskPath -> <EOL> pattern . matches ( taskPath ) <EOL> } . toSet ( ) <EOL> }

/**
 * Returns all the affected during the build tasks, whose [org.gradle.api.Task.getPath] satisfies the [pattern]
 */


fun BuildResult . assertTasksExecuted ( vararg taskPaths : String )

{ <EOL> assertTasksHaveOutcome ( TaskOutcome . SUCCESS , taskPaths . asList ( ) ) <EOL> }

/**
 * Asserts given [taskPaths] have [TaskOutcome.SUCCESS] execution state.
 */


fun BuildResult . assertAnyTaskHasBeenExecuted ( taskPaths : Set < String > )

{ <EOL> val taskOutcomes = taskPaths . associateWith { taskPath -> task ( taskPath ) ? . outcome } <EOL> assert ( taskOutcomes . values . any { it == TaskOutcome . SUCCESS } ) { <EOL> printBuildOutput ( ) <EOL> "<STR_LIT>" <EOL> } <EOL> }

/**
 * Asserts any of [taskPaths] has [TaskOutcome.SUCCESS] execution state.
 */


fun BuildResult . assertTasksExecuted ( taskPaths : Collection < String > )

{ <EOL> assertTasksExecuted ( * taskPaths . toTypedArray ( ) ) <EOL> }


fun BuildResult . assertTasksFailed ( vararg taskPaths : String )

{ <EOL> assertTasksHaveOutcome ( TaskOutcome . FAILED , taskPaths . asList ( ) ) <EOL> }

/**
 * Asserts given [taskPaths] have [TaskOutcome.FAILED] execution state.
 */


fun BuildResult . assertTasksUpToDate ( vararg taskPaths : String )

{ <EOL> assertTasksHaveOutcome ( TaskOutcome . UP_TO_DATE , taskPaths . asList ( ) ) <EOL> }

/**
 * Asserts given [taskPaths] have [TaskOutcome.UP_TO_DATE] execution state.
 */


fun BuildResult . assertTasksUpToDate ( taskPaths : Collection < String > )

{ <EOL> assertTasksUpToDate ( * taskPaths . toTypedArray ( ) ) <EOL> }


fun BuildResult . assertTasksSkipped ( vararg taskPaths : String )

{ <EOL> assertTasksHaveOutcome ( TaskOutcome . SKIPPED , taskPaths . asList ( ) ) <EOL> }

/**
 * Asserts given [taskPaths] have [TaskOutcome.SKIPPED] execution state.
 */


fun BuildResult . assertTasksFromCache ( vararg taskPaths : String )

{ <EOL> assertTasksHaveOutcome ( TaskOutcome . FROM_CACHE , taskPaths . asList ( ) ) <EOL> }

/**
 * Asserts given [taskPaths] have [TaskOutcome.FROM_CACHE] execution state.
 */


fun BuildResult . assertTasksNoSource ( vararg taskPaths : String )

{ <EOL> assertTasksHaveOutcome ( TaskOutcome . NO_SOURCE , taskPaths . asList ( ) ) <EOL> }

/**
 * Asserts given [taskPaths] have [TaskOutcome.NO_SOURCE] execution state.
 */


private fun BuildResult . assertTasksHaveOutcome ( expected : TaskOutcome , taskPaths : Collection < String > )

{ <EOL> taskPaths . forEach { taskPath -> <EOL> val task = task ( taskPath ) <EOL> assertNotNull ( task , "<STR_LIT>" ) <EOL> assert ( task . outcome == expected ) { <EOL> printBuildOutput ( ) <EOL> """<STR_LIT>""" . trimMargin ( ) <EOL> } <EOL> } <EOL> }

/**
 * Asserts given [taskPaths] have [expected] execution state.
 */


fun BuildResult . assertTasksPackedToCache ( vararg taskPaths : String )

{ <EOL> taskPaths . forEach { <EOL> assertOutputContains ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Assert new cache entry was created for given [taskPaths].
 */


@ OptIn ( EnvironmentalVariablesOverride :: class ) <EOL> fun TestProject . buildAndAssertAllTasks ( registeredTasks : List < String > = emptyList ( ) , notRegisteredTasks : List < String > = emptyList ( ) , buildOptions : BuildOptions = this . buildOptions , environmentVariables : EnvironmentalVariables = EnvironmentalVariables ( ) , )

{ <EOL> build ( "<STR_LIT>" , "<STR_LIT>" , buildOptions = buildOptions , environmentVariables = environmentVariables ) { <EOL> assertTasksInBuildOutput ( registeredTasks , notRegisteredTasks ) <EOL> } <EOL> }

/**
 * Builds test project with 'tasks --all' arguments and then
 * asserts that [registeredTasks] of the given tasks have been registered
 * and tasks from the [notRegisteredTasks] list have not been registered.
 *
 * @param registeredTasks The names of the tasks that should have been registered,
 * it could contain task paths as well, but without the first semicolon.
 * @param notRegisteredTasks An optional list of task names that should not have been registered,
 * it could contain task paths as well, but without the first semicolon.
 * @param environmentVariables environmental variables for build process
 * @throws AssertionError if any of the registered tasks do not match the expected task names,
 * or if any of the not-registered tasks were actually registered.
 */


fun BuildResult . assertTasksInBuildOutput ( expectedPresentTasks : List < String > = emptyList ( ) , expectedAbsentTasks : List < String > = emptyList ( ) , )

{ <EOL> val registeredTasks = getAllTasksFromTheOutput ( ) <EOL> expectedPresentTasks . forEach { <EOL> assert ( registeredTasks . contains ( it ) ) { <EOL> printBuildOutput ( ) <EOL> "<STR_LIT>" <EOL> } <EOL> } <EOL> expectedAbsentTasks . forEach { <EOL> assert ( ! registeredTasks . contains ( it ) ) { <EOL> printBuildOutput ( ) <EOL> "<STR_LIT>" <EOL> } <EOL> } <EOL> }

/**
 * Inspects the output of the 'tasks' command and asserts that the specified
 * tasks are either present or absent in the output.
 *
 * @param expectedPresentTasks The names of the tasks that should be present in the output,
 * it could contain task paths as well, but without the first semicolon.
 * @param expectedAbsentTasks The names of the tasks that should be absent from the output,
 * it could contain task paths as well, but without the first semicolon.
 * @throws AssertionError if any of the expected present tasks are not present in the output,
 * or if any of the expected absent tasks are present in the output.
 */


private fun BuildResult . getActualTasksAsString ( ) : String

{ <EOL> return tasks . joinToString ( "<STR_LIT:\n>" ) { "<STR_LIT>" } <EOL> }

/**
 * Returns printable list of task paths that are in the task graph.
 */


private fun BuildResult . getAllTasksFromTheOutput ( ) : List < String >

{ <EOL> val taskPattern = Regex ( "<STR_LIT>" ) <EOL> val tasks = mutableListOf < String > ( ) <EOL> output . lines ( ) . forEach { line -> <EOL> if ( line . matches ( taskPattern ) ) { <EOL> tasks . add ( taskPattern . find ( line ) ! ! . groupValues [ <NUM_LIT:1> ] ) <EOL> } <EOL> } <EOL> return tasks <EOL> }

/**
 * Method parses the output of a 'tasks --all' build
 * and returns a list of all the tasks mentioned in it.
 *
 * @return A list of all the tasks mentioned in the build 'tasks -all' output
 * @throws IllegalStateException if the build output could not be parsed.
 */


override fun equals ( other : Any ? ) : Boolean

{ <EOL> if ( this === other ) return true <EOL> if ( javaClass != other ? . javaClass ) return false <EOL> other as CInteropGist <EOL> if ( identifier != other . identifier ) return false <EOL> if ( konanTarget != other . konanTarget ) return false <EOL> if ( libraryFile != other . libraryFile ) return false <EOL> if ( dependencies != other . dependencies ) return false <EOL> if ( allSourceSetNames != other . allSourceSetNames ) return false <EOL> return true <EOL> }


{ <EOL> var result = identifier . hashCode ( ) <EOL> result = <NUM_LIT:31> * result + konanTarget . hashCode ( ) <EOL> result = <NUM_LIT:31> * result + libraryFile . hashCode ( ) <EOL> result = <NUM_LIT:31> * result + dependencies . hashCode ( ) <EOL> result = <NUM_LIT:31> * result + allSourceSetNames . hashCode ( ) <EOL> return result <EOL> }