{ <EOL> val preprocessing = pipeline < BufferedImage > ( ) <EOL> . crop { <EOL> left = <NUM_LIT:12> <EOL> right = <NUM_LIT:12> <EOL> top = <NUM_LIT:12> <EOL> bottom = <NUM_LIT:12> <EOL> } <EOL> . rotate { <EOL> degrees = <NUM_LIT> <EOL> } <EOL> . resize { <EOL> outputWidth = <NUM_LIT> <EOL> outputHeight = <NUM_LIT> <EOL> interpolation = InterpolationType . NEAREST <EOL> } <EOL> . grayscale ( ) <EOL> . toFloatArray { } <EOL> . rescale { <EOL> scalingCoefficient = <NUM_LIT> <EOL> } <EOL> val resource : URL = Operation :: class . java . getResource ( "<STR_LIT>" ) <EOL> val imageDirectory = Paths . get ( resource . toURI ( ) ) . toFile ( ) <EOL> val dataset = OnFlyImageDataset . create ( imageDirectory , EmptyLabels ( ) , preprocessing ) <EOL> val batchIter : Dataset . BatchIterator = dataset . batchIterator ( <NUM_LIT:8> ) <EOL> val rawImage = batchIter . next ( ) . x [ <NUM_LIT:2> ] <EOL> val image = ImageConverter . floatArrayToBufferedImage ( rawImage , preprocessing . getOutputShape ( TensorShape ( - <NUM_LIT:1> , - <NUM_LIT:1> , <NUM_LIT:3> ) ) , ColorMode . GRAYSCALE , isNormalized = true ) <EOL> showFrame ( "<STR_LIT>" , ImagePanel ( image ) ) <EOL> }

/**
 * This example shows how to do image preprocessing from scratch using preprocessing DSL.
 *
 * It includes:
 * - dataset creation from images located in resource folder;
 * - image preprocessing;
 * - image visualisation with the [ImagePanel].
 */


public fun toNormalizedVector ( bytes : ByteArray ) : FloatArray

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

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


public fun toRawVector ( bytes : ByteArray ) : FloatArray

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

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


public fun KtDeclarationSymbol . getKlibSourceFileName ( ) : String ?

= <EOL> withValidityAssertion { analysisSession . klibSourceFileProvider . getKlibSourceFileName ( this ) }

/**
 * If [KtDeclaration] is a deserialized, klib based symbol, then information about the original
 * [SourceFile] might be retained.
 */


@ Test <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> fun testActivation ( )

= runTest { <EOL> val barrier = CyclicBarrier ( <NUM_LIT:3> ) <EOL> val scope = CoroutineScope ( pool ) <EOL> repeat ( N_ITERATIONS ) { <EOL> var wasStarted = false <EOL> val d = scope . async ( NonCancellable , start = CoroutineStart . LAZY ) { <EOL> wasStarted = true <EOL> throw TestException ( ) <EOL> } <EOL> val causeHolder = object { <EOL> var cause : Throwable ? = null <EOL> } <EOL> d . invokeOnCompletion { <EOL> synchronized ( causeHolder ) { <EOL> causeHolder . cause = it ? : Error ( "<STR_LIT>" ) <EOL> ( causeHolder as Object ) . notifyAll ( ) <EOL> } <EOL> } <EOL> val canceller = scope . launch { <EOL> barrier . await ( ) <EOL> d . cancel ( ) <EOL> } <EOL> val starter = scope . launch { <EOL> barrier . await ( ) <EOL> d . start ( ) <EOL> } <EOL> barrier . await ( ) <EOL> joinAll ( d , canceller , starter ) <EOL> if ( wasStarted ) { <EOL> val exception = d . getCompletionExceptionOrNull ( ) <EOL> assertIs < TestException > ( exception , "<STR_LIT>" ) <EOL> val cause = synchronized ( causeHolder ) { <EOL> while ( causeHolder . cause == null ) ( causeHolder as Object ) . wait ( ) <EOL> causeHolder . cause <EOL> } <EOL> assertIs < TestException > ( cause , "<STR_LIT>" ) <EOL> } <EOL> } <EOL> }

/**
 * Perform concurrent start & cancel of a job with prior installed completion handlers
 */


fun get ( annotated : FirAnnotationContainer , config : LombokConfig , session : FirSession ) : T

= <EOL> extract ( annotated . annotations . findAnnotation ( annotationName ) , config , session )

/**
 * Get from annotation or config or default
 */


fun getIfAnnotated ( annotated : FirAnnotationContainer , config : LombokConfig , session : FirSession ) : T ?

= <EOL> annotated . annotations . findAnnotation ( annotationName ) ? . let { annotation -> <EOL> extract ( annotation , config , session ) <EOL> }

/**
 * If element is annotated, get from it or config or default
 */


@ JvmName ( "<STR_LIT>" ) <EOL> public fun LinAlg . norm ( mat : MultiArray < Float , D2 > , norm : Norm = Norm . Fro ) : Float

= this . linAlgEx . normF ( mat , norm )


@ JvmName ( "<STR_LIT>" ) <EOL> public fun LinAlg . norm ( mat : MultiArray < Double , D2 > , norm : Norm = Norm . Fro ) : Double

= this . linAlgEx . norm ( mat , norm )

/**
 * Returns norm of double matrix
 */


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> public fun SupervisorJob ( parent : Job ? = null ) : CompletableJob

= SupervisorJobImpl ( parent )

/**
 * Creates a _supervisor_ job object in an active state.
 * Children of a supervisor job can fail independently of each other.
 *
 * A failure or cancellation of a child does not cause the supervisor job to fail and does not affect its other children,
 * so a supervisor can implement a custom policy for handling failures of its children:
 *
 * - A failure of a child job that was created using [launch][CoroutineScope.launch] can be handled via [CoroutineExceptionHandler] in the context.
 * - A failure of a child job that was created using [async][CoroutineScope.async] can be handled via [Deferred.await] on the resulting deferred value.
 *
 * If a [parent] job is specified, then this supervisor job becomes a child job of [parent] and is cancelled when the
 * parent fails or is cancelled. All this supervisor's children are cancelled in this case, too.
 */


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> @ Deprecated ( level = DeprecationLevel . HIDDEN , message = "<STR_LIT>" ) <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> public fun SupervisorJob0 ( parent : Job ? = null ) : Job

= SupervisorJob ( parent )

/** @suppress Binary compatibility only */


public suspend fun < R > supervisorScope ( block : suspend CoroutineScope . ( ) -> R ) : R

{ <EOL> contract { <EOL> callsInPlace ( block , InvocationKind . EXACTLY_ONCE ) <EOL> } <EOL> return suspendCoroutineUninterceptedOrReturn { uCont -> <EOL> val coroutine = SupervisorCoroutine ( uCont . context , uCont ) <EOL> coroutine . startUndispatchedOrReturn ( coroutine , block ) <EOL> } <EOL> }

/**
 * Creates a [CoroutineScope] with [SupervisorJob] and calls the specified suspend [block] with this scope.
 * The provided scope inherits its [coroutineContext][CoroutineScope.coroutineContext] from the outer scope, using the
 * [Job] from that context as the parent for the new [SupervisorJob].
 * This function returns as soon as the given block and all its child coroutines are completed.
 *
 * Unlike [coroutineScope], a failure of a child does not cause this scope to fail and does not affect its other children,
 * so a custom policy for handling failures of its children can be implemented. See [SupervisorJob] for additional details.
 *
 * If an exception happened in [block], then the supervisor job is failed and all its children are cancelled.
 * If the current coroutine was cancelled, then both the supervisor job itself and all its children are cancelled.
 *
 * The method may throw a [CancellationException] if the current job was cancelled externally,
 * or rethrow an exception thrown by the given [block].
 */


public operator fun contains ( char : Char ) : Boolean

/**
 * Returns `true` if [char] character belongs to this category.
 */


@ ExperimentalCoroutinesApi <EOL> public fun advanceTimeBy ( delayTimeMillis : Long ) : Long

/**
 * Moves the Dispatcher's virtual clock forward by a specified amount of time.
 *
 * The amount the clock is progressed may be larger than the requested `delayTimeMillis` if the code under test uses
 * blocking coroutines.
 *
 * The virtual clock time will advance once for each delay resumed until the next delay exceeds the requested
 * `delayTimeMills`. In the following test, the virtual time will progress by 2_000 then 1 to resume three different
 * calls to delay.
 *
 * ```
 * @Test
 * fun advanceTimeTest() = runBlockingTest {
 * foo()
 * advanceTimeBy(2_000) // advanceTimeBy(2_000) will progress through the first two delays
 * // virtual time is 2_000, next resume is at 2_001
 * advanceTimeBy(2) // progress through the last delay of 501 (note 500ms were already advanced)
 * // virtual time is 2_0002
 * }
 *
 * fun CoroutineScope.foo() {
 * launch {
 * delay(1_000) // advanceTimeBy(2_000) will progress through this delay (resume @ virtual time 1_000)
 * // virtual time is 1_000
 * delay(500) // advanceTimeBy(2_000) will progress through this delay (resume @ virtual time 1_500)
 * // virtual time is 1_500
 * delay(501) // advanceTimeBy(2_000) will not progress through this delay (resume @ virtual time 2_001)
 * // virtual time is 2_001
 * }
 * }
 * ```
 *
 * @param delayTimeMillis The amount of time to move the CoroutineContext's clock forward.
 * @return The amount of delay-time that this Dispatcher's clock has been forwarded.
 */


@ ExperimentalCoroutinesApi <EOL> public fun advanceUntilIdle ( ) : Long

/**
 * Immediately execute all pending tasks and advance the virtual clock-time to the last delay.
 *
 * If new tasks are scheduled due to advancing virtual time, they will be executed before `advanceUntilIdle`
 * returns.
 *
 * @return the amount of delay-time that this Dispatcher's clock has been forwarded in milliseconds.
 */


@ ExperimentalCoroutinesApi <EOL> public fun runCurrent ( )

/**
 * Run any tasks that are pending at or before the current virtual clock-time.
 *
 * Calling this function will never advance the clock.
 */


@ ExperimentalCoroutinesApi <EOL> @ Throws ( AssertionError :: class ) <EOL> public fun cleanupTestCoroutines ( )

/**
 * Call after test code completes to ensure that the dispatcher is properly cleaned up.
 *
 * @throws AssertionError if any pending tasks are active, however it will not throw for suspended
 * coroutines.
 */


@ Deprecated ( "<STR_LIT>" , level = DeprecationLevel . ERROR ) <EOL> public suspend fun pauseDispatcher ( block : suspend ( ) -> Unit )

/**
 * Run a block of code in a paused dispatcher.
 *
 * By pausing the dispatcher any new coroutines will not execute immediately. After block executes, the dispatcher
 * will resume auto-advancing.
 *
 * This is useful when testing functions that start a coroutine. By pausing the dispatcher assertions or
 * setup may be done between the time the coroutine is created and started.
 */


@ Deprecated ( "<STR_LIT>" , level = DeprecationLevel . ERROR ) <EOL> public fun pauseDispatcher ( )

/**
 * Pause the dispatcher.
 *
 * When paused, the dispatcher will not execute any coroutines automatically, and you must call [runCurrent] or
 * [advanceTimeBy], or [advanceUntilIdle] to execute coroutines.
 */


@ Deprecated ( "<STR_LIT>" , level = DeprecationLevel . ERROR ) <EOL> public fun resumeDispatcher ( )

/**
 * Resume the dispatcher from a paused state.
 *
 * Resumed dispatchers will automatically progress through all coroutines scheduled at the current time. To advance
 * time and execute coroutines scheduled in the future use, one of [advanceTimeBy],
 * or [advanceUntilIdle].
 */


@ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) , level = DeprecationLevel . ERROR ) <EOL> override fun advanceTimeBy ( delayTimeMillis : Long ) : Long

{ <EOL> val oldTime = scheduler . currentTime <EOL> scheduler . advanceTimeBy ( delayTimeMillis ) <EOL> scheduler . runCurrent ( ) <EOL> return scheduler . currentTime - oldTime <EOL> }


@ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) , level = DeprecationLevel . ERROR ) <EOL> override fun advanceUntilIdle ( ) : Long

{ <EOL> val oldTime = scheduler . currentTime <EOL> scheduler . advanceUntilIdle ( ) <EOL> return scheduler . currentTime - oldTime <EOL> }


@ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) , level = DeprecationLevel . ERROR ) <EOL> override fun runCurrent ( ) : Unit

= scheduler . runCurrent ( )


@ ExperimentalCoroutinesApi <EOL> override fun cleanupTestCoroutines ( )

{ <EOL> scheduler . runCurrent ( ) <EOL> if ( ! scheduler . isIdle ( strict = false ) ) { <EOL> throw UncompletedCoroutinesError ( "<STR_LIT>" + "<STR_LIT>" ) <EOL> } <EOL> }


