internal fun addSources ( sourceDirectories : Iterable < File > )

{ <EOL> sourceDirectories . forEach { directory -> <EOL> configuration . addKotlinSourceRoot ( directory . path ) <EOL> if ( directory . isDirectory || directory . extension == "<STR_LIT:java>" ) { <EOL> configuration . addJavaSourceRoot ( directory ) <EOL> } <EOL> } <EOL> }

/**
 * Adds list of paths to source roots.
 * $list: collection of files to add
 */


{ <EOL> Disposer . dispose ( this ) <EOL> }

/**
 * Disposes the environment and frees all associated resources.
 */


inline fun < T , reified R > Dataset < T > . col ( colName : String ) : TypedColumn < T , R >

= <EOL> org . jetbrains . kotlinx . spark . api . col < T , R > ( colName )

/**
 * Selects column based on the column name and returns it as a [TypedColumn].
 *
 * For example:
 * ```kotlin
 * dataset.col<_, Int>("a")
 * ```
 *
 * @note The column name can also reference to a nested column like `a.b`.
 */


inline operator fun < T , reified R > Dataset < T > . invoke ( colName : String ) : TypedColumn < T , R >

/**
 * Selects column based on the column name and returns it as a [TypedColumn].
 *
 * For example:
 * ```kotlin
 * dataset<_, Int>("a")
 * ```
 * @note The column name can also reference to a nested column like `a.b`.
 */


operator fun Dataset < * > . invoke ( colName : String ) : Column

= apply ( colName )

/**
 * Selects column based on the column name and returns it as a [Column].
 *
 * @note The column name can also reference to a nested column like `a.b`.
 *
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < T , reified U > Dataset < T > . col ( column : KProperty1 < T , U > ) : TypedColumn < T , U >

= <EOL> col ( column . name ) . `as` ( )

/**
 * Helper function to quickly get a [TypedColumn] (or [Column]) from a dataset in a refactor-safe manner.
 * ```kotlin
 * val dataset: Dataset<YourClass> = ...
 * val columnA: TypedColumn<YourClass, TypeOfA> = dataset.col(YourClass::a)
 * ```
 * @see invoke
 */


inline operator fun < T , reified U > Dataset < T > . invoke ( column : KProperty1 < T , U > ) : TypedColumn < T , U >

= col ( column )

/**
 * Helper function to quickly get a [TypedColumn] (or [Column]) from a dataset in a refactor-safe manner.
 * ```kotlin
 * val dataset: Dataset<YourClass> = ...
 * val columnA: TypedColumn<YourClass, TypeOfA> = dataset(YourClass::a)
 * ```
 * @see col
 */


inline fun < reified T > Dataset < T > . singleCol ( colName : String = "<STR_LIT:value>" ) : TypedColumn < T , T >

{ <EOL> require ( schema ( ) . fields ( ) . size == <NUM_LIT:1> ) { "<STR_LIT>" } <EOL> return org . jetbrains . kotlinx . spark . api . singleCol ( colName ) <EOL> }

/**
 * Can be used to create a [TypedColumn] for a simple [Dataset]
 * with just one single column called "value".
 */


operator fun Column . unaryMinus ( ) : Column

= `unary_$minus` ( )

/**
 * Unary minus, i.e. negate the expression.
 * ```
 * // Scala: select the amount column and negates all values.
 * df.select( -df("amount") )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * df.select( -df("amount") )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * df.select( negate(col("amount") );
 * ```
 */


= `unary_$bang` ( )

/**
 * Inversion of boolean expression, i.e. NOT.
 * ```
 * // Scala: select rows that are not active (isActive === false)
 * df.filter( !df("isActive") )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * df.filter( !df("amount") )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * df.filter( not(df.col("isActive")) );
 * ```
 */


infix fun Column . eq ( other : Any ) : Column

= `$eq$eq$eq` ( other )

/**
 * Equality test.
 * ```
 * // Scala:
 * df.filter( df("colA") === df("colB") )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * df.filter( df("colA") eq df("colB") )
 * // or
 * df.filter( df("colA") `===` df("colB") )
 *
 * // Java
 * import static org.apache.spark.sql.functions.*;
 * df.filter( col("colA").equalTo(col("colB")) );
 * ```
 */


infix fun Column . `===` ( other : Any ) : Column

= `$eq$eq$eq` ( other )


infix fun Column . neq ( other : Any ) : Column

= `$eq$bang$eq` ( other )

/**
 * Inequality test.
 * ```
 * // Scala:
 * df.select( df("colA") =!= df("colB") )
 * df.select( !(df("colA") === df("colB")) )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * df.select( df("colA") neq df("colB") )
 * df.select( !(df("colA") eq df("colB")) )
 * // or
 * df.select( df("colA") `=!=` df("colB") )
 * df.select( !(df("colA") `===` df("colB")) )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * df.select( col("colA").notEqual(col("colB")) );
 * ```
 */


infix fun Column . `=!=` ( other : Any ) : Column

= `$eq$bang$eq` ( other )


infix fun Column . gt ( other : Any ) : Column

= `$greater` ( other )

/**
 * Greater than.
 * ```
 * // Scala: The following selects people older than 21.
 * people.select( people("age") > 21 )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * people.select( people("age") gt 21 )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * people.select( people.col("age").gt(21) );
 * ```
 */


infix fun Column . lt ( other : Any ) : Column

= `$less` ( other )

/**
 * Less than.
 * ```
 * // Scala: The following selects people younger than 21.
 * people.select( people("age") < 21 )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * people.select( people("age") lt 21 )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * people.select( people.col("age").lt(21) );
 * ```
 */


infix fun Column . leq ( other : Any ) : Column

= `$less$eq` ( other )

/**
 * Less than or equal to.
 * ```
 * // Scala: The following selects people age 21 or younger than 21.
 * people.select( people("age") <= 21 )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * people.select( people("age") leq 21 )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * people.select( people.col("age").leq(21) );
 * ```
 */


infix fun Column . geq ( other : Any ) : Column

= `$greater$eq` ( other )

/**
 * Greater than or equal to an expression.
 * ```
 * // Scala: The following selects people age 21 or older than 21.
 * people.select( people("age") >= 21 )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * people.select( people("age") geq 21 )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * people.select( people.col("age").geq(21) );
 * ```
 */


infix fun Column . inRangeOf ( range : ClosedRange < * > ) : Column

= between ( range . start , range . endInclusive )

/**
 * True if the current column is in the given [range].
 * ```
 * // Scala:
 * df.where( df("colA").between(1, 5) )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * df.where( df("colA") inRangeOf 1..5 )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * df.where( df.col("colA").between(1, 5) );
 * ```
 */


infix fun Column . or ( other : Any ) : Column

= `$bar$bar` ( other )

/**
 * Boolean OR.
 * ```
 * // Scala: The following selects people that are in school or employed.
 * people.filter( people("inSchool") || people("isEmployed") )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * people.filter( people("inSchool") or people("isEmployed") )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * people.filter( people.col("inSchool").or(people.col("isEmployed")) );
 * ```
 */


infix fun Column . and ( other : Any ) : Column

= `$amp$amp` ( other )

/**
 * Boolean AND.
 * ```
 * // Scala: The following selects people that are in school and employed at the same time.
 * people.select( people("inSchool") && people("isEmployed") )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * people.select( people("inSchool") and people("isEmployed") )
 * // or
 * people.select( people("inSchool") `&&` people("isEmployed") )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * people.select( people.col("inSchool").and(people.col("isEmployed")) );
 * ```
 */


infix fun Column . `&&` ( other : Any ) : Column

= `$amp$amp` ( other )


operator fun Column . times ( other : Any ) : Column

= `$times` ( other )

/**
 * Multiplication of this expression and another expression.
 * ```
 * // Scala: The following multiplies a person's height by their weight.
 * people.select( people("height") * people("weight") )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * people.select( people("height") * people("weight") )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * people.select( people.col("height").multiply(people.col("weight")) );
 * ```
 */


operator fun Column . div ( other : Any ) : Column

= `$div` ( other )

/**
 * Division this expression by another expression.
 * ```
 * // Scala: The following divides a person's height by their weight.
 * people.select( people("height") / people("weight") )
 *
 * // Kotlin
 * import org.jetbrains.kotlinx.spark.api.*
 * people.select( people("height") / people("weight") )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * people.select( people.col("height").divide(people.col("weight")) );
 * ```
 */


operator fun Column . rem ( other : Any ) : Column

= `$percent` ( other )

/**
 * Modulo (a.k.a. remainder) expression.
 * ```
 * // Scala:
 * df.where( df("colA") % 2 === 0 )
 *
 * // Kotlin:
 * import org.jetbrains.kotlinx.spark.api.*
 * df.where( df("colA") % 2 eq 0 )
 *
 * // Java:
 * import static org.apache.spark.sql.functions.*;
 * df.where( df.col("colA").mod(2).equalTo(0) );
 * ```
 */


operator fun Column . get ( key : Any ) : Column

= getItem ( key )

/**
 * An expression that gets an item at position `ordinal` out of an array,
 * or gets a value by key `key` in a `MapType`.
 * ```
 * // Scala:
 * df.where( df("arrayColumn").getItem(0) === 5 )
 *
 * // Kotlin
 * import org.jetbrains.kotlinx.spark.api.*
 * df.where( df("arrayColumn")[0] eq 5 )
 *
 * // Java
 * import static org.apache.spark.sql.functions.*;
 * df.where( df.col("arrayColumn").getItem(0).equalTo(5) );
 * ```
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < DsType , reified U > Column . `as` ( ) : TypedColumn < DsType , U >

= `as` ( encoder < U > ( ) ) as TypedColumn < DsType , U >

/**
 * Provides a type hint about the expected return value of this column. This information can
 * be used by operations such as `select` on a [Dataset] to automatically convert the
 * results into the correct JVM types.
 *
 * ```
 * val df: Dataset<Row> = ...
 * val typedColumn: Dataset<Int> = df.select( col("a").`as`<_, Int>() )
 * ```
 *
 * @see typed
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < DsType , reified U > TypedColumn < DsType , * > . `as` ( ) : TypedColumn < DsType , U >


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < DsType , reified T > Column . typed ( ) : TypedColumn < DsType , T >

= `as` ( )

/**
 * Provides a type hint about the expected return value of this column. This information can
 * be used by operations such as `select` on a [Dataset] to automatically convert the
 * results into the correct JVM types.
 *
 * ```
 * val df: Dataset<Row> = ...
 * val typedColumn: Dataset<Int> = df.select( col("a").typed<_, Int>() )
 * ```
 *
 * @see as
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < DsType , reified T > TypedColumn < DsType , * > . typed ( ) : TypedColumn < DsType , T >

= `as` ( )


= functions . lit ( a )

/**
 * Creates a [Column] of literal value.
 *
 * The passed in object is returned directly if it is already a [Column].
 * If the object is a Scala Symbol, it is converted into a [Column] also.
 * Otherwise, a new [Column] is created to represent the literal value.
 *
 * This is just a shortcut to the function from [org.apache.spark.sql.functions].
 * For all the functions, simply add `import org.apache.spark.sql.functions.*` to your file.
 */


inline fun < DsType , reified U > typedLit ( literal : U ) : TypedColumn < DsType , U >

= functions . lit ( literal ) . typed ( )

/**
 * Creates a [Column] of literal value.
 *
 * The passed in object is returned directly if it is already a [Column].
 * If the object is a Scala Symbol, it is converted into a [Column] also.
 * Otherwise, a new [Column] is created to represent the literal value.
 * The difference between this function and [lit] is that this function
 * can handle types and parameterized scala types e.g.: List, Seq and Map.
 *
 */


inline fun < DsType , reified U > col ( colName : String ) : TypedColumn < DsType , U >

= functions . col ( colName ) . `as` ( )

/**
 * Returns a [TypedColumn] based on the given column name and type [DsType].
 *
 * This is just a shortcut to the function from [org.apache.spark.sql.functions] combined with an [as] call.
 * For all the functions, simply add `import org.apache.spark.sql.functions.*` to your file.
 *
 * @see col
 * @see as
 */


inline fun < reified DsType > singleCol ( colName : String = "<STR_LIT:value>" ) : TypedColumn < DsType , DsType >

/**
 * Can be used to create a [TypedColumn] for a simple [Dataset]
 * with just one single column called "value".
 */


= functions . col ( colName )

/**
 * Returns a [Column] based on the given column name.
 *
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> inline fun < DsType , reified U > col ( column : KProperty1 < DsType , U > ) : TypedColumn < DsType , U >

= <EOL> functions . col ( column . name ) . `as` ( )

/**
 * Returns a [Column] based on the given class attribute, not connected to a dataset.
 * ```kotlin
 * val dataset: Dataset<YourClass> = ...
 * val new: Dataset<Tuple2<TypeOfA, TypeOfB>> = dataset.select( col(YourClass::a), col(YourClass::b) )
 * ```
 * @see col
 */


