{ <EOL> var oldValue : V ? = null <EOL> var removedRef : SoftReferenceWithCleanup < K , V > ? = null <EOL> backingMap . compute ( key ) { _ , currentRef -> <EOL> val currentValue = currentRef ? . get ( ) <EOL> oldValue = currentValue <EOL> if ( value === currentValue ) { <EOL> return@compute currentRef <EOL> } <EOL> removedRef = currentRef <EOL> createSoftReference ( key , value ) <EOL> } <EOL> removedRef ? . performCleanup ( ) <EOL> processQueue ( ) <EOL> return oldValue <EOL> }

/**
 * Adds or replaces [value] to/in the cache at the given [key]. **Must be called in a read action.**
 *
 * As replacement constitutes removal, cleanup will be performed on the replaced value. When the existing value and the new value are
 * the same (referentially equal), cleanup will not be performed, because the existing value effectively wasn't removed from the cache.
 *
 * @return The old value that has been replaced, if any.
 */


{ <EOL> val ref = backingMap . remove ( key ) <EOL> ref ? . performCleanup ( ) <EOL> processQueue ( ) <EOL> return ref ? . get ( ) <EOL> }

/**
 * Removes the value associated with [key] from the cache, performs cleanup on it, and returns it if it exists. **Must be called in a
 * read action.**
 */


{ <EOL> ApplicationManager . getApplication ( ) . assertWriteAccessAllowed ( ) <EOL> backingMap . values . forEach { it . performCleanup ( ) } <EOL> backingMap . clear ( ) <EOL> processQueue ( ) <EOL> }

/**
 * Removes all values from the cache and performs cleanup on them. **Must be called in a *write* action.**
 *
 * The write action requirement is due to the complexity associated with atomically clearing a concurrent cache while also performing
 * cleanup on exactly the cleared values. Because this cache implementation is used by components which operate in read and write
 * actions, requiring a write action is more economical than synchronizing on some cache-wide lock.
 */


{ <EOL> processQueue ( ) <EOL> return backingMap . isEmpty ( ) <EOL> }

/**
 * Returns whether the cache is empty. **Must be called in a read action.**
 */


private fun TestProject . assertConsecutiveBuildsProduceSameBinaries ( )

{ <EOL> fun File . relativeToProject ( ) = this . relativeTo ( projectPath . toFile ( ) ) <EOL> fun Diff . reportString ( ) : String = when ( this ) { <EOL> is Diff . DifferentContent -> "<STR_LIT>" <EOL> is Diff . MissingFile -> "<STR_LIT>" <EOL> is Diff . TypeMismatch -> "<STR_LIT>" <EOL> } <EOL> buildGradleKts . appendText ( """<STR_LIT>""" . trimIndent ( ) ) <EOL> build ( "<STR_LIT>" ) <EOL> build ( "<STR_LIT>" , "<STR_LIT>" ) { <EOL> tasks . forEach { task -> <EOL> assertTrue ( task . outcome in setOf ( TaskOutcome . SUCCESS , TaskOutcome . SKIPPED , TaskOutcome . NO_SOURCE ) , "<STR_LIT>" ) <EOL> } <EOL> } <EOL> val repo1 = projectPath . resolve ( "<STR_LIT>" ) . toFile ( ) <EOL> val repo2 = projectPath . resolve ( "<STR_LIT>" ) . toFile ( ) <EOL> val diffs = diff ( repo1 , repo2 ) . filter { diff -> "<STR_LIT>" !in diff . fileName } <EOL> if ( diffs . isNotEmpty ( ) ) { <EOL> fail ( buildString { <EOL> appendLine ( "<STR_LIT>" ) <EOL> diffs . forEach { diff -> <EOL> appendLine ( diff . reportString ( ) ) <EOL> } <EOL> } ) <EOL> } <EOL> }

/**
 * This will test if building a project consecutively will result in the same binaries.
 * This method will inject code into the build.gradle.kts file to perform the following:
 *
 * - publish the project into a local repository (repo1)
 * - publish the project into a local repository (repo2) (whilst --rerun-tasks guarantees everything is re-built)
 * - Run the 'diff' tool to ensure that the published artifacts are equal in repo1 & repo2
 */


fun findMetadata ( classId : ClassId ) : InputStream ?

/**
 * @return an [InputStream] which should be used to load the .kotlin_metadata file for class with the given [classId].
 * [classId] identifies either a real top level class, or a package part (e.g. it can be "foo/bar/_1Kt")
 */


fun hasMetadataPackage ( fqName : FqName ) : Boolean

/**
 * @return `true` iff this finder is able to locate the package with the given [fqName], containing .kotlin_metadata files.
 * Note that returning `true` makes [MetadataPackageFragmentProvider] construct the package fragment for the package,
 * and that fact can alter the qualified name expression resolution in the compiler front-end
 */


fun findBuiltInsData ( packageFqName : FqName ) : InputStream ?

/**
 * @return an [InputStream] which should be used to load the .kotlin_builtins file for package with the given [packageFqName].
 */


internal fun KtUserType . classId ( ) : ClassId

{ <EOL> val packageFragments = mutableListOf < String > ( ) <EOL> val classFragments = mutableListOf < String > ( ) <EOL> fun collectFragments ( type : KtUserType ) { <EOL> val userType = type . getStubOrPsiChild ( KtStubElementTypes . USER_TYPE ) <EOL> if ( userType != null ) { <EOL> collectFragments ( userType ) <EOL> } <EOL> val referenceExpression = type . referenceExpression as? KtNameReferenceExpression <EOL> if ( referenceExpression != null ) { <EOL> val referencedName = referenceExpression . getReferencedName ( ) <EOL> val stub = referenceExpression . stub ? : loadStubByElement ( referenceExpression ) <EOL> if ( stub is KotlinNameReferenceExpressionStubImpl && stub . isClassRef ) { <EOL> classFragments . add ( referencedName ) <EOL> } else { <EOL> packageFragments . add ( referencedName ) <EOL> } <EOL> } <EOL> } <EOL> collectFragments ( this ) <EOL> return ClassId ( FqName . fromSegments ( packageFragments ) , FqName . fromSegments ( classFragments ) , isLocal = false ) <EOL> }

/**
 * Retrieves classId from [KtUserType] for compiled code only.
 *
 * It relies on [org.jetbrains.kotlin.psi.stubs.impl.KotlinNameReferenceExpressionStubImpl.isClassRef],
 * which is set during cls analysis only.
 */


fun tmpdir ( ) : String ?

/**
 * See https://nodejs.org/api/os.html#ostmpdir
 */


fun platform ( ) : String

/**
 * See https://nodejs.org/api/os.html#osplatform
 */


public fun serialNameForJson ( descriptor : SerialDescriptor , elementIndex : Int , serialName : String ) : String

/**
 * Accepts an original [serialName] (defined by property name in the class or [SerialName] annotation) and returns
 * a transformed serial name which should be used for serialization and deserialization.
 *
 * Besides string manipulation operations, it is also possible to implement transformations that depend on the [descriptor]
 * and its element (defined by [elementIndex]) currently being serialized.
 * It is guaranteed that `descriptor.getElementName(elementIndex) == serialName`.
 * For example, one can choose different transformations depending on [SerialInfo]
 * annotations (see [SerialDescriptor.getElementAnnotations]) or element optionality (see [SerialDescriptor.isElementOptional]).
 *
 * Note that invocations of this function are cached for performance reasons.
 * Caching strategy is an implementation detail and should not be assumed as a part of the public API contract, as it may be changed in future releases.
 * Therefore, it is essential for this function to be pure: it should not have any side effects, and it should
 * return the same String for a given [descriptor], [elementIndex], and [serialName], regardless of the number of invocations.
 */