public fun < T > yIntercept ( column : ColumnReference < T > ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( Y_INTERCEPT , column . name ( ) , null ) <EOL> }

/**
 * Maps the `yIntercept` aesthetic to a data column by [ColumnReference].
 *
 * @param column the data column to be mapped.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun < T > yIntercept ( column : KProperty < T > ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( Y_INTERCEPT , column . name , null ) <EOL> }

/**
 * Maps the `yIntercept` aesthetic to a data column by [KProperty].
 *
 * @param column the data column to be mapped.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun yIntercept ( column : String ) : PositionalMapping < Any ? >

{ <EOL> return addPositionalMapping ( Y_INTERCEPT , column , null ) <EOL> }

/**
 * Maps the `yIntercept` aesthetic to a data column by [String].
 *
 * @param column the data column to be mapped.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun < T > yIntercept ( values : Iterable < T > ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( Y_INTERCEPT , values . toList ( ) , null , null ) <EOL> }

/**
 * Maps the `yIntercept` aesthetic to iterable of values.
 *
 * @param values the iterable of values to be mapped.
 * @return a [PositionalMapping] object representing the mapping.
 */


public fun < T > yIntercept ( values : DataColumn < T > ) : PositionalMapping < T >

{ <EOL> return addPositionalMapping < T > ( Y_INTERCEPT , values , null ) <EOL> }

/**
 * Maps the `yIntercept` aesthetic to a data column.
 *
 * @param values the data column to be mapped.
 * @return a [PositionalMapping] object representing the mapping.
 */


fun getSystemClasspathFiles ( ) : Set < File >

{ <EOL> return getSystemClasspaths ( ) . map { File ( it ) } . toSet ( ) <EOL> }

/**
 * Returns the list of File's in the system classpath
 *
 * @see getSystemClasspaths
 */


fun getSystemClasspaths ( ) : Set < String >

{ <EOL> val pathSeparator = System . getProperty ( "<STR_LIT>" ) ! ! <EOL> return System . getProperty ( "<STR_LIT>" ) ! ! . split ( pathSeparator ) . toSet ( ) <EOL> }

/**
 * Returns the file paths from the system class loader
 *
 * @see getSystemClasspathFiles
 */


private fun chooseMaximallySpecificCandidates ( candidates : Set < Candidate > , discriminateAbstracts : Boolean , discriminateGenerics : Boolean , ) : Set < Candidate >

{ <EOL> if ( candidates . size == <NUM_LIT:1> ) return candidates <EOL> val fixedCandidates = <EOL> if ( candidates . first ( ) . callInfo . candidateForCommonInvokeReceiver != null ) <EOL> chooseCandidatesWithMostSpecificInvokeReceiver ( candidates ) <EOL> else <EOL> candidates <EOL> val candidatesWithoutOverrides = filterOverrides ( fixedCandidates ) <EOL> val noCompatibilityMode = inferenceComponents . session . languageVersionSettings . supportsFeature ( LanguageFeature . DisableCompatibilityModeForNewInference ) <EOL> return chooseMaximallySpecificCandidates ( candidatesWithoutOverrides , DiscriminationFlags ( lowPrioritySAMs = noCompatibilityMode , adaptationsInPostponedAtoms = noCompatibilityMode , generics = discriminateGenerics , abstracts = discriminateAbstracts , SAMs = true , suspendConversions = true , byUnwrappedSmartCastOrigin = true , ) ) <EOL> }

/**
 * Partial mirror of [org.jetbrains.kotlin.resolve.calls.results.OverloadingConflictResolver.chooseMaximallySpecificCandidates]
 */


private fun filterOverrides ( candidateSet : Set < Candidate > , ) : Set < Candidate >

{ <EOL> if ( candidateSet . size <= <NUM_LIT:1> ) return candidateSet <EOL> val result = mutableSetOf < Candidate > ( ) <EOL> outerLoop @ for ( me in candidateSet ) { <EOL> val iterator = result . iterator ( ) <EOL> while ( iterator . hasNext ( ) ) { <EOL> val other = iterator . next ( ) <EOL> if ( me . overrides ( other ) ) { <EOL> iterator . remove ( ) <EOL> } else if ( other . overrides ( me ) ) { <EOL> continue@outerLoop <EOL> } <EOL> } <EOL> result . add ( me ) <EOL> } <EOL> require ( result . isNotEmpty ( ) ) { "<STR_LIT>" } <EOL> return result <EOL> }

/**
 * See K1 version at OverridingUtil.filterOverrides
 */


private fun isNotLessSpecificCallWithArgumentMapping ( call1 : CandidateSignature , call2 : CandidateSignature , discriminateGenerics : Boolean , useOriginalSamTypes : Boolean = false ) : Boolean

{ <EOL> return compareCallsByUsedArguments ( call1 , call2 , discriminateGenerics , useOriginalSamTypes ) <EOL> }

/**
 * `call1` is not less specific than `call2`
 */


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

{ <EOL> require ( context [ Job ] === null ) { "<STR_LIT>" + <EOL> "<STR_LIT>" } <EOL> return Flux . from ( reactorPublish ( GlobalScope , context , block ) ) <EOL> }

/**
 * Creates a cold reactive [Flux] that runs the given [block] in a coroutine.
 * Every time the returned flux is subscribed, it starts a new coroutine in the specified [context].
 * The coroutine emits ([Subscriber.onNext]) values with [send][ProducerScope.send], completes ([Subscriber.onComplete])
 * when the coroutine completes, or, in case the coroutine throws an exception or the channel is closed,
 * emits the error ([Subscriber.onError]) and closes the channel with the 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.
 *
 * **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.
 */


private fun < T > Subscriber < T > ? . reject ( t : Throwable )

{ <EOL> if ( this == null ) <EOL> throw NullPointerException ( "<STR_LIT>" ) <EOL> onSubscribe ( object : Subscription { <EOL> override fun request ( n : Long ) { <EOL> } <EOL> override fun cancel ( ) { <EOL> } <EOL> } ) <EOL> onError ( t ) <EOL> }

/** The proper way to reject the subscriber, according to
 * [the reactive spec](https://github.com/reactive-streams/reactive-streams-jvm/blob/v1.0.3/README.md#1.9)
 */


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN , replaceWith = ReplaceWith ( "<STR_LIT>" ) ) <EOL> public fun < T > CoroutineScope . flux ( context : CoroutineContext = EmptyCoroutineContext , @ BuilderInference block : suspend ProducerScope < T > . ( ) -> Unit ) : Flux < T >

= <EOL> Flux . from ( reactorPublish ( this , context , block ) )


@ Test <EOL> fun testNotAllocatingExtraDispatchers ( )

{ <EOL> val barrier = BlockingBarrier ( <NUM_LIT:2> ) <EOL> val lock = SynchronizedObject ( ) <EOL> suspend fun spin ( set : MutableSet < Worker > ) { <EOL> repeat ( <NUM_LIT:100> ) { <EOL> synchronized ( lock ) { set . add ( Worker . current ) } <EOL> delay ( <NUM_LIT:1> ) <EOL> } <EOL> } <EOL> val dispatcher = newFixedThreadPoolContext ( <NUM_LIT> , "<STR_LIT:test>" ) <EOL> try { <EOL> runBlocking { <EOL> val encounteredWorkers = mutableSetOf < Worker > ( ) <EOL> val coroutine1 = launch ( dispatcher ) { <EOL> barrier . await ( ) <EOL> spin ( encounteredWorkers ) <EOL> } <EOL> val coroutine2 = launch ( dispatcher ) { <EOL> barrier . await ( ) <EOL> spin ( encounteredWorkers ) <EOL> } <EOL> listOf ( coroutine1 , coroutine2 ) . joinAll ( ) <EOL> assertEquals ( <NUM_LIT:2> , encounteredWorkers . size ) <EOL> } <EOL> } finally { <EOL> dispatcher . close ( ) <EOL> } <EOL> }

/**
 * Test that [newFixedThreadPoolContext] does not allocate more dispatchers than it needs to.
 * Incidentally also tests that it will allocate enough workers for its needs. Otherwise, the test will hang.
 */


@ Test <EOL> fun timeoutsNotPreventingClosing ( ) : Unit

= runBlocking { <EOL> val dispatcher = WorkerDispatcher ( "<STR_LIT:test>" ) <EOL> withContext ( dispatcher ) { <EOL> withTimeout ( <NUM_LIT:5> . seconds ) { <EOL> } <EOL> } <EOL> withTimeout ( <NUM_LIT:1> . seconds ) { <EOL> dispatcher . close ( ) <EOL> yield ( ) <EOL> } <EOL> }

/**
 * Test that [newSingleThreadContext] will not wait for the cancelled scheduled coroutines before closing.
 */


public operator fun get ( index : Int ) : Int

{ <EOL> checkBounds ( index ) <EOL> return array . atomicGet ( index ) <EOL> }

/**
 * Atomically gets the value of the element at the given [index].
 *
 * Provides sequential consistent ordering guarantees.
 *
 * @throws [IndexOutOfBoundsException] if the [index] is out of bounds of this array.
 */


public operator fun set ( index : Int , newValue : Int ) : Unit

{ <EOL> checkBounds ( index ) <EOL> array . atomicSet ( index , newValue ) <EOL> }

/**
 * Atomically sets the value of the element at the given [index] to the [new value][newValue].
 *
 * Provides sequential consistent ordering guarantees.
 *
 * @throws [IndexOutOfBoundsException] if the [index] is out of bounds of this array.
 */


public fun getAndSet ( index : Int , newValue : Int ) : Int

{ <EOL> checkBounds ( index ) <EOL> return array . getAndSet ( index , newValue ) <EOL> }

/**
 * Atomically sets the value of the element at the given [index] to the [new value][newValue]
 * and returns the old value of the element.
 *
 * Provides sequential consistent ordering guarantees.
 *
 * @throws [IndexOutOfBoundsException] if the [index] is out of bounds of this array.
 */


public fun compareAndSet ( index : Int , expectedValue : Int , newValue : Int ) : Boolean

{ <EOL> checkBounds ( index ) <EOL> return array . compareAndSet ( index , expectedValue , newValue ) <EOL> }

/**
 * Atomically sets the value of the element at the given [index] to the [new value][newValue]
 * if the current value equals the [expected value][expectedValue].
 * Returns true if the operation was successful and false only if the current value of the element was not equal to the expected value.
 *
 * Provides sequential consistent ordering guarantees and never fails spuriously.
 *
 * @throws [IndexOutOfBoundsException] if the [index] is out of bounds of this array.
 */


public fun compareAndExchange ( index : Int , expectedValue : Int , newValue : Int ) : Int

{ <EOL> checkBounds ( index ) <EOL> return array . compareAndExchange ( index , expectedValue , newValue ) <EOL> }

/**
 * Atomically sets the value of the element at the given [index] to the [new value][newValue]
 * if the current value equals the [expected value][expectedValue] and returns the old value of the element in any case.
 *
 * Provides sequential consistent ordering guarantees and never fails spuriously.
 *
 * @throws [IndexOutOfBoundsException] if the [index] is out of bounds of this array.
 */


public fun getAndAdd ( index : Int , delta : Int ) : Int

{ <EOL> checkBounds ( index ) <EOL> return array . getAndAdd ( index , delta ) <EOL> }

/**
 * Atomically adds the given [delta] to the element at the given [index] and returns the old value of the element.
 *
 * Provides sequential consistent ordering guarantees.
 *
 * @throws [IndexOutOfBoundsException] if the [index] is out of bounds of this array.
 */


public fun addAndGet ( index : Int , delta : Int ) : Int

{ <EOL> checkBounds ( index ) <EOL> return array . getAndAdd ( index , delta ) + delta <EOL> }

/**
 * Atomically adds the given [delta] to the element at the given [index] and returns the new value of the element.
 *
 * Provides sequential consistent ordering guarantees.
 *
 * @throws [IndexOutOfBoundsException] if the [index] is out of bounds of this array.
 */


public fun getAndIncrement ( index : Int ) : Int

{ <EOL> checkBounds ( index ) <EOL> return array . getAndAdd ( index , <NUM_LIT:1> ) <EOL> }

/**
 * Atomically increments the element at the given [index] by one and returns the old value of the element.
 *
 * Provides sequential consistent ordering guarantees.
 *
 * @throws [IndexOutOfBoundsException] if the [index] is out of bounds of this array.
 */


public fun incrementAndGet ( index : Int ) : Int

{ <EOL> checkBounds ( index ) <EOL> return array . getAndAdd ( index , <NUM_LIT:1> ) + <NUM_LIT:1> <EOL> }

/**
 * Atomically increments the element at the given [index] by one and returns the new value of the element.
 *
 * Provides sequential consistent ordering guarantees.
 *
 * @throws [IndexOutOfBoundsException] if the [index] is out of bounds of this array.
 */


