public fun < DomainType > addPositionalMapping ( aes : Aes , values : List < DomainType > , name : String ? , parameters : PositionalMappingParameters < DomainType > ? <EOL> ) : PositionalMapping < DomainType >

{ <EOL> val columnID = datasetHandler . addColumn ( values , name ? : aes . name ) <EOL> return PositionalMapping ( aes , columnID , parameters ) . also { <EOL> bindingCollector . mappings [ aes ] = it <EOL> } <EOL> }

/**
 * Creates and adds a [positional mapping][PositionalMapping] for a given aesthetic attribute
 * ([aes]) and [values].
 *
 * @param aes the aesthetic attribute (aes) to be mapped.
 * @param values the list of values to be mapped.
 * @param name the name of the mapping (optional, defaults to the name of the aes).
 * @param parameters the positional mapping parameters (optional).
 * @return the created [positional mapping][PositionalMapping].
 */


public fun < DomainType > addPositionalMapping ( aes : Aes , columnID : String , parameters : PositionalMappingParameters < DomainType > ? <EOL> ) : PositionalMapping < DomainType >

{ <EOL> val newColumnID = datasetHandler . takeColumn ( columnID ) <EOL> return PositionalMapping ( aes , newColumnID , parameters ) . also { <EOL> bindingCollector . mappings [ aes ] = it <EOL> } <EOL> }

/**
 * Creates and adds a [positional mapping][PositionalMapping] for a given aesthetic attribute
 * ([aes]), [columnID], and [parameters].
 *
 * @param aes the aesthetic attribute (aes) to be mapped.
 * @param columnID the column ID from dataset to be mapped.
 * @param parameters the positional mapping parameters (optional).
 * @return the created [positional mapping][PositionalMapping].
 */


public fun < DomainType > addPositionalMapping ( aes : Aes , values : DataColumn < DomainType > , parameters : PositionalMappingParameters < DomainType > ? <EOL> ) : PositionalMapping < DomainType >

{ <EOL> val columnID = datasetHandler . addColumn ( values ) <EOL> return PositionalMapping ( aes , columnID , parameters ) . also { <EOL> bindingCollector . mappings [ aes ] = it <EOL> } <EOL> }

/**
 * Creates and adds a [positional mapping][PositionalMapping] for a given aesthetic attribute
 * ([aes]), [values], and [parameters].
 *
 * @param aes the aesthetic attribute (aes) to be mapped.
 * @param values the [DataColumn] of values to be mapped.
 * @param parameters the positional mapping parameters (optional).
 * @return the created [positional mapping][PositionalMapping].
 */


public fun < DomainType , RangeType > addNonPositionalMapping ( aes : Aes , values : List < DomainType > , name : String ? , parameters : NonPositionalMappingParameters < DomainType , RangeType > ? <EOL> ) : NonPositionalMapping < DomainType , RangeType >

{ <EOL> val columnID = datasetHandler . addColumn ( values , name ? : aes . name ) <EOL> return NonPositionalMapping ( aes , columnID , parameters ) . also { <EOL> bindingCollector . mappings [ aes ] = it <EOL> } <EOL> }

/**
 * Creates and adds a [non-positional mapping][NonPositionalMapping] for a given aesthetic attribute
 * ([aes]) and [values].
 *
 * @param aes the aesthetic attribute (aes) to be mapped.
 * @param values the list of values to be mapped.
 * @param name the name of the mapping (optional, defaults to the name of the aes).
 * @param parameters the non-positional mapping parameters (optional).
 * @return the created [non-positional mapping][NonPositionalMapping].
 */


public fun < DomainType , RangeType > addNonPositionalMapping ( aes : Aes , values : DataColumn < DomainType > , parameters : NonPositionalMappingParameters < DomainType , RangeType > ? <EOL> ) : NonPositionalMapping < DomainType , RangeType >

{ <EOL> val columnID = datasetHandler . addColumn ( values ) <EOL> return NonPositionalMapping ( aes , columnID , parameters ) . also { <EOL> bindingCollector . mappings [ aes ] = it <EOL> } <EOL> }

/**
 * Creates and adds a [non-positional mapping][NonPositionalMapping] for a given aesthetic attribute
 * ([aes]), [values], and [parameters].
 *
 * @param aes the aesthetic attribute (aes) to be mapped.
 * @param values the [DataColumn] of values to be mapped.
 * @param parameters the non-positional mapping parameters (optional).
 * @return the created [non-positional mapping][NonPositionalMapping].
 */


public fun < DomainType , RangeType > addNonPositionalMapping ( aes : Aes , columnID : String , parameters : NonPositionalMappingParameters < DomainType , RangeType > ? <EOL> ) : NonPositionalMapping < DomainType , RangeType >

{ <EOL> val newColumnID = datasetHandler . takeColumn ( columnID ) <EOL> return NonPositionalMapping ( aes , newColumnID , parameters ) . also { <EOL> bindingCollector . mappings [ aes ] = it <EOL> } <EOL> }

/**
 * Creates and adds a [non-positional mapping][NonPositionalMapping] for a given aesthetic attribute
 * ([aes]), [columnID], and [parameters].
 *
 * @param aes the aesthetic attribute (aes) to be mapped.
 * @param columnID the column ID from dataset to be mapped.
 * @param parameters the non-positional mapping parameters (optional).
 * @return the created [non-positional mapping][NonPositionalMapping].
 */


public fun < DomainType > addPositionalFreeScale ( aes : Aes , parameters : PositionalMappingParameters < DomainType > )

{ <EOL> bindingCollector . freeScales [ aes ] = PositionalFreeScale ( aes , parameters ) <EOL> }

/**
 * Adds a [non-positional mapping][NonPositionalMapping] for a given positional aesthetic attribute
 * ([aes]) and [parameters] to [binding collector][BindingCollector].
 *
 * @param aes the positional aesthetic attribute (aes) to be mapped.
 * @param parameters the positional mapping parameters (optional).
 */


public fun toPlot ( ) : Plot

/**
 * Creates a [Plot] instance based on the current configurations and bindings
 * present within this context.
 *
 * @return A newly instantiated [Plot] configured by the current context.
 */


public fun toLayer ( layersInheritMappings : Boolean ) : Layer

/**
 * Produces a [Layer] instance based on the current configurations, bindings, and
 * properties found within this context.
 *
 * @param layersInheritMappings a flag determining whether the resulting layer should inherit mappings from a higher-level context.
 * @return a created [Layer] as configured by this context.
 */


@ Test <EOL> fun `test commonizeNativeDistributionTask applied jvm-ecosystem plugin` ( )

{ <EOL> val rootProject = ProjectBuilder . builder ( ) . build ( ) as ProjectInternal <EOL> val subproject = ProjectBuilder . builder ( ) . withParent ( rootProject ) . build ( ) as ProjectInternal <EOL> val jvmEcosystemPluginId = "<STR_LIT>" <EOL> assertNull ( rootProject . plugins . findPlugin ( jvmEcosystemPluginId ) ) <EOL> val kotlin = subproject . applyMultiplatformPlugin ( ) <EOL> assertNull ( rootProject . plugins . findPlugin ( jvmEcosystemPluginId ) ) <EOL> kotlin . linuxArm64 ( ) <EOL> kotlin . linuxX64 ( ) <EOL> rootProject . evaluate ( ) <EOL> subproject . evaluate ( ) <EOL> assertNotNull ( rootProject . plugins . findPlugin ( jvmEcosystemPluginId ) ) <EOL> }

/**
 * Check if jvm-ecosystem plugin is applied when commonizer task is applied to the root project.
 * Context: https://github.com/gradle/gradle/issues/20145
 * https://youtrack.jetbrains.com/issue/KT-51583
 */


public fun < T > size ( column : ColumnReference < T > , parameters : LetsPlotNonPositionalMappingParametersContinuous < T , Double > . ( ) -> Unit = { } ) : NonPositionalMapping < T , Double >

