private fun buildClassSuiteConstructor ( suiteName : String , testClassType : IrType , testCompanionType : IrType , testSuite : IrClassSymbol , owner : IrClass , functions : Collection < TestFunction > , ignored : Boolean ) : IrConstructor

= <EOL> context . irFactory . createConstructor ( testSuite . owner . startOffset , testSuite . owner . endOffset , TEST_SUITE_GENERATED_MEMBER , Name . special ( "<STR_LIT:<init>>" ) , DescriptorVisibilities . PUBLIC , isInline = false , isExpect = false , testSuite . starProjectedType , IrConstructorSymbolImpl ( ) , isPrimary = true , ) . apply { <EOL> parent = owner <EOL> fun IrClass . getFunction ( name : String , predicate : ( IrSimpleFunction ) -> Boolean ) = <EOL> simpleFunctions ( ) . single { it . name . asString ( ) == name && predicate ( it ) } <EOL> val registerTestCase = baseClassSuite . getFunction ( "<STR_LIT>" ) { <EOL> it . valueParameters . size == <NUM_LIT:3> <EOL> && it . valueParameters [ <NUM_LIT:0> ] . type . isString ( ) <EOL> && it . valueParameters [ <NUM_LIT:1> ] . type . isFunction ( ) <EOL> && it . valueParameters [ <NUM_LIT:2> ] . type . isBoolean ( ) <EOL> } <EOL> val registerFunction = baseClassSuite . getFunction ( "<STR_LIT>" ) { <EOL> it . valueParameters . size == <NUM_LIT:2> <EOL> && it . valueParameters [ <NUM_LIT:0> ] . type . isTestFunctionKind ( ) <EOL> && it . valueParameters [ <NUM_LIT:1> ] . type . isFunction ( ) <EOL> } <EOL> body = context . createIrBuilder ( symbol , symbol . owner . startOffset , symbol . owner . endOffset ) . irBlockBody { <EOL> + irDelegatingConstructorCall ( baseClassSuiteConstructor ) . apply { <EOL> putTypeArgument ( <NUM_LIT:0> , testClassType ) <EOL> putTypeArgument ( <NUM_LIT:1> , testCompanionType ) <EOL> putValueArgument ( <NUM_LIT:0> , irString ( suiteName ) ) <EOL> putValueArgument ( <NUM_LIT:1> , irBoolean ( ignored ) ) <EOL> } <EOL> generateFunctionRegistration ( testSuite . owner . thisReceiver ! ! , registerTestCase , registerFunction , functions ) <EOL> } <EOL> }

/**
 * Builds a constructor for a test suite class representing a test class (any class in the original IrFile with
 * method(s) annotated with @Test). The test suite class is a subclass of ClassTestSuite<T>
 * where T is the test class.
 */


private fun buildClassSuite ( suiteName : String , testClass : IrClass , testCompanion : IrClass ? , functions : Collection < TestFunction > , irFile : IrFile ) : IrClass

{ <EOL> return context . irFactory . createClass ( testClass . startOffset , testClass . endOffset , TEST_SUITE_CLASS , testClass . name . synthesizeSuiteClassName ( ) , DescriptorVisibilities . PRIVATE , IrClassSymbolImpl ( ) , ClassKind . CLASS , Modality . FINAL , ) . apply { <EOL> irFile . addChild ( this ) <EOL> createParameterDeclarations ( ) <EOL> val testClassType = testClass . defaultType <EOL> val testCompanionType = if ( testClass . kind == ClassKind . OBJECT ) { <EOL> testClassType <EOL> } else { <EOL> testCompanion ? . defaultType ? : context . irBuiltIns . nothingType <EOL> } <EOL> val constructor = buildClassSuiteConstructor ( suiteName , testClassType , testCompanionType , symbol , this , functions , testClass . ignored ) <EOL> val instanceGetter : IrFunction <EOL> val companionGetter : IrFunction ? <EOL> if ( testClass . kind == ClassKind . OBJECT ) { <EOL> instanceGetter = buildObjectGetter ( testClass . symbol , this , INSTANCE_GETTER_NAME ) <EOL> companionGetter = buildObjectGetter ( testClass . symbol , this , COMPANION_GETTER_NAME ) <EOL> } else { <EOL> instanceGetter = buildInstanceGetter ( testClass . symbol , this , INSTANCE_GETTER_NAME ) <EOL> companionGetter = testCompanion ? . let { <EOL> buildObjectGetter ( it . symbol , this , COMPANION_GETTER_NAME ) <EOL> } <EOL> } <EOL> declarations += constructor <EOL> declarations += instanceGetter <EOL> companionGetter ? . let { declarations += it } <EOL> superTypes += symbols . baseClassSuite . typeWith ( listOf ( testClassType , testCompanionType ) ) <EOL> addFakeOverrides ( context . typeSystem ) <EOL> } <EOL> }

/**
 * Builds a test suite class representing a test class (any class in the original IrFile with method(s)
 * annotated with @Test). The test suite class is a subclass of ClassTestSuite<T> where T is the test class.
 */


private fun checkTopLevelSuiteName ( irFile : IrFile , topLevelSuiteName : String ) : Boolean

{ <EOL> if ( topLevelSuiteNames . contains ( topLevelSuiteName ) ) { <EOL> context . reportCompilationError ( "<STR_LIT>" + "<STR_LIT>" ) <EOL> } <EOL> topLevelSuiteNames . add ( topLevelSuiteName ) <EOL> return true <EOL> }

/** Check if this fqName already used or not. */


internal open fun cancelCompletedResult ( takenState : Any ? , cause : Throwable )

/**
 * Called when this task was cancelled while it was being dispatched.
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> internal open fun < T > getSuccessfulResult ( state : Any ? ) : T

= <EOL> state as T

/**
 * There are two implementations of `DispatchedTask`:
 * - [DispatchedContinuation] keeps only simple values as successfully results.
 * - [CancellableContinuationImpl] keeps additional data with values and overrides this method to unwrap it.
 */


internal open fun getExceptionalResult ( state : Any ? ) : Throwable ?

= <EOL> ( state as? CompletedExceptionally ) ? . cause

/**
 * There are two implementations of `DispatchedTask`:
 * - [DispatchedContinuation] is just an intermediate storage that stores the exception that has its stack-trace
 * properly recovered and is ready to pass to the [delegate] continuation directly.
 * - [CancellableContinuationImpl] stores raw cause of the failure in its state; when it needs to be dispatched
 * its stack-trace has to be recovered, so it overrides this method for that purpose.
 */


internal fun handleFatalException ( exception : Throwable ? , finallyException : Throwable ? )

{ <EOL> if ( exception === null && finallyException === null ) return <EOL> if ( exception !== null && finallyException !== null ) { <EOL> exception . addSuppressed ( finallyException ) <EOL> } <EOL> val cause = exception ? : finallyException <EOL> val reason = CoroutinesInternalError ( "<STR_LIT>" + "<STR_LIT>" , cause ! ! ) <EOL> handleCoroutineException ( this . delegate . context , reason ) <EOL> }

/**
 * Machinery that handles fatal exceptions in kotlinx.coroutines.
 * There are two kinds of fatal exceptions:
 *
 * 1) Exceptions from kotlinx.coroutines code. Such exceptions indicate that either
 * the library or the compiler has a bug that breaks internal invariants.
 * They usually have specific workarounds, but require careful study of the cause and should
 * be reported to the maintainers and fixed on the library's side anyway.
 *
 * 2) Exceptions from [ThreadContextElement.updateThreadContext] and [ThreadContextElement.restoreThreadContext].
 * While a user code can trigger such exception by providing an improper implementation of [ThreadContextElement],
 * we can't ignore it because it may leave coroutine in the inconsistent state.
 * If you encounter such exception, you can either disable this context element or wrap it into
 * another context element that catches all exceptions and handles it in the application specific manner.
 *
 * Fatal exception handling can be intercepted with [CoroutineExceptionHandler] element in the context of
 * a failed coroutine, but such exceptions should be reported anyway.
 */


fun taskNameForKotlinModule ( moduleName : String ) : String

= lowerCamelCaseName ( defaultTaskName , moduleName )

/**
 * The name of the default [FromKpmModule] task of the given [GradleKpmModule]'s name
 */


@ ExperimentalNativeApi <EOL> public fun < T > MutableList < T > . replaceAll ( transformation : ( T ) -> T )

{ <EOL> val it = listIterator ( ) <EOL> while ( it . hasNext ( ) ) { <EOL> val element = it . next ( ) <EOL> it . set ( transformation ( element ) ) <EOL> } <EOL> }

/**
 * Replaces each element in the list with a result of a transformation specified.
 */


internal fun ExpectActualMatchingContext < * > . areEnumConstructors ( expectDeclaration : CallableSymbolMarker , actualDeclaration : CallableSymbolMarker , expectContainingClass : RegularClassSymbolMarker ? , actualContainingClass : RegularClassSymbolMarker ? , ) : Boolean

= expectContainingClass ? . classKind == ClassKind . ENUM_CLASS && <EOL> actualContainingClass ? . classKind == ClassKind . ENUM_CLASS && <EOL> expectDeclaration is ConstructorSymbolMarker && <EOL> actualDeclaration is ConstructorSymbolMarker

/**
 * In terms of KMP, there is no such thing as `expect constructor` for enums,
 * but they are physically exist in FIR and IR, so we need to skip matching and checking for them
 */


@ Benchmark <EOL> fun removeAll_All ( ) : PersistentList < String >

{ <EOL> return persistentList . removeAll ( truePredicate ) <EOL> }


@ Benchmark <EOL> fun removeAll_Non ( ) : PersistentList < String >

{ <EOL> return persistentList . removeAll ( falsePredicate ) <EOL> }


@ Benchmark <EOL> fun removeAll_RandomHalf ( ) : PersistentList < String >

{ <EOL> return persistentList . removeAll ( randomHalfElementsPredicate ) <EOL> }

/** Removes half of the elements randomly selected. */


@ Benchmark <EOL> fun removeAll_RandomTen ( ) : PersistentList < String >

{ <EOL> return persistentList . removeAll ( randomTenElementsPredicate ) <EOL> }


@ Benchmark <EOL> fun removeAll_RandomOne ( ) : PersistentList < String >

{ <EOL> return persistentList . removeAll ( randomOneElementPredicate ) <EOL> }


@ Benchmark <EOL> fun removeAll_Tail ( ) : PersistentList < String >

{ <EOL> return persistentList . removeAll ( tailElementsPredicate ) <EOL> }

/** Removes last [tailSize] elements. */


public fun < T > DataRow < T > . diff ( firstRowResult : Long , expression : RowExpression < T , Long > ) : Long

= <EOL> prev ( ) ? . let { p -> expression ( this , this ) - expression ( p , p ) } ? : firstRowResult


public fun < T > DataRow < T > . diff ( firstRowResult : Float , expression : RowExpression < T , Float > ) : Float


public fun < T > DataRow < T > . diffOrNull ( expression : RowExpression < T , Int > ) : Int ?

= <EOL> prev ( ) ? . let { p -> expression ( this , this ) - expression ( p , p ) }


public fun < T > DataRow < T > . diffOrNull ( expression : RowExpression < T , Long > ) : Long ?


public fun < T > DataRow < T > . diffOrNull ( expression : RowExpression < T , Float > ) : Float ?


private inline fun < reified S : FirCallableSymbol < * > > computeBaseSymbolsWithContainingClass ( klass : FirClass , originalSymbol : S , directOverridden : FirTypeScope . ( S ) -> List < S > , processOverridden : FirTypeScope . ( S , ( S ) -> ProcessorAction ) -> ProcessorAction ) : List < Pair < S , ConeClassLikeLookupTag > >

{ <EOL> val scope = klass . unsubstitutedScope ( c ) <EOL> val classLookupTag = klass . symbol . toLookupTag ( ) <EOL> val overriddenFirSymbols = computeBaseSymbols ( originalSymbol , directOverridden , scope , classLookupTag ) <EOL> val typeContext = session . typeContext <EOL> val overriddenPerSupertype = setMultimapOf < ConeClassLikeLookupTag , S > ( ) <EOL> with ( typeContext ) { <EOL> for ( symbol in overriddenFirSymbols ) { <EOL> val symbolDispatchReceiver = symbol . containingClassLookupTag ( ) ? : continue <EOL> for ( superType in klass . superConeTypes ) { <EOL> val compatibleType = superType . anySuperTypeConstructor { <EOL> it . typeConstructor ( ) == symbolDispatchReceiver <EOL> } <EOL> if ( ! compatibleType ) { <EOL> continue <EOL> } <EOL> overriddenPerSupertype . put ( superType . lookupTag , symbol ) <EOL> } <EOL> } <EOL> } <EOL> val result = overriddenPerSupertype . map { ( superType , overridden ) -> <EOL> val chosenOverridden = when ( overridden . size ) { <EOL> <NUM_LIT:0> -> shouldNotBeCalled ( ) <EOL> <NUM_LIT:1> -> overridden . first ( ) <EOL> else -> chooseMostSpecificOverridden ( superType , overridden , processOverridden ) <EOL> } <EOL> chosenOverridden to superType <EOL> } <EOL> return result <EOL> }