public fun getAndDecrement ( index : Int ) : Int

{ <EOL> checkBounds ( index ) <EOL> return array . getAndAdd ( index , - <NUM_LIT:1> ) <EOL> }

/**
 * Atomically decrements the element at the given [index] by one and returns the old value of the element.
 *
 * Provides sequential consistent ordering guarantees.
 *
 * @throws [IndexOutOfBoundsException] if the [index] is out of bounds of this array.
 */


public fun decrementAndGet ( index : Int ) : Int

{ <EOL> checkBounds ( index ) <EOL> return array . getAndAdd ( index , - <NUM_LIT:1> ) - <NUM_LIT:1> <EOL> }

/**
 * Atomically decrements the element at the given [index] by one and returns the new value of the element.
 *
 * Provides sequential consistent ordering guarantees.
 *
 * @throws [IndexOutOfBoundsException] if the [index] is out of bounds of this array.
 */


public override fun toString ( ) : String

= array . toString ( )

/**
 * Returns the string representation of the underlying [IntArray][array].
 */


@ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> @ RequireKotlin ( version = "<STR_LIT>" , versionKind = RequireKotlinVersionKind . COMPILER_VERSION ) <EOL> @ ExperimentalStdlibApi <EOL> public inline fun AtomicIntArray ( size : Int , init : ( Int ) -> Int ) : AtomicIntArray

{ <EOL> val inner = IntArray ( size ) <EOL> for ( index in <NUM_LIT:0> until size ) { <EOL> inner [ index ] = init ( index ) <EOL> } <EOL> return AtomicIntArray ( inner ) <EOL> }

/**
 * Creates a new [AtomicIntArray] of the given [size], where each element is initialized by calling the given [init] function.
 *
 * The function [init] is called for each array element sequentially starting from the first one.
 * It should return the value for an array element given its index.
 *
 * @throws RuntimeException if the specified [size] is negative.
 */


public operator fun get ( index : Int ) : Long


public operator fun set ( index : Int , newValue : Long ) : Unit


public fun getAndSet ( index : Int , newValue : Long ) : Long


public fun compareAndSet ( index : Int , expectedValue : Long , newValue : Long ) : Boolean


public fun compareAndExchange ( index : Int , expectedValue : Long , newValue : Long ) : Long


public fun getAndAdd ( index : Int , delta : Long ) : Long


public fun addAndGet ( index : Int , delta : Long ) : Long


public fun getAndIncrement ( index : Int ) : Long

{ <EOL> checkBounds ( index ) <EOL> return array . getAndAdd ( index , <NUM_LIT:1L> ) <EOL> }


public fun incrementAndGet ( index : Int ) : Long

{ <EOL> checkBounds ( index ) <EOL> return array . getAndAdd ( index , <NUM_LIT:1L> ) + <NUM_LIT:1L> <EOL> }


public fun getAndDecrement ( index : Int ) : Long

{ <EOL> checkBounds ( index ) <EOL> return array . getAndAdd ( index , - <NUM_LIT:1L> ) <EOL> }


public fun decrementAndGet ( index : Int ) : Long

{ <EOL> checkBounds ( index ) <EOL> return array . getAndAdd ( index , - <NUM_LIT:1L> ) - <NUM_LIT:1L> <EOL> }


= array . toString ( )


@ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> @ RequireKotlin ( version = "<STR_LIT>" , versionKind = RequireKotlinVersionKind . COMPILER_VERSION ) <EOL> @ ExperimentalStdlibApi <EOL> public inline fun AtomicLongArray ( size : Int , init : ( Int ) -> Long ) : AtomicLongArray

{ <EOL> val inner = LongArray ( size ) <EOL> for ( index in <NUM_LIT:0> until size ) { <EOL> inner [ index ] = init ( index ) <EOL> } <EOL> return AtomicLongArray ( inner ) <EOL> }

/**
 * Creates a new [AtomicLongArray] of the given [size], where each element is initialized by calling the given [init] function.
 *
 * The function [init] is called for each array element sequentially starting from the first one.
 * It should return the value for an array element given its index.
 *
 * @throws RuntimeException if the specified [size] is negative.
 */


public operator fun get ( index : Int ) : T

{ <EOL> checkBounds ( index ) <EOL> return array . atomicGet ( index ) <EOL> }


public operator fun set ( index : Int , newValue : T ) : Unit

{ <EOL> checkBounds ( index ) <EOL> array . atomicSet ( index , newValue ) <EOL> }


public fun getAndSet ( index : Int , newValue : T ) : T

{ <EOL> checkBounds ( index ) <EOL> return array . getAndSet ( index , newValue ) <EOL> }


public fun compareAndSet ( index : Int , expectedValue : T , newValue : T ) : Boolean

{ <EOL> checkBounds ( index ) <EOL> return array . compareAndSet ( index , expectedValue , newValue ) <EOL> }


public fun compareAndExchange ( index : Int , expectedValue : T , newValue : T ) : T

{ <EOL> checkBounds ( index ) <EOL> return array . compareAndExchange ( index , expectedValue , newValue ) <EOL> }


public override fun toString ( ) : String

= array . toString ( )


@ SinceKotlin ( "<STR_LIT:1.9>" ) <EOL> @ RequireKotlin ( version = "<STR_LIT>" , versionKind = RequireKotlinVersionKind . COMPILER_VERSION ) <EOL> @ ExperimentalStdlibApi <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public inline fun < reified T > AtomicArray ( size : Int , init : ( Int ) -> T ) : AtomicArray < T >

{ <EOL> val inner = arrayOfNulls < T > ( size ) <EOL> for ( index in <NUM_LIT:0> until size ) { <EOL> inner [ index ] = init ( index ) <EOL> } <EOL> return AtomicArray ( inner as Array < T > ) <EOL> }

/**
 * Creates a new [AtomicArray]<T> of the given [size], where each element is initialized by calling the given [init] function.
 *
 * The function [init] is called for each array element sequentially starting from the first one.
 * It should return the value for an array element given its index.
 *
 * @throws RuntimeException if the specified [size] is negative.
 */


@ TypedIntrinsic ( IntrinsicType . ATOMIC_GET_ARRAY_ELEMENT ) <EOL> internal external fun IntArray . atomicGet ( index : Int ) : Int

/**
 * Atomically gets the value of the [IntArray][this] element at the given [index].
 *
 * Provides sequential consistent ordering guarantees.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . ATOMIC_SET_ARRAY_ELEMENT ) <EOL> internal external fun IntArray . atomicSet ( index : Int , newValue : Int )

/**
 * Atomically sets the value of the [IntArray][this] element at the given [index] to the [new value][newValue].
 *
 * Provides sequential consistent ordering guarantees.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . GET_AND_SET_ARRAY_ELEMENT ) <EOL> internal external fun IntArray . getAndSet ( index : Int , newValue : Int ) : Int

/**
 * Atomically sets the value of the [IntArray][this] element at the given [index] to the [new value][newValue]
 * and returns the old value of the element.
 *
 * Provides sequential consistent ordering guarantees.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . GET_AND_ADD_ARRAY_ELEMENT ) <EOL> internal external fun IntArray . getAndAdd ( index : Int , delta : Int ) : Int

/**
 * Atomically adds the given [delta] to the [IntArray][this] element at the given [index]
 * and returns the old value of the element.
 *
 * Provides sequential consistent ordering guarantees.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . COMPARE_AND_EXCHANGE_ARRAY_ELEMENT ) <EOL> internal external fun IntArray . compareAndExchange ( index : Int , expectedValue : Int , newValue : Int ) : Int

/**
 * Atomically sets the value of the [IntArray][this] element at the given [index] to the [new value][newValue]
 * if the current value equals the [expected value][expectedValue] and returns the old value of the element in any case.
 *
 * Provides sequential consistent ordering guarantees and never fails spuriously.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . COMPARE_AND_SET_ARRAY_ELEMENT ) <EOL> internal external fun IntArray . compareAndSet ( index : Int , expectedValue : Int , newValue : Int ) : Boolean

/**
 * Atomically sets the value of the [IntArray][this] element at the given [index] to the [new value][newValue]
 * if the current value equals the [expected value][expectedValue].
 * Returns true if the operation was successful and false only if the current value of the element was not equal to the expected value.
 *
 * Provides sequential consistent ordering guarantees and never fails spuriously.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . ATOMIC_GET_ARRAY_ELEMENT ) <EOL> internal external fun LongArray . atomicGet ( index : Int ) : Long

/**
 * Atomically gets the value of the [LongArray][this] element at the given [index].
 *
 * Provides sequential consistent ordering guarantees.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . ATOMIC_SET_ARRAY_ELEMENT ) <EOL> internal external fun LongArray . atomicSet ( index : Int , newValue : Long )

/**
 * Atomically sets the value of the [LongArray][this] element at the given [index] to the [new value][newValue].
 *
 * Provides sequential consistent ordering guarantees.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . GET_AND_SET_ARRAY_ELEMENT ) <EOL> internal external fun LongArray . getAndSet ( index : Int , newValue : Long ) : Long

/**
 * Atomically sets the value of the [LongArray][this] element at the given [index] to the [new value][newValue]
 * and returns the old value of the element.
 *
 * Provides sequential consistent ordering guarantees.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . GET_AND_ADD_ARRAY_ELEMENT ) <EOL> internal external fun LongArray . getAndAdd ( index : Int , delta : Long ) : Long

/**
 * Atomically adds the given [delta] to the [LongArray][this] element at the given [index]
 * and returns the old value of the element.
 *
 * Provides sequential consistent ordering guarantees.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . COMPARE_AND_EXCHANGE_ARRAY_ELEMENT ) <EOL> internal external fun LongArray . compareAndExchange ( index : Int , expectedValue : Long , newValue : Long ) : Long

/**
 * Atomically sets the value of the [LongArray][this] element at the given [index] to the [new value][newValue]
 * if the current value equals the [expected value][expectedValue] and returns the old value of the element in any case.
 *
 * Provides sequential consistent ordering guarantees and never fails spuriously.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . COMPARE_AND_SET_ARRAY_ELEMENT ) <EOL> internal external fun LongArray . compareAndSet ( index : Int , expectedValue : Long , newValue : Long ) : Boolean

/**
 * Atomically sets the value of the [LongArray][this] element at the given [index] to the [new value][newValue]
 * if the current value equals the [expected value][expectedValue].
 * Returns true if the operation was successful and false only if the current value of the element was not equal to the expected value.
 *
 * Provides sequential consistent ordering guarantees and never fails spuriously.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . ATOMIC_GET_ARRAY_ELEMENT ) <EOL> internal external fun < T > Array < T > . atomicGet ( index : Int ) : T

/**
 * Atomically gets the value of the [Array<T>][this] element at the given [index].
 *
 * Provides sequential consistent ordering guarantees.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . ATOMIC_SET_ARRAY_ELEMENT ) <EOL> internal external fun < T > Array < T > . atomicSet ( index : Int , newValue : T )

/**
 * Atomically sets the value of the [Array<T>][this] element at the given [index] to the [new value][newValue].
 *
 * Provides sequential consistent ordering guarantees.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . GET_AND_SET_ARRAY_ELEMENT ) <EOL> internal external fun < T > Array < T > . getAndSet ( index : Int , value : T ) : T

/**
 * Atomically sets the value of the [Array<T>][this] element at the given [index] to the [new value][newValue]
 * and returns the old value of the element.
 *
 * Provides sequential consistent ordering guarantees.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . COMPARE_AND_EXCHANGE_ARRAY_ELEMENT ) <EOL> internal external fun < T > Array < T > . compareAndExchange ( index : Int , expectedValue : T , newValue : T ) : T

/**
 * Atomically sets the value of the [Array<T>][this] element at the given [index] to the [new value][newValue]
 * if the current value equals the [expected value][expectedValue] and returns the old value of the element in any case.
 *
 * Comparison of values is done by reference.
 *
 * Provides sequential consistent ordering guarantees and never fails spuriously.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


@ TypedIntrinsic ( IntrinsicType . COMPARE_AND_SET_ARRAY_ELEMENT ) <EOL> internal external fun < T > Array < T > . compareAndSet ( index : Int , expectedValue : T , newValue : T ) : Boolean

/**
 * Atomically sets the value of the [Array<T>][this] element at the given [index] to the [new value][newValue]
 * if the current value equals the [expected value][expectedValue].
 * Returns true if the operation was successful and false only if the current value of the element was not equal to the expected value.
 *
 * Comparison of values is done by reference.
 *
 * Provides sequential consistent ordering guarantees and never fails spuriously.
 *
 * NOTE: Ensure that the provided [index] does not exceed the size of the [array][this]. Exceeding the array size may result in undefined behavior.
 */


fun parse ( testProject : TestProject , logger : DokkaLogger ) : DModule

