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

= asSpecificImplementation ( ) . let { scope -> <EOL> scope . enter ( ) <EOL> createTestResult { <EOL> scope . start ( CoroutineStart . UNDISPATCHED , scope ) { <EOL> yield ( ) <EOL> testBody ( ) <EOL> } <EOL> var timeoutError : Throwable ? = null <EOL> var cancellationException : CancellationException ? = null <EOL> val workRunner = launch ( CoroutineName ( "<STR_LIT>" ) ) { <EOL> while ( true ) { <EOL> val executedSomething = testScheduler . tryRunNextTaskUnless { ! isActive } <EOL> if ( executedSomething ) { <EOL> yield ( ) <EOL> } else { <EOL> testScheduler . receiveDispatchEvent ( ) <EOL> } <EOL> } <EOL> } <EOL> try { <EOL> withTimeout ( timeout ) { <EOL> coroutineContext . job . invokeOnCompletion ( onCancelling = true ) { exception -> <EOL> if ( exception is TimeoutCancellationException ) { <EOL> dumpCoroutines ( ) <EOL> val activeChildren = scope . children . filter ( Job :: isActive ) . toList ( ) <EOL> val completionCause = if ( scope . isCancelled ) scope . tryGetCompletionCause ( ) else null <EOL> var message = "<STR_LIT>" <EOL> if ( completionCause == null ) <EOL> message += "<STR_LIT>" <EOL> if ( activeChildren . isNotEmpty ( ) ) <EOL> message += "<STR_LIT>" <EOL> if ( completionCause != null && activeChildren . isEmpty ( ) ) { <EOL> message += if ( scope . isCompleted ) <EOL> "<STR_LIT>" <EOL> else <EOL> "<STR_LIT>" <EOL> } <EOL> timeoutError = UncompletedCoroutinesError ( message ) <EOL> cancellationException = CancellationException ( "<STR_LIT>" ) <EOL> ( scope as Job ) . cancel ( cancellationException ! ! ) <EOL> } <EOL> } <EOL> scope . join ( ) <EOL> workRunner . cancelAndJoin ( ) <EOL> } <EOL> } catch ( _ : TimeoutCancellationException ) { <EOL> scope . join ( ) <EOL> val completion = scope . getCompletionExceptionOrNull ( ) <EOL> if ( completion != null && completion !== cancellationException ) { <EOL> timeoutError ! ! . addSuppressed ( completion ) <EOL> } <EOL> workRunner . cancelAndJoin ( ) <EOL> } finally { <EOL> backgroundScope . cancel ( ) <EOL> testScheduler . advanceUntilIdleOr { false } <EOL> val uncaughtExceptions = scope . leave ( ) <EOL> throwAll ( timeoutError ? : scope . getCompletionExceptionOrNull ( ) , uncaughtExceptions ) <EOL> } <EOL> } <EOL> }

/**
 * Performs [runTest] on an existing [TestScope]. See the documentation for [runTest] for details.
 */


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

= asSpecificImplementation ( ) . let { <EOL> it . enter ( ) <EOL> @ Suppress ( "<STR_LIT:DEPRECATION>" ) <EOL> createTestResult { <EOL> runTestCoroutineLegacy ( it , dispatchTimeoutMs . milliseconds , TestScopeImpl :: tryGetCompletionCause , testBody ) { <EOL> backgroundScope . cancel ( ) <EOL> testScheduler . advanceUntilIdleOr { false } <EOL> it . legacyLeave ( ) <EOL> } <EOL> } <EOL> }

/**
 * Performs [runTest] on an existing [TestScope].
 *
 * In the general case, if there are active jobs, it's impossible to detect if they are going to complete eventually due
 * to the asynchronous nature of coroutines. In order to prevent tests hanging in this scenario, [runTest] will wait
 * for [dispatchTimeoutMs] from the moment when [TestCoroutineScheduler] becomes
 * idle before throwing [AssertionError]. If some dispatcher linked to [TestCoroutineScheduler] receives a
 * task during that time, the timer gets reset.
 */


@ Suppress ( "<STR_LIT>" ) <EOL> internal expect fun createTestResult ( testProcedure : suspend CoroutineScope . ( ) -> Unit ) : TestResult

/**
 * Runs [testProcedure], creating a [TestResult].
 */


@ Deprecated ( "<STR_LIT>" ) <EOL> internal suspend fun < T : AbstractCoroutine < Unit > > CoroutineScope . runTestCoroutineLegacy ( coroutine : T , dispatchTimeout : Duration , tryGetCompletionCause : T . ( ) -> Throwable ? , testBody : suspend T . ( ) -> Unit , cleanup : ( ) -> List < Throwable > , )

{ <EOL> val scheduler = coroutine . coroutineContext [ TestCoroutineScheduler ] ! ! <EOL> coroutine . start ( CoroutineStart . UNDISPATCHED , coroutine ) { <EOL> testBody ( ) <EOL> } <EOL> var completed = false <EOL> while ( ! completed ) { <EOL> scheduler . advanceUntilIdle ( ) <EOL> if ( coroutine . isCompleted ) { <EOL> completed = true <EOL> continue <EOL> } <EOL> val backgroundWorkRunner = launch ( CoroutineName ( "<STR_LIT>" ) ) { <EOL> while ( true ) { <EOL> val executedSomething = scheduler . tryRunNextTaskUnless { ! isActive } <EOL> if ( executedSomething ) { <EOL> yield ( ) <EOL> } else { <EOL> scheduler . receiveDispatchEvent ( ) <EOL> } <EOL> } <EOL> } <EOL> try { <EOL> select < Unit > { <EOL> coroutine . onJoin { <EOL> completed = true <EOL> } <EOL> scheduler . onDispatchEventForeground { <EOL> } <EOL> onTimeout ( dispatchTimeout ) { <EOL> throw handleTimeout ( coroutine , dispatchTimeout , tryGetCompletionCause , cleanup ) <EOL> } <EOL> } <EOL> } finally { <EOL> backgroundWorkRunner . cancelAndJoin ( ) <EOL> } <EOL> } <EOL> coroutine . getCompletionExceptionOrNull ( ) ? . let { exception -> <EOL> val exceptions = try { <EOL> cleanup ( ) <EOL> } catch ( e : UncompletedCoroutinesError ) { <EOL> emptyList ( ) <EOL> } <EOL> throwAll ( exception , exceptions ) <EOL> } <EOL> throwAll ( null , cleanup ( ) ) <EOL> }

/**
 * Run the [body][testBody] of the [test coroutine][coroutine], waiting for asynchronous completions for at most
 * [dispatchTimeout] and performing the [cleanup] procedure at the end.
 *
 * [tryGetCompletionCause] is the [JobSupport.completionCause], which is passed explicitly because it is protected.
 *
 * The [cleanup] procedure may either throw [UncompletedCoroutinesError] to denote that child coroutines were leaked, or
 * return a list of uncaught exceptions that should be reported at the end of the test.
 */


private inline fun < T : AbstractCoroutine < Unit > > handleTimeout ( coroutine : T , dispatchTimeout : Duration , tryGetCompletionCause : T . ( ) -> Throwable ? , cleanup : ( ) -> List < Throwable > , ) : AssertionError

{ <EOL> val uncaughtExceptions = try { <EOL> cleanup ( ) <EOL> } catch ( e : UncompletedCoroutinesError ) { <EOL> emptyList ( ) <EOL> } <EOL> val activeChildren = coroutine . children . filter { it . isActive } . toList ( ) <EOL> val completionCause = if ( coroutine . isCancelled ) coroutine . tryGetCompletionCause ( ) else null <EOL> var message = "<STR_LIT>" <EOL> if ( completionCause == null ) <EOL> message += "<STR_LIT>" <EOL> if ( activeChildren . isNotEmpty ( ) ) <EOL> message += "<STR_LIT>" <EOL> if ( completionCause != null && activeChildren . isEmpty ( ) ) { <EOL> message += if ( coroutine . isCompleted ) <EOL> "<STR_LIT>" <EOL> else <EOL> "<STR_LIT>" <EOL> } <EOL> val error = UncompletedCoroutinesError ( message ) <EOL> completionCause ? . let { cause -> error . addSuppressed ( cause ) } <EOL> uncaughtExceptions . forEach { error . addSuppressed ( it ) } <EOL> return error <EOL> }

/**
 * Invoked on timeout in [runTest]. Just builds a nice [UncompletedCoroutinesError] and returns it.
 */


@ Throws ( URISyntaxException :: class ) <EOL> fun getFileFromResource ( fileName : String ) : File

{ <EOL> val classLoader : ClassLoader = object { } . javaClass . classLoader <EOL> val resource : URL ? = classLoader . getResource ( fileName ) <EOL> return if ( resource == null ) { <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } else { <EOL> File ( resource . toURI ( ) ) <EOL> } <EOL> }

/** Converts resource string path to the file. */


fun KtAnalysisSession . getAllAnnotationsFrom ( annotated : KtAnnotated ) : List < Annotations . Annotation >

{ <EOL> val directAnnotations = getDirectAnnotationsFrom ( annotated ) <EOL> val backingFieldAnnotations = <EOL> ( annotated as? KtPropertySymbol ) ? . backingFieldSymbol ? . let { getDirectAnnotationsFrom ( it ) } . orEmpty ( ) <EOL> val fileLevelAnnotations = ( annotated as? KtSymbol ) ? . let { getFileLevelAnnotationsFrom ( it ) } . orEmpty ( ) <EOL> return directAnnotations + backingFieldAnnotations + fileLevelAnnotations <EOL> }

/**
 * The examples of annotations from backing field are [JvmField], [JvmSynthetic].
 *
 * @return direct annotations, annotations from backing field and file-level annotations
 */


internal fun KtAnnotated . getPresentableName ( ) : String ?

= <EOL> this . annotationsByClassId ( parameterNameAnnotation ) <EOL> . firstOrNull ( ) ? . arguments ? . firstOrNull { it . name == Name . identifier ( "<STR_LIT:name>" ) } ? . expression ? . let { it as? KtConstantAnnotationValue } <EOL> ? . let { it . constantValue . value . toString ( ) }

/**
 * Functional types can have **generated** [ParameterName] annotation
 * @see ParameterName
 */


fun property ( propertyName : String , project : Project ) : Provider < String >

{ <EOL> return propertiesManager . computeIfAbsent ( project ) { PropertiesManager ( project , parameters . localProperties . get ( ) ) } <EOL> . property ( propertyName ) <EOL> }

/** Returns a [Provider] of the value of the property with the given [propertyName] in the given [project]. */


fun get ( propertyName : String , project : Project ) : String ?

{ <EOL> return property ( propertyName , project ) . orNull <EOL> }

/** Returns the value of the property with the given [propertyName] in the given [project]. */


fun additionalTrainingAndPartialFreezingAndPartialInitialization ( )

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

/**
 * This example demonstrates the transfer learning concept:
 * - Weights are loaded from .h5 file for a pre-filtered list of layers (Conv2D only), configuration is loaded from .json file.
 * - Conv2D layer is added to the new Neural Network, its weights are frozen, Dense layers are added too, and its weights are initialized via defined initializers.
 * - No new layers are added.
 *
 * NOTE: Model and weights are resources in `examples` module.
 */


= additionalTrainingAndPartialFreezingAndPartialInitialization ( )