/**
 * This functions takes a list of overridden symbols and associate each one with one of the supertypes, from which this symbol came
 * from. This mapping will be used later to generate proper fake-overrides in IR
 *
 * ```
 * open class A {
 * fun foo() {}
 * }
 *
 * interface B
 *
 * open class C : A()
 *
 * class D : C(), B {
 * override fun foo() {}
 * }
 * ```
 *
 * In this example FIR returns that `C.foo` overrides `A.foo`
 * But in IR there are fake-overrides on each level of the hierarchy, so we need to associate `A.foo` with class `C`,
 * so later it will be converted to IR f/o `B.foo`
 * To understand that we should choose `C` here instead of `B`, we check if the dispatch receiver of the overridden is supertype
 * of each of supertypes (here `A` from `A.foo` is not supertype of `B`, so supertype `B` is discarded)
 *
 * There might be some cases when the same overridden function is accessible from multiple supertypes.
 * Note that this example is simplified, and actually requires java classes on the way (see KT-65592)
 *
 * ```
 * interface A {
 * fun foo()
 * }
 *
 * open class AImpl : A {
 * override fun foo() {}
 * }
 *
 * interface B : A
 * open class BImpl : AImpl(), B
 *
 * interface C : B
 * class CImpl : BImpl(), C
 * ```
 *
 * Here we have f/o `CImpl.foo` function, which overrides `A.foo` and `AImpl.foo` from FIR point of view
 * `AImpl.foo` matches only with supertype `BImpl`
 * But receiver of `A.foo` is a supertype both of `BImpl` and `C`, which leads to the situation, when there are two different base
 * overridden functions matches `BImpl` supertype
 * To resolve this ambiguity (which one choose, `A.foo` or `AImpl.foo`), we need to understand, which of those functions override
 * all other candidates (see [chooseMostSpecificOverridden] function) and leave only `AImpl.foo`
 */


@ ExperimentalNativeApi <EOL> public fun ByteArray . getUByteAt ( index : Int ) : UByte

= UByte ( get ( index ) )

/**
 * Gets [UByte] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . getCharAt ( index : Int ) : Char

/**
 * Gets [Char] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . getShortAt ( index : Int ) : Short

/**
 * Gets [Short] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public external fun ByteArray . getUShortAt ( index : Int ) : UShort

/**
 * Gets [UShort] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . getIntAt ( index : Int ) : Int

/**
 * Gets [Int] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public external fun ByteArray . getUIntAt ( index : Int ) : UInt

/**
 * Gets [UInt] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . getLongAt ( index : Int ) : Long

/**
 * Gets [Long] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public external fun ByteArray . getULongAt ( index : Int ) : ULong

/**
 * Gets [ULong] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . getFloatAt ( index : Int ) : Float

/**
 * Gets [Float] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . getDoubleAt ( index : Int ) : Double

/**
 * Gets [Double] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . setUByteAt ( index : Int , value : UByte )

/**
 * Sets [UByte] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . setCharAt ( index : Int , value : Char )

/**
 * Sets [Char] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . setShortAt ( index : Int , value : Short )

/**
 * Sets [Short] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public external fun ByteArray . setUShortAt ( index : Int , value : UShort )

/**
 * Sets [UShort] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . setIntAt ( index : Int , value : Int )

/**
 * Sets [Int] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . setUIntAt ( index : Int , value : UInt )

/**
 * Sets [UInt] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . setLongAt ( index : Int , value : Long )

/**
 * Sets [Long] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> @ ExperimentalUnsignedTypes <EOL> public external fun ByteArray . setULongAt ( index : Int , value : ULong )

/**
 * Sets [ULong] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . setFloatAt ( index : Int , value : Float )

/**
 * Sets [Float] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


@ ExperimentalNativeApi <EOL> @ GCUnsafeCall ( "<STR_LIT>" ) <EOL> public external fun ByteArray . setDoubleAt ( index : Int , value : Double )

/**
 * Sets [Double] out of the [ByteArray] byte buffer at specified index [index]
 * @throws IndexOutOfBoundsException if [index] is outside of array boundaries.
 */


fun getOutputLines ( withErrors : Boolean = false ) : List < String >

= <EOL> getResult ( withErrors , handleError = true ) . outputLines

/**
 * If withErrors is true then output from error stream will be added
 */


{ <EOL> return DefaultEvaluatedConstTracker ( ) <EOL> }

/**
 * Right now there are two places where we want to create this tracker.
 * 1. Right before `fir2ir` phase. We need to store evaluated values to use them later in const value serialization.
 * 2. In tests for K1 IR. This is needed ONLY for tests to log results of interpretation on lowering level.
 */


@ ExternalKotlinTargetApi <EOL> fun < T : DecoratedExternalKotlinCompilation > DecoratedExternalKotlinTarget . createCompilation ( descriptor : ExternalKotlinCompilationDescriptor < T > , ) : T

{ <EOL> val compilationImplFactory = KotlinCompilationImplFactory ( compilerOptionsFactory = when ( platformType ) { <EOL> KotlinPlatformType . common -> KotlinMultiplatformCommonCompilerOptionsFactory <EOL> KotlinPlatformType . jvm -> KotlinJvmCompilerOptionsFactory <EOL> KotlinPlatformType . androidJvm -> KotlinJvmCompilerOptionsFactory <EOL> KotlinPlatformType . js -> KotlinJsCompilerOptionsFactory <EOL> KotlinPlatformType . native -> KotlinNativeCompilerOptionsFactory <EOL> KotlinPlatformType . wasm -> KotlinMultiplatformCommonCompilerOptionsFactory <EOL> } , compilationSourceSetsContainerFactory = { _ , _ -> KotlinCompilationSourceSetsContainer ( descriptor . defaultSourceSet ) } , compilationTaskNamesContainerFactory = { target , compilationName -> <EOL> val default = DefaultKotlinCompilationTaskNamesContainerFactory . create ( target , compilationName ) <EOL> default . copy ( compileTaskName = descriptor . compileTaskName ? : default . compileTaskName , compileAllTaskName = descriptor . compileAllTaskName ? : default . compileAllTaskName ) <EOL> } , compilationAssociator = @ Suppress ( "<STR_LIT>" ) KotlinCompilationAssociator { _ , first , second -> <EOL> descriptor . compilationAssociator . associate ( first . decoratedInstance as T , second . decoratedInstance as DecoratedExternalKotlinCompilation ) <EOL> } , compilationFriendPathsResolver = DefaultKotlinCompilationFriendPathsResolver ( DefaultKotlinCompilationFriendPathsResolver . FriendArtifactResolver . composite ( DefaultKotlinCompilationFriendPathsResolver . DefaultFriendArtifactResolver , descriptor . friendArtifactResolver ? . let { declaredResolver -> <EOL> DefaultKotlinCompilationFriendPathsResolver . FriendArtifactResolver { compilation -> <EOL> @ Suppress ( "<STR_LIT>" ) <EOL> declaredResolver . resolveFriendPaths ( compilation . decoratedInstance as T ) <EOL> } <EOL> } ) ) ) <EOL> val compilationImpl = compilationImplFactory . create ( this , descriptor . compilationName ) <EOL> val decoratedCompilation = descriptor . compilationFactory . create ( Delegate ( compilationImpl ) ) <EOL> decoratedCompilation . sourceSetTreeClassifier = descriptor . sourceSetTreeClassifierV2 <EOL> ? : @ Suppress ( "<STR_LIT:DEPRECATION>" ) SourceSetTreeClassifierWrapper ( descriptor . sourceSetTreeClassifier ) <EOL> descriptor . configure ? . invoke ( decoratedCompilation ) <EOL> this . delegate . compilations . add ( decoratedCompilation ) <EOL> setupCompileTask ( decoratedCompilation ) <EOL> return decoratedCompilation <EOL> }

/**
 * Creates a compilation for External Kotlin Targets adhering to the configuration provided in the [descriptor]
 * - The _kind_ of compilation will be chosen automatically by the specified [DecoratedExternalKotlinTarget.platformType]
 * - The compilation will use the [ExternalKotlinCompilationDescriptor.defaultSourceSet] as its (default) source set
 * - The compilation wil reference the compile task using the [ExternalKotlinCompilationDescriptor.compileTaskName] if specified
 * - The compilation will reference the compile all task name using the[ExternalKotlinCompilationDescriptor.compileAllTaskName] if specified
 * - Compilations .associateWith calls will be handled by the [ExternalKotlinCompilationDescriptor.compilationAssociator] if specified
 * - An additional friendArtifactResolver will be respected if the [ExternalKotlinCompilationDescriptor.friendArtifactResolver] is specified
 * - The [ExternalKotlinCompilationDescriptor.configure] method will be called before the compilation is available in [KotlinTarget.compilations]
 * container
 */


@ ExternalKotlinTargetApi <EOL> fun < T : DecoratedExternalKotlinCompilation > DecoratedExternalKotlinTarget . createCompilation ( descriptor : ExternalKotlinCompilationDescriptorBuilder < T > . ( ) -> Unit , ) : T

{ <EOL> return createCompilation ( ExternalKotlinCompilationDescriptor ( descriptor ) ) <EOL> }


protected fun compareCallsByUsedArguments ( call1 : FlatSignature < Candidate > , call2 : FlatSignature < Candidate > , discriminateGenerics : Boolean , useOriginalSamTypes : Boolean ) : Boolean

{ <EOL> if ( discriminateGenerics ) { <EOL> val isGeneric1 = call1 . isGeneric <EOL> val isGeneric2 = call2 . isGeneric <EOL> if ( isGeneric1 && ! isGeneric2 ) return false <EOL> if ( ! isGeneric1 && isGeneric2 ) return true <EOL> if ( isGeneric1 && isGeneric2 ) return false <EOL> } <EOL> if ( call1 . contextReceiverCount > call2 . contextReceiverCount ) return true <EOL> if ( call1 . contextReceiverCount < call2 . contextReceiverCount ) return false <EOL> return createEmptyConstraintSystem ( ) . isSignatureNotLessSpecific ( call1 , call2 , SpecificityComparisonWithNumerics , specificityComparator , useOriginalSamTypes ) <EOL> }

/**
 * Returns `true` if [call1] is definitely more or equally specific [call2],
 * `false` otherwise.
 */


internal fun Project . launch ( start : CoroutineStart = CoroutineStart . Default , block : suspend KotlinPluginLifecycle . ( ) -> Unit , )

{ <EOL> kotlinPluginLifecycle . launch ( start , block ) <EOL> }

/**
 * Launches the given [block] as coroutine inside the Kotlin Gradle Plugin which allows to suspend execution of the code.
 * Intended use cases for suspensions are:
 *
 * #### Waiting for a given [KotlinPluginLifecycle.Stage]
 *
 * ```kotlin
 * project.launch {
 * // code
 * await(Stage.AfterEvaluate) // <- suspends
 * assertEquals(Stage.AfterEvaluate, stage)
 *
 * await(Stage.FinaliseDsl) // suspends
 * assertEquals(Stage.FinaliseDsl, stage)
 * // code
 * }
 * ```
 *
 * #### Waiting for some Gradle property to return a final value
 *
 * ```kotlin
 * project.launch {
 * val value = myProperty.awaitFinalValue() // <- suspends until final value is available!
 * }
 * ```
 *
 * #### Waiting for other suspending code in the Kotlin Gradle Plugin
 *
 * ```kotlin
 * project.launch {
 * // code
 * callMyOtherSuspendingFunction() // <- suspends
 * }
 * ```
 *
 * When launching a coroutine, the execution start of the [block] is not guaranteed.
 * It can be executed right away, effectively executing the [block] before this launch function returns
 * However, when called inside an already existing coroutine (or once Gradle has started executing afterEvaluate listeners),
 * then this block executed after this launch function returns and put at the end of the execution queue
 *
 * If the lifecycle already finished and Gradle moved to its execution phase, then the block will be invoked right away.
 */


internal fun Project . launchInStage ( stage : Stage , block : suspend KotlinPluginLifecycle . ( ) -> Unit )

{ <EOL> launch { <EOL> await ( stage ) <EOL> block ( ) <EOL> } <EOL> }