{ <EOL> return withTempDirectory ( logger ) { tempDirectory -> <EOL> val ( _ , context ) = testProject . initialize ( outputDirectory = tempDirectory , logger ) <EOL> generateDocumentableModel ( context , logger ) <EOL> } <EOL> }

/**
 * A quick way to analyze a [TestProject], for cases when only the documentable
 * model is needed to verify the result.
 *
 * Creates the input test files, runs Dokka and then deletes them right after the documentable
 * model has been created, leaving no trailing files or any other garbage behind.
 *
 * @see [TestProject.parse] for a user-friendly way to call it
 */


fun analyze ( testProject : TestProject , persistentDirectory : File , logger : DokkaLogger ) : Pair < TestAnalysisServices , TestAnalysisContext >

{ <EOL> val ( dokkaConfiguration , dokkaContext ) = testProject . initialize ( outputDirectory = persistentDirectory , logger ) <EOL> val analysisServices = createTestAnalysisServices ( dokkaContext , logger ) <EOL> val testAnalysisContext = TestAnalysisContext ( context = dokkaContext , configuration = dokkaConfiguration , module = generateDocumentableModel ( dokkaContext , logger ) ) <EOL> return analysisServices to testAnalysisContext <EOL> }

/**
 * Works in the same way as [parse], but it returns the context and configuration used for
 * running Dokka, and does not delete the input test files at the end of the execution - it
 * must be taken care of on call site.
 *
 * @param persistentDirectory a directory that will be used to generate the input test files into.
 * It must be available during the test run, especially if services are used,
 * otherwise parts of Dokka might not work as expected. Can be safely deleted
 * at the end of the test after all asserts have been run.
 *
 * @see [TestProject.useServices] for a user-friendly way to call it
 */


private fun TestProject . initialize ( outputDirectory : File , logger : DokkaLogger ) : Pair < DokkaConfiguration , DokkaContext >

{ <EOL> logger . progress ( "<STR_LIT>" ) <EOL> this . verify ( ) <EOL> require ( outputDirectory . isDirectory ) { <EOL> "<STR_LIT>" <EOL> } <EOL> this . initializeTestFiles ( relativeToDir = outputDirectory , logger ) <EOL> logger . progress ( "<STR_LIT>" ) <EOL> val testDokkaConfiguration = this . getConfiguration ( ) <EOL> val dokkaConfiguration = testDokkaConfiguration . toDokkaConfiguration ( projectDir = outputDirectory ) . also { <EOL> it . verify ( ) <EOL> } <EOL> return dokkaConfiguration to createContext ( dokkaConfiguration , logger , getPluginList ( ) ) <EOL> }

/**
 * Prepares this [TestProject] for analysis by creating
 * the test files, setting up context and configuration.
 */


private fun TestProject . initializeTestFiles ( relativeToDir : File , logger : DokkaLogger )

{ <EOL> logger . progress ( "<STR_LIT>" ) <EOL> this . getTestData ( ) . getFiles ( ) . forEach { <EOL> val testDataFile = relativeToDir . resolve ( it . pathFromProjectRoot . removePrefix ( "<STR_LIT:/>" ) ) <EOL> try { <EOL> testDataFile . parentFile . mkdirs ( ) <EOL> } catch ( e : Exception ) { <EOL> throw IllegalStateException ( "<STR_LIT>" , e ) <EOL> } <EOL> logger . debug ( "<STR_LIT>" ) <EOL> check ( testDataFile . createNewFile ( ) ) { <EOL> "<STR_LIT>" <EOL> } <EOL> testDataFile . writeText ( it . getContents ( ) , Charsets . UTF_8 ) <EOL> } <EOL> }

/**
 * Takes the virtual [TestDataFile] of this [TestProject] and creates
 * the real files relative to the [relativeToDir] param.
 */


private fun DokkaConfiguration . verify ( )

{ <EOL> this . includes . forEach { verifyFileExists ( it ) } <EOL> this . sourceSets . forEach { sourceSet -> <EOL> sourceSet . classpath . forEach { verifyFileExists ( it ) } <EOL> sourceSet . includes . forEach { verifyFileExists ( it ) } <EOL> sourceSet . samples . forEach { verifyFileExists ( it ) } <EOL> } <EOL> }

/**
 * Verifies this [DokkaConfiguration] to make sure there are no unexpected
 * parameter option values, such as non-existing classpath entries.
 *
 * If this method fails, it's likely there's a configuration error in the test,
 * or an exception must be made in one of the checks.
 */


private fun generateDocumentableModel ( context : DokkaContext , logger : DokkaLogger ) : DModule

{ <EOL> logger . progress ( "<STR_LIT>" ) <EOL> val sourceSetModules = context <EOL> . configuration <EOL> . sourceSets <EOL> . map { sourceSet -> translateSources ( sourceSet , context , logger ) } <EOL> . flatten ( ) <EOL> if ( sourceSetModules . isEmpty ( ) ) { <EOL> throw IllegalStateException ( "<STR_LIT>" ) <EOL> } <EOL> return DefaultDocumentableMerger ( context ) . invoke ( sourceSetModules ) <EOL> ? : error ( "<STR_LIT>" ) <EOL> }

/**
 * Generates the documentable model by using all available [SourceToDocumentableTranslator] extensions,
 * and then merging all the results into a single [DModule] by calling [DocumentableMerger].
 */


private fun translateSources ( sourceSet : DokkaConfiguration . DokkaSourceSet , context : DokkaContext , logger : DokkaLogger ) : List < DModule >

{ <EOL> val translators = context [ CoreExtensions . sourceToDocumentableTranslator ] <EOL> require ( translators . isNotEmpty ( ) ) { <EOL> "<STR_LIT>" <EOL> } <EOL> logger . debug ( "<STR_LIT>" ) <EOL> return translators . map { it . invoke ( sourceSet , context ) } <EOL> }

/**
 * Translates input source files to the documentable model by using
 * all registered [SourceToDocumentableTranslator] core extensions.
 */


private fun createTestAnalysisServices ( context : DokkaContext , logger : DokkaLogger ) : TestAnalysisServices

{ <EOL> logger . progress ( "<STR_LIT>" ) <EOL> val publicAnalysisPlugin = context . plugin < KotlinAnalysisPlugin > ( ) <EOL> val internalAnalysisPlugin = context . plugin < InternalKotlinAnalysisPlugin > ( ) <EOL> return TestAnalysisServices ( sampleAnalysisEnvironmentCreator = publicAnalysisPlugin . querySingle { sampleAnalysisEnvironmentCreator } , externalDocumentableProvider = publicAnalysisPlugin . querySingle { externalDocumentableProvider } , moduleAndPackageDocumentationReader = internalAnalysisPlugin . querySingle { <EOL> moduleAndPackageDocumentationReader <EOL> } ) <EOL> }

/**
 * A helper function to query analysis services, to avoid
 * boilerplate and misconfiguration in the tests.
 *
 * The idea is to provide the users with ready-to-use services,
 * without them having to know how to query or configure them.
 */


abstract fun findClass ( name : String , pathSegments : List < String > ) : JavaClassifier ?

/**
 * @param name name of a class to find
 * @param pathSegments name of a class to find that is split into path segments (e.g. Outer<String>.Inner -> {"Outer", "Inner"})
 */


fun FunctionSymbolMarker . allRecursivelyOverriddenDeclarationsIncludingSelf ( containingClass : RegularClassSymbolMarker ? ) : List < CallableSymbolMarker >

/**
 * Returns all symbols that are overridden by [this] symbol, including self
 */


fun skipCheckingAnnotationsOfActualClassMember ( actualMember : DeclarationSymbolMarker ) : Boolean

/**
 * Determines whether it is needed to skip checking annotations on class member in [AbstractExpectActualAnnotationMatchChecker].
 *
 * This is needed to prevent checking member twice if it is real `actual` member (not fake override or member of
 * class being typealiased).
 * Example:
 * ```
 * actual class A {
 * actual fun foo() {} // 1: checked itself, 2: checked as member of A
 * }
 * ```
 */


fun check ( expectAnnotations : List < AnnotationCallInfo > , actualAnnotations : List < AnnotationCallInfo > , actualTypeRefSource : SourceElementMarker , )

/**
 * Implementation must check `expect` and `actual` annotations and report diagnostic in case of incompatibility.
 * [actualTypeRefSource] is needed in order to know where on the `actual` declaration to insert the missing annotation
 * from the `expect` declaration (see [AbstractExpectActualAnnotationMatchChecker.Incompatibility.actualAnnotationTargetElement]).
 */


fun checkAnnotationsOnTypeRefAndArguments ( expectContainingSymbol : DeclarationSymbolMarker , actualContainingSymbol : DeclarationSymbolMarker , expectTypeRef : TypeRefMarker , actualTypeRef : TypeRefMarker , checker : AnnotationsCheckerCallback , )

/**
 * Finds pairs of matching expect and actual types, on which annotations must be checked by [AbstractExpectActualAnnotationMatchChecker].
 *
 * This is done by recursively traversing [expectTypeRef] and [actualTypeRef] and their arguments, which is needed in case of
 * complex types like `T1<T2<@Ann T3>>`. Founded expect and actual annotations are passed to [checker] callback.
 * For functional types (e.g. `ReceiverType.(Arg1Type) -> ReturnType`) receiver, argument and return types and their arguments
 * are checked.
 *
 * **Example**: for type `@Ann1 List<@Ann2 Map<@Ann3 Int, @Ann4 String>>`, there are 4 types to check in [checker].
 */


inline fun < reified T : Any > onVariable ( noinline callback : VariableDeclarationCallback < T > )

{ <EOL> addTypeConverter ( FieldHandlerFactory . createDeclareHandler ( TypeDetection . COMPILE_TIME , callback ) ) <EOL> }

/**
 * Runs [callback] for every snippet property of compile-time subtype of type [T]
 *
 * [callback] gives access to both runtime value of the property and its [KProperty] object
 */


inline fun < reified T : Any > updateVariable ( noinline callback : VariableUpdateCallback < T > )

{ <EOL> addTypeConverter ( FieldHandlerFactory . createUpdateHandler ( TypeDetection . COMPILE_TIME , callback ) ) <EOL> }

/**
 * Runs [callback] for every snippet property of compile-time subtype of type [T]
 *
 * [callback] gives access to both runtime value of the property and its [KProperty] object
 *
 * [callback] should usually execute some code that:
 * - has non-Unit result and return the name of result field
 * - defines some variable and return its name
 *
 * Original variable will then be **reassigned** to this new name.
 *
 * For example:
 *
 * ```
 * updateVariable<MyType> { value, kProperty ->
 * // MyWrapper class should be previously defined in the notebook
 * execute("MyWrapper(${kProperty.name})").name
 * }
 * ```
 * or
 * ```
 * updateVariable<MyType> { value, kProperty ->
 * // MyWrapper class should be previously defined in the notebook
 * execute("val wrapper = MyWrapper(${kProperty.name})")
 * return "wrapper"
 * }
 * ```
 */


inline fun < reified T : Any > onVariableByRuntimeType ( noinline callback : VariableDeclarationCallback < T > )

{ <EOL> addTypeConverter ( FieldHandlerFactory . createDeclareHandler ( TypeDetection . RUNTIME , callback ) ) <EOL> }

/**
 * Same as [onVariable], but based on runtime type that is figured out by reflection
 */


inline fun < reified T : Any > updateVariableByRuntimeType ( noinline callback : VariableUpdateCallback < T > )

{ <EOL> addTypeConverter ( FieldHandlerFactory . createUpdateHandler ( TypeDetection . RUNTIME , callback ) ) <EOL> }

/**
 * Same as [updateVariable], but based on runtime type that is figured out by reflection
 */


fun addIntegrationTypeNameRule ( rule : AcceptanceRule < TypeName > )

{ <EOL> integrationTypeNameRules . add ( rule ) <EOL> }

/**
 * All integrations transitively loaded by this integration will be tested against
 * passed acceptance rule and won't be loaded if the rule returned `false`.
 * If there were no acceptance rules that returned not-null values, integration
 * **will be loaded**. If there are several acceptance rules that returned not-null values,
 * the latest one will be taken into account.
 */


fun acceptIntegrationTypeNameIf ( predicate : ( TypeName ) -> Boolean )

{ <EOL> addIntegrationTypeNameRule ( NameAcceptanceRule ( true , predicate ) ) <EOL> }

/**
 * See [addIntegrationTypeNameRule]
 */


fun discardIntegrationTypeNameIf ( predicate : ( TypeName ) -> Boolean )

{ <EOL> addIntegrationTypeNameRule ( NameAcceptanceRule ( false , predicate ) ) <EOL> }