{ <EOL> val ( train , test ) = fashionMnist ( ) <EOL> val jsonConfigFile = getJSONConfigFileToyResNet ( ) <EOL> val model = Functional . loadModelConfiguration ( jsonConfigFile ) <EOL> model . use { <EOL> it . compile ( optimizer = RMSProp ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> it . init ( ) <EOL> var accuracy = it . evaluate ( dataset = test , batchSize = <NUM_LIT> ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> it . fit ( dataset = train , epochs = <NUM_LIT:3> , batchSize = <NUM_LIT:100> ) <EOL> accuracy = it . evaluate ( dataset = test , batchSize = <NUM_LIT> ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * We described ToyResNet in Keras and saved model configuration.
 *
 * It used simple initializers and training from zero is too long.
 *
 * It's better to load pretrained model.
 */


internal fun getJSONConfigFileToyResNet ( ) : File

{ <EOL> val pathToConfig = "<STR_LIT>" <EOL> val realPathToConfig = OnHeapDataset :: class . java . classLoader . getResource ( pathToConfig ) . path . toString ( ) <EOL> return File ( realPathToConfig ) <EOL> }

/** Returns JSON file with model configuration, saved from Keras 2.x. */


internal fun getWeightsFileToyResNet ( ) : HdfFile

{ <EOL> val pathToWeights = "<STR_LIT>" <EOL> val realPathToWeights = OnHeapDataset :: class . java . classLoader . getResource ( pathToWeights ) . path . toString ( ) <EOL> return HdfFile ( File ( realPathToWeights ) ) <EOL> }

/** Returns .h5 file with model weights, saved from Keras 2.x. */


public fun < T : Number > inv ( mat : MultiArray < T , D2 > ) : NDArray < Double , D2 >

/**
 * Returns inverse of a double matrix from numeric matrix
 */


public fun invF ( mat : MultiArray < Float , D2 > ) : NDArray < Float , D2 >


public fun < T : Complex > invC ( mat : MultiArray < T , D2 > ) : NDArray < T , D2 >

/**
 * Returns inverse complex matrix
 */


public fun < T : Number , D : Dim2 > solve ( a : MultiArray < T , D2 > , b : MultiArray < T , D > ) : NDArray < Double , D >

/**
 * Solve a linear matrix equation, or system of linear scalar equations.
 */


public fun < D : Dim2 > solveF ( a : MultiArray < Float , D2 > , b : MultiArray < Float , D > ) : NDArray < Float , D >


public fun < T : Complex , D : Dim2 > solveC ( a : MultiArray < T , D2 > , b : MultiArray < T , D > ) : NDArray < T , D >


public fun normF ( mat : MultiArray < Float , D2 > , norm : Norm = Norm . Fro ) : Float


public fun norm ( mat : MultiArray < Double , D2 > , norm : Norm = Norm . Fro ) : Double

/**
 * Returns norm of double matrix
 */


public fun < T : Number > qr ( mat : MultiArray < T , D2 > ) : Pair < D2Array < Double > , D2Array < Double > >

/**
 * Returns QR decomposition of the numeric matrix
 */


public fun qrF ( mat : MultiArray < Float , D2 > ) : Pair < D2Array < Float > , D2Array < Float > >

/**
 * Returns QR decomposition of the float matrix
 */


public fun < T : Complex > qrC ( mat : MultiArray < T , D2 > ) : Pair < D2Array < T > , D2Array < T > >

/**
 * Returns QR decomposition of the complex matrix
 */


public fun < T : Number > plu ( mat : MultiArray < T , D2 > ) : Triple < D2Array < Double > , D2Array < Double > , D2Array < Double > >

/**
 * Returns PLU decomposition of the numeric matrix
 */


public fun pluF ( mat : MultiArray < Float , D2 > ) : Triple < D2Array < Float > , D2Array < Float > , D2Array < Float > >

/**
 * Returns PLU decomposition of the float matrix
 */


public fun < T : Complex > pluC ( mat : MultiArray < T , D2 > ) : Triple < D2Array < T > , D2Array < T > , D2Array < T > >

/**
 * Returns PLU decomposition of the complex matrix
 */


@ ExperimentalMultikApi <EOL> public fun svdF ( mat : MultiArray < Float , D2 > ) : Triple < D2Array < Float > , D1Array < Float > , D2Array < Float > >

/**
 * Returns SVD decomposition of the float matrix
 */


@ ExperimentalMultikApi <EOL> public fun < T : Number > svd ( mat : MultiArray < T , D2 > ) : Triple < D2Array < Double > , D1Array < Double > , D2Array < Double > >

/**
 * Returns SVD decomposition of the numeric matrix
 */


@ ExperimentalMultikApi <EOL> public fun < T : Complex > svdC ( mat : MultiArray < T , D2 > ) : Triple < D2Array < T > , D1Array < T > , D2Array < T > >

/**
 * Returns SVD decomposition of the complex matrix
 */


public fun < T : Number > eig ( mat : MultiArray < T , D2 > ) : Pair < D1Array < ComplexDouble > , D2Array < ComplexDouble > >

/**
 * Calculates the eigenvalues and eigenvectors of a numeric matrix
 * @return a pair of a vector of eigenvalues and a matrix of eigenvectors
 */


public fun eigF ( mat : MultiArray < Float , D2 > ) : Pair < D1Array < ComplexFloat > , D2Array < ComplexFloat > >

/**
 * Calculates the eigenvalues and eigenvectors of a float matrix
 * @return a pair of a vector of eigenvalues and a matrix of eigenvectors
 */


public fun < T : Complex > eigC ( mat : MultiArray < T , D2 > ) : Pair < D1Array < T > , D2Array < T > >

/**
 * Calculates the eigenvalues and eigenvectors of a complex matrix
 * @return a pair of a vector of eigenvalues and a matrix of eigenvectors
 */


public fun < T : Number > eigVals ( mat : MultiArray < T , D2 > ) : D1Array < ComplexDouble >

/**
 * Calculates the eigenvalues of a numeric matrix.
 * @return [ComplexDouble] vector
 */


public fun eigValsF ( mat : MultiArray < Float , D2 > ) : D1Array < ComplexFloat >

/**
 * Calculates the eigenvalues of a float matrix
 * @return [ComplexFloat] vector
 */


public fun < T : Complex > eigValsC ( mat : MultiArray < T , D2 > ) : D1Array < T >

/**
 * Calculates the eigenvalues of a float matrix
 * @return complex vector
 */


public fun < T : Number > dotMM ( a : MultiArray < T , D2 > , b : MultiArray < T , D2 > ) : NDArray < T , D2 >

/**
 * Dot products of two number matrices.
 */


public fun < T : Complex > dotMMComplex ( a : MultiArray < T , D2 > , b : MultiArray < T , D2 > ) : NDArray < T , D2 >

/**
 * Dot products of two complex matrices.
 */


public fun < T : Number > dotMV ( a : MultiArray < T , D2 > , b : MultiArray < T , D1 > ) : NDArray < T , D1 >

/**
 * Dot products of number matrix and number vector.
 */


public fun < T : Complex > dotMVComplex ( a : MultiArray < T , D2 > , b : MultiArray < T , D1 > ) : NDArray < T , D1 >

/**
 * Dot products of complex matrix and complex vector.
 */


public fun < T : Number > dotVV ( a : MultiArray < T , D1 > , b : MultiArray < T , D1 > ) : T

/**
 * Dot products of two number vectors. Scalar product.
 */


public fun < T : Complex > dotVVComplex ( a : MultiArray < T , D1 > , b : MultiArray < T , D1 > ) : T

/**
 * Dot products of two complex vectors. Scalar product.
 */


abstract fun convertAttributeToAnnotation ( attribute : ConeAttribute < * > ) : FirAnnotation ?

/**
 * Please don't convert attributes which you didn't create
 * If [attribute] came from compiler or another plugin just return null
 */


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

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

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


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

= Flowable . fromPublisher ( publishInternal ( this , context , RX_HANDLER , block ) )


private fun ensureCapacity ( minCapacity : Int )

{ <EOL> if ( minCapacity < <NUM_LIT:0> ) throw IllegalStateException ( "<STR_LIT>" ) <EOL> if ( minCapacity <= elementData . size ) return <EOL> if ( elementData === emptyElementData ) { <EOL> elementData = arrayOfNulls ( minCapacity . coerceAtLeast ( defaultMinCapacity ) ) <EOL> return <EOL> } <EOL> val newCapacity = AbstractList . newCapacity ( elementData . size , minCapacity ) <EOL> copyElements ( newCapacity ) <EOL> }

/**
 * Ensures that the capacity of this deque is at least equal to the specified [minCapacity].
 *
 * If the current capacity is less than the [minCapacity], a new backing storage is allocated with greater capacity.
 * Otherwise, this method takes no action and simply returns.
 */


private fun copyElements ( newCapacity : Int )

{ <EOL> val newElements = arrayOfNulls < Any ? > ( newCapacity ) <EOL> elementData . copyInto ( newElements , <NUM_LIT:0> , head , elementData . size ) <EOL> elementData . copyInto ( newElements , elementData . size - head , <NUM_LIT:0> , head ) <EOL> head = <NUM_LIT:0> <EOL> elementData = newElements <EOL> }

/**
 * Creates a new array with the specified [newCapacity] size and copies elements in the [elementData] array to it.
 */


= if ( isEmpty ( ) ) throw NoSuchElementException ( "<STR_LIT>" ) else internalGet ( head )

/**
 * Returns the first element, or throws [NoSuchElementException] if this deque is empty.
 */


= if ( isEmpty ( ) ) null else internalGet ( head )

/**
 * Returns the first element, or `null` if this deque is empty.
 */


= if ( isEmpty ( ) ) throw NoSuchElementException ( "<STR_LIT>" ) else internalGet ( internalIndex ( lastIndex ) )

/**
 * Returns the last element, or throws [NoSuchElementException] if this deque is empty.
 */


= if ( isEmpty ( ) ) null else internalGet ( internalIndex ( lastIndex ) )

/**
 * Returns the last element, or `null` if this deque is empty.
 */


{ <EOL> registerModification ( ) <EOL> ensureCapacity ( size + <NUM_LIT:1> ) <EOL> head = decremented ( head ) <EOL> elementData [ head ] = element <EOL> size += <NUM_LIT:1> <EOL> }

/**
 * Prepends the specified [element] to this deque.
 */


{ <EOL> registerModification ( ) <EOL> ensureCapacity ( size + <NUM_LIT:1> ) <EOL> elementData [ internalIndex ( size ) ] = element <EOL> size += <NUM_LIT:1> <EOL> }

/**
 * Appends the specified [element] to this deque.
 */


{ <EOL> if ( isEmpty ( ) ) throw NoSuchElementException ( "<STR_LIT>" ) <EOL> registerModification ( ) <EOL> val element = internalGet ( head ) <EOL> elementData [ head ] = null <EOL> head = incremented ( head ) <EOL> size -= <NUM_LIT:1> <EOL> return element <EOL> }

/**
 * Removes the first element from this deque and returns that removed element, or throws [NoSuchElementException] if this deque is empty.
 */


= if ( isEmpty ( ) ) null else removeFirst ( )

/**
 * Removes the first element from this deque and returns that removed element, or returns `null` if this deque is empty.
 */


{ <EOL> if ( isEmpty ( ) ) throw NoSuchElementException ( "<STR_LIT>" ) <EOL> registerModification ( ) <EOL> val internalLastIndex = internalIndex ( lastIndex ) <EOL> val element = internalGet ( internalLastIndex ) <EOL> elementData [ internalLastIndex ] = null <EOL> size -= <NUM_LIT:1> <EOL> return element <EOL> }

/**
 * Removes the last element from this deque and returns that removed element, or throws [NoSuchElementException] if this deque is empty.
 */


= if ( isEmpty ( ) ) null else removeLast ( )

/**
 * Removes the last element from this deque and returns that removed element, or returns `null` if this deque is empty.
 */


private fun nullifyNonEmpty ( internalFromIndex : Int , internalToIndex : Int )

{ <EOL> if ( internalFromIndex < internalToIndex ) { <EOL> elementData . fill ( null , internalFromIndex , internalToIndex ) <EOL> } else { <EOL> elementData . fill ( null , internalFromIndex , elementData . size ) <EOL> elementData . fill ( null , <NUM_LIT:0> , internalToIndex ) <EOL> } <EOL> }

/** If `internalFromIndex == internalToIndex`, the buffer is considered full and all elements are nullified. */


fun lenetOnFashionMnistExportImportToTxt ( )

{ <EOL> val ( train , test ) = fashionMnist ( ) <EOL> val ( newTrain , validation ) = train . split ( <NUM_LIT> ) <EOL> lenet5 ( ) . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . fit ( trainingDataset = newTrain , validationDataset = validation , epochs = EPOCHS , trainBatchSize = TRAINING_BATCH_SIZE , validationBatchSize = TEST_BATCH_SIZE ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> it . save ( File ( PATH_TO_MODEL ) , writingMode = WritingMode . OVERRIDE ) <EOL> } <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> } <EOL> }

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


= lenetOnFashionMnistExportImportToTxt ( )


fun addMessageCallback ( callback : RawMessageCallback ) : RawMessageCallback

/**
 * Add callback for incoming message and return it
 */


fun removeMessageCallback ( callback : RawMessageCallback )

/**
 * Remove added message callback
 */


fun send ( socketName : JupyterSocketType , message : RawMessage , )

/**
 * Send raw [message] to a given [socketName]
 */


fun openComm ( target : String , data : JsonObject = Json . EMPTY , ) : Comm

/**
 * Creates a comm with a given target, generates unique ID for it. Sends comm_open request to frontend
 *
 * @param target Target to create comm for. Should be registered on frontend side.
 * @param data Content of comm_open message
 * @return Created comm
 */


fun closeComm ( id : String , data : JsonObject = Json . EMPTY , )

/**
 * Closes a comm with a given ID. Sends comm_close request to frontend
 *
 * @param id ID of a comm to close
 * @param data Content of comm_close message
 */


fun getComms ( target : String ? = null ) : Collection < Comm >

/**
 * Get all comms for a given target, or all opened comms if `target` is `null`
 */


fun registerCommTarget ( target : String , callback : CommOpenCallback , )

/**
 * Register a [callback] for `comm_open` with a specified [target]. Overrides already registered callback.
 *
 * @param target
 * @param callback
 */


fun unregisterCommTarget ( target : String )


fun send ( data : JsonObject )

/**
 * Send JSON data to this comm. Effectively sends `comm_msg` message to frontend
 */


fun onMessage ( action : CommMsgCallback ) : CommMsgCallback

/**
 * Add [action] callback for `comm_msg` requests. Doesn't override existing callbacks
 *
 * @return Added callback
 */


fun removeMessageCallback ( callback : CommMsgCallback )

/**
 * Remove added [onMessage] callback
 */


fun close ( data : JsonObject = Json . EMPTY , notifyClient : Boolean = true , )

/**
 * Closes a comm. Sends comm_close request to frontend if [notifyClient] is `true`
 */


fun onClose ( action : CommCloseCallback ) : CommCloseCallback

/**
 * Adds [action] callback for `comm_close` requests. Does not override existing callbacks
 */


fun removeCloseCallback ( callback : CommCloseCallback )

/**
 * Remove added [onClose] callback
 */


fun rawMessageCallback ( socket : JupyterSocketType , messageType : String ? , action : RawMessageAction , ) : RawMessageCallback

{ <EOL> return object : RawMessageCallback { <EOL> override val socket : JupyterSocketType get ( ) = socket <EOL> override val messageType : String ? get ( ) = messageType <EOL> override val action : RawMessageAction get ( ) = action <EOL> } <EOL> }

/**
 * Construct raw message callback
 */


inline fun < reified T > Comm . sendData ( data : T )

{ <EOL> send ( Json . encodeToJsonElement ( data ) . jsonObject ) <EOL> }

/**
 * Send an object. `data` should be serializable to JSON object
 * (generally it means that the corresponding class should be marked with @Serializable)
 */


public fun resolve ( dri : DRI ) : String ?

/**
 * @return Path to the page containing the [dri] or null if the path cannot be created
 * (eg. when the package-list does not contain [dri]'s package)
 */


private fun explicitVisibilityIsNotRequired ( declaration : FirMemberDeclaration , context : CheckerContext ) : Boolean

{ <EOL> return when ( declaration ) { <EOL> is FirPrimaryConstructor , <EOL> is FirPropertyAccessor , <EOL> is FirValueParameter , <EOL> is FirAnonymousFunction -> true <EOL> is FirCallableDeclaration -> { <EOL> val containingClass = context . containingDeclarations . lastOrNull ( ) as? FirRegularClass <EOL> if ( declaration is FirProperty && containingClass != null && ( containingClass . isData || containingClass . classKind == ClassKind . ANNOTATION_CLASS ) ) { <EOL> return true <EOL> } <EOL> declaration . isOverride || declaration . isLocalMember <EOL> } <EOL> else -> false <EOL> } <EOL> }

/**
 * Exclusion list:
 * 1. Primary constructors of public API classes
 * 2. Properties of data classes in public API
 * 3. Overrides of public API. Effectively, this means 'no report on overrides at all'
 * 4. Getters and setters (because getters can't change visibility and setter-only explicit visibility looks ugly)
 * 5. Properties of annotations in public API
 * 6. Value parameter declaration
 * 7. An anonymous function
 * 8. A local named function
 */


open fun getPackageNames ( ) : Set < String > ?

= null

/**
 * Returns the set of fully qualified package names which contain any top-level declaration within the provider's scope.
 *
 * [getPackageNames] is used as the default implementation for [getPackageNamesWithTopLevelClassifiers] and
 * [getPackageNamesWithTopLevelCallables]. It depends on the symbol names provider whether it's worth computing separate package sets
 * for classifiers and callables, or just one set containing all package names.
 */


open fun getPackageNamesWithTopLevelClassifiers ( ) : Set < String > ?

= getPackageNames ( )

/**
 * Returns the set of fully qualified package names which contain a top-level classifier declaration within the provider's scope.
 */


abstract fun getTopLevelClassifierNamesInPackage ( packageFqName : FqName ) : Set < Name > ?

/**
 * Returns the set of top-level classifier names (classes, interfaces, objects, and type aliases) inside the [packageFqName] package
 * within the provider's scope.
 *
 * All usages must take into account that the result might not include `kotlin.FunctionN` (and others for which a [FunctionTypeKind]
 * exists).
 */


open fun getPackageNamesWithTopLevelCallables ( ) : Set < String > ?

= getPackageNames ( )

/**
 * Returns the set of fully qualified package names which contain a top-level callable declaration within the provider's scope.
 */


abstract fun getTopLevelCallableNamesInPackage ( packageFqName : FqName ) : Set < Name > ?

/**
 * Returns the set of top-level callable names (functions and properties) inside the [packageFqName] package within the provider's
 * scope.
 *
 * When implementing this function, [getPackageNamesWithTopLevelCallables] should be taken into account. Specifically, if a package name
 * is not in the set of package names with top-level callables, [getTopLevelCallableNamesInPackage] must return an empty set or `null`.
 */


open fun mayHaveSyntheticFunctionType ( classId : ClassId ) : Boolean

= mayHaveSyntheticFunctionTypes

/**
 * Whether [classId] is considered a generated function type within the provider's scope and session.
 */


open fun mayHaveTopLevelClassifier ( classId : ClassId ) : Boolean

{ <EOL> if ( mayHaveSyntheticFunctionTypes && mayHaveSyntheticFunctionType ( classId ) ) return true <EOL> val names = getTopLevelClassifierNamesInPackage ( classId . packageFqName ) ? : return true <EOL> if ( classId . outerClassId == null ) { <EOL> if ( ! names . mayContainTopLevelClassifier ( classId . shortClassName ) ) return false <EOL> } else { <EOL> if ( ! names . mayContainTopLevelClassifier ( classId . outermostClassId . shortClassName ) ) return false <EOL> } <EOL> return true <EOL> }

/**
 * Checks if the provider's scope may contain a top-level classifier (class, interface, object, or type alias) with the given [classId].
 */


open fun mayHaveTopLevelCallable ( packageFqName : FqName , name : Name ) : Boolean

{ <EOL> if ( name . isSpecial ) return true <EOL> val names = getTopLevelCallableNamesInPackage ( packageFqName ) ? : return true <EOL> return name in names <EOL> }

/**
 * Checks if the provider's scope may contain a top-level callable (function or property) called [name] inside the [packageFqName]
 * package.
 */


public fun customFormat ( columnSeparator : String , lineSeparatorSymbol : Char , thickLineSeparatorSymbol : Char , inputsColumnHeader : String = "<STR_LIT>" , outputsColumnHeader : String = "<STR_LIT>" , typeColumnHeader : String = "<STR_LIT>" ) : List < String >

{ <EOL> val inputRows = inputsSummaries . map { ( name , summary ) -> <EOL> TableRow ( name , summary . toSummaryRow ( ) ) <EOL> } <EOL> val outputRows = outputsSummaries . map { ( name , summary ) -> <EOL> TableRow ( name , summary . toSummaryRow ( ) ) <EOL> } <EOL> val header = SimpleSection ( listOf ( "<STR_LIT>" ) ) <EOL> val inputsSection = SectionWithColumns ( inputRows , listOf ( inputsColumnHeader , typeColumnHeader ) ) <EOL> val outputsSection = SectionWithColumns ( outputRows , listOf ( outputsColumnHeader , typeColumnHeader ) ) <EOL> return formatTable ( listOf ( header , inputsSection , outputsSection ) , columnSeparator , lineSeparatorSymbol , thickLineSeparatorSymbol ) <EOL> }

/**
 * Format function with customizable column names.
 * @param [inputsColumnHeader] title of the column with input variables
 * @param [outputsColumnHeader] title of the column with output variables
 * @param [typeColumnHeader] title of the column with variable types
 */


public fun toSummaryRow ( ) : String

/**
 * Returns text description of the variable.
 */


@ Suppress ( "<STR_LIT:UNUSED_PARAMETER>" , "<STR_LIT:unused>" ) <EOL> @ PublishedApi <EOL> internal fun < T > ( suspend ( ) -> T ) . invokeSuspendSuperType ( completion : Continuation < T > ) : Any ?

{ <EOL> throw NotImplementedError ( "<STR_LIT>" ) <EOL> }

/**
 * Invoke 'invoke' method of suspend super type
 * Because callable references translated with local classes,
 * necessary to call it in special way, not in synamic way
 */


@ Suppress ( "<STR_LIT:UNUSED_PARAMETER>" , "<STR_LIT:unused>" ) <EOL> @ PublishedApi <EOL> internal fun < R , T > ( suspend R . ( ) -> T ) . invokeSuspendSuperTypeWithReceiver ( receiver : R , completion : Continuation < T > ) : Any ?

/**
 * Invoke 'invoke' method of suspend super type with receiver
 * Because callable references translated with local classes,
 * necessary to call it in special way, not in synamic way
 */


@ Suppress ( "<STR_LIT:UNUSED_PARAMETER>" , "<STR_LIT:unused>" ) <EOL> @ PublishedApi <EOL> internal fun < R , P , T > ( suspend R . ( P ) -> T ) . invokeSuspendSuperTypeWithReceiverAndParam ( receiver : R , param : P , completion : Continuation < T > ) : Any ?

/**
 * Invoke 'invoke' method of suspend super type with receiver and param
 * Because callable references translated with local classes,
 * necessary to call it in special way, not in synamic way
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ InlineOnly <EOL> public actual inline fun < T > ( suspend ( ) -> T ) . startCoroutineUninterceptedOrReturn ( completion : Continuation < T > ) : Any ?

{ <EOL> val a = this . asDynamic ( ) <EOL> return if ( jsTypeOf ( a ) == "<STR_LIT:function>" ) a ( completion ) <EOL> else this . invokeSuspendSuperType ( completion ) <EOL> }

/**
 * Starts unintercepted coroutine without receiver and with result type [T] and executes it until its first suspension.
 * Returns the result of the coroutine or throws its exception if it does not suspend or [COROUTINE_SUSPENDED] if it suspends.
 * In the latter case, the [completion] continuation is invoked when coroutine completes with result or exception.
 *
 * The coroutine is started directly in the invoker's thread without going through the [ContinuationInterceptor] that might
 * be present in the completion's [CoroutineContext]. It is the invoker's responsibility to ensure that a proper invocation
 * context is established.
 *
 * This function is designed to be used from inside of [suspendCoroutineUninterceptedOrReturn] to resume the execution of a suspended
 * coroutine using a reference to the suspending function.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> @ InlineOnly <EOL> public actual inline fun < R , T > ( suspend R . ( ) -> T ) . startCoroutineUninterceptedOrReturn ( receiver : R , completion : Continuation < T > ) : Any ?

{ <EOL> val a = this . asDynamic ( ) <EOL> return if ( jsTypeOf ( a ) == "<STR_LIT:function>" ) a ( receiver , completion ) <EOL> else this . invokeSuspendSuperTypeWithReceiver ( receiver , completion ) <EOL> }

/**
 * Starts unintercepted coroutine with receiver type [R] and result type [T] and executes it until its first suspension.
 * Returns the result of the coroutine or throws its exception if it does not suspend or [COROUTINE_SUSPENDED] if it suspends.
 * In the latter case, the [completion] continuation is invoked when coroutine completes with result or exception.
 *
 * The coroutine is started directly in the invoker's thread without going through the [ContinuationInterceptor] that might
 * be present in the completion's [CoroutineContext]. It is the invoker's responsibility to ensure that a proper invocation
 * context is established.
 *
 * This function is designed to be used from inside of [suspendCoroutineUninterceptedOrReturn] to resume the execution of a suspended
 * coroutine using a reference to the suspending function.
 */


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

= <EOL> createCoroutineFromSuspendFunction ( completion ) { <EOL> val a = this . asDynamic ( ) <EOL> if ( jsTypeOf ( a ) == "<STR_LIT:function>" ) a ( completion ) <EOL> else this . invokeSuspendSuperType ( completion ) <EOL> }

/**
 * Creates unintercepted coroutine without receiver and with result type [T].
 * This function creates a new, fresh instance of suspendable computation every time it is invoked.
 *
 * To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
 * The [completion] continuation is invoked when coroutine completes with result or exception.
 *
 * This function returns unintercepted continuation.
 * Invocation of `resume(Unit)` starts coroutine directly in the invoker's thread without going through the
 * [ContinuationInterceptor] that might be present in the completion's [CoroutineContext].
 * It is the invoker's responsibility to ensure that a proper invocation context is established.
 * [Continuation.intercepted] can be used to acquire the intercepted continuation.
 *
 * Repeated invocation of any resume function on the resulting continuation corrupts the
 * state machine of the coroutine and may result in arbitrary behaviour or exception.
 */


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

= <EOL> createCoroutineFromSuspendFunction ( completion ) { <EOL> val a = this . asDynamic ( ) <EOL> if ( jsTypeOf ( a ) == "<STR_LIT:function>" ) a ( receiver , completion ) <EOL> else this . invokeSuspendSuperTypeWithReceiver ( receiver , completion ) <EOL> }

/**
 * Creates unintercepted coroutine with receiver type [R] and result type [T].
 * This function creates a new, fresh instance of suspendable computation every time it is invoked.
 *
 * To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
 * The [completion] continuation is invoked when coroutine completes with result or exception.
 *
 * This function returns unintercepted continuation.
 * Invocation of `resume(Unit)` starts coroutine directly in the invoker's thread without going through the
 * [ContinuationInterceptor] that might be present in the completion's [CoroutineContext].
 * It is the invoker's responsibility to ensure that a proper invocation context is established.
 * [Continuation.intercepted] can be used to acquire the intercepted continuation.
 *
 * Repeated invocation of any resume function on the resulting continuation corrupts the
 * state machine of the coroutine and may result in arbitrary behaviour or exception.
 */


@ SinceKotlin ( "<STR_LIT:1.3>" ) <EOL> public actual fun < T > Continuation < T > . intercepted ( ) : Continuation < T >

= <EOL> ( this as? InterceptedCoroutine ) ? . intercepted ( ) ? : this

/**
 * Intercepts this continuation with [ContinuationInterceptor].
 */


fun BuildOptions . withBundledKotlinNative ( )

= copy ( nativeOptions = nativeOptions . copy ( version = null ) )

/**
 * This wrapper erases k/n version from passing parameters,
 * because we should use Kotlin Native bundled in KGP instead of which built from current branch.
 *
 * In this case we will use k/n version, which declared in KGP.
 *
 * The most common case is when we override local konan dir for some reason.
 */


@ Test <EOL> fun testTrySendNotThrowing ( )

= runTest { <EOL> var producerScope : ProducerScope < Int > ? = null <EOL> expect ( <NUM_LIT:1> ) <EOL> val flux = flux < Int > ( Dispatchers . Unconfined ) { <EOL> producerScope = this <EOL> expect ( <NUM_LIT:3> ) <EOL> delay ( Long . MAX_VALUE ) <EOL> } <EOL> val job = launch ( start = CoroutineStart . UNDISPATCHED ) { <EOL> expect ( <NUM_LIT:2> ) <EOL> flux . awaitFirstOrNull ( ) <EOL> expectUnreached ( ) <EOL> } <EOL> job . cancel ( ) <EOL> expect ( <NUM_LIT:4> ) <EOL> val result = producerScope ! ! . trySend ( <NUM_LIT:1> ) <EOL> assertTrue ( result . isFailure ) <EOL> finish ( <NUM_LIT:5> ) <EOL> }

/** Tests that `trySend` doesn't throw in `flux`. */


= runTest { <EOL> val flux = flux { <EOL> assertFailsWith < NullPointerException > { send ( null ) } <EOL> assertFailsWith < NullPointerException > { trySend ( null ) } <EOL> send ( "<STR_LIT:OK>" ) <EOL> } <EOL> assertEquals ( "<STR_LIT:OK>" , flux . awaitFirstOrNull ( ) ) <EOL> }

/** Tests that all methods on `flux` fail without closing the channel when attempting to emit `null`. */


@ Throws ( KtCodeCompilationException :: class ) <EOL> public fun compile ( file : KtFile , configuration : CompilerConfiguration , target : KtCompilerTarget , allowedErrorFilter : ( KtDiagnostic ) -> Boolean ) : KtCompilationResult

{ <EOL> return withValidityAssertion { <EOL> try { <EOL> analysisSession . compilerFacility . compile ( file , configuration , target , allowedErrorFilter ) <EOL> } catch ( e : ProcessCanceledException ) { <EOL> throw e <EOL> } catch ( e : Throwable ) { <EOL> throw KtCodeCompilationException ( e ) <EOL> } <EOL> } <EOL> }

/**
 * Compile the given [file] in-memory (without dumping the compiled binaries to a disk).
 *
 * @param file A file to compile.
 * The file must be either a source module file, or a [KtCodeFragment].
 * For a [KtCodeFragment], a source module context, a compiled library source context, or an empty context(`null`) are supported.
 *
 * @param configuration Compiler configuration.
 * It is recommended to submit at least the module name ([CommonConfigurationKeys.MODULE_NAME])
 * and language version settings ([CommonConfigurationKeys.LANGUAGE_VERSION_SETTINGS]).
 *
 * @param target Compilation target platform.
 *
 * @param allowedErrorFilter Filter for the allowed errors.
 * Compilation will be aborted if there are errors that this filter rejects.
 *
 * @return Compilation result.
 *
 * The function rethrows exceptions from the compiler, wrapped in [KtCodeCompilationException].
 * The implementation should wrap the `compile()` call into a `try`/`catch` block when necessary.
 */


@ PublishedApi <EOL> internal inline fun < T > unsafeFlow ( @ BuilderInference crossinline block : suspend FlowCollector < T > . ( ) -> Unit ) : Flow < T >

{ <EOL> return object : Flow < T > { <EOL> override suspend fun collect ( collector : FlowCollector < T > ) { <EOL> collector . block ( ) <EOL> } <EOL> } <EOL> }

/**
 * An analogue of the [flow] builder that does not check the context of execution of the resulting flow.
 * Used in our own operators where we trust the context of invocations.
 */


override fun getReferenceName ( ) : String ?

= referenceInformationProvider . referenceName

/**
 * @see com.intellij.psi.impl.PsiImplUtil.findAnnotation
 */


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < T1 , T2 , R > Flow < T1 > . combine ( flow : Flow < T2 > , transform : suspend ( a : T1 , b : T2 ) -> R ) : Flow < R >

= flow { <EOL> combineInternal ( arrayOf ( this @ combine , flow ) , nullArrayFactory ( ) , { emit ( transform ( it [ <NUM_LIT:0> ] as T1 , it [ <NUM_LIT:1> ] as T2 ) ) } ) <EOL> }

/**
 * Returns a [Flow] whose values are generated with [transform] function by combining
 * the most recently emitted values by each flow.
 *
 * It can be demonstrated with the following example:
 * ```
 * val flow = flowOf(1, 2).onEach { delay(10) }
 * val flow2 = flowOf("a", "b", "c").onEach { delay(15) }
 * flow.combine(flow2) { i, s -> i.toString() + s }.collect {
 * println(it) // Will print "1a 2a 2b 2c"
 * }
 * ```
 *
 * This function is a shorthand for `flow.combineTransform(flow2) { a, b -> emit(transform(a, b)) }
 */


public fun < T1 , T2 , R > combine ( flow : Flow < T1 > , flow2 : Flow < T2 > , transform : suspend ( a : T1 , b : T2 ) -> R ) : Flow < R >

= <EOL> flow . combine ( flow2 , transform )

/**
 * Returns a [Flow] whose values are generated with [transform] function by combining
 * the most recently emitted values by each flow.
 *
 * It can be demonstrated with the following example:
 * ```
 * val flow = flowOf(1, 2).onEach { delay(10) }
 * val flow2 = flowOf("a", "b", "c").onEach { delay(15) }
 * combine(flow, flow2) { i, s -> i.toString() + s }.collect {
 * println(it) // Will print "1a 2a 2b 2c"
 * }
 * ```
 *
 * This function is a shorthand for `combineTransform(flow, flow2) { a, b -> emit(transform(a, b)) }
 */


@ JvmName ( "<STR_LIT>" ) <EOL> public fun < T1 , T2 , R > Flow < T1 > . combineTransform ( flow : Flow < T2 > , @ BuilderInference transform : suspend FlowCollector < R > . ( a : T1 , b : T2 ) -> Unit ) : Flow < R >

= combineTransformUnsafe ( this , flow ) { args : Array < * > -> <EOL> transform ( args [ <NUM_LIT:0> ] as T1 , args [ <NUM_LIT:1> ] as T2 ) <EOL> }

/**
 * Returns a [Flow] whose values are generated by [transform] function that process the most recently emitted values by each flow.
 *
 * The receiver of the [transform] is [FlowCollector] and thus `transform` is a
 * generic function that may transform emitted element, skip it or emit it multiple times.
 *
 * Its usage can be demonstrated with the following example:
 * ```
 * val flow = requestFlow()
 * val flow2 = searchEngineFlow()
 * flow.combineTransform(flow2) { request, searchEngine ->
 * emit("Downloading in progress")
 * val result = download(request, searchEngine)
 * emit(result)
 * }
 * ```
 */


public fun < T1 , T2 , R > combineTransform ( flow : Flow < T1 > , flow2 : Flow < T2 > , @ BuilderInference transform : suspend FlowCollector < R > . ( a : T1 , b : T2 ) -> Unit ) : Flow < R >

= combineTransformUnsafe ( flow , flow2 ) { args : Array < * > -> <EOL> transform ( args [ <NUM_LIT:0> ] as T1 , args [ <NUM_LIT:1> ] as T2 ) <EOL> }

/**
 * Returns a [Flow] whose values are generated by [transform] function that process the most recently emitted values by each flow.
 *
 * The receiver of the [transform] is [FlowCollector] and thus `transform` is a
 * generic function that may transform emitted element, skip it or emit it multiple times.
 *
 * Its usage can be demonstrated with the following example:
 * ```
 * val flow = requestFlow()
 * val flow2 = searchEngineFlow()
 * combineTransform(flow, flow2) { request, searchEngine ->
 * emit("Downloading in progress")
 * val result = download(request, searchEngine)
 * emit(result)
 * }
 * ```
 */


public fun < T1 , T2 , T3 , R > combine ( flow : Flow < T1 > , flow2 : Flow < T2 > , flow3 : Flow < T3 > , @ BuilderInference transform : suspend ( T1 , T2 , T3 ) -> R ) : Flow < R >

= combineUnsafe ( flow , flow2 , flow3 ) { args : Array < * > -> <EOL> transform ( args [ <NUM_LIT:0> ] as T1 , args [ <NUM_LIT:1> ] as T2 , args [ <NUM_LIT:2> ] as T3 ) <EOL> }

/**
 * Returns a [Flow] whose values are generated with [transform] function by combining
 * the most recently emitted values by each flow.
 */


public fun < T1 , T2 , T3 , R > combineTransform ( flow : Flow < T1 > , flow2 : Flow < T2 > , flow3 : Flow < T3 > , @ BuilderInference transform : suspend FlowCollector < R > . ( T1 , T2 , T3 ) -> Unit ) : Flow < R >

= combineTransformUnsafe ( flow , flow2 , flow3 ) { args : Array < * > -> <EOL> transform ( args [ <NUM_LIT:0> ] as T1 , args [ <NUM_LIT:1> ] as T2 , args [ <NUM_LIT:2> ] as T3 ) <EOL> }

/**
 * Returns a [Flow] whose values are generated by [transform] function that process the most recently emitted values by each flow.
 *
 * The receiver of the [transform] is [FlowCollector] and thus `transform` is a
 * generic function that may transform emitted element, skip it or emit it multiple times.
 */


public fun < T1 , T2 , T3 , T4 , R > combine ( flow : Flow < T1 > , flow2 : Flow < T2 > , flow3 : Flow < T3 > , flow4 : Flow < T4 > , transform : suspend ( T1 , T2 , T3 , T4 ) -> R ) : Flow < R >

= combineUnsafe ( flow , flow2 , flow3 , flow4 ) { args : Array < * > -> <EOL> transform ( args [ <NUM_LIT:0> ] as T1 , args [ <NUM_LIT:1> ] as T2 , args [ <NUM_LIT:2> ] as T3 , args [ <NUM_LIT:3> ] as T4 ) <EOL> }


public fun < T1 , T2 , T3 , T4 , R > combineTransform ( flow : Flow < T1 > , flow2 : Flow < T2 > , flow3 : Flow < T3 > , flow4 : Flow < T4 > , @ BuilderInference transform : suspend FlowCollector < R > . ( T1 , T2 , T3 , T4 ) -> Unit ) : Flow < R >

= combineTransformUnsafe ( flow , flow2 , flow3 , flow4 ) { args : Array < * > -> <EOL> transform ( args [ <NUM_LIT:0> ] as T1 , args [ <NUM_LIT:1> ] as T2 , args [ <NUM_LIT:2> ] as T3 , args [ <NUM_LIT:3> ] as T4 ) <EOL> }


public fun < T1 , T2 , T3 , T4 , T5 , R > combine ( flow : Flow < T1 > , flow2 : Flow < T2 > , flow3 : Flow < T3 > , flow4 : Flow < T4 > , flow5 : Flow < T5 > , transform : suspend ( T1 , T2 , T3 , T4 , T5 ) -> R ) : Flow < R >

= combineUnsafe ( flow , flow2 , flow3 , flow4 , flow5 ) { args : Array < * > -> <EOL> transform ( args [ <NUM_LIT:0> ] as T1 , args [ <NUM_LIT:1> ] as T2 , args [ <NUM_LIT:2> ] as T3 , args [ <NUM_LIT:3> ] as T4 , args [ <NUM_LIT:4> ] as T5 ) <EOL> }


public fun < T1 , T2 , T3 , T4 , T5 , R > combineTransform ( flow : Flow < T1 > , flow2 : Flow < T2 > , flow3 : Flow < T3 > , flow4 : Flow < T4 > , flow5 : Flow < T5 > , @ BuilderInference transform : suspend FlowCollector < R > . ( T1 , T2 , T3 , T4 , T5 ) -> Unit ) : Flow < R >

= combineTransformUnsafe ( flow , flow2 , flow3 , flow4 , flow5 ) { args : Array < * > -> <EOL> transform ( args [ <NUM_LIT:0> ] as T1 , args [ <NUM_LIT:1> ] as T2 , args [ <NUM_LIT:2> ] as T3 , args [ <NUM_LIT:3> ] as T4 , args [ <NUM_LIT:4> ] as T5 ) <EOL> }


public inline fun < reified T , R > combine ( vararg flows : Flow < T > , crossinline transform : suspend ( Array < T > ) -> R ) : Flow < R >

= flow { <EOL> combineInternal ( flows , { arrayOfNulls ( flows . size ) } , { emit ( transform ( it ) ) } ) <EOL> }


public inline fun < reified T , R > combineTransform ( vararg flows : Flow < T > , @ BuilderInference crossinline transform : suspend FlowCollector < R > . ( Array < T > ) -> Unit ) : Flow < R >

= safeFlow { <EOL> combineInternal ( flows , { arrayOfNulls ( flows . size ) } , { transform ( it ) } ) <EOL> }


public inline fun < reified T , R > combine ( flows : Iterable < Flow < T > > , crossinline transform : suspend ( Array < T > ) -> R ) : Flow < R >

{ <EOL> val flowArray = flows . toList ( ) . toTypedArray ( ) <EOL> return flow { <EOL> combineInternal ( flowArray , arrayFactory = { arrayOfNulls ( flowArray . size ) } , transform = { emit ( transform ( it ) ) } ) <EOL> } <EOL> }


public inline fun < reified T , R > combineTransform ( flows : Iterable < Flow < T > > , @ BuilderInference crossinline transform : suspend FlowCollector < R > . ( Array < T > ) -> Unit ) : Flow < R >

{ <EOL> val flowArray = flows . toList ( ) . toTypedArray ( ) <EOL> return safeFlow { <EOL> combineInternal ( flowArray , { arrayOfNulls ( flowArray . size ) } , { transform ( it ) } ) <EOL> } <EOL> }


public fun < T1 , T2 , R > Flow < T1 > . zip ( other : Flow < T2 > , transform : suspend ( T1 , T2 ) -> R ) : Flow < R >

= zipImpl ( this , other , transform )

/**
 * Zips values from the current flow (`this`) with [other] flow using provided [transform] function applied to each pair of values.
 * The resulting flow completes as soon as one of the flows completes and cancel is called on the remaining flow.
 *
 * It can be demonstrated with the following example:
 * ```
 * val flow = flowOf(1, 2, 3).onEach { delay(10) }
 * val flow2 = flowOf("a", "b", "c", "d").onEach { delay(15) }
 * flow.zip(flow2) { i, s -> i.toString() + s }.collect {
 * println(it) // Will print "1a 2b 3c"
 * }
 * ```
 *
 * ### Buffering
 *
 * The upstream flow is collected sequentially in the same coroutine without any buffering, while the
 * [other] flow is collected concurrently as if `buffer(0)` is used. See documentation in the [buffer] operator
 * for explanation. You can use additional calls to the [buffer] operator as needed for more concurrency.
 */


internal inline fun < reified T : Any > ComponentManager . serviceOrNull ( ) : T ?

{ <EOL> return getService ( T :: class . java ) <EOL> }

/**
 * Returns `null` if the service cannot be found in [this] component manager,
 * otherwise initializes a service if not yet initialized, and returns the service instance.
 * @see ComponentManager.getService
 */


fun findOrGenerateCEnum ( classDescriptor : ClassDescriptor , parent : IrDeclarationContainer ) : IrClass

{ <EOL> val irClassSymbol = symbolTable . descriptorExtension . referenceClass ( classDescriptor ) <EOL> return if ( ! irClassSymbol . isBound ) { <EOL> provideIrClassForCEnum ( classDescriptor ) . also { <EOL> it . patchDeclarationParents ( parent ) <EOL> parent . declarations += it <EOL> } <EOL> } else { <EOL> irClassSymbol . owner <EOL> } <EOL> }

/**
 * Searches for an IR class for [classDescriptor] in symbol table.
 * Generates one if absent.
 */


private fun provideIrClassForCEnum ( descriptor : ClassDescriptor ) : IrClass

= <EOL> createClass ( descriptor ) { enumIrClass -> <EOL> enumIrClass . addMember ( createEnumPrimaryConstructor ( descriptor ) ) <EOL> enumIrClass . addMember ( createValueProperty ( enumIrClass ) ) <EOL> descriptor . enumEntries . mapTo ( enumIrClass . declarations ) { entryDescriptor -> <EOL> createEnumEntry ( descriptor , entryDescriptor ) <EOL> } <EOL> enumClassMembersGenerator . generateSpecialMembers ( enumIrClass ) <EOL> enumIrClass . addChild ( cEnumCompanionGenerator . generate ( enumIrClass ) ) <EOL> enumIrClass . addChild ( cEnumVarClassGenerator . generate ( enumIrClass ) ) <EOL> }

/**
 * The main function that for given [descriptor] of the enum generates the whole
 * IR tree including entries, CEnumVar class, and companion objects.
 */


private fun createValueProperty ( irClass : IrClass ) : IrProperty

{ <EOL> val propertyDescriptor = irClass . descriptor <EOL> . findDeclarationByName < PropertyDescriptor > ( "<STR_LIT:value>" ) <EOL> ? : error ( "<STR_LIT>" ) <EOL> val irProperty = createProperty ( propertyDescriptor ) <EOL> symbolTable . withScope ( irProperty ) { <EOL> irProperty . backingField = symbolTable . descriptorExtension . declareField ( SYNTHETIC_OFFSET , SYNTHETIC_OFFSET , IrDeclarationOrigin . PROPERTY_BACKING_FIELD , propertyDescriptor , propertyDescriptor . type . toIrType ( ) , DescriptorVisibilities . PRIVATE ) . also { <EOL> postLinkageSteps . add { <EOL> it . initializer = irBuiltIns . createIrBuilder ( it . symbol , SYNTHETIC_OFFSET , SYNTHETIC_OFFSET ) . run { <EOL> irExprBody ( irGet ( irClass . primaryConstructor ! ! . valueParameters [ <NUM_LIT:0> ] ) ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> val getter = irProperty . getter ! ! <EOL> getter . correspondingPropertySymbol = irProperty . symbol <EOL> postLinkageSteps . add { <EOL> getter . body = irBuiltIns . createIrBuilder ( getter . symbol , SYNTHETIC_OFFSET , SYNTHETIC_OFFSET ) . irBlockBody { <EOL> + irReturn ( irGetField ( irGet ( getter . dispatchReceiverParameter ! ! ) , irProperty . backingField ! ! <EOL> ) ) <EOL> } <EOL> } <EOL> return irProperty <EOL> }

/**
 * Creates `value` property that stores integral value of the enum.
 */


private fun extractEnumEntryValue ( entryDescriptor : ClassDescriptor ) : IrExpression

= <EOL> cEnumEntryValueTypes . firstNotNullOfOrNull { extractConstantValue ( entryDescriptor , it ) } ? . let { <EOL> context . constantValueGenerator . generateConstantValueAsExpression ( SYNTHETIC_OFFSET , SYNTHETIC_OFFSET , it ) <EOL> } ? : error ( "<STR_LIT>" )

/**
 * Every enum entry that came from metadata-based interop library is annotated with
 * [kotlinx.cinterop.internal.ConstantValue] annotation that holds internal constant value of the
 * corresponding entry.
 *
 * This function extracts value from the annotation.
 */


fun < K , V > JavaDStream < Tuple2 < K , V > > . groupByKey ( numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , ) : JavaDStream < Tuple2 < K , Iterable < V > > >

= <EOL> toPairDStream ( ) <EOL> . groupByKey ( numPartitions ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying `groupByKey` to each RDD. Hash partitioning is used to
 * generate the RDDs with `numPartitions` partitions.
 */


fun < K , V > JavaDStream < Tuple2 < K , V > > . groupByKey ( partitioner : Partitioner ) : JavaDStream < Tuple2 < K , Iterable < V > > >

= <EOL> toPairDStream ( ) <EOL> . groupByKey ( partitioner ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying `groupByKey` on each RDD. The supplied
 * org.apache.spark.Partitioner is used to control the partitioning of each RDD.
 */


fun < K , V > JavaDStream < Tuple2 < K , V > > . reduceByKey ( numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , reduceFunc : ( V , V ) -> V , ) : JavaDStream < Tuple2 < K , V > >

= <EOL> toPairDStream ( ) <EOL> . reduceByKey ( reduceFunc , numPartitions ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying `reduceByKey` to each RDD. The values for each key are
 * merged using the supplied reduce function. Hash partitioning is used to generate the RDDs
 * with `numPartitions` partitions.
 */


fun < K , V > JavaDStream < Tuple2 < K , V > > . reduceByKey ( partitioner : Partitioner , reduceFunc : ( V , V ) -> V , ) : JavaDStream < Tuple2 < K , V > >

= <EOL> toPairDStream ( ) <EOL> . reduceByKey ( reduceFunc , partitioner ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying `reduceByKey` to each RDD. The values for each key are
 * merged using the supplied reduce function. org.apache.spark.Partitioner is used to control
 * the partitioning of each RDD.
 */


fun < K , V , C > JavaDStream < Tuple2 < K , V > > . combineByKey ( createCombiner : ( V ) -> C , mergeValue : ( C , V ) -> C , mergeCombiner : ( C , C ) -> C , numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , mapSideCombine : Boolean = true , ) : JavaDStream < Tuple2 < K , C > >

= <EOL> toPairDStream ( ) <EOL> . combineByKey ( createCombiner , mergeValue , mergeCombiner , HashPartitioner ( numPartitions ) , mapSideCombine ) <EOL> . toTupleDStream ( )

/**
 * Combine elements of each key in DStream's RDDs using custom functions. This is similar to the
 * combineByKey for RDDs. Please refer to combineByKey in
 * org.apache.spark.rdd.PairRDDFunctions in the Spark core documentation for more information.
 */


fun < K , V , C > JavaDStream < Tuple2 < K , V > > . combineByKey ( createCombiner : ( V ) -> C , mergeValue : ( C , V ) -> C , mergeCombiner : ( C , C ) -> C , partitioner : Partitioner , mapSideCombine : Boolean = true , ) : JavaDStream < Tuple2 < K , C > >

= <EOL> toPairDStream ( ) <EOL> . combineByKey ( createCombiner , mergeValue , mergeCombiner , partitioner , mapSideCombine ) <EOL> . toTupleDStream ( )


fun < K , V > JavaDStream < Tuple2 < K , V > > . groupByKeyAndWindow ( windowDuration : Duration , slideDuration : Duration = dstream ( ) . slideDuration ( ) , numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , ) : JavaDStream < Tuple2 < K , Iterable < V > > >

= <EOL> toPairDStream ( ) <EOL> . groupByKeyAndWindow ( windowDuration , slideDuration , numPartitions ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying `groupByKey` over a sliding window on `this` DStream.
 * Similar to `DStream.groupByKey()`, but applies it over a sliding window.
 * Hash partitioning is used to generate the RDDs with `numPartitions` partitions.
 * @param windowDuration width of the window; must be a multiple of this DStream's
 * batching interval
 * @param slideDuration sliding interval of the window (i.e., the interval after which
 * the new DStream will generate RDDs); must be a multiple of this
 * DStream's batching interval
 * @param numPartitions number of partitions of each RDD in the new DStream; if not specified
 * then Spark's default number of partitions will be used
 */


fun < K , V > JavaDStream < Tuple2 < K , V > > . groupByKeyAndWindow ( windowDuration : Duration , slideDuration : Duration = dstream ( ) . slideDuration ( ) , partitioner : Partitioner , ) : JavaDStream < Tuple2 < K , Iterable < V > > >

= <EOL> toPairDStream ( ) <EOL> . groupByKeyAndWindow ( windowDuration , slideDuration , partitioner ) <EOL> . toTupleDStream ( )

/**
 * Create a new DStream by applying `groupByKey` over a sliding window on `this` DStream.
 * Similar to `DStream.groupByKey()`, but applies it over a sliding window.
 * @param windowDuration width of the window; must be a multiple of this DStream's
 * batching interval
 * @param slideDuration sliding interval of the window (i.e., the interval after which
 * the new DStream will generate RDDs); must be a multiple of this
 * DStream's batching interval
 * @param partitioner partitioner for controlling the partitioning of each RDD in the new
 * DStream.
 */


fun < K , V > JavaDStream < Tuple2 < K , V > > . reduceByKeyAndWindow ( windowDuration : Duration , slideDuration : Duration = dstream ( ) . slideDuration ( ) , numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , reduceFunc : ( V , V ) -> V , ) : JavaDStream < Tuple2 < K , V > >

= <EOL> toPairDStream ( ) <EOL> . reduceByKeyAndWindow ( reduceFunc , windowDuration , slideDuration , numPartitions ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying `reduceByKey` over a sliding window. This is similar to
 * `DStream.reduceByKey()` but applies it over a sliding window. Hash partitioning is used to
 * generate the RDDs with `numPartitions` partitions.
 * @param reduceFunc associative and commutative reduce function
 * @param windowDuration width of the window; must be a multiple of this DStream's
 * batching interval
 * @param slideDuration sliding interval of the window (i.e., the interval after which
 * the new DStream will generate RDDs); must be a multiple of this
 * DStream's batching interval
 * @param numPartitions number of partitions of each RDD in the new DStream.
 */


fun < K , V > JavaDStream < Tuple2 < K , V > > . reduceByKeyAndWindow ( windowDuration : Duration , slideDuration : Duration = dstream ( ) . slideDuration ( ) , partitioner : Partitioner , reduceFunc : ( V , V ) -> V , ) : JavaDStream < Tuple2 < K , V > >

= <EOL> toPairDStream ( ) <EOL> . reduceByKeyAndWindow ( reduceFunc , windowDuration , slideDuration , partitioner ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying `reduceByKey` over a sliding window. Similar to
 * `DStream.reduceByKey()`, but applies it over a sliding window.
 * @param reduceFunc associative and commutative reduce function
 * @param windowDuration width of the window; must be a multiple of this DStream's
 * batching interval
 * @param slideDuration sliding interval of the window (i.e., the interval after which
 * the new DStream will generate RDDs); must be a multiple of this
 * DStream's batching interval
 * @param partitioner partitioner for controlling the partitioning of each RDD
 * in the new DStream.
 */


fun < K , V > JavaDStream < Tuple2 < K , V > > . reduceByKeyAndWindow ( invReduceFunc : ( V , V ) -> V , windowDuration : Duration , slideDuration : Duration = dstream ( ) . slideDuration ( ) , numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , filterFunc : ( ( Tuple2 < K , V > ) -> Boolean ) ? = null , reduceFunc : ( V , V ) -> V , ) : JavaDStream < Tuple2 < K , V > >

= <EOL> toPairDStream ( ) <EOL> . reduceByKeyAndWindow ( reduceFunc , invReduceFunc , windowDuration , slideDuration , numPartitions , filterFunc ? . let { <EOL> { tuple : Tuple2 < K , V > -> <EOL> filterFunc ( tuple ) <EOL> } <EOL> } ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying incremental `reduceByKey` over a sliding window.
 * The reduced value of over a new window is calculated using the old window's reduced value :
 * 1. reduce the new values that entered the window (e.g., adding new counts)
 *
 * 2. "inverse reduce" the old values that left the window (e.g., subtracting old counts)
 *
 * This is more efficient than reduceByKeyAndWindow without "inverse reduce" function.
 * However, it is applicable to only "invertible reduce functions".
 * Hash partitioning is used to generate the RDDs with Spark's default number of partitions.
 * @param reduceFunc associative and commutative reduce function
 * @param invReduceFunc inverse reduce function; such that for all y, invertible x:
 * `invReduceFunc(reduceFunc(x, y), x) = y`
 * @param windowDuration width of the window; must be a multiple of this DStream's
 * batching interval
 * @param slideDuration sliding interval of the window (i.e., the interval after which
 * the new DStream will generate RDDs); must be a multiple of this
 * DStream's batching interval
 * @param filterFunc Optional function to filter expired key-value pairs;
 * only pairs that satisfy the function are retained
 */


fun < K , V > JavaDStream < Tuple2 < K , V > > . reduceByKeyAndWindow ( invReduceFunc : ( V , V ) -> V , windowDuration : Duration , slideDuration : Duration = dstream ( ) . slideDuration ( ) , partitioner : Partitioner , filterFunc : ( ( Tuple2 < K , V > ) -> Boolean ) ? = null , reduceFunc : ( V , V ) -> V , ) : JavaDStream < Tuple2 < K , V > >

= <EOL> toPairDStream ( ) <EOL> . reduceByKeyAndWindow ( reduceFunc , invReduceFunc , windowDuration , slideDuration , partitioner , filterFunc ? . let { <EOL> { tuple : Tuple2 < K , V > -> <EOL> filterFunc ( tuple ) <EOL> } <EOL> } ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying incremental `reduceByKey` over a sliding window.
 * The reduced value of over a new window is calculated using the old window's reduced value :
 * 1. reduce the new values that entered the window (e.g., adding new counts)
 * 2. "inverse reduce" the old values that left the window (e.g., subtracting old counts)
 * This is more efficient than reduceByKeyAndWindow without "inverse reduce" function.
 * However, it is applicable to only "invertible reduce functions".
 * @param reduceFunc associative and commutative reduce function
 * @param invReduceFunc inverse reduce function
 * @param windowDuration width of the window; must be a multiple of this DStream's
 * batching interval
 * @param slideDuration sliding interval of the window (i.e., the interval after which
 * the new DStream will generate RDDs); must be a multiple of this
 * DStream's batching interval
 * @param partitioner partitioner for controlling the partitioning of each RDD in the new
 * DStream.
 * @param filterFunc Optional function to filter expired key-value pairs;
 * only pairs that satisfy the function are retained
 */


fun < K , V , StateType , MappedType > JavaDStream < Tuple2 < K , V > > . mapWithState ( spec : StateSpec < K , V , StateType , MappedType > , ) : JavaMapWithStateDStream < K , V , StateType , MappedType >

= <EOL> toPairDStream ( ) . mapWithState ( spec )

/**
 * Return a [JavaMapWithStateDStream] by applying a function to every key-value element of
 * `this` stream, while maintaining some state data for each unique key. The mapping function
 * and other specification (e.g. partitioners, timeouts, initial state data, etc.) of this
 * transformation can be specified using `StateSpec` class. The state data is accessible in
 * as a parameter of type `State` in the mapping function.
 *
 * Example of using `mapWithState`:
 * ```kotlin
 * // A mapping function that maintains an integer state and return a String
 * fun mappingFunction(key: String, value: Optional<Int>, state: State<Int>): Optional<String> {
 * // Use state.exists(), state.get(), state.update() and state.remove()
 * // to manage state, and return the necessary string
 * }
 *
 * val spec = StateSpec.function(::mappingFunction).numPartitions(10)
 *
 * val mapWithStateDStream = keyValueDStream.mapWithState<StateType, MappedType>(spec)
 * ```
 *
 * @param spec Specification of this transformation
 * @tparam StateType Class type of the state data
 * @tparam MappedType Class type of the mapped data
 */


@ JvmName ( "<STR_LIT>" ) <EOL> fun < K , V , S > JavaDStream < Tuple2 < K , V > > . updateStateByKey ( numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , updateFunc : ( List < V > , S ? ) -> S ? , ) : JavaDStream < Tuple2 < K , S > >

= <EOL> toPairDStream ( ) <EOL> . updateStateByKey ( { list : List < V > , s : Optional < S > -> <EOL> updateFunc ( list , s . getOrNull ( ) ) . toOptional ( ) <EOL> } , numPartitions , ) <EOL> . toTupleDStream ( )

/**
 * Return a new "state" DStream where the state for each key is updated by applying
 * the given function on the previous state of the key and the new values of each key.
 * In every batch the updateFunc will be called for each state even if there are no new values.
 * Hash partitioning is used to generate the RDDs with Spark's default number of partitions.
 * Note: Needs checkpoint directory to be set.
 * @param updateFunc State update function. If `this` function returns `null`, then
 * corresponding state key-value pair will be eliminated.
 * @tparam S State type
 */


@ JvmName ( "<STR_LIT>" ) <EOL> fun < K , V , S > JavaDStream < Tuple2 < K , V > > . updateStateByKey ( numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , updateFunc : ( List < V > , Optional < S > ) -> Optional < S > , ) : JavaDStream < Tuple2 < K , S > >

= <EOL> toPairDStream ( ) <EOL> . updateStateByKey ( updateFunc , numPartitions , ) <EOL> . toTupleDStream ( )


@ JvmName ( "<STR_LIT>" ) <EOL> fun < K , V , S > JavaDStream < Tuple2 < K , V > > . updateStateByKey ( partitioner : Partitioner , updateFunc : ( List < V > , S ? ) -> S ? , ) : JavaDStream < Tuple2 < K , S > >

= <EOL> toPairDStream ( ) <EOL> . updateStateByKey ( { list : List < V > , s : Optional < S > -> <EOL> updateFunc ( list , s . getOrNull ( ) ) . toOptional ( ) <EOL> } , partitioner , ) <EOL> . toTupleDStream ( )

/**
 * Return a new "state" DStream where the state for each key is updated by applying
 * the given function on the previous state of the key and the new values of each key.
 * In every batch the updateFunc will be called for each state even if there are no new values.
 * [[org.apache.spark.Partitioner]] is used to control the partitioning of each RDD.
 * Note: Needs checkpoint directory to be set.
 * @param updateFunc State update function. Note, that this function may generate a different
 * tuple with a different key than the input key. Therefore keys may be removed
 * or added in this way. It is up to the developer to decide whether to
 * remember the partitioner despite the key being changed.
 * @param partitioner Partitioner for controlling the partitioning of each RDD in the new
 * DStream
 * @tparam S State type
 */


fun < K , V , S > JavaDStream < Tuple2 < K , V > > . updateStateByKey ( partitioner : Partitioner , updateFunc : ( List < V > , Optional < S > ) -> Optional < S > , ) : JavaDStream < Tuple2 < K , S > >

= <EOL> toPairDStream ( ) <EOL> . updateStateByKey ( updateFunc , partitioner , ) <EOL> . toTupleDStream ( )


@ JvmName ( "<STR_LIT>" ) <EOL> fun < K , V , S > JavaDStream < Tuple2 < K , V > > . updateStateByKey ( partitioner : Partitioner , initialRDD : JavaRDD < Tuple2 < K , S > > , updateFunc : ( List < V > , S ? ) -> S ? , ) : JavaDStream < Tuple2 < K , S > >

= <EOL> toPairDStream ( ) <EOL> . updateStateByKey ( { list : List < V > , s : Optional < S > -> <EOL> updateFunc ( list , s . getOrNull ( ) ) . toOptional ( ) <EOL> } , partitioner , initialRDD . toJavaPairRDD ( ) , ) <EOL> . toTupleDStream ( )

/**
 * Return a new "state" DStream where the state for each key is updated by applying
 * the given function on the previous state of the key and the new values of the key.
 * org.apache.spark.Partitioner is used to control the partitioning of each RDD.
 * Note: Needs checkpoint directory to be set.
 * @param updateFunc State update function. If `this` function returns `null`, then
 * corresponding state key-value pair will be eliminated.
 * @param partitioner Partitioner for controlling the partitioning of each RDD in the new
 * DStream.
 * @param initialRDD initial state value of each key.
 * @tparam S State type
 */


fun < K , V , S > JavaDStream < Tuple2 < K , V > > . updateStateByKey ( partitioner : Partitioner , initialRDD : JavaRDD < Tuple2 < K , S > > , updateFunc : ( List < V > , Optional < S > ) -> Optional < S > , ) : JavaDStream < Tuple2 < K , S > >

= <EOL> toPairDStream ( ) <EOL> . updateStateByKey ( updateFunc , partitioner , initialRDD . toJavaPairRDD ( ) , ) <EOL> . toTupleDStream ( )


fun < K , V , U > JavaDStream < Tuple2 < K , V > > . mapValues ( mapValuesFunc : ( V ) -> U , ) : JavaDStream < Tuple2 < K , U > >

= <EOL> toPairDStream ( ) <EOL> . mapValues ( mapValuesFunc ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying a map function to the value of each key-value pairs in
 * 'this' DStream without changing the key.
 */


fun < K , V , U > JavaDStream < Tuple2 < K , V > > . flatMapValues ( flatMapValuesFunc : ( V ) -> Iterator < U > , ) : JavaDStream < Tuple2 < K , U > >

= <EOL> toPairDStream ( ) <EOL> . flatMapValues ( flatMapValuesFunc ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying a flatmap function to the value of each key-value pairs in
 * 'this' DStream without changing the key.
 */


fun < K , V , W > JavaDStream < Tuple2 < K , V > > . cogroup ( other : JavaDStream < Tuple2 < K , W > > , numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , ) : JavaDStream < Tuple2 < K , Tuple2 < Iterable < V > , Iterable < W > > > >

= <EOL> toPairDStream ( ) <EOL> . cogroup ( other . toPairDStream ( ) , numPartitions , ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying 'cogroup' between RDDs of `this` DStream and `other` DStream.
 * Hash partitioning is used to generate the RDDs with `numPartitions` partitions.
 */


fun < K , V , W > JavaDStream < Tuple2 < K , V > > . cogroup ( other : JavaDStream < Tuple2 < K , W > > , partitioner : Partitioner , ) : JavaDStream < Tuple2 < K , Tuple2 < Iterable < V > , Iterable < W > > > >

= <EOL> toPairDStream ( ) <EOL> . cogroup ( other . toPairDStream ( ) , partitioner , ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying 'cogroup' between RDDs of `this` DStream and `other` DStream.
 * The supplied org.apache.spark.Partitioner is used to partition the generated RDDs.
 */


fun < K , V , W > JavaDStream < Tuple2 < K , V > > . join ( other : JavaDStream < Tuple2 < K , W > > , numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , ) : JavaDStream < Tuple2 < K , Tuple2 < V , W > > >

= <EOL> toPairDStream ( ) <EOL> . join ( other . toPairDStream ( ) , numPartitions , ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying 'join' between RDDs of `this` DStream and `other` DStream.
 * Hash partitioning is used to generate the RDDs with `numPartitions` partitions.
 */


fun < K , V , W > JavaDStream < Tuple2 < K , V > > . join ( other : JavaDStream < Tuple2 < K , W > > , partitioner : Partitioner , ) : JavaDStream < Tuple2 < K , Tuple2 < V , W > > >

= <EOL> toPairDStream ( ) <EOL> . join ( other . toPairDStream ( ) , partitioner , ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying 'join' between RDDs of `this` DStream and `other` DStream.
 * The supplied org.apache.spark.Partitioner is used to control the partitioning of each RDD.
 */


fun < K , V , W > JavaDStream < Tuple2 < K , V > > . leftOuterJoin ( other : JavaDStream < Tuple2 < K , W > > , numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , ) : JavaDStream < Tuple2 < K , Tuple2 < V , Optional < W > > > >

= <EOL> toPairDStream ( ) <EOL> . leftOuterJoin ( other . toPairDStream ( ) , numPartitions , ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying 'left outer join' between RDDs of `this` DStream and
 * `other` DStream. Hash partitioning is used to generate the RDDs with `numPartitions`
 * partitions.
 */


fun < K , V , W > JavaDStream < Tuple2 < K , V > > . leftOuterJoin ( other : JavaDStream < Tuple2 < K , W > > , partitioner : Partitioner , ) : JavaDStream < Tuple2 < K , Tuple2 < V , Optional < W > > > >

= <EOL> toPairDStream ( ) <EOL> . leftOuterJoin ( other . toPairDStream ( ) , partitioner , ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying 'left outer join' between RDDs of `this` DStream and
 * `other` DStream. The supplied org.apache.spark.Partitioner is used to control
 * the partitioning of each RDD.
 */


fun < K , V , W > JavaDStream < Tuple2 < K , V > > . rightOuterJoin ( other : JavaDStream < Tuple2 < K , W > > , numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , ) : JavaDStream < Tuple2 < K , Tuple2 < Optional < V > , W > > >

= <EOL> toPairDStream ( ) <EOL> . rightOuterJoin ( other . toPairDStream ( ) , numPartitions , ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying 'right outer join' between RDDs of `this` DStream and
 * `other` DStream. Hash partitioning is used to generate the RDDs with `numPartitions`
 * partitions.
 */


fun < K , V , W > JavaDStream < Tuple2 < K , V > > . rightOuterJoin ( other : JavaDStream < Tuple2 < K , W > > , partitioner : Partitioner , ) : JavaDStream < Tuple2 < K , Tuple2 < Optional < V > , W > > >

= <EOL> toPairDStream ( ) <EOL> . rightOuterJoin ( other . toPairDStream ( ) , partitioner , ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying 'right outer join' between RDDs of `this` DStream and
 * `other` DStream. The supplied org.apache.spark.Partitioner is used to control
 * the partitioning of each RDD.
 */


fun < K , V , W > JavaDStream < Tuple2 < K , V > > . fullOuterJoin ( other : JavaDStream < Tuple2 < K , W > > , numPartitions : Int = dstream ( ) . ssc ( ) . sc ( ) . defaultParallelism ( ) , ) : JavaDStream < Tuple2 < K , Tuple2 < Optional < V > , Optional < W > > > >

= <EOL> toPairDStream ( ) <EOL> . fullOuterJoin ( other . toPairDStream ( ) , numPartitions , ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying 'full outer join' between RDDs of `this` DStream and
 * `other` DStream. Hash partitioning is used to generate the RDDs with `numPartitions`
 * partitions.
 */


fun < K , V , W > JavaDStream < Tuple2 < K , V > > . fullOuterJoin ( other : JavaDStream < Tuple2 < K , W > > , partitioner : Partitioner , ) : JavaDStream < Tuple2 < K , Tuple2 < Optional < V > , Optional < W > > > >

= <EOL> toPairDStream ( ) <EOL> . fullOuterJoin ( other . toPairDStream ( ) , partitioner , ) <EOL> . toTupleDStream ( )

/**
 * Return a new DStream by applying 'full outer join' between RDDs of `this` DStream and
 * `other` DStream. The supplied org.apache.spark.Partitioner is used to control
 * the partitioning of each RDD.
 */


fun < K , V > JavaDStream < Tuple2 < K , V > > . saveAsHadoopFiles ( prefix : String , suffix : String , ) : Unit

= toPairDStream ( ) . saveAsHadoopFiles ( prefix , suffix )

/**
 * Save each RDD in `this` DStream as a Hadoop file. The file name at each batch interval is
 * generated based on `prefix` and `suffix`: "prefix-TIME_IN_MS.suffix".
 */


fun < K , V > JavaDStream < Tuple2 < K , V > > . saveAsNewAPIHadoopFiles ( prefix : String , suffix : String , ) : Unit

= toPairDStream ( ) . saveAsNewAPIHadoopFiles ( prefix , suffix )


fun require ( request : String ) : String

{ <EOL> return modules . require ( request ) <EOL> }

/**
 * Require [request] nodejs module and return canonical path to it's main js file.
 */


internal fun resolve ( name : String ) : File ?

= modules . resolve ( name )

/**
 * Find node module according to https://nodejs.org/api/modules.html#modules_all_together,
 * with exception that instead of traversing parent folders, we are traversing parent projects
 */


fun postponeForeignAnnotationResolution ( symbol : FirBasedSymbol < * > )

{ <EOL> val symbolToPostpone = symbol . symbolToPostponeIfCanBeResolvedOnDemand ( ) ? : return <EOL> val currentSymbol = anchorForForeignAnnotations ? : errorWithAttachment ( "<STR_LIT>" ) { <EOL> withFirSymbolEntry ( "<STR_LIT>" , symbolToPostpone ) <EOL> } <EOL> if ( currentSymbol == symbolToPostpone ) return <EOL> postponedSymbols . put ( currentSymbol , symbolToPostpone ) <EOL> }

/**
 * Postpone the resolution request to [symbol] until [annotation arguments][FirResolvePhase.ANNOTATION_ARGUMENTS] phase
 * of the declaration which is used this foreign annotation.
 *
 * @see postponedSymbols
 */


fun postponedSymbols ( target : FirCallableDeclaration ) : Collection < FirBasedSymbol < * > >

{ <EOL> return postponedSymbols [ target . symbol ] <EOL> }

/**
 * @return all symbols postponed with [postponeForeignAnnotationResolution] for the [target] element
 *
 * @see postponeForeignAnnotationResolution
 */


fun pushCycledSymbol ( symbol : FirCallableSymbol < * > )

{ <EOL> requireWithAttachment ( cycledSymbol == null , { "<STR_LIT>" } ) <EOL> cycledSymbol = symbol <EOL> }

/**
 * Push [symbol] with a recursion return type to be able to report it later
 *
 * @param symbol is a symbol with the recursion error in the return type
 *
 * @see popCycledSymbolIfExists
 * @see LLFirImplicitBodyTargetResolver.handleCycleInResolution
 */


fun popCycledSymbolIfExists ( ) : FirCallableSymbol < * > ?

= cycledSymbol ? . also { cycledSymbol = null }

/**
 * Pop [FirCallableSymbol] with a recursion return type if it was [pushed][pushCycledSymbol]
 *
 * @see pushCycledSymbol
 * @see org.jetbrains.kotlin.analysis.low.level.api.fir.element.builder.LLFirReturnTypeCalculatorWithJump.resolveDeclaration
 */


override fun handleCycleInResolution ( target : FirElementWithResolveState )

{ <EOL> requireWithAttachment ( target is FirCallableDeclaration , { "<STR_LIT>" } ) { <EOL> withFirEntry ( "<STR_LIT>" , target ) <EOL> } <EOL> llImplicitBodyResolveComputationSession . pushCycledSymbol ( target . symbol ) <EOL> }

/**
 * @see org.jetbrains.kotlin.analysis.low.level.api.fir.element.builder.LLFirReturnTypeCalculatorWithJump.resolveDeclaration
 */


fun < T , R , T1 : T > Tuple1 < T1 > . map ( func : ( T ) -> R ) : Tuple1 < R >

= Tuple1 < R > ( func ( this . _1 ( ) ) )

/**
 * This file provides map-functions to all Tuple variants.
 * Given a tuple `t(a1, ..., an)`, returns a new tuple `t(func(a1), ..., func(an))`.
 * Compared to Scala 3, no type mapping can occur in Kotlin, so to create a `TupleX<T1, T2, ...>`
 * the user will need to explicitly [cast] the result.
 *
 * For example:
 * ```kotlin
 * val myTuple: Tuple4<Int, String, Int, String> = t(1, "3", 2, "4")
 * val myStringTuple: Tuple4<String, Int, String, Int> = myTuple.map {
 * when (it) {
 * is Int -> it.toString()
 * is String -> it.toInt()
 * else -> error("")
 * }
 * }.cast<String, Int, String, Int>()
 * ```
 */


@ ExperimentalSerializationApi <EOL> public fun SerializersModule . getContextualDescriptor ( descriptor : SerialDescriptor ) : SerialDescriptor ?

= <EOL> descriptor . capturedKClass ? . let { klass -> getContextual ( klass ) ? . descriptor }

/**
 * Looks up a descriptor of serializer registered for contextual serialization in [this],
 * using [SerialDescriptor.capturedKClass] as a key.
 *
 * @see SerializersModuleBuilder.contextual
 */


@ ExperimentalSerializationApi <EOL> public fun SerializersModule . getPolymorphicDescriptors ( descriptor : SerialDescriptor ) : List < SerialDescriptor >

{ <EOL> val kClass = descriptor . capturedKClass ? : return emptyList ( ) <EOL> return ( this as SerialModuleImpl ) . polyBase2Serializers [ kClass ] ? . values . orEmpty ( ) . map { it . descriptor } <EOL> }

/**
 * Retrieves a collection of descriptors which serializers are registered for polymorphic serialization in [this]
 * with base class equal to [descriptor]'s [SerialDescriptor.capturedKClass].
 * This method does not retrieve serializers registered with [PolymorphicModuleBuilder.defaultDeserializer]
 * or [PolymorphicModuleBuilder.defaultSerializer].
 *
 * @see SerializersModule.getPolymorphic
 * @see SerializersModuleBuilder.polymorphic
 */


internal fun SerialDescriptor . withContext ( context : KClass < * > ) : SerialDescriptor

= <EOL> ContextDescriptor ( this , context )

/**
 * Wraps [this] in [ContextDescriptor].
 */


= throw SerializationException ( "<STR_LIT>" )

/**
 * Invoked to decode a value when specialized `decode*` method was not overridden.
 */


fun existsSync ( path : String ) : Boolean

/**
 * See https://nodejs.org/api/fs.html#fsexistssyncpath
 */


fun mkdirSync ( path : String ) : Boolean

/**
 * See https://nodejs.org/api/fs.html#fsmkdirsyncpath-options
 */


fun renameSync ( from : String , to : String )

/**
 * See https://nodejs.org/api/fs.html#fsrenamesyncoldpath-newpath
 */


fun rmdirSync ( path : String )

/**
 * See https://nodejs.org/api/fs.html#fsrmdirsyncpath-options
 */


fun rmSync ( path : String )

/**
 * See https://nodejs.org/api/fs.html#fsrmsyncpath-options
 */


fun statSync ( path : String ) : Stats ?

/**
 * See https://nodejs.org/api/fs.html#fsstatsyncpath-options
 */


fun openSync ( path : String , mode : String ) : Int

/**
 * See https://nodejs.org/api/fs.html#fsopensyncpath-flags-mode
 */


fun closeSync ( fd : Int )

/**
 * See https://nodejs.org/api/fs.html#fsclosesyncfd
 */


fun readFileSync ( fd : Int , options : String ? ) : Buffer

/**
 * See https://nodejs.org/api/fs.html#fsreadfilesyncpath-options
 */


fun writeFileSync ( fd : Int , buffer : Buffer )

/**
 * See https://nodejs.org/api/fs.html#fswritefilesyncfile-data-options
 */


public fun assertHtmlEqualsIgnoringWhitespace ( expected : String , actual : String )

{ <EOL> val ignoreFormattingSettings = Document . OutputSettings ( ) . indentAmount ( <NUM_LIT:0> ) . outline ( true ) <EOL> assertEquals ( Jsoup . parse ( expected ) . outputSettings ( ignoreFormattingSettings ) . outerHtml ( ) . trimSpacesAtTheEndOfLine ( ) , Jsoup . parse ( actual ) . outputSettings ( ignoreFormattingSettings ) . outerHtml ( ) . trimSpacesAtTheEndOfLine ( ) ) <EOL> }

/**
 * Parses it using JSOUP, trims whitespace at the end of the line and asserts if they are equal
 * parsing is required to unify the formatting
 */


final override fun addSubtypeConstraint ( subType : KotlinTypeMarker , superType : KotlinTypeMarker , isFromNullabilityConstraint : Boolean ) : Boolean ?

{ <EOL> val hasNoInfer = subType . isTypeVariableWithNoInfer ( ) || superType . isTypeVariableWithNoInfer ( ) <EOL> if ( hasNoInfer ) return true <EOL> val hasExact = subType . isTypeVariableWithExact ( ) || superType . isTypeVariableWithExact ( ) <EOL> val mySubType = <EOL> if ( hasExact ) extractTypeForProjectedType ( subType , out = true ) <EOL> ? : with ( extensionTypeContext ) { subType . removeExactAnnotation ( ) } else subType <EOL> val mySuperType = <EOL> if ( hasExact ) extractTypeForProjectedType ( superType , out = false ) <EOL> ? : with ( extensionTypeContext ) { superType . removeExactAnnotation ( ) } else superType <EOL> val result = internalAddSubtypeConstraint ( mySubType , mySuperType , isFromNullabilityConstraint ) <EOL> if ( ! hasExact ) return result <EOL> val result2 = internalAddSubtypeConstraint ( mySuperType , mySubType , isFromNullabilityConstraint ) <EOL> if ( result == null && result2 == null ) return null <EOL> return ( result ? : true ) && ( result2 ? : true ) <EOL> }

/**
 * todo: possible we should override this method, because otherwise OR in subtyping transformed to AND in constraint system
 * Now we cannot do this, because sometimes we have proper intersection type as lower type and if we first supertype,
 * then we can get wrong result.
 * override val sameConstructorPolicy get() = SeveralSupertypesWithSameConstructorPolicy.TAKE_FIRST_FOR_SUBTYPING
 */


private fun simplifyLowerConstraint ( typeVariable : KotlinTypeMarker , subType : KotlinTypeMarker , isFromNullabilityConstraint : Boolean = false ) : Boolean

= with ( extensionTypeContext ) { <EOL> val subTypeConstructor = subType . typeConstructor ( ) <EOL> val lowerConstraint = when ( typeVariable ) { <EOL> is SimpleTypeMarker -> <EOL> when { <EOL> isK2 && typeVariable . isDefinitelyNotNullType ( ) && ! subTypeConstructor . isTypeVariable ( ) && <EOL> ! AbstractNullabilityChecker . isSubtypeOfAny ( extensionTypeContext , subType ) -> { <EOL> return false <EOL> } <EOL> typeVariable . isMarkedNullable ( ) -> { <EOL> val typeVariableTypeConstructor = typeVariable . typeConstructor ( ) <EOL> val needToMakeDefNotNull = subTypeConstructor . isTypeVariable ( ) || <EOL> typeVariableTypeConstructor !is TypeVariableTypeConstructorMarker || <EOL> ! typeVariableTypeConstructor . isContainedInInvariantOrContravariantPositions ( ) <EOL> val resultType = if ( needToMakeDefNotNull ) { <EOL> subType . makeDefinitelyNotNullOrNotNull ( ) <EOL> } else { <EOL> if ( ! isInferenceCompatibilityEnabled && subType is CapturedTypeMarker ) { <EOL> subType . withNotNullProjection ( ) <EOL> } else { <EOL> subType . withNullability ( false ) <EOL> } <EOL> } <EOL> if ( isInferenceCompatibilityEnabled && resultType is CapturedTypeMarker ) resultType . withNotNullProjection ( ) else resultType <EOL> } <EOL> else -> subType <EOL> } <EOL> is FlexibleTypeMarker -> { <EOL> assertFlexibleTypeVariable ( typeVariable ) <EOL> when ( subType ) { <EOL> is SimpleTypeMarker -> <EOL> when { <EOL> useRefinedBoundsForTypeVariableInFlexiblePosition ( ) -> <EOL> createFlexibleType ( subType . makeSimpleTypeDefinitelyNotNullOrNotNull ( ) , subType . withNullability ( true ) ) <EOL> subType . isMarkedNullable ( ) -> subType <EOL> else -> createFlexibleType ( subType , subType . withNullability ( true ) ) <EOL> } <EOL> is FlexibleTypeMarker -> <EOL> when { <EOL> useRefinedBoundsForTypeVariableInFlexiblePosition ( ) -> <EOL> createFlexibleType ( subType . lowerBound ( ) . makeSimpleTypeDefinitelyNotNullOrNotNull ( ) , subType . upperBound ( ) . withNullability ( true ) ) <EOL> else -> <EOL> createFlexibleType ( subType . lowerBound ( ) . makeSimpleTypeDefinitelyNotNullOrNotNull ( ) , subType . upperBound ( ) ) <EOL> } <EOL> else -> error ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> else -> error ( "<STR_LIT>" ) <EOL> } <EOL> addLowerConstraint ( typeVariable . typeConstructor ( ) , lowerConstraint , isFromNullabilityConstraint ) <EOL> return true <EOL> }

/**
 * Foo <: T -- leave as is
 *
 * T?
 *
 * Foo <: T? -- Foo & Any <: T
 * Foo? <: T? -- Foo? & Any <: T -- Foo & Any <: T
 * (Foo..Bar) <: T? -- (Foo..Bar) & Any <: T
 *
 * T!
 *
 * Foo <: T! --
 * assert T! == (T..T?)
 * Foo <: T?
 * Foo <: T (optional constraint, needs to preserve nullability)
 * =>
 * Foo & Any <: T
 * Foo <: T
 * =>
 * (Foo & Any .. Foo) <: T -- (Foo!! .. Foo) <: T
 *
 * => Foo <: T! -- (Foo!! .. Foo) <: T
 *
 * Foo? <: T! -- Foo? <: T
 *
 *
 * (Foo..Bar) <: T! --
 * assert T! == (T..T?)
 * (Foo..Bar) <: (T..T?)
 * =>
 * Foo <: T?
 * Bar <: T (optional constraint, needs to preserve nullability)
 * =>
 * (Foo & Any .. Bar) <: T -- (Foo!! .. Bar) <: T
 *
 * => (Foo..Bar) <: T! -- (Foo!! .. Bar) <: T
 *
 * T & Any
 *
 * Foo? <: T & Any => ERROR (for K2 only)
 *
 * Foo..Bar? <: T & Any => Foo..Bar? <: T
 * Foo <: T & Any => Foo <: T
 */


private fun simplifyUpperConstraint ( typeVariable : KotlinTypeMarker , superType : KotlinTypeMarker ) : Boolean

= with ( extensionTypeContext ) { <EOL> val typeVariableLowerBound = typeVariable . lowerBoundIfFlexible ( ) <EOL> val simplifiedSuperType = when { <EOL> typeVariable . isFlexible ( ) && useRefinedBoundsForTypeVariableInFlexiblePosition ( ) -> <EOL> createFlexibleType ( superType . lowerBoundIfFlexible ( ) . makeSimpleTypeDefinitelyNotNullOrNotNull ( ) , superType . upperBoundIfFlexible ( ) . withNullability ( true ) ) <EOL> typeVariableLowerBound . isDefinitelyNotNullType ( ) -> { <EOL> superType . withNullability ( true ) <EOL> } <EOL> typeVariable . isFlexible ( ) && superType is SimpleTypeMarker -> <EOL> createFlexibleType ( superType , superType . withNullability ( true ) ) <EOL> else -> superType <EOL> } <EOL> addUpperConstraint ( typeVariableLowerBound . typeConstructor ( ) , simplifiedSuperType ) <EOL> if ( typeVariableLowerBound . isMarkedNullable ( ) ) { <EOL> return simplifiedSuperType . anyBound ( :: isMyTypeVariable ) || <EOL> isSubtypeOfByTypeChecker ( nullableNothingType ( ) , simplifiedSuperType ) <EOL> } <EOL> return true <EOL> }

/**
 * T! <: Foo <=> T <: Foo & Any..Foo?
 * T? <: Foo <=> T <: Foo && Nothing? <: Foo
 * T <: Foo -- leave as is
 * T & Any <: Foo <=> T <: Foo?
 */


fun replaceVariables ( mapping : Map < String , String > ) : T

/**
 * Replace variables and return the result.
 *
 * @param mapping maps variables names to their values
 * @return instance with substituted variables
 */


private fun getFunctionDefinitionImpl ( call : JsInvocation , scope : InliningScope ) : InlineFunctionDefinition ?

{ <EOL> assert ( scope . fragment in fragmentInfo ) <EOL> return lookUpFunctionDirect ( call , scope ) ? : lookUpFunctionIndirect ( call , scope ) ? : lookUpFunctionExternal ( call , scope . fragment ) <EOL> }

/**
 * Gets function definition by invocation.
 *
 * Notes:
 * 1. Qualifier -- [()/.call()] part of invocation.
 * 2. Local functions are compiled like function literals,
 * but called not directly, but through variable.
 *
 * For example, local `fun f(a, b) = a + b; f(1, 2)` becomes `var f = _.foo.f$; f(1, 2)`
 *
 * Invocation properties:
 * 1. Ends with either [()/.call()].
 *
 * 2. Qualifier can be JsNameRef with static ref to JsFunction
 * in case of function literal without closure.
 *
 * For example, qualifier == _.foo.lambda$
 *
 * 3. Qualifier can be JsInvocation with static ref to JsFunction
 * in case of function literal with closure. In this case
 * qualifier arguments are captured in closure.
 *
 * For example, qualifier == _.foo.lambda(captured_1)
 *
 * 4. Qualifier can be JsNameRef with static ref to case [2]
 * in case of local function without closure.
 *
 * 5. Qualifier can be JsNameRef with ref to case [3]
 * in case of local function with closure.
 */