{ <EOL> val preprocessing = pipeline < BufferedImage > ( ) <EOL> . crop { <EOL> left = <NUM_LIT:2> <EOL> right = <NUM_LIT:2> <EOL> top = <NUM_LIT:2> <EOL> bottom = <NUM_LIT:2> <EOL> } <EOL> . rotate { <EOL> degrees = <NUM_LIT> <EOL> } <EOL> . resize { <EOL> outputHeight = IMAGE_SIZE . toInt ( ) <EOL> outputWidth = IMAGE_SIZE . toInt ( ) <EOL> interpolation = InterpolationType . NEAREST <EOL> } <EOL> . convert { colorMode = ColorMode . BGR } <EOL> . toFloatArray { } <EOL> . rescale { <EOL> scalingCoefficient = <NUM_LIT> <EOL> } <EOL> val ( cifarImagesArchive , cifarLabelsArchive ) = cifar10Paths ( ) <EOL> val y = extractCifar10LabelsAnsSort ( cifarLabelsArchive ) <EOL> val dataset = OnFlyImageDataset . create ( File ( cifarImagesArchive ) , y , preprocessing ) <EOL> val ( train , test ) = dataset . split ( TRAIN_TEST_SPLIT_RATIO ) <EOL> vgg11 . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> val start = System . currentTimeMillis ( ) <EOL> it . fit ( dataset = train , epochs = EPOCHS , batchSize = TRAINING_BATCH_SIZE ) <EOL> println ( "<STR_LIT>" ) <EOL> it . save ( File ( PATH_TO_MODEL ) , writingMode = WritingMode . OVERRIDE ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example shows how to do image classification from scratch using [vgg11] model, without leveraging pre-trained weights.
 * We demonstrate the workflow on the Cifar'10 classification dataset.
 *
 * We use the preprocessing DSL to describe the dataset generation pipeline.
 *
 * It includes:
 * - dataset loading from S3
 * - preprocessing DSL declaration
 * - [OnFlyImageDataset] dataset creation
 * - dataset splitting
 * - model compilation
 * - model training
 * - model export
 * - model evaluation
 */


private fun findReceiverFirExpression ( receiverExpression : KtExpression ) : FirExpression ?

{ <EOL> if ( receiverExpression is KtStatementExpression ) { <EOL> return null <EOL> } <EOL> val parentCall = receiverExpression . getQualifiedExpressionForReceiver ( ) <EOL> if ( parentCall !is KtSafeQualifiedExpression ) { <EOL> return receiverExpression . getOrBuildFirOfType < FirExpression > ( firResolveSession ) <EOL> } <EOL> val firSafeCall = parentCall . getOrBuildFirOfType < FirSafeCallExpression > ( firResolveSession ) <EOL> return firSafeCall . checkedSubjectRef . value <EOL> }

/**
 * Returns a [FirExpression] matching the given PSI [receiverExpression].
 *
 * @param receiverExpression a qualified expression receiver (e.g., `foo` in `foo?.bar()`, or in `foo.bar`).
 *
 * The function unwraps certain receiver expressions. For instance, for safe calls direct counterpart to a [KtSafeQualifiedExpression]
 * is (FirCheckedSafeCallSubject)[org.jetbrains.kotlin.fir.expressions.FirCheckedSafeCallSubject] which requires additional unwrapping
 * to be used for call resolution.
 */


internal fun < T : Any > registerEvent ( dispatcher : TestDispatcher , timeDeltaMillis : Long , marker : T , context : CoroutineContext , isCancelled : ( T ) -> Boolean ) : DisposableHandle

{ <EOL> require ( timeDeltaMillis >= <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> checkSchedulerInContext ( this , context ) <EOL> val count = count . getAndIncrement ( ) <EOL> val isForeground = context [ BackgroundWork ] === null <EOL> return synchronized ( lock ) { <EOL> val time = addClamping ( currentTime , timeDeltaMillis ) <EOL> val event = TestDispatchEvent ( dispatcher , count , time , marker as Any , isForeground ) { isCancelled ( marker ) } <EOL> events . addLast ( event ) <EOL> sendDispatchEvent ( context ) <EOL> DisposableHandle { <EOL> synchronized ( lock ) { <EOL> events . remove ( event ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Registers a request for the scheduler to notify [dispatcher] at a virtual moment [timeDeltaMillis] milliseconds
 * later via [TestDispatcher.processEvent], which will be called with the provided [marker] object.
 *
 * Returns the handler which can be used to cancel the registration.
 */


internal fun tryRunNextTaskUnless ( condition : ( ) -> Boolean ) : Boolean

{ <EOL> val event = synchronized ( lock ) { <EOL> if ( condition ( ) ) return false <EOL> val event = events . removeFirstOrNull ( ) ? : return false <EOL> if ( currentTime > event . time ) <EOL> currentTimeAheadOfEvents ( ) <EOL> currentTime = event . time <EOL> event <EOL> } <EOL> event . dispatcher . processEvent ( event . marker ) <EOL> return true <EOL> }

/**
 * Runs the next enqueued task, advancing the virtual time to the time of its scheduled awakening,
 * unless [condition] holds.
 */


= advanceUntilIdleOr { events . none ( TestDispatchEvent < * > :: isForeground ) }

/**
 * Runs the enqueued tasks in the specified order, advancing the virtual time as needed until there are no more
 * tasks associated with the dispatchers linked to this scheduler.
 *
 * A breaking change from `TestCoroutineDispatcher.advanceTimeBy` is that it no longer returns the total number of
 * milliseconds by which the execution of this method has advanced the virtual time. If you want to recreate that
 * functionality, query [currentTime] before and after the execution to achieve the same result.
 */


internal fun advanceUntilIdleOr ( condition : ( ) -> Boolean )

{ <EOL> while ( true ) { <EOL> if ( ! tryRunNextTaskUnless ( condition ) ) <EOL> return <EOL> } <EOL> }

/**
 * [condition]: guaranteed to be invoked under the lock.
 */


{ <EOL> val timeMark = synchronized ( lock ) { currentTime } <EOL> while ( true ) { <EOL> val event = synchronized ( lock ) { <EOL> events . removeFirstIf { it . time <= timeMark } ? : return <EOL> } <EOL> event . dispatcher . processEvent ( event . marker ) <EOL> } <EOL> }

/**
 * Runs the tasks that are scheduled to execute at this moment of virtual time.
 */


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

= advanceTimeBy ( delayTimeMillis . milliseconds )

/**
 * Moves the virtual clock of this dispatcher forward by [the specified amount][delayTimeMillis], running the
 * scheduled tasks in the meantime.
 *
 * Breaking changes from [TestCoroutineDispatcher.advanceTimeBy]:
 * - Intentionally doesn't return a `Long` value, as its use cases are unclear. We may restore it in the future;
 * please describe your use cases at [the issue tracker](https://github.com/Kotlin/kotlinx.coroutines/issues/).
 * For now, it's possible to query [currentTime] before and after execution of this method, to the same effect.
 * - It doesn't run the tasks that are scheduled at exactly [currentTime] + [delayTimeMillis]. For example,
 * advancing the time by one millisecond used to run the tasks at the current millisecond *and* the next
 * millisecond, but now will stop just before executing any task starting at the next millisecond.
 * - Overflowing the target time used to lead to nothing being done, but will now run the tasks scheduled at up to
 * (but not including) [Long.MAX_VALUE].
 *
 * @throws IllegalArgumentException if passed a negative [delay][delayTimeMillis].
 */


public fun advanceTimeBy ( delayTime : Duration )

{ <EOL> require ( ! delayTime . isNegative ( ) ) { "<STR_LIT>" } <EOL> val startingTime = currentTime <EOL> val targetTime = addClamping ( startingTime , delayTime . inWholeMilliseconds ) <EOL> while ( true ) { <EOL> val event = synchronized ( lock ) { <EOL> val timeMark = currentTime <EOL> val event = events . removeFirstIf { targetTime > it . time } <EOL> when { <EOL> event == null -> { <EOL> currentTime = targetTime <EOL> return <EOL> } <EOL> timeMark > event . time -> currentTimeAheadOfEvents ( ) <EOL> else -> { <EOL> currentTime = event . time <EOL> event <EOL> } <EOL> } <EOL> } <EOL> event . dispatcher . processEvent ( event . marker ) <EOL> } <EOL> }

/**
 * Moves the virtual clock of this dispatcher forward by [the specified amount][delayTime], running the
 * scheduled tasks in the meantime.
 *
 * @throws IllegalArgumentException if passed a negative [delay][delayTime].
 */


internal fun isIdle ( strict : Boolean = true ) : Boolean

= <EOL> synchronized ( lock ) { <EOL> if ( strict ) events . isEmpty else events . none { ! it . isCancelled ( ) } <EOL> }

/**
 * Checks that the only tasks remaining in the scheduler are cancelled.
 */


internal fun sendDispatchEvent ( context : CoroutineContext )

{ <EOL> dispatchEvents . trySend ( Unit ) <EOL> if ( context [ BackgroundWork ] !== BackgroundWork ) <EOL> dispatchEventsForeground . trySend ( Unit ) <EOL> }

/**
 * Notifies this scheduler about a dispatch event.
 *
 * [context] is the context in which the task will be dispatched.
 */


internal suspend fun receiveDispatchEvent ( )

= dispatchEvents . receive ( )

/**
 * Waits for a notification about a dispatch event.
 */


public fun < R > Sequence < * > . filterIsInstance ( klass : Class < R > ) : Sequence < R >

{ <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> return filter { klass . isInstance ( it ) } as Sequence < R > <EOL> }

/**
 * Returns a sequence containing all elements that are instances of specified class.
 *
 * The operation is _intermediate_ and _stateless_.
 *
 * @sample samples.collections.Collections.Filtering.filterIsInstanceJVM
 */


public fun < C : MutableCollection < in R > , R > Sequence < * > . filterIsInstanceTo ( destination : C , klass : Class < R > ) : C

{ <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> for ( element in this ) if ( klass . isInstance ( element ) ) destination . add ( element as R ) <EOL> return destination <EOL> }

/**
 * Appends all elements that are instances of specified class to the given [destination].
 *
 * The operation is _terminal_.
 *
 * @sample samples.collections.Collections.Filtering.filterIsInstanceToJVM
 */


public fun < T : Comparable < T > > Sequence < T > . toSortedSet ( ) : java . util . SortedSet < T >

{ <EOL> return toCollection ( java . util . TreeSet < T > ( ) ) <EOL> }

/**
 * Returns a new [SortedSet][java.util.SortedSet] of all elements.
 *
 * The operation is _terminal_.
 */


public fun < T > Sequence < T > . toSortedSet ( comparator : Comparator < in T > ) : java . util . SortedSet < T >

{ <EOL> return toCollection ( java . util . TreeSet < T > ( comparator ) ) <EOL> }

/**
 * Returns a new [SortedSet][java.util.SortedSet] of all elements.
 *
 * Elements in the set returned are sorted according to the given [comparator].
 *
 * The operation is _terminal_.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ OptIn ( kotlin . experimental . ExperimentalTypeInference :: class ) <EOL> @ OverloadResolutionByLambdaReturnType <EOL> @ kotlin . jvm . JvmName ( "<STR_LIT>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun < T > Sequence < T > . sumOf ( selector : ( T ) -> java . math . BigDecimal ) : java . math . BigDecimal

{ <EOL> var sum : java . math . BigDecimal = <NUM_LIT:0> . toBigDecimal ( ) <EOL> for ( element in this ) { <EOL> sum += selector ( element ) <EOL> } <EOL> return sum <EOL> }

/**
 * Returns the sum of all values produced by [selector] function applied to each element in the sequence.
 *
 * The operation is _terminal_.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ OptIn ( kotlin . experimental . ExperimentalTypeInference :: class ) <EOL> @ OverloadResolutionByLambdaReturnType <EOL> @ kotlin . jvm . JvmName ( "<STR_LIT>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun < T > Sequence < T > . sumOf ( selector : ( T ) -> java . math . BigInteger ) : java . math . BigInteger

{ <EOL> var sum : java . math . BigInteger = <NUM_LIT:0> . toBigInteger ( ) <EOL> for ( element in this ) { <EOL> sum += selector ( element ) <EOL> } <EOL> return sum <EOL> }


{ <EOL> }


private fun resolveSupertypesTree ( values : List < Supertypes > ) : List < SupertypesTree >

{ <EOL> return values . mapIndexed { index : Int , supertypes : Supertypes -> <EOL> val classifierIndex = classifiers . classifierIndices [ index ] <EOL> val resolver = SimpleCirSupertypesResolver ( classifiers . classifierIndices [ index ] , classifiers . commonDependencies ) <EOL> val nodes = supertypes . filterIsInstance < CirClassType > ( ) . map { type -> createTypeNode ( classifierIndex , resolver , type ) } <EOL> SupertypesTree ( nodes ) <EOL> } <EOL> }

/**
 * For every supertype listed in [values] a full [SupertypesTree] will be resolved.
 * This tree represents the supertype-hierarchy:
 *
 * ```
 * interface A
 * interface B: A
 * interface C: B, A
 * ```
 *
 * will become a tree like
 * ```
 * C
 * |\
 * | \
 * B A
 * |
 * A
 *
 * ```
 *
 */


private fun buildSupertypesGroups ( trees : List < SupertypesTree > ) : List < SupertypesGroup >

{ <EOL> val groups = mutableListOf < SupertypesGroup > ( ) <EOL> var allowClassTypes = true <EOL> trees . flatMap { tree -> tree . allNodes } . forEach { node -> <EOL> if ( node . isConsumed ) return@forEach <EOL> val candidateGroup = buildTypeGroup ( trees , node . type . classifierId ) ? : return@forEach <EOL> if ( containsAnyClassKind ( candidateGroup ) ) { <EOL> if ( ! allowClassTypes ) return@forEach <EOL> allowClassTypes = false <EOL> } <EOL> assignGroupToNodes ( candidateGroup ) <EOL> groups . add ( candidateGroup ) <EOL> } <EOL> return groups <EOL> }

/**
 * Builds [SupertypesGroup] (a group representing one type for every platform) that will be enqueued for type commonization.
 * To find out which types shall be grouped this implementation will go through every single node in all trees (BFS!)
 * If a certain type can be found on all other platforms, then a group is build.
 * This types and all transitively "covered" supertypes will be marked as 'consumed' and therefore will be 'effectively removed'
 * from the tree.
 *
 * This grouping implementation will also be very careful about *not* grouping two groups that could effectively
 * represent a 'ClassKind' (to avoid commonizing with two abstract class supertypes)
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public fun < C > ColumnSet < C ? > . withoutNulls ( ) : ColumnSet < C & Any >

= <EOL> transform { cols -> cols . filter { ! it . hasNulls ( ) } } as ColumnSet < C & Any >

/**
 * @include [CommonWithoutNullsDocs]
 * @set [CommonWithoutNullsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[cols][ColumnsSelectionDsl.cols]` { .. }.`[withoutNulls][ColumnSet.withoutNulls]`() }`
 */


public fun ColumnsSelectionDsl < * > . withoutNulls ( ) : ColumnSet < Any >

= <EOL> asSingleColumn ( ) . colsWithoutNulls ( )

/**
 * @include [CommonWithoutNullsDocs]
 * @set [CommonWithoutNullsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[withoutNulls][ColumnsSelectionDsl.colsWithoutNulls]`() }`
 */


public fun SingleColumn < DataRow < * > > . colsWithoutNulls ( ) : ColumnSet < Any >

= <EOL> ensureIsColumnGroup ( ) . allColumnsInternal ( ) . withoutNulls ( )

/**
 * @include [CommonWithoutNullsDocs]
 * @set [CommonWithoutNullsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { myColumnGroup.`[colsWithoutNulls][SingleColumn.colsWithoutNulls]`() }`
 */


public fun String . colsWithoutNulls ( ) : ColumnSet < Any >

= <EOL> columnGroup ( this ) . colsWithoutNulls ( )

/**
 * @include [CommonWithoutNullsDocs]
 * @set [CommonWithoutNullsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "myColumnGroup".`[colsWithoutNulls][String.colsWithoutNulls]`() }`
 */


public fun KProperty < * > . colsWithoutNulls ( ) : ColumnSet < Any >

/**
 * @include [CommonWithoutNullsDocs]
 * @set [CommonWithoutNullsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::myColumnGroup.`[colsWithoutNulls][KProperty.colsWithoutNulls]`() }`
 */


public fun ColumnPath . colsWithoutNulls ( ) : ColumnSet < Any >

/**
 * @include [CommonWithoutNullsDocs]
 * @set [CommonWithoutNullsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "pathTo"["myColGroup"].`[colsWithoutNulls][ColumnPath.colsWithoutNulls]`() }`
 */


override fun fullyExpandedType ( type : KtType ) : KtType

= type


fun testDaemonExecutionViaIntermediateProcess ( )

{ <EOL> val clientAliveFile = FileUtil . createTempFile ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> val daemonOptions = makeTestDaemonOptions ( getTestName ( true ) ) <EOL> val jar = testTempDir . absolutePath + File . separator + "<STR_LIT>" <EOL> val args = listOf ( File ( File ( System . getProperty ( "<STR_LIT>" ) , "<STR_LIT>" ) , "<STR_LIT:java>" ) . absolutePath , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , daemonClientClassPath . joinToString ( File . pathSeparator ) { it . absolutePath } , KotlinCompilerClient :: class . qualifiedName ! ! ) + <EOL> daemonOptions . mappers . flatMap { it . toArgs ( COMPILE_DAEMON_CMDLINE_OPTIONS_PREFIX ) } + <EOL> compilerId . mappers . flatMap { it . toArgs ( COMPILE_DAEMON_CMDLINE_OPTIONS_PREFIX ) } + <EOL> File ( getHelloAppBaseDir ( ) , "<STR_LIT>" ) . absolutePath + <EOL> "<STR_LIT:-d>" + jar <EOL> try { <EOL> var resOutput : String ? = null <EOL> var resCode : Int ? = null <EOL> val runnerProcess = ProcessBuilder ( args ) . redirectErrorStream ( true ) . start ( ) <EOL> thread { <EOL> resOutput = runnerProcess . inputStream . reader ( ) . readText ( ) <EOL> } <EOL> val waitThread = thread { <EOL> resCode = runnerProcess . waitFor ( ) <EOL> } <EOL> waitThread . join ( TIMEOUT_DAEMON_RUNNER_EXIT_MS ) <EOL> assertFalse ( "<STR_LIT>" , waitThread . isAlive ) <EOL> assertEquals ( "<STR_LIT>" , <NUM_LIT:0> , resCode ) <EOL> } <EOL> finally { <EOL> if ( clientAliveFile . exists ( ) ) <EOL> clientAliveFile . delete ( ) <EOL> } <EOL> }

/** Testing that running daemon in the child process doesn't block on s child process.waitFor()
 * that may happen on windows if simple processBuilder.start is used due to handles inheritance:
 * - process A starts process B using ProcessBuilder and waits for it using process.waitFor()
 * - process B starts daemon and exits
 * - due to default behavior of CreateProcess on windows, the handles of process B are inherited by the daemon
 * (in particular handles of stdin/out/err) and therefore these handles remain open while daemon is running
 * - (seems) due to the way how waiting for process is implemented, waitFor() hangs until daemon is killed
 * This seems a known problem, e.g. gradle uses a library with native code that prevents io handles inheritance when launching it's daemon
 * (the same solution is used in kotlin daemon client - see next commit)
 */


{ <EOL> data . shuffle ( ) <EOL> val dataset = OnHeapDataset . create ( extractX ( ) , extractY ( ) ) <EOL> val ( train , test ) = dataset . split ( <NUM_LIT> ) <EOL> model . use { <EOL> it . compile ( optimizer = SGD ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> it . fit ( dataset = train , epochs = EPOCHS , batchSize = TRAINING_BATCH_SIZE ) <EOL> val accuracy = model . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example shows how to do classification from scratch, starting from static Iris dataset, using simple Dense-based [model].
 *
 * It includes:
 * - dataset creation
 * - dataset splitting
 * - model compilation
 * - model training
 * - model evaluation
 */


= irisClassification ( )


override fun dispatch ( context : CoroutineContext , block : Runnable ) : Unit

= SwingUtilities . invokeLater ( block )


override fun scheduleResumeAfterDelay ( timeMillis : Long , continuation : CancellableContinuation < Unit > )

{ <EOL> val timer = schedule ( timeMillis ) { <EOL> with ( continuation ) { resumeUndispatched ( Unit ) } <EOL> } <EOL> continuation . invokeOnCancellation { timer . stop ( ) } <EOL> }


override fun invokeOnTimeout ( timeMillis : Long , block : Runnable , context : CoroutineContext ) : DisposableHandle

{ <EOL> val timer = schedule ( timeMillis ) { <EOL> block . run ( ) <EOL> } <EOL> return DisposableHandle { timer . stop ( ) } <EOL> }


private fun isCastToAForwardDeclaration ( forwardDeclarationType : KotlinType ) : Boolean

{ <EOL> val forwardDeclarationClassDescriptor = forwardDeclarationType . constructor . declarationDescriptor <EOL> if ( forwardDeclarationClassDescriptor !is ClassDescriptor ) return false <EOL> return forwardDeclarationClassDescriptor . getForwardDeclarationKindOrNull ( ) != null <EOL> }

/**
 * Here, we only check that we are casting to a forward declaration to suppress a CAST_NEVER_SUCCEEDS warning. The cast is further
 * checked in NativeForwardDeclarationRttiChecker.
 */


internal fun encodeDuration ( value : Duration ) : String

= value . toComponents { seconds , nanoseconds -> <EOL> when { <EOL> nanoseconds == <NUM_LIT:0> -> { <EOL> if ( seconds % <NUM_LIT> == <NUM_LIT:0L> ) { <EOL> if ( seconds % <NUM_LIT> == <NUM_LIT:0L> ) { <EOL> if ( seconds % <NUM_LIT> == <NUM_LIT:0L> ) { <EOL> "<STR_LIT>" <EOL> } else { <EOL> "<STR_LIT>" <EOL> } <EOL> } else { <EOL> "<STR_LIT>" <EOL> } <EOL> } else { <EOL> "<STR_LIT>" <EOL> } <EOL> } <EOL> nanoseconds % <NUM_LIT> == <NUM_LIT:0> -> "<STR_LIT>" <EOL> nanoseconds % <NUM_LIT> == <NUM_LIT:0> -> "<STR_LIT>" <EOL> else -> "<STR_LIT>" <EOL> } <EOL> }

/**
 * Encode [Duration] objects using time unit short names: d, h, m, s, ms, us, ns.
 * Example:
 * 120.seconds -> 2 m;
 * 121.seconds -> 121 s;
 * 120.minutes -> 2 h;
 * 122.minutes -> 122 m;
 * 24.hours -> 1 d.
 * Encoding uses the largest time unit.
 * All restrictions on the maximum and minimum duration are specified in [Duration].
 * @return encoded value
 */


@ SuppressAnimalSniffer <EOL> internal fun Config . decodeJavaDuration ( path : String ) : JDuration

= try { <EOL> getDuration ( path ) <EOL> } catch ( e : ConfigException ) { <EOL> throw SerializationException ( "<STR_LIT>" , e ) <EOL> }

/**
 * Decode [JDuration] from [Config].
 * See https://github.com/lightbend/config/blob/main/HOCON.md#duration-format
 *
 * @param path in config
 */


fun getArchiveTaskOrNull ( kotlinCompilation : KotlinCompilation < * > ) : TaskProvider < out AbstractArchiveTask > ?

/**
 * Returns archive task associated with [kotlinCompilation] instance.
 *
 * This method searches via Identity class (Project path, target and compilation names) of Compilations not by reference.
 * So it is safe to pass decorated or wrapped instances.
 */


private fun Iterable < Pair < String , String > > . aligned ( ) : List < String >

{ <EOL> val maxPrefixLength = maxOf { it . first . length } <EOL> return map { ( prefix , suffix ) -> prefix . padEnd ( maxPrefixLength ) + suffix } <EOL> }

/**
 * For each pair in the list, pads its first element with a number of spaces and concatenates it with the second element in such a way
 * that the second elements of each pair are vertically aligned in concatenated strings.
 *
 * In other words, transforms this list:
 *
 * ```kotlin
 * listOf(
 * Pair("Capacity: ", "normal"),
 * Pair("Usability: ", "very good"),
 * Pair("Magic: ", "minimal"),
 * )
 * ```
 *
 * to this:
 *
 * ```kotlin
 * listOf(
 * "Capacity: normal",
 * "Usability: very good",
 * "Magic: minimal",
 * )
 * ```
 */


private fun parseSingleCheckBlock ( trimmedCheckLine : String , lineIterator : Iterator < String > ) : Pair < String ? , CheckBlock >

{ <EOL> assert ( trimmedCheckLine . startsWith ( CHECK_MARKER ) ) <EOL> val colonIndex = trimmedCheckLine . indexOf ( '<CHAR_LIT::>' ) <EOL> if ( colonIndex < <NUM_LIT:0> ) { <EOL> error ( "<STR_LIT>" ) <EOL> } <EOL> val backends = trimmedCheckLine <EOL> . substring ( CHECK_MARKER . length , colonIndex ) <EOL> . splitToSequence ( whitespaceRegex ) <EOL> . filter { it . isNotEmpty ( ) } <EOL> . map { enumValueOf < TargetBackend > ( it ) } <EOL> . toList ( ) <EOL> val expectations = mutableListOf < String > ( ) <EOL> for ( line in lineIterator ) { <EOL> val trimmed = line . trim ( ) <EOL> if ( trimmed . startsWith ( CHECK_MARKER ) ) { <EOL> return trimmed to CheckBlock ( backends , expectations ) <EOL> } <EOL> if ( trimmed . startsWith ( "<STR_LIT>" ) ) { <EOL> expectations . add ( trimmed ) <EOL> } else { <EOL> break <EOL> } <EOL> } <EOL> return null to CheckBlock ( backends , expectations ) <EOL> }

/**
 * Parses a single check block.
 *
 * The valid `// CHECK` block is multiline string that starts with the `// CHECK` comment optionally followed by a whitespace-separated list
 * of [TargetBackend] names, and ending with a colon. After that, an arbitrary number of single-line comments may follow. The `// CHECK` block
 * ends with the first non-comment line.
 *
 * For example, this text
 * ```kotlin
 * // CHECK JS_IR NATIVE:
 * // Mangled name: #test(){}
 * // Public signature: /test|6620506149988718649[0]
 * // Public signature debug description: test(){}
 * fun test(): Int
 * ```
 * will be parsed into:
 * ```kotlin
 * CheckBlock(
 * backends = listOf(TargetBackend.JS_IR, TargetBackend.NATIVE),
 * expectations = listOf(
 * "// Mangled name: #test(){}",
 * "// Public signature: /test|6620506149988718649[0]",
 * "// Public signature debug description: test(){}",
 * )
 * )
 * ```
 *
 * @param trimmedCheckLine The line that starts with `// CHECK <BACKEND>*:`
 * @param lineIterator The iterator over lines in the expectation file.
 * @return The line representing the beginning of the next `// CHECK` block (if there is one), and the parsed `// CHECK` block.
 */


internal fun isCaseMissedByK1Intersector ( a : TypeInfo , b : TypeInfo )

= <EOL> a . canHaveSubtypesAccordingToK1 && b . canHaveSubtypesAccordingToK1

/**
 * Unfortunately, intersections in K1 are not
 * smart enough: K1 doesn't say that the
 * intersection is empty if all the input
 * types "can have subtypes". For example,
 * K1 thinks that type parameters always
 * allow subtypes, so it won't report
 * empty intersections for them regardless
 * the bounds.
 *
 * See: [org.jetbrains.kotlin.types.TypeIntersector.intersectTypes]
 */


internal fun isCaseMissedByAdditionalK1IncompatibleEnumsCheck ( a : ConeKotlinType , b : ConeKotlinType , session : FirSession ) : Boolean

{ <EOL> return when { <EOL> ! a . isEnum ( session ) && ! b . isEnum ( session ) -> true <EOL> a . isNullable && b . isNullable -> true <EOL> a . isNothingOrNullableNothing || b . isNothingOrNullableNothing -> true <EOL> else -> ! a . isClass ( session ) || ! b . isClass ( session ) <EOL> } <EOL> }

/**
 * This function simply replicates `if` with
 * early returns from the corresponding function
 * in K1.
 *
 * See: [org.jetbrains.kotlin.types.isIncompatibleEnums]
 */


public fun decodeJsonElement ( ) : JsonElement

/**
 * Decodes the next element in the current input as [JsonElement].
 * The type of the decoded element depends on the current state of the input and, when received
 * by [serializer][KSerializer] in its [KSerializer.serialize] method, the type of the token directly matches
 * the [kind][SerialDescriptor.kind].
 *
 * This method is allowed to invoke only as the part of the whole deserialization process of the class,
 * calling this method after invoking [beginStructure] or any `decode*` method will lead to unspecified behaviour.
 * For example:
 * ```
 * class Holder(val value: Int, val list: List<Int>())
 *
 * // Holder deserialize method
 * fun deserialize(decoder: Decoder): Holder {
 * // Completely okay, the whole Holder object is read
 * val jsonObject = (decoder as JsonDecoder).decodeJsonElement()
 * // ...
 * }
 *
 * // Incorrect Holder deserialize method
 * fun deserialize(decoder: Decoder): Holder {
 * // decode "value" key unconditionally
 * decoder.decodeElementIndex(descriptor)
 * val value = decode.decodeInt()
 * // Incorrect, decoder is already in an intermediate state after decodeInt
 * val json = (decoder as JsonDecoder).decodeJsonElement()
 * // ...
 * }
 * ```
 */


private fun ContentPage . displayableName ( ) : String

= <EOL> if ( this is WithDocumentables && documentables . all { it is DFunction } ) { <EOL> "<STR_LIT>" <EOL> } else { <EOL> name <EOL> }

/**
 * Parenthesis is applied in 1 case:
 * - page only contains functions (therefore documentable from this page is [DFunction])
 */


fun buildSession ( environment : OrtEnvironment , options : SessionOptions ) : OrtSession

/**
 * Method for building an [OrtSession] from the model source.
 */


public override fun initializeWith ( vararg executionProviders : ExecutionProvider )

{ <EOL> val uniqueProviders = collectProviders ( executionProviders ) <EOL> if ( :: executionProvidersInUse . isInitialized && uniqueProviders == executionProvidersInUse ) { <EOL> return <EOL> } <EOL> if ( :: session . isInitialized ) { <EOL> session . close ( ) <EOL> } <EOL> session = modelSource . buildSession ( env , buildSessionOptions ( uniqueProviders ) ) <EOL> executionProvidersInUse = uniqueProviders <EOL> inputInfo = session . inputInfo <EOL> outputInfo = session . outputInfo <EOL> }

/**
 * Initializes the model, if it's not initialized, or re-initializes it, depending on the execution providers.
 *
 * By default, the model is initialized with CPU execution provider with BFCArena memory allocator.
 * This method allows to set the execution provider to use.
 * If the model is already initialized, internal session will be closed and new one will be created.
 * If [executionProvidersInUse] is the same as the one passed, nothing will happen.
 * If execution provider is not supported, an exception will be thrown.
 * If empty list is passed, the model will be initialized with CPU execution provider.
 *
 * @param executionProviders list of execution providers to use.
 */


public fun predictRaw ( inputData : FloatData ) : Map < String , Any >

{ <EOL> return predict ( inputData ) { it . getValues ( ) } <EOL> }

/**
 * Returns list of multidimensional arrays with data from model outputs.
 *
 * NOTE: This operation can be quite slow for high dimensional tensors,
 * use [predict] with custom output processing for better performance.
 */


public override fun < R > predict ( inputData : FloatData , extractResult : ( OrtSession . Result ) -> R ) : R

{ <EOL> return predict ( mapOf ( inputInfo . getName ( <NUM_LIT:0> ) to inputData ) , extractResult ) <EOL> }

/**
 * Runs prediction on a given [inputData] and calls [extractResult] function to process output.
 * For models with multiple inputs, [inputData] is passed as a first input.
 * @see OrtSessionResultConverter
 */


public fun < R > predict ( inputs : Map < String , FloatData > , extractResult : ( OrtSession . Result ) -> R ) : R

{ <EOL> return predict ( inputs , outputInfo . keys . toList ( ) , extractResult ) <EOL> }

/**
 * Runs prediction on a given [inputs] and calls [extractResult] function to process output.
 * @see OrtSessionResultConverter
 */


{ <EOL> if ( :: session . isInitialized ) { <EOL> session . close ( ) <EOL> } <EOL> env . close ( ) <EOL> }

/** Releases the ONNXRuntime - related resources. */


public fun load ( pathToModel : String , vararg executionProviders : ExecutionProvider = arrayOf ( CPU ( true ) ) ) : OnnxInferenceModel

{ <EOL> val model = OnnxInferenceModel ( pathToModel ) <EOL> model . initializeWith ( * executionProviders ) <EOL> return model <EOL> }

/**
 * Loads model from serialized ONNX file.
 */


public fun load ( modelBytes : ByteArray , vararg executionProviders : ExecutionProvider = arrayOf ( CPU ( true ) ) ) : OnnxInferenceModel

{ <EOL> val model = OnnxInferenceModel ( modelBytes ) <EOL> model . initializeWith ( * executionProviders ) <EOL> return model <EOL> }

/**
 * Loads model from a byte array representing an ONNX model.
 */


public fun captureOutput ( name : String , stdoutEnabled : Boolean = STDOUT_ENABLED_DEFAULT , main : ( out : PrintStream ) -> Unit ) : List < String >

{ <EOL> val oldOut = System . out <EOL> val oldErr = System . err <EOL> val logOut = if ( stdoutEnabled ) oldOut else NullOut <EOL> val bytesOut = ByteArrayOutputStream ( ) <EOL> val tee = TeeOutput ( bytesOut , logOut ) <EOL> val ps = PrintStream ( tee ) <EOL> logOut . println ( "<STR_LIT>" ) <EOL> System . setErr ( ps ) <EOL> System . setOut ( ps ) <EOL> val bytes : ByteArray <EOL> try { <EOL> try { <EOL> main ( logOut ) <EOL> } catch ( e : Throwable ) { <EOL> System . err . print ( "<STR_LIT>" ) <EOL> e . printStackTrace ( ) <EOL> } <EOL> bytes = bytesOut . toByteArray ( ) <EOL> if ( tee . flushLine ( ) ) logOut . println ( ) <EOL> logOut . println ( "<STR_LIT>" ) <EOL> } finally { <EOL> System . setOut ( oldOut ) <EOL> System . setErr ( oldErr ) <EOL> } <EOL> return ByteArrayInputStream ( bytes ) . bufferedReader ( ) . readLines ( ) <EOL> }

/**
 * Captures stdout and stderr of the specified block of code.
 *
 * The [name] is used to display which test is being run.
 * When [stdoutEnabled] is true, then everything is displayed to stdout when then code runs, too.
 */


public fun List < String > . verifyOutputLines ( vararg expected : String )

{ <EOL> val expectedLines = expected . toList ( ) <EOL> if ( this != expectedLines ) { <EOL> val diff = computeLinesDiff ( expectedLines , this ) <EOL> throw Exception ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Verifies that this lines captured by [captureOutput] are the same as [expected] one
 * and throws exception with the difference if not.
 */


public fun List < String > . verifyOutputLinesStart ( vararg expected : String )

{ <EOL> val expectedLines = expected . toList ( ) <EOL> val prefix = subList ( <NUM_LIT:0> , minOf ( size , expected . size ) ) <EOL> if ( prefix != expectedLines ) { <EOL> val diff = computeLinesDiff ( expectedLines , this ) <EOL> throw Exception ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Verifies that this lines captured by [captureOutput] start with the same list as [expected] one
 * and throws exception if not. Additional lines in the output are ignored. This is useful for
 * testing that the exception with the appropriate message was thrown
 */


fun FirSession . doUnify ( originalTypeProjection : ConeTypeProjection , typeWithParametersProjection : ConeTypeProjection , targetTypeParameters : Set < FirTypeParameterSymbol > , result : MutableMap < FirTypeParameterSymbol , ConeTypeProjection > , ) : Boolean

{ <EOL> val originalType = originalTypeProjection . type ? . lowerBoundIfFlexible ( ) ? . fullyExpandedType ( this ) <EOL> val typeWithParameters = typeWithParametersProjection . type ? . lowerBoundIfFlexible ( ) ? . fullyExpandedType ( this ) <EOL> if ( typeWithParameters is ConeErrorType ) { <EOL> return true <EOL> } <EOL> if ( originalType is ConeIntersectionType ) { <EOL> val intersectionResult = mutableMapOf < FirTypeParameterSymbol , ConeTypeProjection > ( ) <EOL> for ( intersectedType in originalType . intersectedTypes ) { <EOL> val localResult = mutableMapOf < FirTypeParameterSymbol , ConeTypeProjection > ( ) <EOL> if ( ! doUnify ( intersectedType , typeWithParametersProjection , targetTypeParameters , localResult ) ) return false <EOL> for ( ( typeParameter , typeProjection ) in localResult ) { <EOL> val existingTypeProjection = intersectionResult [ typeParameter ] <EOL> if ( existingTypeProjection == null || ( typeProjection is KotlinTypeMarker && existingTypeProjection is KotlinTypeMarker && AbstractTypeChecker . isSubtypeOf ( typeContext , typeProjection , existingTypeProjection ) ) ) { <EOL> intersectionResult [ typeParameter ] = typeProjection <EOL> } <EOL> } <EOL> } <EOL> for ( ( key , value ) in intersectionResult ) { <EOL> result [ key ] = value <EOL> } <EOL> return true <EOL> } <EOL> if ( originalTypeProjection . kind == typeWithParametersProjection . kind && originalTypeProjection . kind != ProjectionKind . INVARIANT && originalTypeProjection . kind != ProjectionKind . STAR ) { <EOL> return doUnify ( originalType ! ! , typeWithParameters ! ! , targetTypeParameters , result ) <EOL> } <EOL> if ( originalType ? . nullability == ConeNullability . NULLABLE && typeWithParameters ? . nullability == ConeNullability . NULLABLE ) { <EOL> return doUnify ( originalTypeProjection . removeQuestionMark ( typeContext ) , typeWithParametersProjection . removeQuestionMark ( typeContext ) , targetTypeParameters , result , ) <EOL> } <EOL> if ( originalTypeProjection . kind != typeWithParametersProjection . kind && typeWithParametersProjection . kind != ProjectionKind . INVARIANT ) { <EOL> return true <EOL> } <EOL> if ( typeWithParameters is ConeDefinitelyNotNullType ) { <EOL> return doUnify ( originalTypeProjection , typeWithParametersProjection . replaceType ( typeWithParameters . original ) , targetTypeParameters , result , ) <EOL> } <EOL> if ( originalTypeProjection !is ConeStarProjection && originalType ? . nullability != ConeNullability . NULLABLE && typeWithParameters ? . nullability == ConeNullability . NULLABLE ) { <EOL> return true <EOL> } <EOL> val typeParameter = ( typeWithParameters as? ConeTypeParameterType ) ? . lookupTag ? . typeParameterSymbol <EOL> if ( typeParameter != null && typeParameter in targetTypeParameters ) { <EOL> if ( typeParameter in result && result [ typeParameter ] != originalTypeProjection ) return false <EOL> result [ typeParameter ] = originalTypeProjection <EOL> return true <EOL> } <EOL> if ( originalType ? . nullability ? . isNullable != typeWithParameters ? . nullability ? . isNullable ) return true <EOL> if ( originalTypeProjection . kind != typeWithParametersProjection . kind ) return true <EOL> if ( ( originalType as? ConeLookupTagBasedType ) ? . lookupTag != ( typeWithParameters as? ConeLookupTagBasedType ) ? . lookupTag ) return true <EOL> if ( originalType == null || typeWithParameters == null ) return true <EOL> if ( originalType . typeArguments . size != typeWithParameters . typeArguments . size ) { <EOL> return true <EOL> } <EOL> if ( originalType . typeArguments . isEmpty ( ) ) { <EOL> return true <EOL> } <EOL> for ( ( originalTypeArgument , typeWithParametersArgument ) in originalType . typeArguments . zip ( typeWithParameters . typeArguments ) ) { <EOL> if ( ! doUnify ( originalTypeArgument , typeWithParametersArgument , targetTypeParameters , result ) ) return false <EOL> } <EOL> return true <EOL> }

/**
 * @return false does only mean that there were conflicted values for some type parameter. In all other cases, it returns true.
 * "fail" result in the comments below means that we can't infer anything meaningful in that branch of unification.
 * See more at org.jetbrains.kotlin.types.TypeUnifier.doUnify.
 * NB: "Failed@ result of UnificationResultImpl is effectively unused in production.
 */


public fun serializer ( type : Type ) : KSerializer < Any >

= EmptySerializersModule ( ) . serializer ( type )

/**
 * Reflectively retrieves a serializer for the given [type].
 *
 * This overload is intended to be used as an interoperability layer for JVM-centric libraries,
 * that operate with Java's type tokens and cannot use Kotlin's [KType] or [typeOf].
 * For application-level serialization, it is recommended to use `serializer<T>()` or `serializer(KType)` instead as it is aware of
 * Kotlin-specific type information, such as nullability, sealed classes and object singletons.
 *
 * Note that because [Type] does not contain any information about nullability, all created serializers
 * work only with non-nullable data.
 *
 * Not all [Type] implementations are supported.
 * [type] must be an instance of [Class], [GenericArrayType], [ParameterizedType] or [WildcardType].
 *
 * @throws SerializationException if serializer cannot be created (provided [type] or its type argument is not serializable).
 * @throws IllegalArgumentException if an unsupported subclass of [Type] is provided.
 */


public fun serializerOrNull ( type : Type ) : KSerializer < Any > ?

= EmptySerializersModule ( ) . serializerOrNull ( type )

/**
 * Reflectively retrieves a serializer for the given [type].
 *
 * This overload is intended to be used as an interoperability layer for JVM-centric libraries,
 * that operate with Java's type tokens and cannot use Kotlin's [KType] or [typeOf].
 * For application-level serialization, it is recommended to use `serializer<T>()` or `serializer(KType)` instead as it is aware of
 * Kotlin-specific type information, such as nullability, sealed classes and object singletons.
 *
 * Note that because [Type] does not contain any information about nullability, all created serializers
 * work only with non-nullable data.
 *
 * Not all [Type] implementations are supported.
 * [type] must be an instance of [Class], [GenericArrayType], [ParameterizedType] or [WildcardType].
 *
 * @return [KSerializer] for given [type] or `null` if serializer cannot be created (given [type] or its type argument is not serializable).
 * @throws IllegalArgumentException if an unsupported subclass of [Type] is provided.
 */


public fun SerializersModule . serializer ( type : Type ) : KSerializer < Any >

= <EOL> serializerByJavaTypeImpl ( type , failOnMissingTypeArgSerializer = true ) <EOL> ? : type . prettyClass ( ) . serializerNotRegistered ( )

/**
 * Retrieves a serializer for the given [type] using
 * reflective construction and [contextual][SerializersModule.getContextual] lookup as a fallback for non-serializable types.
 *
 * This overload is intended to be used as an interoperability layer for JVM-centric libraries,
 * that operate with Java's type tokens and cannot use Kotlin's [KType] or [typeOf].
 * For application-level serialization, it is recommended to use `serializer<T>()` or `serializer(KType)` instead as it is aware of
 * Kotlin-specific type information, such as nullability, sealed classes and object singletons.
 *
 * Note that because [Type] does not contain any information about nullability, all created serializers
 * work only with non-nullable data.
 *
 * Not all [Type] implementations are supported.
 * [type] must be an instance of [Class], [GenericArrayType], [ParameterizedType] or [WildcardType].
 *
 * @throws SerializationException if serializer cannot be created (provided [type] or its type argument is not serializable).
 * @throws IllegalArgumentException if an unsupported subclass of [Type] is provided.
 */


public fun SerializersModule . serializerOrNull ( type : Type ) : KSerializer < Any > ?

= <EOL> serializerByJavaTypeImpl ( type , failOnMissingTypeArgSerializer = false )

/**
 * Retrieves a serializer for the given [type] using
 * reflective construction and [contextual][SerializersModule.getContextual] lookup as a fallback for non-serializable types.
 *
 * This overload is intended to be used as an interoperability layer for JVM-centric libraries,
 * that operate with Java's type tokens and cannot use Kotlin's [KType] or [typeOf].
 * For application-level serialization, it is recommended to use `serializer<T>()` or `serializer(KType)` instead as it is aware of
 * Kotlin-specific type information, such as nullability, sealed classes and object singletons.
 *
 * Note that because [Type] does not contain any information about nullability, all created serializers
 * work only with non-nullable data.
 *
 * Not all [Type] implementations are supported.
 * [type] must be an instance of [Class], [GenericArrayType], [ParameterizedType] or [WildcardType].
 *
 * @return [KSerializer] for given [type] or `null` if serializer cannot be created (given [type] or its type argument is not serializable).
 * @throws IllegalArgumentException if an unsupported subclass of [Type] is provided.
 */


@ ExperimentalCoroutinesApi <EOL> public fun Dispatchers . setMain ( dispatcher : CoroutineDispatcher )

{ <EOL> require ( dispatcher !is TestMainDispatcher ) { "<STR_LIT>" } <EOL> getTestMainDispatcher ( ) . setDispatcher ( dispatcher ) <EOL> }

/**
 * Sets the given [dispatcher] as an underlying dispatcher of [Dispatchers.Main].
 * All subsequent usages of [Dispatchers.Main] will use the given [dispatcher] under the hood.
 *
 * Using [TestDispatcher] as an argument has special behavior: subsequently-called [runTest], as well as
 * [TestScope] and test dispatcher constructors, will use the [TestCoroutineScheduler] of the provided dispatcher.
 *
 * It is unsafe to call this method if alive coroutines launched in [Dispatchers.Main] exist.
 */


@ ExperimentalCoroutinesApi <EOL> public fun Dispatchers . resetMain ( )

{ <EOL> getTestMainDispatcher ( ) . resetDispatcher ( ) <EOL> }

/**
 * Resets state of the [Dispatchers.Main] to the original main dispatcher.
 *
 * For example, in Android, the Main thread dispatcher will be set as [Dispatchers.Main].
 * This method undoes a dependency injection performed for tests, and so should be used in tear down (`@After`) methods.
 *
 * It is unsafe to call this method if alive coroutines launched in [Dispatchers.Main] exist.
 */


{ <EOL> assert ( Files . exists ( file ) ) { <EOL> "<STR_LIT>" <EOL> } <EOL> assert ( Files . isRegularFile ( file ) ) { <EOL> "<STR_LIT>" <EOL> } <EOL> }

/**
 * Asserts file under [file] path exists and is a regular file.
 */


fun GradleProject . assertFileInProjectExists ( pathToFile : String , )

{ <EOL> assertFileExists ( projectPath . resolve ( pathToFile ) ) <EOL> }

/**
 * Asserts file under [pathToFile] relative to the test project exists and is a regular file.
 */


fun GradleProject . assertFileInProjectNotExists ( pathToFile : String , )

{ <EOL> assertFileNotExists ( projectPath . resolve ( pathToFile ) ) <EOL> }

/**
 * Asserts file under [pathToFile] relative to the test project does not exist.
 */


fun assertSymlinkExists ( path : Path , )

{ <EOL> assert ( Files . exists ( path ) ) { <EOL> "<STR_LIT>" <EOL> } <EOL> assert ( Files . isSymbolicLink ( path ) ) { <EOL> "<STR_LIT>" <EOL> } <EOL> }

/**
 * Asserts symlink under [path] exists and is a symlink
 */


fun TestProject . assertSymlinkInProjectExists ( pathToFile : String , )

{ <EOL> assertSymlinkExists ( projectPath . resolve ( pathToFile ) ) <EOL> }

/**
 * Asserts symlink under [pathToFile] relative to the test project exists and is a symlink.
 */


fun GradleProject . assertDirectoryInProjectExists ( pathToDir : String , )

= assertDirectoryExists ( projectPath . resolve ( pathToDir ) )

/**
 * Asserts directory under [pathToDir] relative to the test project exists and is a directory.
 */


fun assertDirectoryExists ( dirPath : Path , message : String ? = null , )

= assertDirectoriesExist ( dirPath , message = message )

/**
 * Asserts directory under [dirPath] exists and is a directory.
 */


fun GradleProject . assertFileInProjectContains ( pathToFile : String , vararg expectedText : String , )

{ <EOL> assertFileContains ( projectPath . resolve ( pathToFile ) , * expectedText ) <EOL> }

/**
 * Asserts file under [pathToFile] relative to the test project exists and contains all the lines from [expectedText]
 */


fun GradleProject . assertFileInProjectDoesNotContain ( pathToFile : String , vararg unexpectedText : String , )

{ <EOL> assertFileDoesNotContain ( projectPath . resolve ( pathToFile ) , * unexpectedText ) <EOL> }

/**
 * Asserts file under [pathToFile] relative to the test project exists and does not contain any line from [unexpectedText]
 */


fun assertFileContains ( file : Path , vararg expectedText : String , ) : String

{ <EOL> return assertFilesCombinedContains ( listOf ( file ) , * expectedText ) <EOL> }

/**
 * Asserts file under [file] exists and contains all the lines from [expectedText]
 *
 * @return the content of the [file]
 */


fun assertFilesCombinedContains ( files : List < Path > , vararg expectedText : String , ) : String

{ <EOL> files . forEach { assertFileExists ( it ) } <EOL> val text = files . joinToString ( separator = "<STR_LIT:\n>" ) { <EOL> it . readText ( ) <EOL> } <EOL> val textNotInTheFile = expectedText . filterNot { text . contains ( it ) } <EOL> assert ( textNotInTheFile . isEmpty ( ) ) { <EOL> """<STR_LIT>""" . trimMargin ( ) <EOL> } <EOL> return text <EOL> }

/**
 * Asserts files together contains all the lines from [expectedText]
 */


fun assertFileDoesNotContain ( file : Path , vararg unexpectedText : String , )

{ <EOL> assertFileExists ( file ) <EOL> val text = file . readText ( ) <EOL> val textInTheFile = unexpectedText . filter { text . contains ( it ) } <EOL> assert ( textInTheFile . isEmpty ( ) ) { <EOL> """<STR_LIT>""" . trimMargin ( ) <EOL> } <EOL> }

/**
 * Asserts file under [file] exists and does not contain any line from [unexpectedText]
 */


fun assertFilesContentEquals ( expected : Path , actual : Path )

{ <EOL> assertFileExists ( expected ) <EOL> assertFileExists ( actual ) <EOL> assertContentEquals ( expected . readLines ( ) . asSequence ( ) , actual . readLines ( ) . asSequence ( ) , "<STR_LIT>" ) <EOL> }

/**
 * Asserts that the content of two files is equal.
 * @param expected The path to the expected file.
 * @param actual The path to the actual file.
 * @throws AssertionError if the contents of the two files are not equal.
 */


fun invoke ( phaseConfig : PhaseConfigurationService , phaserState : PhaserState < Input > , context : Context , input : Input ) : Output

/**
 * Executes this compiler phase. It accepts some parameter of type [Input] and transforms it into [Output].
 *
 * @param phaseConfig Controls which parts of the compilation pipeline are enabled and how the compiler should validate their invariants.
 * @param phaserState The global context.
 * @param context The local context in which the compiler stores all the necessary information for the given phase.
 */


fun IdeaModule . excludeGeneratedGradleDsl ( layout : ProjectLayout )

{ <EOL> val generatedSrcDirs = listOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , ) <EOL> excludeDirs . addAll ( layout . projectDirectory . asFile . walk ( ) . filter { it . isDirectory && it . parentFile . name in generatedSrcDirs } . flatMap { file -> <EOL> file . walk ( ) . maxDepth ( <NUM_LIT:1> ) . filter { it . isDirectory } . toList ( ) <EOL> } ) <EOL> }

/** exclude generated Gradle code, so it doesn't clog up search results */


fun Project . initIdeProjectLogo ( svgLogoPath : String )

{ <EOL> val logoSvg = rootProject . layout . projectDirectory . file ( svgLogoPath ) <EOL> val ideaDir = rootProject . layout . projectDirectory . dir ( "<STR_LIT>" ) <EOL> if ( logoSvg . asFile . exists ( ) && ideaDir . asFile . exists ( ) && ! ideaDir . file ( "<STR_LIT>" ) . asFile . exists ( ) && ! ideaDir . file ( "<STR_LIT>" ) . asFile . exists ( ) ) { <EOL> copy { <EOL> from ( logoSvg ) { rename { "<STR_LIT>" } } <EOL> into ( ideaDir ) <EOL> } <EOL> } <EOL> }


fun generatePrimaryConstructorOverloadsIfNeeded ( constructorDescriptor : ConstructorDescriptor , classBuilder : ClassBuilder , memberCodegen : MemberCodegen < * > , contextKind : OwnerKind , classOrObject : KtPureClassOrObject )

{ <EOL> val element = classOrObject . primaryConstructor ? : classOrObject <EOL> if ( ! generateOverloadsIfNeeded ( element , constructorDescriptor , constructorDescriptor , contextKind , classBuilder , memberCodegen ) && isEmptyConstructorNeeded ( constructorDescriptor , classOrObject ) ) { <EOL> generateOverloadWithSubstitutedParameters ( constructorDescriptor , constructorDescriptor , classBuilder , memberCodegen , element , contextKind , constructorDescriptor . countDefaultParameters ( ) ) <EOL> } <EOL> }

/**
 * If all of the parameters of the specified constructor declare default values,
 * generates a no-argument constructor that passes default values for all arguments.
 */


fun generateOverloadsIfNeeded ( methodElement : KtPureElement ? , functionDescriptor : FunctionDescriptor , delegateFunctionDescriptor : FunctionDescriptor , contextKind : OwnerKind , classBuilder : ClassBuilder , memberCodegen : MemberCodegen < * > ) : Boolean

{ <EOL> if ( functionDescriptor . findJvmOverloadsAnnotation ( ) == null ) return false <EOL> for ( i in <NUM_LIT:1> .. functionDescriptor . countDefaultParameters ( ) ) { <EOL> generateOverloadWithSubstitutedParameters ( functionDescriptor , delegateFunctionDescriptor , classBuilder , memberCodegen , methodElement , contextKind , i ) <EOL> } <EOL> return true <EOL> }

/**
 * If the function is annotated with [kotlin.jvm.JvmOverloads], generates Java methods that
 * have the default parameter values substituted. If a method has N parameters and M of which
 * have default values, M overloads are generated: the first one takes N-1 parameters (all but
 * the last one that takes a default value), the second takes N-2 parameters, and so on.
 *
 * @param functionDescriptor the method for which the overloads are generated
 * @param delegateFunctionDescriptor the method descriptor for the implementation that we need to call
 * (same as [functionDescriptor] in all cases except for companion object methods annotated with @JvmStatic,
 * where [functionDescriptor] is the static method in the main class and [delegateFunctionDescriptor] is the
 * implementation in the companion object class)
 * @return true if the overloads annotation was found on the element, false otherwise
 */


private fun generateOverloadWithSubstitutedParameters ( functionDescriptor : FunctionDescriptor , delegateFunctionDescriptor : FunctionDescriptor , classBuilder : ClassBuilder , memberCodegen : MemberCodegen < * > , methodElement : KtPureElement ? , contextKind : OwnerKind , substituteCount : Int )

{ <EOL> val typeMapper = state . typeMapper <EOL> val isStatic = DescriptorAsmUtil . isStaticMethod ( contextKind , functionDescriptor ) <EOL> val baseMethodFlags = DescriptorAsmUtil . getCommonCallableFlags ( functionDescriptor , state ) and Opcodes . ACC_VARARGS . inv ( ) <EOL> val remainingParameters = getRemainingParameters ( functionDescriptor . original , substituteCount ) <EOL> val remainingParametersDeclarations = <EOL> remainingParameters . map { DescriptorToSourceUtils . descriptorToDeclaration ( it ) as? KtParameter } <EOL> val generateAsFinal = <EOL> ( functionDescriptor . modality == Modality . FINAL || state . languageVersionSettings . supportsFeature ( LanguageFeature . GenerateJvmOverloadsAsFinal ) ) && <EOL> ! isJvmInterface ( functionDescriptor . containingDeclaration ) <EOL> val flags = <EOL> baseMethodFlags or <EOL> ( if ( isStatic ) Opcodes . ACC_STATIC else <NUM_LIT:0> ) or <EOL> ( if ( generateAsFinal && functionDescriptor !is ConstructorDescriptor ) Opcodes . ACC_FINAL else <NUM_LIT:0> ) or <EOL> ( if ( remainingParameters . lastOrNull ( ) ? . varargElementType != null ) Opcodes . ACC_VARARGS else <NUM_LIT:0> ) <EOL> val signature = typeMapper . mapSignatureWithCustomParameters ( functionDescriptor , contextKind , remainingParameters , false ) <EOL> val mv = classBuilder . newMethod ( JvmDeclarationOrigin ( JvmDeclarationOriginKind . JVM_OVERLOADS , methodElement ? . psiOrParent , functionDescriptor , remainingParametersDeclarations ) , flags , signature . asmMethod . name , signature . asmMethod . descriptor , signature . genericsSignature , FunctionCodegen . getThrownExceptions ( functionDescriptor , typeMapper ) ) <EOL> val skipNullabilityAnnotations = flags and Opcodes . ACC_PRIVATE != <NUM_LIT:0> || flags and Opcodes . ACC_SYNTHETIC != <NUM_LIT:0> <EOL> AnnotationCodegen . forMethod ( mv , memberCodegen , state , skipNullabilityAnnotations ) <EOL> . genAnnotations ( functionDescriptor , signature . returnType , functionDescriptor . returnType ) <EOL> if ( state . classBuilderMode == ClassBuilderMode . KAPT3 ) { <EOL> mv . visitAnnotation ( ANNOTATION_TYPE_DESCRIPTOR_FOR_JVM_OVERLOADS_GENERATED_METHODS , false ) <EOL> } <EOL> FunctionCodegen . generateParameterAnnotations ( functionDescriptor , mv , signature , remainingParameters , memberCodegen , state , skipNullabilityAnnotations ) <EOL> if ( ! state . classBuilderMode . generateBodies ) { <EOL> FunctionCodegen . generateLocalVariablesForParameters ( mv , signature , functionDescriptor , null , Label ( ) , Label ( ) , remainingParameters , isStatic , state ) <EOL> mv . visitEnd ( ) <EOL> return <EOL> } <EOL> val frameMap = FrameMap ( ) <EOL> val v = InstructionAdapter ( mv ) <EOL> mv . visitCode ( ) <EOL> val methodBegin = Label ( ) <EOL> mv . visitLabel ( methodBegin ) <EOL> val methodOwner = typeMapper . mapToCallableMethod ( delegateFunctionDescriptor , false ) . owner <EOL> if ( ! isStatic ) { <EOL> val thisIndex = frameMap . enterTemp ( AsmTypes . OBJECT_TYPE ) <EOL> v . load ( thisIndex , methodOwner ) <EOL> if ( functionDescriptor is ConstructorDescriptor ) { <EOL> val closure = state . bindingContext . get ( CodegenBinding . CLOSURE , functionDescriptor . constructedClass ) <EOL> val captureThis = getDispatchReceiverParameterForConstructorCall ( functionDescriptor , closure ) <EOL> if ( captureThis != null ) { <EOL> val outerIndex = frameMap . enterTemp ( AsmTypes . OBJECT_TYPE ) <EOL> v . load ( outerIndex , typeMapper . mapType ( captureThis ) ) <EOL> } <EOL> } <EOL> } else { <EOL> val delegateOwner = delegateFunctionDescriptor . containingDeclaration <EOL> if ( delegateOwner is ClassDescriptor && delegateOwner . isCompanionObject ) { <EOL> val singletonValue = StackValue . singleton ( delegateOwner , typeMapper ) <EOL> singletonValue . put ( singletonValue . type , singletonValue . kotlinType , v ) <EOL> } <EOL> } <EOL> val receiver = functionDescriptor . extensionReceiverParameter <EOL> if ( receiver != null ) { <EOL> val receiverKotlinType = receiver . returnType <EOL> val receiverType = typeMapper . mapType ( receiver ) <EOL> val receiverIndex = frameMap . enter ( receiver , receiverType ) <EOL> StackValue . local ( receiverIndex , receiverType , receiverKotlinType ) . put ( receiverType , receiverKotlinType , v ) <EOL> } <EOL> for ( parameter in remainingParameters ) { <EOL> frameMap . enter ( parameter , typeMapper . mapType ( parameter ) ) <EOL> } <EOL> val args = DefaultCallArgs ( functionDescriptor . valueParameters . size ) <EOL> for ( parameterDescriptor in functionDescriptor . valueParameters ) { <EOL> val paramKotlinType = parameterDescriptor . type <EOL> val paramType = typeMapper . mapType ( paramKotlinType ) <EOL> if ( parameterDescriptor in remainingParameters ) { <EOL> val index = frameMap . getIndex ( parameterDescriptor ) <EOL> StackValue . local ( index , paramType , paramKotlinType ) . put ( paramType , paramKotlinType , v ) <EOL> } else { <EOL> AsmUtil . pushDefaultValueOnStack ( paramType , v ) <EOL> args . mark ( parameterDescriptor . index ) <EOL> } <EOL> } <EOL> for ( mask in args . toInts ( ) ) { <EOL> v . iconst ( mask ) <EOL> } <EOL> v . aconst ( null ) <EOL> val defaultMethod = typeMapper . mapDefaultMethod ( delegateFunctionDescriptor , contextKind ) <EOL> if ( functionDescriptor is ConstructorDescriptor && ! functionDescriptor . containingDeclaration . isInlineClass ( ) ) { <EOL> v . invokespecial ( methodOwner . internalName , defaultMethod . name , defaultMethod . descriptor , false ) <EOL> } else { <EOL> v . invokestatic ( methodOwner . internalName , defaultMethod . name , defaultMethod . descriptor , false ) <EOL> } <EOL> v . areturn ( signature . returnType ) <EOL> val methodEnd = Label ( ) <EOL> mv . visitLabel ( methodEnd ) <EOL> val thisType = functionDescriptor . dispatchReceiverParameter ? . type ? . asmType ( typeMapper ) <EOL> FunctionCodegen . generateLocalVariablesForParameters ( mv , signature , functionDescriptor , thisType , methodBegin , methodEnd , remainingParameters , isStatic , state ) <EOL> FunctionCodegen . endVisit ( mv , null , methodElement ) <EOL> }

/**
 * Generates an overload for [functionDescriptor] that substitutes default values for the last
 * [substituteCount] parameters that have default values.
 *
 * @param functionDescriptor the method for which the overloads are generated
 * @param delegateFunctionDescriptor the method descriptor for the implementation that we need to call
 * (same as [functionDescriptor] in all cases except for companion object methods annotated with @JvmStatic,
 * where [functionDescriptor] is the static method in the main class and [delegateFunctionDescriptor] is the
 * implementation in the companion object class)
 * @param methodElement the PSI element for the method implementation (used in diagnostic messages only)
 */


@ JvmOverloads <EOL> fun Project . kotlinTest ( suffix : String ? = null , classifier : String ? = null ) : Any

{ <EOL> return if ( kotlinBuildProperties . isInJpsBuildIdeaSync ) { <EOL> kotlinDep ( listOfNotNull ( "<STR_LIT:test>" , suffix ? . lowercase ( ) ) . joinToString ( "<STR_LIT:->" ) , bootstrapKotlinVersion , classifier ) <EOL> } else { <EOL> val elementsType = when ( classifier ) { <EOL> null -> "<STR_LIT>" <EOL> "<STR_LIT>" -> "<STR_LIT>" <EOL> else -> error ( "<STR_LIT>" ) <EOL> } <EOL> val configuration = when ( suffix ? . lowercase ( ) ) { <EOL> null -> classifier ? . let { "<STR_LIT>" } <EOL> "<STR_LIT>" -> "<STR_LIT>" <EOL> "<STR_LIT>" -> "<STR_LIT>" <EOL> "<STR_LIT>" -> "<STR_LIT>" <EOL> "<STR_LIT:js>" -> "<STR_LIT>" <EOL> else -> error ( "<STR_LIT>" ) <EOL> } <EOL> dependencies . project ( "<STR_LIT>" , configuration ) <EOL> } <EOL> }

/**
 * Use this function to declare a dependency on kotlin-test project artifacts.
 *
 * It creates either a project dependency or a binary dependency on bootstrap artifacts when JPS build is imported.
 *
 * @param suffix Supported suffixes are:
 * - `null` for the default project dependency, variant is resolved by attributes
 * - `junit`, `junit5`, `testng` - jvm variants with annotation typealiases for different test frameworks,
 * - `js` - js variant with assertions and annotations
 * @param classifier Supported classifiers are: `null` for the runtime artifact, `sources` for the sources jar artifact
 */


{ <EOL> val ( train , test ) = fashionMnist ( ) <EOL> val jsonConfigFile = getJSONConfigFile ( ) <EOL> val model = Sequential . loadModelConfiguration ( jsonConfigFile ) <EOL> model . use { <EOL> it . layers . filterIsInstance < Conv2D > ( ) . forEach ( Layer :: freeze ) <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> val hdfFile = getWeightsFile ( ) <EOL> it . loadWeights ( hdfFile ) <EOL> val accuracyBefore = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> it . fit ( dataset = train , validationRate = <NUM_LIT> , epochs = <NUM_LIT:3> , trainBatchSize = <NUM_LIT> , validationBatchSize = <NUM_LIT:100> , ) <EOL> val accuracyAfterTraining = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example demonstrates the transfer learning concept:
 * - Weights are loaded from .h5 file, configuration is loaded from .json file.
 * - Conv2D layer is added to the new Neural Network, its weights are frozen, Dense layers are added too and its weights are not frozen, and can be changed during the training.
 * - No new layers are added.
 *
 * NOTE: Model and weights are resources in `examples` module.
 */


= additionalTrainingAndFreezing ( )


fun withFile ( firFile : FirFile , action : ( ) -> Unit ) : Unit

= action ( )

/**
 * Access to [FirFile] declaration will be performed inside [action].
 */


fun withRegularClass ( firClass : FirRegularClass , action : ( ) -> Unit ) : Unit

= action ( )

/**
 * Access to elements inside [FirRegularClass] will be performed inside [action].
 * Will be called for each nested [FirRegularClass] on the path.
 */


fun withScript ( firScript : FirScript , action : ( ) -> Unit ) : Unit

= action ( )

/**
 * Access to elements inside [FirScript] will be performed inside [action].
 */


fun performAction ( element : FirElementWithResolveState )

/**
 * This method will be performed on some target element depends on [LLFirResolveTarget] implementation.
 */


@ Suppress ( "<STR_LIT>" ) <EOL> internal fun String . splitQuotedArgs ( ) : List < String >

= <EOL> Regex ( """<STR_LIT>""" ) . findAll ( this ) . map { <EOL> it . value . replace ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> } . toList ( )

/**
 * Splits a string using a whitespace characters as delimiters.
 * Ignores whitespaces in quotes and drops quotes, e.g. a string
 * `foo "bar baz" qux="quux"` will be split into ["foo", "bar baz", "qux=quux"].
 */


fun KotlinNativeArtifactConfig . withPodspec ( configure : KotlinArtifactsPodspecExtension . ( ) -> Unit )

{ <EOL> val extension = cast < ExtensionAware > ( ) . kotlinArtifactsPodspecExtension <EOL> checkNotNull ( extension ) { "<STR_LIT>" } <EOL> extension . configure ( ) <EOL> }

/**
 * Extends a KotlinArtifact with a corresponding Podspec
 *
 * Only needed in *.kts build files. In Groovy you can use the same syntax but without explicit extension import
 */


fun getSession ( module : KtModule ) : LLFirSession

{ <EOL> return getSession ( module , preferBinary = true ) <EOL> }

/**
 * Returns an [LLFirSession] for the [module].
 * For a binary module, the resulting session will be a binary (non-resolvable) one.
 */


fun getResolvableSession ( module : KtModule ) : LLFirResolvableModuleSession

{ <EOL> return getSession ( module , preferBinary = false ) as LLFirResolvableModuleSession <EOL> }

/**
 * Returns an analyzable [LLFirSession] for the module.
 * For a binary module, the resulting session will still be a resolvable one.
 *
 * Note: prefer using [getSession] unless you need to perform resolution actively.
 * Resolvable sessions for libraries are much less performant.
 */


{ <EOL> lastIndex = <NUM_LIT:0> <EOL> }

/**
 * Resets the regular expression so that subsequent [RegExp.test] and [RegExp.exec] calls will match starting with the beginning of the input string.
 */


public inline operator fun RegExpMatch . get ( index : Int ) : String ?

= asDynamic ( ) [ index ]

/**
 * Returns the entire text matched by [RegExp.exec] if the [index] parameter is 0, or the text matched by the capturing parenthesis
 * at the given index.
 */


public inline fun RegExpMatch . asArray ( ) : Array < out String ? >

= unsafeCast < Array < out String ? > > ( )

/**
 * Converts the result of [RegExp.exec] to an array where the first element contains the entire matched text and each subsequent
 * element is the text matched by each capturing parenthesis.
 */


@ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> @ DeprecatedSinceKotlin ( warningSince = "<STR_LIT:1.9>" ) <EOL> @ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> @ ExperimentalStdlibApi <EOL> @ ExportForCompiler <EOL> @ OptIn ( ExperimentalNativeApi :: class , ObsoleteWorkersApi :: class ) <EOL> public fun < T > createCleaner ( argument : T , block : ( T ) -> Unit ) : Cleaner

= <EOL> kotlin . native . ref . createCleanerImpl ( argument , block ) as Cleaner

/**
 * Creates an object with a cleanup associated.
 *
 * After the resulting object ("cleaner") gets deallocated by memory manager,
 * [block] is eventually called once with [argument].
 *
 * Example of usage:
 * ```
 * class ResourceWrapper {
 * private val resource = Resource()
 *
 * private val cleaner = createCleaner(resource) { it.dispose() }
 * }
 * ```
 *
 * When `ResourceWrapper` becomes unused and gets deallocated, its `cleaner`
 * is also deallocated, and the resource is disposed later.
 *
 * It is not specified which thread runs [block], as well as whether two or more
 * blocks from different cleaners can be run in parallel.
 *
 * Note: if [argument] refers (directly or indirectly) the cleaner, then both
 * might leak, and the [block] will not be called in this case.
 * For example, the code below has a leak:
 * ```
 * class LeakingResourceWrapper {
 * private val resource = Resource()
 * private val cleaner = createCleaner(this) { it.resource.dispose() }
 * }
 * ```
 * In this case cleaner's argument (`LeakingResourceWrapper`) can't be deallocated
 * until cleaner's block is executed, which can happen only strictly after
 * the cleaner is deallocated, which can't happen until `LeakingResourceWrapper`
 * is deallocated. So the requirements on object deallocations are contradictory
 * in this case, which can't be handled gracefully. The cleaner's block
 * is not executed then, and cleaner and its argument might leak
 * (depending on the implementation).
 *
 * [block] should not use `@ThreadLocal` globals, because it may
 * be executed on a different thread.
 *
 * If [block] throws an exception, the behavior is unspecified.
 *
 * Cleaners should not be kept in globals, because if cleaner is not deallocated
 * before exiting main(), it'll never get executed.
 * Use `Platform.isCleanersLeakCheckerActive` to warn about unexecuted cleaners.
 *
 * If cleaners are not GC'd before main() exits, then it's not guaranteed that
 * they will be run. Moreover, it depends on `Platform.isCleanersLeakCheckerActive`.
 * With the checker enabled, cleaners will be run (and therefore not reported as
 * unexecuted cleaners); with the checker disabled - they might not get run.
 *
 * @param argument must be shareable
 * @param block must not capture anything
 */


@ InternalForKotlinNative <EOL> @ OptIn ( kotlin . native . runtime . NativeRuntimeApi :: class , ObsoleteWorkersApi :: class ) <EOL> public fun performGCOnCleanerWorker ( ) : Unit

= <EOL> getCleanerWorker ( ) . execute ( TransferMode . SAFE , { } ) { <EOL> GC . collect ( ) <EOL> } . result

/**
 * Perform GC on a worker that executes Cleaner blocks.
 */


@ InternalForKotlinNative <EOL> @ OptIn ( ObsoleteWorkersApi :: class ) <EOL> public fun waitCleanerWorker ( ) : Unit

= <EOL> getCleanerWorker ( ) . execute ( TransferMode . SAFE , { } ) { <EOL> Unit <EOL> } . result

/**
 * Wait for a worker that executes Cleaner blocks to complete its scheduled tasks.
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < reified T : Parcelable > parcelableCreator ( ) : Parcelable . Creator < T >

= <EOL> T :: class . java . getDeclaredField ( "<STR_LIT>" ) . get ( null ) as? Parcelable . Creator < T > <EOL> ? : throw IllegalArgumentException ( "<STR_LIT>" )

/**
 * Read the CREATOR field of the given [Parcelable] class. Calls to this function with
 * a concrete class will be optimized to a direct field access.
 */


@ Throws ( IOException :: class ) <EOL> public fun detectObjects ( imageFile : File , topK : Int = <NUM_LIT:5> ) : List < DetectedObject >

{ <EOL> return detectObjects ( ImageConverter . toBufferedImage ( imageFile ) , topK ) <EOL> }

/**
 * Returns the detected object for the given image file sorted by the score.
 *
 * NOTE: this method includes the EfficientDet - related preprocessing.
 *
 * @param [imageFile] File, should be an image.
 * @param [topK] The number of the detected objects with the highest score to be returned.
 * @return List of [DetectedObject] sorted by score.
 */


{ <EOL> val ( train , test ) = mnist ( ) <EOL> model . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> println ( it . kGraph ) <EOL> it . fit ( dataset = train , epochs = EPOCHS , batchSize = TRAINING_BATCH_SIZE , callback = FitCallback ( ) ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE , callback = EvaluationCallback ( ) ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> val predictions = it . predictSoftly ( dataset = test , batchSize = TEST_BATCH_SIZE , callback = PredictCallback ( ) ) <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example shows how to do image classification from scratch using [model], without leveraging pre-trained weights or a pre-made model.
 * We demonstrate the workflow on the Mnist classification dataset.
 *
 * It includes:
 * - dataset loading from S3
 * - callback definitions
 * - TensorFlow graph printing
 * - model training with custom callback
 * - model evaluation with custom callback
 * - model prediction with custom callback
 */


= lenetMnistWithCustomCallback ( )


fun getTypeAsList ( nullableArray : kotlin . Boolean , typeFqName : kotlin . String ) : FieldType . ValueFieldType

= <EOL> FieldType . ValueFieldType ( typeFqName = "<STR_LIT>" , )

/** used for list of primitives (read as List<MyPrimitive>) */


fun getTypeAsFrame ( nullable : kotlin . Boolean , markerName : kotlin . String ) : FieldType . FrameFieldType

= <EOL> FieldType . FrameFieldType ( markerName = markerName . let { if ( nullable ) it . toNullable ( ) else it } , nullable = false , )

/** used for list of objects (read as DataFrame<MyMarker>) */


fun getTypeAsFrameList ( nullable : kotlin . Boolean , nullableArray : kotlin . Boolean , markerName : kotlin . String , ) : FieldType . ValueFieldType

/** used for list of AdditionalProperty objects (read as List<DataFrame<MyMarker>>) */


public fun < T > label ( column : ColumnReference < T > , ) : NonPositionalMapping < T , String >

{ <EOL> return addNonPositionalMapping < T , String > ( LABEL , column . name ( ) , null ) <EOL> }

/**
 * Maps the `label` 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 > label ( column : KProperty < T > , ) : NonPositionalMapping < T , String >

{ <EOL> return addNonPositionalMapping < T , String > ( LABEL , column . name , null ) <EOL> }

/**
 * Maps the `label` 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 label ( column : String , ) : NonPositionalMapping < Any ? , String >

{ <EOL> return addNonPositionalMapping < Any ? , String > ( LABEL , column , null ) <EOL> }

/**
 * Maps the `label` 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 > label ( values : Iterable < T > , name : String ? = null , ) : NonPositionalMapping < T , String >

{ <EOL> return addNonPositionalMapping < T , String > ( LABEL , values . toList ( ) , name , null ) <EOL> }

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


public fun < T > label ( values : DataColumn < T > , ) : NonPositionalMapping < T , String >

{ <EOL> return addNonPositionalMapping < T , String > ( LABEL , values , null ) <EOL> }

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


private fun BaseKotlinScope . createProjectHierarchyWithPluginOnSub1 ( )

{ <EOL> settingsGradleKts { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> buildGradleKts { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> dir ( "<STR_LIT>" ) { <EOL> buildGradleKts { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> dir ( "<STR_LIT>" ) { <EOL> buildGradleKts { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> dir ( "<STR_LIT>" ) { <EOL> buildGradleKts { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> } <EOL> dir ( "<STR_LIT>" ) { <EOL> buildGradleKts { <EOL> resolve ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> }

/**
 * Sets up a project hierarchy like this:
 * ```
 * build.gradle.kts (without the plugin)
 * settings.gradle.kts (including refs to 4 subprojects)
 * sub1/
 * build.gradle.kts (with the plugin)
 * subsub1/build.gradle.kts
 * subsub2/build.gradle.kts
 * sub2/build.gradle.kts
 * ```
 */


public fun < T > use ( block : SampleAnalysisEnvironment . ( ) -> T ) : T

/**
 * Creates and configures the sample analysis environment for a limited-time use.
 *
 * Configuring sample analysis environment is a rather expensive operation that takes up additional
 * resources since Dokka needs to configure and analyze source roots additional to the main ones.
 * It's best to limit the scope of use and the lifetime of the created environment
 * so that the resources could be freed as soon as possible.
 *
 * No specific cleanup is required by the caller - everything is taken care of automatically
 * as soon as you exit the [block] block.
 *
 * Usage example:
 * ```kotlin
 * // create a short-lived environment and resolve all the needed samples
 * val sample = sampleAnalysisEnvironmentCreator.use {
 * resolveSample(sampleSourceSet, "org.jetbrains.dokka.sample.functionName")
 * }
 * // process the samples
 * // ...
 * ```
 */


fun decodeCDPResponse ( message : String , serializerForMessageId : ( Int ) -> CDPMethodCallEncodingInfo ) : CDPResponse

{ <EOL> val jsonElement = json . parseToJsonElement ( message ) <EOL> return when ( val id = jsonElement . jsonObject [ "<STR_LIT:id>" ] ? . jsonPrimitive ? . int ) { <EOL> null -> CDPResponse . Event ( decodeCDPEvent ( jsonElement ) ) <EOL> else -> { <EOL> val serializer = when ( val encodingInfo = serializerForMessageId ( id ) ) { <EOL> is CDPMethodCallEncodingInfoImpl -> encodingInfo . serializer <EOL> is CDPMethodCallEncodingInfoPlainText -> null <EOL> } <EOL> val result = jsonElement . jsonObject [ "<STR_LIT>" ] <EOL> val error = jsonElement . jsonObject [ "<STR_LIT:error>" ] <EOL> if ( result != null ) { <EOL> CDPResponse . MethodInvocationResult ( id , serializer ? . let { json . decodeFromJsonElement ( it , result ) } ? : CDPMethodInvocationResultPlainText ( result . toString ( ) ) ) <EOL> } else if ( error != null ) { <EOL> CDPResponse . Error ( id , json . decodeFromJsonElement ( error ) ) <EOL> } else { <EOL> error ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Decodes an instance of [CDPResponse] from JSON-encoded [message].
 *
 * [serializerForMessageId] is used for retrieving additional information about how to decode the response for the given message id.
 */


private inline fun < reified Response : CDPMethodInvocationResult , reified Params : CDPRequestParams > encodeCDPMethodCall ( messageId : Int , methodName : String , params : Params ? <EOL> ) : Pair < String , CDPMethodCallEncodingInfo >

{ <EOL> val request = CDPRequest ( messageId , methodName , params ) <EOL> return json . encodeToString ( request ) to <EOL> CDPMethodCallEncodingInfoImpl ( json . serializersModule . serializer < Response > ( ) ) <EOL> }

/**
 * Returns the JSON message for invoking the method, as well as the information about how to decode its result.
 */


suspend fun genericEvaluateRequest ( encodeMethodCallWithMessageId : ( Int ) -> Pair < String , CDPMethodCallEncodingInfo > ) : CDPMethodInvocationResult

/**
 * @param encodeMethodCallWithMessageId passed a message id, expected to return the JSON-encoded CDP message
 * and some information about how to decode the response.
 */


{ <EOL> requestEvaluator . evaluateRequest < CDPMethodInvocationResultUnit > { messageId -> <EOL> encodeCDPMethodCall < CDPMethodInvocationResultUnit , CDPRequestParamsUnit > ( messageId , "<STR_LIT>" , null ) <EOL> } <EOL> }

/**
 * Enables reporting of execution contexts creation by means of [Runtime.Event.ExecutionContextCreated] event.
 * When the reporting gets enabled the event will be sent immediately for each existing execution context.
 *
 * See [Runtime.enable](https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#method-enable)
 */


/**
 * Tells inspected instance to run if it was waiting for debugger to attach.
 *
 * See [Runtime.runIfWaitingForDebugger](https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#method-runIfWaitingForDebugger)
 */


suspend fun evaluate ( expression : String , contextId : ExecutionContextId ? = null )

= <EOL> requestEvaluator . evaluateRequest < EvaluationResult > { messageId -> <EOL> encodeCDPMethodCall < EvaluationResult , EvaluateRequestParams > ( messageId , "<STR_LIT>" , EvaluateRequestParams ( expression , contextId ) ) <EOL> }

/**
 * Evaluates expression on global object.
 *
 * See [Runtime.evaluate](https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#method-evaluate)
 *
 * @param expression Expression to evaluate.
 * @param contextId Specifies in which execution context to perform evaluation.
 * If the parameter is omitted the evaluation will be performed in the context of the inspected page.
 */


{ <EOL> requestEvaluator . evaluateRequest < CDPMethodInvocationResultUnit > { messageId -> <EOL> encodeCDPMethodCall < CDPMethodInvocationResultUnit , ResumeRequestParams > ( messageId , "<STR_LIT>" , null ) <EOL> } <EOL> }

/**
 * Resumes JavaScript execution.
 *
 * See [Debugger.resume](https://chromedevtools.github.io/devtools-protocol/tot/Debugger/#method-resume)
 */


suspend fun setBreakpointByUrl ( lineNumber : Int , url : String , scriptHash : String ? = null , columnNumber : Int ? = null , condition : String ? = null )

= requestEvaluator . evaluateRequest < SetBreakpointByUrlResult > { messageId -> <EOL> encodeCDPMethodCall < SetBreakpointByUrlResult , SetBreakpointByUrlRequestParams > ( messageId , "<STR_LIT>" , SetBreakpointByUrlRequestParams ( lineNumber , url , scriptHash , columnNumber , condition ) ) <EOL> }

/**
 * Sets JavaScript breakpoint at given location specified either by URL or URL regex.
 * Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in
 * [SetBreakpointByUrlResult.locations] property.
 * Further matching script parsing will result in subsequent [Debugger.Event.BreakpointResolved] events issued.
 *
 * See [Debugger.setBreakpointByUrl](https://chromedevtools.github.io/devtools-protocol/tot/Debugger/#method-setBreakpointByUrl)
 *
 * @param lineNumber Line number to set breakpoint at.
 * @param url URL of the resources to set breakpoint on.
 * @param scriptHash Script hash of the resources to set breakpoint on.
 * @param columnNumber Offset in the line to set breakpoint at.
 * @param condition Expression to use as a breakpoint condition.
 * When specified, debugger will only stop on the breakpoint if this expression evaluates to true.
 */


suspend fun setBreakpoint ( scriptId : Runtime . ScriptId , lineNumber : Int , columnNumber : Int ? = null , condition : String ? = null )

= requestEvaluator . evaluateRequest < SetBreakpointResult > { messageId -> <EOL> encodeCDPMethodCall < SetBreakpointResult , SetBreakpointRequestParams > ( messageId , "<STR_LIT>" , SetBreakpointRequestParams ( Location ( scriptId , lineNumber , columnNumber ) , condition ) ) <EOL> }

/**
 * Sets JavaScript breakpoint at a given location.
 *
 * See [Debugger.setBreakpoint](https://chromedevtools.github.io/devtools-protocol/tot/Debugger/#method-setBreakpoint)
 *
 * @param scriptId Script identifier as reported in the [Debugger.Event.ScriptParsed].
 * @param lineNumber Line number in the script (0-based).
 * @param columnNumber Column number in the script (0-based).
 * @param condition Expression to use as a breakpoint condition.
 * When specified, debugger will only stop on the breakpoint if this expression evaluates to true.
 */


suspend fun setSkipAllPauses ( skip : Boolean )

{ <EOL> requestEvaluator . evaluateRequest < CDPMethodInvocationResultUnit > { messageId -> <EOL> encodeCDPMethodCall < CDPMethodInvocationResultUnit , SetSkipAllPausesRequestParams > ( messageId , "<STR_LIT>" , SetSkipAllPausesRequestParams ( skip ) ) <EOL> } <EOL> }

/**
 * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc).
 *
 * See [Debugger.setSkipAllPauses](https://chromedevtools.github.io/devtools-protocol/tot/Debugger/#method-setSkipAllPauses)
 *
 * @param skip New value for skip pauses state.
 */


/**
 * Steps into the function call.
 *
 * See [Debugger.stepInto](https://chromedevtools.github.io/devtools-protocol/tot/Debugger/#method-stepInto)
 */


suspend fun evaluateOnCallFrame ( callFrameId : CallFrameId , expression : String , returnByValue : Boolean ? = null , )

= requestEvaluator . evaluateRequest < Runtime . EvaluationResult > { messageId -> <EOL> encodeCDPMethodCall < Runtime . EvaluationResult , EvaluateOnCallFrameRequestParams > ( messageId , "<STR_LIT>" , EvaluateOnCallFrameRequestParams ( callFrameId , expression , returnByValue ) ) <EOL> }

/**
 * Evaluates expression on a given call frame.
 *
 * See [Debugger.evaluateOnCallFrame](https://chromedevtools.github.io/devtools-protocol/tot/Debugger/#method-evaluateOnCallFrame)
 *
 * @param callFrameId Call frame identifier to evaluate on.
 * @param expression Expression to evaluate.
 * @param returnByValue Whether the result is expected to be a JSON object that should be sent by value.
 */


@ BetaInteropApi <EOL> public fun getOriginalKotlinClass ( objCClass : ObjCClass ) : KClass < * > ?

{ <EOL> val typeInfo = getTypeInfoForClass ( objCClass . objcPtr ( ) ) <EOL> if ( typeInfo . isNull ( ) ) return null <EOL> return KClassImpl < Any > ( typeInfo ) <EOL> }

/**
 * If [objCClass] is a class generated to Objective-C header for Kotlin class,
 * returns [KClass] for that original Kotlin class.
 *
 * Otherwise returns `null`.
 */


@ BetaInteropApi <EOL> public fun getOriginalKotlinClass ( objCProtocol : ObjCProtocol ) : KClass < * > ?

{ <EOL> val typeInfo = getTypeInfoForProtocol ( objCProtocol . objcPtr ( ) ) <EOL> if ( typeInfo . isNull ( ) ) return null <EOL> return KClassImpl < Any > ( typeInfo ) <EOL> }

/**
 * If [objCProtocol] is a protocol generated to Objective-C header for Kotlin class,
 * returns [KClass] for that original Kotlin class.
 *
 * Otherwise returns `null`.
 */


public fun format ( columnSeparator : String = "<STR_LIT:U+0020>" , lineSeparatorSymbol : Char = '<CHAR_LIT:_>' , thickLineSeparatorSymbol : Char = '<CHAR_LIT>' ) : List < String >

/**
 * Formats model summary to an array of strings.
 * Rows should form a table with a clean and readable structure.
 *
 * @param [columnSeparator] text chunk that will be used as column separator for the output table
 * @param [lineSeparatorSymbol] character that will be used to produce a string to separate rows of the output table
 * @param [thickLineSeparatorSymbol] character that will be used to produce
 * a string to separate blocks of the output table
 *
 * @return formatted model summary
 */


public inline fun EChartsLayout . legend ( crossinline block : Legend . ( ) -> Unit )

{ <EOL> this . legend = Legend ( ) . apply ( block ) <EOL> }

/**
 * Shows name, symbol and color of different layers.
 *
 * - [type][Legend.type] - [type][LegendType] of legend. `plain` is default.
 * - [left][Legend.left] - distance between a legend component and the left side of the container. `auto` by default.
 * - [top][Legend.top] - distance between a legend component and the top side of the container. `auto` by default.
 * - [right][Legend.right] - distance between a legend component and the right side of the container. `auto` by default.
 * - [bottom][Legend.bottom] - distance between a legend component and the bottom side of the container. `auto` by default.
 * - [width][Legend.width] - width of a legend component. `auto` by default.
 * - [height][Legend.height] - height of a legend component. `auto` by default.
 * - [orient][Legend.orient] - the layout [orientation][Orient] of legend. `horizontal` by default.
 * - [formatter][Legend.formatter] - formatter is used to format label of legend.
 *
 * ```kotlin
 * plot(mapOf()) {
 * layout {
 * legend {
 * type = LegendType.PLAIN
 * left = 10.pct
 * top = 60.px
 * right = 10.pct
 * bottom = 60.px
 * width = 300.px
 * height = 10.pct
 * orient = Orient.VERTICAL
 * formatter = "Legend {name}"
 * }
 * }
 * }
 * ```
 *
 * @see org.jetbrains.kotlinx.kandy.echarts.layers.layout
 * @see SizeUnit
 * @see LegendType
 * @see Orient
 */


{ <EOL> val modelHub = ONNXModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = ONNXModels . ObjectDetection . SSDMobileNetV1 <EOL> val model = modelHub . loadModel ( modelType ) <EOL> model . printSummary ( ) <EOL> model . use { <EOL> println ( it ) <EOL> val fileDataLoader = pipeline < BufferedImage > ( ) <EOL> . resize { <EOL> outputHeight = <NUM_LIT> <EOL> outputWidth = <NUM_LIT> <EOL> } <EOL> . convert { colorMode = ColorMode . BGR } <EOL> . toFloatArray { } <EOL> . call ( modelType . preprocessor ) <EOL> . fileLoader ( ) <EOL> for ( i in <NUM_LIT:1> .. <NUM_LIT:6> ) { <EOL> val inputData = fileDataLoader . load ( getFileFromResource ( "<STR_LIT>" ) ) <EOL> val yhat = it . predictRaw ( inputData ) <EOL> println ( yhat . values . toTypedArray ( ) . contentDeepToString ( ) ) <EOL> } <EOL> } <EOL> }

/**
 * This examples demonstrates the inference concept on SSD model:
 * - Model is obtained from [ONNXModelHub].
 * - Model predicts on a few images located in resources.
 * - Special preprocessing is applied to each image before prediction.
 */


= ssdMobile ( )


@ Language ( "<STR_LIT>" ) <EOL> fun createSettingsXml ( ) : String

{ <EOL> val devMavenRepositories : List < Path > by systemProperty { repos -> <EOL> repos . split ( "<STR_LIT:U+002C>" ) . map { Paths . get ( it ) } <EOL> } <EOL> val pluginRepos = devMavenRepositories <EOL> . withIndex ( ) <EOL> . joinToString ( "<STR_LIT:\n>" ) { ( i , repoPath ) -> <EOL> """<STR_LIT>""" . trimMargin ( ) <EOL> } <EOL> return """<STR_LIT>""" . trimMargin ( ) <EOL> }

/** Create `settings.xml` file contents, with the custom dev Maven repos. */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun Char ( code : Int ) : Char

{ <EOL> if ( code < Char . MIN_VALUE . code || code > Char . MAX_VALUE . code ) { <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } <EOL> return code . toChar ( ) <EOL> }

/**
 * Creates a Char with the specified [code], or throws an exception if the [code] is out of `Char.MIN_VALUE.code..Char.MAX_VALUE.code`.
 *
 * If the program that calls this function is written in a way that only valid [code] is passed as the argument,
 * using the overload that takes a [UShort] argument is preferable (`Char(intValue.toUShort())`).
 * That overload doesn't check validity of the argument, and may improve program performance when the function is called routinely inside a loop.
 *
 * @sample samples.text.Chars.charFromCode
 */


@ SinceKotlin ( "<STR_LIT:1.5>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> public expect fun Char ( code : UShort ) : Char

/**
 * Creates a Char with the specified [code].
 *
 * @sample samples.text.Chars.charFromCode
 */


internal fun < T > KotlinGradlePluginExtensionPoint ( ) : KotlinGradlePluginExtensionPoint < T >

{ <EOL> @ OptIn ( UnsafeApi :: class ) <EOL> return KotlinGradlePluginExtensionPointInternal ( ) <EOL> }

/**
 * Creates a new [KotlinGradlePluginExtensionPoint]
 * See [KotlinGradlePluginExtensionPoint] documentation for the intended usage!
 */


public fun createExtensionCandidateChecker ( originalFile : KtFile , nameExpression : KtSimpleNameExpression , explicitReceiver : KtExpression ? <EOL> ) : KtCompletionExtensionCandidateChecker

{ <EOL> return analysisSession . completionCandidateChecker . createExtensionCandidateChecker ( originalFile , nameExpression , explicitReceiver ) <EOL> }

/**
 * Returns an extension applicability checker for the given context [nameExpression].
 * The function is meant to only be used for providing auto-completion for Kotlin in IntelliJ IDEA.
 *
 * The returned checker does not cache the results for individual callable candidates.
 *
 * @param originalFile The file being edited.
 * @param nameExpression The expression under the caret in an in-memory copy of [originalFile]
 * with a dummy identifier inserted. Also see `CompletionUtilCore.DUMMY_IDENTIFIER` in IntelliJ IDEA.
 * @param explicitReceiver A receiver expression, if available (also from the in-memory copy of [originalFile]).
 */