{ <EOL> val modelHub = <EOL> TFModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val model = modelHub [ TFModels . CV . ResNet50 ( ) ] <EOL> model . use { <EOL> for ( i in <NUM_LIT:1> .. <NUM_LIT:8> ) { <EOL> val imageFile = getFileFromResource ( "<STR_LIT>" ) <EOL> val recognizedObject = it . predictObject ( imageFile = imageFile ) <EOL> println ( recognizedObject ) <EOL> val top5 = it . predictTopKObjects ( imageFile = imageFile , topK = <NUM_LIT:5> ) <EOL> println ( top5 . toString ( ) ) <EOL> } <EOL> } <EOL> }

/**
 * This example demonstrates the inference concept on ResNet'50 model:
 * - Model configuration, model weights and labels are obtained from [TFModelHub].
 * - Weights are loaded from .h5 file, configuration is loaded from .json file.
 * - Model predicts on a few images located in resources.
 * - No additional training.
 * - No new layers are added.
 * - Special preprocessing (used in ResNet'50 during training on ImageNet dataset) is applied to each image before prediction.
 */


= resnet50easyPrediction2 ( )


@ Test <EOL> fun testCreateThrowsOnInvalidArguments ( )

{ <EOL> for ( ctx in invalidContexts ) { <EOL> assertFailsWith < IllegalArgumentException > { <EOL> TestScope ( ctx ) <EOL> } <EOL> } <EOL> }

/** Tests failing to create a [TestScope] with incorrect contexts. */


@ Test <EOL> fun testCreateProvidesScheduler ( )

{ <EOL> run { <EOL> val scope = TestScope ( ) <EOL> assertNotNull ( scope . coroutineContext [ TestCoroutineScheduler ] ) <EOL> } <EOL> run { <EOL> val dispatcher = StandardTestDispatcher ( ) <EOL> val scope = TestScope ( dispatcher ) <EOL> assertSame ( dispatcher . scheduler , scope . coroutineContext [ TestCoroutineScheduler ] ) <EOL> } <EOL> run { <EOL> val scheduler = TestCoroutineScheduler ( ) <EOL> val scope = TestScope ( scheduler ) <EOL> assertSame ( scheduler , scope . coroutineContext [ TestCoroutineScheduler ] ) <EOL> assertSame ( scheduler , ( scope . coroutineContext [ ContinuationInterceptor ] as TestDispatcher ) . scheduler ) <EOL> } <EOL> run { <EOL> val scheduler = TestCoroutineScheduler ( ) <EOL> val dispatcher = StandardTestDispatcher ( scheduler ) <EOL> val scope = TestScope ( scheduler + dispatcher ) <EOL> assertSame ( scheduler , scope . coroutineContext [ TestCoroutineScheduler ] ) <EOL> assertSame ( dispatcher , scope . coroutineContext [ ContinuationInterceptor ] ) <EOL> } <EOL> }

/** Tests that a newly-created [TestScope] provides the correct scheduler. */


@ Test <EOL> fun testCreateReusesScheduler ( )

{ <EOL> run { <EOL> val scheduler = TestCoroutineScheduler ( ) <EOL> val mainDispatcher = StandardTestDispatcher ( scheduler ) <EOL> Dispatchers . setMain ( mainDispatcher ) <EOL> try { <EOL> val scope = TestScope ( ) <EOL> assertSame ( scheduler , scope . coroutineContext [ TestCoroutineScheduler ] ) <EOL> assertNotSame ( mainDispatcher , scope . coroutineContext [ ContinuationInterceptor ] ) <EOL> } finally { <EOL> Dispatchers . resetMain ( ) <EOL> } <EOL> } <EOL> run { <EOL> val mainDispatcher = StandardTestDispatcher ( ) <EOL> Dispatchers . setMain ( mainDispatcher ) <EOL> try { <EOL> val scheduler = TestCoroutineScheduler ( ) <EOL> val scope = TestScope ( scheduler ) <EOL> assertSame ( scheduler , scope . coroutineContext [ TestCoroutineScheduler ] ) <EOL> assertNotSame ( mainDispatcher . scheduler , scope . coroutineContext [ TestCoroutineScheduler ] ) <EOL> assertNotSame ( mainDispatcher , scope . coroutineContext [ ContinuationInterceptor ] ) <EOL> } finally { <EOL> Dispatchers . resetMain ( ) <EOL> } <EOL> } <EOL> }

/** Part of [testCreateProvidesScheduler], disabled for Native */


@ Test <EOL> fun testPresentDelaysThrowing ( )

{ <EOL> val scope = TestScope ( ) <EOL> var result = false <EOL> scope . launch { <EOL> delay ( <NUM_LIT:5> ) <EOL> result = true <EOL> } <EOL> assertFalse ( result ) <EOL> scope . asSpecificImplementation ( ) . enter ( ) <EOL> assertFailsWith < UncompletedCoroutinesError > { scope . asSpecificImplementation ( ) . legacyLeave ( ) } <EOL> assertFalse ( result ) <EOL> }

/** Tests that the cleanup procedure throws if there were uncompleted delays by the end. */


@ Test <EOL> fun testActiveJobsThrowing ( )

{ <EOL> val scope = TestScope ( ) <EOL> var result = false <EOL> val deferred = CompletableDeferred < String > ( ) <EOL> scope . launch { <EOL> deferred . await ( ) <EOL> result = true <EOL> } <EOL> assertFalse ( result ) <EOL> scope . asSpecificImplementation ( ) . enter ( ) <EOL> assertFailsWith < UncompletedCoroutinesError > { scope . asSpecificImplementation ( ) . legacyLeave ( ) } <EOL> assertFalse ( result ) <EOL> }

/** Tests that the cleanup procedure throws if there were active jobs by the end. */


@ Test <EOL> fun testCancelledDelaysThrowing ( )

{ <EOL> val scope = TestScope ( ) <EOL> var result = false <EOL> val deferred = CompletableDeferred < String > ( ) <EOL> val job = scope . launch { <EOL> deferred . await ( ) <EOL> result = true <EOL> } <EOL> job . cancel ( ) <EOL> assertFalse ( result ) <EOL> scope . asSpecificImplementation ( ) . enter ( ) <EOL> assertFailsWith < UncompletedCoroutinesError > { scope . asSpecificImplementation ( ) . legacyLeave ( ) } <EOL> assertFalse ( result ) <EOL> }

/** Tests that the cleanup procedure throws even if it detects that the job is already cancelled. */


@ Test <EOL> fun testGetsCancelledOnChildFailure ( ) : TestResult

{ <EOL> val scope = TestScope ( ) <EOL> val exception = TestException ( "<STR_LIT:test>" ) <EOL> scope . launch { <EOL> throw exception <EOL> } <EOL> return testResultMap ( { <EOL> try { <EOL> it ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : TestException ) { <EOL> } <EOL> } ) { <EOL> scope . runTest { <EOL> } <EOL> } <EOL> }

/** Tests that uncaught exceptions are thrown at the cleanup. */


@ Test <EOL> fun testSuppressedExceptions ( )

{ <EOL> TestScope ( ) . apply { <EOL> asSpecificImplementation ( ) . enter ( ) <EOL> launch ( SupervisorJob ( ) ) { throw TestException ( "<STR_LIT:x>" ) } <EOL> launch ( SupervisorJob ( ) ) { throw TestException ( "<STR_LIT:y>" ) } <EOL> launch ( SupervisorJob ( ) ) { throw TestException ( "<STR_LIT:z>" ) } <EOL> runCurrent ( ) <EOL> val e = asSpecificImplementation ( ) . legacyLeave ( ) <EOL> assertEquals ( <NUM_LIT:3> , e . size ) <EOL> assertEquals ( "<STR_LIT:x>" , e [ <NUM_LIT:0> ] . message ) <EOL> assertEquals ( "<STR_LIT:y>" , e [ <NUM_LIT:1> ] . message ) <EOL> assertEquals ( "<STR_LIT:z>" , e [ <NUM_LIT:2> ] . message ) <EOL> } <EOL> }

/** Tests that, when reporting several exceptions, the first one is thrown, with the rest suppressed. */


@ Test <EOL> fun testBackgroundWorkBeingRun ( ) : TestResult

= runTest { <EOL> var i = <NUM_LIT:0> <EOL> var j = <NUM_LIT:0> <EOL> backgroundScope . launch { <EOL> ++ i <EOL> } <EOL> backgroundScope . launch { <EOL> delay ( <NUM_LIT:10> ) <EOL> ++ j <EOL> } <EOL> assertEquals ( <NUM_LIT:0> , i ) <EOL> assertEquals ( <NUM_LIT:0> , j ) <EOL> delay ( <NUM_LIT:1> ) <EOL> assertEquals ( <NUM_LIT:1> , i ) <EOL> assertEquals ( <NUM_LIT:0> , j ) <EOL> delay ( <NUM_LIT:10> ) <EOL> assertEquals ( <NUM_LIT:1> , i ) <EOL> assertEquals ( <NUM_LIT:1> , j ) <EOL> }

/** Tests that the background work is being run at all. */


@ Test <EOL> fun testBackgroundWorkCancelled ( ) : TestResult