{ <EOL> return addNonPositionalMapping < T , Double > ( SIZE , column . name ( ) , LetsPlotNonPositionalMappingParametersContinuous < T , Double > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `size` aesthetic to a data column by [ColumnReference].
 *
 * @param column the data column to map to the size.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > size ( column : KProperty < T > , parameters : LetsPlotNonPositionalMappingParametersContinuous < T , Double > . ( ) -> Unit = { } ) : NonPositionalMapping < T , Double >

{ <EOL> return addNonPositionalMapping < T , Double > ( SIZE , column . name , LetsPlotNonPositionalMappingParametersContinuous < T , Double > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `size` aesthetic to a data column by [KProperty].
 *
 * @param column the data column to map to the size.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun size ( column : String , parameters : LetsPlotNonPositionalMappingParametersContinuous < Any ? , Double > . ( ) -> Unit = { } ) : NonPositionalMapping < Any ? , Double >

{ <EOL> return addNonPositionalMapping ( SIZE , column , LetsPlotNonPositionalMappingParametersContinuous < Any ? , Double > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `size` aesthetic to a data column by [String].
 *
 * @param column the data column to map to the size.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > size ( values : Iterable < T > , name : String ? = null , parameters : LetsPlotNonPositionalMappingParametersContinuous < T , Double > . ( ) -> Unit = { } ) : NonPositionalMapping < T , Double >

{ <EOL> return addNonPositionalMapping ( SIZE , values . toList ( ) , name , LetsPlotNonPositionalMappingParametersContinuous < T , Double > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `size` aesthetic to iterable of discrete values.
 *
 * @param values the iterable containing the discrete values.
 * @param name optional name for this aesthetic mapping.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


public fun < T > size ( values : DataColumn < T > , parameters : LetsPlotNonPositionalMappingParametersContinuous < T , Double > . ( ) -> Unit = { } ) : NonPositionalMapping < T , Double >

{ <EOL> return addNonPositionalMapping ( SIZE , values , LetsPlotNonPositionalMappingParametersContinuous < T , Double > ( ) . apply ( parameters ) ) <EOL> }

/**
 * Maps the `size` aesthetic to a data column.
 *
 * @param values the data column to map to the size.
 * @param parameters optional lambda to configure additional scale parameters.
 * @return a [NonPositionalMapping] object representing the mapping.
 */


{ <EOL> needPodspec = false <EOL> }

/**
 * Setup plugin not to produce podspec file for cocoapods section
 */


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

{ <EOL> project . kotlinToolingDiagnosticsCollector . report ( project , CocoapodsPluginDiagnostics . UseLibrariesUsed ( ) ) <EOL> }

/**
 * Setup plugin to generate synthetic xcodeproj compatible with static libraries
 */


fun framework ( configure : Framework . ( ) -> Unit )

{ <EOL> forAllPodFrameworks ( configure ) <EOL> }

/**
 * Configure framework of the pod built from this project.
 */


fun framework ( configure : Action < Framework > )


@ JvmOverloads <EOL> fun pod ( name : String , version : String ? = null , path : File ? = null , moduleName : String = name . asModuleName ( ) , headers : String ? = null , linkOnly : Boolean = false , )

{ <EOL> require ( name . isNotEmpty ( ) ) { "<STR_LIT>" } <EOL> addToPods ( project . objects . newInstance ( CocoapodsDependency :: class . java , name , moduleName ) . apply { <EOL> this . headers = headers <EOL> this . version = version <EOL> source = path ? . let ( :: Path ) <EOL> this . linkOnly = linkOnly <EOL> } ) <EOL> }

/**
 * Add a CocoaPods dependency to the pod built from this project.
 *
 * @param linkOnly designates that the pod will be used only for dynamic framework linking and not for the cinterops. Code from it won't
 * be accessible for referencing from Kotlin but its native symbols will be visible while linking the framework.
 */


fun pod ( name : String , configure : CocoapodsDependency . ( ) -> Unit )

{ <EOL> require ( name . isNotEmpty ( ) ) { "<STR_LIT>" } <EOL> val dependency = project . objects . newInstance ( CocoapodsDependency :: class . java , name , name . asModuleName ( ) ) <EOL> dependency . configure ( ) <EOL> addToPods ( dependency ) <EOL> }

/**
 * Add a CocoaPods dependency to the pod built from this project.
 */


fun pod ( name : String , configure : Action < CocoapodsDependency > )

= pod ( name ) { <EOL> configure . execute ( this ) <EOL> }


fun specRepos ( configure : SpecRepos . ( ) -> Unit )

= specRepos . configure ( )

/**
 * Add spec repositories (note that spec repository is different from usual git repository).
 * Please refer to cocoapods documentation
 * for additional information.
 * Default sources (cdn.cocoapods.org) implicitly included.
 */


fun specRepos ( configure : Action < SpecRepos > )

= specRepos { <EOL> configure . execute ( this ) <EOL> }


fun useInteropBindingFrom ( podName : String )

{ <EOL> interopBindingDependencies . add ( podName ) <EOL> }

/**
 * Specify that the pod depends on another pod **podName** and a Kotlin-binding for **podName** should be used while building
 * a binding for the pod. This is necessary if you need to operate entities from **podName** and from the pod together, for
 * instance pass an object from **podName** to the pod in Kotlin.
 *
 * A pod with the exact name must be declared before calling this function.
 *
 * @see interopBindingDependencies
 */


fun path ( podspecDirectory : String ) : PodLocation

= Path ( File ( podspecDirectory ) )


fun path ( podspecDirectory : File ) : PodLocation

= Path ( podspecDirectory )


@ JvmOverloads <EOL> fun git ( url : String , configure : ( Git . ( ) -> Unit ) ? = null ) : PodLocation

{ <EOL> val git = Git ( URI ( url ) ) <EOL> if ( configure != null ) { <EOL> git . configure ( ) <EOL> } <EOL> return git <EOL> }

/**
 * Configure pod from git repository. The podspec file is expected to be in the repository root.
 */


fun git ( url : String , configure : Action < Git > )

= git ( url ) { <EOL> configure . execute ( this ) <EOL> }


{ <EOL> val modelHub = TFModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = TFModels . CV . DenseNet169 ( ) <EOL> val model = modelHub . loadModel ( modelType ) <EOL> val imageNetClassLabels = modelHub . loadClassLabels ( ) <EOL> model . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . MAE , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> val hdfFile = modelHub . loadWeights ( modelType ) <EOL> val weightPaths = listOf ( LayerConvOrDensePaths ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) , LayerBatchNormPaths ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> it . loadWeightsByPaths ( hdfFile , weightPaths , missedWeights = MissedWeightsStrategy . LOAD_CUSTOM_PATH ) <EOL> val fileDataLoader = modelType . createPreprocessing ( model ) . fileLoader ( ) <EOL> for ( i in <NUM_LIT:1> .. <NUM_LIT:8> ) { <EOL> val inputData = fileDataLoader . load ( getFileFromResource ( "<STR_LIT>" ) ) <EOL> val res = it . predictLabel ( inputData ) <EOL> println ( "<STR_LIT>" ) <EOL> val top5 = it . predictTop5Labels ( inputData , imageNetClassLabels ) <EOL> println ( top5 . toString ( ) ) <EOL> } <EOL> } <EOL> }

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


= denseNet169Prediction ( )


actual abstract override fun add ( element : E ) : Boolean

/**
 * Adds the specified element to the set.
 *
 * @return `true` if the element has been added, `false` if the element is already contained in the set.
 */


override fun equals ( other : Any ? ) : Boolean

{ <EOL> if ( other === this ) return true <EOL> if ( other !is Set < * > ) return false <EOL> return AbstractSet . setEquals ( this , other ) <EOL> }

/**
 * Compares this set with another set instance with the unordered structural equality.
 *
 * @return `true`, if [other] instance is a [Set] of the same size, all elements of which are contained in this set.
 */


= AbstractSet . unorderedHashCode ( this )

/**
 * Returns the hash code value for this set.
 */


{ <EOL> val modelHub = TFModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = TFModels . CV . DenseNet201 ( ) <EOL> val model = modelHub . loadModel ( modelType ) <EOL> val imageNetClassLabels = modelHub . loadClassLabels ( ) <EOL> model . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . MAE , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> val hdfFile = modelHub . loadWeights ( modelType ) <EOL> val weightPaths = listOf ( LayerConvOrDensePaths ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) , LayerBatchNormPaths ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> it . loadWeightsByPaths ( hdfFile , weightPaths , missedWeights = MissedWeightsStrategy . LOAD_CUSTOM_PATH ) <EOL> val fileDataLoader = modelType . createPreprocessing ( it ) . fileLoader ( ) <EOL> for ( i in <NUM_LIT:1> .. <NUM_LIT:8> ) { <EOL> val inputData = fileDataLoader . load ( getFileFromResource ( "<STR_LIT>" ) ) <EOL> val res = it . predictLabel ( inputData ) <EOL> println ( "<STR_LIT>" ) <EOL> val top5 = it . predictTop5Labels ( inputData , imageNetClassLabels ) <EOL> println ( top5 . toString ( ) ) <EOL> } <EOL> } <EOL> }

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


= denseNet201Prediction ( )


private fun layerVariables ( ) : List < KVariable >

= layers . variables ( )

/**
 * Returns a list of layer variables in this model.
 */


private fun frozenLayerVariables ( ) : List < KVariable >

= layers . frozenVariables ( )

/**
 * Returns a list of non-trainable, 'frozen' layer variables in this model.
 */


protected abstract fun buildLayers ( training : Operand < Boolean > , numberOfLosses : Operand < Float > ) : Pair < Placeholder < Float > , Operand < Float > >

/** Common method for building model static graph layer by layer via calling build() method on each layer in correct order. */


{ <EOL> check ( isModelCompiled ) { "<STR_LIT>" } <EOL> check ( ! isModelInitialized ) { "<STR_LIT>" } <EOL> check ( ! isOptimizerVariableInitialized ) { "<STR_LIT>" } <EOL> logger . debug { "<STR_LIT>" } <EOL> layers . initializeVariables ( session ) <EOL> isModelInitialized = true <EOL> }

/**
 * Initializes kGraph variables.
 *
 * NOTE: The model becomes initialized after this method call. The flag [isModelInitialized] is set to True.
 */


{ <EOL> check ( isModelCompiled ) { "<STR_LIT>" } <EOL> logger . debug { "<STR_LIT>" } <EOL> layers . initializeVariables ( session ) <EOL> isModelInitialized = true <EOL> isOptimizerVariableInitialized = false <EOL> }

/**
 * It ignores that model is initialized already and call initializers under the hood to re-initialize [kGraph] variables.
 *
 * NOTE: The model becomes initialized after this method call.
 * The flag [isModelInitialized] is set to True and the flag [isOptimizerVariableInitialized] is set to False.
 * As a result, when the method ```fit()``` will be called, optimizer variables are re-initialized.
 */


private fun getLossAndMetricValues ( batch : DataBatch , isTraining : Boolean ) : Pair < Float , List < Float > >

{ <EOL> val yBatchShape = longArrayOf ( batch . size . toLong ( ) , numberOfClasses ) <EOL> val inputs = mapOf ( xOp to batch . toXTensor ( ) , yTrueOp to Tensor . create ( yBatchShape , serializeLabelsToBuffer ( batch . y , numberOfClasses ) ) , numberOfLossesOp to Tensor . create ( TensorShape ( yBatchShape ) . numElements ( ) . toFloat ( ) ) , training to Tensor . create ( isTraining ) ) <EOL> val outputs = listOf ( OutputKey . Name ( TRAINING_LOSS ) ) + metricOps . map ( OutputKey :: Operand ) <EOL> val targetsList = if ( isTraining ) targets else emptyList ( ) <EOL> return runModelInternal ( inputs , outputs , targetsList ) { tensors -> <EOL> check ( tensors . size == metricOps . size + <NUM_LIT:1> ) { <EOL> "<STR_LIT>" <EOL> } <EOL> tensors . first ( ) . floatValue ( ) to tensors . drop ( <NUM_LIT:1> ) . map { it . floatValue ( ) } <EOL> } <EOL> }

/**
 * Returns the loss value and metric value on train batch.
 */


{ <EOL> return kGraph <EOL> }

/**
 * Returns KGraph.
 *
 * NOTE: Be careful, this is direct access to the model graph, not a copy.
 */


protected fun saveVariables ( pathToModelDirectory : String , saveOptimizerState : Boolean )

{ <EOL> val variablesAndTensors = getVariablesAndTensors ( saveOptimizerState ) <EOL> Files . createDirectories ( Paths . get ( pathToModelDirectory ) ) <EOL> val file = File ( "<STR_LIT>" ) <EOL> file . bufferedWriter ( ) . use { variableNamesFile -> <EOL> for ( ( variable , tensorForCopying ) in variablesAndTensors ) { <EOL> val variableName = variable . asOutput ( ) . op ( ) . name ( ) <EOL> variableNamesFile . write ( variableName ) <EOL> variableNamesFile . newLine ( ) <EOL> val variableNameFile = File ( "<STR_LIT>" ) <EOL> variableNameFile . bufferedWriter ( ) . use { file -> <EOL> tensorForCopying . use { <EOL> val reshaped = tensorForCopying . toFloatArray ( ) <EOL> for ( i in <NUM_LIT:0> .. reshaped . size - <NUM_LIT:2> ) { <EOL> file . write ( reshaped [ i ] . toString ( ) + "<STR_LIT:U+0020>" ) <EOL> } <EOL> file . write ( reshaped [ reshaped . size - <NUM_LIT:1> ] . toString ( ) ) <EOL> file . flush ( ) <EOL> } <EOL> } <EOL> variableNamesFile . flush ( ) <EOL> } <EOL> } <EOL> }

/** Saves variables and optimizer state if [saveOptimizerState] is enabled in txt format to the [pathToModelDirectory] directory.*/


private fun getVariablesAndTensors ( saveOptimizerState : Boolean ) : List < Pair < Variable < Float > , Tensor < * > > >

{ <EOL> var variables = layerVariables ( ) . map { it . variable } <EOL> if ( saveOptimizerState ) { <EOL> variables = variables + kGraph . optimizerVariables ( ) <EOL> } <EOL> val modelWeightsExtractorRunner = session . runner ( ) <EOL> variables . forEach ( modelWeightsExtractorRunner :: fetch ) <EOL> return variables . zip ( modelWeightsExtractorRunner . run ( ) ) <EOL> }

/** Returns a list of variables paired with their data. */


private fun isVariableRelatedToFrozenLayer ( variableName : String ) : Boolean

{ <EOL> return frozenLayerVariables ( ) . map { it . name } . any { variableName . contains ( it ) } <EOL> }

/** Check that the variable with the name [variableName] belongs to the frozen layer. */


protected override fun loadVariables ( variableNames : Collection < String > , getData : ( String , Shape ) -> Any )

{ <EOL> val layerVariablesByName = layerVariables ( ) . associateBy { it . name } <EOL> for ( variableName in variableNames ) { <EOL> val variableOperation = kGraph . tfGraph . operation ( variableName ) <EOL> check ( variableOperation != null ) { "<STR_LIT>" } <EOL> val variableShape = variableOperation . output < Float > ( <NUM_LIT:0> ) . shape ( ) <EOL> val data = getData ( variableName , variableShape ) <EOL> val variable = layerVariablesByName [ variableName ] <EOL> if ( variable != null ) { <EOL> fill ( variable , data ) <EOL> } else { <EOL> assignVariable ( variableName , variableShape , data ) <EOL> } <EOL> } <EOL> }

/**
 * Loads variable data for variable names in the provided collection using a provided function.
 * @param [variableNames] Variable names to load.
 * @param [getData] Function that returns variable data by variable name and shape.
 */


public infix fun getLayer ( layerName : String ) : Layer

{ <EOL> return layersByName [ layerName ] ? : error ( "<STR_LIT>" ) <EOL> }

/**
 * Return layer by [layerName].
 *
 * @param [layerName] Should be existing layer name. Throws an error otherwise.
 */


public fun GraphTrainableModel . freeze ( )

{ <EOL> layers . forEach ( Layer :: freeze ) <EOL> }

/**
 * Freezes weights in all layers in this model, so they won't be changed during training.
 * @see [Layer.freeze]
 */


public actual fun ComplexDouble ( re : Double , im : Double ) : ComplexDouble

= JsComplexDouble ( re , im )

/**
 * Creates a [ComplexDouble] with the given real and imaginary values in floating-point format.
 *
 * @param re the real value of the complex number in double format.
 * @param im the imaginary value of the complex number in double format.
 */


public actual fun ComplexDouble ( re : Number , im : Number ) : ComplexDouble

= ComplexDouble ( re . toDouble ( ) , im . toDouble ( ) )

/**
 * Creates a [ComplexDouble] with the given real and imaginary values in number format.
 *
 * @param re the real value of the complex number in number format.
 * @param im the imaginary value of the complex number in number format.
 */


@ Suppress ( "<STR_LIT:UNUSED_PARAMETER>" ) <EOL> fun tryEvaluateSpecialCall ( callSite : IrFunctionAccessExpression , resultSlot : LLVMValueRef ? ) : LLVMValueRef ?

{ <EOL> val function = callSite . symbol . owner <EOL> if ( ! function . isTypedIntrinsic ) { <EOL> return null <EOL> } <EOL> return when ( getIntrinsicType ( callSite ) ) { <EOL> IntrinsicType . IMMUTABLE_BLOB -> { <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> val arg = callSite . getValueArgument ( <NUM_LIT:0> ) as IrConst < String > <EOL> codegen . llvm . staticData . createImmutableBlob ( arg ) <EOL> } <EOL> IntrinsicType . OBJC_GET_SELECTOR -> { <EOL> val selector = ( callSite . getValueArgument ( <NUM_LIT:0> ) as IrConst < * > ) . value as String <EOL> environment . functionGenerationContext . genObjCSelector ( selector ) <EOL> } <EOL> IntrinsicType . INIT_INSTANCE -> { <EOL> val initializer = callSite . getValueArgument ( <NUM_LIT:1> ) as IrConstructorCall <EOL> val thiz = environment . evaluateExpression ( callSite . getValueArgument ( <NUM_LIT:0> ) ! ! , null ) <EOL> environment . evaluateCall ( initializer . symbol . owner , listOf ( thiz ) + environment . evaluateExplicitArgs ( initializer ) , environment . calculateLifetime ( initializer ) , ) <EOL> codegen . theUnitInstanceRef . llvm <EOL> } <EOL> else -> null <EOL> } <EOL> }

/**
 * Some intrinsics have to be processed before evaluation of their arguments.
 * So this method looks at [callSite] and if it is call to "special" intrinsic
 * processes it. Otherwise, it returns null.
 */


internal suspend fun Project . isPluginApplied ( pluginId : String ) : Boolean

{ <EOL> val result = CompletableFuture < Boolean > ( ) <EOL> pluginManager . withPlugin ( pluginId ) { <EOL> check ( ! result . isCompleted ) { <EOL> "<STR_LIT>" <EOL> } <EOL> result . complete ( true ) <EOL> } <EOL> launchInStage ( AfterEvaluateBuildscript ) { <EOL> if ( ! result . isCompleted ) result . complete ( false ) <EOL> } <EOL> return result . await ( ) <EOL> }

/**
 * Returns true as soon as Gradle plugin with [pluginId] is applied.
 * Returns false if plugin wasn't applied during
 */


fun JDialog . takeScreenshot ( ) : BufferedImage ?

{ <EOL> return rootPane . takeScreenshot ( ) <EOL> }

/**
 * Takes a screenshot of a [JDialog].
 */


fun JFrame . takeScreenshot ( ) : BufferedImage ?

/**
 * Takes a screenshot of a [JFrame].
 */


fun JComponent . takeScreenshot ( ) : BufferedImage ?

{ <EOL> try { <EOL> val config : GraphicsConfiguration ? = graphicsConfiguration <EOL> val scaleFactor : Double = config ? . defaultTransform ? . scaleX ? : <NUM_LIT:1.0> <EOL> if ( ! isVisible || width == <NUM_LIT:0> || height == <NUM_LIT:0> ) return null <EOL> val image = BufferedImage ( ( width * scaleFactor ) . toInt ( ) , ( height * scaleFactor ) . toInt ( ) , BufferedImage . TYPE_INT_ARGB ) <EOL> with ( image . createGraphics ( ) ) { <EOL> setRenderingHint ( RenderingHints . KEY_INTERPOLATION , RenderingHints . VALUE_INTERPOLATION_BILINEAR ) <EOL> setRenderingHint ( RenderingHints . KEY_RENDERING , RenderingHints . VALUE_RENDER_QUALITY ) <EOL> setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) <EOL> scale ( scaleFactor , scaleFactor ) <EOL> paint ( this ) <EOL> dispose ( ) <EOL> } <EOL> return image <EOL> } catch ( ignore : Throwable ) { <EOL> return null <EOL> } <EOL> }

/**
 * Takes a screenshot of the Swing component. This is only possible if the
 * component has been given a size, see [JComponent.getSize]. Either manually
 * or through a [java.awt.LayoutManager].
 *
 * If the size of the component cannot be determined, `null` is returned.
 */


public fun openSubscription ( ) : ReceiveChannel < E >

/**
 * Subscribes to this [BroadcastChannel] and returns a channel to receive elements from it.
 * The resulting channel shall be [cancelled][ReceiveChannel.cancel] to unsubscribe from this
 * broadcast channel.
 */


public fun cancel ( cause : CancellationException ? = null )

/**
 * Cancels reception of remaining elements from this channel with an optional cause.
 * This function closes the channel with
 * the specified cause (unless it was already closed), removes all buffered sent elements from it,
 * and [cancels][ReceiveChannel.cancel] all open subscriptions.
 * A cause can be used to specify an error message or to provide other details on
 * a cancellation reason for debugging purposes.
 */


@ Deprecated ( level = DeprecationLevel . HIDDEN , message = "<STR_LIT>" ) <EOL> public fun cancel ( cause : Throwable ? = null ) : Boolean

/**
 * @suppress This method has bad semantics when cause is not a [CancellationException]. Use [cancel].
 */


@ ObsoleteCoroutinesApi <EOL> @ Deprecated ( level = DeprecationLevel . WARNING , message = "<STR_LIT>" ) <EOL> public fun < E > BroadcastChannel ( capacity : Int ) : BroadcastChannel < E >

= <EOL> when ( capacity ) { <EOL> <NUM_LIT:0> -> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> UNLIMITED -> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> CONFLATED -> ConflatedBroadcastChannel ( ) <EOL> BUFFERED -> BroadcastChannelImpl ( CHANNEL_DEFAULT_CAPACITY ) <EOL> else -> BroadcastChannelImpl ( capacity ) <EOL> }

/**
 * Creates a broadcast channel with the specified buffer capacity.
 *
 * The resulting channel type depends on the specified [capacity] parameter:
 *
 * - when `capacity` positive, but less than [UNLIMITED] -- creates `ArrayBroadcastChannel` with a buffer of given capacity.
 * **Note:** this channel looses all items that have been sent to it until the first subscriber appears;
 * - when `capacity` is [CONFLATED] -- creates [ConflatedBroadcastChannel] that conflates back-to-back sends;
 * - when `capacity` is [BUFFERED] -- creates `ArrayBroadcastChannel` with a default capacity.
 * - otherwise -- throws [IllegalArgumentException].
 *
 * **Note: This API is obsolete since 1.5.0 and deprecated for removal since 1.7.0**
 * It is replaced with [SharedFlow][kotlinx.coroutines.flow.SharedFlow] and [StateFlow][kotlinx.coroutines.flow.StateFlow].
 */


override suspend fun send ( element : E )

{ <EOL> val subs = lock . withLock { <EOL> if ( isClosedForSend ) throw sendException <EOL> if ( capacity == CONFLATED ) lastConflatedElement = element <EOL> subscribers <EOL> } <EOL> subs . forEach { <EOL> val success = it . sendBroadcast ( element ) <EOL> if ( ! success && isClosedForSend ) throw sendException <EOL> } <EOL> }

/**
 * Sends the specified element to all subscribers.
 *
 * **!!! THIS IMPLEMENTATION IS NOT LINEARIZABLE !!!**
 *
 * As the operation should send the element to multiple
 * subscribers simultaneously, it is non-trivial to
 * implement it in an atomic way. Specifically, this
 * would require a special implementation that does
 * not transfer the element until all parties are able
 * to resume it (this `send(..)` can be cancelled
 * or the broadcast can become closed in the meantime).
 * As broadcasts are obsolete, we keep this implementation
 * as simple as possible, allowing non-linearizability
 * in corner cases.
 */


{ <EOL> val preprocessing = pipeline < BufferedImage > ( ) <EOL> . convert { colorMode = ColorMode . BGR } <EOL> . toFloatArray { } <EOL> . rescale { <EOL> scalingCoefficient = <NUM_LIT> <EOL> } <EOL> val ( cifarImagesArchive , cifarLabelsArchive ) = cifar10Paths ( ) <EOL> val y = extractCifar10LabelsAnsSort ( cifarLabelsArchive ) <EOL> val dataset = OnHeapDataset . create ( File ( cifarImagesArchive ) , y , preprocessing ) <EOL> val ( train , test ) = dataset . split ( TRAIN_TEST_SPLIT_RATIO ) <EOL> vgg11 . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> val start = System . currentTimeMillis ( ) <EOL> it . fit ( dataset = train , epochs = EPOCHS , batchSize = TRAINING_BATCH_SIZE ) <EOL> println ( "<STR_LIT>" ) <EOL> it . save ( File ( PATH_TO_MODEL ) , writingMode = WritingMode . OVERRIDE ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

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


override fun lower ( irClass : IrClass )

{ <EOL> if ( ! context . config . languageVersionSettings . supportsFeature ( LanguageFeature . ExtendedMainConvention ) ) return <EOL> if ( ! irClass . isFileClass ) return <EOL> irClass . functions . find { it . isMainMethod ( ) } ? . let { mainMethod -> <EOL> if ( mainMethod . isSuspend ) { <EOL> irClass . generateMainMethod { newMain , args -> <EOL> + irRunSuspend ( mainMethod , args , newMain ) <EOL> } <EOL> } <EOL> return <EOL> } <EOL> irClass . functions . find { it . isParameterlessMainMethod ( ) } ? . let { parameterlessMainMethod -> <EOL> irClass . generateMainMethod { newMain , _ -> <EOL> if ( parameterlessMainMethod . isSuspend ) { <EOL> + irRunSuspend ( parameterlessMainMethod , null , newMain ) <EOL> } else { <EOL> + irCall ( parameterlessMainMethod ) <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * This pass finds extended main methods and introduces a regular
 * `public static void main(String[] args)` entry point, as appropriate:
 * - invocation via [kotlin.coroutines.jvm.internal.runSuspend] suspend main methods.
 * - a simple delegating wrapper for parameterless main methods
 *
 * There are three cases that must be handled, in order of precedence:
 *
 * 1. `suspend fun main(args: Array<String>) { .. }` for which we generate
 * ```
 * fun main(args: Array<String>) {
 * runSuspend { main(args) }
 * }
 * ```
 *
 * 2. `suspend fun main() { .. }` for which we generate
 * ```
 * fun main(args: Array<String>) {
 * runSuspend { main() }
 * }
 * ```
 *
 * 3. `fun main() { .. }` for which we generate
 * ```
 * fun main(args: Array<String>) {
 * main()
 * }
 * ```
 */


fun runTest ( @ TestDataFile testDataFilePath : String )

{ <EOL> val absoluteTestFile = getAbsoluteFile ( testDataFilePath ) <EOL> val testCaseId = TestCaseId . TestDataFile ( absoluteTestFile ) <EOL> try { <EOL> runTestCase ( testCaseId ) <EOL> } catch ( e : CompilationToolException ) { <EOL> if ( testRunSettings . isIgnoredTarget ( absoluteTestFile ) ) <EOL> println ( "<STR_LIT>" ) <EOL> else <EOL> fail { e . reason } <EOL> } <EOL> }

/**
 * Run JUnit test.
 *
 * This function should be called from a method annotated with [org.junit.jupiter.api.Test].
 */


internal fun runTestCase ( testCaseId : TestCaseId )

{ <EOL> val testRun = testRunProvider . getSingleTestRun ( testCaseId , testRunSettings ) <EOL> performTestRun ( testRun ) <EOL> }


fun dynamicTest ( @ TestDataFile testDataFilePath : String ) : Collection < DynamicNode >

{ <EOL> val testCaseId = TestCaseId . TestDataFile ( getAbsoluteFile ( testDataFilePath ) ) <EOL> return dynamicTestCase ( testCaseId ) <EOL> }

/**
 * Run JUnit dynamic test.
 *
 * This function should be called from a method annotated with [org.junit.jupiter.api.TestFactory].
 */


internal fun dynamicTestCase ( testCaseId : TestCaseId ) : Collection < DynamicNode >

{ <EOL> val testRunNodes = testRunProvider . getTestRuns ( testCaseId , testRunSettings ) <EOL> return buildJUnitDynamicNodes ( testRunNodes ) <EOL> }


{ <EOL> return "<STR_LIT>" <EOL> }

/**
 * Returns the String representation of this KmVersionRequirement object, consisting of
 * [kind], [level], [version], [errorCode], and [message].
 */


= "<STR_LIT>"


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public expect fun Int . countOneBits ( ) : Int

/**
 * Counts the number of set bits in the binary representation of this [Int] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public expect fun Int . countLeadingZeroBits ( ) : Int

/**
 * Counts the number of consecutive most significant bits that are zero in the binary representation of this [Int] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public expect fun Int . countTrailingZeroBits ( ) : Int

/**
 * Counts the number of consecutive least significant bits that are zero in the binary representation of this [Int] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public expect fun Int . takeHighestOneBit ( ) : Int

/**
 * Returns a number having a single bit set in the position of the most significant set bit of this [Int] number,
 * or zero, if this number is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public expect fun Int . takeLowestOneBit ( ) : Int

/**
 * Returns a number having a single bit set in the position of the least significant set bit of this [Int] number,
 * or zero, if this number is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.6>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> public expect fun Int . rotateLeft ( bitCount : Int ) : Int

/**
 * Rotates the binary representation of this [Int] number left by the specified [bitCount] number of bits.
 * The most significant bits pushed out from the left side reenter the number as the least significant bits on the right side.
 *
 * Rotating the number left by a negative bit count is the same as rotating it right by the negated bit count:
 * `number.rotateLeft(-n) == number.rotateRight(n)`
 *
 * Rotating by a multiple of [Int.SIZE_BITS] (32) returns the same number, or more generally
 * `number.rotateLeft(n) == number.rotateLeft(n % 32)`
 */


@ SinceKotlin ( "<STR_LIT:1.6>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> public expect fun Int . rotateRight ( bitCount : Int ) : Int

/**
 * Rotates the binary representation of this [Int] number right by the specified [bitCount] number of bits.
 * The least significant bits pushed out from the right side reenter the number as the most significant bits on the left side.
 *
 * Rotating the number right by a negative bit count is the same as rotating it left by the negated bit count:
 * `number.rotateRight(-n) == number.rotateLeft(n)`
 *
 * Rotating by a multiple of [Int.SIZE_BITS] (32) returns the same number, or more generally
 * `number.rotateRight(n) == number.rotateRight(n % 32)`
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public expect fun Long . countOneBits ( ) : Int

/**
 * Counts the number of set bits in the binary representation of this [Long] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public expect fun Long . countLeadingZeroBits ( ) : Int

/**
 * Counts the number of consecutive most significant bits that are zero in the binary representation of this [Long] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public expect fun Long . countTrailingZeroBits ( ) : Int

/**
 * Counts the number of consecutive least significant bits that are zero in the binary representation of this [Long] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public expect fun Long . takeHighestOneBit ( ) : Long

/**
 * Returns a number having a single bit set in the position of the most significant set bit of this [Long] number,
 * or zero, if this number is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> public expect fun Long . takeLowestOneBit ( ) : Long

/**
 * Returns a number having a single bit set in the position of the least significant set bit of this [Long] number,
 * or zero, if this number is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.6>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> public expect fun Long . rotateLeft ( bitCount : Int ) : Long

/**
 * Rotates the binary representation of this [Long] number left by the specified [bitCount] number of bits.
 * The most significant bits pushed out from the left side reenter the number as the least significant bits on the right side.
 *
 * Rotating the number left by a negative bit count is the same as rotating it right by the negated bit count:
 * `number.rotateLeft(-n) == number.rotateRight(n)`
 *
 * Rotating by a multiple of [Long.SIZE_BITS] (64) returns the same number, or more generally
 * `number.rotateLeft(n) == number.rotateLeft(n % 64)`
 */


@ SinceKotlin ( "<STR_LIT:1.6>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> public expect fun Long . rotateRight ( bitCount : Int ) : Long

/**
 * Rotates the binary representation of this [Long] number right by the specified [bitCount] number of bits.
 * The least significant bits pushed out from the right side reenter the number as the most significant bits on the left side.
 *
 * Rotating the number right by a negative bit count is the same as rotating it left by the negated bit count:
 * `number.rotateRight(-n) == number.rotateLeft(n)`
 *
 * Rotating by a multiple of [Long.SIZE_BITS] (64) returns the same number, or more generally
 * `number.rotateRight(n) == number.rotateRight(n % 64)`
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun Byte . countOneBits ( ) : Int

= ( toInt ( ) and <NUM_LIT> ) . countOneBits ( )

/**
 * Counts the number of set bits in the binary representation of this [Byte] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun Byte . countLeadingZeroBits ( ) : Int

= ( toInt ( ) and <NUM_LIT> ) . countLeadingZeroBits ( ) - ( Int . SIZE_BITS - Byte . SIZE_BITS )

/**
 * Counts the number of consecutive most significant bits that are zero in the binary representation of this [Byte] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun Byte . countTrailingZeroBits ( ) : Int

= ( toInt ( ) or <NUM_LIT> ) . countTrailingZeroBits ( )

/**
 * Counts the number of consecutive least significant bits that are zero in the binary representation of this [Byte] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun Byte . takeHighestOneBit ( ) : Byte

= ( toInt ( ) and <NUM_LIT> ) . takeHighestOneBit ( ) . toByte ( )

/**
 * Returns a number having a single bit set in the position of the most significant set bit of this [Byte] number,
 * or zero, if this number is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun Byte . takeLowestOneBit ( ) : Byte

= toInt ( ) . takeLowestOneBit ( ) . toByte ( )

/**
 * Returns a number having a single bit set in the position of the least significant set bit of this [Byte] number,
 * or zero, if this number is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.6>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> public fun Byte . rotateLeft ( bitCount : Int ) : Byte

= <EOL> ( toInt ( ) . shl ( bitCount and <NUM_LIT:7> ) or ( toInt ( ) and <NUM_LIT> ) . ushr ( <NUM_LIT:8> - ( bitCount and <NUM_LIT:7> ) ) ) . toByte ( )

/**
 * Rotates the binary representation of this [Byte] number left by the specified [bitCount] number of bits.
 * The most significant bits pushed out from the left side reenter the number as the least significant bits on the right side.
 *
 * Rotating the number left by a negative bit count is the same as rotating it right by the negated bit count:
 * `number.rotateLeft(-n) == number.rotateRight(n)`
 *
 * Rotating by a multiple of [Byte.SIZE_BITS] (8) returns the same number, or more generally
 * `number.rotateLeft(n) == number.rotateLeft(n % 8)`
 */


@ SinceKotlin ( "<STR_LIT:1.6>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> public fun Byte . rotateRight ( bitCount : Int ) : Byte

= <EOL> ( toInt ( ) . shl ( <NUM_LIT:8> - ( bitCount and <NUM_LIT:7> ) ) or ( toInt ( ) and <NUM_LIT> ) . ushr ( bitCount and <NUM_LIT:7> ) ) . toByte ( )

/**
 * Rotates the binary representation of this [Byte] number right by the specified [bitCount] number of bits.
 * The least significant bits pushed out from the right side reenter the number as the most significant bits on the left side.
 *
 * Rotating the number right by a negative bit count is the same as rotating it left by the negated bit count:
 * `number.rotateRight(-n) == number.rotateLeft(n)`
 *
 * Rotating by a multiple of [Byte.SIZE_BITS] (8) returns the same number, or more generally
 * `number.rotateRight(n) == number.rotateRight(n % 8)`
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun Short . countOneBits ( ) : Int

/**
 * Counts the number of set bits in the binary representation of this [Short] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun Short . countLeadingZeroBits ( ) : Int

= <EOL> ( toInt ( ) and <NUM_LIT> ) . countLeadingZeroBits ( ) - ( Int . SIZE_BITS - Short . SIZE_BITS )

/**
 * Counts the number of consecutive most significant bits that are zero in the binary representation of this [Short] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun Short . countTrailingZeroBits ( ) : Int

/**
 * Counts the number of consecutive least significant bits that are zero in the binary representation of this [Short] number.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun Short . takeHighestOneBit ( ) : Short

= ( toInt ( ) and <NUM_LIT> ) . takeHighestOneBit ( ) . toShort ( )

/**
 * Returns a number having a single bit set in the position of the most significant set bit of this [Short] number,
 * or zero, if this number is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.4>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun Short . takeLowestOneBit ( ) : Short

= toInt ( ) . takeLowestOneBit ( ) . toShort ( )

/**
 * Returns a number having a single bit set in the position of the least significant set bit of this [Short] number,
 * or zero, if this number is zero.
 */


@ SinceKotlin ( "<STR_LIT:1.6>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> public fun Short . rotateLeft ( bitCount : Int ) : Short

= <EOL> ( toInt ( ) . shl ( bitCount and <NUM_LIT> ) or ( toInt ( ) and <NUM_LIT> ) . ushr ( <NUM_LIT:16> - ( bitCount and <NUM_LIT> ) ) ) . toShort ( )

/**
 * Rotates the binary representation of this [Short] number left by the specified [bitCount] number of bits.
 * The most significant bits pushed out from the left side reenter the number as the least significant bits on the right side.
 *
 * Rotating the number left by a negative bit count is the same as rotating it right by the negated bit count:
 * `number.rotateLeft(-n) == number.rotateRight(n)`
 *
 * Rotating by a multiple of [Short.SIZE_BITS] (16) returns the same number, or more generally
 * `number.rotateLeft(n) == number.rotateLeft(n % 16)`
 */


@ SinceKotlin ( "<STR_LIT:1.6>" ) <EOL> @ WasExperimental ( ExperimentalStdlibApi :: class ) <EOL> public fun Short . rotateRight ( bitCount : Int ) : Short

= <EOL> ( toInt ( ) . shl ( <NUM_LIT:16> - ( bitCount and <NUM_LIT> ) ) or ( toInt ( ) and <NUM_LIT> ) . ushr ( bitCount and <NUM_LIT> ) ) . toShort ( )

/**
 * Rotates the binary representation of this [Short] number right by the specified [bitCount] number of bits.
 * The least significant bits pushed out from the right side reenter the number as the most significant bits on the left side.
 *
 * Rotating the number right by a negative bit count is the same as rotating it left by the negated bit count:
 * `number.rotateRight(-n) == number.rotateLeft(n)`
 *
 * Rotating by a multiple of [Short.SIZE_BITS] (16) returns the same number, or more generally
 * `number.rotateRight(n) == number.rotateRight(n % 16)`
 */


protected open fun shouldSkipTest ( filePath : String , configuration : TestConfiguration ) : Boolean

= false

/**
 * Consider [org.jetbrains.kotlin.test.model.AfterAnalysisChecker.suppressIfNeeded] firstly
 */


protected fun assertLayerOutputIsCorrect ( layer : Layer , input : Array < * > , expectedOutput : Array < * > , runMode : RunMode = RunMode . EAGER , )

{ <EOL> val output = when ( runMode ) { <EOL> RunMode . EAGER -> runLayerInEagerMode ( layer , input ) <EOL> RunMode . GRAPH -> runLayerInGraphMode ( layer , input ) <EOL> } <EOL> output . use { <EOL> val outputShape = output . shape ( ) <EOL> val expectedShape = expectedOutput . shape . toLongArray ( ) <EOL> assertArrayEquals ( expectedShape , outputShape ) <EOL> val result = it . toFloatArray ( ) <EOL> val expected = expectedOutput . flattenFloats ( ) <EOL> assertArrayEquals ( expected , result ) <EOL> } <EOL> }

/**
 * Checks the output of a layer given the input data is equal to the expected output.
 *
 * This takes care of building and running the layer instance ([layer]), in either of
 * Eager or Graph mode execution ([runMode]) to verify the output of layer for the given
 * input data ([input]), is equal to the expected output ([expectedOutput]).
 *
 * Note that this method could be used for a layer with any input/output dimensionality.
 */


protected fun assertLayerComputedOutputShape ( layer : Layer , expectedOutputShape : LongArray )

{ <EOL> assertArrayEquals ( expectedOutputShape , layer . outputShape . dims ( ) , "<STR_LIT>" , ) <EOL> }

/**
 * Checks the computed output shape of layer is equal to the expected output shape.
 */


public fun isApplicableForDefinedLanguage ( language : String ) : Boolean

/**
 * Whether this renderer supports rendering Markdown code blocks
 * for the given [language] explicitly specified in the fenced code block definition,
 */


public fun isApplicableForUndefinedLanguage ( code : String ) : Boolean

/**
 * Whether this renderer supports rendering Markdown code blocks
 * for the given [code] when language is not specified in fenced code blocks
 * or indented code blocks are used.
 */


public fun FlowContent . buildCodeBlock ( language : String ? , code : String )

/**
 * Defines how to render [code] for specified [language] via HTML tags.
 *
 * The value of the [language] will be the same as in the input Markdown fenced code block definition.
 * In the following example [language] = `kotlin` and [code] = `val a`:
 * ~~~markdown
 * ```kotlin
 * val a
 * ```
 * ~~~
 * The value of the [language] will be `null` if language is not specified in the fenced code block definition
 * or indented code blocks are used.
 * In the following example [language] = `null` and [code] = `val a`:
 * ~~~markdown
 * ```
 * val a
 * ```
 * ~~~
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun File . reader ( charset : Charset = Charsets . UTF_8 ) : InputStreamReader

= <EOL> inputStream ( ) . reader ( charset )

/**
 * Returns a new [FileReader] for reading the content of this file.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun File . bufferedReader ( charset : Charset = Charsets . UTF_8 , bufferSize : Int = DEFAULT_BUFFER_SIZE ) : BufferedReader

= <EOL> reader ( charset ) . buffered ( bufferSize )

/**
 * Returns a new [BufferedReader] for reading the content of this file.
 *
 * @param bufferSize necessary size of the buffer.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun File . writer ( charset : Charset = Charsets . UTF_8 ) : OutputStreamWriter

= <EOL> outputStream ( ) . writer ( charset )

/**
 * Returns a new [FileWriter] for writing the content of this file.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun File . bufferedWriter ( charset : Charset = Charsets . UTF_8 , bufferSize : Int = DEFAULT_BUFFER_SIZE ) : BufferedWriter

= <EOL> writer ( charset ) . buffered ( bufferSize )

/**
 * Returns a new [BufferedWriter] for writing the content of this file.
 *
 * @param bufferSize necessary size of the buffer.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun File . printWriter ( charset : Charset = Charsets . UTF_8 ) : PrintWriter

= <EOL> PrintWriter ( bufferedWriter ( charset ) )

/**
 * Returns a new [PrintWriter] for writing the content of this file.
 */


public fun File . readBytes ( ) : ByteArray

= inputStream ( ) . use { input -> <EOL> var offset = <NUM_LIT:0> <EOL> var remaining = this . length ( ) . also { length -> <EOL> if ( length > Int . MAX_VALUE ) throw OutOfMemoryError ( "<STR_LIT>" ) <EOL> } . toInt ( ) <EOL> val result = ByteArray ( remaining ) <EOL> while ( remaining > <NUM_LIT:0> ) { <EOL> val read = input . read ( result , offset , remaining ) <EOL> if ( read < <NUM_LIT:0> ) break <EOL> remaining -= read <EOL> offset += read <EOL> } <EOL> if ( remaining > <NUM_LIT:0> ) return@use result . copyOf ( offset ) <EOL> val extraByte = input . read ( ) <EOL> if ( extraByte == - <NUM_LIT:1> ) return@use result <EOL> val extra = ExposingBufferByteArrayOutputStream ( DEFAULT_BUFFER_SIZE + <NUM_LIT:1> ) <EOL> extra . write ( extraByte ) <EOL> input . copyTo ( extra ) <EOL> val resultingSize = result . size + extra . size ( ) <EOL> if ( resultingSize < <NUM_LIT:0> ) throw OutOfMemoryError ( "<STR_LIT>" ) <EOL> return@use extra . buffer . copyInto ( destination = result . copyOf ( resultingSize ) , destinationOffset = result . size , startIndex = <NUM_LIT:0> , endIndex = extra . size ( ) ) <EOL> }

/**
 * Gets the entire content of this file as a byte array.
 *
 * This method is not recommended on huge files. It has an internal limitation of 2 GB byte array size.
 *
 * @return the entire content of this file as a byte array.
 */


public fun File . writeBytes ( array : ByteArray ) : Unit

= FileOutputStream ( this ) . use { it . write ( array ) }

/**
 * Sets the content of this file as an [array] of bytes.
 * If this file already exists, it becomes overwritten.
 *
 * @param array byte array to write into this file.
 */


public fun File . appendBytes ( array : ByteArray ) : Unit

= FileOutputStream ( this , true ) . use { it . write ( array ) }

/**
 * Appends an [array] of bytes to the content of this file.
 *
 * @param array byte array to append to this file.
 */


public fun File . readText ( charset : Charset = Charsets . UTF_8 ) : String

= reader ( charset ) . use { it . readText ( ) }

/**
 * Gets the entire content of this file as a String using UTF-8 or specified [charset].
 *
 * This method is not recommended on huge files. It has an internal limitation of 2 GB file size.
 *
 * @param charset character set to use.
 * @return the entire content of this file as a String.
 */


public fun File . writeText ( text : String , charset : Charset = Charsets . UTF_8 ) : Unit

= <EOL> FileOutputStream ( this ) . use { it . writeTextImpl ( text , charset ) }

/**
 * Sets the content of this file as [text] encoded using UTF-8 or specified [charset].
 * If this file exists, it becomes overwritten.
 *
 * @param text text to write into file.
 * @param charset character set to use.
 */


public fun File . appendText ( text : String , charset : Charset = Charsets . UTF_8 ) : Unit

= <EOL> FileOutputStream ( this , true ) . use { it . writeTextImpl ( text , charset ) }

/**
 * Appends [text] to the content of this file using UTF-8 or the specified [charset].
 *
 * @param text text to append to file.
 * @param charset character set to use.
 */


public fun File . forEachBlock ( action : ( buffer : ByteArray , bytesRead : Int ) -> Unit ) : Unit

= forEachBlock ( DEFAULT_BLOCK_SIZE , action )

/**
 * Reads file by byte blocks and calls [action] for each block read.
 * Block has default size which is implementation-dependent.
 * This functions passes the byte array and amount of bytes in the array to the [action] function.
 *
 * You can use this function for huge files.
 *
 * @param action function to process file blocks.
 */


public fun File . forEachBlock ( blockSize : Int , action : ( buffer : ByteArray , bytesRead : Int ) -> Unit ) : Unit

{ <EOL> val arr = ByteArray ( blockSize . coerceAtLeast ( MINIMUM_BLOCK_SIZE ) ) <EOL> inputStream ( ) . use { input -> <EOL> do { <EOL> val size = input . read ( arr ) <EOL> if ( size <= <NUM_LIT:0> ) { <EOL> break <EOL> } else { <EOL> action ( arr , size ) <EOL> } <EOL> } while ( true ) <EOL> } <EOL> }

/**
 * Reads file by byte blocks and calls [action] for each block read.
 * This functions passes the byte array and amount of bytes in the array to the [action] function.
 *
 * You can use this function for huge files.
 *
 * @param action function to process file blocks.
 * @param blockSize size of a block, replaced by 512 if it's less, 4096 by default.
 */


public fun File . forEachLine ( charset : Charset = Charsets . UTF_8 , action : ( line : String ) -> Unit ) : Unit

{ <EOL> BufferedReader ( InputStreamReader ( FileInputStream ( this ) , charset ) ) . forEachLine ( action ) <EOL> }

/**
 * Reads this file line by line using the specified [charset] and calls [action] for each line.
 * Default charset is UTF-8.
 *
 * You may use this function on huge files.
 *
 * @param charset character set to use.
 * @param action function to process file lines.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun File . inputStream ( ) : FileInputStream

{ <EOL> return FileInputStream ( this ) <EOL> }

/**
 * Constructs a new FileInputStream of this file and returns it as a result.
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun File . outputStream ( ) : FileOutputStream

{ <EOL> return FileOutputStream ( this ) <EOL> }

/**
 * Constructs a new FileOutputStream of this file and returns it as a result.
 */


public fun File . readLines ( charset : Charset = Charsets . UTF_8 ) : List < String >

{ <EOL> val result = ArrayList < String > ( ) <EOL> forEachLine ( charset ) { result . add ( it ) ; } <EOL> return result <EOL> }

/**
 * Reads the file content as a list of lines.
 *
 * Do not use this function for huge files.
 *
 * @param charset character set to use. By default uses UTF-8 charset.
 * @return list of file lines.
 */


public inline fun < T > File . useLines ( charset : Charset = Charsets . UTF_8 , block : ( Sequence < String > ) -> T ) : T

{ <EOL> contract { <EOL> callsInPlace ( block , InvocationKind . EXACTLY_ONCE ) <EOL> } <EOL> return bufferedReader ( charset ) . use { block ( it . lineSequence ( ) ) } <EOL> }

/**
 * Calls the [block] callback giving it a sequence of all the lines in this file and closes the reader once
 * the processing is complete.

 * @param charset character set to use. By default uses UTF-8 charset.
 * @return the value returned by [block].
 */


fun D . signatureString ( compatibleMode : Boolean ) : String

/**
 * Returns the mangled name for the declaration [D] to be used for computing that declaration's [IdSignature].
 *
 * Unlike the one computed by [mangleString], this mangled name does not include mangled names of the declaration's parents.
 *
 * For example, for `foo`'s getter in the following code:
 * ```kotlin
 * class Test {
 * val foo: Int
 * }
 * ```
 * the result of this function will be `"<get-foo>(){}kotlin.Int"` or `"<get-foo>(){}"` (depending on the target platform).
 *
 * **The result of this function affects klib ABI.**
 *
 * @param compatibleMode If `true`, the mangled names of property backing fields are just those fields' names.
 * Otherwise, mangles such fields exactly as their corresponding properties.
 */


fun D . signatureMangle ( compatibleMode : Boolean ) : Long

= signatureString ( compatibleMode ) . hashMangle

/**
 * Computes the hash code of the string returned by [signatureString] using the CityHash64 algorithm.
 *
 * This hash code is to be used for building the declaration's [IdSignature].
 *
 * **The result of this function affects klib ABI.**
 *
 * @param compatibleMode If `true`, the mangled names of property backing fields are just those fields' names.
 * Otherwise, mangles such fields exactly as their corresponding properties.
 *
 * @see [IdSignature.CommonSignature.id]
 */


fun IrDeclaration . mangleString ( compatibleMode : Boolean ) : String

/**
 * Returns the mangled name for the declaration, prefixed by mangled names of all its parents.
 *
 * For example, for `foo`'s getter in the following code:
 * ```kotlin
 * class Test {
 * val foo: Int
 * }
 * ```
 * the result of this function will be `"Test#<get-foo>(){}kotlin.Int"` or `"Test#<get-foo>(){}"`
 * (depending on the target platform).
 *
 * The result of this function is only used for assigning names to binary symbols of Kotlin functions in the final executable
 * produced by Kotlin/Native.
 * **It does not affect klib ABI.**
 *
 * @param compatibleMode If `true`, the mangled names of property backing fields are just those fields' names.
 * Otherwise, mangles such fields exactly as their corresponding properties.
 */


abstract fun check ( typeRef : T , context : CheckerContext , reporter : DiagnosticReporter )

/**
 * [FirTypeChecker] should only be used when the check can be performed independent of the context of the type refs. That is,
 * you should NOT be examining containing declarations, qualified accesses, etc. when writing a FirTypeChecker.
 *
 * If the check is dependent on context, or if it is specific to type refs in a certain kind of declaration or expression,
 * please write a [org.jetbrains.kotlin.fir.analysis.checkers.declaration.FirDeclarationChecker] or
 * [org.jetbrains.kotlin.fir.analysis.checkers.expression.FirExpressionChecker] instead.
 */


public fun getAllAnchorModules ( ) : Collection < KtSourceModule >

/**
 * Returns all anchor modules configured in the project.
 */


public fun createDispatcher ( allFactories : List < MainDispatcherFactory > ) : MainCoroutineDispatcher

/**
 * Creates the main dispatcher. [allFactories] parameter contains all factories found by service loader.
 * This method is not guaranteed to be idempotent.
 *
 * It is required that this method fails with an exception instead of returning an instance that doesn't work
 * correctly as a [Delay].
 * The reason for this is that, on the JVM, [DefaultDelay] will use [Dispatchers.Main] for most delays by default
 * if this method returns an instance without throwing.
 */


= null

/**
 * Hint used along with error message when the factory failed to create a dispatcher.
 */


fun computeSignature ( declaration : IrDeclaration ) : IdSignature ?

/**
 * Computes a signature of [declaration].
 *
 * @param declaration The declaration to compute the signature for.
 * @return The signature of the [declaration], or `null` if the declaration cannot have a signature (for example,
 * because it is not exportable according to [org.jetbrains.kotlin.backend.common.serialization.mangle.KotlinExportChecker]).
 */


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

/**
 * Informs the signature computer that all signature computations for top-level private declarations within [block] will use
 * the [file]'s signature (a signature for a top-level private declaration should always contain a signature of the file this
 * declaration is declared in).
 *
 * @param file A symbol of the file for declarations in which signatures will be computed in [block], or `null` if the declarations
 * won't have a file associated (like some compiler generated declarations).
 * @param block A block within which signatures computed for private declarations will include [file]'s signature.
 * @see [IdSignature.FileSignature]
 */


internal inline fun Project . runProjectConfigurationHealthCheck ( check : Project . ( ) -> Unit )

{ <EOL> if ( failures . isNotEmpty ( ) ) { <EOL> return <EOL> } <EOL> check ( ) <EOL> }

/**
 * Function used to wrap any checks/assertions done on the current project configuration / project model.
 *
 * Runs the given [check] only on projects that are considered "healthy".
 * A "healthy" project did evaluate correctly which means "without exceptions/errors".
 *
 * This function has to be used over "just running the check", because running project configuration checks
 * on projects that failed to configure will lead to false positive error reporting.
 * In most cases (when called in 'afterEvaluate') such false positive error message will even swallow the real root cause
 * of configuration failure.
 *
 * Note:
 * During Gradle/IDEA sync (import), Gradle will be set into `lenientMode` and will catch all exceptions
 * during evaluation of the build script. Those exceptions will be put into the [ClassPathModeExceptionCollector].
 * Any project that contains caught and collected exceptions in this 'collector' should be considered failed
 * and running project model checks is undesirable. In this mode, throwing exceptions in `afterEvaluate` will even fail the process
 * which would swallow the previously collected exceptions.
 *
 * Example:
 * We have a post-evaluation check that will report users an error if no Kotlin target
 * was registered.
 *
 * Consider the following build script:
 *
 * ```kotlin
 * plugins {
 * kotlin("multiplatform")
 * }
 *
 * error("Something went wrong during the configuration phase")
 *
 * kotlin {
 * jvm() // <- * Note: jvm target registered
 * js() // <- * Note: js target registered
 * }
 * ```
 *
 * In this example, the exception is thrown before the configuration of Kotlin targets.
 * During IDEA import, this exception will be caught and put into the [ClassPathModeExceptionCollector].
 * When running the assertion just plainly (*without this wrapper function*), the user
 * will not see the real cause of failure, but a rather bizarre:
 * "Please initialize at least one Kotlin target"
 * error message. Which is not helpful at all.
 *
 */


internal inline fun Project . runProjectConfigurationHealthCheckWhenEvaluated ( crossinline check : Project . ( ) -> Unit )

{ <EOL> launchInStage ( KotlinPluginLifecycle . Stage . ReadyForExecution ) { <EOL> runProjectConfigurationHealthCheck ( check ) <EOL> } <EOL> }

/**
 * Convenience function for
 * ```kotlin
 * whenEvaluated {
 * runProjectConfigurationCheck(action)
 * }
 * ```
 * @see runProjectConfigurationHealthCheck
 */


@ OptIn ( DelicateCoroutinesApi :: class , ExperimentalCoroutinesApi :: class ) <EOL> public fun createDocumentationModels ( ) : List < DModule >

= newSingleThreadContext ( "<STR_LIT>" ) . use { coroutineContext -> <EOL> runBlocking ( coroutineContext ) { <EOL> context . configuration . sourceSets . parallelMap { sourceSet -> translateSources ( sourceSet , context ) } . flatten ( ) <EOL> . also { modules -> if ( modules . isEmpty ( ) ) exitGenerationGracefully ( "<STR_LIT>" ) } <EOL> } <EOL> }

/**
 * Implementation note: it runs in a separated single thread due to existing support of coroutines (see #2936)
 */


override fun chooseConstructor ( implClass : IrClass , expression : IrConstructorCall ) : IrConstructor

{ <EOL> val existingValueArguments = ( <NUM_LIT:0> until expression . valueArgumentsCount ) <EOL> . filter { expression . getValueArgument ( it ) != null } <EOL> . map { expression . symbol . owner . valueParameters [ it ] . name } <EOL> . toSet ( ) <EOL> return implClass . constructors . singleOrNull { cons -> <EOL> cons . valueParameters . map { it . name } . toSet ( ) == existingValueArguments <EOL> } ? : implClass . addConstructor { <EOL> startOffset = SYNTHETIC_OFFSET <EOL> endOffset = SYNTHETIC_OFFSET <EOL> visibility = DescriptorVisibilities . PUBLIC <EOL> } . apply { <EOL> expression . symbol . owner . valueParameters <EOL> . filter { it . name in existingValueArguments } <EOL> . forEach { parameter -> addValueParameter ( parameter . name . asString ( ) , parameter . type ) } <EOL> createConstructorBody ( this , expression . symbol . owner ) <EOL> } <EOL> }

/**
 * When annotation is defined in another module, default values can be not available
 * during incremental compilation.
 *
 * In that case we need to delegate evaluating defaults to original class constructor.
 * The simplest way to do that - generate a constructor for each set of arguments used for
 * instantiating annotations, hope there shouldn't be too many of them in each module.
 */


@ ObsoleteCoroutinesApi <EOL> @ Deprecated ( level = DeprecationLevel . WARNING , message = "<STR_LIT>" ) <EOL> public fun < E > ReceiveChannel < E > . broadcast ( capacity : Int = <NUM_LIT:1> , start : CoroutineStart = CoroutineStart . LAZY ) : BroadcastChannel < E >

{ <EOL> val scope = GlobalScope + Dispatchers . Unconfined + CoroutineExceptionHandler { _ , _ -> } <EOL> val channel = this <EOL> return scope . broadcast ( capacity = capacity , start = start , onCompletion = { cancelConsumed ( it ) } ) { <EOL> for ( e in channel ) { <EOL> send ( e ) <EOL> } <EOL> } <EOL> }

/**
 * Broadcasts all elements of the channel.
 * This function [consumes][ReceiveChannel.consume] all elements of the original [ReceiveChannel].
 *
 * The kind of the resulting channel depends on the specified [capacity] parameter:
 * when `capacity` is positive (1 by default), but less than [UNLIMITED] -- uses [BroadcastChannel] with a buffer of given capacity,
 * when `capacity` is [CONFLATED] -- uses [ConflatedBroadcastChannel] that conflates back-to-back sends;
 * Note that resulting channel behaves like [ConflatedBroadcastChannel] but is not an instance of [ConflatedBroadcastChannel].
 * otherwise -- throws [IllegalArgumentException].
 *
 * ### Cancelling broadcast
 *
 * **To stop broadcasting from the underlying channel call [cancel][BroadcastChannel.cancel] on the result.**
 *
 * Do not use [close][BroadcastChannel.close] on the resulting channel.
 * It causes eventual failure of the broadcast coroutine and cancellation of the underlying channel, too,
 * but it is not as prompt.
 *
 * ### Future replacement
 *
 * This function has an inappropriate result type of [BroadcastChannel] which provides
 * [send][BroadcastChannel.send] and [close][BroadcastChannel.close] operations that interfere with
 * the broadcasting coroutine in hard-to-specify ways.
 *
 * **Note: This API is obsolete since 1.5.0.** It is deprecated with warning in 1.7.0.
 * It is replaced with [Flow.shareIn][kotlinx.coroutines.flow.shareIn] operator.
 *
 * @param start coroutine start option. The default value is [CoroutineStart.LAZY].
 */


@ ObsoleteCoroutinesApi <EOL> @ Deprecated ( level = DeprecationLevel . WARNING , message = "<STR_LIT>" ) <EOL> public fun < E > CoroutineScope . broadcast ( context : CoroutineContext = EmptyCoroutineContext , capacity : Int = <NUM_LIT:1> , start : CoroutineStart = CoroutineStart . LAZY , onCompletion : CompletionHandler ? = null , @ BuilderInference block : suspend ProducerScope < E > . ( ) -> Unit ) : BroadcastChannel < E >

{ <EOL> val newContext = newCoroutineContext ( context ) <EOL> val channel = BroadcastChannel < E > ( capacity ) <EOL> val coroutine = if ( start . isLazy ) <EOL> LazyBroadcastCoroutine ( newContext , channel , block ) else <EOL> BroadcastCoroutine ( newContext , channel , active = true ) <EOL> if ( onCompletion != null ) coroutine . invokeOnCompletion ( handler = onCompletion ) <EOL> coroutine . start ( start , coroutine , block ) <EOL> return coroutine <EOL> }

/**
 * Launches new coroutine to produce a stream of values by sending them to a broadcast channel
 * and returns a reference to the coroutine as a [BroadcastChannel]. The resulting
 * object can be used to [subscribe][BroadcastChannel.openSubscription] to elements produced by this coroutine.
 *
 * The scope of the coroutine contains [ProducerScope] interface, which implements
 * both [CoroutineScope] and [SendChannel], so that coroutine can invoke
 * [send][SendChannel.send] directly. The channel is [closed][SendChannel.close]
 * when the coroutine completes.
 *
 * Coroutine context is inherited from a [CoroutineScope], additional context elements can be specified with [context] argument.
 * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used.
 * The parent job is inherited from a [CoroutineScope] as well, but it can also be overridden
 * with corresponding [context] element.
 *
 * Uncaught exceptions in this coroutine close the channel with this exception as a cause and
 * the resulting channel becomes _failed_, so that any attempt to receive from such a channel throws exception.
 *
 * The kind of the resulting channel depends on the specified [capacity] parameter:
 * - when `capacity` is positive (1 by default), but less than [UNLIMITED] -- uses [BroadcastChannel] with a buffer of given capacity,
 * - when `capacity` is [CONFLATED] -- uses [ConflatedBroadcastChannel] that conflates back-to-back sends;
 * Note that resulting channel behaves like [ConflatedBroadcastChannel] but is not an instance of [ConflatedBroadcastChannel].
 * - otherwise -- throws [IllegalArgumentException].
 *
 * **Note:** By default, the coroutine does not start until the first subscriber appears via [BroadcastChannel.openSubscription]
 * as [start] parameter has a value of [CoroutineStart.LAZY] by default.
 * This ensures that the first subscriber does not miss any sent elements.
 * However, later subscribers may miss elements.
 *
 * See [newCoroutineContext] for a description of debugging facilities that are available for newly created coroutine.
 *
 * ### Cancelling broadcast
 *
 * **To stop broadcasting from the underlying channel call [cancel][BroadcastChannel.cancel] on the result.**
 *
 * Do not use [close][BroadcastChannel.close] on the resulting channel.
 * It causes failure of the `send` operation in broadcast coroutine and would not cancel it if the
 * coroutine is doing something else.
 *
 * ### Future replacement
 *
 * This API is obsolete since 1.5.0 and deprecated with warning since 1.7.0.
 * This function has an inappropriate result type of [BroadcastChannel] which provides
 * [send][BroadcastChannel.send] and [close][BroadcastChannel.close] operations that interfere with
 * the broadcasting coroutine in hard-to-specify ways.
 * It is replaced with [Flow.shareIn][kotlinx.coroutines.flow.shareIn] operator.
 *
 * @param context additional to [CoroutineScope.coroutineContext] context of the coroutine.
 * @param capacity capacity of the channel's buffer (1 by default).
 * @param start coroutine start option. The default value is [CoroutineStart.LAZY].
 * @param onCompletion optional completion handler for the producer coroutine (see [Job.invokeOnCompletion]).
 * @param block the coroutine code.
 */


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

{ <EOL> val newEvent = BatchTrainingEvent ( epochIndex , batchIndex , lossValue , metricValues ) <EOL> addNewBatchEvent ( newEvent , epochIndex , batchIndex ) <EOL> }

/**
 * Appends tracked data from one batch event.
 *
 * @param epochIndex Epoch index.
 * @param batchIndex Epoch index.
 * @param lossValue Value of loss function on training dataset.
 * @param metricValues Value of metric function on training dataset.
 */


public fun appendBatch ( batchTrainingEvent : BatchTrainingEvent )

{ <EOL> addNewBatchEvent ( batchTrainingEvent , batchTrainingEvent . epochIndex , batchTrainingEvent . batchIndex ) <EOL> }

/**
 * Appends one [BatchTrainingEvent].
 */


public fun appendEpoch ( epochIndex : Int , lossValue : Double , metricValues : List < Double > , valLossValue : Double ? , valMetricValues : List < Double > ? <EOL> )

{ <EOL> val newEvent = EpochTrainingEvent ( epochIndex , lossValue , metricValues , valLossValue , valMetricValues ) <EOL> addNewEpochEvent ( newEvent , epochIndex ) <EOL> }

/**
 * Appends tracked data from one epoch event.
 *
 * @param epochIndex Epoch index.
 * @param lossValue Value of loss function on training dataset.
 * @param metricValues Value of metric function on training dataset.
 * @param valLossValue Value of loss function on validation dataset. Could be null, if validation phase is missed.
 * @param valMetricValues Value of metric function on validation dataset. Could be null, if validation phase is missed.
 */


public fun appendEpoch ( epochTrainingEvent : EpochTrainingEvent )

{ <EOL> addNewEpochEvent ( epochTrainingEvent , epochTrainingEvent . epochIndex ) <EOL> }

/**
 * Appends one [EpochTrainingEvent].
 */


public fun lastBatchEvent ( ) : BatchTrainingEvent

{ <EOL> return historyByEpochAndBatch . lastEntry ( ) . value ! ! . lastEntry ( ) . value <EOL> }

/**
 * Returns last [BatchTrainingEvent]
 */


public fun lastEpochEvent ( ) : EpochTrainingEvent

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

/**
 * Returns last [EpochTrainingEvent].
 */


public fun eventsByEpoch ( epochIndex : Int ) : TreeMap < Int , BatchTrainingEvent > ?

{ <EOL> return historyByEpochAndBatch [ epochIndex ] <EOL> }

/**
 * Returns all [BatchTrainingEvent] of the specific epoch.
 *
 * @param [epochIndex] Epoch index of the required epoch to return its batch events.
 * @return Indexed and sorted [TreeMap] of [BatchTrainingEvent].
 */


internal fun torchStylePreprocessing ( channelsLastParameter : Boolean = true ) : Operation < FloatData , FloatData >

{ <EOL> return pipeline < FloatData > ( ) <EOL> . rescale { scalingCoefficient = <NUM_LIT> } <EOL> . normalize { <EOL> mean = floatArrayOf ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) <EOL> std = floatArrayOf ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) <EOL> channelsLast = channelsLastParameter <EOL> } <EOL> }


internal fun caffeStylePreprocessing ( channelsLastParameter : Boolean = true ) : Operation < FloatData , FloatData >

{ <EOL> return pipeline < FloatData > ( ) <EOL> . normalize { <EOL> mean = floatArrayOf ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) <EOL> std = floatArrayOf ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) <EOL> channelsLast = channelsLastParameter <EOL> } <EOL> }


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

{ <EOL> return filterIsInstanceTo ( ArrayList < R > ( ) , klass ) <EOL> }

/**
 * Returns a list containing all elements that are instances of specified class.
 *
 * @sample samples.collections.Collections.Filtering.filterIsInstanceJVM
 */


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

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

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


public actual fun < T > MutableList < T > . reverse ( ) : Unit

{ <EOL> java . util . Collections . reverse ( this ) <EOL> }

/**
 * Reverses elements in the list in-place.
 */


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

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

/**
 * Returns a new [SortedSet][java.util.SortedSet] of all elements.
 */


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

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

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


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

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

/**
 * Returns the sum of all values produced by [selector] function applied to each element in the collection.
 */


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

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


internal fun PageContentBuilder . DocumentableContentBuilder . customTagSectionContent ( documentable : Documentable , sourceSets : Set < DokkaConfiguration . DokkaSourceSet > , customTagContentProviders : List < CustomTagContentProvider > , )

{ <EOL> val customTags = documentable . customTags <EOL> if ( customTags . isEmpty ( ) ) return <EOL> sourceSets . forEach { sourceSet -> <EOL> customTags . forEach { ( _ , sourceSetTag ) -> <EOL> sourceSetTag [ sourceSet ] ? . let { tag -> <EOL> customTagContentProviders . filter { it . isApplicable ( tag ) } . forEach { provider -> <EOL> group ( sourceSets = setOf ( sourceSet ) , styles = setOf ( ContentStyle . KDocTag ) ) { <EOL> with ( provider ) { <EOL> contentForDescription ( sourceSet , tag ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Custom tags are tags which are not part of the [KDoc specification](https://kotlinlang.org/docs/kotlin-doc.html). For instance, a user-defined tag
 * which is specific to the user's code base would be considered a custom tag.
 *
 * For details, see [CustomTagContentProvider]
 */


internal fun PageContentBuilder . DocumentableContentBuilder . unnamedTagSectionContent ( documentable : Documentable , sourceSets : Set < DokkaConfiguration . DokkaSourceSet > , toHeaderString : TagWrapper . ( ) -> String , )

{ <EOL> val unnamedTags = documentable . groupedTags <EOL> . filterNot { ( k , _ ) -> k . isSubclassOf ( NamedTagWrapper :: class ) || k in unnamedTagsExceptions } <EOL> . values . flatten ( ) . groupBy { it . first } <EOL> . mapValues { it . value . map { it . second } } <EOL> . takeIf { it . isNotEmpty ( ) } ? : return <EOL> sourceSets . forEach { sourceSet -> <EOL> unnamedTags [ sourceSet ] ? . let { tags -> <EOL> if ( tags . isNotEmpty ( ) ) { <EOL> tags . groupBy { it :: class } . forEach { ( _ , sameCategoryTags ) -> <EOL> group ( sourceSets = setOf ( sourceSet ) , styles = setOf ( ContentStyle . KDocTag ) ) { <EOL> header ( level = KDOC_TAG_HEADER_LEVEL , text = sameCategoryTags . first ( ) . toHeaderString ( ) , styles = setOf ( ) ) <EOL> sameCategoryTags . forEach { comment ( it . root , styles = setOf ( ) ) } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Tags in KDoc are used in form of "@tag name value".
 * This function handles tags that have only value parameter without name.
 * List of such tags: `@return`, `@author`, `@since`, `@receiver`
 */


private fun Set < DokkaConfiguration . DokkaSourceSet > . getPossibleFallback ( sourceSet : DokkaConfiguration . DokkaSourceSet )

= <EOL> this . filter { it . sourceSetID in sourceSet . dependentSourceSets }

/**
 * Used for multi-value tags (e.g. params) when values are missed on some platforms.
 * It this case description is inherited from parent platform.
 * E.g. if param hasn't description in JVM, the description is taken from common.
 */


private fun Documentable . isDefinedInSharedSourceSetOnly ( inheritorsSourceSets : Set < DokkaConfiguration . DokkaSourceSet > )

= <EOL> sourceSets . size == <NUM_LIT:1> && <EOL> ( sourceSets . first ( ) . analysisPlatform == Platform . common || sourceSets . first ( ) . hasDependentSourceSet ( inheritorsSourceSets ) )

/**
 * Detect that documentable is located only in the shared code without expect-actuals
 * Value of `analysisPlatform` will be [Platform.common] in cases if a source set shared between 2 different platforms.
 * But if it shared between 2 same platforms (e.g. jvm("awt") and jvm("android"))
 * then the source set will be still marked as jvm platform.
 *
 * So, we also try to check if any of inheritors source sets depends on current documentable source set.
 * that will mean that the source set is shared.
 */


override fun matches ( startIndex : Int , testString : CharSequence , matchResult : MatchResultImpl ) : Int

{ <EOL> val start = matchResult . getConsumed ( groupIndex ) <EOL> matchResult . setConsumed ( groupIndex , startIndex ) <EOL> children . forEach { <EOL> val shift = it . matches ( startIndex , testString , matchResult ) <EOL> if ( shift >= <NUM_LIT:0> ) { <EOL> return shift <EOL> } <EOL> } <EOL> matchResult . setConsumed ( groupIndex , start ) <EOL> return - <NUM_LIT:1> <EOL> }

/**
 * Returns startIndex+shift, the next position to match
 */


public fun resolveKdocFqName ( analysisSession : KtAnalysisSession , fqName : FqName , contextElement : KtElement ) : Collection < KtSymbol >

/**
 * This function must return additional symbols for [contextElement] in KDoc.
 */


= <EOL> EP_NAME . extensions . flatMap { it . resolveKdocFqName ( analysisSession , fqName , contextElement ) }


@ DelicateSymbolTableApi <EOL> fun forEachDeclarationSymbol ( block : ( IrSymbol ) -> Unit )

{ <EOL> classSlice . forEachSymbol { block ( it ) } <EOL> constructorSlice . forEachSymbol { block ( it ) } <EOL> functionSlice . forEachSymbol { block ( it ) } <EOL> propertySlice . forEachSymbol { block ( it ) } <EOL> enumEntrySlice . forEachSymbol { block ( it ) } <EOL> typeAliasSlice . forEachSymbol { block ( it ) } <EOL> fieldSlice . forEachSymbol { block ( it ) } <EOL> }

/**
 * This function is quite messy and doesn't have good contract of what exactly is traversed.
 * Basic idea is it traverse symbols which can be reasonable referered from other module
 *
 * Be careful when using it, and avoid it, except really need.
 */


public fun onModification ( module : KtModule )

/**
 * [onModification] is invoked in a write action before or after an out-of-block modification happens in [module]'s source code.
 *
 * See [KotlinModificationTrackerFactory.createProjectWideOutOfBlockModificationTracker] for an explanation of out-of-block
 * modifications.
 *
 * This event may be published for any and all source code changes, not just out-of-block modifications, to simplify the implementation
 * of modification detection.
 *
 * @see KotlinTopics
 */


fun generateClass ( generator : ClassGenerator , declaration : IrClass ? ) : ClassGenerator

/**
 * Override this method to decorate the [generator] that is used in the compiler backend to generate IR to bytecode.
 * [Interface delegation](https://kotlinlang.org/docs/delegation.html) can be used to avoid implementing each member manually.
 *
 * @param generator the generator used to generate the original class
 * @param declaration the IR representation of the generated class, or `null` if this class has no IR representation
 * (for example, if it's an anonymous object copied during inlining bytecode)
 */


public fun runTest ( context : CoroutineContext = EmptyCoroutineContext , timeout : Duration = DEFAULT_TIMEOUT . getOrThrow ( ) , testBody : suspend TestScope . ( ) -> Unit ) : TestResult

{ <EOL> check ( context [ RunningInRunTest ] == null ) { <EOL> "<STR_LIT>" <EOL> } <EOL> return TestScope ( context + RunningInRunTest ) . runTest ( timeout , testBody ) <EOL> }

/**
 * Executes [testBody] as a test in a new coroutine, returning [TestResult].
 *
 * On JVM and Native, this function behaves similarly to `runBlocking`, with the difference that the code that it runs
 * will skip delays. This allows to use [delay] in tests without causing them to take more time than necessary.
 * On JS, this function creates a `Promise` that executes the test body with the delay-skipping behavior.
 *
 * ```
 * @Test
 * fun exampleTest() = runTest {
 * val deferred = async {
 * delay(1.seconds)
 * async {
 * delay(1.seconds)
 * }.await()
 * }
 *
 * deferred.await() // result available immediately
 * }
 * ```
 *
 * The platform difference entails that, in order to use this function correctly in common code, one must always
 * immediately return the produced [TestResult] from the test method, without doing anything else afterwards. See
 * [TestResult] for details on this.
 *
 * The test is run on a single thread, unless other [CoroutineDispatcher] are used for child coroutines.
 * Because of this, child coroutines are not executed in parallel to the test body.
 * In order for the spawned-off asynchronous code to actually be executed, one must either [yield] or suspend the
 * test body some other way, or use commands that control scheduling (see [TestCoroutineScheduler]).
 *
 * ```
 * @Test
 * fun exampleWaitingForAsyncTasks1() = runTest {
 * // 1
 * val job = launch {
 * // 3
 * }
 * // 2
 * job.join() // the main test coroutine suspends here, so the child is executed
 * // 4
 * }
 *
 * @Test
 * fun exampleWaitingForAsyncTasks2() = runTest {
 * // 1
 * launch {
 * // 3
 * }
 * // 2
 * testScheduler.advanceUntilIdle() // runs the tasks until their queue is empty
 * // 4
 * }
 * ```
 *
 * ### Task scheduling
 *
 * Delay skipping is achieved by using virtual time.
 * If [Dispatchers.Main] is set to a [TestDispatcher] via [Dispatchers.setMain] before the test,
 * then its [TestCoroutineScheduler] is used;
 * otherwise, a new one is automatically created (or taken from [context] in some way) and can be used to control
 * the virtual time, advancing it, running the tasks scheduled at a specific time etc.
 * The scheduler can be accessed via [TestScope.testScheduler].
 *
 * Delays in code that runs inside dispatchers that don't use a [TestCoroutineScheduler] don't get skipped:
 * ```
 * @Test
 * fun exampleTest() = runTest {
 * val elapsed = TimeSource.Monotonic.measureTime {
 * val deferred = async {
 * delay(1.seconds) // will be skipped
 * withContext(Dispatchers.Default) {
 * delay(5.seconds) // Dispatchers.Default doesn't know about TestCoroutineScheduler
 * }
 * }
 * deferred.await()
 * }
 * println(elapsed) // about five seconds
 * }
 * ```
 *
 * ### Failures
 *
 * #### Test body failures
 *
 * If the created coroutine completes with an exception, then this exception will be thrown at the end of the test.
 *
 * #### Timing out
 *
 * There's a built-in timeout of 60 seconds for the test body. If the test body doesn't complete within this time,
 * then the test fails with an [AssertionError]. The timeout can be changed for each test separately by setting the
 * [timeout] parameter.
 *
 * Additionally, setting the `kotlinx.coroutines.test.default_timeout` system property on the
 * JVM to any string that can be parsed using [Duration.parse] (like `1m`, `30s` or `1500ms`) will change the default
 * timeout to that value for all tests whose [timeout] is not set explicitly; setting it to anything else will throw an
 * exception every time [runTest] is invoked.
 *
 * On timeout, the test body is cancelled so that the test finishes. If the code inside the test body does not
 * respond to cancellation, the timeout will not be able to make the test execution stop.
 * In that case, the test will hang despite the attempt to terminate it.
 *
 * On the JVM, if `DebugProbes` from the `kotlinx-coroutines-debug` module are installed, the current dump of the
 * coroutines' stack is printed to the console on timeout before the test body is cancelled.
 *
 * #### Reported exceptions
 *
 * Unhandled exceptions will be thrown at the end of the test.
 * If uncaught exceptions happen after the test finishes, they are propagated in a platform-specific manner:
 * see [handleCoroutineException] for details.
 * If the test coroutine completes with an exception, the unhandled exceptions are suppressed by it.
 *
 * #### Uncompleted coroutines
 *
 * Otherwise, the test will hang until all the coroutines launched inside [testBody] complete.
 * This may be an issue when there are some coroutines that are not supposed to complete, like infinite loops that
 * perform some background work and are supposed to outlive the test.
 * In that case, [TestScope.backgroundScope] can be used to launch such coroutines.
 * They will be cancelled automatically when the test finishes.
 *
 * ### Configuration
 *
 * [context] can be used to affect the environment of the code under test. Beside just being passed to the coroutine
 * scope created for the test, [context] also can be used to change how the test is executed.
 * See the [TestScope] constructor function documentation for details.
 *
 * @throws IllegalArgumentException if the [context] is invalid. See the [TestScope] constructor docs for details.
 */


@ Deprecated ( "<STR_LIT>" + "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" , "<STR_LIT>" ) , DeprecationLevel . WARNING ) <EOL> public fun runTest ( context : CoroutineContext = EmptyCoroutineContext , dispatchTimeoutMs : Long , testBody : suspend TestScope . ( ) -> Unit ) : TestResult

{ <EOL> if ( context [ RunningInRunTest ] != null ) <EOL> throw IllegalStateException ( "<STR_LIT>" ) <EOL> @ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> return TestScope ( context + RunningInRunTest ) . runTest ( dispatchTimeoutMs = dispatchTimeoutMs , testBody ) <EOL> }

/**
 * Executes [testBody] as a test in a new coroutine, returning [TestResult].
 *
 * On JVM and Native, this function behaves similarly to `runBlocking`, with the difference that the code that it runs
 * will skip delays. This allows to use [delay] in without causing the tests to take more time than necessary.
 * On JS, this function creates a `Promise` that executes the test body with the delay-skipping behavior.
 *
 * ```
 * @Test
 * fun exampleTest() = runTest {
 * val deferred = async {
 * delay(1.seconds)
 * async {
 * delay(1.seconds)
 * }.await()
 * }
 *
 * deferred.await() // result available immediately
 * }
 * ```
 *
 * The platform difference entails that, in order to use this function correctly in common code, one must always
 * immediately return the produced [TestResult] from the test method, without doing anything else afterwards. See
 * [TestResult] for details on this.
 *
 * The test is run in a single thread, unless other [CoroutineDispatcher] are used for child coroutines.
 * Because of this, child coroutines are not executed in parallel to the test body.
 * In order for the spawned-off asynchronous code to actually be executed, one must either [yield] or suspend the
 * test body some other way, or use commands that control scheduling (see [TestCoroutineScheduler]).
 *
 * ```
 * @Test
 * fun exampleWaitingForAsyncTasks1() = runTest {
 * // 1
 * val job = launch {
 * // 3
 * }
 * // 2
 * job.join() // the main test coroutine suspends here, so the child is executed
 * // 4
 * }
 *
 * @Test
 * fun exampleWaitingForAsyncTasks2() = runTest {
 * // 1
 * launch {
 * // 3
 * }
 * // 2
 * advanceUntilIdle() // runs the tasks until their queue is empty
 * // 4
 * }
 * ```
 *
 * ### Task scheduling
 *
 * Delay-skipping is achieved by using virtual time.
 * If [Dispatchers.Main] is set to a [TestDispatcher] via [Dispatchers.setMain] before the test,
 * then its [TestCoroutineScheduler] is used;
 * otherwise, a new one is automatically created (or taken from [context] in some way) and can be used to control
 * the virtual time, advancing it, running the tasks scheduled at a specific time etc.
 * Some convenience methods are available on [TestScope] to control the scheduler.
 *
 * Delays in code that runs inside dispatchers that don't use a [TestCoroutineScheduler] don't get skipped:
 * ```
 * @Test
 * fun exampleTest() = runTest {
 * val elapsed = TimeSource.Monotonic.measureTime {
 * val deferred = async {
 * delay(1.seconds) // will be skipped
 * withContext(Dispatchers.Default) {
 * delay(5.seconds) // Dispatchers.Default doesn't know about TestCoroutineScheduler
 * }
 * }
 * deferred.await()
 * }
 * println(elapsed) // about five seconds
 * }
 * ```
 *
 * ### Failures
 *
 * #### Test body failures
 *
 * If the created coroutine completes with an exception, then this exception will be thrown at the end of the test.
 *
 * #### Reported exceptions
 *
 * Unhandled exceptions will be thrown at the end of the test.
 * If the uncaught exceptions happen after the test finishes, the error is propagated in a platform-specific manner.
 * If the test coroutine completes with an exception, the unhandled exceptions are suppressed by it.
 *
 * #### Uncompleted coroutines
 *
 * This method requires that, after the test coroutine has completed, all the other coroutines launched inside
 * [testBody] also complete, or are cancelled.
 * Otherwise, the test will be failed (which, on JVM and Native, means that [runTest] itself will throw
 * [AssertionError], whereas on JS, the `Promise` will fail with it).
 *
 * In the general case, if there are active jobs, it's impossible to detect if they are going to complete eventually due
 * to the asynchronous nature of coroutines. In order to prevent tests hanging in this scenario, [runTest] will wait
 * for [dispatchTimeoutMs] from the moment when [TestCoroutineScheduler] becomes
 * idle before throwing [AssertionError]. If some dispatcher linked to [TestCoroutineScheduler] receives a
 * task during that time, the timer gets reset.
 *
 * ### Configuration
 *
 * [context] can be used to affect the environment of the code under test. Beside just being passed to the coroutine
 * scope created for the test, [context] also can be used to change how the test is executed.
 * See the [TestScope] constructor function documentation for details.
 *
 * @throws IllegalArgumentException if the [context] is invalid. See the [TestScope] constructor docs for details.
 */