{ <EOL> val modelHub = TFModelHub ( cacheDirectory = File ( "<STR_LIT>" ) ) <EOL> val modelType = TFModels . CV . ResNet50 ( ) <EOL> val model = modelHub . loadModel ( modelType ) <EOL> val hdfFile = modelHub . loadWeights ( modelType ) <EOL> val layers = model . layers . toMutableList ( ) <EOL> layers . forEach ( Layer :: freeze ) <EOL> val lastLayer = layers . last ( ) <EOL> for ( outboundLayer in lastLayer . inboundLayers ) <EOL> outboundLayer . outboundLayers . remove ( lastLayer ) <EOL> layers . removeLast ( ) <EOL> val newDenseLayer = Dense ( name = "<STR_LIT>" , kernelInitializer = GlorotUniform ( ) , biasInitializer = GlorotUniform ( ) , outputSize = <NUM_LIT> , activation = Activations . Relu ) <EOL> newDenseLayer . inboundLayers . add ( layers . last ( ) ) <EOL> layers . add ( newDenseLayer ) <EOL> val newDenseLayer2 = Dense ( name = "<STR_LIT>" , kernelInitializer = GlorotUniform ( ) , biasInitializer = GlorotUniform ( ) , outputSize = NUM_CLASSES , activation = Activations . Linear ) <EOL> newDenseLayer2 . inboundLayers . add ( layers . last ( ) ) <EOL> layers . add ( newDenseLayer2 ) <EOL> val model2 = Functional . of ( layers ) <EOL> val dogsCatsImages = dogsCatsSmallDatasetPath ( ) <EOL> val dataset = OnFlyImageDataset . create ( File ( dogsCatsImages ) , FromFolders ( mapping = mapOf ( "<STR_LIT>" to <NUM_LIT:0> , "<STR_LIT>" to <NUM_LIT:1> ) ) , modelType . createPreprocessing ( model2 ) ) . shuffle ( ) <EOL> val ( train , test ) = dataset . split ( TRAIN_TEST_SPLIT_RATIO ) <EOL> model2 . use { <EOL> it . compile ( optimizer = Adam ( ) , loss = Losses . SOFT_MAX_CROSS_ENTROPY_WITH_LOGITS , metric = Metrics . ACCURACY ) <EOL> it . loadWeightsForFrozenLayers ( hdfFile ) <EOL> val accuracyBeforeTraining = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> it . fit ( dataset = train , batchSize = TRAINING_BATCH_SIZE , epochs = EPOCHS ) <EOL> val accuracyAfterTraining = it . evaluate ( dataset = test , batchSize = TEST_BATCH_SIZE ) . metrics [ Metrics . ACCURACY ] <EOL> println ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * This example demonstrates the transfer learning 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.
 * - All layers, excluding the last [Dense], are added to the new Neural Network, its weights are frozen.
 * - New Dense layers are added and initialized via defined initializers.
 * - Model is re-trained on [dogsCatsSmallDatasetPath] dataset.
 *
 * We use the preprocessing DSL to describe the dataset generation pipeline.
 * We demonstrate the workflow on the subset of Kaggle Cats vs Dogs binary classification dataset.
 */


= resnet50additionalTraining ( )


fun Project . sourcesJarWithSourcesFromEmbedded ( vararg embeddedDepSourcesJarTasks : TaskProvider < out Jar > , body : Jar . ( ) -> Unit = { } , ) : TaskProvider < Jar >

{ <EOL> val sourcesJarTask = sourcesJar ( body ) <EOL> sourcesJarTask . configure { <EOL> val archiveOperations = serviceOf < ArchiveOperations > ( ) <EOL> embeddedDepSourcesJarTasks . forEach { embeddedSourceJarTask -> <EOL> dependsOn ( embeddedSourceJarTask ) <EOL> from ( embeddedSourceJarTask . map { archiveOperations . zipTree ( it . archiveFile ) } ) <EOL> } <EOL> } <EOL> return sourcesJarTask <EOL> }

/**
 * Also embeds into final '-sources.jar' file source files from embedded dependencies.
 */


fun Project . javadocJarWithJavadocFromEmbedded ( vararg embeddedDepJavadocJarTasks : TaskProvider < out Jar > , body : Jar . ( ) -> Unit = { } , ) : TaskProvider < Jar >

{ <EOL> val javadocJarTask = javadocJar ( body ) <EOL> javadocJarTask . configure { <EOL> val archiveOperations = serviceOf < ArchiveOperations > ( ) <EOL> embeddedDepJavadocJarTasks . forEach { embeddedJavadocJarTask -> <EOL> dependsOn ( embeddedJavadocJarTask ) <EOL> from ( embeddedJavadocJarTask . map { archiveOperations . zipTree ( it . archiveFile ) } ) <EOL> } <EOL> } <EOL> return javadocJarTask <EOL> }

/**
 * Also embeds into final '-javadoc.jar' file javadoc files from embedded dependencies.
 */


protected abstract fun mergeFunction ( input : List < Operand < Float > > , tf : Ops ) : Operand < Float >

/** Should be overridden in all AbstractMerge descendants. */


protected open fun checkInputShapes ( inputShapes : List < Shape > )

{ <EOL> require ( inputShapes . size > <NUM_LIT:1> ) { "<STR_LIT>" } <EOL> val firstInputShape = inputShapes . first ( ) . toTensorShape ( ) <EOL> for ( ( index , inputShape ) in inputShapes . withIndex ( ) ) { <EOL> val currentInputShape = inputShape . toTensorShape ( ) <EOL> require ( firstInputShape == currentInputShape ) { <EOL> "<STR_LIT>" <EOL> } <EOL> } <EOL> }


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

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

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


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public fun < C > ColumnSet < C > . nameContains ( text : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < C >

= <EOL> colsInternal { it . name . contains ( text , ignoreCase ) } as TransformableColumnSet < C >

/**
 * @include [NameContainsTextDocs]
 * @set [CommonNameContainsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[cols][ColumnsSelectionDsl.cols]` { .. }.`[nameContains][ColumnSet.nameContains]`("my") }`
 *
 * `df.`[select][DataFrame.select]` { `[colsOf][SingleColumn.colsOf]`<`[Int][Int]`>().`[nameContains][ColumnSet.nameContains]`("my", ignoreCase = true) }`
 */


public fun ColumnsSelectionDsl < * > . nameContains ( text : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

= <EOL> asSingleColumn ( ) . colsNameContains ( text , ignoreCase )

/**
 * @include [NameContainsTextDocs]
 * @set [CommonNameContainsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[nameContains][ColumnsSelectionDsl.colsNameContains]`("my") }`
 */


public fun SingleColumn < DataRow < * > > . colsNameContains ( text : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

= <EOL> this . ensureIsColumnGroup ( ) . colsInternal { it . name . contains ( text , ignoreCase ) }

/**
 * @include [NameContainsTextDocs]
 * @set [CommonNameContainsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { someGroupCol.`[colsNameContains][SingleColumn.colsNameContains]`("my") }`
 */


public fun String . colsNameContains ( text : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

= <EOL> columnGroup ( this ) . colsNameContains ( text , ignoreCase )

/**
 * @include [NameContainsTextDocs]
 * @set [CommonNameContainsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "someGroupCol".`[colsNameContains][String.colsNameContains]`("my") }`
 */


public fun KProperty < * > . colsNameContains ( text : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

/**
 * @include [NameContainsTextDocs]
 * @set [CommonNameContainsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::someGroupCol.`[colsNameContains][KProperty.colsNameContains]`("my") }`
 */


public fun ColumnPath . colsNameContains ( text : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

/**
 * @include [NameContainsTextDocs]
 * @set [CommonNameContainsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "pathTo"["someGroupCol"].`[colsNameContains][ColumnPath.colsNameContains]`("my") }`
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public fun < C > ColumnSet < C > . nameContains ( regex : Regex ) : TransformableColumnSet < C >

= <EOL> colsInternal { it . name . contains ( regex ) } as TransformableColumnSet < C >

/**
 * @include [NameContainsRegexDocs]
 * @set [CommonNameContainsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[cols][ColumnsSelectionDsl.cols]` { .. }.`[nameContains][ColumnSet.nameContains]`(`[Regex][Regex]`("order-[0-9]+")) }`
 *
 * `df.`[select][DataFrame.select]` { `[colsOf][SingleColumn.colsOf]`<`[Int][Int]`>().`[nameContains][ColumnSet.nameContains]`(`[Regex][Regex]`("order-[0-9]+")) }`
 */


public fun ColumnsSelectionDsl < * > . nameContains ( regex : Regex ) : TransformableColumnSet < * >

= <EOL> asSingleColumn ( ) . colsNameContains ( regex )

/**
 * @include [NameContainsRegexDocs]
 * @set [CommonNameContainsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[nameContains][ColumnsSelectionDsl.nameContains]`(`[Regex][Regex]`("order-[0-9]+")) }`
 */


public fun SingleColumn < DataRow < * > > . colsNameContains ( regex : Regex ) : TransformableColumnSet < * >

= <EOL> this . ensureIsColumnGroup ( ) . colsInternal { it . name . contains ( regex ) }

/**
 * @include [NameContainsRegexDocs]
 * @set [CommonNameContainsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { someGroupCol.`[colsNameContains][SingleColumn.colsNameContains]`(`[Regex][Regex]`("order-[0-9]+")) }`
 */


public fun String . colsNameContains ( regex : Regex ) : TransformableColumnSet < * >

= <EOL> columnGroup ( this ) . colsNameContains ( regex )

/**
 * @include [NameContainsRegexDocs]
 * @set [CommonNameContainsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "someGroupCol".`[colsNameContains][String.colsNameContains]`(`[Regex][Regex]`("order-[0-9]+")) }`
 */


public fun KProperty < * > . colsNameContains ( regex : Regex ) : TransformableColumnSet < * >

/**
 * @include [NameContainsRegexDocs]
 * @set [CommonNameContainsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::someGroupCol.`[colsNameContains][KProperty.colsNameContains]`(`[Regex][Regex]`("order-[0-9]+")) }`
 */


public fun ColumnPath . colsNameContains ( regex : Regex ) : TransformableColumnSet < * >

/**
 * @include [NameContainsRegexDocs]
 * @set [CommonNameContainsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "pathTo"["someGroupCol"].`[colsNameContains][ColumnPath.colsNameContains]`(`[Regex][Regex]`("order-[0-9]+")) }`
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public fun < C > ColumnSet < C > . nameStartsWith ( prefix : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < C >

= <EOL> colsInternal { it . name . startsWith ( prefix , ignoreCase ) } as TransformableColumnSet < C >

/**
 * @include [CommonNameStartsWithDocs]
 * @set [CommonNameStartsEndsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[colsOf][SingleColumn.colsOf]`<`[Int][Int]`>().`[nameStartsWith][ColumnSet.nameStartsWith]`("order-") }`
 */


public fun ColumnsSelectionDsl < * > . nameStartsWith ( prefix : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

= <EOL> asSingleColumn ( ) . colsNameStartsWith ( prefix , ignoreCase )

/**
 * @include [CommonNameStartsWithDocs]
 * @set [CommonNameStartsEndsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[nameStartsWith][ColumnsSelectionDsl.nameStartsWith]`("order-") }`
 */


public fun SingleColumn < DataRow < * > > . colsNameStartsWith ( prefix : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

= <EOL> this . ensureIsColumnGroup ( ) . colsInternal { it . name . startsWith ( prefix , ignoreCase ) }

/**
 * @include [CommonNameStartsWithDocs]
 * @set [CommonNameStartsEndsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { someGroupCol.`[colsNameStartsWith][SingleColumn.colsNameStartsWith]`("order-") }`
 */


public fun String . colsNameStartsWith ( prefix : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

= <EOL> columnGroup ( this ) . colsNameStartsWith ( prefix , ignoreCase )

/**
 * @include [CommonNameStartsWithDocs]
 * @set [CommonNameStartsEndsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "someGroupCol".`[colsNameStartsWith][String.colsNameStartsWith]`("order-") }`
 */


public fun KProperty < * > . colsNameStartsWith ( prefix : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

/**
 * @include [CommonNameStartsWithDocs]
 * @set [CommonNameStartsEndsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::someGroupCol.`[colsNameStartsWith][KProperty.colsNameStartsWith]`("order-") }`
 */


public fun ColumnPath . colsNameStartsWith ( prefix : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

/**
 * @include [CommonNameStartsWithDocs]
 * @set [CommonNameStartsEndsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "pathTo"["someGroupCol"].`[colsNameStartsWith][ColumnPath.colsNameStartsWith]`("order-") }`
 */


@ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> public fun < C > ColumnSet < C > . nameEndsWith ( suffix : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < C >

= <EOL> colsInternal { it . name . endsWith ( suffix , ignoreCase ) } as TransformableColumnSet < C >

/**
 * @include [CommonNameEndsWithDocs]
 * @set [CommonNameStartsEndsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[colsOf][SingleColumn.colsOf]`<`[Int][Int]`>().`[nameEndsWith][ColumnSet.nameEndsWith]`("-order") }`
 */


public fun ColumnsSelectionDsl < * > . nameEndsWith ( suffix : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

= <EOL> asSingleColumn ( ) . colsNameEndsWith ( suffix , ignoreCase )

/**
 * @include [CommonNameEndsWithDocs]
 * @set [CommonNameStartsEndsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { `[nameEndsWith][ColumnsSelectionDsl.nameEndsWith]`("-order") }`
 */


public fun SingleColumn < DataRow < * > > . colsNameEndsWith ( suffix : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

= <EOL> this . ensureIsColumnGroup ( ) . colsInternal { it . name . endsWith ( suffix , ignoreCase ) }

/**
 * @include [CommonNameEndsWithDocs]
 * @set [CommonNameStartsEndsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { someGroupCol.`[colsNameEndsWith][SingleColumn.colsNameEndsWith]`("-order") }`
 */


public fun String . colsNameEndsWith ( suffix : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

= <EOL> columnGroup ( this ) . colsNameEndsWith ( suffix , ignoreCase )

/**
 * @include [CommonNameEndsWithDocs]
 * @set [CommonNameStartsEndsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "someGroupCol".`[colsNameEndsWith][String.colsNameEndsWith]`("-order") }`
 */


public fun KProperty < * > . colsNameEndsWith ( suffix : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

/**
 * @include [CommonNameEndsWithDocs]
 * @set [CommonNameStartsEndsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { DataSchemaType::someGroupCol.`[colsNameEndsWith][KProperty.colsNameEndsWith]`("-order") }`
 */


public fun ColumnPath . colsNameEndsWith ( suffix : CharSequence , ignoreCase : Boolean = false , ) : TransformableColumnSet < * >

/**
 * @include [CommonNameEndsWithDocs]
 * @set [CommonNameStartsEndsDocs.ExampleArg]
 *
 * `df.`[select][DataFrame.select]` { "pathTo"["someGroupCol"].`[colsNameEndsWith][ColumnPath.colsNameEndsWith]`("-order") }`
 */


fun validateArguments ( errors : ArgumentParseErrors ? ) : String ?

{ <EOL> if ( errors == null ) return null <EOL> if ( errors . argumentWithoutValue != null ) { <EOL> return "<STR_LIT>" <EOL> } <EOL> errors . booleanArgumentWithValue ? . let { arg -> <EOL> return "<STR_LIT>" <EOL> } <EOL> if ( errors . unknownArgs . isNotEmpty ( ) ) { <EOL> return "<STR_LIT>" <EOL> } <EOL> return null <EOL> }

/**
 * @return error message if arguments are parsed incorrectly, null otherwise
 */


fun StubType . map ( shouldExpandTypeAliases : Boolean = true ) : KmType

= when ( this ) { <EOL> is AbbreviatedType -> { <EOL> val typeAliasClassifier = KmClassifier . TypeAlias ( abbreviatedClassifier . fqNameSerialized ) <EOL> val typeArguments = typeArguments . map { it . map ( shouldExpandTypeAliases ) } <EOL> val abbreviatedType = KmType ( ) . also { km -> <EOL> km . modifiersFrom ( this ) <EOL> km . classifier = typeAliasClassifier <EOL> km . arguments += typeArguments <EOL> } <EOL> if ( shouldExpandTypeAliases ) { <EOL> KmType ( ) . also { km -> <EOL> km . isNullable = this . isEffectivelyNullable ( ) <EOL> km . abbreviatedType = abbreviatedType <EOL> val kmUnderlyingType = underlyingType . map ( true ) <EOL> km . arguments += kmUnderlyingType . arguments <EOL> km . classifier = kmUnderlyingType . classifier <EOL> } <EOL> } else { <EOL> abbreviatedType <EOL> } <EOL> } <EOL> is ClassifierStubType -> KmType ( ) . also { km -> <EOL> km . modifiersFrom ( this ) <EOL> typeArguments . mapTo ( km . arguments ) { it . map ( shouldExpandTypeAliases ) } <EOL> km . classifier = KmClassifier . Class ( classifier . fqNameSerialized ) <EOL> } <EOL> is FunctionalType -> KmType ( ) . also { km -> <EOL> km . modifiersFrom ( this ) <EOL> typeArguments . mapTo ( km . arguments ) { it . map ( shouldExpandTypeAliases ) } <EOL> km . classifier = KmClassifier . Class ( classifier . fqNameSerialized ) <EOL> } <EOL> is TypeParameterType -> KmType ( ) . also { km -> <EOL> km . modifiersFrom ( this ) <EOL> km . classifier = KmClassifier . TypeParameter ( id ) <EOL> } <EOL> }

/**
 * @param shouldExpandTypeAliases describes how should we write type aliases.
 * If [shouldExpandTypeAliases] is true then type alias-based types are written as
 * ```
 * Type {
 * abbreviatedType = AbbreviatedType.abbreviatedClassifier
 * classifier = AbbreviatedType.underlyingType
 * arguments = AbbreviatedType.underlyingType.typeArguments
 * }
 * ```
 * So we basically replacing type alias with underlying class.
 * Otherwise:
 * ```
 * Type {
 * classifier = AbbreviatedType.abbreviatedClassifier
 * }
 * ```
 * As of 25 Nov 2019, the latter form is used only for KmTypeAlias.underlyingType.
 */


private fun String ? . toTeamCityFormat ( ) : String

= this ? . let { <EOL> it . replace ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> . replace ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> . replace ( "<STR_LIT:\n>" , "<STR_LIT>" ) <EOL> . replace ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> . replace ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> . replace ( "<STR_LIT:]>" , "<STR_LIT>" ) } ? : "<STR_LIT:null>"

/**
 * Teamcity require escaping some symbols in pipe manner.
 * https://github.com/GitTools/GitVersion/issues/94
 */


fun IrType . eraseTypeParameters ( ) : IrType

= when ( this ) { <EOL> is IrSimpleType -> <EOL> when ( val owner = classifier . owner ) { <EOL> is IrScript -> { <EOL> assert ( arguments . isEmpty ( ) ) { "<STR_LIT>" + owner . render ( ) } <EOL> IrSimpleTypeImpl ( classifier , nullability , emptyList ( ) , annotations ) <EOL> } <EOL> is IrClass -> IrSimpleTypeImpl ( classifier , nullability , arguments . map { it . eraseTypeParameters ( ) } , annotations ) <EOL> is IrTypeParameter -> owner . erasedType ( isNullable ( ) ) <EOL> else -> error ( "<STR_LIT>" ) <EOL> } <EOL> is IrErrorType -> <EOL> this <EOL> else -> error ( "<STR_LIT>" ) <EOL> }

/**
 * Perform as much type erasure as is significant for JVM signature generation.
 * Class types are kept as is, while type parameters are replaced with their
 * erased upper bounds, keeping the nullability information.
 *
 * For example, a type parameter `T?` where `T : Any`, `T : Comparable<T>` is
 * erased to `Any?`.
 *
 * Type arguments to the erased upper bound are replaced by `*`, since
 * recursive erasure could loop. For example, a type parameter
 * `T : Comparable<T>` is replaced by `Comparable<*>`.
 */


fun IrType . defaultValue ( startOffset : Int , endOffset : Int , context : JvmBackendContext ) : IrExpression

{ <EOL> val classifier = this . classifierOrNull <EOL> if ( classifier is IrTypeParameterSymbol ) { <EOL> return classifier . owner . representativeUpperBound . defaultValue ( startOffset , endOffset , context ) <EOL> } <EOL> if ( this !is IrSimpleType || this . isMarkedNullable ( ) || classOrNull ? . owner ? . isSingleFieldValueClass != true ) <EOL> return IrConstImpl . defaultValueForType ( startOffset , endOffset , this ) <EOL> val underlyingType = unboxInlineClass ( ) <EOL> val defaultValueForUnderlyingType = IrConstImpl . defaultValueForType ( startOffset , endOffset , underlyingType ) <EOL> return IrCallImpl . fromSymbolOwner ( startOffset , endOffset , this , context . ir . symbols . unsafeCoerceIntrinsic ) . also { <EOL> it . putTypeArgument ( <NUM_LIT:0> , underlyingType ) <EOL> it . putTypeArgument ( <NUM_LIT:1> , this ) <EOL> it . putValueArgument ( <NUM_LIT:0> , defaultValueForUnderlyingType ) <EOL> } <EOL> }

/**
 * Get the default null/0 value for the type.
 *
 * This handles unboxing of non-nullable inline class types to their underlying types and produces
 * a null/0 default value for the resulting type. When such unboxing takes place it ensures that
 * the value is not reboxed and reunboxed by the codegen by using the unsafeCoerceIntrinsic.
 */


@ SinceKotlin ( "<STR_LIT:1.1>" ) <EOL> fun KClassifier . createType ( arguments : List < KTypeProjection > = emptyList ( ) , nullable : Boolean = false , annotations : List < Annotation > = emptyList ( ) ) : KType

{ <EOL> val descriptor = ( this as? KClassifierImpl ) ? . descriptor <EOL> ? : throw KotlinReflectionInternalError ( "<STR_LIT>" ) <EOL> val typeConstructor = descriptor . typeConstructor <EOL> val parameters = typeConstructor . parameters <EOL> if ( parameters . size != arguments . size ) { <EOL> throw IllegalArgumentException ( "<STR_LIT>" ) <EOL> } <EOL> val typeAttributes = <EOL> if ( annotations . isEmpty ( ) ) TypeAttributes . Empty <EOL> else TypeAttributes . Empty <EOL> return KTypeImpl ( createKotlinType ( typeAttributes , typeConstructor , arguments , nullable ) ) <EOL> }

/**
 * Creates a [KType] instance with the given classifier, type arguments, nullability and annotations.
 * If the number of passed type arguments is not equal to the total number of type parameters of a classifier,
 * an exception is thrown. If any of the arguments does not satisfy the bounds of the corresponding type parameter,
 * an exception is thrown.
 *
 * For classifiers representing type parameters, the type argument list must always be empty.
 * For classes, the type argument list should contain arguments for the type parameters of the class. If the class is `inner`,
 * the list should follow with arguments for the type parameters of its outer class, and so forth until a class is
 * not `inner`, or is declared on the top level.
 */


fun plugin ( instance : DokkaPlugin )

/**
 * Add a plugin instance to a project
 */


fun verify ( )

/**
 * Verifies that this project is valid from the user's and Dokka's perspectives.
 * Exists to save time with debugging difficult to catch mistakes, such as copy-pasted
 * test data that is not applicable to this project.
 *
 * Must throw an exception if there's misconfiguration, incorrect / corrupted test data
 * or API misuse.
 *
 * Verification is performed before running Dokka on this project.
 */


fun getConfiguration ( ) : TestDokkaConfiguration

/**
 * Returns the configuration of this project, which will then be mapped to [DokkaConfiguration].
 *
 * This is typically constructed using [BaseTestDokkaConfigurationBuilder].
 */


fun getPluginList ( ) : List < DokkaPlugin >

/**
 * Returns the list of plugins, which will then be directly passed to [DokkaContext].
 *
 * Unlike [DokkaConfiguration.pluginsClasspath], it does not require a JAR file with a configuration of [java.util.ServiceLoader]
 */


fun getTestData ( ) : TestData

/**
 * Returns this project's test data - a collection of source code files, markdown files
 * and whatever else that can be usually found in a user-defined project.
 */


fun TestProject . parse ( logger : DokkaLogger = defaultAnalysisLogger ) : DModule

= TestProjectAnalyzer . parse ( this , logger )

/**
 * Runs Dokka on the given [TestProject] and returns the generated documentable model.
 *
 * Can be used to verify the resulting documentable model, to check that
 * everything was parsed and converted correctly.
 *
 * Usage example:
 * ```kotlin
 * val testProject = kotlinJvmTestProject {
 * ...
 * }
 *
 * val module: DModule = testProject.parse()
 * ```
 *
 * @param logger logger to be used for running Dokka and tests. Custom loggers like [CollectingDokkaConsoleLogger]
 * can be useful in verifying the behavior.
 */


fun TestProject . useServices ( logger : DokkaLogger = defaultAnalysisLogger , block : TestAnalysisServices . ( context : TestAnalysisContext ) -> Unit )

{ <EOL> withTempDirectory { tempDirectory -> <EOL> val ( services , context ) = TestProjectAnalyzer . analyze ( this , tempDirectory , logger ) <EOL> services . block ( context ) <EOL> } <EOL> }

/**
 * Runs Dokka on the given [TestProject] and provides not only the resulting documentable model,
 * but analysis context and configuration as well, which gives you the ability to call public
 * analysis services.
 *
 * Usage example:
 *
 * ```kotlin
 * val testProject = kotlinJvmTestProject {
 * ...
 * }
 *
 * testProject.useServices { context ->
 * val pckg: DPackage = context.module.packages.single()
 *
 * // use `moduleAndPackageDocumentationReader` service to get documentation of a package
 * val allPackageDocs: SourceSetDependent<DocumentationNode> = moduleAndPackageDocumentationReader.read(pckg)
 * }
 * ```
 *
 * @param logger logger to be used for running Dokka and tests. Custom loggers like [CollectingDokkaConsoleLogger]
 * can be useful in verifying the behavior.
 */


@ Suppress ( "<STR_LIT:FunctionName>" ) <EOL> public fun Format ( block : DateTimeFormatBuilder . WithDateTimeComponents . ( ) -> Unit ) : DateTimeFormat < DateTimeComponents >

{ <EOL> val builder = DateTimeComponentsFormat . Builder ( AppendableFormatStructure ( ) ) <EOL> block ( builder ) <EOL> return DateTimeComponentsFormat ( builder . build ( ) ) <EOL> }

/**
 * Creates a [DateTimeFormat] for [DateTimeComponents] values using [DateTimeFormatBuilder.WithDateTimeComponents].
 *
 * There is a collection of predefined formats in [DateTimeComponents.Formats].
 *
 * @throws IllegalArgumentException if parsing using this format is ambiguous.
 */


public fun setTime ( localTime : LocalTime )

{ <EOL> contents . time . populateFrom ( localTime ) <EOL> }

/**
 * Writes the contents of the specified [localTime] to this [DateTimeComponents].
 * The [localTime] is written to the [hour], [hourOfAmPm], [amPm], [minute], [second] and [nanosecond] fields.
 *
 * If any of the fields are already set, they will be overwritten.
 */


public fun setDate ( localDate : LocalDate )

{ <EOL> contents . date . populateFrom ( localDate ) <EOL> }

/**
 * Writes the contents of the specified [localDate] to this [DateTimeComponents].
 * The [localDate] is written to the [year], [monthNumber], [dayOfMonth], and [dayOfWeek] fields.
 *
 * If any of the fields are already set, they will be overwritten.
 */


public fun setDateTime ( localDateTime : LocalDateTime )

{ <EOL> contents . date . populateFrom ( localDateTime . date ) <EOL> contents . time . populateFrom ( localDateTime . time ) <EOL> }

/**
 * Writes the contents of the specified [localDateTime] to this [DateTimeComponents].
 * The [localDateTime] is written to the
 * [year], [monthNumber], [dayOfMonth], [dayOfWeek],
 * [hour], [hourOfAmPm], [amPm], [minute], [second] and [nanosecond] fields.
 *
 * If any of the fields are already set, they will be overwritten.
 */


public fun setOffset ( utcOffset : UtcOffset )

{ <EOL> contents . offset . populateFrom ( utcOffset ) <EOL> }

/**
 * Writes the contents of the specified [utcOffset] to this [DateTimeComponents].
 * The [utcOffset] is written to the [offsetHours], [offsetMinutesOfHour], [offsetSecondsOfMinute], and
 * [offsetIsNegative] fields.
 *
 * If any of the fields are already set, they will be overwritten.
 */


public fun setDateTimeOffset ( instant : Instant , utcOffset : UtcOffset )

{ <EOL> val smallerInstant = Instant . fromEpochSeconds ( instant . epochSeconds % SECONDS_PER_10000_YEARS , instant . nanosecondsOfSecond ) <EOL> setDateTime ( smallerInstant . toLocalDateTime ( utcOffset ) ) <EOL> setOffset ( utcOffset ) <EOL> year = year ! ! + ( ( instant . epochSeconds / SECONDS_PER_10000_YEARS ) * <NUM_LIT> ) . toInt ( ) <EOL> }

/**
 * Writes the contents of the specified [instant] to this [DateTimeComponents].
 *
 * This method is almost always equivalent to the following code:
 * ```
 * setDateTime(instant.toLocalDateTime(offset))
 * setOffset(utcOffset)
 * ```
 * However, this also works for instants that are too large to be represented as a [LocalDateTime].
 *
 * If any of the fields are already set, they will be overwritten.
 */


public fun setDateTimeOffset ( localDateTime : LocalDateTime , utcOffset : UtcOffset )

{ <EOL> setDateTime ( localDateTime ) <EOL> setOffset ( utcOffset ) <EOL> }

/**
 * Writes the contents of the specified [localDateTime] and [utcOffset] to this [DateTimeComponents].
 *
 * A shortcut for calling [setDateTime] and [setOffset] separately.
 *
 * If [localDateTime] is obtained from an [Instant] using [LocalDateTime.toInstant], it is recommended to use
 * [setDateTimeOffset] that accepts an [Instant] directly.
 */


= contents . offset . toUtcOffset ( )

/**
 * Builds a [UtcOffset] from the fields in this [DateTimeComponents].
 *
 * This method uses the following fields:
 * * [offsetIsNegative] (default value is `false`)
 * * [offsetHours] (default value is 0)
 * * [offsetMinutesOfHour] (default value is 0)
 * * [offsetSecondsOfMinute] (default value is 0)
 *
 * @throws IllegalArgumentException if any of the fields has an out-of-range value.
 */


= contents . date . toLocalDate ( )

/**
 * Builds a [LocalDate] from the fields in this [DateTimeComponents].
 *
 * This method uses the following fields:
 * * [year]
 * * [monthNumber]
 * * [dayOfMonth]
 *
 * Also, [dayOfWeek] is checked for consistency with the other fields.
 *
 * @throws IllegalArgumentException if any of the fields is missing or invalid.
 */


= contents . time . toLocalTime ( )

/**
 * Builds a [LocalTime] from the fields in this [DateTimeComponents].
 *
 * This method uses the following fields:
 * * [hour], [hourOfAmPm], and [amPm]
 * * [minute]
 * * [second] (default value is 0)
 * * [nanosecond] (default value is 0)
 *
 * @throws IllegalArgumentException if hours or minutes are not present, if any of the fields are invalid, or
 * [hourOfAmPm] and [amPm] are inconsistent with [hour].
 */


public fun toLocalDateTime ( ) : LocalDateTime

= toLocalDate ( ) . atTime ( toLocalTime ( ) )

/**
 * Builds a [LocalDateTime] from the fields in this [DateTimeComponents].
 *
 * This method uses the following fields:
 * * [year]
 * * [monthNumber]
 * * [dayOfMonth]
 * * [hour], [hourOfAmPm], and [amPm]
 * * [minute]
 * * [second] (default value is 0)
 * * [nanosecond] (default value is 0)
 *
 * Also, [dayOfWeek] is checked for consistency with the other fields.
 *
 * @throws IllegalArgumentException if any of the required fields are not present,
 * any of the fields are invalid, or there's inconsistency.
 *
 * @see toLocalDate
 * @see toLocalTime
 */


public fun toInstantUsingOffset ( ) : Instant

{ <EOL> val offset = toUtcOffset ( ) <EOL> val time = toLocalTime ( ) <EOL> val truncatedDate = contents . date . copy ( ) <EOL> truncatedDate . year = requireParsedField ( truncatedDate . year , "<STR_LIT>" ) % <NUM_LIT> <EOL> val totalSeconds = try { <EOL> val secDelta = safeMultiply ( ( year ! ! / <NUM_LIT> ) . toLong ( ) , SECONDS_PER_10000_YEARS ) <EOL> val epochDays = truncatedDate . toLocalDate ( ) . toEpochDays ( ) . toLong ( ) <EOL> safeAdd ( secDelta , epochDays * SECONDS_PER_DAY + time . toSecondOfDay ( ) - offset . totalSeconds ) <EOL> } catch ( e : ArithmeticException ) { <EOL> throw DateTimeFormatException ( "<STR_LIT>" , e ) <EOL> } <EOL> if ( totalSeconds < Instant . MIN . epochSeconds || totalSeconds > Instant . MAX . epochSeconds ) <EOL> throw DateTimeFormatException ( "<STR_LIT>" ) <EOL> return Instant . fromEpochSeconds ( totalSeconds , nanosecond ? : <NUM_LIT:0> ) <EOL> }

/**
 * Builds an [Instant] from the fields in this [DateTimeComponents].
 *
 * Uses the fields required for [toLocalDateTime] and [toUtcOffset].
 *
 * Almost always equivalent to `toLocalDateTime().toInstant(toUtcOffset())`, but also accounts for cases when
 * the year is outside the range representable by [LocalDate] but not outside the range representable by [Instant].
 *
 * @throws IllegalArgumentException if any of the required fields are not present, out-of-range, or inconsistent
 * with one another.
 */


public fun DateTimeFormat < DateTimeComponents > . format ( block : DateTimeComponents . ( ) -> Unit ) : String

= <EOL> format ( DateTimeComponents ( ) . apply { block ( ) } )

/**
 * Uses this format to format an unstructured [DateTimeComponents].
 *
 * [block] is called on an initially-empty [DateTimeComponents] before formatting.
 *
 * Example:
 * ```
 * // Mon, 16 Mar 2020 23:59:59 +0300
 * DateTimeComponents.Formats.RFC_1123.format {
 * setDateTime(LocalDateTime(2020, 3, 16, 23, 59, 59, 999_999_999))
 * setOffset(UtcOffset(hours = 3))
 * }
 * ```
 *
 * @throws IllegalStateException if some values needed for the format are not present or can not be formatted:
 * for example, trying to format [DateTimeFormatBuilder.WithDate.monthName] using a [DateTimeComponents.monthNumber]
 * value of 20.
 */


public fun DateTimeComponents . Companion . parse ( input : CharSequence , format : DateTimeFormat < DateTimeComponents > ) : DateTimeComponents

= <EOL> format . parse ( input )

/**
 * Parses a [DateTimeComponents] from [input] using the given format.
 * Equivalent to calling [DateTimeFormat.parse] on [format] with [input].
 *
 * [DateTimeComponents] does not perform any validation, so even invalid values may be parsed successfully if the string pattern
 * matches.
 *
 * @throws IllegalArgumentException if the text does not match the format.
 */


public fun vgg19 ( 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>" ) , 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>" ) , 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>" ) , 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 VGG19 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'19 model and an approach to build it in Keras.
 */


fun eval ( code : Code , compilingOptions : JupyterCompilingOptions = JupyterCompilingOptions . DEFAULT , evaluatorWorkflowListener : EvaluatorWorkflowListener ? = null , ) : InternalEvalResult

/**
 * Executes code snippet
 * @throws IllegalStateException if this method was invoked recursively
 */


fun popAddedCompiledScripts ( ) : SerializedCompiledScriptsData

= SerializedCompiledScriptsData . EMPTY

/**
 * Pop a serialized form of recently added compiled scripts
 *
 * This operation is stateful: second call of this method in a row always
 * returns empty data or null
 */


suspend fun complete ( snippet : SourceCode , cursor : SourceCode . Position , configuration : ScriptCompilationConfiguration ) : ResultWithDiagnostics < ReplCompletionResult >

/**
 * Returns the list of possible reference variants in [cursor] position.
 * Generally <b>doesn't change</b> the internal state of implementing object.
 * @param snippet Completion context
 * @param cursor Cursor position in which completion variants should be calculated
 * @param configuration Compilation configuration which is used. Script should be analyzed, but code generation is not performed
 * @return List of reference variants
 */


suspend fun analyze ( snippet : SourceCode , cursor : SourceCode . Position , configuration : ScriptCompilationConfiguration ) : ResultWithDiagnostics < ReplAnalyzerResult >

/**
 * Reports compilation errors and warnings in the given [snippet]
 * @param snippet Code to analyze
 * @param cursor Current cursor position. May be used by implementation for suppressing errors and warnings near it.
 * @param configuration Compilation configuration which is used. Script should be analyzed, but code generation is not performed
 * @return List of diagnostic messages
 */


public fun ClassName . toJvmInternalName ( ) : String

= <EOL> if ( this . isLocalClassName ( ) ) substring ( <NUM_LIT:1> ) <EOL> else replace ( '<CHAR_LIT:.>' , '<CHAR_LIT:$>' )

/**
 * Converts [this] to a JVM internal name of the class, where package names are separated by '/', and class names are separated by '$',
 * for example: `"org/foo/bar/Baz.Nested"` -> `"org/foo/bar/Baz$Nested"`
 */


public fun Metadata ( kind : Int ? = null , metadataVersion : IntArray ? = null , data1 : Array < String > ? = null , data2 : Array < String > ? = null , extraString : String ? = null , packageName : String ? = null , extraInt : Int ? = null ) : Metadata

= Metadata ( kind ? : <NUM_LIT:1> , metadataVersion ? : intArrayOf ( ) , intArrayOf ( <NUM_LIT:1> , <NUM_LIT:0> , <NUM_LIT:3> ) , data1 ? : emptyArray ( ) , data2 ? : emptyArray ( ) , extraString ? : "<STR_LIT>" , packageName ? : "<STR_LIT>" , extraInt ? : <NUM_LIT:0> )

/**
 * Helper function to instantiate [Metadata].
 * Contrary to a direct constructor call, this one accepts nullable parameters to substitute nulls with default values.
 * Also, this one does not accept [Metadata.bytecodeVersion] as it is deprecated.
 */


public fun AnyFrame . arrowWriter ( ) : ArrowWriter

= this . arrowWriter ( this . columns ( ) . toArrowSchema ( ) )

/**
 * Create [ArrowWriter] for [this] DataFrame with target schema matching actual data
 */


public fun AnyFrame . arrowWriter ( targetSchema : Schema , mode : ArrowWriter . Mode = ArrowWriter . Mode . STRICT , mismatchSubscriber : ( ConvertingMismatch ) -> Unit = ignoreMismatchMessage , ) : ArrowWriter

= ArrowWriter . create ( this , targetSchema , mode , mismatchSubscriber )

/**
 * Create [ArrowWriter] for [this] DataFrame with explicit [targetSchema].
 * If DataFrame does not match with [targetSchema], behaviour is specified by [mode], mismatches would be sent to [mismatchSubscriber]
 */


public fun AnyFrame . writeArrowIPC ( channel : WritableByteChannel )

{ <EOL> this . arrowWriter ( ) . use { writer -> <EOL> writer . writeArrowIPC ( channel ) <EOL> } <EOL> }

/**
 * Save data to [Arrow interprocess streaming format](https://arrow.apache.org/docs/java/ipc.html#writing-and-reading-streaming-format), write to opened [channel].
 */


public fun AnyFrame . writeArrowIPC ( stream : OutputStream )

{ <EOL> this . arrowWriter ( ) . use { writer -> <EOL> writer . writeArrowIPC ( stream ) <EOL> } <EOL> }

/**
 * Save data to [Arrow interprocess streaming format](https://arrow.apache.org/docs/java/ipc.html#writing-and-reading-streaming-format), write to opened [stream].
 */


public fun AnyFrame . writeArrowIPC ( file : File , append : Boolean = true )

{ <EOL> this . arrowWriter ( ) . use { writer -> <EOL> writer . writeArrowIPC ( file , append ) <EOL> } <EOL> }

/**
 * Save data to [Arrow interprocess streaming format](https://arrow.apache.org/docs/java/ipc.html#writing-and-reading-streaming-format), write to new or existing [file].
 * If file exists, it can be recreated or expanded.
 */


public fun AnyFrame . saveArrowIPCToByteArray ( ) : ByteArray

{ <EOL> return this . arrowWriter ( ) . use { writer -> <EOL> writer . saveArrowIPCToByteArray ( ) <EOL> } <EOL> }

/**
 * Save data to [Arrow interprocess streaming format](https://arrow.apache.org/docs/java/ipc.html#writing-and-reading-streaming-format), write to new [ByteArray]
 */


public fun AnyFrame . writeArrowFeather ( channel : WritableByteChannel )

{ <EOL> this . arrowWriter ( ) . use { writer -> <EOL> writer . writeArrowFeather ( channel ) <EOL> } <EOL> }

/**
 * Save data to [Arrow random access format](https://arrow.apache.org/docs/java/ipc.html#writing-and-reading-random-access-files), write to opened [channel].
 */


public fun AnyFrame . writeArrowFeather ( stream : OutputStream )

{ <EOL> this . arrowWriter ( ) . use { writer -> <EOL> writer . writeArrowFeather ( stream ) <EOL> } <EOL> }

/**
 * Save data to [Arrow random access format](https://arrow.apache.org/docs/java/ipc.html#writing-and-reading-random-access-files), write to opened [stream].
 */


public fun AnyFrame . writeArrowFeather ( file : File )

{ <EOL> this . arrowWriter ( ) . use { writer -> <EOL> writer . writeArrowFeather ( file ) <EOL> } <EOL> }

/**
 * Save data to [Arrow random access format](https://arrow.apache.org/docs/java/ipc.html#writing-and-reading-random-access-files), write to new or existing [file].
 * If file exists, it would be recreated.
 */


public fun AnyFrame . saveArrowFeatherToByteArray ( ) : ByteArray

{ <EOL> return this . arrowWriter ( ) . use { writer -> <EOL> writer . saveArrowFeatherToByteArray ( ) <EOL> } <EOL> }

/**
 * Save data to [Arrow random access format](https://arrow.apache.org/docs/java/ipc.html#writing-and-reading-random-access-files), write to new [ByteArray]
 */


protected fun doTestByKtFile ( ktFile : KtFile , testServices : TestServices )

{ <EOL> fun TextRange . asLineColumnRange ( ) : String { <EOL> return getLineAndColumnRangeInPsiFile ( ktFile , this ) . toString ( ) <EOL> } <EOL> analyseForTest ( ktFile ) { <EOL> val diagnosticsInFile = <EOL> ktFile . collectDiagnosticsForFile ( KtDiagnosticCheckerFilter . EXTENDED_AND_COMMON_CHECKERS ) . map { it . getKey ( ) } . sorted ( ) <EOL> val diagnosticsFromElements = buildList { <EOL> ktFile . accept ( object : KtTreeVisitorVoid ( ) { <EOL> override fun visitKtElement ( element : KtElement ) { <EOL> for ( diagnostic in element . getDiagnostics ( KtDiagnosticCheckerFilter . EXTENDED_AND_COMMON_CHECKERS ) ) { <EOL> add ( element to diagnostic . getKey ( ) ) <EOL> } <EOL> super . visitKtElement ( element ) <EOL> } <EOL> } ) <EOL> } . sortedBy { ( _ , diagnostic ) -> diagnostic } <EOL> val actual = buildString { <EOL> fun DiagnosticKey . print ( indent : Int ) { <EOL> val indentString = "<STR_LIT:U+0020>" . repeat ( indent ) <EOL> append ( indentString + factoryName ) <EOL> appendLine ( "<STR_LIT>" ) <EOL> appendLine ( "<STR_LIT>" ) <EOL> } <EOL> appendLine ( "<STR_LIT>" ) <EOL> for ( ( element , diagnostic ) in diagnosticsFromElements ) { <EOL> appendLine ( "<STR_LIT>" ) <EOL> diagnostic . print ( <NUM_LIT:4> ) <EOL> } <EOL> } <EOL> testServices . assertions . assertEqualsToTestDataFileSibling ( actual ) <EOL> assertEquals ( diagnosticsInFile , diagnosticsFromElements . map { ( _ , v ) -> v } , "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * [ktFile] may be a fake file for dangling module tests.
 */


protected fun compileLibrary ( libraryName : String , destination : File = File ( tmpdir , "<STR_LIT>" ) , additionalOptions : List < String > = emptyList ( ) , compileJava : ( sourceDir : File , javaFiles : List < File > , outputDir : File ) -> Boolean = { _ , javaFiles , outputDir -> <EOL> KotlinTestUtils . compileJavaFiles ( javaFiles , listOf ( "<STR_LIT:-d>" , outputDir . path ) ) <EOL> } , checkKotlinOutput : ( String ) -> Unit = { actual -> assertEquals ( normalizeOutput ( "<STR_LIT>" to ExitCode . OK ) , actual ) } , manifest : Manifest ? = null , extraClassPath : List < File > = emptyList ( ) ) : File

{ <EOL> val sourceDir = File ( testDataDirectory , libraryName ) <EOL> val javaFiles = FileUtil . findFilesByMask ( JAVA_FILES , sourceDir ) <EOL> val kotlinFiles = FileUtil . findFilesByMask ( KOTLIN_FILES , sourceDir ) <EOL> assert ( javaFiles . isNotEmpty ( ) || kotlinFiles . isNotEmpty ( ) ) { "<STR_LIT>" } <EOL> val isJar = destination . name . endsWith ( "<STR_LIT>" ) <EOL> val outputDir = if ( isJar ) File ( tmpdir , "<STR_LIT>" ) else destination <EOL> if ( kotlinFiles . isNotEmpty ( ) ) { <EOL> val output = compileKotlin ( libraryName , outputDir , extraClassPath , K2JVMCompiler ( ) , additionalOptions , expectedFileName = null ) <EOL> checkKotlinOutput ( normalizeOutput ( output ) ) <EOL> } <EOL> if ( javaFiles . isNotEmpty ( ) ) { <EOL> outputDir . mkdirs ( ) <EOL> if ( ! compileJava ( sourceDir , javaFiles , outputDir ) ) { <EOL> throw JavaCompilationError ( ) <EOL> } <EOL> } <EOL> if ( isJar ) { <EOL> destination . delete ( ) <EOL> val stream = <EOL> if ( manifest != null ) JarOutputStream ( destination . outputStream ( ) , manifest ) <EOL> else JarOutputStream ( destination . outputStream ( ) ) <EOL> stream . use { jar -> <EOL> ZipUtil . addDirToZipRecursively ( jar , destination , outputDir , "<STR_LIT>" , null , null ) <EOL> } <EOL> } else assertNull ( "<STR_LIT>" , manifest ) <EOL> return destination <EOL> }

/**
 * Compiles all sources (.java and .kt) under the directory named [libraryName] to [destination].
 * [destination] should be either a path to the directory under [tmpdir], or a path to the resulting .jar file (also under [tmpdir]).
 * Kotlin sources are compiled first, and there should be no errors or warnings. Java sources are compiled next.
 *
 * @return [destination]
 */


protected fun compileJsLibrary ( libraryName : String , additionalOptions : List < String > = emptyList ( ) , checkKotlinOutput : ( String ) -> Unit = { actual -> assertEquals ( normalizeOutput ( "<STR_LIT>" to ExitCode . OK ) , actual ) } ) : File

{ <EOL> val destination = File ( tmpdir , libraryName ) <EOL> val output = compileKotlin ( libraryName , destination , compiler = K2JSCompiler ( ) , additionalOptions = additionalOptions , expectedFileName = null ) <EOL> checkKotlinOutput ( normalizeOutput ( output ) ) <EOL> return destination <EOL> }

/**
 * Compiles all .kt sources under the directory named [libraryName] to a file named "[libraryName].js" in [tmpdir]
 *
 * @return the path to the corresponding .meta.js file, i.e. "[libraryName].meta.js"
 */


protected fun compileCommonLibrary ( libraryName : String , additionalOptions : List < String > = emptyList ( ) , checkKotlinOutput : ( String ) -> Unit = { actual -> assertEquals ( normalizeOutput ( "<STR_LIT>" to ExitCode . OK ) , actual ) } ) : File

{ <EOL> val destination = File ( tmpdir , libraryName ) <EOL> val output = compileKotlin ( libraryName , destination , compiler = K2MetadataCompiler ( ) , additionalOptions = additionalOptions , expectedFileName = null ) <EOL> checkKotlinOutput ( normalizeOutput ( output ) ) <EOL> return destination <EOL> }

/**
 * Compiles all .kt sources under the directory named [libraryName] to a directory named "[libraryName]" in [tmpdir]
 *
 * @return the path to the corresponding directory
 */


fun extract ( archive : File , targetDirectory : File , archiveType : ArchiveType )

/**
 * Extracts the contents of the specified archive file to the target directory.
 *
 * @param archive The archive file to extract.
 * @param targetDirectory The directory where the contents of the archive will be extracted to.
 * @param archiveType The type of the archive file.
 */


fun createDiagnosticReporter ( pluginId : String ) : IrMessageLogger

/**
 * Returns a logger instance to post diagnostic messages from plugin
 *
 * @param pluginId the unique plugin ID to make it easy to distinguish in log
 * @return the logger associated with specified ID
 */


public fun rxCompletable ( context : CoroutineContext = EmptyCoroutineContext , block : suspend CoroutineScope . ( ) -> Unit ) : Completable

{ <EOL> require ( context [ Job ] === null ) { "<STR_LIT>" + <EOL> "<STR_LIT>" } <EOL> return rxCompletableInternal ( GlobalScope , context , block ) <EOL> }

/**
 * Creates cold [Completable] that runs a given [block] in a coroutine and emits its result.
 * Every time the returned completable is subscribed, it starts a new coroutine.
 * Unsubscribing cancels running coroutine.
 * Coroutine context can be specified with [context] argument.
 * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used.
 * Method throws [IllegalArgumentException] if provided [context] contains a [Job] instance.
 */


@ Deprecated ( message = "<STR_LIT>" , level = DeprecationLevel . HIDDEN , replaceWith = ReplaceWith ( "<STR_LIT>" ) ) <EOL> public fun CoroutineScope . rxCompletable ( context : CoroutineContext = EmptyCoroutineContext , block : suspend CoroutineScope . ( ) -> Unit ) : Completable

= rxCompletableInternal ( this , context , block )


override fun add ( compilationResultCategory : Int , value : Serializable )

{ <EOL> when ( compilationResultCategory ) { <EOL> CompilationResultCategory . IC_COMPILE_ITERATION . code -> kotlinLogger . debug ( value as? CompileIterationResult , rootProjectDir ) <EOL> else -> kotlinLogger . debug ( "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Possible combinations:
 * 1. [CompilationResultCategory.IC_COMPILE_ITERATION.code] -> a [CompileIterationResult] instance
 * 2. [CompilationResultCategory.BUILD_REPORT_LINES.code] -> a [List] of [String]
 * 3. [CompilationResultCategory.VERBOSE_BUILD_REPORT_LINES.code] -> a [List] of [String]
 * 4. [CompilationResultCategory.BUILD_METRICS.code] -> a [BuildMetrics] instance
 **/


internal fun plus ( value : Int , unit : DateTimeUnit . DateBased ) : ZonedDateTime

= dateTime . plus ( value , unit ) . resolve ( )

/**
 * @throws IllegalArgumentException if the result exceeds the boundaries
 * @throws ArithmeticException if arithmetic overflow occurs
 */


internal fun ZonedDateTime . until ( other : ZonedDateTime , unit : DateTimeUnit ) : Long

= <EOL> when ( unit ) { <EOL> is DateTimeUnit . DateBased -> dateTime . until ( other . dateTime , unit ) . toLong ( ) <EOL> is DateTimeUnit . TimeBased -> { <EOL> val offsetDiff = offset . totalSeconds - other . offset . totalSeconds <EOL> val otherLdtAdjusted = try { <EOL> other . dateTime . plusSeconds ( offsetDiff ) <EOL> } catch ( e : IllegalArgumentException ) { <EOL> throw DateTimeArithmeticException ( "<STR_LIT>" ) <EOL> } <EOL> dateTime . until ( otherLdtAdjusted , unit ) <EOL> } <EOL> }

/**
 * @throws ArithmeticException on arithmetic overflow
 * @throws DateTimeArithmeticException if setting [other] to the offset of [this] leads to exceeding boundaries of
 * [LocalDateTime].
 */


override fun createCandidate ( towerCandidate : CandidateWithBoundDispatchReceiver , explicitReceiverKind : ExplicitReceiverKind , extensionReceiverCandidates : List < ReceiverValueWithSmartCastInfo > ) : CallableReferenceResolutionCandidate

= <EOL> error ( "<STR_LIT>" )

/**
 * The function is called only inside [NoExplicitReceiverScopeTowerProcessor] with [TowerData.BothTowerLevelAndContextReceiversGroup].
 * This case involves only [SimpleCandidateFactory].
 */


@ FlowPreview <EOL> public fun < T > Flow < T > . debounce ( timeoutMillis : Long ) : Flow < T >

{ <EOL> require ( timeoutMillis >= <NUM_LIT:0L> ) { "<STR_LIT>" } <EOL> if ( timeoutMillis == <NUM_LIT:0L> ) return this <EOL> return debounceInternal { timeoutMillis } <EOL> }

/**
 * Returns a flow that mirrors the original flow, but filters out values
 * that are followed by the newer values within the given [timeout][timeoutMillis].
 * The latest value is always emitted.
 *
 * Example:
 *
 * ```kotlin
 * flow {
 * emit(1)
 * delay(90)
 * emit(2)
 * delay(90)
 * emit(3)
 * delay(1010)
 * emit(4)
 * delay(1010)
 * emit(5)
 * }.debounce(1000)
 * ```
 * <!--- KNIT example-delay-01.kt -->
 *
 * produces the following emissions
 *
 * ```text
 * 3, 4, 5
 * ```
 * <!--- TEST -->
 *
 * Note that the resulting flow does not emit anything as long as the original flow emits
 * items faster than every [timeoutMillis] milliseconds.
 */


@ FlowPreview <EOL> @ OverloadResolutionByLambdaReturnType <EOL> public fun < T > Flow < T > . debounce ( timeoutMillis : ( T ) -> Long ) : Flow < T >

= <EOL> debounceInternal ( timeoutMillis )

/**
 * Returns a flow that mirrors the original flow, but filters out values
 * that are followed by the newer values within the given [timeout][timeoutMillis].
 * The latest value is always emitted.
 *
 * A variation of [debounce] that allows specifying the timeout value dynamically.
 *
 * Example:
 *
 * ```kotlin
 * flow {
 * emit(1)
 * delay(90)
 * emit(2)
 * delay(90)
 * emit(3)
 * delay(1010)
 * emit(4)
 * delay(1010)
 * emit(5)
 * }.debounce {
 * if (it == 1) {
 * 0L
 * } else {
 * 1000L
 * }
 * }
 * ```
 * <!--- KNIT example-delay-02.kt -->
 *
 * produces the following emissions
 *
 * ```text
 * 1, 3, 4, 5
 * ```
 * <!--- TEST -->
 *
 * Note that the resulting flow does not emit anything as long as the original flow emits
 * items faster than every [timeoutMillis] milliseconds.
 *
 * @param timeoutMillis [T] is the emitted value and the return value is timeout in milliseconds.
 */


@ FlowPreview <EOL> public fun < T > Flow < T > . debounce ( timeout : Duration ) : Flow < T >

= <EOL> debounce ( timeout . toDelayMillis ( ) )

/**
 * Returns a flow that mirrors the original flow, but filters out values
 * that are followed by the newer values within the given [timeout].
 * The latest value is always emitted.
 *
 * Example:
 *
 * ```kotlin
 * flow {
 * emit(1)
 * delay(90.milliseconds)
 * emit(2)
 * delay(90.milliseconds)
 * emit(3)
 * delay(1010.milliseconds)
 * emit(4)
 * delay(1010.milliseconds)
 * emit(5)
 * }.debounce(1000.milliseconds)
 * ```
 * <!--- KNIT example-delay-duration-01.kt -->
 *
 * produces the following emissions
 *
 * ```text
 * 3, 4, 5
 * ```
 * <!--- TEST -->
 *
 * Note that the resulting flow does not emit anything as long as the original flow emits
 * items faster than every [timeout] milliseconds.
 */


@ FlowPreview <EOL> @ JvmName ( "<STR_LIT>" ) <EOL> @ OverloadResolutionByLambdaReturnType <EOL> public fun < T > Flow < T > . debounce ( timeout : ( T ) -> Duration ) : Flow < T >

= <EOL> debounceInternal { emittedItem -> <EOL> timeout ( emittedItem ) . toDelayMillis ( ) <EOL> }

/**
 * Returns a flow that mirrors the original flow, but filters out values
 * that are followed by the newer values within the given [timeout].
 * The latest value is always emitted.
 *
 * A variation of [debounce] that allows specifying the timeout value dynamically.
 *
 * Example:
 *
 * ```kotlin
 * flow {
 * emit(1)
 * delay(90.milliseconds)
 * emit(2)
 * delay(90.milliseconds)
 * emit(3)
 * delay(1010.milliseconds)
 * emit(4)
 * delay(1010.milliseconds)
 * emit(5)
 * }.debounce {
 * if (it == 1) {
 * 0.milliseconds
 * } else {
 * 1000.milliseconds
 * }
 * }
 * ```
 * <!--- KNIT example-delay-duration-02.kt -->
 *
 * produces the following emissions
 *
 * ```text
 * 1, 3, 4, 5
 * ```
 * <!--- TEST -->
 *
 * Note that the resulting flow does not emit anything as long as the original flow emits
 * items faster than every [timeout] unit.
 *
 * @param timeout [T] is the emitted value and the return value is timeout in [Duration].
 */


@ FlowPreview <EOL> public fun < T > Flow < T > . sample ( periodMillis : Long ) : Flow < T >

{ <EOL> require ( periodMillis > <NUM_LIT:0> ) { "<STR_LIT>" } <EOL> return scopedFlow { downstream -> <EOL> val values = produce ( capacity = Channel . CONFLATED ) { <EOL> collect { value -> send ( value ? : NULL ) } <EOL> } <EOL> var lastValue : Any ? = null <EOL> val ticker = fixedPeriodTicker ( periodMillis ) <EOL> while ( lastValue !== DONE ) { <EOL> select < Unit > { <EOL> values . onReceiveCatching { result -> <EOL> result <EOL> . onSuccess { lastValue = it } <EOL> . onFailure { <EOL> it ? . let { throw it } <EOL> ticker . cancel ( ChildCancelledException ( ) ) <EOL> lastValue = DONE <EOL> } <EOL> } <EOL> ticker . onReceive { <EOL> val value = lastValue ? : return@onReceive <EOL> lastValue = null <EOL> downstream . emit ( NULL . unbox ( value ) ) <EOL> } <EOL> } <EOL> } <EOL> } <EOL> }

/**
 * Returns a flow that emits only the latest value emitted by the original flow during the given sampling [period][periodMillis].
 *
 * Example:
 *
 * ```kotlin
 * flow {
 * repeat(10) {
 * emit(it)
 * delay(110)
 * }
 * }.sample(200)
 * ```
 * <!--- KNIT example-delay-03.kt -->
 *
 * produces the following emissions
 *
 * ```text
 * 1, 3, 5, 7, 9
 * ```
 * <!--- TEST -->
 *
 * Note that the latest element is not emitted if it does not fit into the sampling window.
 */


@ FlowPreview <EOL> public fun < T > Flow < T > . sample ( period : Duration ) : Flow < T >

= sample ( period . toDelayMillis ( ) )

/**
 * Returns a flow that emits only the latest value emitted by the original flow during the given sampling [period].
 *
 * Example:
 *
 * ```kotlin
 * flow {
 * repeat(10) {
 * emit(it)
 * delay(110.milliseconds)
 * }
 * }.sample(200.milliseconds)
 * ```
 * <!--- KNIT example-delay-duration-03.kt -->
 *
 * produces the following emissions
 *
 * ```text
 * 1, 3, 5, 7, 9
 * ```
 * <!--- TEST -->
 *
 * Note that the latest element is not emitted if it does not fit into the sampling window.
 */


@ FlowPreview <EOL> public fun < T > Flow < T > . timeout ( timeout : Duration ) : Flow < T >

= timeoutInternal ( timeout )

/**
 * Returns a flow that will emit a [TimeoutCancellationException] if the upstream doesn't emit an item within the given time.
 *
 * Example:
 *
 * ```kotlin
 * flow {
 * emit(1)
 * delay(100)
 * emit(2)
 * delay(100)
 * emit(3)
 * delay(1000)
 * emit(4)
 * }.timeout(100.milliseconds).catch { exception ->
 * if (exception is TimeoutCancellationException) {
 * // Catch the TimeoutCancellationException emitted above.
 * // Emit desired item on timeout.
 * emit(-1)
 * } else {
 * // Throw other exceptions.
 * throw exception
 * }
 * }.onEach {
 * delay(300) // This will not cause a timeout
 * }
 * ```
 * <!--- KNIT example-timeout-duration-01.kt -->
 *
 * produces the following emissions
 *
 * ```text
 * 1, 2, 3, -1
 * ```
 * <!--- TEST -->
 *
 * Note that delaying on the downstream doesn't trigger the timeout.
 *
 * @param timeout Timeout duration. If non-positive, the flow is timed out immediately
 */


internal fun < T > sortArrayWith ( array : Array < out T > , fromIndex : Int , toIndex : Int , comparator : Comparator < T > )

{ <EOL> if ( fromIndex < toIndex - <NUM_LIT:1> ) { <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> mergeSort ( array as Array < T > , fromIndex , toIndex - <NUM_LIT:1> , comparator ) <EOL> } <EOL> }

/**
 * Sorts the subarray specified by [fromIndex] (inclusive) and [toIndex] (exclusive) parameters
 * using the merge sort algorithm with the given [comparator].
 */


internal fun < T : Comparable < T > > sortArray ( array : Array < out T > , fromIndex : Int , toIndex : Int )

{ <EOL> if ( fromIndex < toIndex - <NUM_LIT:1> ) { <EOL> @ Suppress ( "<STR_LIT:UNCHECKED_CAST>" ) <EOL> mergeSort ( array as Array < T > , fromIndex , toIndex - <NUM_LIT:1> ) <EOL> } <EOL> }

/**
 * Sorts a subarray of [Comparable] elements specified by [fromIndex] (inclusive) and
 * [toIndex] (exclusive) parameters using the merge sort algorithm.
 */


internal fun sortArray ( array : ByteArray , fromIndex : Int , toIndex : Int )

= quickSort ( array , fromIndex , toIndex - <NUM_LIT:1> )

/**
 * Sorts the given array using qsort algorithm.
 */


internal fun systemProp ( propertyName : String , defaultValue : Boolean ) : Boolean

= systemProp ( propertyName ) ? . toBoolean ( ) ? : defaultValue

/**
 * Gets the system property indicated by the specified [property name][propertyName],
 * or returns [defaultValue] if there is no property with that key.
 *
 * **Note: this function should be used in JVM tests only, other platforms use the default value.**
 */


internal fun systemProp ( propertyName : String , defaultValue : Int , minValue : Int = <NUM_LIT:1> , maxValue : Int = Int . MAX_VALUE ) : Int

= systemProp ( propertyName , defaultValue . toLong ( ) , minValue . toLong ( ) , maxValue . toLong ( ) ) . toInt ( )

/**
 * Gets the system property indicated by the specified [property name][propertyName],
 * or returns [defaultValue] if there is no property with that key. It also checks that the result
 * is between [minValue] and [maxValue] (inclusively), throws [IllegalStateException] if it is not.
 *
 * **Note: this function should be used in JVM tests only, other platforms use the default value.**
 */


internal fun systemProp ( propertyName : String , defaultValue : Long , minValue : Long = <NUM_LIT:1> , maxValue : Long = Long . MAX_VALUE ) : Long

{ <EOL> val value = systemProp ( propertyName ) ? : return defaultValue <EOL> val parsed = value . toLongOrNull ( ) <EOL> ? : error ( "<STR_LIT>" ) <EOL> if ( parsed !in minValue .. maxValue ) { <EOL> error ( "<STR_LIT>" ) <EOL> } <EOL> return parsed <EOL> }


internal fun systemProp ( propertyName : String , defaultValue : String ) : String

= systemProp ( propertyName ) ? : defaultValue


internal expect fun systemProp ( propertyName : String ) : String ?

/**
 * Gets the system property indicated by the specified [property name][propertyName],
 * or returns `null` if there is no property with that key.
 *
 * **Note: this function should be used in JVM tests only, other platforms use the default value.**
 */


protected fun assertContainsFilePaths ( outputFiles : List < File > , expectedFilePaths : List < Regex > )

{ <EOL> expectedFilePaths . forEach { pathRegex -> <EOL> assertNotNull ( outputFiles . any { it . absolutePath . contains ( pathRegex ) } , "<STR_LIT>" ) <EOL> } <EOL> }

/**
 * Check that [outputFiles] contain specific file paths provided in [expectedFilePaths].
 * Can be used for checking whether expected folders/pages have been created.
 */


fun gradleKtsProjectTest ( testProjectName : String , baseDir : Path = GradleProjectTest . funcTestTempDir , build : GradleProjectTest . ( ) -> Unit , ) : GradleProjectTest

{ <EOL> return GradleProjectTest ( baseDir = baseDir , testProjectName = testProjectName ) . apply { <EOL> settingsGradleKts = """<STR_LIT>""" . trimMargin ( ) <EOL> gradleProperties = """<STR_LIT>""" . trimMargin ( ) <EOL> build ( ) <EOL> } <EOL> }

/**
 * Builder for testing a Gradle project that uses Kotlin script DSL and creates default
 * `settings.gradle.kts` and `gradle.properties` files.
 *
 * @param[testProjectName] the path of the project directory, relative to [baseDir
 */


fun gradleGroovyProjectTest ( testProjectName : String , baseDir : Path = GradleProjectTest . funcTestTempDir , build : GradleProjectTest . ( ) -> Unit , ) : GradleProjectTest

{ <EOL> return GradleProjectTest ( baseDir = baseDir , testProjectName = testProjectName ) . apply { <EOL> settingsGradle = """<STR_LIT>""" . trimMargin ( ) <EOL> gradleProperties = """<STR_LIT>""" . trimMargin ( ) <EOL> build ( ) <EOL> } <EOL> }

/**
 * Builder for testing a Gradle project that uses Groovy script and creates default,
 * `settings.gradle`, and `gradle.properties` files.
 *
 * @param[testProjectName] the name of the test, which should be distinct across the project
 */


{ <EOL> gradle ( ) <EOL> ksp ( ) <EOL> }

/**
 * In this file we'll demonstrate how to use OpenApi schemas
 * to generate DataSchemas and how to use them.
 */


{ <EOL> val apis = ApiGuruOpenApiGradle . APIs . readJson ( "<STR_LIT>" ) <EOL> apis . print ( columnTypes = true , title = true , borders = true ) <EOL> apis . filter { <EOL> value . versions . value . any { <EOL> ( it . updated ? : it . added ) . year >= <NUM_LIT> <EOL> } <EOL> } <EOL> val metrics = <EOL> ApiGuruOpenApiGradle . Metrics . readJson ( "<STR_LIT>" ) <EOL> metrics . print ( columnTypes = true , title = true , borders = true ) <EOL> }

/**
 * Gradle example of reading JSON files with OpenApi schemas.
 * Ctrl+Click on [GradleAPIs] or [GradleMetrics] to see the generated code.
 *
 * (We use import aliases to avoid clashes with the KSP example)
 */


{ <EOL> val apis = ApiGuruOpenApiKsp . APIs . readJson ( "<STR_LIT>" ) <EOL> apis . print ( columnTypes = true , title = true , borders = true ) <EOL> val metrics = <EOL> ApiGuruOpenApiKsp . Metrics . readJson ( "<STR_LIT>" ) <EOL> metrics . print ( columnTypes = true , title = true , borders = true ) <EOL> }

/**
 * KSP example of reading JSON files with OpenApi schemas.
 * Ctrl+Click on [APIs] or [Metrics] to see the generated code.
 */


@ Test <EOL> fun readLargeNioBufferOnlyReadsOneSegment ( )

{ <EOL> val expected : String = if ( factory . isOneByteAtATime ) "<STR_LIT:a>" else "<STR_LIT:a>" . repeat ( SEGMENT_SIZE ) <EOL> sink . writeString ( "<STR_LIT:a>" . repeat ( SEGMENT_SIZE * <NUM_LIT:4> ) ) <EOL> sink . emit ( ) <EOL> val nioByteBuffer : ByteBuffer = ByteBuffer . allocate ( SEGMENT_SIZE * <NUM_LIT:3> ) <EOL> val byteCount : Int = source . readAtMostTo ( nioByteBuffer ) <EOL> assertEquals ( expected . length , byteCount ) <EOL> assertEquals ( expected . length , nioByteBuffer . position ( ) ) <EOL> assertEquals ( nioByteBuffer . capacity ( ) , nioByteBuffer . limit ( ) ) <EOL> ( nioByteBuffer as Buffer ) . flip ( ) <EOL> val data = ByteArray ( expected . length ) <EOL> nioByteBuffer . get ( data ) <EOL> assertEquals ( expected , String ( data ) ) <EOL> }

/** Note that this test crashes the VM on Android. */


override fun compareTo ( other : JvmMetadataVersion ) : Int

{ <EOL> val majors = major . compareTo ( other . major ) <EOL> if ( majors != <NUM_LIT:0> ) return majors <EOL> val minors = minor . compareTo ( other . minor ) <EOL> return if ( minors != <NUM_LIT:0> ) minors else patch . compareTo ( other . patch ) <EOL> }

/**
 * Compares this JvmMetadataVersion object with another JvmMetadataVersion object.
 *
 * Comparison is based on integer values of version parts with [major] being most significant one, then [minor], and finally [patch].
 *
 * @return a negative integer, zero, or a positive integer if this JvmMetadataVersion object is less than, equal to, or greater than [other].
 */


= "<STR_LIT>"

/**
 * Returns a string representation of the version number.
 * The string representation is in the format "major.minor.patch".
 */


{ <EOL> var result = major <EOL> result = <NUM_LIT:31> * result + minor <EOL> result = <NUM_LIT:31> * result + patch <EOL> return result <EOL> }

/**
 * Calculates the hash code value for the object based on major, minor, and patch components.
 */


override fun equals ( other : Any ? ) : Boolean

{ <EOL> if ( this === other ) return true <EOL> if ( javaClass != other ? . javaClass ) return false <EOL> other as JvmMetadataVersion <EOL> if ( major != other . major ) return false <EOL> if ( minor != other . minor ) return false <EOL> if ( patch != other . patch ) return false <EOL> return true <EOL> }

/**
 * Checks if this JvmMetadataVersion object is equal to [other] JvmMetadataVersion object.
 *
 * Instances of JvmMetadataVersion are equal if they have the same major, minor, and patch components.
 */


fun annotationProcessor ( fqName : String )

/**
 * Adds annotation processor with the specified [fqName] to the list of processors to run.
 */


fun annotationProcessors ( vararg fqName : String )

/**
 * Adds annotation processors with the specified [fqName] to the list of processors to run.
 */


fun arguments ( action : KaptArguments . ( ) -> Unit )

/**
 * Configure [KaptArguments] used for annotation processing.
 */


fun arguments ( action : Action < KaptArguments > )

{ <EOL> arguments { action . execute ( this ) } <EOL> }

/**
 * Configures the [KaptArguments] used for annotation processing.
 */


fun javacOptions ( action : KaptJavacOption . ( ) -> Unit )

/**
 * Configures the [KaptJavacOption] used for annotation processing.
 */


fun javacOptions ( action : Action < KaptJavacOption > )

{ <EOL> javacOptions { action . execute ( this ) } <EOL> }


fun getJavacOptions ( ) : Map < String , String >

/**
 * Gets all the javac options used to run kapt annotation processing.
 */


fun arg ( name : Any , vararg values : Any )

/**
 * Adds argument with the specified name and values.
 *
 * Expected [name] and [values] type is [String].
 */


fun option ( name : Any , value : Any )

/**
 * Adds an option with name and value.
 *
 * Expected [name] and [value] type is [String].
 */


fun option ( name : Any )

/**
 * Adds an option with name only.
 *
 * Expected [name] type is [String].
 */


@ JvmOverloads <EOL> public fun < T : Any > Flow < T > . asFlux ( context : CoroutineContext = EmptyCoroutineContext ) : Flux < T >

= <EOL> FlowAsFlux ( this , Dispatchers . Unconfined + context )

/**
 * Converts the given flow to a cold flux.
 * The original flow is cancelled when the flux subscriber is disposed.
 *
 * This function is integrated with [ReactorContext], see its documentation for additional details.
 *
 * An optional [context] can be specified to control the execution context of calls to [Subscriber] methods.
 * You can set a [CoroutineDispatcher] to confine them to a specific thread and/or various [ThreadContextElement] to
 * inject additional context into the caller thread. By default, the [Unconfined][Dispatchers.Unconfined] dispatcher
 * is used, so calls are performed from an arbitrary thread.
 */


public fun GraphTrainableModel . saveModelConfiguration ( jsonConfigFile : File , isKerasFullyCompatible : Boolean = false )

{ <EOL> val kerasModel = serializeModel ( isKerasFullyCompatible ) <EOL> val jsonString2 = Klaxon ( ) <EOL> . converter ( PaddingConverter ( ) ) <EOL> . toJsonString ( kerasModel ) <EOL> jsonConfigFile . writeText ( jsonString2 , Charsets . UTF_8 ) <EOL> }

/**
 * Saves model description as json configuration file fully compatible with the Keras TensorFlow framework.
 *
 * @param jsonConfigFile File to write model configuration.
 * @param isKerasFullyCompatible If true, it generates fully Keras-compatible configuration.
 */


private fun createKerasGlobalAvgPool2DLayer ( layer : GlobalAvgPool2D ) : KerasLayer

{ <EOL> val configX = LayerConfig ( dtype = DATATYPE_FLOAT32 , name = layer . name , trainable = layer . isTrainable ) <EOL> return KerasLayer ( class_name = LAYER_GLOBAL_AVG_POOL_2D , config = configX ) <EOL> }

/**
 * The layer creator functions for Keras should be put below.
 */


@ kotlin . internal . IntrinsicConstEvaluation <EOL> public fun String . trimMargin ( marginPrefix : String = "<STR_LIT>" ) : String

= <EOL> replaceIndentByMargin ( "<STR_LIT>" , marginPrefix )

/**
 * Trims leading whitespace characters followed by [marginPrefix] from every line of a source string and removes
 * the first and the last lines if they are blank (notice difference blank vs empty).
 *
 * Doesn't affect a line if it doesn't contain [marginPrefix] except the first and the last blank lines.
 *
 * Doesn't preserve the original line endings.
 *
 * @param marginPrefix non-blank string, which is used as a margin delimiter. Default is `|` (pipe character).
 *
 * @sample samples.text.Strings.trimMargin
 * @see trimIndent
 * @see kotlin.text.isWhitespace
 */


public fun String . replaceIndentByMargin ( newIndent : String = "<STR_LIT>" , marginPrefix : String = "<STR_LIT>" ) : String

{ <EOL> require ( marginPrefix . isNotBlank ( ) ) { "<STR_LIT>" } <EOL> val lines = lines ( ) <EOL> return lines . reindent ( length + newIndent . length * lines . size , getIndentFunction ( newIndent ) , { line -> <EOL> val firstNonWhitespaceIndex = line . indexOfFirst { ! it . isWhitespace ( ) } <EOL> when { <EOL> firstNonWhitespaceIndex == - <NUM_LIT:1> -> null <EOL> line . startsWith ( marginPrefix , firstNonWhitespaceIndex ) -> line . substring ( firstNonWhitespaceIndex + marginPrefix . length ) <EOL> else -> null <EOL> } <EOL> } ) <EOL> }

/**
 * Detects indent by [marginPrefix] as it does [trimMargin] and replace it with [newIndent].
 *
 * @param marginPrefix non-blank string, which is used as a margin delimiter. Default is `|` (pipe character).
 */


@ kotlin . internal . IntrinsicConstEvaluation <EOL> public fun String . trimIndent ( ) : String

= replaceIndent ( "<STR_LIT>" )

/**
 * Detects a common minimal indent of all the input lines, removes it from every line and also removes the first and the last
 * lines if they are blank (notice difference blank vs empty).
 *
 * Note that blank lines do not affect the detected indent level.
 *
 * In case if there are non-blank lines with no leading whitespace characters (no indent at all) then the
 * common indent is 0, and therefore this function doesn't change the indentation.
 *
 * Doesn't preserve the original line endings.
 *
 * @sample samples.text.Strings.trimIndent
 * @see trimMargin
 * @see kotlin.text.isBlank
 */


public fun String . replaceIndent ( newIndent : String = "<STR_LIT>" ) : String

{ <EOL> val lines = lines ( ) <EOL> val minCommonIndent = lines <EOL> . filter ( String :: isNotBlank ) <EOL> . map ( String :: indentWidth ) <EOL> . minOrNull ( ) ? : <NUM_LIT:0> <EOL> return lines . reindent ( length + newIndent . length * lines . size , getIndentFunction ( newIndent ) , { line -> line . drop ( minCommonIndent ) } ) <EOL> }

/**
 * Detects a common minimal indent like it does [trimIndent] and replaces it with the specified [newIndent].
 */


public fun String . prependIndent ( indent : String = "<STR_LIT>" ) : String

= <EOL> lineSequence ( ) <EOL> . map { <EOL> when { <EOL> it . isBlank ( ) -> { <EOL> when { <EOL> it . length < indent . length -> indent <EOL> else -> it <EOL> } <EOL> } <EOL> else -> indent + it <EOL> } <EOL> } <EOL> . joinToString ( "<STR_LIT:\n>" )

/**
 * Prepends [indent] to every line of the original string.
 *
 * Doesn't preserve the original line endings.
 */


private fun assertMapping ( aes : Aes , columnID : String , parameters : MappingParameters , result : Mapping )

{ <EOL> assertEquals ( aes , result . aes ) <EOL> assertEquals ( columnID , result . columnID ) <EOL> assertEquals ( parameters , result . parameters ) <EOL> assertEquals ( bindingContext . bindingCollector . mappings [ aes ] , result ) <EOL> }

/**
 * Assertion method to compare the given mapping parameters to the expected result.
 *
 * @param aes The AES name to compare with the mapping result.
 * @param columnID The column ID to compare with the mapping result.
 * @param parameters The mapping parameters to compare with the mapping result.
 * @param result The actual mapping result.
 */


abstract fun computeReturnType ( declaration : FirCallableDeclaration ) : FirTypeRef ?

/**
 * Returns the [FirTypeRef] for [FirCallableDeclaration.returnTypeRef] of the [declaration].
 *
 * Depending on the implementation, this call might invoke a deferred computation of the return type
 * (see [FirDeclarationAttributes.deferredCallableCopyReturnType]).
 *
 * A return value of `null` signifies that the calculation has failed or that no deferred computation was stored
 * and the return type could not be resolved ordinarily.
 */


abstract fun computeReturnType ( calc : CallableCopyTypeCalculator ) : ConeKotlinType ?

/**
 * Performs a deferred computation some declaration's return type.
 *
 * [calc] must be used for the return type calculation of overridden members which might recursively trigger the computation of
 * deferred return types.
 */


fun getLightClassMethod ( parameter : KtParameter ) : PsiMethod ?

{ <EOL> return getPsiMethodWrapper ( parameter ) <EOL> }

/**
 * Returns the light method generated from the parameter of an annotation class.
 */


public fun addBinaryRoot ( root : Path )

{ <EOL> binaryRoots . add ( root ) <EOL> }

/**
 * Adds a [root] to the current library.
 *
 * The [root] can be:
 * * A .jar file for JVM libraries or common metadata KLibs
 * * A directory with a set of .classfiles for JVM Libraries
 * * A Kotlin/Native, Kotlin/Common, Kotlin/JS KLib.
 * In this case, all KLib dependencies should be provided together with the KLib itself.
 */


public fun addBinaryRoots ( roots : Collection < Path > )

{ <EOL> binaryRoots . addAll ( roots ) <EOL> }

/**
 * Adds a collection of [roots] to the current library.
 *
 * See [addBinaryRoot] for details
 *
 * @see addBinaryRoot for details
 */


/**
 * [kotlin.LazyThreadSafetyMode.PUB<caret>LICATION]
 */


= runBlocking { <EOL> repeat ( N_REPEATS ) { <EOL> val result = withTimeout ( <NUM_LIT> ) { <EOL> val job = launch ( Dispatchers . Default ) { <EOL> } <EOL> job . join ( ) <EOL> "<STR_LIT>" <EOL> } <EOL> assertEquals ( "<STR_LIT>" , result ) <EOL> } <EOL> }

/**
 * This stress-test makes sure that dispatching resumption from within withTimeout
 * works appropriately (without additional dispatch) despite the presence of
 * children coroutine in a different dispatcher.
 */


fun sourceLink ( action : Action < in DokkaSourceLinkSpec > )

{ <EOL> sourceLinks . add ( objects . newInstance ( DokkaSourceLinkSpec :: class ) . also { <EOL> action . execute ( it ) <EOL> } ) <EOL> }

/**
 * Configure and add a new source link to [sourceLinks].
 *
 * @see DokkaSourceLinkSpec
 */


fun perPackageOption ( action : Action < in DokkaPackageOptionsSpec > )

{ <EOL> perPackageOptions . add ( objects . newInstance ( DokkaPackageOptionsSpec :: class ) . also { <EOL> action . execute ( it ) <EOL> } ) <EOL> }

/**
 * Action for configuring package options, appending to [perPackageOptions].
 *
 * @see DokkaPackageOptionsSpec
 */


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


private fun findDisplayOffset ( expression : IrExpression , sourceRangeInfo : SourceRangeInfo , source : String , ) : Int

{ <EOL> return when ( expression ) { <EOL> is IrMemberAccessExpression < * > -> memberAccessOffset ( expression , sourceRangeInfo , source ) <EOL> is IrTypeOperatorCall -> typeOperatorOffset ( expression , sourceRangeInfo , source ) <EOL> else -> <NUM_LIT:0> <EOL> } <EOL> }

/**
 * Responsible for determining the diagram display offset of the expression
 * beginning from the startOffset of the expression.
 *
 * Equality:
 * ```
 * number == 42
 * | <- startOffset
 * | <- display offset: 7
 * ```
 *
 * Arithmetic:
 * ```
 * i + 2
 * | <- startOffset
 * | <- display offset: 2
 * ```
 *
 * Infix:
 * ```
 * 1 shl 2
 * | <- startOffset
 * | <- display offset: 2
 * ```
 *
 * Standard:
 * ```
 * 1.shl(2)
 * | <- startOffset
 * | <- display offset: 0
 * ```
 */


private fun binaryOperatorOffset ( lhs : IrExpression , wholeOperatorSourceRangeInfo : SourceRangeInfo , wholeOperatorSource : String ) : Int

{ <EOL> val offset = lhs . endOffset - wholeOperatorSourceRangeInfo . startOffset <EOL> if ( offset < <NUM_LIT:0> || offset >= wholeOperatorSource . length ) return <NUM_LIT:0> <EOL> KotlinLexer ( ) . run { <EOL> start ( wholeOperatorSource , offset , wholeOperatorSource . length ) <EOL> while ( tokenType != null && tokenType != KtTokens . EOF && ( tokenType == KtTokens . DOT || tokenType !in KtTokens . OPERATIONS ) ) { <EOL> advance ( ) <EOL> } <EOL> if ( tokenStart >= wholeOperatorSource . length ) return <NUM_LIT:0> <EOL> return tokenStart <EOL> } <EOL> }

/**
 * The offset of the infix operator/function token itself.
 *
 * @param lhs The left-hand side expression of the operator.
 * @param wholeOperatorSourceRangeInfo The source range of the whole operator expression.
 * @param wholeOperatorSource The source text of the whole operator expression.
 */


private fun IrMemberAccessExpression < * > . binaryOperatorLhs ( ) : IrExpression ?

= when ( origin ) { <EOL> IrStatementOrigin . EXCLEQ -> { <EOL> ( dispatchReceiver as? IrCall ) ? . simpleBinaryOperatorLhs ( ) <EOL> } <EOL> IrStatementOrigin . EXCLEQEQ -> { <EOL> ( dispatchReceiver as? IrCall ) ? . simpleBinaryOperatorLhs ( ) <EOL> } <EOL> IrStatementOrigin . IN -> { <EOL> getValueArgument ( <NUM_LIT:0> ) <EOL> } <EOL> IrStatementOrigin . NOT_IN -> { <EOL> ( dispatchReceiver as? IrCall ) ? . getValueArgument ( <NUM_LIT:0> ) <EOL> } <EOL> else -> simpleBinaryOperatorLhs ( ) <EOL> }

/**
 * The left-hand side expression of an infix operator/function that takes into account special cases like `in`, `!in` and `!=` operators
 * that have a more complex structure than just a single call with two arguments.
 */