/**
 * See [launch] and [launchInRequiredStage]
 *
 * This is a shortcut to [launch] and immediately awaiting the specified [stage]:
 * @param block Is guaranteed to be executed *not before* [stage]. However, when this function is called in a higher stage then specified
 * the [block] will still be launched.
 */


internal fun Project . launchInRequiredStage ( stage : Stage , block : suspend KotlinPluginLifecycle . ( ) -> Unit )

{ <EOL> launchInStage ( stage ) { <EOL> requiredStage ( stage ) { <EOL> block ( ) <EOL> } <EOL> } <EOL> }

/**
 * See also [launch]
 *
 * Launches the given block in the specified lifecycle stage [stage].
 * It is guaranteed that [block] is only executed in the specified [stage]. Leaving the stage is forbidden.
 *
 * @throws IllegalLifecycleException if the [stage] was already executed or [block] tries to exit the required [stage]
 *
 * ```kotlin
 * project.launchInRequiredStage(Stage.BeforeFinaliseDsl) {
 * assertEquals(Stage.BeforeFinaliseDsl, stage) // guaranteed!
 * assertFails { await(Stage.FinaliseDsl) } // <- forbidden, as it tried to leave the required stage!
 * }
 * ```
 */


internal fun Project . startKotlinPluginLifecycle ( )

{ <EOL> ( kotlinPluginLifecycle as KotlinPluginLifecycleImpl ) . start ( ) <EOL> }

/**
 * Will start the lifecycle, this shall be called before the [kotlinPluginLifecycle] is effectively used
 */


internal suspend fun currentKotlinPluginLifecycle ( ) : KotlinPluginLifecycle

{ <EOL> return coroutineContext . kotlinPluginLifecycle <EOL> }

/**
 * Similar to [currentCoroutineContext]: Returns the current [KotlinPluginLifecycle] instance used to launch
 * the currently running coroutine. Throws if this coroutine was not started using a [KotlinPluginLifecycle]
 */


{ <EOL> currentKotlinPluginLifecycle ( ) . await ( this ) <EOL> }

/**
 * Suspends execution until we *at least* reached the specified [this@await]
 * This will return right away if the specified [this@await] was already executed or we are currently executing the [this@await]
 */


internal suspend fun < T : Any > Property < T > . awaitFinalValue ( ) : T ?

{ <EOL> Stage . AfterFinaliseDsl . await ( ) <EOL> finalizeValue ( ) <EOL> return orNull <EOL> }

/**
 * Will suspend until [Stage.FinaliseDsl], finalise the value using [Property.finalizeValue] and return the
 * final value.
 */


internal suspend fun < T : Any > Property < T > . awaitFinalValueOrThrow ( ) : T

{ <EOL> Stage . AfterFinaliseDsl . await ( ) <EOL> finalizeValue ( ) <EOL> return orNull ? : throw IllegalLifecycleException ( "<STR_LIT>" ) <EOL> }

/**
 * Will suspend until [Stage.FinaliseDsl], finalise the value using [Property.finalizeValue] and return the
 * final value or throw if value wasn't set.
 */


internal suspend fun < T > requiredStage ( stage : Stage , block : suspend ( ) -> T ) : T

{ <EOL> if ( currentKotlinPluginLifecycle ( ) . stage < stage ) stage . await ( ) <EOL> return withRestrictedStages ( hashSetOf ( stage ) , block ) <EOL> }

/**
 * See also [withRestrictedStages]
 *
 * Will ensure that the given [block] can only execute in the given [stage]
 * Will wait for the given [stage] if not arrived yet
 */


internal suspend fun < T > requireCurrentStage ( block : suspend ( ) -> T ) : T

{ <EOL> return requiredStage ( currentKotlinPluginLifecycle ( ) . stage , block ) <EOL> }

/**
 * See also [withRestrictedStages]
 *
 * Will ensure that the given [block] cannot leave the current stage
 * e.g.
 *
 * ```kotlin
 * project.launch {
 * requireCurrentStage {
 * await(stage.nextOrThrow) // <- fails! We are not allowed to switch stages!
 * }
 * }
 * ```
 */


{ <EOL> runImageRecognitionPrediction ( ONNXModels . CV . ResNet18 ) <EOL> }

/**
 * This examples demonstrates the inference concept on ResNet'18 model:
 * - Model configuration, model weights and labels are obtained from [ONNXModelHub].
 * - Model predicts on a few images located in resources.
 * - Special preprocessing (used in ResNet'18 during training on ImageNet dataset) is applied to each image before prediction.
 */


= resnet18prediction ( )


private fun fetchSourceFileMetadata ( srcFile : KotlinSourceFile , loadSignatures : Boolean )

= <EOL> kotlinLibrarySourceFileMetadata . getOrPut ( srcFile ) { <EOL> val deserializer = idSignatureSerialization . getIdSignatureDeserializer ( srcFile ) <EOL> fun < T > CodedInputStream . readDependencies ( signaturesReader : ( ) -> T ) = buildMapUntil ( readInt32 ( ) ) { <EOL> val libFile = KotlinLibraryFile . fromProtoStream ( this @ readDependencies ) <EOL> val depends = buildMapUntil ( readInt32 ( ) ) { <EOL> val dependencySrcFile = KotlinSourceFile . fromProtoStream ( this @ readDependencies ) <EOL> put ( dependencySrcFile , signaturesReader ( ) ) <EOL> } <EOL> put ( libFile , depends ) <EOL> } <EOL> fun CodedInputStream . readDirectDependencies ( ) = readDependencies { <EOL> if ( loadSignatures ) { <EOL> buildMapUntil ( readInt32 ( ) ) { <EOL> val signature = deserializer . deserializeIdSignature ( this @ readDirectDependencies ) <EOL> put ( signature , ICHash . fromProtoStream ( this @ readDirectDependencies ) ) <EOL> } <EOL> } else { <EOL> repeat ( readInt32 ( ) ) { <EOL> deserializer . skipIdSignature ( this @ readDirectDependencies ) <EOL> ICHash . fromProtoStream ( this @ readDirectDependencies ) <EOL> } <EOL> emptyMap ( ) <EOL> } <EOL> } <EOL> fun CodedInputStream . readInverseDependencies ( ) = readDependencies { <EOL> if ( loadSignatures ) { <EOL> buildSetUntil ( readInt32 ( ) ) { add ( deserializer . deserializeIdSignature ( this @ readInverseDependencies ) ) } <EOL> } else { <EOL> repeat ( readInt32 ( ) ) { deserializer . skipIdSignature ( this @ readInverseDependencies ) } <EOL> emptySet ( ) <EOL> } <EOL> } <EOL> srcFile . getCacheFile ( METADATA_SUFFIX ) . useCodedInputIfExists { <EOL> val directDependencies = KotlinSourceFileMap ( readDirectDependencies ( ) ) <EOL> val reverseDependencies = KotlinSourceFileMap ( readInverseDependencies ( ) ) <EOL> KotlinSourceFileMetadataFromDisk ( reverseDependencies , directDependencies ) <EOL> } ? : KotlinSourceFileMetadataNotExist <EOL> }

/**
 * Fetches cached data for a specific [srcFile].
 *
 * @param loadSignatures
 * If false, it loads only file names for the (direct and inverse) dependencies.
 * If true, it also loads the declaration signatures [IdSignature] and declaration hashes [ICHash] for every dependency.
 *
 * Note that if the file is modified or removed, the signatures cannot be loaded, and [loadSignatures] must be false.
 * This is because [IdSignatureSerialization] uses declaration indexes from the klib for serialization and deserialization.
 * If the file is modified, the indexes can be modified (for example, shifted) too, leading to incorrect deserialization.
 */


fun JupyterIntegration . Builder . resources ( block : ResourcesBuilder . ( ) -> Unit )

{ <EOL> val resources = ResourcesBuilder ( notebook . loggerFactory ) . apply ( block ) <EOL> resources . resources . forEach { <EOL> resource ( it ) <EOL> } <EOL> }

/**
 * Build a resource tree using [ResourcesBuilder]. The builder allows to construct `js` and `css` bundles. Each bundle
 * could contain multiple files or urls. Each of those could contain multiple fallback paths (for example if URL not
 * found, local resource is used.
 */


@ OptIn ( ExperimentalStdlibApi :: class ) <EOL> fun url ( url : String , localFallBack : String ? = null , classpathFallBack : String ? = null , embed : Boolean = false , )

{ <EOL> val libraryResource = <EOL> ResourceFallbacksBundle ( buildList { <EOL> if ( embed ) { <EOL> add ( ResourceLocation ( url , ResourcePathType . URL_EMBEDDED ) ) <EOL> } else { <EOL> add ( ResourceLocation ( url , ResourcePathType . URL ) ) <EOL> } <EOL> localFallBack ? . let { <EOL> checkLocalPath ( localFallBack ) <EOL> add ( ResourceLocation ( localFallBack , ResourcePathType . LOCAL_PATH ) ) <EOL> } <EOL> classpathFallBack ? . let { <EOL> add ( ResourceLocation ( classpathFallBack , ResourcePathType . CLASSPATH_PATH ) ) <EOL> } <EOL> } , ) <EOL> bundles . add ( libraryResource ) <EOL> }

/**
 * Create an url resource with optional embedding (governed by [embed] flag) with optional local file fallback
 * and a class-path fallback. If fallbacks are null, they are not used.
 */


{ <EOL> checkLocalPath ( localPath ) <EOL> bundles . add ( ResourceFallbacksBundle ( listOf ( ResourceLocation ( localPath , ResourcePathType . LOCAL_PATH ) ) , ) , ) <EOL> }


{ <EOL> bundles . add ( ResourceFallbacksBundle ( listOf ( ResourceLocation ( classPath , ResourcePathType . CLASSPATH_PATH ) ) , ) , ) <EOL> }


fun js ( name : String , block : BundleBuilder . ( ) -> Unit , )

{ <EOL> val bundles = BundleBuilder ( ) . apply ( block ) . bundles <EOL> resources . add ( LibraryResource ( name = name , type = ResourceType . JS , bundles = bundles , ) , ) <EOL> }


fun css ( name : String , block : BundleBuilder . ( ) -> Unit , )

{ <EOL> val bundles = BundleBuilder ( ) . apply ( block ) . bundles <EOL> resources . add ( LibraryResource ( name = name , type = ResourceType . CSS , bundles = bundles , ) , ) <EOL> }


protected abstract fun getTypeSystemContext ( session : Session ) : TypeSystemContext

/**
 * The type system to use to query properties of types, type parameters and type arguments.
 */


protected open fun Declaration . visitParentForFunctionMangling ( )

{ <EOL> visitParent ( ) <EOL> }

/**
 * Like [visitParent], but may have some logic that makes it suitable specifically for mangling function names.
 */


protected abstract fun Declaration . asTypeParameterContainer ( ) : TypeParameterContainer ?

/**
 * Simply attempts to cast [Declaration] to [TypeParameterContainer].
 */


protected abstract fun renderDeclaration ( declaration : Declaration ) : String

/**
 * Used to show a meaningful exception message.
 */


= buffer . rowsCount ( )

/**
 * Gets the count of rows in the current buffer.
 *
 * @return Number of rows in the buffer.
 */


{ <EOL> return if ( isGrouped ) { <EOL> GroupedData ( buffer , groupKeys ! ! ) <EOL> } else { <EOL> NamedData ( buffer ) <EOL> } <EOL> }

/**
 * Retrieves the dataset as [TableData].
 * If the dataset is grouped, it returns a [GroupedData], otherwise, a [NamedData] is returned.
 *
 * @return The dataset represented as [TableData].
 */


public fun takeColumn ( name : String ) : String

{ <EOL> return referredColumns [ name ] ? : run { <EOL> val columnId = internalAddColumn ( initialNamedData . dataFrame . getColumnOrNull ( name ) ? : error ( "<STR_LIT>" ) ) <EOL> referredColumns [ name ] = columnId <EOL> name <EOL> } <EOL> }

/**
 * Attempts to fetch a column by its name.
 * If not present, the column is retrieved from the initial dataset and added to the internal buffer.
 *
 * @param name Name of the column.
 * @return Name of the retrieved column.
 */


public fun addColumn ( column : ColumnReference < * > ) : String

{ <EOL> return if ( column is DataColumn < * > ) { <EOL> internalAddColumn ( column ) <EOL> } else takeColumn ( column . name ( ) ) <EOL> }

/**
 * Adds a column to the dataset.
 * Depending on the nature of the reference and the `columnAsRefOnly` flag,
 * it either directly adds the column or treats it as a reference.
 *
 * @param column The column to be added, represented as [ColumnReference].
 * @return The name of the added column.
 */


public fun addColumn ( values : List < * > , name : String ) : String