{ <EOL> var cancelled = false <EOL> return testResultMap ( { <EOL> it ( ) <EOL> assertTrue ( cancelled ) <EOL> } ) { <EOL> runTest { <EOL> var i = <NUM_LIT:0> <EOL> backgroundScope . launch { <EOL> try { <EOL> while ( isActive ) { <EOL> ++ i <EOL> yield ( ) <EOL> } <EOL> } catch ( e : CancellationException ) { <EOL> cancelled = true <EOL> } <EOL> } <EOL> repeat ( <NUM_LIT:5> ) { <EOL> assertEquals ( i , it ) <EOL> yield ( ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Tests that the background work gets cancelled after the test body finishes.
 */


@ Test <EOL> fun testBackgroundWorkTimeControl ( ) : TestResult

= runTest { <EOL> var i = <NUM_LIT:0> <EOL> var j = <NUM_LIT:0> <EOL> backgroundScope . launch { <EOL> while ( true ) { <EOL> ++ i <EOL> delay ( <NUM_LIT:100> ) <EOL> } <EOL> } <EOL> backgroundScope . launch { <EOL> while ( true ) { <EOL> ++ j <EOL> delay ( <NUM_LIT> ) <EOL> } <EOL> } <EOL> advanceUntilIdle ( ) <EOL> assertEquals ( <NUM_LIT:0> , i ) <EOL> assertEquals ( <NUM_LIT:0> , j ) <EOL> val job = launch { <EOL> delay ( <NUM_LIT:1> ) <EOL> assertEquals ( <NUM_LIT:1> , i ) <EOL> assertEquals ( <NUM_LIT:1> , j ) <EOL> } <EOL> job . join ( ) <EOL> advanceTimeBy ( <NUM_LIT> . milliseconds ) <EOL> assertEquals ( <NUM_LIT:2> , i ) <EOL> assertEquals ( <NUM_LIT:4> , j ) <EOL> advanceUntilIdle ( ) <EOL> assertEquals ( <NUM_LIT:2> , i ) <EOL> assertEquals ( <NUM_LIT:4> , j ) <EOL> runCurrent ( ) <EOL> assertEquals ( <NUM_LIT:3> , i ) <EOL> assertEquals ( <NUM_LIT:5> , j ) <EOL> launch { <EOL> delay ( <NUM_LIT> ) <EOL> assertEquals ( <NUM_LIT> , i ) <EOL> assertEquals ( <NUM_LIT> , j ) <EOL> } <EOL> advanceUntilIdle ( ) <EOL> }

/** Tests the interactions between the time-control commands and the background work. */


@ Test <EOL> fun testBackgroundWorkErrorReporting ( ) : TestResult

{ <EOL> var testFinished = false <EOL> val exception = RuntimeException ( "<STR_LIT:x>" ) <EOL> return testResultMap ( { <EOL> try { <EOL> it ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : Throwable ) { <EOL> assertSame ( e , exception ) <EOL> assertTrue ( testFinished ) <EOL> } <EOL> } ) { <EOL> runTest { <EOL> backgroundScope . launch { <EOL> throw exception <EOL> } <EOL> delay ( <NUM_LIT> ) <EOL> testFinished = true <EOL> } <EOL> } <EOL> }

/**
 * Tests that an error in a background coroutine does not cancel the test, but is reported at the end.
 */


@ Test <EOL> fun testBackgroundWorkFinalizing ( ) : TestResult

{ <EOL> var taskEnded = <NUM_LIT:0> <EOL> val nTasks = <NUM_LIT:10> <EOL> return testResultMap ( { <EOL> try { <EOL> it ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : TestException ) { <EOL> assertEquals ( <NUM_LIT:2> , e . suppressedExceptions . size ) <EOL> assertEquals ( nTasks , taskEnded ) <EOL> } <EOL> } ) { <EOL> runTest { <EOL> repeat ( nTasks ) { <EOL> backgroundScope . launch { <EOL> try { <EOL> while ( true ) { <EOL> delay ( <NUM_LIT:1> ) <EOL> } <EOL> } finally { <EOL> ++ taskEnded <EOL> if ( taskEnded <= <NUM_LIT:2> ) <EOL> throw TestException ( ) <EOL> } <EOL> } <EOL> } <EOL> delay ( <NUM_LIT:100> ) <EOL> throw TestException ( ) <EOL> } <EOL> } <EOL> }

/**
 * Tests that the background work gets to finish what it's doing after the test is completed.
 */


@ Test <EOL> fun testExampleBackgroundJob1 ( )

= runTest { <EOL> val myFlow = flow { <EOL> var i = <NUM_LIT:0> <EOL> while ( true ) { <EOL> emit ( ++ i ) <EOL> delay ( <NUM_LIT:1> ) <EOL> } <EOL> } <EOL> val stateFlow = myFlow . stateIn ( backgroundScope , SharingStarted . Eagerly , <NUM_LIT:0> ) <EOL> var j = <NUM_LIT:0> <EOL> repeat ( <NUM_LIT:100> ) { <EOL> assertEquals ( j ++ , stateFlow . value ) <EOL> delay ( <NUM_LIT:1> ) <EOL> } <EOL> }

/**
 * Tests using [Flow.stateIn] as a background job.
 */


@ Test <EOL> fun testExampleBackgroundJob2 ( )

= runTest { <EOL> val channel = Channel < Int > ( ) <EOL> backgroundScope . launch { <EOL> var i = <NUM_LIT:0> <EOL> while ( true ) { <EOL> channel . send ( i ++ ) <EOL> } <EOL> } <EOL> repeat ( <NUM_LIT:100> ) { <EOL> assertEquals ( it , channel . receive ( ) ) <EOL> } <EOL> }

/**
 * A test from the documentation of [TestScope.backgroundScope].
 */


@ Test <EOL> fun testBackgroundWorkNotPreventingTimeout ( ) : TestResult

= testResultMap ( { <EOL> try { <EOL> it ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( _ : UncompletedCoroutinesError ) { <EOL> } <EOL> } ) { <EOL> runTest ( timeout = <NUM_LIT:100> . milliseconds ) { <EOL> backgroundScope . launch { <EOL> while ( true ) { <EOL> yield ( ) <EOL> } <EOL> } <EOL> backgroundScope . launch { <EOL> while ( true ) { <EOL> delay ( <NUM_LIT:1> ) <EOL> } <EOL> } <EOL> val deferred = CompletableDeferred < Unit > ( ) <EOL> deferred . await ( ) <EOL> } <EOL> }

/**
 * Tests that the test will timeout due to idleness even if some background tasks are running.
 */


@ Test <EOL> fun testUnconfinedBackgroundWorkNotPreventingTimeout ( ) : TestResult

= testResultMap ( { <EOL> try { <EOL> it ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( _ : UncompletedCoroutinesError ) { <EOL> } <EOL> } ) { <EOL> runTest ( UnconfinedTestDispatcher ( ) , timeout = <NUM_LIT:100> . milliseconds ) { <EOL> backgroundScope . launch { <EOL> while ( true ) { <EOL> delay ( <NUM_LIT:1> ) <EOL> } <EOL> } <EOL> val deferred = CompletableDeferred < Unit > ( ) <EOL> deferred . await ( ) <EOL> } <EOL> }

/**
 * Tests that the background work will not prevent the test from timing out even in some cases
 * when the unconfined dispatcher is used.
 */


@ Test <EOL> fun testAsyncFailureInBackgroundReported ( )

= testResultMap ( { <EOL> try { <EOL> it ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : TestException ) { <EOL> assertEquals ( "<STR_LIT:z>" , e . message ) <EOL> assertEquals ( setOf ( "<STR_LIT:x>" , "<STR_LIT:y>" ) , e . suppressedExceptions . map { it . message } . toSet ( ) ) <EOL> } <EOL> } ) { <EOL> runTest { <EOL> backgroundScope . async { <EOL> throw TestException ( "<STR_LIT:x>" ) <EOL> } <EOL> backgroundScope . produce < Unit > { <EOL> throw TestException ( "<STR_LIT:y>" ) <EOL> } <EOL> delay ( <NUM_LIT:1> ) <EOL> throw TestException ( "<STR_LIT:z>" ) <EOL> } <EOL> }

/**
 * Tests that even the exceptions in the background scope that don't typically get reported and need to be queried
 * (like failures in [async]) will still surface in some simple scenarios.
 */


@ Test <EOL> fun testNoDuplicateExceptions ( )

= testResultMap ( { <EOL> try { <EOL> it ( ) <EOL> fail ( "<STR_LIT>" ) <EOL> } catch ( e : TestException ) { <EOL> assertEquals ( "<STR_LIT:y>" , e . message ) <EOL> assertEquals ( listOf ( "<STR_LIT:x>" ) , e . suppressedExceptions . map { it . message } ) <EOL> } <EOL> } ) { <EOL> runTest { <EOL> backgroundScope . launch { <EOL> throw TestException ( "<STR_LIT:x>" ) <EOL> } <EOL> delay ( <NUM_LIT:1> ) <EOL> throw TestException ( "<STR_LIT:y>" ) <EOL> } <EOL> }

/**
 * Tests that, if an exception reaches the [TestScope] exception reporting mechanism via several
 * channels, it will only be reported once.
 */


@ Test <EOL> fun testTimingOutWithVirtualTimeMessage ( )

= runTest { <EOL> try { <EOL> withTimeout ( <NUM_LIT> ) { <EOL> Channel < Unit > ( ) . receive ( ) <EOL> } <EOL> } catch ( e : TimeoutCancellationException ) { <EOL> assertContains ( e . message ! ! , "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Tests that [TestScope.withTimeout] notifies the programmer about using the virtual time.
 */


@ Test <EOL> fun testReportingStrayUncaughtExceptionsDuringTest ( ) : TestResult

{ <EOL> val thrown = TestException ( "<STR_LIT:x>" ) <EOL> return testResultChain ( { _ -> <EOL> runTest { <EOL> val job = launch ( Dispatchers . Default + NonCancellable ) { <EOL> throw thrown <EOL> } <EOL> job . join ( ) <EOL> } <EOL> } , { <EOL> runTest { <EOL> assertEquals ( thrown , it . exceptionOrNull ( ) ) <EOL> } <EOL> } ) <EOL> }

/**
 * Tests that the uncaught exceptions that happen during the test are reported.
 */


override fun check ( declaration : IrDeclaration , type : SpecialDeclarationType ) : Boolean

{ <EOL> return declaration . accept ( if ( compatibleMode ) compatibleChecker else checker , null ) <EOL> }

/**
 * @return true if [declaration] is exportable from klib point of view.
 * Depending on [compatibleMode] option the same declaration could have FileLocal or Common signature.
 */


@ GeneratedTest <EOL> fun BuildConfigurator . testLogLevel ( )

{ <EOL> val headerText = "<STR_LIT>" <EOL> addProjectWithKover { <EOL> sourcesFrom ( "<STR_LIT:simple>" ) <EOL> kover { <EOL> reports { <EOL> total { <EOL> log { <EOL> header . set ( headerText ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> run ( "<STR_LIT>" , "<STR_LIT>" ) { <EOL> assertContains ( output , headerText ) <EOL> } <EOL> run ( "<STR_LIT>" , "<STR_LIT>" ) { <EOL> assertContains ( output , headerText ) <EOL> } <EOL> }

/**
 * Check that coverage log is printed even if log level strictly limited (e.g. warn or quiet).
 */


public fun < T > height ( column : ColumnReference < T > , ) : NonPositionalMapping < T , Double >

= <EOL> addNonPositionalMapping < T , Double > ( HEIGHT , column . name ( ) , null )

/**
 * Maps the `height` aesthetic to a data column by [ColumnReference].
 *
 * @param column the data column to map to the color.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > height ( column : KProperty < T > , ) : NonPositionalMapping < T , Double >

= <EOL> addNonPositionalMapping < T , Double > ( HEIGHT , column . name , null )

/**
 * Maps the `height` aesthetic to a data column by [KProperty].
 *
 * @param column the data column to map to the color.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun height ( column : String ) : NonPositionalMapping < Any ? , Double >

= <EOL> addNonPositionalMapping ( HEIGHT , column , null )

/**
 * Maps the `height` aesthetic to a data column by [String].
 *
 * @param column the data column to map to the color.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > height ( values : Iterable < T > , name : String ? = null ) : NonPositionalMapping < T , Double >

= <EOL> addNonPositionalMapping ( HEIGHT , values . toList ( ) , name , null )

/**
 * Maps the `height` aesthetic to the iterable of values.
 *
 * @param values the iterable of values to be mapped.
 * @param name optional name for this aesthetic mapping.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > height ( values : DataColumn < T > ) : PositionalMapping < T >

= <EOL> addPositionalMapping ( HEIGHT , values , null )

/**
 * Maps the `height` aesthetic to a data column.
 *
 * @param values the data column to map to the color.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


internal fun IrSimpleFunction . findInterfaceImplementation ( jvmDefaultMode : JvmDefaultMode ) : IrSimpleFunction ?

{ <EOL> if ( ! isFakeOverride ) return null <EOL> val parent = parent <EOL> if ( parent is IrClass && ( parent . isJvmInterface || parent . isFromJava ( ) ) ) return null <EOL> val implementation = resolveFakeOverride ( toSkip = :: isDefaultImplsBridge ) ? : return null <EOL> if ( ! implementation . hasInterfaceParent ( ) || DescriptorVisibilities . isPrivate ( implementation . visibility ) || implementation . isDefinitelyNotDefaultImplsMethod ( jvmDefaultMode , implementation ) || implementation . isMethodOfAny ( ) ) { <EOL> return null <EOL> } <EOL> if ( overriddenSymbols . any { <EOL> ! it . owner . parentAsClass . isInterface && <EOL> it . owner . modality != Modality . ABSTRACT && <EOL> it . owner . resolveFakeOverride ( toSkip = :: isDefaultImplsBridge ) == implementation <EOL> } ) { <EOL> return null <EOL> } <EOL> return implementation <EOL> }

/**
 * Given a fake override in a class, returns an overridden declaration with implementation in interface, such that a method delegating to that
 * interface implementation should be generated into the class containing the fake override; or null if the given function is not a fake
 * override of any interface implementation or such method was already generated into the superclass or is a method from Any.
 */


internal fun < V : Any > createCache ( compute : ( Class < * > ) -> V ) : CacheByClass < V >

{ <EOL> return if ( useClassValue ) ClassValueCache ( compute ) else ConcurrentHashMapCache ( compute ) <EOL> }

/**
 * Creates a **softly referenced** cache of values associated with [Class].
 * Values are computed using provided [compute] function.
 *
 * `null` values are not supported, though there aren't any technical limitations.
 */


fun String . underlineAsText ( from : Int , to : Int ) : String

{ <EOL> val lines = StringBuilder ( ) <EOL> var marks = StringBuilder ( ) <EOL> var lineWasMarked = false <EOL> for ( i in indices ) { <EOL> val c = this [ i ] <EOL> val mark : Char <EOL> mark = when ( i ) { <EOL> in from .. to -> '<CHAR_LIT>' <EOL> else -> '<CHAR_LIT:U+0020>' <EOL> } <EOL> lines . append ( c ) <EOL> marks . append ( mark ) <EOL> lineWasMarked = lineWasMarked || mark != '<CHAR_LIT:U+0020>' <EOL> if ( isEndOfLine ( c . code ) ) { <EOL> if ( lineWasMarked ) { <EOL> lines . appendLine ( marks . toString ( ) . trimEnd ( ) ) <EOL> lineWasMarked = false <EOL> } <EOL> marks = StringBuilder ( ) <EOL> } <EOL> } <EOL> if ( lineWasMarked ) { <EOL> lines . appendLine ( ) <EOL> lines . append ( marks . toString ( ) ) <EOL> } <EOL> return lines . toString ( ) <EOL> }

/**
 * Underlines string in given rage.
 *
 * For example:
 * var = 10;
 * ^^^^
 */


private fun String . wildcardsToClassFileRegex ( ) : String

{ <EOL> val filenameWithWildcards = this . replace ( '<CHAR_LIT:.>' , File . separatorChar ) + "<STR_LIT>" <EOL> return KoverFeatures . koverWildcardToRegex ( filenameWithWildcards ) <EOL> }

/**
 * Replaces characters `.` to `|` or `\` and added `.class` as postfix and `.* /` or `.*\` as prefix.
 */


fun findStaticallyKnownSubtype ( supertype : ConeKotlinType , subTypeClassSymbol : FirRegularClassSymbol , context : CheckerContext ) : ConeKotlinType

{ <EOL> assert ( ! supertype . isMarkedNullable ) { "<STR_LIT>" } <EOL> val session = context . session <EOL> val typeContext = session . typeContext <EOL> val subtypeWithVariablesType = subTypeClassSymbol . defaultType ( ) <EOL> val typeCheckerState = context . session . typeContext . newTypeCheckerState ( errorTypesEqualToAnything = false , stubTypesEqualToAnything = false ) <EOL> val normalizedTypes = if ( supertype is ConeIntersectionType ) { <EOL> supertype . intersectedTypes <EOL> } else { <EOL> ArrayList < ConeKotlinType > ( <NUM_LIT:1> ) . also { it . add ( supertype ) } <EOL> } <EOL> val resultSubstitution = mutableMapOf < FirTypeParameterSymbol , ConeKotlinType > ( ) <EOL> for ( normalizedType in normalizedTypes ) { <EOL> val supertypeWithVariables = <EOL> findCorrespondingSupertypes ( typeCheckerState , subtypeWithVariablesType , normalizedType . typeConstructor ( typeContext ) ) . firstOrNull ( ) <EOL> val variables : List < FirTypeParameterSymbol > = subTypeClassSymbol . typeParameterSymbols <EOL> val substitution = if ( supertypeWithVariables != null ) { <EOL> val result = mutableMapOf < FirTypeParameterSymbol , ConeTypeProjection > ( ) <EOL> if ( context . session . doUnify ( supertype , supertypeWithVariables as ConeKotlinTypeProjection , variables . toSet ( ) , result ) ) { <EOL> result <EOL> } else { <EOL> mutableMapOf ( ) <EOL> } <EOL> } else { <EOL> mutableMapOf ( ) <EOL> } <EOL> for ( variable in variables ) { <EOL> val resultValue = when ( val value = substitution [ variable ] ) { <EOL> null -> null <EOL> is ConeStarProjection -> { <EOL> ConeStubTypeForTypeVariableInSubtyping ( ConeTypeVariable ( "<STR_LIT>" , null ) , ConeNullability . NULLABLE ) <EOL> } <EOL> else -> value . type <EOL> } <EOL> if ( resultValue != null ) { <EOL> resultSubstitution [ variable ] = resultValue <EOL> } <EOL> } <EOL> } <EOL> val substitutor = ConeSubstitutorByMap . create ( resultSubstitution , session ) <EOL> return substitutor . substituteOrSelf ( subtypeWithVariablesType ) <EOL> }

/**
 * Remember that we are trying to cast something of type `supertype` to `subtype`.

 * Since at runtime we can only check the class (type constructor), the rest of the subtype should be known statically, from supertype.
 * This method reconstructs all static information that can be obtained from supertype.

 * Example 1:
 * supertype = Collection
 * subtype = List<...>
 * result = List, all arguments are inferred

 * Example 2:
 * supertype = Any
 * subtype = List<...>
 * result = List<*>, some arguments were not inferred, replaced with '*'
 */


public fun resumeWith ( result : Result < T > )

/**
 * Resumes the execution of the corresponding coroutine passing a successful or failed [result] as the
 * return value of the last suspension point.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ InlineOnly <EOL> public inline fun < T > Continuation < T > . resume ( value : T ) : Unit

= <EOL> resumeWith ( Result . success ( value ) )

/**
 * Resumes the execution of the corresponding coroutine passing [value] as the return value of the last suspension point.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ InlineOnly <EOL> public inline fun < T > Continuation < T > . resumeWithException ( exception : Throwable ) : Unit

= <EOL> resumeWith ( Result . failure ( exception ) )

/**
 * Resumes the execution of the corresponding coroutine so that the [exception] is re-thrown right after the
 * last suspension point.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ InlineOnly <EOL> public inline fun < T > Continuation ( context : CoroutineContext , crossinline resumeWith : ( Result < T > ) -> Unit ) : Continuation < T >

= <EOL> object : Continuation < T > { <EOL> override val context : CoroutineContext <EOL> get ( ) = context <EOL> override fun resumeWith ( result : Result < T > ) = <EOL> resumeWith ( result ) <EOL> }

/**
 * Creates a [Continuation] instance with the given [context] and implementation of [resumeWith] method.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public fun < T > ( suspend ( ) -> T ) . createCoroutine ( completion : Continuation < T > ) : Continuation < Unit >

= <EOL> SafeContinuation ( createCoroutineUnintercepted ( completion ) . intercepted ( ) , COROUTINE_SUSPENDED )

/**
 * Creates a coroutine without a receiver and with result type [T].
 * This function creates a new, fresh instance of suspendable computation every time it is invoked.
 *
 * To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
 * The [completion] continuation is invoked when the coroutine completes with a result or an exception.
 * Subsequent invocation of any resume function on the resulting continuation will produce an [IllegalStateException].
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public fun < R , T > ( suspend R . ( ) -> T ) . createCoroutine ( receiver : R , completion : Continuation < T > ) : Continuation < Unit >

= <EOL> SafeContinuation ( createCoroutineUnintercepted ( receiver , completion ) . intercepted ( ) , COROUTINE_SUSPENDED )

/**
 * Creates a coroutine with receiver type [R] and result type [T].
 * This function creates a new, fresh instance of suspendable computation every time it is invoked.
 *
 * To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
 * The [completion] continuation is invoked when the coroutine completes with a result or an exception.
 * Subsequent invocation of any resume function on the resulting continuation will produce an [IllegalStateException].
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public fun < T > ( suspend ( ) -> T ) . startCoroutine ( completion : Continuation < T > )

{ <EOL> createCoroutineUnintercepted ( completion ) . intercepted ( ) . resume ( Unit ) <EOL> }

/**
 * Starts a coroutine without a receiver and with result type [T].
 * This function creates and starts a new, fresh instance of suspendable computation every time it is invoked.
 * The [completion] continuation is invoked when the coroutine completes with a result or an exception.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public fun < R , T > ( suspend R . ( ) -> T ) . startCoroutine ( receiver : R , completion : Continuation < T > )

{ <EOL> createCoroutineUnintercepted ( receiver , completion ) . intercepted ( ) . resume ( Unit ) <EOL> }

/**
 * Starts a coroutine with receiver type [R] and result type [T].
 * This function creates and starts a new, fresh instance of suspendable computation every time it is invoked.
 * The [completion] continuation is invoked when the coroutine completes with a result or an exception.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ InlineOnly <EOL> public suspend inline fun < T > suspendCoroutine ( crossinline block : ( Continuation < T > ) -> Unit ) : T

{ <EOL> contract { callsInPlace ( block , InvocationKind . EXACTLY_ONCE ) } <EOL> return suspendCoroutineUninterceptedOrReturn { c : Continuation < T > -> <EOL> val safe = SafeContinuation ( c . intercepted ( ) ) <EOL> block ( safe ) <EOL> safe . getOrThrow ( ) <EOL> } <EOL> }

/**
 * Obtains the current continuation instance inside suspend functions and suspends
 * the currently running coroutine.
 *
 * In this function both [Continuation.resume] and [Continuation.resumeWithException] can be used either synchronously in
 * the same stack-frame where the suspension function is run or asynchronously later in the same thread or
 * from a different thread of execution. Subsequent invocation of any resume function will produce an [IllegalStateException].
 */


open fun isLineTerminator ( char : Char ) : Boolean

= isLineTerminator ( char . toInt ( ) )

/** Checks if the single character is a line terminator or not. */


abstract fun isLineTerminator ( codepoint : Int ) : Boolean

/** Checks if the codepoint is a line terminator or not */


abstract fun isLineTerminatorPair ( char1 : Char , char2 : Char ) : Boolean

/** Checks if the pair of symbols is a line terminator (e.g. for \r\n case) */


abstract fun isAfterLineTerminator ( previous : Char , checked : Char ) : Boolean

/** Checks if a [checked] character is after a line terminator using the [previous] character.*/


{ <EOL> val ( train , test ) = mnist ( ) <EOL> val ( newTrain , validation ) = train . split ( <NUM_LIT> ) <EOL> lenet5 ( ) . use { <EOL> it . compile ( optimizer = SGD ( learningRate = <NUM_LIT> ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> it . fit ( trainingDataset = newTrain , validationDataset = validation , epochs = EPOCHS , trainBatchSize = TRAINING_BATCH_SIZE , validationBatchSize = TEST_BATCH_SIZE ) <EOL> it . save ( File ( PATH_TO_MODEL ) , SavingFormat . JsonConfigCustomVariables ( ) , writingMode = WritingMode . OVERRIDE ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> val model = Sequential . loadModelConfiguration ( File ( "<STR_LIT>" ) ) <EOL> model . use { <EOL> it . layers . filterIsInstance < Conv2D > ( ) . forEach ( Layer :: freeze ) <EOL> it . compile ( optimizer = RMSProp ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> it . loadWeights ( File ( PATH_TO_MODEL ) ) <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:2> , 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 examples demonstrates model and model weights export and import back:
 * - Model is exported in Keras-style JSON format; weights are exported in custom (TXT) format.
 * - Model is trained on Mnist dataset.
 * - It saves all the data to the project root directory.
 * - [Sequential] model is created via JSON configuration and weights loading.
 * - After loading model is trained again with another optimizer with frozen Conv2D layers. Only weights in Dense layers can be updated.
 */


= lenetOnMnistExportImportToJson ( )


public fun < R , T : InferenceModel < * > > T . predict ( dataset : Dataset , predictionFunction : T . ( FloatData ) -> R ) : List < R >

{ <EOL> return dataset . map { predictionFunction ( it ) } <EOL> }

/**
 * Runs [predictionFunction] for all observations in [dataset]
 * and collects predictions to the list.
 *
 * NOTE: Slow method.
 *
 * @param [R] Prediction result type.
 * @param [T] Model type.
 * @param [dataset] Dataset.
 * @param [predictionFunction] Prediction function to make predictions with.
 */


public fun < T : InferenceModel < * > > T . evaluate ( dataset : Dataset , metric : Metrics , predictionFunction : T . ( FloatData ) -> Int ) : Double

{ <EOL> if ( metric != Metrics . ACCURACY ) return Double . NaN <EOL> var counter = <NUM_LIT:0> <EOL> for ( i in <NUM_LIT:0> until dataset . xSize ( ) ) { <EOL> val predictedLabel = predictionFunction ( dataset . getX ( i ) ) <EOL> if ( predictedLabel == dataset . getY ( i ) . toInt ( ) ) <EOL> counter ++ <EOL> } <EOL> return ( counter . toDouble ( ) / dataset . xSize ( ) ) <EOL> }

/**
 * Evaluates [dataset] via [metric] with the given [predictionFunction].
 *
 * NOTE: Slow method.
 *
 * @param [T] Model type.
 * @param [dataset] Dataset.
 * @param [metric] Metric to use.
 * @param [predictionFunction] Prediction function to make predictions with.
 */


{ <EOL> val modelHub = TFModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = TFModels . CVnoTop . ResNet50 ( inputShape = intArrayOf ( IMAGE_SIZE , IMAGE_SIZE , <NUM_LIT:3> ) ) <EOL> val model = modelHub . loadModel ( modelType ) <EOL> val hdfFile = modelHub . loadWeights ( modelType ) <EOL> val layers = mutableListOf < Layer > ( ) <EOL> for ( layer in model . layers ) { <EOL> layers . add ( layer ) <EOL> } <EOL> val newGlobalAvgPool2DLayer = GlobalAvgPool2D ( name = "<STR_LIT>" , ) <EOL> newGlobalAvgPool2DLayer . inboundLayers . add ( layers . last ( ) ) <EOL> layers . add ( newGlobalAvgPool2DLayer ) <EOL> val newDenseLayer = Dense ( name = "<STR_LIT>" , kernelInitializer = GlorotUniform ( ) , biasInitializer = GlorotUniform ( ) , outputSize = <NUM_LIT> , activation = Activations . Relu ) <EOL> newDenseLayer . inboundLayers . add ( layers . last ( ) ) <EOL> layers . add ( newDenseLayer ) <EOL> val newDenseLayer2 = Dense ( name = "<STR_LIT>" , kernelInitializer = GlorotUniform ( ) , biasInitializer = GlorotUniform ( ) , outputSize = NUM_CLASSES , activation = Activations . Linear ) <EOL> newDenseLayer2 . inboundLayers . add ( layers . last ( ) ) <EOL> layers . add ( newDenseLayer2 ) <EOL> val model2 = Functional . of ( layers ) <EOL> val dataset = OnFlyImageDataset . create ( File ( dogsCatsSmallDatasetPath ( ) ) , FromFolders ( mapping = mapOf ( "<STR_LIT>" to <NUM_LIT:0> , "<STR_LIT>" to <NUM_LIT:1> ) ) , modelType . createPreprocessing ( model2 ) ) . shuffle ( ) <EOL> val ( train , test ) = dataset . split ( TRAIN_TEST_SPLIT_RATIO ) <EOL> model2 . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . loadWeightsForFrozenLayers ( hdfFile ) <EOL> val accuracyBeforeTraining = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> it . fit ( dataset = train , batchSize = TRAINING_BATCH_SIZE , epochs = EPOCHS ) <EOL> val accuracyAfterTraining = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example demonstrates the transfer learning concept on ResNet'50 model:
 * - Model configuration, model weights and labels are obtained from [TFModelHub].
 * - Weights are loaded from .h5 file, configuration is loaded from .json file.
 * - All layers, are added to the new Neural Network, its weights are frozen.
 * - New GlobalAvgPool2D and Dense layers are added and initialized via defined initializers.
 * - Model is re-trained on [dogsCatsSmallDatasetPath] dataset.
 *
 * We use the preprocessing DSL to describe the dataset generation pipeline.
 * We demonstrate the workflow on the subset of Kaggle Cats vs Dogs binary classification dataset.
 */


= resnet50noTopAdditionalTraining ( )


private fun FirTypeParameterRefsOwner . buildSubstitutorWithUpperBounds ( session : FirSession , type : ConeClassLikeType ) : ConeSubstitutor ?

{ <EOL> if ( typeParameters . isEmpty ( ) ) return null <EOL> fun createMapping ( substitutor : ConeSubstitutor ) : Map < FirTypeParameterSymbol , ConeKotlinType > { <EOL> return typeParameters . zip ( type . typeArguments ) . associate { ( parameter , projection ) -> <EOL> val typeArgument = <EOL> ( projection as? ConeKotlinTypeProjection ) ? . type <EOL> ? : parameter . symbol . fir . bounds . firstOrNull ( ) ? . coneTypeSafe ( ) <EOL> ? : session . builtinTypes . nullableAnyType . type <EOL> Pair ( parameter . symbol , substitutor . substituteOrSelf ( typeArgument ) ) <EOL> } <EOL> } <EOL> var substitutor : ConeSubstitutor = ConeSubstitutor . Empty <EOL> var containsNonSubstitutedArguments = false <EOL> for ( i in typeParameters . indices ) { <EOL> val mapping = createMapping ( substitutor ) <EOL> substitutor = substitutorByMap ( mapping , session ) <EOL> containsNonSubstitutedArguments = mapping . values . any { bound -> <EOL> bound . contains { type -> <EOL> type is ConeTypeParameterType && typeParameters . any { it . symbol == type . lookupTag . typeParameterSymbol } <EOL> } <EOL> } <EOL> if ( ! containsNonSubstitutedArguments ) { <EOL> break <EOL> } <EOL> } <EOL> if ( containsNonSubstitutedArguments ) { <EOL> val errorSubstitution = typeParameters . associate { <EOL> val diagnostic = ConeSimpleDiagnostic ( reason = "<STR_LIT>" , DiagnosticKind . CannotInferParameterType ) <EOL> it . symbol to ConeErrorType ( diagnostic ) <EOL> } <EOL> val errorSubstitutor = substitutorByMap ( errorSubstitution , session ) <EOL> substitutor = substitutorByMap ( createMapping ( errorSubstitutor ) , session ) <EOL> } <EOL> return substitutor <EOL> }

/**
 * This function creates a substitutor for SAM class/SAM constructor based on the expected SAM type.
 * If there is a typeless projection in some argument of the expected type then the upper bound of the corresponding type parameters is used
 */


private fun FirSimpleFunction . isPublicInObject ( checkOnlyName : Boolean ) : Boolean

{ <EOL> if ( ! isJavaOrEnhancement ) return false <EOL> if ( name . asString ( ) !in PUBLIC_METHOD_NAMES_IN_OBJECT ) return false <EOL> if ( checkOnlyName ) return true <EOL> return when ( name . asString ( ) ) { <EOL> "<STR_LIT:hashCode>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT:toString>" -> valueParameters . isEmpty ( ) <EOL> "<STR_LIT:equals>" -> valueParameters . singleOrNull ( ) ? . hasTypeOf ( StandardClassIds . Any , allowNullable = true ) == true <EOL> "<STR_LIT>" -> when ( valueParameters . size ) { <EOL> <NUM_LIT:0> -> true <EOL> <NUM_LIT:1> -> valueParameters [ <NUM_LIT:0> ] . hasTypeOf ( StandardClassIds . Long , allowNullable = false ) <EOL> <NUM_LIT:2> -> valueParameters [ <NUM_LIT:0> ] . hasTypeOf ( StandardClassIds . Long , allowNullable = false ) && <EOL> valueParameters [ <NUM_LIT:1> ] . hasTypeOf ( StandardClassIds . Int , allowNullable = false ) <EOL> else -> false <EOL> } <EOL> else -> errorWithAttachment ( "<STR_LIT>" ) { <EOL> withEntry ( "<STR_LIT>" , name . asString ( ) ) <EOL> } <EOL> } <EOL> }

/**
 * From the definition of function interfaces in the Java specification (pt. 9.8):
 * "methods that are members of I that do not have the same signature as any public instance method of the class Object"
 * It means that if an interface declares `int hashCode()` then the method won't be taken into account when
 * checking if the interface is SAM.
 *
 * For K1 compatibility, this only applies to members declared in Java, see KT-67283.
 */


{ <EOL> disposeStablePointer ( this . stablePtr ) <EOL> }

/**
 * Disposes the handle. It must not be [used][get] after that.
 */


= @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) ( derefStablePointer ( stablePtr ) as T )

/**
 * Returns the underlying pinned object.
 */


internal fun DObject ? . staticPropertiesForJava ( ) : List < DProperty >

{ <EOL> if ( this == null ) return emptyList ( ) <EOL> return properties . filter { it . isJvmField || it . isConst || it . isLateInit } <EOL> }

/**
 * @return properties that will be visible as static for java.
 * See [Static fields](https://kotlinlang.org/docs/java-to-kotlin-interop.html#static-fields)
 */


internal fun DObject . hasNothingToRender ( ) : Boolean

{ <EOL> val nonStaticPropsCount = properties . size - staticPropertiesForJava ( ) . size <EOL> val nonStaticFunctionsCount = functions . size - staticFunctionsForJava ( ) . size <EOL> val classLikesCount = classlikes . size <EOL> val superTypesCount = supertypes . values . firstOrNull ( ) ? . size ? : <NUM_LIT:0> <EOL> return nonStaticFunctionsCount + nonStaticPropsCount + <EOL> classLikesCount + superTypesCount == <NUM_LIT:0> <EOL> }

/**
 * Hide companion object if there isn't members of parents.
 * Properties and functions that are moved to outer class are not counted as members.
 */


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> @ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> @ DeprecatedSinceKotlin ( warningSince = "<STR_LIT:1.4>" , errorSince = "<STR_LIT:1.5>" ) <EOL> public actual fun String ( chars : CharArray ) : String

{ <EOL> var result = "<STR_LIT>" <EOL> for ( char in chars ) { <EOL> result += char <EOL> } <EOL> return result <EOL> }

/**
 * Converts the characters in the specified array to a string.
 */


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> @ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> @ DeprecatedSinceKotlin ( warningSince = "<STR_LIT:1.4>" , errorSince = "<STR_LIT:1.5>" ) <EOL> public actual fun String ( chars : CharArray , offset : Int , length : Int ) : String

{ <EOL> if ( offset < <NUM_LIT:0> || length < <NUM_LIT:0> || chars . size - offset < length ) <EOL> throw IndexOutOfBoundsException ( "<STR_LIT>" ) <EOL> var result = "<STR_LIT>" <EOL> for ( index in offset until offset + length ) { <EOL> result += chars [ index ] <EOL> } <EOL> return result <EOL> }

/**
 * Converts the characters from a portion of the specified array to a string.
 *
 * @throws IndexOutOfBoundsException if either [offset] or [length] are less than zero
 * or `offset + length` is out of [chars] array bounds.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun CharArray . concatToString ( ) : String

{ <EOL> var result = "<STR_LIT>" <EOL> for ( char in this ) { <EOL> result += char <EOL> } <EOL> return result <EOL> }

/**
 * Concatenates characters in this [CharArray] into a String.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ Suppress ( "<STR_LIT:ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS>" ) <EOL> public actual fun CharArray . concatToString ( startIndex : Int = <NUM_LIT:0> , endIndex : Int = this . size ) : String

{ <EOL> AbstractList . checkBoundsIndexes ( startIndex , endIndex , this . size ) <EOL> var result = "<STR_LIT>" <EOL> for ( index in startIndex until endIndex ) { <EOL> result += this [ index ] <EOL> } <EOL> return result <EOL> }

/**
 * Concatenates characters in this [CharArray] or its subrange into a String.
 *
 * @param startIndex the beginning (inclusive) of the subrange of characters, 0 by default.
 * @param endIndex the end (exclusive) of the subrange of characters, size of this array by default.
 *
 * @throws IndexOutOfBoundsException if [startIndex] is less than zero or [endIndex] is greater than the size of this array.
 * @throws IllegalArgumentException if [startIndex] is greater than [endIndex].
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun String . toCharArray ( ) : CharArray

{ <EOL> return CharArray ( length ) { get ( it ) } <EOL> }

/**
 * Returns a [CharArray] containing characters of this string.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ Suppress ( "<STR_LIT:ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS>" ) <EOL> public actual fun String . toCharArray ( startIndex : Int = <NUM_LIT:0> , endIndex : Int = this . length ) : CharArray

{ <EOL> AbstractList . checkBoundsIndexes ( startIndex , endIndex , length ) <EOL> return CharArray ( endIndex - startIndex ) { get ( startIndex + it ) } <EOL> }

/**
 * Returns a [CharArray] containing characters of this string or its substring.
 *
 * @param startIndex the beginning (inclusive) of the substring, 0 by default.
 * @param endIndex the end (exclusive) of the substring, length of this string by default.
 *
 * @throws IndexOutOfBoundsException if [startIndex] is less than zero or [endIndex] is greater than the length of this string.
 * @throws IllegalArgumentException if [startIndex] is greater than [endIndex].
 */


@ SinceKotlin ( "<STR_LIT:2.0>" ) <EOL> @ Suppress ( "<STR_LIT:ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS>" ) <EOL> public actual fun String . toCharArray ( destination : CharArray , destinationOffset : Int = <NUM_LIT:0> , startIndex : Int = <NUM_LIT:0> , endIndex : Int = length ) : CharArray

{ <EOL> AbstractList . checkBoundsIndexes ( startIndex , endIndex , length ) <EOL> AbstractList . checkBoundsIndexes ( destinationOffset , destinationOffset + endIndex - startIndex , destination . size ) <EOL> var destIndex = destinationOffset <EOL> for ( i in startIndex until endIndex ) { <EOL> destination [ destIndex ++ ] = this [ i ] <EOL> } <EOL> return destination <EOL> }

/**
 * Copies characters from this string into the [destination] character array and returns that array.
 *
 * @param destination the array to copy to.
 * @param destinationOffset the position in the array to copy to.
 * @param startIndex the start offset (inclusive) of the substring to copy.
 * @param endIndex the end offset (exclusive) of the substring to copy.
 *
 * @throws IndexOutOfBoundsException or [IllegalArgumentException] when [startIndex] or [endIndex] is out of range of this string builder indices or when `startIndex > endIndex`.
 * @throws IndexOutOfBoundsException when the subrange doesn't fit into the [destination] array starting at the specified [destinationOffset],
 * or when that index is out of the [destination] array indices range.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun ByteArray . decodeToString ( ) : String

{ <EOL> return decodeUtf8 ( this , <NUM_LIT:0> , size , false ) <EOL> }

/**
 * Decodes a string from the bytes in UTF-8 encoding in this array.
 *
 * Malformed byte sequences are replaced by the replacement char `\uFFFD`.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ Suppress ( "<STR_LIT:ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS>" ) <EOL> public actual fun ByteArray . decodeToString ( startIndex : Int = <NUM_LIT:0> , endIndex : Int = this . size , throwOnInvalidSequence : Boolean = false ) : String

{ <EOL> AbstractList . checkBoundsIndexes ( startIndex , endIndex , this . size ) <EOL> return decodeUtf8 ( this , startIndex , endIndex , throwOnInvalidSequence ) <EOL> }

/**
 * Decodes a string from the bytes in UTF-8 encoding in this array or its subrange.
 *
 * @param startIndex the beginning (inclusive) of the subrange to decode, 0 by default.
 * @param endIndex the end (exclusive) of the subrange to decode, size of this array by default.
 * @param throwOnInvalidSequence specifies whether to throw an exception on malformed byte sequence or replace it by the replacement char `\uFFFD`.
 *
 * @throws IndexOutOfBoundsException if [startIndex] is less than zero or [endIndex] is greater than the size of this array.
 * @throws IllegalArgumentException if [startIndex] is greater than [endIndex].
 * @throws CharacterCodingException if the byte array contains malformed UTF-8 byte sequence and [throwOnInvalidSequence] is true.
 */