fun < T : Any > unique ( ar : KtNDArray < T > , returnIndex : Boolean = false , returnInverse : Boolean = false , returnCounts : Boolean = false , axis : Int ? = null ) : KtNDArray < Long >

= callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( ar , returnIndex , returnInverse , returnCounts , axis ? : None . none ) )

/**
 * Find the unique elements of an array.
 *
 * @param ar input array.
 * @param returnIndex if True, also return the indices of [ar] (along the specified axis,
 * if provided, or in the flattened array) that result in the unique array.
 * @param returnInverse if True, also return the indices of the unique array (for the specified axis, if provided)
 * that can be used to reconstruct [ar].
 * @param returnCounts if True, also return the number of times each unique item appears in [ar].
 * @param axis the axis to operate on.
 * @return The sorted unique values.
 */


fun < T : Any > flip ( m : KtNDArray < T > , vararg axis : Int ? = emptyArray ( ) ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( m , if ( axis . isNotEmpty ( ) ) axis else None . none ) )

/**
 * Reverse the order of elements in an array along the given axis.
 *
 * @param m input data.
 * @param axis or axes along which to flip over.
 * @return A view of [m] with the entries of axis reversed.
 * @see flipud
 * @see fliplr
 */


fun < T : Any > fliplr ( m : KtNDArray < T > ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( m ) )

/**
 * Flip array in the left/right direction.
 * >Note that, input array, must be at least 2-D.
 *
 * @param m input array.
 * @return A view of m with the columns reversed.
 * @see flipud
 * @see rot90
 */


fun < T : Any > flipud ( m : KtNDArray < T > ) : KtNDArray < T >

/**
 * Flip array in the up/down direction.
 *
 * @param m input array.
 * @return A view of m with the columns reversed.
 * @see fliplr
 * @see rot90
 */


fun < T : Any > reshape ( a : KtNDArray < T > , vararg newshape : Int , order : Order = Order . C ) : KtNDArray < T >

= <EOL> a . reshape ( * newshape , order = order )

/**
 * Gives a new shape to an array without changing its data.
 *
 * @param a input array [KtNDArray] of type [T].
 * @param newshape the new shape should be compatible with the original shape.
 * If an integer, then the result will be a 1-D array of that length.
 * One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
 * @return view of an array containing the same data with a new shape.
 * @see KtNDArray.reshape
 */


fun < T : Any > roll ( a : KtNDArray < T > , shift : IntArray , axes : IntArray ? = null ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , shift , axes ? : None . none ) )

/**
 * Roll array elements along a given axis.
 *
 * @param a input array.
 * @param shift the number of places by which elements are shifted.
 * @param axes along which elements are shifted.
 * @return Output [KtNDArray], with the same shape as a.
 * @see rollAxis
 */


fun < T : Any > rot90 ( m : KtNDArray < T > , k : Int = <NUM_LIT:1> , axes : IntArray = intArrayOf ( <NUM_LIT:0> , <NUM_LIT:1> ) ) : KtNDArray < T >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( m , k , axes ) )

/**
 * Rotate an array by 90 degrees in the plane specified by axes.
 *
 * @param m [KtNDArray] of two or more dimensions.
 * @param k number of times the array is rotate by 90 degrees.
 * @param axes the array is rotated in the plane defined by the axes.
 * @return A rotated view of [m].
 * @see flip
 * @see fliplr
 * @see flipud
 */


private fun KtFirPsiJavaClassSymbol . isVisibleByPsi ( useSiteFile : KtFirFileSymbol ) : Boolean ?

{ <EOL> when ( visibility ) { <EOL> Visibilities . Private -> <EOL> return false <EOL> Visibilities . Public -> <EOL> return when ( val outerClass = this . outerClass ) { <EOL> null -> true <EOL> else -> outerClass . isVisibleByPsi ( useSiteFile ) <EOL> } <EOL> JavaVisibilities . PackageVisibility -> { <EOL> val isSamePackage = classIdIfNonLocal . packageFqName == useSiteFile . firSymbol . fir . packageFqName <EOL> if ( ! isSamePackage ) return false <EOL> return when ( val outerClass = this . outerClass ) { <EOL> null -> true <EOL> else -> outerClass . isVisibleByPsi ( useSiteFile ) <EOL> } <EOL> } <EOL> } <EOL> return null <EOL> }

/**
 * [isVisibleByPsi] is a heuristic that decides visibility for most [KtFirPsiJavaClassSymbol]s without deferring to its FIR symbol,
 * thereby avoiding lazy construction of the FIR class. The visibility rules are tailored specifically for Java classes accessed from
 * Kotlin. They cover the most popular visibilities `private`, `public`, and default (package) visibility for top-level and nested
 * classes.
 *
 * Returns `null` if visibility cannot be decided by the heuristic.
 */


public fun < I > pipeline ( ) : Identity < I >

= Identity ( )

/**
 * An entry point for building the preprocessing pipeline.
 */


internal fun ICConfiguration . extractIncrementalCompilationFeatures ( ) : IncrementalCompilationFeatures

{ <EOL> return IncrementalCompilationFeatures ( withAbiSnapshot = false , preciseCompilationResultsBackup = preciseCompilationResultsBackupEnabled , keepIncrementalCompilationCachesInMemory = incrementalCompilationCachesKeptInMemory , ) <EOL> }

/**
 * IncrementalJvmCompilationConfiguration provides single-property API for forward-compatibility.
 *
 * configurationAdapters are there to regroup the properties and work with higher-level interfaces.
 */


protected open fun extractValueParameters ( blockBodyBuilder : IrBlockBodyBuilder , irFunction : IrSimpleFunction , bridge : IrSimpleFunction ) : List < IrValueDeclaration >

= irFunction . valueParameters

/**
 * Usually just returns [irFunction]'s value parameters, but special transformations may be required if,
 * for example, we're dealing with an external function, and that function contains a vararg,
 * which we must extract and convert to an array.
 */


private fun IrSimpleFunction . copyValueParametersFrom ( bridge : IrSimpleFunction , substitutionMap : Map < IrTypeParameterSymbol , IrType > )

{ <EOL> var valueParametersToCopy = bridge . valueParameters <EOL> if ( bridge . isEffectivelyExternal ( ) ) { <EOL> val varargIndex = bridge . varargParameterIndex ( ) <EOL> if ( varargIndex != - <NUM_LIT:1> ) { <EOL> valueParametersToCopy = bridge . valueParameters . take ( varargIndex ) <EOL> } <EOL> } <EOL> valueParameters = valueParameters memoryOptimizedPlus valueParametersToCopy . map { p -> p . copyTo ( this , type = p . type . substitute ( substitutionMap ) ) } <EOL> }

/**
 * Copies the value parameters from [bridge] to [this]. If [bridge] is external and contains a vararg parameter,
 * only copies the parameters before the vararg.
 * The rest parameters are expected to be obtained later using the `arguments` object in JS.
 */


private fun decodeSignedVarintInt ( input : ByteArrayInput ) : Int

{ <EOL> val raw = input . readVarint32 ( ) <EOL> val temp = raw shl <NUM_LIT:31> shr <NUM_LIT:31> xor raw shr <NUM_LIT:1> <EOL> return temp xor ( raw and ( <NUM_LIT:1> shl <NUM_LIT:31> ) ) <EOL> }

/**
 * Source for all varint operations:
 * https://github.com/addthis/stream-lib/blob/master/src/main/java/com/clearspring/analytics/util/Varint.java
 */


private fun PrettyPrinter . handleCompiledClassDeclaration ( classOrObject : KtClassOrObject , text : String )

{ <EOL> handleClassDeclaration ( classOrObject , text ) <EOL> appendLine ( ) <EOL> classOrObject . declarations . forEach { declaration -> <EOL> when ( declaration ) { <EOL> is KtEnumEntry -> { <EOL> handleClassDeclaration ( declaration , text ) <EOL> appendLine ( ) <EOL> } <EOL> is KtClassOrObject -> handleCompiledClassDeclaration ( declaration , text ) <EOL> } <EOL> } <EOL> }

/**
 * [handleCompiledClassDeclaration] uses a custom traversal instead of [forEachDescendantOfType] because trying to access the PSI of
 * compiled code in this test results in exceptions. Hence, we have to traverse nested classes and enum entries manually.
 */


inline operator fun < reified T : Element > getValue ( x : Any ? , kProperty : KProperty < * > ) : T

{ <EOL> val id = kProperty . name <EOL> val element = document . getElementById ( id ) ? : throw NullPointerException ( "<STR_LIT>" ) <EOL> return element as? T ? : throw ClassCastException ( "<STR_LIT>" ) <EOL> }

/**
 * Implementation details of [Document.gettingElementById]. Delegated property
 * @see Document.gettingElementById
 */


fun from ( vararg frameworks : Framework )

= from ( frameworks . toList ( ) )

/**
 * Adds the specified frameworks in this fat framework.
 */


fun from ( frameworks : Iterable < Framework > )

{ <EOL> fromFrameworkDescriptors ( frameworks . map { FrameworkDescriptor ( it ) } ) <EOL> frameworks . forEach { dependsOn ( it . linkTask ) } <EOL> }


fun fromFrameworkDescriptors ( frameworks : Iterable < FrameworkDescriptor > )