{ <EOL> val columnId = internalAddColumn ( DataColumn . createValueColumn ( name , values , Infer . Type ) ) <EOL> referredColumns [ name ] = columnId <EOL> return internalAddColumn ( DataColumn . createValueColumn ( name , values , Infer . Type ) ) <EOL> }

/**
 * Directly adds a column with specified values and name to the dataset.
 * Useful for adding custom columns not present in the initial dataset.
 *
 * @param values A list of values for the column.
 * @param name Name for the column.
 * @return The name of the added column.
 */


{ <EOL> return when ( i ) { <EOL> <NUM_LIT:1> -> ByteDataType <EOL> <NUM_LIT:2> -> ShortDataType <EOL> <NUM_LIT:3> -> IntDataType <EOL> <NUM_LIT:4> -> LongDataType <EOL> <NUM_LIT:5> -> FloatDataType <EOL> <NUM_LIT:6> -> DoubleDataType <EOL> <NUM_LIT:7> -> ComplexFloatDataType <EOL> <NUM_LIT:8> -> ComplexDoubleDataType <EOL> else -> throw IllegalStateException ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Returns [DataType] by [nativeCode].
 */


public inline fun < T > of ( element : T ) : DataType

{ <EOL> element ? : throw IllegalStateException ( "<STR_LIT>" ) <EOL> return dataTypeOf ( element ! ! :: class ) <EOL> }

/**
 * Returns [DataType] by class of [element].
 */


public inline fun < T : Any > ofKClass ( type : KClass < out T > ) : DataType

= dataTypeOf ( type )

/**
 * Returns [DataType] by [KClass] of [type]. [T] is `reified` type.
 */


public fun < A , B > convert ( from : KType , to : KType , converter : ( A ) -> B )

/**
 * Defines how to convert [from]: [A] to [to]: [B].
 *
 * Note: In most cases using `convert<Type>().with { }` is more convenient, however
 * if you only have [KType], this method can be used.
 */


public fun convertIf ( condition : ( fromType : KType , toSchema : ColumnSchema ) -> Boolean , converter : ConverterScope . ( Any ? ) -> Any ? , )

/**
 * Advanced version of [convert].
 * If you want to define a common conversion for multiple types (or any type), or
 * you need extra information about the target, such as its schema, use this method.
 *
 * The exact type conversion does have higher priority. After that, this flexible conversions will be checked
 * in order.
 *
 * @param condition a function that should return `true` if the conversion should be applied from the given `fromType`
 * to the given `toSchema`.
 * @param converter a function that performs the conversion with access to a [ConverterScope].
 */


public inline fun < T , reified C > ConvertSchemaDsl < T > . fill ( noinline columns : ColumnsSelector < T , C > ) : ConvertToFill < T , C >

= ConvertToFill ( this , columns )

/**
 * Defines how to fill specified columns in destination schema that were not found in original dataframe.
 * All [fill] operations for missing columns are executed after successful conversion of matched columns, so converted values of matched columns can be safely used in [with] expression.
 * @param columns target columns in destination dataframe schema to be filled
 */


public inline fun < reified C > ConvertSchemaDsl < * > . parser ( noinline parser : ( String ) -> C ) : Unit

= <EOL> convert < String > ( ) . with ( parser )

/**
 * Defines how to convert `String` values into given type [C].
 */


public inline fun < reified C > ConvertSchemaDsl < * > . convert ( ) : ConvertType < C >

= ConvertType ( this , typeOf < C > ( ) )

/**
 * Defines how to convert values of given type [C]
 */


public inline fun < C , reified R > ConvertType < C > . with ( noinline converter : ( C ) -> R ) : Unit

= <EOL> dsl . convert ( from , typeOf < R > ( ) , converter )

/**
 * Defines how to convert values of type [C] into type [R]
 */


public inline fun < reified T : Any > AnyFrame . convertTo ( excessiveColumnsBehavior : ExcessiveColumns = ExcessiveColumns . Keep , noinline body : ConvertSchemaDsl < T > . ( ) -> Unit = { } ) : DataFrame < T >

= convertToImpl ( typeOf < T > ( ) , true , excessiveColumnsBehavior , body ) . cast ( )

/**
 * Converts values in [DataFrame] to match given column schema [T].
 *
 * Original columns are mapped to destination columns by column [path][DataColumn.path].
 *
 * Type converters for every column are selected automatically. See [convert] operation for details.
 *
 * To specify custom type converters for the particular types use [ConvertSchemaDsl].
 *
 * Example of Dsl:
 * ```kotlin
 * df.convertTo<SomeSchema> {
 * // defines how to convert Int? -> String
 * convert<Int?>().with { it?.toString() ?: "No input given" }
 * // defines how to convert String -> SomeType
 * parser { SomeType(it) }
 * // fill missing column `sum` with expression `a + b`
 * fill { sum }.with { a + b }
 * }
 * ```
 *
 * @param [T] class that defines target schema for conversion.
 * @param [excessiveColumnsBehavior] how to handle excessive columns in the original [DataFrame].
 * @param [body] optional dsl to define custom type converters.
 * @throws [ColumnNotFoundException] if [DataFrame] doesn't contain columns that are required by destination schema.
 * @throws [ExcessiveColumnsException] if [DataFrame] contains columns that are not required by destination schema and [excessiveColumnsBehavior] is set to [ExcessiveColumns.Fail].
 * @throws [TypeConverterNotFoundException] if suitable type converter for some column was not found.
 * @throws [TypeConversionException] if type converter failed to convert column values.
 * @return converted [DataFrame].
 */


public fun AnyFrame . convertTo ( schemaType : KType , excessiveColumnsBehavior : ExcessiveColumns = ExcessiveColumns . Keep , body : ConvertSchemaDsl < Any > . ( ) -> Unit = { } , ) : AnyFrame

= convertToImpl ( schemaType , true , excessiveColumnsBehavior , body )

/**
 * Converts values in [DataFrame] to match given column schema [schemaType].
 *
 * Original columns are mapped to destination columns by column [path][DataColumn.path].
 *
 * Type converters for every column are selected automatically. See [convert] operation for details.
 *
 * To specify custom type converters for the particular types use [ConvertSchemaDsl].
 *
 * Example of Dsl:
 * ```kotlin
 * df.convertTo<SomeSchema> {
 * // defines how to convert Int? -> String
 * convert<Int?>().with { it?.toString() ?: "No input given" }
 * // defines how to convert String -> SomeType
 * parser { SomeType(it) }
 * // fill missing column `sum` with expression `a+b`
 * fill { sum }.with { a + b }
 * }
 * ```
 *
 * @param [schemaType] defines target schema for conversion.
 * @param [excessiveColumnsBehavior] how to handle excessive columns in the original [DataFrame].
 * @param [body] optional dsl to define custom type converters.
 * @throws [ColumnNotFoundException] if [DataFrame] doesn't contain columns that are required by destination schema.
 * @throws [ExcessiveColumnsException] if [DataFrame] contains columns that are not required by destination schema and [excessiveColumnsBehavior] is set to [ExcessiveColumns.Fail].
 * @throws [TypeConverterNotFoundException] if suitable type converter for some column was not found.
 * @throws [TypeConversionException] if type converter failed to convert column values.
 * @return converted [DataFrame].
 */


fun < T1 > EmptyTuple . appendedBy ( other : T1 ) : Tuple1 < T1 >

= Tuple1 < T1 > ( other )

/**
 * This file provides functions to easily extend Scala Tuples.
 *
 * This means you can easily create a new tuple appended-, or prepended by a new value or tuple.
 *
 * For example (using tupleOf() to create a new tuple):
 * ```tupleOf(a, b).appendedBy(c) == tupleOf(a, b, c)```
 * and
 * ```tupleOf(a, b).prependedBy(c) == tupleOf(c, a, b)```
 *
 * or in shorthand:
 * ```tupleOf(a, b) + c == tupleOf(a, b, c)```
 * and
 * ```c + tupleOf(a, b) == tupleOf(c, a, b)```
 *
 * Note that ```tupleOf(a, b) + tupleOf(c, d)``` will merge the two into ```tupleOf(a, b, c, d)```:
 * If you mean to create ```tupleOf(a, b, tupleOf(c, d))``` or ```tupleOf(tupleOf(a, b), c, d)```,
 * use [appendedBy] and [prependedBy] explicitly.
 *
 * Note that [String.plus] concatenates any object to the string, so prepending it like ```myString + myTuple``` won't work.
 *
 * For concatenating two tuples, see [org.jetbrains.kotlinx.spark.api.tuples.concat].
 *
 */


{ <EOL> val ( train , _ ) = fashionMnist ( ) <EOL> val inferenceModel = TensorFlowInferenceModel . load ( File ( PATH_TO_MODEL ) , loadOptimizerState = true ) <EOL> inferenceModel . use { <EOL> var accuracy = <NUM_LIT:0.0> <EOL> val amountOfTestSet = <NUM_LIT> <EOL> for ( imageId in <NUM_LIT:0> .. amountOfTestSet ) { <EOL> val prediction = it . predict ( train . getX ( imageId ) ) <EOL> if ( prediction == train . getY ( imageId ) . toInt ( ) ) <EOL> accuracy += ( <NUM_LIT:1.0> / amountOfTestSet ) <EOL> } <EOL> println ( "<STR_LIT>" ) <EOL> val amountOfOps = <NUM_LIT> <EOL> val start = System . currentTimeMillis ( ) <EOL> for ( i in <NUM_LIT:0> .. amountOfOps ) { <EOL> it . predict ( train . getX ( i % <NUM_LIT> ) ) <EOL> } <EOL> println ( "<STR_LIT>" ) <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Inference model is used here, separately from model training code to illustrate the ability to load model graph and weights to start prediction process.
 *
 * NOTE: The example requires the saved model in the appropriate directory (run [lenetOnFashionMnistExportImportToTxt] firstly).
 */


public fun EchartsLayerContext . markPoint ( block : MarkPointContext . ( ) -> Unit )

{ <EOL> layerFeatures [ MarkPointFeature . FEATURE_NAME ] = MarkPointContext ( ) . apply ( block ) . toMarkPointFeature ( ) <EOL> }

/**
 * Sets mark points on a layer.
 *
 * - [points][MarkPointContext.points] - list of [mark point][MarkPoint]
 *
 * ```kotlin
 * plot {
 * line {
 * markPoint {
 * points = listOf(MarkPoint("avg", MarkType.AVERAGE), MarkPoint(coord = 1.5 to 2.0, value = "2"))
 * }
 * }
 * }
 * ```
 *
 * @see MarkPoint
 */


public fun EchartsLayerContext . markLine ( block : MarkLineContext . ( ) -> Unit )

{ <EOL> layerFeatures [ MarkLineFeature . FEATURE_NAME ] = MarkLineContext ( ) . apply ( block ) . toMarkLineFeature ( ) <EOL> }

/**
 * Sets mark lines on a layer.
 *
 * - [points][MarkLineContext.lines] - list of [mark line][MarkLine]
 *
 * ```kotlin
 * plot {
 * line {
 * markLine {
 * lines = listOf(
 * MarkLine("max", MarkType.MAX),
 * MarkLine("two points", MarkPoint(MarkType.MIN), MarkPoint(5, 3))
* )
 * }
 * }
 * }
 * ```
 *
 * @see MarkLine
 */


public fun EchartsLayerContext . markArea ( block : MarkAreaContext . ( ) -> Unit )

{ <EOL> layerFeatures [ MarkAreaFeature . FEATURE_NAME ] = MarkAreaContext ( ) . apply ( block ) . toMarkAreaFeature ( ) <EOL> }

/**
 * Sets mark areas on a layer.
 *
 * - [points][MarkAreaContext.areas] - list of [mark area][MarkArea]
 *
 * ```kotlin
 * plot {
 * line {
 * markArea {
 * areas = listOf(MarkArea("area", MarkPoint(MarkType.MIN), MarkPoint(MarkType.MAX)))
 * }
 * }
 * }
 * ```
 *
 * @see MarkArea
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun assert ( value : Boolean )

{ <EOL> assert ( value ) { "<STR_LIT>" } <EOL> }

/**
 * Throws an [AssertionError] if the [value] is false
 * and runtime assertions have been enabled on the JVM using the *-ea* JVM option.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun assert ( value : Boolean , lazyMessage : ( ) -> Any )

{ <EOL> if ( _Assertions . ENABLED ) { <EOL> if ( ! value ) { <EOL> val message = lazyMessage ( ) <EOL> throw AssertionError ( message ) <EOL> } <EOL> } <EOL> }

/**
 * Throws an [AssertionError] calculated by [lazyMessage] if the [value] is false
 * and runtime assertions have been enabled on the JVM using the *-ea* JVM option.
 */


{ <EOL> gameState . sceneState . initialized = true <EOL> previous = Vector2 . Zero <EOL> }

/**
 * To be called when the screen gets touched.
 */


{ <EOL> val delta = total - previous <EOL> if ( delta . length < <NUM_LIT> ) return <EOL> previous = total <EOL> val ( axis , angle ) = movementToRotation ( delta ) <EOL> gameState . manualRotate ( axis , angle ) <EOL> }

/**
 * To be called when finger moves;
 *
 * @param total the vector from the point where the screen have got touched to the current one.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> public actual fun < T : Comparable < T > > maxOf ( a : T , b : T ) : T

{ <EOL> return if ( a >= b ) a else b <EOL> }

/**
 * Returns the greater of two values.
 *
 * If values are equal, returns the first one.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun maxOf ( a : Byte , b : Byte ) : Byte

{ <EOL> return maxOf ( a . toInt ( ) , b . toInt ( ) ) . unsafeCast < Byte > ( ) <EOL> }

/**
 * Returns the greater of two values.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun maxOf ( a : Short , b : Short ) : Short

{ <EOL> return maxOf ( a . toInt ( ) , b . toInt ( ) ) . unsafeCast < Short > ( ) <EOL> }


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun maxOf ( a : Int , b : Int ) : Int

{ <EOL> return JsMath . max ( a , b ) <EOL> }


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ Suppress ( "<STR_LIT:NOTHING_TO_INLINE>" ) <EOL> public actual inline fun maxOf ( a : Long , b : Long ) : Long


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun maxOf ( a : Float , b : Float ) : Float

/**
 * Returns the greater of two values.
 *
 * If either value is `NaN`, returns `NaN`.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun maxOf ( a : Double , b : Double ) : Double


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> public actual fun < T : Comparable < T > > maxOf ( a : T , b : T , c : T ) : T

{ <EOL> return maxOf ( a , maxOf ( b , c ) ) <EOL> }

/**
 * Returns the greater of three values.
 *
 * If there are multiple equal maximal values, returns the first of them.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun maxOf ( a : Byte , b : Byte , c : Byte ) : Byte

{ <EOL> return JsMath . max ( a . toInt ( ) , b . toInt ( ) , c . toInt ( ) ) . unsafeCast < Byte > ( ) <EOL> }

/**
 * Returns the greater of three values.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun maxOf ( a : Short , b : Short , c : Short ) : Short

{ <EOL> return JsMath . max ( a . toInt ( ) , b . toInt ( ) , c . toInt ( ) ) . unsafeCast < Short > ( ) <EOL> }


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun maxOf ( a : Int , b : Int , c : Int ) : Int

{ <EOL> return JsMath . max ( a , b , c ) <EOL> }


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun maxOf ( a : Long , b : Long , c : Long ) : Long


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun maxOf ( a : Float , b : Float , c : Float ) : Float

/**
 * Returns the greater of three values.
 *
 * If any value is `NaN`, returns `NaN`.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun maxOf ( a : Double , b : Double , c : Double ) : Double


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun < T : Comparable < T > > maxOf ( a : T , vararg other : T ) : T

{ <EOL> var max = a <EOL> for ( e in other ) max = maxOf ( max , e ) <EOL> return max <EOL> }

/**
 * Returns the greater of the given values.
 *
 * If there are multiple equal maximal values, returns the first of them.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun maxOf ( a : Byte , vararg other : Byte ) : Byte

/**
 * Returns the greater of the given values.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun maxOf ( a : Short , vararg other : Short ) : Short


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun maxOf ( a : Int , vararg other : Int ) : Int


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun maxOf ( a : Long , vararg other : Long ) : Long


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun maxOf ( a : Float , vararg other : Float ) : Float

/**
 * Returns the greater of the given values.
 *
 * If any value is `NaN`, returns `NaN`.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun maxOf ( a : Double , vararg other : Double ) : Double


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> public actual fun < T : Comparable < T > > minOf ( a : T , b : T ) : T

{ <EOL> return if ( a <= b ) a else b <EOL> }

/**
 * Returns the smaller of two values.
 *
 * If values are equal, returns the first one.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun minOf ( a : Byte , b : Byte ) : Byte

{ <EOL> return minOf ( a . toInt ( ) , b . toInt ( ) ) . unsafeCast < Byte > ( ) <EOL> }

/**
 * Returns the smaller of two values.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun minOf ( a : Short , b : Short ) : Short

{ <EOL> return minOf ( a . toInt ( ) , b . toInt ( ) ) . unsafeCast < Short > ( ) <EOL> }


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun minOf ( a : Int , b : Int ) : Int

{ <EOL> return JsMath . min ( a , b ) <EOL> }


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ Suppress ( "<STR_LIT:NOTHING_TO_INLINE>" ) <EOL> public actual inline fun minOf ( a : Long , b : Long ) : Long


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun minOf ( a : Float , b : Float ) : Float

/**
 * Returns the smaller of two values.
 *
 * If either value is `NaN`, returns `NaN`.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun minOf ( a : Double , b : Double ) : Double


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> public actual fun < T : Comparable < T > > minOf ( a : T , b : T , c : T ) : T

{ <EOL> return minOf ( a , minOf ( b , c ) ) <EOL> }

/**
 * Returns the smaller of three values.
 *
 * If there are multiple equal minimal values, returns the first of them.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun minOf ( a : Byte , b : Byte , c : Byte ) : Byte

{ <EOL> return JsMath . min ( a . toInt ( ) , b . toInt ( ) , c . toInt ( ) ) . unsafeCast < Byte > ( ) <EOL> }

/**
 * Returns the smaller of three values.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun minOf ( a : Short , b : Short , c : Short ) : Short

{ <EOL> return JsMath . min ( a . toInt ( ) , b . toInt ( ) , c . toInt ( ) ) . unsafeCast < Short > ( ) <EOL> }


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun minOf ( a : Int , b : Int , c : Int ) : Int

{ <EOL> return JsMath . min ( a , b , c ) <EOL> }


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun minOf ( a : Long , b : Long , c : Long ) : Long


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun minOf ( a : Float , b : Float , c : Float ) : Float

/**
 * Returns the smaller of three values.
 *
 * If any value is `NaN`, returns `NaN`.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun minOf ( a : Double , b : Double , c : Double ) : Double


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun < T : Comparable < T > > minOf ( a : T , vararg other : T ) : T

{ <EOL> var min = a <EOL> for ( e in other ) min = minOf ( min , e ) <EOL> return min <EOL> }

/**
 * Returns the smaller of the given values.
 *
 * If there are multiple equal minimal values, returns the first of them.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun minOf ( a : Byte , vararg other : Byte ) : Byte

/**
 * Returns the smaller of the given values.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun minOf ( a : Short , vararg other : Short ) : Short


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun minOf ( a : Int , vararg other : Int ) : Int


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun minOf ( a : Long , vararg other : Long ) : Long


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun minOf ( a : Float , vararg other : Float ) : Float

/**
 * Returns the smaller of the given values.
 *
 * If any value is `NaN`, returns `NaN`.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public actual fun minOf ( a : Double , vararg other : Double ) : Double


public fun summary ( ) : ModelSummary

/**
 * Returns model summary.
 *
 * @return model summary
 */


{ <EOL> if ( ! _targets . remove ( target ) ) { <EOL> return <EOL> } <EOL> topLevelDeclaration . remove ( target ) <EOL> }

/**
 * Remove the [target] from this dump.
 * If some declaration was declared only for [target], it will be removed from the dump.
 */


fun retainTargetSpecificAbi ( target : KlibTarget )

{ <EOL> if ( ! _targets . contains ( target ) ) { <EOL> _targets . clear ( ) <EOL> topLevelDeclaration . children . clear ( ) <EOL> topLevelDeclaration . targets . clear ( ) <EOL> return <EOL> } <EOL> topLevelDeclaration . retainSpecific ( target , _targets ) <EOL> _targets . retainAll ( setOf ( target ) ) <EOL> }

/**
 * Leave only declarations specific to a [target].
 * A declaration is considered target-specific if:
 * 1) it defined for some [targets] subset including [target], but not for all [targets];
 * 2) it defined for all [targets], but contains target-specific child declaration.
 */


{ <EOL> topLevelDeclaration . retainCommon ( _targets ) <EOL> if ( topLevelDeclaration . children . isEmpty ( ) ) { <EOL> _targets . clear ( ) <EOL> } <EOL> }

/**
 * Remove all declarations that are not defined for all [KlibAbiDumpMerger.targets].
 */


fun mergeTargetSpecific ( other : KlibAbiDumpMerger )

{ <EOL> require ( other . _targets . size == <NUM_LIT:1> ) { <EOL> "<STR_LIT>" <EOL> } <EOL> require ( other . _targets . first ( ) !in _targets ) { <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" <EOL> } <EOL> _targets . addAll ( other . _targets ) <EOL> topLevelDeclaration . mergeTargetSpecific ( other . topLevelDeclaration ) <EOL> }

/**
 * Merge the [other] dump containing declarations for a single target into this dump.
 * The dump [other] should contain exactly one target and this dump should not contain that target.
 */


{ <EOL> if ( other . targets . isEmpty ( ) ) return <EOL> targets . intersect ( other . targets ) . also { <EOL> require ( it . isEmpty ( ) ) { <EOL> "<STR_LIT>" <EOL> } <EOL> } <EOL> if ( headerContent != other . headerContent ) { <EOL> if ( headerContent . isEmpty ( ) && targets . isEmpty ( ) ) { <EOL> headerContent . addAll ( other . headerContent ) <EOL> } else { <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> _targets . addAll ( other . _targets ) <EOL> topLevelDeclaration . merge ( other . topLevelDeclaration ) <EOL> }

/**
 * Merges other [KlibAbiDumpMerger] into this one.
 */


fun overrideTargets ( targets : Set < KlibTarget > )

{ <EOL> _targets . clear ( ) <EOL> _targets . addAll ( targets ) <EOL> topLevelDeclaration . overrideTargets ( targets ) <EOL> }

/**
 * For each declaration change targets to a specified [targets] set.
 */


{ <EOL> if ( parent != null && ! targets . contains ( target ) ) { <EOL> return <EOL> } <EOL> targets . remove ( target ) <EOL> mutateChildrenAndRemoveTargetless { it . remove ( target ) } <EOL> }


{ <EOL> this . targets . clear ( ) <EOL> this . targets . addAll ( targets ) <EOL> children . forEach { it . value . overrideTargets ( targets ) } <EOL> }


public fun isScalar ( ) : Boolean

/**
 * Returns `true` if the array contains only one element, otherwise `false`.
 */


public fun isEmpty ( ) : Boolean

/**
 * Returns `true` if this ndarray is empty.
 */


public fun isNotEmpty ( ) : Boolean

/**
 * Returns `true` if this ndarray is not empty.
 */


public fun copy ( ) : MultiArray < T , D >

/**
 * Returns new [MultiArray] which is a copy of the original ndarray.
 */


public fun deepCopy ( ) : MultiArray < T , D >

/**
 * Returns new [MultiArray] which is a deep copy of the original ndarray.
 */


public fun flatten ( ) : MultiArray < T , D1 >

/**
 * Returns new one-dimensional ndarray which is a copy of the original ndarray.
 */


public fun reshape ( dim1 : Int ) : MultiArray < T , D1 >

/**
 * Returns an ndarray with a new ([dim1]) shape without changing data.
 */


public fun reshape ( dim1 : Int , dim2 : Int ) : MultiArray < T , D2 >

/**
 * Returns an ndarray with a new ([dim1], [dim2]) shape without changing data.
 */


public fun reshape ( dim1 : Int , dim2 : Int , dim3 : Int ) : MultiArray < T , D3 >

/**
 * Returns an ndarray with a new ([dim1], [dim2], [dim3]) shape without changing data.
 */


public fun reshape ( dim1 : Int , dim2 : Int , dim3 : Int , dim4 : Int ) : MultiArray < T , D4 >

/**
 * Returns an ndarray with a new ([dim1], [dim2], [dim3], [dim4]) shape without changing data.
 */


public fun reshape ( dim1 : Int , dim2 : Int , dim3 : Int , dim4 : Int , vararg dims : Int ) : MultiArray < T , DN >

/**
 * Returns an ndarray with a new ([dim1], [dim2], [dim3], [dim4], [dims]) shape without changing data.
 */


public fun transpose ( vararg axes : Int ) : MultiArray < T , D >

/**
 * Reverse or permute the [axes] of an array.
 */


public fun squeeze ( vararg axes : Int ) : MultiArray < T , DN >

/**
 * Returns an ndarray with all axes removed equal to one.
 */


public fun unsqueeze ( vararg axes : Int ) : MultiArray < T , DN >

/**
 * Returns a new ndarray with a dimension of size one inserted at the specified [axes].
 */


public infix fun cat ( other : MultiArray < T , D > ) : NDArray < T , D >

/**
 * Concatenates this ndarray with [other].
 */


public fun cat ( other : MultiArray < T , D > , axis : Int = <NUM_LIT:0> ) : NDArray < T , D >

/**
 * Concatenates this ndarray with [other] along the specified [axis].
 */


public fun cat ( other : List < MultiArray < T , D > > , axis : Int = <NUM_LIT:0> ) : NDArray < T , D >

/**
 * Concatenates this ndarray with a list of [other] ndarrays.
 */


private fun readKlibUniqNameFromManifest ( ) : String

{ <EOL> val konanHome = compilerDistributionPath . get ( ) . absolutePath <EOL> val resolver = defaultResolver ( repositories = emptyList ( ) , directLibs = emptyList ( ) , target = PlatformManager ( konanHome ) . targetByName ( target ) , distribution = Distribution ( konanHome ) , logger = object : Logger { <EOL> override fun log ( message : String ) = logger . info ( message ) <EOL> override fun warning ( message : String ) = logger . warn ( message ) <EOL> override fun error ( message : String ) : Unit = logger . error ( message ) <EOL> override fun fatal ( message : String ) : Nothing = kotlin . error ( message ) <EOL> } ) <EOL> return resolver . resolve ( originalKlib . asFile . get ( ) . absolutePath ) . uniqueName <EOL> }

/**
 * Note: we can't use this function instead of [klibUniqName] in [cacheFile],
 * because the latter is `@OutputDirectory`, so Gradle can call it even before
 * the task dependencies are finished, and [originalKlib] might be not build yet.
 */


public fun KtDeclarationSymbol . getExpectsForActual ( ) : List < KtDeclarationSymbol >

= <EOL> withValidityAssertion { analysisSession . multiplatformInfoProvider . getExpectForActual ( this ) }

/**
 * Gives expect symbol for the actual one if it is available.
 *
 * @return a single expect declaration corresponds to the [KtDeclarationSymbol] on valid code or multiple expects in a case of erroneous code with multiple expects.
 **/


public inline fun < reified T : Any , reified D : Dim2 > Multik . readCSV ( fileName : String , delimiter : Char = '<CHAR_LIT:U+002C>' , charset : Charset = Charsets . UTF_8 ) : NDArray < T , D >

= readCSV ( fileName , DataType . ofKClass ( T :: class ) , dimensionClassOf < D > ( ) , delimiter , charset )

/**
 * Returns an NDArray of type [T] and [D] dimension read from csv file.
 * @param T NDArray element type
 * @param D dimension of NDArray. It can be 1 or 2
 * @param fileName file path including file name and extensions
 * @param delimiter separator between elements
 * @param charset character encoding, by default is UTF_8
 */


public fun < T , D : Dim2 > Multik . readCSV ( fileName : String , dtype : DataType , dim : Dim2 , delimiter : Char = '<CHAR_LIT:U+002C>' , charset : Charset = Charsets . UTF_8 ) : NDArray < T , D >

{ <EOL> val file = File ( fileName ) <EOL> if ( ! file . exists ( ) ) throw NoSuchFileException ( file ) <EOL> return readCSV ( file , dtype , dim , delimiter , charset ) <EOL> }

/**
 * Returns an NDArray of type [T] and [D] dimension read from csv file.
 * @param T NDArray element type
 * @param D dimension of NDArray. It can be 1 or 2
 * @param fileName file path including file name and extensions
 * @param dtype NDArray element type
 * @param delimiter separator between elements
 * @param charset character encoding, by default is UTF_8
 */


public fun Multik . readRaw ( fileName : String , dtype : DataType ? = null , dim : Dim2 ? = null , delimiter : Char = '<CHAR_LIT:U+002C>' , charset : Charset = Charsets . UTF_8 ) : NDArray < * , D2 >

{ <EOL> val file = File ( fileName ) <EOL> if ( ! file . exists ( ) ) throw NoSuchFileException ( file ) <EOL> return readRaw ( file , dtype , dim , delimiter , charset ) <EOL> }

/**
 * Returns a raw array of dimension 2. The type casts to either [Double] or [ComplexDouble].
 * @param fileName file path including file name and extensions
 * @param dtype NDArray element type
 * @param dim dimension of NDArray
 * @param delimiter separator between elements
 * @param charset character encoding, by default is UTF_8
 */


public inline fun < reified T : Any , reified D : Dim2 > Multik . readCSV ( file : File , delimiter : Char = '<CHAR_LIT:U+002C>' , charset : Charset = Charsets . UTF_8 ) : NDArray < T , D >

= readCSV ( file , DataType . ofKClass ( T :: class ) , dimensionClassOf < D > ( ) , delimiter , charset )

/**
 * Returns an NDArray of type [T] and [D] dimension read from csv file.
 * @param T NDArray element type
 * @param D dimension of NDArray. It can be 1 or 2
 * @param file csv file
 * @param delimiter separator between elements
 * @param charset character encoding, by default is UTF_8
 */


public fun < T , D : Dim2 > Multik . readCSV ( file : File , dtype : DataType , dim : Dim2 , delimiter : Char = '<CHAR_LIT:U+002C>' , charset : Charset = Charsets . UTF_8 ) : NDArray < T , D >

= <EOL> readDelim ( FileInputStream ( file ) , dtype , dim , delimiter , charset , isCompressed ( file ) )

/**
 * Returns an NDArray of type [T] and [D] dimension read from csv file.
 * @param T NDArray element type
 * @param D dimension of NDArray. It can be 1 or 2
 * @param dtype NDArray element type
 * @param file csv file
 * @param delimiter separator between elements
 * @param charset character encoding, by default is UTF_8
 */


public fun Multik . readRaw ( file : File , dtype : DataType ? = null , dim : Dim2 ? = null , delimiter : Char = '<CHAR_LIT:U+002C>' , charset : Charset = Charsets . UTF_8 ) : NDArray < * , D2 >

= <EOL> readDelim < Any , D2 > ( FileInputStream ( file ) , dtype , dim , delimiter , charset , isCompressed ( file ) )

/**
 * Returns a raw array of dimension 2. The type casts to either [Double] or [ComplexDouble].
 * @param file csv file
 * @param dtype NDArray element type
 * @param dim dimension of NDArray
 * @param delimiter separator between elements
 * @param charset character encoding, by default is UTF_8
 */


public fun < T , D : Dim2 > Multik . readDelim ( inStream : InputStream , dtype : DataType ? , dim : Dim2 ? , delimiter : Char = '<CHAR_LIT:U+002C>' , charset : Charset , isCompressed : Boolean = false ) : NDArray < T , D >

= <EOL> if ( isCompressed ) { <EOL> InputStreamReader ( GZIPInputStream ( inStream ) , charset ) <EOL> } else { <EOL> BufferedReader ( InputStreamReader ( inStream , charset ) ) <EOL> } . run { <EOL> readDelim ( this , CSVFormat . Builder . create ( CSVFormat . DEFAULT ) . setDelimiter ( delimiter ) . build ( ) , dtype , dim ) <EOL> }

/**
 * Returns an NDArray of type [T] and [D] dimension read from csv file.
 * @param T NDArray element type
 * @param D dimension of NDArray. It can be 1 or 2
 * @param inStream data input stream from file
 * @param dtype NDArray element type
 * @param dim dimension of NDArray
 * @param delimiter separator between elements
 * @param isCompressed shows whether the data is compressed, by default is false
 */


public fun < T , D : Dim2 > Multik . readDelim ( reader : Reader , format : CSVFormat = CSVFormat . DEFAULT , dtype : DataType ? , dim : Dim2 ? <EOL> ) : NDArray < T , D >

{ <EOL> val iSize : Int <EOL> val jSize : Int <EOL> val data : MemoryView < T > <EOL> format . parse ( reader ) . use { csvParser -> <EOL> val records = csvParser . records <EOL> iSize = records . size <EOL> jSize = records . first ( ) . size ( ) <EOL> val type = dtype ? : records [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] . parseDtype ( ) <EOL> data = initMemoryView ( iSize * jSize , type ) <EOL> var index = <NUM_LIT:0> <EOL> for ( record in records ) { <EOL> for ( el in record ) { <EOL> data [ index ++ ] = el . toType ( type ) <EOL> } <EOL> } <EOL> } <EOL> val d = dim ? : D2 <EOL> return if ( d == D1 ) { <EOL> val shape = intArrayOf ( jSize * iSize ) <EOL> D1Array ( data , <NUM_LIT:0> , shape , dim = D1 ) <EOL> } else { <EOL> val shape = intArrayOf ( iSize , jSize ) <EOL> D2Array ( data , <NUM_LIT:0> , shape , dim = D2 ) <EOL> } as NDArray < T , D > <EOL> }

/**
 * Returns an NDArray of type [T] and [D] dimension read from csv file.
 * @param T NDArray element type
 * @param D dimension of NDArray. It can be 1 or 2
 * @param reader reading character-input streams
 * @param format csv format from apache
 * @param dtype NDArray element type
 * @param dim dimension of NDArray
 */


public fun < T , D : Dim2 > Multik . writeCSV ( file : File , ndarray : NDArray < T , D > , delimiter : Char = '<CHAR_LIT:U+002C>' ) : Unit

= <EOL> writeCSV ( FileWriter ( file ) , ndarray , CSVFormat . Builder . create ( CSVFormat . DEFAULT ) . setDelimiter ( delimiter ) . build ( ) )

/**
 * Writes an NDArray to csv file. The NDArray must be up to the second dimension.
 * @param T NDArray element type
 * @param D dimension of NDArray. It can be 1 or 2
 * @param file file where the data will be written, if the file does not exist, it will be created
 * @param delimiter separator between elements
 */


public fun < T , D : Dim2 > Multik . writeCSV ( path : String , ndarray : NDArray < T , D > , delimiter : Char = '<CHAR_LIT:U+002C>' ) : Unit

= <EOL> writeCSV ( FileWriter ( path ) , ndarray , CSVFormat . Builder . create ( CSVFormat . DEFAULT ) . setDelimiter ( delimiter ) . build ( ) )

/**
 * Writes an NDArray to csv file. The NDArray must be up to the second dimension.
 * @param T NDArray element type
 * @param D dimension of NDArray. It can be 1 or 2
 * @param path file path where the data will be written
 * @param delimiter separator between elements
 */


public fun < T , D : Dim2 > Multik . writeCSV ( writer : Appendable , ndarray : NDArray < T , D > , format : CSVFormat = CSVFormat . DEFAULT ) : Unit

= <EOL> format . print ( writer ) . use { printer -> <EOL> if ( ndarray . dim . d == <NUM_LIT:1> ) { <EOL> ndarray . forEach { printer . printRecord ( it ) } <EOL> } else { <EOL> ndarray as D2Array < T > <EOL> for ( i in <NUM_LIT:0> until ndarray . shape [ <NUM_LIT:0> ] ) { <EOL> for ( j in <NUM_LIT:0> until ndarray . shape [ <NUM_LIT:1> ] ) { <EOL> printer . print ( ndarray [ i , j ] ) <EOL> } <EOL> printer . println ( ) <EOL> } <EOL> } <EOL> }

/**
 * Returns an NDArray of type [T] and [D] dimension read from csv file.
 * @param T NDArray element type
 * @param D dimension of NDArray. It can be 1 or 2
 * @param writer
 * @param ndarray array of data
 * @param format csv format from apache
 */


@ Test <EOL> fun testNotDoingDispatchesWhenNoTasksArePresent ( )

= runTest { <EOL> class NaggingDispatcher : CoroutineDispatcher ( ) { <EOL> private val closed = atomic ( false ) <EOL> override fun dispatch ( context : CoroutineContext , block : Runnable ) { <EOL> if ( closed . value ) <EOL> fail ( "<STR_LIT>" ) <EOL> Dispatchers . Default . dispatch ( context , block ) <EOL> } <EOL> fun close ( ) { <EOL> closed . value = true <EOL> } <EOL> } <EOL> repeat ( stressTestMultiplier * <NUM_LIT> ) { <EOL> val dispatcher = NaggingDispatcher ( ) <EOL> val view = dispatcher . limitedParallelism ( <NUM_LIT:1> ) <EOL> val deferred = CompletableDeferred < Unit > ( ) <EOL> val job = launch ( view ) { <EOL> deferred . await ( ) <EOL> } <EOL> launch ( Dispatchers . Default ) { <EOL> deferred . complete ( Unit ) <EOL> } <EOL> job . join ( ) <EOL> dispatcher . close ( ) <EOL> } <EOL> }

/**
 * Tests that, when no tasks are present, the limited dispatcher does not dispatch any tasks.
 * This is important for the case when a dispatcher is closeable and the [CoroutineDispatcher.limitedParallelism]
 * machinery could trigger a dispatch after the dispatcher is closed.
 */


= runTest { <EOL> val mainAtStart = TestMainDispatcher . currentTestDispatcher <EOL> assertNotNull ( mainAtStart ) <EOL> withContext ( Dispatchers . Main ) { <EOL> delay ( <NUM_LIT:10> ) <EOL> } <EOL> withContext ( Dispatchers . Default ) { <EOL> delay ( <NUM_LIT:10> ) <EOL> } <EOL> withContext ( Dispatchers . Main ) { <EOL> delay ( <NUM_LIT:10> ) <EOL> } <EOL> assertSame ( mainAtStart , TestMainDispatcher . currentTestDispatcher ) <EOL> }

/** Tests that asynchronous execution of tests does not happen concurrently with [AfterTest]. */


@ Test <EOL> fun testMockedMainImplementsDelay ( )

= runTest { <EOL> val main = Dispatchers . Main <EOL> withContext ( main ) { <EOL> delay ( <NUM_LIT:10> ) <EOL> } <EOL> withContext ( Dispatchers . Default ) { <EOL> delay ( <NUM_LIT:10> ) <EOL> } <EOL> withContext ( main ) { <EOL> delay ( <NUM_LIT:10> ) <EOL> } <EOL> }

/** Tests that the mocked [Dispatchers.Main] correctly forwards [Delay] methods. */


{ <EOL> assertFailsWith < IllegalArgumentException > { Dispatchers . setMain ( Dispatchers . Main ) } <EOL> }

/** Tests that [Distpachers.setMain] fails when called with [Dispatchers.Main]. */


fun isOverloadable ( a : DeclarationDescriptor , b : DeclarationDescriptor ) : Boolean

{ <EOL> val aCategory = getDeclarationCategory ( a ) <EOL> val bCategory = getDeclarationCategory ( b ) <EOL> if ( aCategory != bCategory ) return true <EOL> if ( a !is CallableDescriptor || b !is CallableDescriptor ) return false <EOL> return checkOverloadability ( a , b ) <EOL> }


private fun < Signature > findSuperImplementationForStubDelegation ( function : FunctionDescriptor , state : GenerationState , signatureByDescriptor : ( FunctionDescriptor ) -> Signature ) : FunctionDescriptor ?

{ <EOL> val implementation = findConcreteSuperDeclaration ( DescriptorBasedFunctionHandleForJvm ( function , state ) ) ? : return null <EOL> if ( ! implementation . mayBeUsedAsSuperImplementation ) return null <EOL> if ( signatureByDescriptor ( function ) == signatureByDescriptor ( implementation . descriptor ) ) return null <EOL> return implementation . descriptor <EOL> }

/**
 * Stub is a method having signature from Kotlin built-ins that we generate for non-abstract declarations,
 * it's bytecode consists of INVOKESPECIAL-call to real declaration in super class.
 *
 * Note that stub is needed only for first Kotlin class in the hierarchy.
 *
 * For example:
 * class A : HashMap<String, Any>
 *
 * Here we generate `entrySet()` special bridge with INVOKEVIRTUAL getEntries(),
 * But the latter does not exists yet, so we create a stub for it with delegation to super-class
 *
 * Also note that there is no special bridges for final declarations, thus no stubs either
 */


{ <EOL> isClosed = true <EOL> tfGraph . close ( ) <EOL> }

/**
 * Closes internal TensorFlow graph.
 */


public fun variableNames ( ) : List < String >

= tfGraph . variableNames ( )

/** Returns list of variable names in TensorFlow graph. */


{ <EOL> require ( ! isClosed ) { "<STR_LIT>" } <EOL> return KGraph ( tfGraph . toGraphDef ( ) ) <EOL> }


public fun addOptimizerVariable ( variable : Variable < Float > )

{ <EOL> check ( ! optimizerVariables . contains ( variable ) ) { "<STR_LIT>" } <EOL> optimizerVariables . add ( variable ) <EOL> }

/**
 * Adds a variable used in optimizer to the pool of tracked variables.
 *
 * @param variable Optimizer variable to track in KGraph.
 */


public fun addOptimizerVariableInitializer ( initializer : Assign < * > )

{ <EOL> optimizerInitializers += initializer <EOL> }

/**
 * Adds an optimizer initializer for optimizer variable tracked in KGraph.
 *
 * @param initializer Assign TensorFlow operand to initialize optimizer variable.
 */


public fun addOptimizerVariableAssignAddInitializer ( initializer : AssignAdd < Float > )

{ <EOL> optimizerAssignAddInitializers += initializer <EOL> }

/**
 * Adds an optimizer initializer of special 'AssignAdd' type for optimizer variable tracked in KGraph.
 *
 * @param initializer AssignAdd TensorFlow operand to initialize and increase optimizer variable.
 */


public fun optimizerVariables ( ) : List < Variable < Float > >

{ <EOL> return optimizerVariables . toList ( ) <EOL> }

/**
 * Returns all variables used in optimizer and initialized by Assign TensorFlow operand.
 */


public fun initializeOptimizerVariables ( session : Session )

{ <EOL> if ( optimizerInitializers . isNotEmpty ( ) ) { <EOL> optimizerInitializers . forEach { <EOL> val runner = session . runner ( ) <EOL> runner . addTarget ( it ) <EOL> runner . run ( ) <EOL> } <EOL> } <EOL> runAssignAddOpsForOptimizers ( session ) <EOL> }

/**
 * Initializes TensorFlow graph variables used in optimizer.
 */


internal actual fun safeAdd ( a : Long , b : Long ) : Long

{ <EOL> val sum = a + b <EOL> if ( ( a xor sum ) < <NUM_LIT:0> && ( a xor b ) >= <NUM_LIT:0> ) { <EOL> throw ArithmeticException ( "<STR_LIT>" ) <EOL> } <EOL> return sum <EOL> }

/**
 * Safely adds two long values.
 * throws [ArithmeticException] if the result overflows a long
 */


internal actual fun safeMultiply ( a : Long , b : Long ) : Long

{ <EOL> when ( b ) { <EOL> - <NUM_LIT:1L> -> { <EOL> if ( a == Long . MIN_VALUE ) { <EOL> throw ArithmeticException ( "<STR_LIT>" ) <EOL> } <EOL> return - a <EOL> } <EOL> <NUM_LIT:0L> -> return <NUM_LIT:0L> <EOL> <NUM_LIT:1L> -> return a <EOL> } <EOL> val total = a * b <EOL> if ( total / b != a ) { <EOL> throw ArithmeticException ( "<STR_LIT>" ) <EOL> } <EOL> return total <EOL> }

/**
 * Safely multiply a long by an int.
 *
 * @param a the first value
 * @param b the second value
 * @return the new total
 * @throws ArithmeticException if the result overflows a long
 */


@ InternalCoroutinesApi <EOL> public fun handleCoroutineException ( context : CoroutineContext , exception : Throwable )

{ <EOL> try { <EOL> context [ CoroutineExceptionHandler ] ? . let { <EOL> it . handleException ( context , exception ) <EOL> return <EOL> } <EOL> } catch ( t : Throwable ) { <EOL> handleUncaughtCoroutineException ( context , handlerException ( exception , t ) ) <EOL> return <EOL> } <EOL> handleUncaughtCoroutineException ( context , exception ) <EOL> }

/**
 * Helper function for coroutine builder implementations to handle uncaught and unexpected exceptions in coroutines,
 * that could not be otherwise handled in a normal way through structured concurrency, saving them to a future, and
 * cannot be rethrown. This is a last resort handler to prevent lost exceptions.
 *
 * If there is [CoroutineExceptionHandler] in the context, then it is used. If it throws an exception during handling
 * or is absent, all instances of [CoroutineExceptionHandler] found via [ServiceLoader] and
 * [Thread.uncaughtExceptionHandler] are invoked.
 */


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> public inline fun CoroutineExceptionHandler ( crossinline handler : ( CoroutineContext , Throwable ) -> Unit ) : CoroutineExceptionHandler

= <EOL> object : AbstractCoroutineContextElement ( CoroutineExceptionHandler ) , CoroutineExceptionHandler { <EOL> override fun handleException ( context : CoroutineContext , exception : Throwable ) = <EOL> handler . invoke ( context , exception ) <EOL> }

/**
 * Creates a [CoroutineExceptionHandler] instance.
 * @param handler a function which handles exception thrown by a coroutine
 */


public fun handleException ( context : CoroutineContext , exception : Throwable )

/**
 * Handles uncaught [exception] in the given [context]. It is invoked
 * if coroutine has an uncaught exception.
 */


public fun TensorResult . getFloatArray ( index : Int ) : FloatArray

= tensors [ index ] . toFloatArray ( )

/**
 * Returns the output at [index] as a [FloatArray].
 */


public fun TensorResult . getLongArray ( index : Int ) : LongArray

= tensors [ index ] . toLongArray ( )

/**
 * Returns the output at [index] as a [LongArray].
 */


public fun Tensor < * > . toFloatArray ( ) : FloatArray

{ <EOL> val buffer = FloatBuffer . allocate ( numElements ( ) ) <EOL> writeTo ( buffer ) <EOL> return buffer . array ( ) <EOL> }

/** Copies tensor data to float array. */


public fun Tensor < * > . toLongArray ( ) : LongArray

{ <EOL> val buffer = LongBuffer . allocate ( numElements ( ) ) <EOL> writeTo ( buffer ) <EOL> return buffer . array ( ) <EOL> }

/** Copies tensor data to long array. */


public fun Tensor < * > . toMultiDimensionalArray ( ) : Array < * >

{ <EOL> val shape = this . shape ( ) <EOL> if ( shape . isEmpty ( ) ) return emptyArray < Any > ( ) <EOL> if ( shape . size == <NUM_LIT:1> ) return toFloatArray ( ) . toTypedArray ( ) <EOL> val dst = when ( shape . size ) { <EOL> <NUM_LIT:2> -> create2DArray ( shape ) <EOL> <NUM_LIT:3> -> create3DArray ( shape ) <EOL> <NUM_LIT:4> -> create4DArray ( shape ) <EOL> else -> { <EOL> throw UnsupportedOperationException ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> copyTo ( dst ) <EOL> return dst <EOL> }

/** Copies tensor to multidimensional float array. Array rank is equal to tensor rank. */


fun render ( withSeverity : Boolean = true , withLocation : Boolean = true , withException : Boolean = true , withStackTrace : Boolean = false ) : String

= buildString { <EOL> if ( withSeverity ) { <EOL> append ( severity . name ) <EOL> append ( '<CHAR_LIT:U+0020>' ) <EOL> } <EOL> append ( message ) <EOL> if ( withLocation && ( sourcePath != null || location != null ) ) { <EOL> append ( "<STR_LIT>" ) <EOL> sourcePath ? . let { append ( it . substringAfterLast ( File . separatorChar ) ) } <EOL> location ? . let { <EOL> append ( '<CHAR_LIT::>' ) <EOL> append ( it . start . line ) <EOL> append ( '<CHAR_LIT::>' ) <EOL> append ( it . start . col ) <EOL> } <EOL> append ( '<CHAR_LIT>' ) <EOL> } <EOL> if ( withException && exception != null ) { <EOL> append ( "<STR_LIT::U+0020>" ) <EOL> append ( exception ) <EOL> if ( withStackTrace ) { <EOL> ByteArrayOutputStream ( ) . use { os -> <EOL> val ps = PrintStream ( os ) <EOL> exception . printStackTrace ( ps ) <EOL> ps . flush ( ) <EOL> append ( "<STR_LIT:\n>" ) <EOL> append ( os . toString ( ) ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Render diagnostics message as a string in a form:
 * "[SEVERITY ]message[ (file:line:column)][: exception message[\n exception stacktrace]]"
 * @param withSeverity add severity prefix, true by default
 * @param withLocation add error location in the compiled script, if present, true by default
 * @param withException add exception message, if present, true by default
 * @param withStackTrace add exception stacktrace, if exception is present and [withException] is true, false by default
 */


inline fun < R1 , R2 > ResultWithDiagnostics < R1 > . onSuccess ( body : ( R1 ) -> ResultWithDiagnostics < R2 > ) : ResultWithDiagnostics < R2 >

= <EOL> when ( this ) { <EOL> is ResultWithDiagnostics . Success -> this . reports + body ( this . value ) <EOL> is ResultWithDiagnostics . Failure -> this <EOL> }

/**
 * Chains actions on successful result:
 * If receiver is success - executes [body] and merge diagnostic reports
 * otherwise returns the failure as is
 */


inline fun < T , R > Iterable < T > . mapSuccess ( body : ( T ) -> ResultWithDiagnostics < R > ) : ResultWithDiagnostics < List < R > >

= <EOL> mapSuccessImpl ( body ) { results , r -> <EOL> results . add ( r ) <EOL> }

/**
 * maps transformation ([body]) over iterable merging diagnostics
 * return failure with merged diagnostics after first failed transformation
 * and success with merged diagnostics and list of results if all transformations succeeded
 */


inline fun < T , R > Iterable < T > . mapNotNullSuccess ( body : ( T ) -> ResultWithDiagnostics < R ? > ) : ResultWithDiagnostics < List < R > >

= <EOL> mapSuccessImpl ( body ) { results , r -> <EOL> if ( r != null ) <EOL> results . add ( r ) <EOL> }

/**
 * maps transformation ([body]) over iterable merging diagnostics
 * return failure with merged diagnostics after first failed transformation
 * and success with merged diagnostics and list of not null results if all transformations succeeded
 */


inline fun < T , R > Iterable < T > . flatMapSuccess ( body : ( T ) -> ResultWithDiagnostics < Collection < R > > ) : ResultWithDiagnostics < List < R > >

= <EOL> mapSuccessImpl ( body ) { results , r -> <EOL> results . addAll ( r ) <EOL> }

/**
 * maps transformation ([body]) over iterable merging diagnostics and flatten the results
 * return failure with merged diagnostics after first failed transformation
 * and success with merged diagnostics and list of results if all transformations succeeded
 */


inline fun < R > ResultWithDiagnostics < R > . onFailure ( body : ( ResultWithDiagnostics < R > ) -> Unit ) : ResultWithDiagnostics < R >

{ <EOL> if ( this is ResultWithDiagnostics . Failure ) { <EOL> body ( this ) <EOL> } <EOL> return this <EOL> }

/**
 * Chains actions on failure:
 * If receiver is failure - executed [body]
 * otherwise returns the receiver as is
 */


operator fun < R > List < ScriptDiagnostic > . plus ( result : ResultWithDiagnostics < R > ) : ResultWithDiagnostics < R >

= when ( result ) { <EOL> is ResultWithDiagnostics . Success -> ResultWithDiagnostics . Success ( result . value , this + result . reports ) <EOL> is ResultWithDiagnostics . Failure -> ResultWithDiagnostics . Failure ( this + result . reports ) <EOL> }

/**
 * Merges diagnostics report with the [result] wrapper
 */


fun < R > R . asSuccess ( reports : List < ScriptDiagnostic > = listOf ( ) ) : ResultWithDiagnostics . Success < R >

= <EOL> ResultWithDiagnostics . Success ( this , reports )

/**
 * Converts the receiver value to the Success result wrapper with optional diagnostic [reports]
 */


fun makeFailureResult ( reports : List < ScriptDiagnostic > ) : ResultWithDiagnostics . Failure

= <EOL> ResultWithDiagnostics . Failure ( reports )

/**
 * Makes Failure result with optional diagnostic [reports]
 */


fun makeFailureResult ( vararg reports : ScriptDiagnostic ) : ResultWithDiagnostics . Failure

= <EOL> ResultWithDiagnostics . Failure ( reports . asList ( ) )


fun makeFailureResult ( message : String , path : String ? = null , location : SourceCode . Location ? = null ) : ResultWithDiagnostics . Failure

= <EOL> ResultWithDiagnostics . Failure ( message . asErrorDiagnostics ( ScriptDiagnostic . unspecifiedError , path , location ) )

/**
 * Makes Failure result with diagnostic [message] with optional [path] and [location]
 */


fun makeFailureResult ( message : String , locationWithId : SourceCode . LocationWithId ? ) : ResultWithDiagnostics . Failure

= <EOL> ResultWithDiagnostics . Failure ( message . asErrorDiagnostics ( ScriptDiagnostic . unspecifiedError , locationWithId ) )

/**
 * Makes Failure result with diagnostic [message] with optional [locationWithId]
 */


fun Throwable . asDiagnostics ( code : Int = ScriptDiagnostic . unspecifiedException , customMessage : String ? = null , path : String ? = null , location : SourceCode . Location ? = null , severity : ScriptDiagnostic . Severity = ScriptDiagnostic . Severity . ERROR ) : ScriptDiagnostic

= <EOL> ScriptDiagnostic ( code , customMessage ? : message ? : "<STR_LIT>" , severity , path , location , this )

/**
 * Converts the receiver Throwable to the Failure results wrapper with optional [customMessage], [path] and [location]
 */


fun Throwable . asDiagnostics ( code : Int = ScriptDiagnostic . unspecifiedException , customMessage : String ? = null , locationWithId : SourceCode . LocationWithId ? , severity : ScriptDiagnostic . Severity = ScriptDiagnostic . Severity . ERROR ) : ScriptDiagnostic

= <EOL> ScriptDiagnostic ( code , customMessage ? : message ? : "<STR_LIT>" , severity , locationWithId , this )

/**
 * Converts the receiver Throwable to the Failure results wrapper with optional [customMessage], [locationWithId]
 */


fun String . asErrorDiagnostics ( code : Int = ScriptDiagnostic . unspecifiedError , path : String ? = null , location : SourceCode . Location ? = null ) : ScriptDiagnostic

= <EOL> ScriptDiagnostic ( code , this , ScriptDiagnostic . Severity . ERROR , path , location )

/**
 * Converts the receiver String to error diagnostic report with optional [path] and [location]
 */


fun String . asErrorDiagnostics ( code : Int = ScriptDiagnostic . unspecifiedError , locationWithId : SourceCode . LocationWithId ? <EOL> ) : ScriptDiagnostic

= <EOL> ScriptDiagnostic ( code , this , ScriptDiagnostic . Severity . ERROR , locationWithId )

/**
 * Converts the receiver String to error diagnostic report with optional [locationWithId]
 */


fun < R > ResultWithDiagnostics < R > . valueOrNull ( ) : R ?

= when ( this ) { <EOL> is ResultWithDiagnostics . Success < R > -> value <EOL> else -> null <EOL> }

/**
 * Extracts the result value from the receiver wrapper or null if receiver represents a Failure
 */


inline fun < R > ResultWithDiagnostics < R > . valueOr ( body : ( ResultWithDiagnostics . Failure ) -> Nothing ) : R

= when ( this ) { <EOL> is ResultWithDiagnostics . Success < R > -> value <EOL> is ResultWithDiagnostics . Failure -> body ( this ) <EOL> }

/**
 * Extracts the result value from the receiver wrapper or run non-returning lambda if receiver represents a Failure
 */


fun < R > ResultWithDiagnostics < R > . valueOrThrow ( ) : R

= valueOr { <EOL> throw RuntimeException ( reports . joinToString ( "<STR_LIT:\n>" ) { it . exception ? . toString ( ) ? : it . message } , reports . find { it . exception != null } ? . exception ) <EOL> }

/**
 * Extracts the result value from the receiver wrapper or throw RuntimeException with diagnostics
 */


private fun ConeFlexibleType . hasFlexibleMutability ( ) : Boolean

{ <EOL> return JavaToKotlinClassMap . isMutable ( lowerBound . classId ) && JavaToKotlinClassMap . isReadOnly ( upperBound . classId ) <EOL> }

/**
 * `List<Object>` is represented as `MutableList<Any!>..List<Any!>?`.
 */


private fun ConeFlexibleType . isArrayWithFlexibleVariance ( ) : Boolean

{ <EOL> return lowerBound . classId == StandardClassIds . Array && lowerBound . typeArguments . firstOrNull ( ) ? . kind != upperBound . typeArguments . firstOrNull ( ) ? . kind <EOL> }

/**
 * `Object[]` is represented as `Array<Any>..Array<out Any>?`.
 */


{ <EOL> _builder . clearExtras ( ) <EOL> }

/**
 * optional .org.jetbrains.kotlin.gradle.idea.proto.generated.IdeaExtrasProto extras = 1;
 */


{ <EOL> return _builder . hasExtras ( ) <EOL> }

/**
 * optional .org.jetbrains.kotlin.gradle.idea.proto.generated.IdeaExtrasProto extras = 1;
 * @return Whether the extras field is set.
 */


{ <EOL> _builder . clearType ( ) <EOL> }

/**
 * optional .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinSourceDependencyProto.Type type = 2;
 */


{ <EOL> return _builder . hasType ( ) <EOL> }

/**
 * optional .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinSourceDependencyProto.Type type = 2;
 * @return Whether the type field is set.
 */


{ <EOL> _builder . clearCoordinates ( ) <EOL> }

/**
 * optional .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinProjectCoordinatesProto coordinates = 3;
 */


fun hasCoordinates ( ) : kotlin . Boolean

{ <EOL> return _builder . hasCoordinates ( ) <EOL> }

/**
 * optional .org.jetbrains.kotlin.gradle.idea.proto.generated.tcs.IdeaKotlinProjectCoordinatesProto coordinates = 3;
 * @return Whether the coordinates field is set.
 */


fun lenetWithAlternativeLossFunction ( )

{ <EOL> val ( train , test ) = mnist ( ) <EOL> val ( newTrain , validation ) = train . split ( <NUM_LIT> ) <EOL> lenet5Classic . use { model -> <EOL> model . compile ( optimizer = Adam ( ) , loss = Losses . HUBER , metric = Metrics . ACCURACY ) <EOL> model . logSummary ( ) <EOL> val history = model . fit ( trainingDataset = newTrain , validationDataset = validation , epochs = EPOCHS , trainBatchSize = TRAINING_BATCH_SIZE , validationBatchSize = TEST_BATCH_SIZE ) <EOL> val accuracy = model . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> val accuracyByEpoch = history . epochHistory . map { it . metricValues [ <NUM_LIT:0> ] } . toDoubleArray ( ) <EOL> println ( accuracyByEpoch . contentToString ( ) ) <EOL> } <EOL> }

/**
 * This example shows how to do image classification from scratch using [lenet5Classic], 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
 * - dataset splitting on train, test and validation subsets
 * - model compilation with alternative [Losses]
 * - model summary
 * - model training with validation
 * - model evaluation
 */


= lenetWithAlternativeLossFunction ( )


fun fill ( rangeStart : Int , rangeEnd : Int , categoryIdOf : ( Int ) -> String , charCode : Int , categoryId : String ) : Boolean

{ <EOL> require ( charCode == rangeStart - <NUM_LIT:1> || charCode == rangeEnd + <NUM_LIT:1> ) <EOL> val attempt = categoryIds . copyOf ( ) <EOL> for ( ch in rangeStart .. rangeEnd ) { <EOL> if ( ! attempt . fill ( ch , categoryIdOf ( ch ) ) ) return false <EOL> } <EOL> if ( ! attempt . fill ( charCode , categoryId ) ) return false <EOL> attempt . copyInto ( categoryIds ) <EOL> return true <EOL> }

/**
 * Returns true if a range with the specified [rangeStart], [rangeEnd] and [categoryIdOf] was successfully added
 * together with a char with the specified [charCode] and [categoryId].
 *
 * The [charCode] must go immediately after the [rangeEnd] or before the [rangeStart].
 */


fun fill ( charCode : Int , categoryId : String ) : Boolean

{ <EOL> return categoryIds . fill ( charCode , categoryId ) <EOL> }

/**
 * Returns true if the [charCode] with the [categoryId] was successfully placed in [categoryIds].
 */


private fun Array < String ? > . fill ( charCode : Int , categoryId : String ) : Boolean

{ <EOL> val index = charCode % sequenceLength <EOL> val current = this [ index ] <EOL> if ( current == null || ( isPeriodic && current == categoryId ) ) { <EOL> this [ index ] = categoryId <EOL> return true <EOL> } <EOL> return false <EOL> }

/**
 * Returns true if the [charCode] with the [categoryId] was successfully placed in this array.
 *
 * The [charCode] is placed at index `charCode % sequenceLength`.
 */


@ ExperimentalBuildToolsApi <EOL> @ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> public fun SharedApiClassesClassLoader ( ) : ClassLoader

= SharedApiClassesClassLoaderImpl ( SharedApiClassesClassLoaderImpl :: class . java . classLoader , SharedApiClassesClassLoaderImpl :: class . java . `package` . name , )

/**
 * Creates a [ClassLoader] which reuses the API classes from the ClassLoader which loaded the API.
 * This way an API implementation can be loaded with almost fully isolated classpath, sharing only the classes from `org.jetbrains.kotlin.buildtools.api`,
 * so a caller still able to pass API parameters in a compatible way.
 */