{ <EOL> frameworks . forEach { framework -> <EOL> val arch = framework . target . appleArchitecture <EOL> val family = framework . target . family <EOL> val fatFrameworkFamily = getFatFrameworkFamily ( ) <EOL> require ( fatFrameworkFamily == null || family == fatFrameworkFamily ) { <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" <EOL> } <EOL> require ( ! archToFramework . containsKey ( arch ) ) { <EOL> val alreadyAdded = archToFramework . getValue ( arch ) <EOL> "<STR_LIT>" + <EOL> "<STR_LIT>" <EOL> } <EOL> require ( archToFramework . all { it . value . isStatic == framework . isStatic } ) { <EOL> fun staticName ( isStatic : Boolean ) = if ( isStatic ) "<STR_LIT>" else "<STR_LIT>" <EOL> buildString { <EOL> append ( "<STR_LIT>" ) <EOL> archToFramework . forEach { <EOL> append ( "<STR_LIT>" ) <EOL> } <EOL> append ( "<STR_LIT>" ) <EOL> append ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> archToFramework [ arch ] = framework <EOL> } <EOL> }


/**
 * [test.<caret_1>ext]
 * [<caret_2>ext]
 *
 * [Foo.<caret_3>ext]
 * [test.Foo.<caret_4>ext]
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun CharSequence . isEmpty ( ) : Boolean

= length == <NUM_LIT:0>

/**
 * Returns `true` if this char sequence is empty (contains no characters).
 */


public inline fun < T , R > Array < out T > . fold ( initial : R , operation : ( acc : R , T ) -> R ) : R

{ <EOL> var accumulator = initial <EOL> for ( element in this ) accumulator = operation ( accumulator , element ) <EOL> return accumulator <EOL> }

/**
 * Accumulates value starting with [initial] value and applying [operation] from left to right to current accumulator value and each element.
 */


@ SinceKotlin ( "<STR_LIT:1.2>" ) <EOL> public fun Long . toString ( radix : Int ) : String

= <EOL> this . toStringImpl ( checkRadix ( radix ) )

/**
 * Returns a string representation of this [Long] value in the specified [radix].
 *
 * @throws IllegalArgumentException when [radix] is not a valid radix for number to string conversion.
 */


internal fun checkRadix ( radix : Int ) : Int

{ <EOL> if ( radix !in <NUM_LIT:2> .. <NUM_LIT> ) { <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } <EOL> return radix <EOL> }

/**
 * Checks whether the given [radix] is valid radix for string to number and number to string conversion.
 */


public fun vgg16 ( imageSize : Long = <NUM_LIT> , numberOfClasses : Int = <NUM_LIT:10> , numberOfInputChannels : Long = <NUM_LIT:3> , lastLayerActivation : Activations = Activations . Linear ) : Sequential

{ <EOL> return Sequential . of ( Input ( imageSize , imageSize , numberOfInputChannels ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , MaxPool2D ( poolSize = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , padding = ConvPadding . VALID , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , MaxPool2D ( poolSize = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , padding = ConvPadding . VALID , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , MaxPool2D ( poolSize = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , padding = ConvPadding . VALID , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , MaxPool2D ( poolSize = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , padding = ConvPadding . VALID , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , Conv2D ( filters = <NUM_LIT> , kernelSize = intArrayOf ( <NUM_LIT:3> , <NUM_LIT:3> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , dilations = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> ) , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , padding = ConvPadding . SAME , name = "<STR_LIT>" ) , MaxPool2D ( poolSize = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , strides = intArrayOf ( <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:2> , <NUM_LIT:1> ) , padding = ConvPadding . VALID , name = "<STR_LIT>" ) , Flatten ( ) , Dense ( outputSize = <NUM_LIT> , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , name = "<STR_LIT>" ) , Dense ( outputSize = <NUM_LIT> , activation = Activations . Relu , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , name = "<STR_LIT>" ) , Dense ( outputSize = numberOfClasses , activation = lastLayerActivation , kernelInitializer = GlorotUniform ( ) , biasInitializer = Zeros ( ) , name = "<STR_LIT>" ) ) <EOL> }

/**
 * Instantiates the VGG16 model.
 *
 * @param [imageSize] Height = width of image.
 * @param [numberOfClasses] Number of neurons in the last layer (usually, Dense layer).
 * @param [lastLayerActivation] Activation for last layer (usually, Dense layer).
 *
 * @see
 * Very Deep Convolutional Networks for Large-Scale Image Recognition (ICLR 2015).
 * @see
 * Detailed description of VGG'16 model and an approach to build it in Keras.
 */


fun checkContractAndRecordIfPresent ( expression : KtExpression , trace : BindingTrace , ownerDescriptor : FunctionDescriptor )

{ <EOL> if ( ! expression . isContractDescriptionCallPsiCheck ( ) ) return <EOL> val callContext = ContractCallContext ( expression , ownerDescriptor , trace , languageVersionSettings ) <EOL> val contractProviderIfAny = ownerDescriptor . getUserData ( ContractProviderKey ) as? LazyContractProvider ? <EOL> var resultingContractDescription : ContractDescription ? = null <EOL> try { <EOL> if ( ! callContext . isContractDescriptionCallPreciseCheck ( ) ) return <EOL> resultingContractDescription = parseContractAndReportErrors ( callContext ) <EOL> } finally { <EOL> contractProviderIfAny ? . setContractDescription ( resultingContractDescription ) <EOL> } <EOL> }

/**
 * ! IMPORTANT NOTICE !
 *
 * This function has very important non-obvious implicit contract:
 * it *must* call [org.jetbrains.kotlin.contracts.description.LazyContractProvider.setContractDescription]
 * if FunctionDescriptor had [LazyContractProvider] in the user data.
 *
 * Otherwise, it may lead to inconsistent resolve state and failed assertions
 */


private fun parseContractAndReportErrors ( callContext : ContractCallContext ) : ContractDescription ?

{ <EOL> val collector = TraceBasedCollector ( callContext ) <EOL> try { <EOL> checkFeatureEnabled ( collector ) <EOL> val contractNotAllowed = callContext . bindingContext [ BindingContext . CONTRACT_NOT_ALLOWED , callContext . contractCallExpression ] == true <EOL> if ( collector . hasErrors ( ) || contractNotAllowed ) return null <EOL> val parsedContract = PsiContractParserDispatcher ( collector , callContext , storageManager ) . parseContract ( ) <EOL> if ( parsedContract == null ) collector . addFallbackErrorIfNecessary ( ) <EOL> return parsedContract ? . takeUnless { collector . hasErrors ( ) } <EOL> } finally { <EOL> collector . flushDiagnostics ( ) <EOL> } <EOL> }

/**
 * This function deals with some call that is guaranteed to resolve to 'contract' from stdlib, so,
 * ideally, it should satisfy following condition: null returned <=> at least one error was reported
 */


@ OptIn ( ExperimentalNativeApi :: class ) <EOL> fun codePointAt ( strIndex : Int , testString : CharSequence , rightBound : Int ) : Int

{ <EOL> var index = strIndex <EOL> val curChar : Int <EOL> readCharsForCodePoint = <NUM_LIT:1> <EOL> if ( index < rightBound - <NUM_LIT:1> ) { <EOL> val high = testString [ index ++ ] <EOL> val low = testString [ index ] <EOL> if ( Char . isSurrogatePair ( high , low ) ) { <EOL> curChar = Char . toCodePoint ( high , low ) <EOL> readCharsForCodePoint = <NUM_LIT:2> <EOL> } else { <EOL> @ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> curChar = high . toInt ( ) <EOL> } <EOL> } else { <EOL> @ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> curChar = testString [ index ] . toInt ( ) <EOL> } <EOL> return curChar <EOL> }

/** Reads Unicode codepoint from [testString] starting from [strIndex] until [rightBound]. */


= runTest { <EOL> expect ( <NUM_LIT:1> ) <EOL> try { <EOL> ( wrappedCurrentDispatcher ( ) ) { <EOL> expect ( <NUM_LIT:2> ) <EOL> throw AssertionError ( ) <EOL> } <EOL> } catch ( e : AssertionError ) { <EOL> expect ( <NUM_LIT:3> ) <EOL> } <EOL> yield ( ) <EOL> finish ( <NUM_LIT:4> ) <EOL> }

/**
 * Copy pasted from [WithContextTest.testThrowException],
 * then edited to use operator.
 */


@ Test <EOL> fun testWithContextChildWaitSameContext ( )

= runTest { <EOL> expect ( <NUM_LIT:1> ) <EOL> ( wrappedCurrentDispatcher ( ) ) { <EOL> expect ( <NUM_LIT:2> ) <EOL> launch { <EOL> expect ( <NUM_LIT:4> ) <EOL> } <EOL> expect ( <NUM_LIT:3> ) <EOL> "<STR_LIT:OK>" . wrap ( ) <EOL> } . unwrap ( ) <EOL> finish ( <NUM_LIT:5> ) <EOL> }

/**
 * Copy pasted from [WithContextTest.testWithContextChildWaitSameContext],
 * then edited to use operator fun invoke for [CoroutineDispatcher].
 */


public operator fun < C > ColumnsSelector < T , C > . invoke ( ) : ColumnsResolver < C >

= <EOL> this@invoke ( this @ ColumnsSelectionDsl , this @ ColumnsSelectionDsl )

/**
 * Invokes the given [ColumnsSelector] using this [ColumnsSelectionDsl].
 */


@ Deprecated ( message = COL_SELECT_DSL_LIST_DATACOLUMN_GET , replaceWith = ReplaceWith ( COL_SELECT_DSL_LIST_DATACOLUMN_GET_REPLACE ) , level = DeprecationLevel . ERROR , ) <EOL> public operator fun < C > List < DataColumn < C > > . get ( range : IntRange ) : ColumnSet < C >

= <EOL> ColumnsList ( subList ( range . first , range . last + <NUM_LIT:1> ) )

/**
 * ## Deprecated: Columns by Index Range from List of Columns
 * Helper function to create a [ColumnSet] from a list of columns by specifying a range of indices.
 *
 * ### Deprecated
 *
 * Deprecated because it's too niche. Let us know if you have a good use for it!
 */


public operator fun < C , R > SingleColumn < DataRow < C > > . invoke ( selector : ColumnsSelector < C , R > ) : ColumnSet < R >

= <EOL> select ( selector )

/**
 * @include [SelectColumnsSelectionDsl.CommonSelectDocs]
 * @set [SelectColumnsSelectionDsl.CommonSelectDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { myColGroup.`[`select`][SingleColumn.select]` { someCol `[`and`][ColumnsSelectionDsl.and]` `[`colsOf`][SingleColumn.colsOf]`<`[`String`][String]`>() } }`
 *
 * `df.`[select][DataFrame.select]` { myColGroup `[`{`][SingleColumn.select]` colA `[and][ColumnsSelectionDsl.and]` colB `[`}`][SingleColumn.select]` }`
 */


@ Suppress ( "<STR_LIT:INAPPLICABLE_JVM_NAME>" ) <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> public operator fun < C , R > KProperty < DataRow < C > > . invoke ( selector : ColumnsSelector < C , R > ) : ColumnSet < R >

= <EOL> select ( selector )

/**
 * @include [SelectColumnsSelectionDsl.CommonSelectDocs]
 * @set [SelectColumnsSelectionDsl.CommonSelectDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { Type::myColGroup.`[`select`][KProperty.select]` { someCol `[`and`][ColumnsSelectionDsl.and]` `[`colsOf`][SingleColumn.colsOf]`<`[`String`][String]`>() } }`
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::myColGroup `[`{`][KProperty.select]` colA `[`and`][ColumnsSelectionDsl.and]` colB `[`}`][KProperty.select]` }`
 *
 * ## NOTE: {@comment TODO fix warning}
 * If you get a warning `CANDIDATE_CHOSEN_USING_OVERLOAD_RESOLUTION_BY_LAMBDA_ANNOTATION`, you
 * can safely ignore this. It is caused by a workaround for a bug in the Kotlin compiler
 * ([KT-64092](https://youtrack.jetbrains.com/issue/KT-64092/OVERLOADRESOLUTIONAMBIGUITY-caused-by-lambda-argument)).
 */


@ OptIn ( ExperimentalTypeInference :: class ) <EOL> @ OverloadResolutionByLambdaReturnType <EOL> public operator fun < C , R > KProperty < C > . invoke ( selector : ColumnsSelector < C , R > ) : ColumnSet < R >

= <EOL> columnGroup ( this ) . select ( selector )

/**
 * @include [SelectColumnsSelectionDsl.CommonSelectDocs]
 * @set [SelectColumnsSelectionDsl.CommonSelectDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { Type::myColGroup.`[`select`][KProperty.select]` { someCol `[`and`][ColumnsSelectionDsl.and]` `[`colsOf`][SingleColumn.colsOf]`<`[`String`][String]`>() } }`
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::myColGroup `[`{`][KProperty.select]` colA `[`and`][ColumnsSelectionDsl.and]` colB `[`}`][KProperty.select]` }`
 */


public operator fun < R > String . invoke ( selector : ColumnsSelector < * , R > ) : ColumnSet < R >

= <EOL> select ( selector )

/**
 * @include [SelectColumnsSelectionDsl.CommonSelectDocs]
 * @set [SelectColumnsSelectionDsl.CommonSelectDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "myColGroup".`[`select`][String.select]` { someCol `[`and`][ColumnsSelectionDsl.and]` `[`colsOf`][SingleColumn.colsOf]`<`[`String`][String]`>() } }`
 *
 * `df.`[select][DataFrame.select]` { "myColGroup" `[`{`][String.select]` colA `[`and`][ColumnsSelectionDsl.and]` colB `[`}`][String.select]` }`
 */


public operator fun < R > ColumnPath . invoke ( selector : ColumnsSelector < * , R > ) : ColumnSet < R >

= <EOL> select ( selector )

/**
 * @include [SelectColumnsSelectionDsl.CommonSelectDocs]
 * @set [SelectColumnsSelectionDsl.CommonSelectDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "pathTo"["myColGroup"].`[`select`][ColumnPath.select]` { someCol `[`and`][ColumnsSelectionDsl.and]` `[`colsOf`][SingleColumn.colsOf]`<`[`String`][String]`>() } }`
 *
 * `df.`[select][DataFrame.select]` { "pathTo"["myColGroup"] `[`{`][ColumnPath.select]` colA `[`and`][ColumnsSelectionDsl.and]` colB `[`}`][ColumnPath.select]` }`
 *
 * `df.`[select][DataFrame.select]` { `[`pathOf`][pathOf]`("pathTo", "myColGroup").`[`select`][ColumnPath.select]` { someCol `[`and`][ColumnsSelectionDsl.and]` `[`colsOf`][SingleColumn.colsOf]`<`[`String`][String]`>() } }`
 *
 * `df.`[select][DataFrame.select]` { `[`pathOf`][pathOf]`("pathTo", "myColGroup")`[`() {`][ColumnPath.select]` someCol `[`and`][ColumnsSelectionDsl.and]` `[`colsOf`][SingleColumn.colsOf]`<`[`String`][String]`>() `[`}`][ColumnPath.select]` }`
 */


public abstract fun apply ( tf : Ops , yPred : Operand < Float > , yTrue : Operand < Float > , numberOfLabels : Operand < Float > ? <EOL> ) : Operand < Float >

/**
 * Applies [Metric] to the [yPred] labels predicted by the model and known [yTrue] hidden during training.
 *
 * @param yPred The predicted values. shape = `[batch_size, d0, .. dN]`.
 * @param yTrue Ground truth values. Shape = `[batch_size, d0, .. dN]`.
 * @param [tf] TensorFlow graph API for building operations.
 */


public fun convert ( metricType : Metrics ) : Metric

{ <EOL> return when ( metricType ) { <EOL> Metrics . ACCURACY -> Accuracy ( ) <EOL> Metrics . MAE -> MAE ( ) <EOL> Metrics . MSE -> MSE ( ) <EOL> Metrics . MSLE -> MSLE ( ) <EOL> } <EOL> }

/** Converts enum value to subclass of [Metric]. */


public fun convertBack ( metric : Metric ) : Metrics

{ <EOL> return when ( metric ) { <EOL> is Accuracy -> Metrics . ACCURACY <EOL> is MAE -> Metrics . MAE <EOL> is MSE -> Metrics . MSE <EOL> is MSLE -> Metrics . MSLE <EOL> else -> Metrics . ACCURACY <EOL> } <EOL> }

/** Converts subclass of [Metric] to enum value. */


fun exports ( packageFqName : FqName ) : Boolean

/**
 * `true` if this module exports the package with the given FQ name to all dependent modules.
 * For explicit modules, this means that there's an _unqualified_ (without the 'to' clause) exports statement in the module-info file.
 * For automatic modules, this is always `true`.
 *
 * Note that it's assumed that the module contains this package.
 */


fun exportsTo ( packageFqName : FqName , moduleName : String ) : Boolean

/**
 * `true` if this module exports the package with the given FQ name to a module with the given name.
 * For explicit modules, this means that there's either an unqualified exports statement (without the 'to' clause)
 * in the module-info file, or a _qualified_ statement (with the 'to' clause) with the given module name at the right hand side.
 * For automatic modules, this is always `true`.
 *
 * Note that it's assumed that the module contains this package.
 */


override fun getLanguage ( documentable : Documentable , sourceSet : DokkaConfiguration . DokkaSourceSet , ) : DocumentableLanguage ?

{ <EOL> val documentableSource = ( documentable as? WithSources ) ? . sources ? . get ( sourceSet ) ? : return null <EOL> return when ( documentableSource ) { <EOL> is PsiDocumentableSource -> DocumentableLanguage . JAVA <EOL> is KtPsiDocumentableSource -> DocumentableLanguage . KOTLIN <EOL> else -> error ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * For members inherited from Java in Kotlin - it returns [DocumentableLanguage.KOTLIN]
 */


public fun apply ( tf : Ops , features : Operand < Float > , name : String = "<STR_LIT>" ) : Operand < Float >

{ <EOL> return if ( name . isEmpty ( ) ) features else tf . withName ( "<STR_LIT>" ) . identity ( apply ( tf , features ) ) <EOL> }

/**
 * Applies the activation functions to the input [features] to produce the output.
 *
 * @param [tf] TensorFlow graph API for building operations.
 * @param [features] TensorFlow graph leaf node representing layer output before activation function.
 * @param [name] Activation name for TensorFlow graph building purposes.
 */


public fun apply ( tf : Ops , features : Operand < Float > ) : Operand < Float >

/**
 * Applies the activation functions to the input [features] to produce the output.
 *
 * @param [tf] TensorFlow graph API for building operations.
 * @param [features] TensorFlow graph leaf node representing layer output before activation function.
 */


{ <EOL> TODO ( "<STR_LIT:NotU+0020yetU+0020implemented>" ) <EOL> }

/**
 * Linux actual implementation for `getCurrentDate`
 */


internal fun cartesianProductIndices ( x : Int , y : Int ) : List < Pair < Int , Int > >

= <EOL> List ( x ) { i -> List ( y ) { o -> Pair ( i , o ) } } . flatten ( )

/**
 * Create a list of pairs that represents the cartesian product of numbers
 * from the ranges [0, x) and [0, y).
 *
 * @param x specifying the first range [0, x)
 * @param y specifying the second range [0, y)
 * @return list of pairs of numbers from cartesian product
 */


internal fun extractXYInputOutputAxeSizes ( inputData : TensorImageData , permute : IntArray = intArrayOf ( <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> ) ) : IntArray

= <EOL> with ( IntArray ( <NUM_LIT:4> ) ) { <EOL> this [ permute [ <NUM_LIT:0> ] ] = inputData . size <EOL> this [ permute [ <NUM_LIT:1> ] ] = inputData [ <NUM_LIT:0> ] . size <EOL> this [ permute [ <NUM_LIT:2> ] ] = inputData [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] . size <EOL> this [ permute [ <NUM_LIT:3> ] ] = inputData [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] . size <EOL> this <EOL> }

/**
 * Extract x, y, input, and output axe sizes from the tensor data that
 * is actual data of some weights from the model.
 *
 * @param inputData 4D tensor data representing the weights of some model
 * @param permute array of permutation of the result sizes. Defaults to identity
 * permutation that causes results in (x, y, input, output) sizes in returned sizes
 * @return array with 4 numbers representing the sizes (x, y, input, output) of
 * [inputData] according to given permutation
 */


open fun DokkatooFormatPluginContext . configure ( )

/** Format specific configuration - to be implemented by subclasses */


fun DependencyHandler . dokka ( module : String ) : Provider < Dependency >

= <EOL> dokkatooExtension . versions . jetbrainsDokka . map { version -> create ( "<STR_LIT>" ) }

/** Create a [Dependency] for a Dokka module */


fun DependencyHandler . dokkaPlugin ( dependency : Provider < Dependency > ) : Unit

= <EOL> addProvider ( dependencyContainerNames . dokkaPluginsClasspath , dependency )

/** Add a dependency to the Dokka plugins classpath */


fun DependencyHandler . dokkaPlugin ( dependency : String )

{ <EOL> add ( dependencyContainerNames . dokkaPluginsClasspath , dependency ) <EOL> }


fun DependencyHandler . dokkaGenerator ( dependency : Provider < Dependency > )

{ <EOL> addProvider ( dependencyContainerNames . dokkaGeneratorClasspath , dependency ) <EOL> }

/** Add a dependency to the Dokka Generator classpath */


fun DependencyHandler . dokkaGenerator ( dependency : String )

{ <EOL> add ( dependencyContainerNames . dokkaGeneratorClasspath , dependency ) <EOL> }


public fun number ( number : Int ) : AreaPosition

= AreaPosition ( singleOf ( number ) )

/**
 * to fill between specified value and data.
 */


public fun number ( number : Double ) : AreaPosition

= AreaPosition ( singleOf ( number ) )


private fun MockApplication . registerFileDocumentManager ( )

{ <EOL> picoContainer . unregisterComponent ( FileDocumentManager :: class . java . name ) <EOL> registerService ( FileDocumentManager :: class . java , object : MockFileDocumentManagerImpl ( FileDocumentManagerBase . HARD_REF_TO_DOCUMENT_KEY , { DocumentImpl ( it ) } ) { <EOL> override fun getDocument ( file : VirtualFile ) : Document ? { <EOL> val document = super . getDocument ( file ) ? : return null <EOL> file . putUserDataIfAbsent ( FileDocumentManagerBase . HARD_REF_TO_DOCUMENT_KEY , document ) <EOL> return document <EOL> } <EOL> } , ) <EOL> }

/**
 * [MockFileDocumentManagerImpl] doesn't put the cached document as user data under [MockFileDocumentManagerImpl.myCachedDocumentKey] on
 * the virtual file, making [MockFileDocumentManagerImpl.getCachedDocument] effectively return `null`. We extend the file document
 * manager to simulate the behavior of [FileDocumentManagerBase], which puts [FileDocumentManagerBase.HARD_REF_TO_DOCUMENT_KEY] user
 * data on the virtual file.
 */


= applyHierarchyTemplate ( KotlinHierarchyTemplate . default )

/**
 * Sets up a 'natural'/'default' hierarchy withing [KotlinTarget]'s in the project.
 *
 * #### Example
 *
 * ```kotlin
 * kotlin {
 * applyDefaultHierarchyTemplate() // <- position of this call is not relevant!
 *
 * iosX64()
 * iosArm64()
 * linuxX64()
 * linuxArm64()
 * }
 * ```
 *
 * Will create the following SourceSets:
 * `[iosMain, iosTest, appleMain, appleTest, linuxMain, linuxTest, nativeMain, nativeTest]
 *
 *
 * Hierarchy:
 * ```
 * common
 * |
 * +-----------------+-------------------+
 * | |
 *
 * native ...
 *
 * |
 * |
 * |
 * +----------------------+--------------------+-----------------------+
 * | | | |
 *
 * apple linux mingw androidNative
 *
 * |
 * +-----------+------------+------------+
 * | | | |
 *
 * macos ios tvos watchos
 * ```
 *
 * @see KotlinHierarchyTemplate.extend
 */


@ Test <EOL> fun `global settings should overwrite package options in configuration` ( )

{ <EOL> val dokkaOutputDir = File ( projectDir , "<STR_LIT>" ) <EOL> assertTrue ( dokkaOutputDir . mkdirs ( ) ) <EOL> val resourcePath = javaClass . getResource ( "<STR_LIT>" ) ? . toURI ( ) ? : throw IllegalStateException ( "<STR_LIT>" ) <EOL> val jsonPath = File ( resourcePath ) . absolutePath <EOL> PrintWriter ( jsonPath ) . run { <EOL> write ( jsonBuilder ( outputPath = dokkaOutputDir . invariantSeparatorsPath , pluginsClasspath = basePluginJarFile . invariantSeparatorsPath , projectPath = File ( projectDir , "<STR_LIT:src>" ) . invariantSeparatorsPath , globalSourceLinks = """<STR_LIT>""" . trimIndent ( ) , globalExternalDocumentationLinks = """<STR_LIT>""" . trimIndent ( ) , globalPerPackageOptions = """<STR_LIT>""" . trimIndent ( ) , reportUndocumented = false ) , ) <EOL> close ( ) <EOL> } <EOL> val process = ProcessBuilder ( "<STR_LIT:java>" , "<STR_LIT>" , cliJarFile . path , jsonPath ) . redirectErrorStream ( true ) . start ( ) <EOL> val result = process . awaitProcessResult ( ) <EOL> assertEquals ( <NUM_LIT:0> , result . exitCode , "<STR_LIT>" ) <EOL> val extensionLoadedRegex = Regex ( """<STR_LIT>""" ) <EOL> val amountOfExtensionsLoaded = extensionLoadedRegex . findAll ( result . output ) . count ( ) <EOL> assertTrue ( amountOfExtensionsLoaded > <NUM_LIT:10> , "<STR_LIT>" ) <EOL> val undocumentedReportRegex = Regex ( """<STR_LIT>""" ) <EOL> val amountOfUndocumentedReports = undocumentedReportRegex . findAll ( result . output ) . count ( ) <EOL> assertTrue ( amountOfUndocumentedReports > <NUM_LIT:0> , "<STR_LIT>" ) <EOL> assertTrue ( dokkaOutputDir . isDirectory , "<STR_LIT>" ) <EOL> }

/**
 * This test disables global `reportUndocumneted` property and set `reportUndocumented` via perPackageOptions to
 * make sure that global settings apply to dokka context.
 */


private fun createMappingSubstitutor ( fromClass : FirRegularClass , toClass : FirRegularClass , session : FirSession ) : ConeSubstitutor

= <EOL> ConeSubstitutorByMap . create ( fromClass . typeParameters . zip ( toClass . typeParameters ) . associate { ( fromTypeParameter , toTypeParameter ) -> <EOL> fromTypeParameter . symbol to ConeTypeParameterTypeImpl ( ConeTypeParameterLookupTag ( toTypeParameter . symbol ) , isNullable = false ) <EOL> } , session )

/**
 * For fromClass=A<T1, T2>, toClass=B<F1, F1> classes
 * @returns {T1 -> F1, T2 -> F2} substitution
 */


public fun DokkaSourceSet . toDisplaySourceSet ( ) : DisplaySourceSet

= DisplaySourceSet ( this )

/**
 * Transforms the current [DokkaSourceSet] into [DisplaySourceSet],
 * matching the corresponding subset of its properties to [DisplaySourceSet] properties.
 */


public fun Iterable < DokkaSourceSet > . toDisplaySourceSets ( ) : Set < DisplaySourceSet >

= <EOL> map { it . toDisplaySourceSet ( ) } . toSet ( )

/**
 * Transforms all the given [DokkaSourceSet]s into [DisplaySourceSet]s.
 */


private fun substituteArguments ( descriptorVariables : DescriptorVariables , arguments : List < Variable > , ) : Map < String , String >

{ <EOL> val result = mutableMapOf < String , String > ( ) <EOL> fun addResult ( name : String , value : String , ) { <EOL> result [ name ] = substituteKernelVars ( value ) <EOL> } <EOL> val parameters = descriptorVariables . properties <EOL> if ( descriptorVariables . hasOrder ) { <EOL> var namedPart = false <EOL> for ( ( i , arg ) in arguments . withIndex ( ) ) { <EOL> val isNamed = arg . name . isNotEmpty ( ) <EOL> if ( namedPart ) { <EOL> if ( ! isNamed ) throw ReplPreprocessingException ( "<STR_LIT>" ) <EOL> } else { <EOL> if ( isNamed ) namedPart = true <EOL> } <EOL> assert ( namedPart == isNamed ) { "<STR_LIT>" } <EOL> if ( isNamed ) { <EOL> addResult ( arg . name , arg . value ) <EOL> } else { <EOL> if ( parameters . lastIndex < i ) { <EOL> throw ReplPreprocessingException ( "<STR_LIT>" , ) <EOL> } <EOL> addResult ( parameters [ i ] . name , arg . value ) <EOL> } <EOL> } <EOL> } else { <EOL> if ( arguments . any { it . name . isEmpty ( ) } ) { <EOL> if ( parameters . count ( ) != <NUM_LIT:1> ) { <EOL> throw ReplPreprocessingException ( "<STR_LIT>" ) <EOL> } <EOL> if ( arguments . count ( ) != <NUM_LIT:1> ) { <EOL> throw ReplPreprocessingException ( "<STR_LIT>" ) <EOL> } <EOL> addResult ( parameters [ <NUM_LIT:0> ] . name , arguments [ <NUM_LIT:0> ] . value ) <EOL> return result <EOL> } <EOL> arguments . forEach { <EOL> addResult ( it . name , it . value ) <EOL> } <EOL> } <EOL> parameters . forEach { <EOL> if ( ! result . containsKey ( it . name ) ) { <EOL> addResult ( it . name , it . value ) <EOL> } <EOL> } <EOL> return result <EOL> }

/**
 * Matches a list of actual library arguments with declared library parameters
 * Arguments can be named or not. Named arguments should be placed after unnamed
 * Parameters may have default value
 *
 * @return A name-to-value map of library arguments
 */


{ <EOL> val modelHub = TFModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = TFModels . CV . ResNet50 ( ) <EOL> val model = modelHub . loadModel ( modelType ) <EOL> val fileDataLoader = modelType . createPreprocessing ( model ) . fileLoader ( ) <EOL> val imageNetClassLabels = modelHub . loadClassLabels ( ) <EOL> var copiedModel : Functional <EOL> model . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . MAE , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> val hdfFile = modelHub . loadWeights ( modelType ) <EOL> it . loadWeights ( hdfFile ) <EOL> copiedModel = it . copy ( copyWeights = true ) <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> copiedModel . use { <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 ResNet'50 model:
 * - Model configuration, model weights and labels are obtained from [TFModelHub].
 * - Weights are loaded from .h5 file, configuration is loaded from .json file.
 * - Model predicts on a few images located in resources.
 * - No additional training.
 * - No new layers are added.
 * - Special preprocessing (used in ResNet'50 during training on ImageNet dataset) is applied to each image before prediction.
 * - Model copied and used for prediction.
 */


= resnet50copyModelPrediction ( )


private fun createGenericTypeQualifierCallIfApplicable ( firElement : FirElement , psiElement : KtElement ) : KtCallInfo ?

{ <EOL> if ( psiElement !is KtExpression ) return null <EOL> if ( firElement !is FirResolvedQualifier ) return null <EOL> val call = psiElement . getPossiblyQualifiedCallExpression ( ) ? : return null <EOL> if ( call . typeArgumentList == null || call . valueArgumentList != null ) return null <EOL> val parentReferenceExpression = psiElement . parent as? KtDoubleColonExpression ? : return null <EOL> if ( parentReferenceExpression . lhs != psiElement ) return null <EOL> return KtSuccessCallInfo ( KtGenericTypeQualifier ( token , psiElement ) ) <EOL> }

/**
 * Resolves call expressions like `Foo<Bar>` or `test.Foo<Bar>` in calls like `Foo<Bar>::foo`, `test.Foo<Bar>::foo` and class literals like `Foo<Bar>`::class.java.
 *
 * We have a separate [KtGenericTypeQualifier] type of [KtCall].
 */


private fun KtElement . getContainingCallExpressionForCalleeExpression ( ) : KtCallExpression ?

{ <EOL> if ( this !is KtExpression ) return null <EOL> val calleeExpression = deparenthesize ( this ) ? : return null <EOL> if ( calleeExpression is KtCallExpression ) return null <EOL> val callExpression = parentOfType < KtCallExpression > ( ) ? : return null <EOL> if ( deparenthesize ( callExpression . calleeExpression ) != calleeExpression ) return null <EOL> return callExpression <EOL> }

/**
 * When resolving the calleeExpression of a `KtCallExpression`, we resolve the entire `KtCallExpression` instead. This way, the
 * corresponding FIR element is the `FirFunctionCall`, etc. Implicit invoke is then specially handled after obtaining the
 * `FirImplicitInvokeCall`.
 *
 * Note that, if the calleeExpression is already a KtCallExpression, then we don't do this because such a callExpression can be properly
 * resolved to the desired FIR element. That is, cases like `getHighLevelFunction()()` just works, where the both `KtCallExpression`
 * resolve to the desired FIR element.
 */


private fun KtElement . getContainingBinaryExpressionForIncompleteLhs ( ) : KtBinaryExpression ?

{ <EOL> if ( this !is KtExpression ) return null <EOL> val lhs = deparenthesize ( this ) <EOL> val binaryExpression = parentOfType < KtBinaryExpression > ( ) ? : return null <EOL> if ( binaryExpression . operationToken !in KtTokens . ALL_ASSIGNMENTS ) return null <EOL> val leftOfBinary = deparenthesize ( binaryExpression . left ) <EOL> if ( leftOfBinary != lhs && ! ( leftOfBinary is KtDotQualifiedExpression && leftOfBinary . selectorExpression == lhs ) ) return null <EOL> val firBinaryExpression = binaryExpression . getOrBuildFir ( analysisSession . firResolveSession ) <EOL> if ( firBinaryExpression is FirFunctionCall ) { <EOL> if ( firBinaryExpression . origin == FirFunctionCallOrigin . Operator && firBinaryExpression . calleeReference . name in OperatorNameConventions . ASSIGNMENT_OPERATIONS ) { <EOL> return null <EOL> } <EOL> } <EOL> return binaryExpression <EOL> }

/**
 * For `=` and compound access like `+=`, `-=`, `*=`, `/=`, `%=`, the LHS of the binary expression is not a complete call. Hence we
 * find the containing binary expression and resolve that instead.
 *
 * However, if, say, `+=` resolves to `plusAssign`, then the LHS is self-contained. In this case we do not return the containing binary
 * expression so that the FIR element corresponding to the LHS is used directly.
 */


private fun KtElement . getContainingUnaryIncOrDecExpression ( ) : KtUnaryExpression ?

{ <EOL> if ( this !is KtExpression ) return null <EOL> val baseExpression = deparenthesize ( this ) <EOL> val unaryExpression = parentOfType < KtUnaryExpression > ( ) ? : return null <EOL> if ( deparenthesize ( unaryExpression . baseExpression ) != baseExpression || unaryExpression . operationToken !in KtTokens . INCREMENT_AND_DECREMENT ) return null <EOL> return unaryExpression <EOL> }

/**
 * For prefix and postfix `++` and `--`, the idea is the same because FIR represents it as several operations. For example, for `i++`,
 * if the input PSI is `i`, we instead resolve `i++` and extract the read part of this access for `i`.
 */


private fun KtElement . getContainingDotQualifiedExpressionForSelectorExpression ( ) : KtQualifiedExpression ?

{ <EOL> val parent = parent <EOL> if ( parent is KtDotQualifiedExpression && parent . selectorExpression == this ) return parent <EOL> if ( parent is KtSafeQualifiedExpression && parent . selectorExpression == this ) return parent <EOL> return null <EOL> }

/**
 * When resolving selector expression of a [KtDotQualifiedExpression], we instead resolve the containing qualified expression. This way
 * the corresponding FIR element is the `FirFunctionCall` or `FirPropertyAccessExpression`, etc.
 */


private fun toTypeArgumentsMapping ( typeArguments : List < FirTypeProjection > , partiallyAppliedSymbol : KtPartiallyAppliedSymbol < * , * > ) : Map < KtTypeParameterSymbol , KtType >

{ <EOL> val typeParameters = partiallyAppliedSymbol . symbol . typeParameters <EOL> if ( typeParameters . isEmpty ( ) ) return emptyMap ( ) <EOL> if ( typeArguments . size < typeParameters . size ) return emptyMap ( ) <EOL> val result = mutableMapOf < KtTypeParameterSymbol , KtType > ( ) <EOL> for ( ( index , typeParameter ) in typeParameters . withIndex ( ) ) { <EOL> val typeArgument = typeArguments [ index ] <EOL> if ( typeArgument !is FirTypeProjectionWithVariance || typeArgument . variance != Variance . INVARIANT ) return emptyMap ( ) <EOL> result [ typeParameter ] = typeArgument . typeRef . coneType . asKtType ( ) <EOL> } <EOL> return result <EOL> }

/**
 * Maps [typeArguments] to the type parameters of [partiallyAppliedSymbol].
 *
 * If too many type arguments are provided, a mapping is still created. Extra type arguments are simply ignored. If this wasn't the
 * case, the resulting [KtCall] would contain no type arguments at all, which can cause problems later. If too few type arguments are
 * provided, an empty map is returned defensively so that [toTypeArgumentsMapping] doesn't conjure any error types. If you want to map
 * too few type arguments meaningfully, please provide filler types explicitly.
 */


@ JvmName ( "<STR_LIT>" ) <EOL> @ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> internal fun < T : Task > registerTask ( project : Project , name : String , type : Class < T > , body : ( T ) -> ( Unit ) ) : TaskProvider < T >

= <EOL> project . registerTask ( name , type , emptyList ( ) , body )

/**
 * Registers the task with [name] and [type] and initialization script [body]
 */


internal inline fun < reified T : Task > Project . locateTask ( name : String ) : TaskProvider < T > ?

= tasks . locateTask ( name )

/**
 * Locates a task by [name] and [type], without triggering its creation or configuration.
 */


internal inline fun < reified T : Task > TaskContainer . locateTask ( name : String ) : TaskProvider < T > ?

= <EOL> if ( names . contains ( name ) ) named ( name , T :: class . java ) else null


internal inline fun < reified T : Task > Project . locateOrRegisterTask ( name : String , noinline body : ( T ) -> ( Unit ) ) : TaskProvider < T >

{ <EOL> return project . locateTask ( name ) ? : project . registerTask ( name , T :: class . java , body = body ) <EOL> }

/**
 * Locates a task by [name] and [type], without triggering its creation or configuration or registers new task
 * with [name], type [T] and initialization script [body]
 */


@ Benchmark <EOL> fun removeAndPut ( ) : PersistentMap < IntWrapper , String >

{ <EOL> var map = persistentMapRemove ( persistentMap , keysToRemove ) <EOL> for ( key in keysToRemove ) { <EOL> map = map . put ( key , "<STR_LIT>" ) <EOL> } <EOL> return map <EOL> }

/**
 * Removes `keysToRemove.size` entries of the [persistentMap] and
 * then puts `keysToRemove.size` new entries.
 *
 * Measures mean time and memory spent per (roughly one) `remove` and `put` operations.
 *
 * Expected time: [Remove.remove] + [putAfterRemove]
 * Expected memory: [Remove.remove] + [putAfterRemove]
 */


@ Benchmark <EOL> fun removeAndIterateKeys ( bh : Blackhole )

{ <EOL> val map = persistentMapRemove ( persistentMap , keysToRemove ) <EOL> var count = <NUM_LIT:0> <EOL> while ( count < size ) { <EOL> for ( e in map ) { <EOL> bh . consume ( e ) <EOL> if ( ++ count == size ) <EOL> break <EOL> } <EOL> } <EOL> }

/**
 * Removes `keysToRemove.size` entries of the [persistentMap] and
 * then iterates keys of the resulting map several times until iterating [size] elements.
 *
 * Measures mean time and memory spent per (roughly one) `remove` and `next` operations.
 *
 * Expected time: [Remove.remove] + [iterateKeysAfterRemove]
 * Expected memory: [Remove.remove] + [iterateKeysAfterRemove]
 */


@ Benchmark <EOL> fun putAfterRemove ( ) : PersistentMap < IntWrapper , String >

{ <EOL> var map = halfHeightPersistentMap <EOL> repeat ( size - halfHeightPersistentMap . size ) { index -> <EOL> map = map . put ( keys [ index ] , "<STR_LIT>" ) <EOL> } <EOL> return map <EOL> }

/**
 * Puts `size - halfHeightPersistentMap.size` new entries to the [Canonicalization.halfHeightPersistentMap].
 *
 * Measures mean time and memory spent per (roughly one) `put` operation.
 *
 * Expected time: [Put.put]
 * Expected memory: [Put.put]
 */


@ Benchmark <EOL> fun iterateKeysAfterRemove ( bh : Blackhole )

{ <EOL> var count = <NUM_LIT:0> <EOL> while ( count < size ) { <EOL> for ( e in halfHeightPersistentMap ) { <EOL> bh . consume ( e ) <EOL> if ( ++ count == size ) <EOL> break <EOL> } <EOL> } <EOL> }

/**
 * Iterates keys of the [Canonicalization.halfHeightPersistentMap] several times until iterating [size] elements.
 *
 * Measures mean time and memory spent per `iterate` operation.
 *
 * Expected time: [Iterate.iterateKeys] with [Iterate.size] = `halfHeightPersistentMap.size`
 * Expected memory: [Iterate.iterateKeys] with [Iterate.size] = `halfHeightPersistentMap.size`
 */


fun addOnExceptionCallback ( owner : Any , callback : ( Throwable ) -> Unit )

= synchronized ( lock ) { <EOL> enabled = true <EOL> val previousValue = callbacks . put ( owner , callback ) <EOL> check ( previousValue === null ) <EOL> unprocessedExceptions . forEach { reportException ( it ) } <EOL> unprocessedExceptions . clear ( ) <EOL> }

/**
 * Registers [callback] to be executed when an uncaught exception happens.
 * [owner] is a key by which to distinguish different callbacks.
 */


fun removeOnExceptionCallback ( owner : Any )

= synchronized ( lock ) { <EOL> if ( enabled ) { <EOL> val existingValue = callbacks . remove ( owner ) <EOL> check ( existingValue !== null ) <EOL> } <EOL> }

/**
 * Unregisters the callback associated with [owner].
 */


fun handleException ( exception : Throwable ) : Boolean

= synchronized ( lock ) { <EOL> if ( ! enabled ) return false <EOL> if ( reportException ( exception ) ) return true <EOL> unprocessedExceptions . add ( exception ) <EOL> return false <EOL> }

/**
 * Tries to handle the exception by propagating it to an interested consumer.
 * Returns `true` if the exception does not need further processing.
 *
 * Doesn't throw.
 */


private fun reportException ( exception : Throwable ) : Boolean

{ <EOL> var executedACallback = false <EOL> for ( callback in callbacks . values ) { <EOL> callback ( exception ) <EOL> executedACallback = true <EOL> } <EOL> return executedACallback <EOL> }

/**
 * Try to report [exception] to the existing callbacks.
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun Char . isDefined ( ) : Boolean

= Character . isDefined ( this )

/**
 * Returns `true` if this character (Unicode code point) is defined in Unicode.
 *
 * A character is considered to be defined in Unicode if its [category] is not [CharCategory.UNASSIGNED].
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun Char . isLetter ( ) : Boolean

= Character . isLetter ( this )

/**
 * Returns `true` if this character is a letter.
 *
 * A character is considered to be a letter if its [category] is [CharCategory.UPPERCASE_LETTER],
 * [CharCategory.LOWERCASE_LETTER], [CharCategory.TITLECASE_LETTER], [CharCategory.MODIFIER_LETTER], or [CharCategory.OTHER_LETTER].
 *
 * @sample samples.text.Chars.isLetter
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun Char . isLetterOrDigit ( ) : Boolean

= Character . isLetterOrDigit ( this )

/**
 * Returns `true` if this character is a letter or digit.
 *
 * @see isLetter
 * @see isDigit
 *
 * @sample samples.text.Chars.isLetterOrDigit
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun Char . isDigit ( ) : Boolean

= Character . isDigit ( this )

/**
 * Returns `true` if this character is a digit.
 *
 * A character is considered to be a digit if its [category] is [CharCategory.DECIMAL_DIGIT_NUMBER].
 *
 * @sample samples.text.Chars.isDigit
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun Char . isIdentifierIgnorable ( ) : Boolean

= Character . isIdentifierIgnorable ( this )

/**
 * Returns `true` if this character (Unicode code point) should be regarded as an ignorable
 * character in a Java identifier or a Unicode identifier.
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun Char . isISOControl ( ) : Boolean

= Character . isISOControl ( this )

/**
 * Returns `true` if this character is an ISO control character.
 *
 * A character is considered to be an ISO control character if its [category] is [CharCategory.CONTROL],
 * meaning the Char is in the range `'\u0000'..'\u001F'` or in the range `'\u007F'..'\u009F'`.
 *
 * @sample samples.text.Chars.isISOControl
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun Char . isJavaIdentifierPart ( ) : Boolean

= Character . isJavaIdentifierPart ( this )

/**
 * Returns `true` if this character (Unicode code point) may be part of a Java identifier as other than the first character.
 * @sample samples.text.Chars.isJavaIdentifierPart
 */


@ kotlin . internal . InlineOnly <EOL> public inline fun Char . isJavaIdentifierStart ( ) : Boolean

= Character . isJavaIdentifierStart ( this )

/**
 * Returns `true` if this character is permissible as the first character in a Java identifier.
 * @sample samples.text.Chars.isJavaIdentifierStart
 */


public actual fun Char . isWhitespace ( ) : Boolean

= Character . isWhitespace ( this ) || Character . isSpaceChar ( this )

/**
 * Determines whether a character is whitespace.
 *
 * A character is considered whitespace if either its Unicode [category][Char.category]
 * is one of [CharCategory.SPACE_SEPARATOR], [CharCategory.LINE_SEPARATOR], [CharCategory.PARAGRAPH_SEPARATOR],
 * or it is a [CharCategory.CONTROL] character in range `U+0009..U+000D` or `U+001C..U+001F`.
 *
 * Returns `true` if the character is whitespace.
 *
 * @sample samples.text.Chars.isWhitespace
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun Char . isUpperCase ( ) : Boolean

= Character . isUpperCase ( this )

/**
 * Returns `true` if this character is upper case.
 *
 * A character is considered to be an upper case character if its [category] is [CharCategory.UPPERCASE_LETTER],
 * or it has contributory property `Other_Uppercase` as defined by the Unicode Standard.
 *
 * @sample samples.text.Chars.isUpperCase
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun Char . isLowerCase ( ) : Boolean

= Character . isLowerCase ( this )

/**
 * Returns `true` if this character is lower case.
 *
 * A character is considered to be a lower case character if its [category] is [CharCategory.LOWERCASE_LETTER],
 * or it has contributory property `Other_Lowercase` as defined by the Unicode Standard.
 *
 * @sample samples.text.Chars.isLowerCase
 */


@ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> @ DeprecatedSinceKotlin ( warningSince = "<STR_LIT:1.5>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun Char . toUpperCase ( ) : Char

= uppercaseChar ( )

/**
 * Converts this character to upper case using Unicode mapping rules of the invariant locale.
 */


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

= Character . toUpperCase ( this )

/**
 * Converts this character to upper case using Unicode mapping rules of the invariant locale.
 *
 * This function performs one-to-one character mapping.
 * To support one-to-many character mapping use the [uppercase] function.
 * If this character has no mapping equivalent, the character itself is returned.
 *
 * @sample samples.text.Chars.uppercase
 */


@ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> @ DeprecatedSinceKotlin ( warningSince = "<STR_LIT:1.5>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public actual inline fun Char . toLowerCase ( ) : Char

= lowercaseChar ( )

/**
 * Converts this character to lower case using Unicode mapping rules of the invariant locale.
 */


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

= Character . toLowerCase ( this )

/**
 * Converts this character to lower case using Unicode mapping rules of the invariant locale.
 *
 * This function performs one-to-one character mapping.
 * To support one-to-many character mapping use the [lowercase] function.
 * If this character has no mapping equivalent, the character itself is returned.
 *
 * @sample samples.text.Chars.lowercase
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun Char . isTitleCase ( ) : Boolean

= Character . isTitleCase ( this )

/**
 * Returns `true` if this character is a title case letter.
 *
 * A character is considered to be a title case letter if its [category] is [CharCategory.TITLECASE_LETTER].
 *
 * @sample samples.text.Chars.isTitleCase
 */


@ Deprecated ( "<STR_LIT>" , ReplaceWith ( "<STR_LIT>" ) ) <EOL> @ DeprecatedSinceKotlin ( warningSince = "<STR_LIT:1.5>" ) <EOL> @ kotlin . internal . InlineOnly <EOL> public inline fun Char . toTitleCase ( ) : Char

= titlecaseChar ( )

/**
 * Converts this character to title case using Unicode mapping rules of the invariant locale.
 *
 * @see Character.toTitleCase
 */


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

= Character . toTitleCase ( this )

/**
 * Converts this character to title case using Unicode mapping rules of the invariant locale.
 *
 * This function performs one-to-one character mapping.
 * To support one-to-many character mapping use the [titlecase] function.
 * If this character has no mapping equivalent, the result of calling [uppercaseChar] is returned.
 *
 * @sample samples.text.Chars.titlecase
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun Char . isHighSurrogate ( ) : Boolean

= Character . isHighSurrogate ( this )

/**
 * Returns `true` if this character is a Unicode high-surrogate code unit (also known as leading-surrogate code unit).
 */


@ kotlin . internal . InlineOnly <EOL> public actual inline fun Char . isLowSurrogate ( ) : Boolean

= Character . isLowSurrogate ( this )

/**
 * Returns `true` if this character is a Unicode low-surrogate code unit (also known as trailing-surrogate code unit).
 */


@ PublishedApi <EOL> internal actual fun checkRadix ( radix : Int ) : Int

{ <EOL> if ( radix !in Character . MIN_RADIX .. Character . MAX_RADIX ) { <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } <EOL> return radix <EOL> }

/**
 * Checks whether the given [radix] is valid radix for string to number and number to string conversion.
 */


{ <EOL> visualizeFSDDWavFiles ( ) <EOL> val ( train , test ) = freeSpokenDigits ( ) <EOL> smallSoundNet . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> it . fit ( dataset = train , validationRate = <NUM_LIT> , epochs = EPOCHS , trainBatchSize = TRAINING_BATCH_SIZE , validationBatchSize = TEST_BATCH_SIZE ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example demonstrates model activations and Conv1D filters visualization.
 * Additionally, we present the visualization of sound files as the plots of the sound data.
 *
 * Model is trained on Free Spoken Digits Dataset.
 */


private fun visualizeFSDDWavFiles ( personName : String = "<STR_LIT>" , samples : Int = <NUM_LIT:5> )

{ <EOL> val fssd = freeSpokenDigitDatasetPath ( ) <EOL> val wavFiles = File ( fssd ) . listFiles ( ) ? : arrayOf ( ) <EOL> val grouped = wavFiles <EOL> . filter { it . name . split ( "<STR_LIT:_>" ) [ <NUM_LIT:1> ] == personName } <EOL> . groupBy { it . name . split ( "<STR_LIT:_>" ) [ <NUM_LIT:0> ] } <EOL> . mapValues { it . value . sorted ( ) } <EOL> val plots = listOf ( grouped [ "<STR_LIT:0>" ] ! ! . take ( samples ) , grouped [ "<STR_LIT:3>" ] ! ! . take ( samples ) , grouped [ "<STR_LIT:6>" ] ! ! . take ( samples ) , grouped [ "<STR_LIT>" ] ! ! . take ( samples ) ) . transpose ( ) . flatten ( ) <EOL> . map ( :: WavFile ) <EOL> . map { soundPlot ( it , beginDrop = <NUM_LIT> ) } <EOL> columnPlot ( plots , <NUM_LIT:4> , <NUM_LIT> ) . show ( ) <EOL> }

/** Create visualization plots of input sound files for selected data from Free Spoken Digits Dataset */


private fun < T > List < List < T > > . transpose ( ) : List < List < T > >

{ <EOL> val size = getOrNull ( <NUM_LIT:0> ) ? . size ? : <NUM_LIT:0> <EOL> require ( all { it . size == size } ) { "<STR_LIT>" } <EOL> return List ( size ) { x -> <EOL> List ( this . size ) { y -> <EOL> this [ y ] [ x ] <EOL> } <EOL> } <EOL> }

/** Transpose list of lists when every element of list is a list of equal length */


{ <EOL> val ( _ , test ) = fashionMnist ( ) <EOL> val jsonConfigFile = getJSONConfigFile ( ) <EOL> val model = Sequential . loadModelConfiguration ( jsonConfigFile ) <EOL> model . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . logSummary ( ) <EOL> val hdfFile = getWeightsFile ( ) <EOL> it . loadWeights ( hdfFile ) <EOL> val accuracy = it . evaluate ( dataset = test , batchSize = <NUM_LIT:100> ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example demonstrates the inference concept:
 * - Weights are loaded from .h5 file, configuration is loaded from .json file.
 * - Model is evaluated after loading to obtain accuracy value.
 * - No additional training.
 * - No new layers are added.
 *
 * NOTE: Model and weights are resources in `examples` module.
 */


= loadModelWithWeightsAndEvaluate ( )


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

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


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

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


fun getTypesForFiles ( files : Collection < File > ) : Set < String >

{ <EOL> val typesFromFiles = HashSet < String > ( files . size ) <EOL> for ( file in files ) { <EOL> sourceCache [ file . toURI ( ) ] ? . declaredTypes ? . let { <EOL> typesFromFiles . addAll ( it ) <EOL> } <EOL> } <EOL> return typesFromFiles <EOL> }

/** Returns all types defined in these files. */


internal fun getStructure ( sourceFile : File )

= sourceCache [ sourceFile . toURI ( ) ]


fun getAllImpactedTypes ( changes : Changes ) : MutableSet < String >

{ <EOL> fun findImpactedTypes ( changedType : String , transitiveDeps : MutableSet < String > , nonTransitiveDeps : MutableSet < String > ) { <EOL> dependencyCache [ changedType ] ? . let { impactedSources -> <EOL> impactedSources . forEach { <EOL> transitiveDeps . addAll ( sourceCache . getValue ( it ) . declaredTypes ) <EOL> } <EOL> } <EOL> nonTransitiveCache [ changedType ] ? . let { impactedSources -> <EOL> impactedSources . forEach { <EOL> nonTransitiveDeps . addAll ( sourceCache . getValue ( it ) . declaredTypes ) <EOL> } <EOL> } <EOL> } <EOL> val allDirtyTypes = mutableSetOf < String > ( ) <EOL> var currentDirtyTypes = getTypesForFiles ( changes . sourceChanges ) . toMutableSet ( ) <EOL> changes . dirtyFqNamesFromClasspath . forEach { classpathChange -> <EOL> findImpactedTypes ( classpathChange , currentDirtyTypes , allDirtyTypes ) <EOL> } <EOL> while ( currentDirtyTypes . isNotEmpty ( ) ) { <EOL> val nextRound = mutableSetOf < String > ( ) <EOL> for ( dirtyType in currentDirtyTypes ) { <EOL> allDirtyTypes . add ( dirtyType ) <EOL> findImpactedTypes ( dirtyType , nextRound , allDirtyTypes ) <EOL> } <EOL> currentDirtyTypes = nextRound . filterTo ( HashSet ( ) ) { it !in allDirtyTypes } <EOL> } <EOL> return allDirtyTypes <EOL> }

/**
 * Compute the list of types that are impacted by source changes i.e [Changes.sourceChanges] and [Changes.dirtyFqNamesFromClasspath]
 * i.e classpath changes. The search is transitive, if a file is impacted, all files referencing types defined in that file are
 * also considered impacted. Only original sources and generated sources are reported as impacted (final result does not contain
 * classpath types).
 */


fun getSourceFileDefinedTypesCount ( ) : Int

{ <EOL> return sourceCache . values . sumOf { <EOL> val structure = it as? SourceFileStructure ? : return@sumOf <NUM_LIT:0> <EOL> if ( structure . declaredTypes . size == <NUM_LIT:1> && structure . declaredTypes . single ( ) == "<STR_LIT>" ) { <EOL> return@sumOf <NUM_LIT:0> <EOL> } <EOL> return@sumOf structure . declaredTypes . size <EOL> } <EOL> }

/** Returns total number of declared types in .java source files that were processed. */


public fun createOfflineInstrumenter ( ) : OfflineInstrumenter

{ <EOL> return OfflineInstrumenterImpl ( false ) <EOL> }

/**
 * Create instance to instrument already compiled class-files.
 *
 * @return instrumenter for offline instrumentation.
 */


public fun resnet50Light ( imageSize : Long = <NUM_LIT> , numberOfClasses : Int = <NUM_LIT:10> , numberOfInputChannels : Long = <NUM_LIT:3> , lastLayerActivation : Activations = Activations . Linear , ) : Functional

{ <EOL> val stackFn = fun ( pointer : Layer ) : Layer { <EOL> var x = pointer <EOL> x = stack1 ( x , <NUM_LIT> , <NUM_LIT:3> , stride1 = <NUM_LIT:1> , name = "<STR_LIT>" ) <EOL> x = stack1 ( x , <NUM_LIT> , <NUM_LIT:4> , name = "<STR_LIT>" ) <EOL> x = stack1 ( x , <NUM_LIT> , <NUM_LIT:6> , name = "<STR_LIT>" ) <EOL> return stack1 ( x , <NUM_LIT> , <NUM_LIT:3> , name = "<STR_LIT>" ) <EOL> } <EOL> return resnetLight ( stackFn = stackFn , imageSize = imageSize , numberOfClasses = numberOfClasses , numberOfInputChannels = numberOfInputChannels , lastLayerActivation = lastLayerActivation , preact = false ) <EOL> }

/**
 * Instantiates the ResNet50 architecture without BatchNorm layers as a Functional model.
 *
 * @param [imageSize] Height = width of image.
 * @param [numberOfClasses] Number of neurons in the last layer (usually, Dense layer).
 * @param [lastLayerActivation] Activation for last layer (usually, Dense layer).
 *
 * @see
 * Deep Residual Learning for Image Recognition.
 * @see
 * High-Performance Large-Scale Image Recognition Without Normalization
 */


public fun resnet101Light ( imageSize : Long = <NUM_LIT> , numberOfClasses : Int = <NUM_LIT:10> , numberOfInputChannels : Long = <NUM_LIT:3> , lastLayerActivation : Activations = Activations . Linear , ) : Functional

{ <EOL> val stackFn = fun ( pointer : Layer ) : Layer { <EOL> var x = pointer <EOL> x = stack1 ( x , <NUM_LIT> , <NUM_LIT:3> , stride1 = <NUM_LIT:1> , name = "<STR_LIT>" ) <EOL> x = stack1 ( x , <NUM_LIT> , <NUM_LIT:4> , name = "<STR_LIT>" ) <EOL> x = stack1 ( x , <NUM_LIT> , <NUM_LIT:23> , name = "<STR_LIT>" ) <EOL> return stack1 ( x , <NUM_LIT> , <NUM_LIT:3> , name = "<STR_LIT>" ) <EOL> } <EOL> return resnetLight ( stackFn = stackFn , imageSize = imageSize , numberOfClasses = numberOfClasses , numberOfInputChannels = numberOfInputChannels , lastLayerActivation = lastLayerActivation , preact = false ) <EOL> }

/**
 * Instantiates the ResNet101 architecture without BatchNorm layers as a Functional model.
 *
 * @param [imageSize] Height = width of image.
 * @param [numberOfClasses] Number of neurons in the last layer (usually, Dense layer).
 * @param [lastLayerActivation] Activation for last layer (usually, Dense layer).
 *
 * @see
 * Deep Residual Learning for Image Recognition.
 * @see
 * High-Performance Large-Scale Image Recognition Without Normalization
 */


public fun resnet152Light ( imageSize : Long = <NUM_LIT> , numberOfClasses : Int = <NUM_LIT:10> , numberOfInputChannels : Long = <NUM_LIT:3> , lastLayerActivation : Activations = Activations . Linear , ) : Functional

{ <EOL> val stackFn = fun ( pointer : Layer ) : Layer { <EOL> var x = pointer <EOL> x = stack1 ( x , <NUM_LIT> , <NUM_LIT:3> , stride1 = <NUM_LIT:1> , name = "<STR_LIT>" ) <EOL> x = stack1 ( x , <NUM_LIT> , <NUM_LIT:8> , name = "<STR_LIT>" ) <EOL> x = stack1 ( x , <NUM_LIT> , <NUM_LIT> , name = "<STR_LIT>" ) <EOL> return stack1 ( x , <NUM_LIT> , <NUM_LIT:3> , name = "<STR_LIT>" ) <EOL> } <EOL> return resnetLight ( stackFn = stackFn , imageSize = imageSize , numberOfClasses = numberOfClasses , numberOfInputChannels = numberOfInputChannels , lastLayerActivation = lastLayerActivation , preact = false ) <EOL> }

/**
 * Instantiates the ResNet152 architecture without BatchNorm layers as a Functional model.
 *
 * @param [imageSize] Height = width of image.
 * @param [numberOfClasses] Number of neurons in the last layer (usually, Dense layer).
 * @param [lastLayerActivation] Activation for last layer (usually, Dense layer).
 *
 * @see
 * Deep Residual Learning for Image Recognition.
 * @see
 * High-Performance Large-Scale Image Recognition Without Normalization
 */


public fun resnet50v2Light ( imageSize : Long = <NUM_LIT> , numberOfClasses : Int = <NUM_LIT:10> , numberOfInputChannels : Long = <NUM_LIT:3> , lastLayerActivation : Activations = Activations . Linear , ) : Functional

{ <EOL> val stackFn = fun ( pointer : Layer ) : Layer { <EOL> var x = pointer <EOL> x = stack2 ( x , <NUM_LIT> , <NUM_LIT:3> , name = "<STR_LIT>" ) <EOL> x = stack2 ( x , <NUM_LIT> , <NUM_LIT:4> , name = "<STR_LIT>" ) <EOL> x = stack2 ( x , <NUM_LIT> , <NUM_LIT:6> , name = "<STR_LIT>" ) <EOL> return stack2 ( x , <NUM_LIT> , <NUM_LIT:3> , stride1 = <NUM_LIT:1> , name = "<STR_LIT>" ) <EOL> } <EOL> return resnetLight ( stackFn = stackFn , imageSize = imageSize , numberOfClasses = numberOfClasses , numberOfInputChannels = numberOfInputChannels , lastLayerActivation = lastLayerActivation , preact = true ) <EOL> }

/**
 * Instantiates the ResNet50V2 architecture without BatchNorm layers as a Functional model.
 *
 * @param [imageSize] Height = width of image.
 * @param [numberOfClasses] Number of neurons in the last layer (usually, Dense layer).
 * @param [lastLayerActivation] Activation for last layer (usually, Dense layer).
 *
 * @see
 * Deep Residual Learning for Image Recognition.
 * @see
 * High-Performance Large-Scale Image Recognition Without Normalization
 */


public fun resnet101v2Light ( imageSize : Long = <NUM_LIT> , numberOfClasses : Int = <NUM_LIT:10> , numberOfInputChannels : Long = <NUM_LIT:3> , lastLayerActivation : Activations = Activations . Linear , ) : Functional

{ <EOL> val stackFn = fun ( pointer : Layer ) : Layer { <EOL> var x = pointer <EOL> x = stack2 ( x , <NUM_LIT> , <NUM_LIT:3> , name = "<STR_LIT>" ) <EOL> x = stack2 ( x , <NUM_LIT> , <NUM_LIT:4> , name = "<STR_LIT>" ) <EOL> x = stack2 ( x , <NUM_LIT> , <NUM_LIT:23> , name = "<STR_LIT>" ) <EOL> return stack2 ( x , <NUM_LIT> , <NUM_LIT:3> , stride1 = <NUM_LIT:1> , name = "<STR_LIT>" ) <EOL> } <EOL> return resnetLight ( stackFn = stackFn , imageSize = imageSize , numberOfClasses = numberOfClasses , numberOfInputChannels = numberOfInputChannels , lastLayerActivation = lastLayerActivation , preact = true ) <EOL> }

/**
 * Instantiates the ResNet101V2 architecture without BatchNorm layers as a Functional model.
 *
 * @param [imageSize] Height = width of image.
 * @param [numberOfClasses] Number of neurons in the last layer (usually, Dense layer).
 * @param [lastLayerActivation] Activation for last layer (usually, Dense layer).
 *
 * @see
 * Deep Residual Learning for Image Recognition.
 * @see
 * High-Performance Large-Scale Image Recognition Without Normalization
 */


public fun resnet152v2Light ( imageSize : Long = <NUM_LIT> , numberOfClasses : Int = <NUM_LIT:10> , numberOfInputChannels : Long = <NUM_LIT:3> , lastLayerActivation : Activations = Activations . Linear , ) : Functional

{ <EOL> val stackFn = fun ( pointer : Layer ) : Layer { <EOL> var x = pointer <EOL> x = stack2 ( x , <NUM_LIT> , <NUM_LIT:3> , name = "<STR_LIT>" ) <EOL> x = stack2 ( x , <NUM_LIT> , <NUM_LIT:8> , name = "<STR_LIT>" ) <EOL> x = stack2 ( x , <NUM_LIT> , <NUM_LIT> , name = "<STR_LIT>" ) <EOL> return stack2 ( x , <NUM_LIT> , <NUM_LIT:3> , stride1 = <NUM_LIT:1> , name = "<STR_LIT>" ) <EOL> } <EOL> return resnetLight ( stackFn = stackFn , imageSize = imageSize , numberOfClasses = numberOfClasses , numberOfInputChannels = numberOfInputChannels , lastLayerActivation = lastLayerActivation , preact = true ) <EOL> }

/**
 * Instantiates the ResNet152V2 architecture without BatchNorm layers as a Functional model.
 *
 * @param [imageSize] Height = width of image.
 * @param [numberOfClasses] Number of neurons in the last layer (usually, Dense layer).
 * @param [lastLayerActivation] Activation for last layer (usually, Dense layer).
 *
 * @see
 * Deep Residual Learning for Image Recognition.
 * @see
 * High-Performance Large-Scale Image Recognition Without Normalization
 */


private fun stack1 ( pointer : Layer , filters : Int , blocks : Int , stride1 : Int = <NUM_LIT:2> , name : String ) : Layer

{ <EOL> var x = pointer <EOL> x = block1 ( x , filters , stride = stride1 , name = name + "<STR_LIT>" ) <EOL> for ( i in <NUM_LIT:2> until blocks + <NUM_LIT:1> ) { <EOL> x = block1 ( x , filters , convShortcut = false , name = name + "<STR_LIT>" + i , ) <EOL> } <EOL> return x <EOL> }

/**
 * A set of stacked residual blocks.
 *
 * @param [pointer]: input tensor.
 * @param [filters]: filters of the bottleneck layer in a block.
 * @param [blocks]: blocks in the stacked blocks.
 * @param [stride1]: default 2, stride of the first layer in the first block.
 * @param [name]: string, stack label.
 */


private fun stack2 ( pointer : Layer , filters : Int , blocks : Int , stride1 : Int = <NUM_LIT:2> , name : String ) : Layer

{ <EOL> var x = pointer <EOL> x = block2 ( x , filters , convShortcut = true , name = name + "<STR_LIT>" ) <EOL> for ( i in <NUM_LIT:2> until blocks ) { <EOL> x = block2 ( x , filters , name = name + "<STR_LIT>" + i ) <EOL> } <EOL> x = block2 ( x , filters , stride = stride1 , name = name + "<STR_LIT>" + blocks ) <EOL> return x <EOL> }


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

{ <EOL> matchResult . saveState ( ) <EOL> return tryToMatch ( startIndex , testString , matchResult ) . also { if ( it < <NUM_LIT:0> ) matchResult . rollbackState ( ) } <EOL> }

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


@ ObsoleteDescriptorBasedAPI <EOL> fun IrDeclaration . isFromInteropLibraryByDescriptor ( )

= descriptor . isFromInteropLibrary ( )

/**
 * This function should be equivalent to `IrDeclaration.isFromInteropLibrary` from `backend.native`, but in fact it is not for declarations
 * from Fir modules.
 *
 * This should be fixed in the future.
 */


private fun compressedModules ( deserializers : Collection < IrModuleDeserializer > ) : Map < ResolvedDependencyId , ResolvedDependency >

{ <EOL> val compressedModules : MutableMap < ResolvedDependencyId , ResolvedDependency > = mergedModules ( deserializers ) <EOL> var platformLibrariesVersion : ResolvedDependencyVersion ? = null <EOL> val platformLibraries : MutableList < ResolvedDependency > = mutableListOf ( ) <EOL> val outgoingDependencyIds : MutableSet < ResolvedDependencyId > = mutableSetOf ( ) <EOL> for ( ( moduleId , module ) in compressedModules ) { <EOL> if ( moduleId . isKonanPlatformLibrary ) { <EOL> if ( sourceCodeModuleId !in module . requestedVersionsByIncomingDependencies ) { <EOL> continue <EOL> } <EOL> platformLibrariesVersion = when ( platformLibrariesVersion ) { <EOL> null , module . selectedVersion -> module . selectedVersion <EOL> else -> { <EOL> return compressedModules <EOL> } <EOL> } <EOL> platformLibraries += module <EOL> } else { <EOL> module . requestedVersionsByIncomingDependencies . keys . forEach { incomingDependencyId -> <EOL> if ( incomingDependencyId . isKonanPlatformLibrary ) { <EOL> outgoingDependencyIds += moduleId <EOL> } <EOL> } <EOL> } <EOL> } <EOL> if ( platformLibraries . isNotEmpty ( ) ) { <EOL> platformLibraries . forEach { it . visibleAsFirstLevelDependency = false } <EOL> val compressedModuleId = ResolvedDependencyId ( "<STR_LIT>" ) <EOL> val compressedModule = ResolvedDependency ( id = compressedModuleId , selectedVersion = platformLibrariesVersion ! ! , requestedVersionsByIncomingDependencies = mutableMapOf ( sourceCodeModuleId to platformLibrariesVersion ) , artifactPaths = mutableSetOf ( ) ) <EOL> outgoingDependencyIds . forEach { outgoingDependencyId -> <EOL> val outgoingDependency = compressedModules . getValue ( outgoingDependencyId ) <EOL> outgoingDependency . requestedVersionsByIncomingDependencies [ compressedModuleId ] = compressedModule . selectedVersion <EOL> } <EOL> compressedModules [ compressedModuleId ] = compressedModule <EOL> } <EOL> return compressedModules <EOL> }

/**
 * This is an optimization to avoid displaying 100+ Kotlin/Native platform libraries to the user.
 * Instead, lets compress them into a single row and avoid excessive output.
 */


fun readAbiInfo ( library : File , vararg filters : AbiReadingFilter ) : LibraryAbi

= readAbiInfo ( library , filters . asList ( ) )

/**
 * Inspect the KLIB at [library]. The KLIB can be either in a directory (unzipped) or in a file (zipped) form.
 *
 * @param library The file representing the KLIB location.
 * @param filters The filters that are applied while reading the KLIB to exclude/ignore certain entities.
 */


fun readAbiInfo ( library : File , filters : List < AbiReadingFilter > ) : LibraryAbi

= LibraryAbiReaderImpl ( library , filters ) . readAbi ( )


fun isPackageExcluded ( packageName : AbiCompoundName ) : Boolean

= false

/** Tests for each package being read by the ABI reader if it should be excluded/ignored. */


fun isDeclarationExcluded ( declaration : AbiDeclaration ) : Boolean

= false

/** Tests for each declaration being read by the ABI reader if it should be excluded/ignored */


@ Test <EOL> fun verifySpecialIsRuleIsApplied ( )

{ <EOL> val writerPlugin = TestOutputWriterPlugin ( ) <EOL> testInline ( """<STR_LIT>""" . trimIndent ( ) , configuration , cleanupOutput = false , pluginOverrides = listOf ( writerPlugin , JavadocPlugin ( ) ) ) { <EOL> renderingStage = { _ , _ -> <EOL> val html = writerPlugin . writer . contents . getValue ( "<STR_LIT>" ) . let { Jsoup . parse ( it ) } <EOL> val props = html <EOL> . select ( "<STR_LIT>" ) <EOL> . select ( "<STR_LIT>" ) <EOL> . select ( "<STR_LIT>" ) <EOL> . map { it . text ( ) } <EOL> . toSet ( ) <EOL> assertTrue ( setOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , ) == props || setOf ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , ) == props ) <EOL> val descriptionLinks = html <EOL> . select ( "<STR_LIT>" ) <EOL> . select ( "<STR_LIT>" ) <EOL> . select ( "<STR_LIT:a>" ) <EOL> . eachAttr ( "<STR_LIT>" ) <EOL> . map { a -> a . takeLastWhile { it != '<CHAR_LIT>' } } <EOL> assertEquals ( setOf ( "<STR_LIT>" , "<STR_LIT>" , ) , descriptionLinks . toSet ( ) ) <EOL> assertEquals ( <NUM_LIT:1> , html . select ( "<STR_LIT>" ) . size ) <EOL> assertEquals ( <NUM_LIT:0> , html . select ( "<STR_LIT>" ) . size ) <EOL> } <EOL> } <EOL> }

/**
 * This is a quick sanity check for the AccessorMethodNamingTest
 */


fun afterInvalidation ( modules : Set < KtModule > )

/**
 * [afterInvalidation] is published when sessions for the given [modules] have been invalidated. Because the sessions are already
 * invalid, the event carries their [KtModule][org.jetbrains.kotlin.analysis.project.structure.KtModule]s.
 *
 * @see LLFirSessionInvalidationTopics
 */


fun afterGlobalInvalidation ( )

/**
 * [afterGlobalInvalidation] is published when all sessions may have been invalidated. The event doesn't guarantee that all sessions
 * have been invalidated, but e.g. caches should be cleared as if this was the case. This event is published when the invalidated
 * sessions cannot be easily enumerated.
 *
 * @see LLFirSessionInvalidationTopics
 */


internal fun ExpectActualMatchingContext < * > . matchSingleExpectAgainstPotentialActuals ( expectMember : DeclarationSymbolMarker , actualMembers : List < DeclarationSymbolMarker > , substitutor : TypeSubstitutorMarker ? , expectClassSymbol : RegularClassSymbolMarker ? , actualClassSymbol : RegularClassSymbolMarker ? , mismatchedMembers : MutableList < Pair < DeclarationSymbolMarker , Map < ExpectActualMatchingCompatibility . Mismatch , List < DeclarationSymbolMarker ? > > > > ? , ) : List < DeclarationSymbolMarker >

{ <EOL> val mapping = actualMembers . keysToMap { actualMember -> <EOL> when ( expectMember ) { <EOL> is CallableSymbolMarker -> getCallablesCompatibility ( expectMember , actualMember as CallableSymbolMarker , substitutor , expectClassSymbol , actualClassSymbol ) <EOL> is RegularClassSymbolMarker -> { <EOL> matchClassifiers ( expectMember , actualMember as ClassLikeSymbolMarker , this ) <EOL> } <EOL> else -> error ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> val matched = ArrayList < DeclarationSymbolMarker > ( ) <EOL> val mismatched = HashMap < ExpectActualMatchingCompatibility . Mismatch , MutableList < DeclarationSymbolMarker > > ( ) <EOL> for ( ( actualMember , compatibility ) in mapping ) { <EOL> when ( compatibility ) { <EOL> ExpectActualMatchingCompatibility . MatchedSuccessfully -> { <EOL> onMatchedMembers ( expectMember , actualMember , expectClassSymbol , actualClassSymbol ) <EOL> matched . add ( actualMember ) <EOL> } <EOL> is ExpectActualMatchingCompatibility . Mismatch -> mismatched . getOrPut ( compatibility ) { SmartList ( ) } . add ( actualMember ) <EOL> } <EOL> } <EOL> if ( matched . isNotEmpty ( ) ) { <EOL> return matched <EOL> } <EOL> mismatchedMembers ? . add ( expectMember to mismatched ) <EOL> onMismatchedMembersFromClassScope ( expectMember , mismatched , expectClassSymbol , actualClassSymbol ) <EOL> return emptyList ( ) <EOL> }

/**
 * Besides returning the matched declarations, the function has an additional side effects:
 * - It adds mismatched members to `mismatchedMembers`
 * - It calls `onMatchedMembers` and `onMismatchedMembersFromClassScope` callbacks
 */


fun FileLoweringPass . runOnFileInOrder ( irFile : IrFile )

{ <EOL> irFile . acceptVoid ( object : IrElementVisitorVoid { <EOL> override fun visitElement ( element : IrElement ) { <EOL> element . acceptChildrenVoid ( this ) <EOL> } <EOL> override fun visitFile ( declaration : IrFile ) { <EOL> lower ( declaration ) <EOL> declaration . acceptChildrenVoid ( this ) <EOL> } <EOL> } ) <EOL> }

/**
 * Copy of [runOnFilePostfix], but this implementation first lowers declaration, then its children.
 */


public fun KtType . approximateToSuperPublicDenotable ( approximateLocalTypes : Boolean ) : KtType ?

= <EOL> withValidityAssertion { analysisSession . typeProvider . approximateToSuperPublicDenotableType ( this , approximateLocalTypes ) }

/**
 * Approximates [KtType] with a supertype which can be rendered in a source code
 *
 * Return `null` if the type do not need approximation and can be rendered as is
 * Otherwise, for type `T` return type `S` such `T <: S` and `T` and every type argument is denotable
 */


public fun KtType . approximateToSubPublicDenotable ( approximateLocalTypes : Boolean ) : KtType ?

= <EOL> withValidityAssertion { analysisSession . typeProvider . approximateToSubPublicDenotableType ( this , approximateLocalTypes ) }

/**
 * Approximates [KtType] with a subtype which can be rendered in a source code
 *
 * Return `null` if the type do not need approximation and can be rendered as is
 * Otherwise, for type `T` return type `S` such `S <: T` and `T` and every type argument is denotable
 */


public fun KtType . getEnhancedType ( ) : KtType ?

= withValidityAssertion { analysisSession . typeProvider . getEnhancedType ( this ) }

/**
 * Returns a warning-level enhanced type for [KtType] if it is present. Otherwise, returns `null`.
 */


public fun commonSuperType ( types : Collection < KtType > ) : KtType ?

= <EOL> withValidityAssertion { analysisSession . typeProvider . commonSuperType ( types ) }

/**
 * Computes the common super type of the given collection of [KtType].
 *
 * If the collection is empty, it returns `null`.
 */


public fun KtTypeReference . getKtType ( ) : KtType

= <EOL> withValidityAssertion { analysisSession . typeProvider . getKtType ( this ) }

/**
 * Resolve [KtTypeReference] and return corresponding [KtType] if resolved.
 *
 * This may raise an exception if the resolution ends up with an unexpected kind.
 */


public fun KtDoubleColonExpression . getReceiverKtType ( ) : KtType ?

= <EOL> withValidityAssertion { analysisSession . typeProvider . getReceiverTypeForDoubleColonExpression ( this ) }

/**
 * Resolve [KtDoubleColonExpression] and return [KtType] of its receiver.
 *
 * Return `null` if the resolution fails or the resolved callable reference is not a reflection type.
 */


public fun KtType . hasCommonSubTypeWith ( that : KtType ) : Boolean

= <EOL> withValidityAssertion { analysisSession . typeProvider . haveCommonSubtype ( this , that ) }

/** Check whether this type is compatible with that type. If they are compatible, it means they can have a common subtype. */


public fun getImplicitReceiverTypesAtPosition ( position : KtElement ) : List < KtType >

= <EOL> withValidityAssertion { analysisSession . typeProvider . getImplicitReceiverTypesAtPosition ( position ) }

/**
 * Gets all the implicit receiver types available at the given position. The type of the outermost receiver appears at the beginning
 * of the returned list.
 */


public fun KtType . getDirectSuperTypes ( shouldApproximate : Boolean = false ) : List < KtType >

= <EOL> withValidityAssertion { analysisSession . typeProvider . getDirectSuperTypes ( this , shouldApproximate ) }

/**
 * Gets the direct super types of the given type. For example, given `MutableList<String>`, this returns `List<String>` and
 * `MutableCollection<String>`.
 *
 * Note that for flexible types, both direct super types of the upper and lower bounds are returned. If that's not desirable, please
 * first call [KtFlexibleType.upperBound] or [KtFlexibleType.lowerBound] and then call this method.
 *
 * @param shouldApproximate whether to approximate non-denotable types. For example, super type of `List<out String>` is
 * `Collection<CAPTURED out String>`. With approximation set to true, `Collection<out String>` is returned instead.
 */


public fun KtType . getAllSuperTypes ( shouldApproximate : Boolean = false ) : List < KtType >

= <EOL> withValidityAssertion { analysisSession . typeProvider . getAllSuperTypes ( this , shouldApproximate ) }

/**
 * Gets all the super types of the given type. The returned result is ordered by a BFS traversal of the class hierarchy, without any
 * duplicates.
 *
 * @param shouldApproximate see [getDirectSuperTypes]
 */


@ Suppress ( "<STR_LIT>" ) <EOL> @ Deprecated ( "<STR_LIT>" ) <EOL> public fun KtCallableSymbol . getDispatchReceiverType ( ) : KtType ?

= <EOL> withValidityAssertion { analysisSession . typeProvider . getDispatchReceiverType ( this ) }

/**
 * This function is provided for a few use-cases where it's hard to go without it.
 *
 * **Please avoid using it**; it will probably be removed in the future.
 *
 * The function is instantly deprecated, so it's not shown in the completion.
 *
 * @receiver A target callable symbol.
 * @return A dispatch receiver type for this symbol if it has any.
 */


public fun KtType . getArrayElementType ( ) : KtType ?

= <EOL> withValidityAssertion { analysisSession . typeProvider . getArrayElementType ( this ) }

/**
 * If provided [KtType] is a primitive type array or [Array], returns the type of the array's elements. Otherwise, returns null.
 */


fun < Service > loadImplementations ( service : Class < out Service > , classLoader : URLClassLoader ) : List < Service >

{ <EOL> val files = classLoader . urLs . map { url -> <EOL> try { <EOL> Paths . get ( url . toURI ( ) ) . toFile ( ) <EOL> } catch ( e : FileSystemNotFoundException ) { <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } catch ( e : UnsupportedOperationException ) { <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } <EOL> } <EOL> return loadImplementations ( service , files , classLoader ) <EOL> }

/**
 * Returns implementations for the given `service` declared in META-INF/services of the `classLoader` roots.
 *
 * Note that the behavior is radically different from what Java ServiceLoader does.
 * ServiceLoaderLite doesn't iterate over the whole ClassLoader hierarchy, it takes only the immediate roots of `classLoader`.
 * In fact, this is often the desired behavior.
 */


abstract fun isEmpty ( ) : Boolean

/**
 * Check if values of argument are empty.
 */


= :: parsedValue . isInitialized

/**
 * Check if value of argument was initialized.
 */


protected abstract fun saveValue ( stringValue : String )

/**
 * Sace value from command line.
 *
 * @param stringValue value from command line.
 */


fun setDelegatedValue ( providedValue : TResult )

{ <EOL> parsedValue = providedValue <EOL> valueOrigin = ArgParser . ValueOrigin . REDEFINED <EOL> }

/**
 * Set value of delegated property.
 */


internal fun addValue ( stringValue : String )

{ <EOL> if ( descriptor is OptionDescriptor < * , * > && ! descriptor . multiple && ! isEmpty ( ) && descriptor . delimiter == null ) { <EOL> throw ParsingException ( "<STR_LIT>" ) <EOL> } <EOL> descriptor . deprecatedWarning ? . let { <EOL> if ( isEmpty ( ) ) <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> if ( descriptor is OptionDescriptor < * , * > && descriptor . delimiter != null ) { <EOL> stringValue . split ( descriptor . delimiter ) . forEach { <EOL> saveValue ( it ) <EOL> } <EOL> } else { <EOL> saveValue ( stringValue ) <EOL> } <EOL> }

/**
 * Add parsed value from command line.
 *
 * @param stringValue value from command line.
 */


{ <EOL> if ( descriptor . defaultValueSet ) { <EOL> parsedValue = descriptor . defaultValue ! ! <EOL> valueOrigin = ArgParser . ValueOrigin . SET_DEFAULT_VALUE <EOL> } <EOL> }


{ <EOL> descriptor . fullName ? : run { descriptor . fullName = name } <EOL> }

/**
 * Provide name for CLI entity.
 *
 * @param name name for CLI entity.
 */


fun require ( request : String ) : String

{ <EOL> return resolve ( request ) ? . canonicalPath ? : error ( "<STR_LIT>" ) <EOL> }

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


internal fun resolve ( name : String , context : File = dir ) : File ?

= <EOL> if ( name . startsWith ( "<STR_LIT:/>" ) ) resolve ( name . removePrefix ( "<STR_LIT:/>" ) , File ( "<STR_LIT:/>" ) ) <EOL> else resolveAsRelative ( "<STR_LIT>" , name , context ) <EOL> ? : resolveAsRelative ( "<STR_LIT:/>" , name , context ) <EOL> ? : resolveAsRelative ( "<STR_LIT>" , name , context ) <EOL> ? : resolveInNodeModulesDir ( name , context . resolve ( NODE_MODULES ) ) <EOL> ? : context . parentFile ? . let { resolve ( name , it ) }

/**
 * Find node module according to https://nodejs.org/api/modules.html#modules_all_together
 */


fun getDefinitionClasses ( ) : Iterable < String >

/**
 * Should return a list of the FQNs of the script definition template classes to load explicitly, if any
 */


fun getDefinitionsClassPath ( ) : Iterable < File >

/**
 * Should return a classpath required for loading script definition template classes
 */


fun useDiscovery ( ) : Boolean

/**
 * if returns true, the IntelliJ will scan the classpath from [getDefinitionClasses] to discover script definition templates
 * using definition markers in the "META-INF/kotlin/script/templates/" folder
 */


fun provideDefinitions ( baseHostConfiguration : ScriptingHostConfiguration , loadedScriptDefinitions : List < ScriptDefinition > ) : Iterable < ScriptDefinition >

= loadedScriptDefinitions

/**
 * The callback to update/add/remove script definitions after loading, if needed
 */


protected open fun IrDeclarationWithVisibility . accessorParent ( parent : IrDeclarationParent , scopes : List < ScopeWithIr > )

= parent

/**
 * In case of Java `protected static`, access could be done from a public inline function in the same package,
 * or a subclass of the Java class. Both cases require an accessor, which we cannot add to a Java class.
 */


protected open fun fieldAccessorSuffix ( field : IrField , superQualifierSymbol : IrClassSymbol ? ) : String

= field . run { <EOL> if ( superQualifierSymbol != null ) { <EOL> return "<STR_LIT>" <EOL> } <EOL> return "<STR_LIT>" + if ( isStatic && visibility . isProtected ) "<STR_LIT>" + parentAsClass . syntheticAccessorToSuperSuffix ( ) else "<STR_LIT>" <EOL> }

/**
 * For both _reading_ and _writing_ field accessors, the suffix that includes some of [field]'s important properties.
 */


fun String . offsetOf ( position : CodePosition ) : Int

{ <EOL> var i = <NUM_LIT:0> <EOL> var lineCount = <NUM_LIT:0> <EOL> var offsetInLine = <NUM_LIT:0> <EOL> while ( i < length ) { <EOL> val c = this [ i ] <EOL> if ( lineCount == position . line && offsetInLine == position . offset ) { <EOL> return i <EOL> } <EOL> i ++ <EOL> offsetInLine ++ <EOL> if ( Utils . isEndOfLine ( c . code ) ) { <EOL> offsetInLine = <NUM_LIT:0> <EOL> lineCount ++ <EOL> assert ( lineCount <= position . line ) <EOL> } <EOL> } <EOL> return length <EOL> }

/**
 * Calculates an offset from the start of a text for a position,
 * defined by line and offset in that line.
 */


fun < T : Any > all ( a : KtNDArray < T > ) : Boolean

= <EOL> callFunc ( arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a ) , kClass = Boolean :: class )

/**
 * Test whether all array elements along a given axis evaluate to *true*.
 */


fun < T : Any > all ( a : KtNDArray < T > , axis : Int ) : KtNDArray < Boolean >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a , axis ) )


fun < T : Any > any ( a : KtNDArray < T > ) : Boolean

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( a ) , kClass = Boolean :: class )

/**
 * Test whether any array element along a given axis evaluates to *true*.
 */


fun < T : Any > any ( a : KtNDArray < T > , axis : Int ) : KtNDArray < Boolean >


fun < T : Any > isFinite ( x : KtNDArray < T > ) : KtNDArray < Boolean >

= <EOL> callFunc ( nameMethod = arrayOf ( "<STR_LIT>" ) , args = arrayOf ( x ) )

/**
 * Test element-wise for finiteness (not infinity or not Not a Number).
 */


fun < T : Any > isInf ( x : KtNDArray < T > ) : KtNDArray < Boolean >

/**
 * Test element-wise for positive or negative infinity.
 */


fun < T : Any > isNan ( x : KtNDArray < T > ) : KtNDArray < Boolean >

/**
 * Test element-wise for NaN and return result as a boolean array.
 */


fun < T : Any > isNegInf ( x : KtNDArray < T > ) : KtNDArray < Boolean >

/**
 * Test element-wise for negative infinity, return result as bool array.
 */


fun < T : Any > isPosInf ( x : KtNDArray < T > ) : KtNDArray < Boolean >

/**
 * Test element-wise for positive infinity, return result as bool array.
 */