# Kotlin Language Server

[![Release](https://img.shields.io/github/release/fwcd/kotlin-language-server)](https://github.com/fwcd/kotlin-language-server/releases)
[![Build](https://github.com/fwcd/kotlin-language-server/actions/workflows/build.yml/badge.svg)](https://github.com/fwcd/kotlin-language-server/actions/workflows/build.yml)
[![Downloads](https://img.shields.io/github/downloads/fwcd/kotlin-language-server/total)](https://github.com/fwcd/kotlin-language-server/releases)
[![Chat](https://img.shields.io/badge/chat-on%20discord-7289da)](https://discord.gg/cNtppzN)

A [language server](https://microsoft.github.io/language-server-protocol/) that provides smart code completion, diagnostics, hover, document symbols, definition lookup, method signature help and more for [Kotlin](https://kotlinlang.org).

![Icon](Icon128.png)

Any editor conforming to LSP is supported, including [VSCode](https://github.com/fwcd/vscode-kotlin) and [Atom](https://github.com/fwcd/atom-ide-kotlin).

## Getting Started

* See [BUILDING.md](BUILDING.md) for build instructions
* See [Editor Integration](EDITORS.md) for editor-specific instructions
* See [Troubleshooting](TROUBLESHOOTING.md) for tips on troubleshooting errors
* See [Roadmap](https://github.com/fwcd/kotlin-language-server/projects/1) for features, planned additions, bugfixes and changes
* See [Kotlin Quick Start](https://github.com/fwcd/kotlin-quick-start) for a sample project
* See [Kotlin Debug Adapter](https://github.com/fwcd/kotlin-debug-adapter) for editor-agnostic launch and debug support of Kotlin/JVM programs
* See [tree-sitter-kotlin](https://github.com/fwcd/tree-sitter-kotlin) for an experimental [Tree-Sitter](https://tree-sitter.github.io/tree-sitter/) grammar

## Packaging

[![Packaging status](https://repology.org/badge/vertical-allrepos/kotlin-language-server.svg)](https://repology.org/project/kotlin-language-server/versions)

## This repository needs your help!

[The original author](https://github.com/georgewfraser) created this project while he was considering using Kotlin in his work. He ended up deciding not to and is not really using Kotlin these days though this is a pretty fully-functional language server that just needs someone to use it every day for a while and iron out the last few pesky bugs.

There are two hard parts of implementing a language server:
- Figuring out the dependencies
- Incrementally re-compiling as the user types

The project uses the internal APIs of the [Kotlin compiler](https://github.com/JetBrains/kotlin/tree/master/compiler).

### Figuring out the dependencies

Dependencies are determined by the [DefaultClassPathResolver.kt](shared/src/main/kotlin/org/javacs/kt/classpath/DefaultClassPathResolver.kt), which invokes Maven or Gradle to get a list of classpath JARs. Alternatively, projects can also 'manually' provide a list of dependencies through a shell script, located either at `[project root]/kls-classpath` or `[config root]/kotlin-language-server/classpath`, which outputs a list of JARs. Depending on your platform, the scripts also can be suffixed with `.{sh,bat,cmd}`.

* Example of the `~/.config/kotlin-language-server/classpath` on Linux:
```bash
#!/bin/bash
echo /my/path/kotlin-compiler-1.4.10/lib/kotlin-stdlib.jar:/my/path/my-lib.jar
```

* Example of the `%HOMEPATH%\.config\kotlin-language-server\classpath.bat` on Windows:
```cmd
@echo off
echo C:\my\path\kotlin-compiler-1.4.10\lib\kotlin-stdlib.jar;C:\my\path\my-lib.jar
```

### Incrementally re-compiling as the user types

I get incremental compilation at the file-level by keeping the same `KotlinCoreEnvironment` alive between compilations in [Compiler.kt](server/src/main/kotlin/org/javacs/kt/compiler/Compiler.kt). There is a performance benchmark in [OneFilePerformance.kt](server/src/test/kotlin/org/javacs/kt/OneFilePerformance.kt) that verifies this works.

Getting incremental compilation at the expression level is a bit more complicated:
- Fully compile a file and store in [CompiledFile](server/src/main/kotlin/org/javacs/kt/CompiledFile.kt):
    - `val content: String` A snapshot of the source code
    - `val parse: KtFile` The parsed AST
    - `val compile: BindingContext` Additional information about the AST from typechecking
- After the user edits the file:
    - Find the smallest section the encompasses all the user changes
    - Get the `LexicalScope` encompassing this region from the `BindingContext` that was generated by the full-compile
    - Create a fake, in-memory .kt file with just the expression we want to re-compile
        - [Add space](https://github.com/fwcd/kotlin-language-server/blob/427cfa7a688d6d2ff202625ebad1ea605e3b8c37/server/src/main/kotlin/org/javacs/kt/CompiledFile.kt#L125) at the top of the file so the line numbers match up
    - Re-compile this tiny fake file

The incremental expression compilation logic is all in [CompiledFile.kt](server/src/main/kotlin/org/javacs/kt/CompiledFile.kt). The Kotlin AST has a built-in repair API, which seems to be how IntelliJ works, but as far as I can tell this API does not work if the surrounding IntelliJ machinery is not present. Hence I created the "fake tiny file" incremental-compilation mechanism, which seems to be quite fast and predictable.

There is an extensive suite of behavioral [tests](server/src/test/kotlin/org/javacs/kt), which are all implemented in terms of the language server protocol, so you should be able to refactor the code any way you like and the tests should still work.

## Modules

| Name | Description |
| ---- | ----------- |
| server | The language server executable |
| shared | Classpath resolution and utilities |

## Scripts

| Name | Command | Description |
| ---- | ------- | ----------- |
| release_version.py | `python3 scripts/release_version.py` | Creates a tag for the current version and bumps the development version |

## Protocol Extensions

The Kotlin language server supports some non-standard requests through LSP. See [KotlinProtocolExtensions](server/src/main/kotlin/org/javacs/kt/KotlinProtocolExtensions.kt) for a description of the interface. The general syntax for these methods is `kotlin/someCustomMethod`.

## Initialization Options

The Kotlin language server supports some custom initialization options via the `initializationOptions` property in the `initialize` request parameters. See `InitializationOptions` in [Configuration](server/src/main/kotlin/org/javacs/kt/Configuration.kt) for a list of supported properties.

## Features

### Autocomplete
![Autocomplete](images/Autocomplete.png)

### Signature help
![Signature Help](images/SignatureHelp.png)

### Hover
![Hover](images/Hover.png)

### Go-to-definition, find all references
![Find all references](images/FindAllReferences.png)

### Document symbols
![Document symbols](images/DocumentSymbols.png)

### Global symbols
![Global symbols](images/GlobalSymbols.png)

## Authors
* [georgewfraser](https://github.com/georgewfraser)
* [fwcd](https://github.com/fwcd)


# Zally: A minimalistic, simple-to-use OpenAPI 2 and 3 linter

[![Build Status](https://travis-ci.org/zalando/zally.svg?branch=master)](https://travis-ci.org/zalando/zally)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/05a7515011504c06b1cb35ede27ac7d4)](https://www.codacy.com/app/zally/zally?utm_source=github.com&utm_medium=referral&utm_content=zalando/zally&utm_campaign=Badge_Grade)
[![Join the chat at https://gitter.im/zalando/zally](https://badges.gitter.im/zalando/zally.svg)](https://gitter.im/zalando/zally?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

<img src="logo.png" width="200" height="200" />

Zally is a quality assurance tool. It's a linter for OpenAPI specifications,
it performs the following tasks :

- Increases the quality of APIs
- Checks compliance
- Delivers early feedback for API designers
- Ensures the same look-and-feel of APIs
- Supports [API-First approach](https://opensource.zalando.com/restful-api-guidelines/#100)
- Provides best practices and advices

Its standard configuration will check your APIs against the rules defined in
[Zalando's RESTful Guidelines](http://zalando.github.io/restful-api-guidelines/),
but anyone can use it **out-of-the-box**.

Zally has an easy-to-use [CLI](cli/README.md) which uses the server in the background so that
you can check your API *on the spot*. It also features an intuitive
[Web UI](web-ui/README.md) that shows implemented rules and lints external files
and (with its online editor) API definitions.

## Features

- Support for OpenAPI 3 and (Swagger) OpenAPI 2 specifications
- RESTful API, CLI and Web interface
- Rich Check configuration
- Ignore functionality (`x-zally-ignore` extension)
- Java/Kotlin API for new Checks + helper functions

## Quick start guide

Trying out Zally is easy. You can build and run the whole Zally stack (web-ui, server
and database) by executing:

```bash
docker compose up -d
```

Web UI is accessible on `http://localhost:8080`; Zally server on `http://localhost:8000`

## Documentation and Manuals

Please consult the following documents for further information:

- [Zally Concepts](documentation/concepts.md)
- [How to operate](documentation/operation.md) Zally tools
- [How to use Zally](documentation/usage.md)
- [How to develop new Rules](documentation/rule-development.md)
- [Building Under Windows Subsystem for Linux](documentation/build-under-wsl.md)

## Integrations

- [Zally Maven Plugin](https://github.com/ethlo/zally-maven-plugin) (unofficial)

## Contributing to Zally

Zally welcomes contributions from the open source community. To get started, take a
look at our [contributing guidelines](CONTRIBUTING). Then check our
[Project Board](https://github.com/zalando/zally/projects/1) and
[Issues Tracker](https://github.com/zalando/zally/issues) for ideas.

## Contact

Feel free to join our [Gitter room](https://gitter.im/zalando/zally) or contact one
of the [maintainers](MAINTAINERS) directly.

## Alternatives

Zally is not the only linter for OpenAPI v2 and v3. There is [an article](https://nordicapis.com/8-openapi-linters/) comparing different OpenAPI linters.

So why should you choose Zally?
- It supports [Zalando's RESTful Guidelines](http://zalando.github.io/restful-api-guidelines/)
- It can be used in multiple ways: RESTful API, CLI and Web interface
- Highly customizable (with Kotlin)

## License

MIT license with an exception. See [license file](LICENSE).

## Publish

### Prerequisites

* [Signing plugin](https://docs.gradle.org/current/userguide/signing_plugin.htm) configured
* `OSSRH_JIRA_USERNAME` and `OSSRH_JIRA_PASSWORD` environment variables to access [Maven Central Repo](https://oss.sonatype.org/) are
configured

### Steps

1. Create a separate branch with a name `release-<release-version>`.
2. Update current version in `server/gradle.properties` from `-SNAPSHOT` to a final version.
3. Update mime types configuration:
   ```shell
      ./gradlew -q generate-media-types-config --info
   ```
4. Commit the updated file to the repository.
5. Release Zally server and API using the command
   ```
   cd server
   ./gradlew clean build publishAllPublicationsToMavenRepository
   ```
6. Commit `server/gradle.properties` with the release version
7. Create a tag
    ```shell script
    git tag v<release-version> -m "Version <release-version>"
    ```
8. Bump version in `server/gradle.properties` to the next `-SNAPSHOT`

9. Push `release` branch and tag
   ```shell script
    git push origin
    git push origin <tag-name>
   ```
10. Create a Pull Request with the version update
11. Create and publish a release with a new version in GitHub


  Neko

A Free, Open source unofficial manga reader for MangaDex

---

## About:
This is a MangaDex specific fork of Tachiyomi and TachiyomiJ2K. This contains features specific to Mangadex
 that those versions cannot offer. It also features almost every feature that J2K has except for other sources,local sources, and editting manga.

 **Note**: This fork is for Android 7+

## Specific features:
- Supports native login to MangaDex and 2FA
- Use MDList as  Tracker
- Similar Manga Recommendations
- Manually sync of Manga to and from Mangadex follows list
- Sync Followed Manga's read chapters from MangaDex into Neko automatically
- Filter by Scanlation Group in chapter list
- Look at an additional source for missing chapters not hosted on MangaDex
- Ability to attempt to merge missing chapters from MangaDex with another source
- And many more

## Download
Get the app from our [releases page](https://github.com/CarlosEsco/Neko/releases).

## Thanks
- Inorichi for making the original Tachiyomi
- Arkon Current maintainer of Tachiyomi
- Jays2Kings for the wonderful new UI of J2K
- GoldBattle for all the similar manga logic

## License

    Copyright 2015 Javier Tomás

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    Modifications copyright (C) 2019 Carlos Escobedo

## Disclaimer

The developer of this application does not have any affiliation with the content providers available.


[ ![Download](https://img.shields.io/maven-central/v/com.algolia/instantsearch-android?label=Download) ](https://search.maven.org/search?q=a:instantsearch-android)
[![Build Status](https://travis-ci.org/algolia/instantsearch-android.svg?branch=master)](https://travis-ci.org/algolia/instantsearch-android)

InstantSearch family: **InstantSearch Android** | [InstantSearch iOS][instantsearch-ios-github] | [React InstantSearch][react-instantsearch-github] | [InstantSearch.js][instantsearch-js-github] | [Angular InstantSearch][instantsearch-angular-github] | [Vue InstantSearch][instantsearch-vue-github].

**InstantSearch Android** is a library providing widgets and helpers to help you build the best instant-search experience on Android with Algolia.
It is built on top of Algolia's [Kotlin API Client][kotlin-client] to provide you a high-level solution to quickly build various search interfaces.

# Examples

You can see InstantSearch Android in action in our [examples app][examples-url], have a look at it to see concrete examples of all the available widgets.

# Usage

## Installing InstantSearch Android

You can add InstantSearch to your Android application by adding the following line to your build.gradle's dependencies:

```groovy
implementation "com.algolia:instantsearch-android:$instantsearch_version"
```

ℹ Please follow the [migration guide](docs/guide/Migration_2.x_3.x.md) to migrate from `2.x` to the latest version.
▶ See the [documentation][doc]. You can start with the [Getting Started Guide][getting-started].

  Compose

You can add [Compose UI](https://developer.android.com/jetpack/androidx/releases/compose-ui) support by adding the following line to your build.gradle's dependencies:

```groovy
implementation "com.algolia:instantsearch-compose:$instantsearch_version"
```

  Paging 3

You can add [Paging 3](https://developer.android.com/topic/libraries/architecture/paging/v3-overview) support by adding the following line to your build.gradle's dependencies:

```groovy
implementation "com.algolia:instantsearch-android-paging3:$instantsearch_version"
```

  Insights

You can add **InstantSearch Insights** to your Android application by adding the following line to your `build.gradle`'s dependencies.
```groovy
implementation "com.algolia:instantsearch-insights-android:$instantsearch_version"
```

Please refer to the [library](instantsearch-insights/README.md) for more details.

## Requirements

* Kotlin 1.6+
* Android SDK 21+
* Java 8+

### R8 / Proguard rules

If you use this library in an Android project which uses R8, there is nothing you have to do. The specific rules are
already bundled into the JAR, which can be interpreted by R8 automatically.

If however, you don’t use R8, then you might need rules from [Algolia Kotlin Client](https://github.com/algolia/algoliasearch-client-kotlin#r8--proguard-rules) which is a dependency of this library.

## Telemetry
InstantSearch Android collects data points at runtime. This helps the InstantSearch team improve and prioritize future development.

Here's an exhaustive list of the collected data:

- InstantSearch version
- The name of the instantiated InstantSearch components, for example, `HitsSearcher`, `FilterState`
- The name of the components with custom parameters (overridden defaults). InstantSearch doesn't collect the values of those parameters. For example, the default of the `facets` value in `FacetListInteractor` is an empty list. If you instantiate it with a list of facets, then the telemetry tracks that the `facets` parameter received a custom value, but not the value itself.

InstantSearch doesn't collect any sensitive or personal data. However, you can still opt out of the telemetry collection with the following code:
```kotlin
Telemetry.shared.enabled = false
```

## Contributing

From [reporting bugs or missing functionality](https://github.com/algolia/instantsearch-android/issues/new) to [fixing a typo or proposing an improvement](https://github.com/algolia/instantsearch-android/compare), all contributions are welcome! Read the [Contributing Guide](https://github.com/algolia/instantsearch-android/blob/master/CONTRIBUTING.md) to setup your development environment.

## Troubleshooting

Encountering an issue? Before reaching out to support, we recommend heading to our [FAQ](https://www.algolia.com/doc/guides/building-search-ui/troubleshooting/faq/android/) where you will find answers for the most common issues and gotchas with the library.

# License

InstantSearch Android is [licensed under Apache V2](LICENSE).

[doc]: https://algolia.com/doc/guides/building-search-ui/what-is-instantsearch/android/
[getting-started]: https://algolia.com/doc/guides/building-search-ui/getting-started/android/
[kotlin-client]: https://github.com/algolia/algoliasearch-client-kotlin
[showcase-url]: https://algolia.com/doc/guides/building-search-ui/widgets/showcase/android/
[examples-url]: /examples
[react-instantsearch-github]: https://github.com/algolia/react-instantsearch/
[instantsearch-ios-github]: https://github.com/algolia/instantsearch-ios
[instantsearch-js-github]: https://github.com/algolia/instantsearch.js
[instantsearch-vue-github]: https://github.com/algolia/vue-instantsearch
[instantsearch-angular-github]: https://github.com/algolia/angular-instantsearch


# OpenDC

Collaborative Datacenter Simulation and Exploration for Everybody

[![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](/LICENSE.txt)
[![Documentation](https://img.shields.io/badge/docs-master-green.svg)](https://atlarge-research.github.io/opendc)
[![GitHub release](https://img.shields.io/github/v/release/atlarge-research/opendc?include_prereleases)](https://github.com/atlarge-research/opendc/releases)
[![Build](https://github.com/atlarge-research/opendc/actions/workflows/build.yml/badge.svg)](https://github.com/atlarge-research/opendc/actions/workflows/build.yml)

-----

This repository is the home of the OpenDC project, a free and open-source platform for cloud datacenter simulation.

## Latest Release

- General Availability (GA): [OpenDC v2.0](https://github.com/atlarge-research/opendc/releases/tag/v2.0) (May 10, 2021)
- Preview (Release Candidate): [OpenDC v3.0-rc1](https://github.com/atlarge-research/opendc/releases/tag/v3.0-rc1) (Jan 27, 2023)

## Documentation

You can find the OpenDC documentation [on the website](https://atlarge-research.github.io/opendc/).
The documentation is divided into several sections:

* [Getting Started](https://atlarge-research.github.io/opendc/docs/category/getting-started/)
* [Tutorials](https://atlarge-research.github.io/opendc/docs/category/tutorials/)
* [Advanced Guides](https://atlarge-research.github.io/opendc/docs/category/advanced-guides/)
* [Where to Get Support](https://atlarge-research.github.io/opendc/community/support/)
* [Contributing Guide](https://atlarge-research.github.io/opendc/community/contributing/)

The source code for the documentation is located in [site](site).

## Contributing

Questions, suggestions and contributions are welcome and appreciated!
Please refer to the [contributing guidelines](CONTRIBUTING.md) for more details.

## License

OpenDC is distributed under the MIT license. See [LICENSE.txt](/LICENSE.txt).


# AppIntro

[![](https://jitpack.io/v/AppIntro/AppIntro.svg)](https://jitpack.io/#AppIntro/appintro) [![Join the chat at https://kotlinlang.slack.com](https://img.shields.io/badge/slack-@kotlinlang/appintro-yellow.svg?logo=slack)](https://kotlinlang.slack.com/archives/C019SH1RMBN) [![Pre Merge Checks](https://github.com/AppIntro/AppIntro/workflows/Pre%20Merge%20Checks/badge.svg)](https://github.com/AppIntro/AppIntro/actions?query=workflow%3A%22Pre+Merge+Checks%22) [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-AppIntro-green.svg?style=flat)](https://android-arsenal.com/details/1/1939) [![Awesome Kotlin Badge](https://kotlin.link/awesome-kotlin.svg)](https://github.com/KotlinBy/awesome-kotlin)

AppIntro is an Android Library that helps you build a **cool carousel intro** for your App. AppIntro has support for **requesting permissions** and helps you create a great onboarding experience in just a couple of minutes.

  * [Getting Started <g-emoji class="g-emoji" alias="footprints" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f463.png">👣</g-emoji>](#getting-started-)
     * [Adding a dependency](#adding-a-dependency)
     * [Basic usage](#basic-usage)
     * [Java users](#java-users)
  * [Migrating <g-emoji class="g-emoji" alias="car" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f697.png">🚗</g-emoji>](#migrating-)
  * [Features <g-emoji class="g-emoji" alias="toolbox" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f9f0.png">🧰</g-emoji>](#features-)
  * [Creating Slides <g-emoji class="g-emoji" alias="woman_artist" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f469-1f3a8.png">👩🎨</g-emoji>](#creating-slides-)
     * [AppIntroFragment](#appintrofragment)
     * [AppIntroCustomLayoutFragment](#appintrocustomlayoutfragment)
  * [Configure <g-emoji class="g-emoji" alias="art" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f3a8.png">🎨</g-emoji>](#configure-)
     * [Slide Transformer](#slide-transformer)
        * [Custom Slide Transformer](#custom-slide-transformer)
     * [Color Transition](#color-transition)
     * [Multiple Windows Layout](#multiple-windows-layout)
     * [Indicators](#indicators)
     * [Vibration](#vibration)
     * [Wizard Mode](#wizard-mode)
     * [Immersive Mode](#immersive-mode)
     * [System Back button](#system-back-button)
     * [System UI (Status Bar and Navigation Bar)](#system-ui-status-bar-and-navigation-bar)
     * [Bottom Bar Margin](#bottom-bar-margin)
  * [Permission <g-emoji class="g-emoji" alias="lock" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f512.png">🔒</g-emoji>](#permission-)
     * [Slide Policy](#slide-policy)
  * [Example App <g-emoji class="g-emoji" alias="bulb" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f4a1.png">💡</g-emoji>](#example-app-)
  * [Translating <g-emoji class="g-emoji" alias="earth_africa" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f30d.png">🌍</g-emoji>](#translating-)
  * [Snapshots <g-emoji class="g-emoji" alias="package" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f4e6.png">📦</g-emoji>](#snapshots-)
  * [Contributing <g-emoji class="g-emoji" alias="handshake" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f91d.png">🤝</g-emoji>](#contributing-)
  * [Acknowledgments <g-emoji class="g-emoji" alias="cherry_blossom" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f338.png">🌸</g-emoji>](#acknowledgments-)
     * [Maintainers](#maintainers)
     * [Libraries](#libraries)
  * [License <g-emoji class="g-emoji" alias="page_facing_up" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f4c4.png">📄</g-emoji>](#license-)
  * [Apps using AppIntro <g-emoji class="g-emoji" alias="iphone" fallback-src="https://github.githubassets.com/images/icons/emoji/unicode/1f4f1.png">📱</g-emoji>](#apps-using-appintro-)

## Getting Started 👣

AppIntro is distributed through [JitPack](https://jitpack.io/#AppIntro/AppIntro).

### Adding a dependency

To use it you need to add the following gradle dependency to your `build.gradle` file of the module where you want to use AppIntro (NOT the root file).

```groovy
repositories {
    maven { url "https://jitpack.io" }
}
```

```groovy
dependencies {
    // AndroidX Capable version
    implementation 'com.github.AppIntro:AppIntro:6.3.1'

    // *** OR ***

    // Latest version compatible with the old Support Library
    implementation 'com.github.AppIntro:AppIntro:4.2.3'
}
```

Please note that since AppIntro 5.x, the library supports [Android X](https://developer.android.com/jetpack/androidx/). If you haven't migrated yet, you probably want to use a previous version of the library that uses the **old Support Library** packages (or try [Jetifier Reverse mode](https://ncorti.com/blog/jetifier-reverse)).

### Basic usage

To use AppIntro, you simply have to create a new **Activity that extends AppIntro** like the following:

```kotlin
class MyCustomAppIntro : AppIntro() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Make sure you don't call setContentView!

        // Call addSlide passing your Fragments.
        // You can use AppIntroFragment to use a pre-built fragment
        addSlide(AppIntroFragment.createInstance(
                title = "Welcome...",
                description = "This is the first slide of the example"
        ))
        addSlide(AppIntroFragment.createInstance(
                title = "...Let's get started!",
                description = "This is the last slide, I won't annoy you more :)"
        ))
    }

    override fun onSkipPressed(currentFragment: Fragment?) {
        super.onSkipPressed(currentFragment)
        // Decide what to do when the user clicks on "Skip"
        finish()
    }

    override fun onDonePressed(currentFragment: Fragment?) {
        super.onDonePressed(currentFragment)
        // Decide what to do when the user clicks on "Done"
        finish()
    }
}
```

Please note that you **must NOT call** setContentView. The `AppIntro` superclass is taking care of it for you.

Also confirm that you're overriding `onCreate` with **a single parameter** (`Bundle`) and you're not using another override (like `onCreate(Bundle, PersistableBundle)`) instead.

Finally, declare the activity in your Manifest like so:

``` xml
<activity android:name="com.example.MyCustomAppIntro"
    android:label="My Custom AppIntro" />
```

We suggest to don't declare `MyCustomAppIntro` as your first Activity unless you want the intro to launch every time your app starts. Ideally you should show the AppIntro activity only once to the user, and you should hide it once completed (you can use a flag in the `SharedPreferences`).

### Java users

You can find many examples in java language in the [examples directory](example/src/main/java/com/github/appintro/example/ui/java/JavaIntro.java)

## Migrating 🚗

If you're migrating **from AppIntro v5.x to v6.x**, please expect multiple breaking changes. You can find documentation on how to update your code on this other [migration guide](/docs/migrating-from-5.0.md).

## Features 🧰

Don't forget to check the [changelog](CHANGELOG.md) to have a look at all the changes in the latest version of AppIntro.

* **API >= 14** compatible.
* 100% Kotlin Library.
* **AndroidX** Compatible.
* Support for **runtime permissions**.
* Dependent only on AndroidX AppCompat/Annotations, ConstraintLayout and Kotlin JDK.
* Full RTL support.

## Creating Slides 👩🎨

The entry point to add a new slide is the `addSlide(fragment: Fragment)` function on the `AppIntro` class.
You can easily use it to add a new `Fragment` to the carousel.

The library comes with several util classes to help you create your Slide with just a couple lines:

### `AppIntroFragment`

You can use the `AppIntroFragment` if you just want to customize title, description, image and colors.
That's the suggested approach if you want to create a quick intro:

```kotlin
addSlide(AppIntroFragment.createInstance(
    title = "The title of your slide",
    description = "A description that will be shown on the bottom",
    imageDrawable = R.drawable.the_central_icon,
    backgroundDrawable = R.drawable.the_background_image,
    titleColorRes = R.color.yellow,
    descriptionColorRes = R.color.red,
    backgroundColorRes = R.color.blue,
    titleTypefaceFontRes = R.font.opensans_regular,
    descriptionTypefaceFontRes = R.font.opensans_regular,
))
```

All the parameters are optional, so you're free to customize your slide as you wish.

If you need to programmatically create several slides you can also use the `SliderPage` class.
This class can be passed to `AppIntroFragment.createInstance(sliderPage: SliderPage)` that will create
a new slide starting from that instance.

### `AppIntroCustomLayoutFragment`

If you need further control on the customization of your slide, you can use the `AppIntroCustomLayoutFragment`.
This will allow you pass your custom Layout Resource file:

```kotlin
AppIntroCustomLayoutFragment.newInstance(R.layout.intro_custom_layout1)
```

This allows you to achieve complex layout and include your custom logic in the Intro (see also [Slide Policy](#slide-policy)):

## Configure 🎨

AppIntro offers several configuration option to help you customize your onboarding experience.

### Slide Transformer

AppIntro comes with a set of _Slide Transformer_ that you can use out of the box to animate your Slide transition.

| Slide Transformers | Slide Transformers |
| :---: | :---: |
| Fade
 | Zoom
 |
| Flow
 | Slide Over
 |
| Depth
 | Parallax
 |

You can simply call `setTransformer()` and pass one of the subclass of the sealed class `AppIntroPageTransformerType`:

```kotlin
setTransformer(AppIntroPageTransformerType.Fade)
setTransformer(AppIntroPageTransformerType.Zoom)
setTransformer(AppIntroPageTransformerType.Flow)
setTransformer(AppIntroPageTransformerType.SlideOver)
setTransformer(AppIntroPageTransformerType.Depth)

// You can customize your parallax parameters in the constructors.
setTransformer(AppIntroPageTransformerType.Parallax(
                titleParallaxFactor = 1.0,
                imageParallaxFactor = -1.0,
                descriptionParallaxFactor = 2.0
))
```

#### Custom Slide Transformer

You can also provide your custom Slide Transformer (implementing the `ViewPager.PageTransformer` interface) with:

```kotlin
setCustomTransformer(ViewPager.PageTransformer)
```

### Color Transition

AppIntro offers the possibility to animate the **color transition** between two slides background.
This feature is disabled by default, and you need to enable it on your AppIntro with:

```kotlin
isColorTransitionsEnabled = true
```

Once you enable it, the color will be animated between slides with a gradient.
Make sure you provide a `backgroundColor` parameter in your slides.

If you're providing custom Fragments, you can let them support the color transition by implementing
the `SlideBackgroundColorHolder` interface.

### Multiple Windows Layout

AppIntro is shipped with two top-level layouts that you can use.
The default layout (`AppIntro`) has textual buttons, while the alternative
layout has buttons with icons.

To change the Window layout, you can simply change your superclass to `AppIntro2`.
The methods to add and customize the AppIntro are unchanged.

```kotlin
class MyCustomAppIntro : AppIntro2() {
    // Same code as displayed in the `Basic Usage` section of this README
}
```

| Page | `AppIntro` | `AppIntro2` |
| ---: | :--------: | :---------: |
| standard page |  |  |
| last page |  |  |

### Indicators

AppIntro supports two indicators out of the box to show the progress of the Intro experience to the user:

* `DotIndicatorController` represented with a list of Dot (the default)
* `ProgressIndicatorController` represented with a progress bar.

| `DotIndicator` | `ProgressIndicator` |
| ---------- | ----------- |
| ![dotted indicator](assets/dotted-indicator.gif) | ![progress indicator](assets/progress-indicator.gif) |

Moreover, you can supply your own indicator by providing an implementation of the `IndicatorController` interface.

You can customize the indicator with the following API on the `AppIntro` class:

```kotlin
// Toggle Indicator Visibility
isIndicatorEnabled = true

// Change Indicator Color
setIndicatorColor(
    selectedIndicatorColor = getColor(R.color.red),
    unselectedIndicatorColor = getColor(R.color.blue)
)

// Switch from Dotted Indicator to Progress Indicator
setProgressIndicator()

// Supply your custom `IndicatorController` implementation
indicatorController = MyCustomIndicator(/* initialize me */)
```

If you don't specify any customization, a `DotIndicatorController` will be shown.

### Vibration

AppIntro supports providing haptic _vibration_ feedback on button clicks.
Please note that you **need to specify the Vibration permission** in your app Manifest
(the library is not doing it). If you forget to specify the permission, the app will experience a crash.

```xml
<uses-permission android:name="android.permission.VIBRATE" />
```

You can enable and customize the vibration with:

```kotlin
// Enable vibration and set duration in ms
isVibrate = true
vibrateDuration = 50L
```

### Wizard Mode

AppIntro supports a _Wizard_ mode where the Skip button will be replaced with the back arrow.
This comes handy if you're presenting a Wizard to your users with a set of steps they need to do,
and they might frequently go back and forth.

You can enable it with:

```kotlin
isWizardMode = true
```

### Immersive Mode

If you want to display your Intro with a fullscreen experience, you can enable the _Immersive_ mode. This will
hide both the _Status Bar_ and the _Navigation Bar_ and the user will have to scroll from the top of the screen to
show them again.

This allows you to have more space for your Intro content and graphics.

You can enable it with:

```kotlin
setImmersiveMode()
```

### System Back button

You can lock the System Back button if you don't want your user to go back from intro.
This could be useful if you need to request permission and the Intro experience is not optional.

If this is the case, please set to true the following flag:

```kotlin
isSystemBackButtonLocked = true
```

### System UI (Status Bar and Navigation Bar)

You can customize the _Status Bar_, and the _Navigation Bar_ visibility & color with the following methods:

```kotlin
// Hide/Show the status Bar
showStatusBar(true)
// Control the status bar color
setStatusBarColor(Color.GREEN)
setStatusBarColorRes(R.color.green)

// Control the navigation bar color
setNavBarColor(Color.RED)
setNavBarColorRes(R.color.red)
```

### Bottom Bar Margin

By default, the slides use the whole size available in the screen, so it might happen that the
bottom bar overlaps the content of the slide if you have set the background color to a
non-transparent one.
If you want to make sure that the bar doesn't overlap the content, use the `setBarMargin` function
as follows:
```kotlin
setBarMargin(true)
```

## Permission 🔒

AppIntro simplifies the process of requesting **runtime permissions** to your user.
You can integrate one or more permission request inside a slide with the `askForPermissions` method inside your activity.

Please note that:
* `slideNumber` is in a **One-based numbering** (it starts from 1)
* You can specify more than one permission if needed
* You can specify if the permission is required. If so, users can't proceed if he denies the permission.

```kotlin
// Ask for required CAMERA permission on the second slide.
askForPermissions(
    permissions = arrayOf(Manifest.permission.CAMERA),
    slideNumber = 2,
    required = true)

// Ask for both optional ACCESS_FINE_LOCATION and WRITE_EXTERNAL_STORAGE
// permission on the third slide.
askForPermissions(
    permissions = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    ),
    slideNumber = 3,
    required = false)
```

Should you need further control on the permission request, you can override those two methods on the `AppIntro` class:

```kotlin
override fun onUserDeniedPermission(permissionName: String) {
    // User pressed "Deny" on the permission dialog
}
override fun onUserDisabledPermission(permissionName: String) {
    // User pressed "Deny" + "Don't ask again" on the permission dialog
}
```

### Slide Policy

If you want to restrict navigation between your slides (i.e. the user has to toggle a checkbox in order to continue),
the `SlidePolicy` feature might help you.

All you have to do is implement `SlidePolicy` in your slides.

This interface contains the `isPolicyRespected` property and the `onUserIllegallyRequestedNextPage` method
that you must implement with your custom logic

```kotlin
class MyFragment : Fragment(), SlidePolicy {

    // If user should be allowed to leave this slide
    override val isPolicyRespected: Boolean
        get() = false // Your custom logic here.

    override fun onUserIllegallyRequestedNextPage() {
        // User illegally requested next slide.
        // Show a toast or an informative message to the user.
    }
}
```

You can find a full working example of `SlidePolicy` in the [example app - CustomSlidePolicyFragment.kt](example/src/main/java/com/github/appintro/example/ui/custom/fragments/CustomSlidePolicyFragment.kt)

## Example App 💡

AppIntro comes with a **sample app** full of examples and use case that you can use as inspiration for your project. You can find it inside the [/example folder](https://github.com/AppIntro/AppIntro/tree/main/example).

You can get a **debug APK** of the sample app from the **Pre Merge** GitHub Actions job as an [output artifact here](https://github.com/AppIntro/AppIntro/actions?query=workflow%3A%22Pre+Merge+Checks%22).

## Translating 🌍

Do you want to help AppIntro becoming international 🌍? We are more than happy!
AppIntro currently supports [the following languages](appintro/src/main/res).

To add a new translation just add a pull request with a new `strings.xml` file inside a `values-xx` folder (where `xx` is a [two-letter ISO 639-1 language code](https://en.wikipedia.org/wiki/ISO_639-1)).

In order to provide the translation, your file needs to contain the following strings:

```xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
    <string name="app_intro_skip_button">[Translation for SKIP]</string>
    <string name="app_intro_next_button">[Translation for NEXT]</string>
    <string name="app_intro_back_button">[Translation for BACK]</string>
    <string name="app_intro_done_button">[Translation for DONE]</string>
    <string name="app_intro_image_content_description">[Translation for "graphics"]</string>
</resources>
```

An updated version of the English version translation is [available here](appintro/src/main/res/values/strings.xml).

If a translation in your language is already available, please check it and eventually fix it (all the strings should be listed, not just a subset).

## Snapshots 📦

Development of AppIntro happens on the [main](https://github.com/AppIntro/AppIntro/tree/main) branch. You can get `SNAPSHOT` versions directly from JitPack if needed.

```gradle
repositories {
    maven { url "https://jitpack.io" }
}
```

```gradle
dependencies {
  implementation "com.github.AppIntro:AppIntro:main-SNAPSHOT"
}
```

⚠ Please note that the latest snapshot might be **unstable**. Use it at your own risk ⚠

## Contributing 🤝

We're offering support for AppIntro on the [#appintro channel on KotlinLang Slack](https://kotlinlang.slack.com/archives/C019SH1RMBN). Come and join the conversation over there. If you don't have access to KotlinLang Slack, you can [request access here](https://surveys.jetbrains.com/s3/kotlin-slack-sign-up).

**We're looking for contributors! Don't be shy.** 👍 Feel free to open issues/pull requests to help me improve this project.

* When reporting a new Issue, make sure to attach **Screenshots**, **Videos** or **GIFs** of the problem you are reporting.
* When submitting a new PR, make sure tests are all green. Write new tests if necessary.

## Acknowledgments 🌸

### Maintainers

AppIntro is currently developed and maintained by the [AppIntro GitHub Org](https://github.com/AppIntro). When submitting a new PR, please ping one of:

- [@paolorotolo](https://github.com/paolorotolo)
- [@cortinico](https://github.com/cortinico)

### Libraries

AppIntro is not relying on any third party library other than those from AndroidX:

- `androidx.appcompat:appcompat`
- `androidx.annotation:annotation`
- `androidx.constraintlayout:constraintlayout`

## License 📄

```
    Copyright (C) 2015-2020 AppIntro Developers

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
```

## Apps using AppIntro 📱

If you are using AppIntro in your app and would like to be listed here, please open a pull request and we will be more than happy to include you:

  List of Apps using AppIntro

* [Smoothie Recipes](https://play.google.com/store/apps/details?id=com.skykonig.smoothierecipes)
* [neutriNote](https://play.google.com/store/apps/details?id=com.appmindlab.nano)
* [Handwriting Note](https://play.google.com/store/apps/details?id=com.lyk.immersivenote)
* [ChineseDictionary (粵韻漢典離線粵語普通話發聲中文字典)](https://play.google.com/store/apps/details?id=com.jonasng.chinesedictionary)
* [Salary Barometer](https://play.google.com/store/apps/details?id=anaware.salarybarometer)
* [Best Business Idea!](https://play.google.com/store/apps/details?id=anaware.bestidea)
* [Wi-Fi password reminder](https://play.google.com/store/apps/details?id=com.rusdelphi.wifipassword)
* [Find My Parked Car](https://play.google.com/store/apps/details?id=com.ofirmiron.findmycarandroidwear)
* [Vape Tool Pro](https://play.google.com/store/apps/details?id=com.stasbar.vapetoolpro)
* [Third Eye](https://play.google.com/store/apps/details?id=com.miragestacks.thirdeye)
* [Web Video Cast](https://play.google.com/store/apps/details?id=com.instantbits.cast.webvideo)
* [Fitness Challenge](https://play.google.com/store/apps/details?id=com.isidroid.fitchallenge)
* [Filmy - Your Movie Guide](https://play.google.com/store/apps/details?id=tech.salroid.filmy)
* [HEBF Optimizer ▪ Root](https://play.google.com/store/apps/details?id=com.androidvip.hebf)
* [IIFYM](https://play.google.com/store/apps/details?id=com.javierd.iifym)
* [Ampwifi Winamp Remote](https://play.google.com/store/apps/details?id=com.blitterhead.ampwifi)
* [Hugetwit](https://play.google.com/store/apps/details?id=com.halilibo.hugetwit)
* [Boo Music Player](https://play.google.com/store/apps/details?id=cdn.BooPlayer)
* [BeatPrompter](https://play.google.com/store/apps/details?id=com.stevenfrew.beatprompter)
* [BlueWords](https://play.google.com/store/apps/details?id=com.thesrb.bluewords&referrer=utm_source%3Dappintro%26utm_medium%3Dgithub%26utm_campaign%3Dreadme)
* [Orbot](https://play.google.com/store/apps/details?id=org.torproject.android)
* [PhotoGuard Photo Vault](https://play.google.com/store/apps/details?id=com.photovault.photoguard)
* [Ride My Park - Best Spots, Skateparks Map](https://play.google.com/store/apps/details?id=com.andrieutom.rmp)
* [Shopping list](https://play.google.com/store/apps/details?id=de.vanse.shoppinglist) and [Shopping list pro](https://play.google.com/store/apps/details?id=de.vanse.shoppinglist.pro)
* [PZPIC - Pan & Zoom Effect Video from Still Picture](https://play.google.com/store/apps/details?id=com.photo3dlab.pzpic)
* [PrezziBenzina](https://play.google.com/store/apps/details?id=org.vernazza.androidfuel)
* [LogViewer for openHAB](https://github.com/cyb3rko/logviewer-for-openhab-app)
* [Firmo con CIE](https://play.google.com/store/apps/details?id=com.cyberneid.disigoncie)
* [iC-YOURLS](https://play.google.com/store/apps/details?id=net.inscomers.yourls)
* [Noon Happen](https://play.google.com/store/apps/details?id=com.noonhappen.noonhappen)
* [Weather Forecast](https://play.google.com/store/apps/details?id=com.ehlb.weatherapp)
* [Zoned Pomodoro Timer](https://play.google.com/store/apps/details?id=com.just.five)
* [PCAPdroid Network Monitor](https://play.google.com/store/apps/details?id=com.emanuelef.remote_capture)
* [EQtive](https://play.google.com/store/apps/details?id=com.vekanto.eqtive)
* [PocketMark - MarkDown Editor](https://play.google.com/store/apps/details?id=com.ZetaDev.PocketMark)


# <img src="docs/images/icon-sqldelight.svg" style="height: 1em; margin-bottom: -0.1em;"> SQLDelight

See the [project website](https://cashapp.github.io/sqldelight/) for documentation and APIs

SQLDelight generates typesafe Kotlin APIs from your SQL statements. It verifies your schema, statements, and migrations at compile-time and provides IDE features like autocomplete and refactoring which make writing and maintaining SQL simple.

SQLDelight understands your existing SQL schema.

```sql
CREATE TABLE hockey_player (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  number INTEGER NOT NULL
);
```

It generates typesafe code for any labeled SQL statements.

![intro.gif](docs/images/intro.gif)

---

SQLDelight supports a variety of dialects and platforms:

SQLite

* [Android](https://cashapp.github.io/sqldelight/android_sqlite)
* [Native (iOS, macOS, or Windows)](https://cashapp.github.io/sqldelight/native_sqlite)
* [JVM](https://cashapp.github.io/sqldelight/jvm_sqlite)
* [Javascript](https://cashapp.github.io/sqldelight/js_sqlite)
* [Multiplatform](https://cashapp.github.io/sqldelight/multiplatform_sqlite)

[MySQL (JVM)](https://cashapp.github.io/sqldelight/jvm_mysql/)

[PostgreSQL (JVM)](https://cashapp.github.io/sqldelight/jvm_postgresql)

[HSQL/H2 (JVM)](https://cashapp.github.io/sqldelight/jvm_h2) (Experimental)

## Snapshots

Snapshots of the development version (including the IDE plugin zip) are available in
[Sonatype's `snapshots` repository](https://oss.sonatype.org/content/repositories/snapshots/). Note that the coordinates are all app.cash.sqldelight instead of com.squareup.cash for the 2.0.0+ SNAPSHOTs.

Documentation pages for the latest snapshot version can be [found here](https://cashapp.github.io/sqldelight/snapshot).

License
=======

    Copyright 2016 Square, Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


KotlinPoet
==========

`KotlinPoet` is a Kotlin and Java API for generating `.kt` source files.

### [square.github.io/kotlinpoet](https://square.github.io/kotlinpoet)

License
-------

    Copyright 2017 Square, Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


[![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-Kaspresso-green.svg?style=flat )](https://android-arsenal.com/details/1/7896)
[![Android Weekly](https://img.shields.io/badge/Android%20Weekly-383-green.svg)](http://androidweekly.net/issues/issue-383)
[![Android Weekly](https://img.shields.io/badge/Android%20Weekly-392-green.svg)](http://androidweekly.net/issues/issue-392)
[![MavenCentral](https://img.shields.io/maven-central/v/com.kaspersky.android-components/kaspresso)](https://search.maven.org/artifact/com.kaspersky.android-components/kaspresso)
![Build and Deploy](https://github.com/KasperskyLab/Kaspresso/workflows/Build%20and%20Deploy/badge.svg)
[![Telegram](https://img.shields.io/static/v1?label=Telegram&message=RU&color=0088CC)](https://t.me/kaspresso)
[![Telegram](https://img.shields.io/static/v1?label=Telegram&message=EN&color=0088CC)](https://t.me/kaspresso_en)
[![Discord](https://img.shields.io/discord/1152145101825527839?label=discord&labelColor=7289da&style=flat)](https://kas.pr/gh_discord)

# Kaspresso

Kaspresso is a framework for Android UI testing. Based on [Espresso](https://developer.android.com/training/testing/espresso) and [UI
Automator](https://developer.android.com/training/testing/ui-automator), Kaspresso provides a wide range of additional features, such as:

* Built-in protection against flaky tests
* Jetpack Compose support
* Screenshot testing with native approach (with dark mode support)
* Declarative approach for writing tests
* Ability to interact with other applications and system elements and interfaces
* Human readability with Kotlin DSL wrappers over UiAutomator and Espresso
* Detailed logs and reports (logs, view hierarchy, screenshots, video etc.)
* ADB support
* Allure support
* Robolectric support
* Easy migration from Espresso
* Flexible configuration options
* Automatic artifacts pulling after tests execution
* Significantly faster execution of UI Automator commands. With Kaspresso, some UI Automator commands run **10 times faster**!
* Page object pattern from the box

And many more!

## Integration

To integrate Kaspresso into your project:
1. If the `mavenCentral` repository does not exist, include it to your root `build.gradle` file:

```groovy
allprojects {
    repositories {
        mavenCentral()
    }
}
```

2. Add a dependency to `build.gradle`:

```groovy
dependencies {
    androidTestImplementation 'com.kaspersky.android-components:kaspresso:<latest_version>'
    // Allure support
    androidTestImplementation "com.kaspersky.android-components:kaspresso-allure-support:<latest_version>"
    // Jetpack Compose support
    androidTestImplementation "com.kaspersky.android-components:kaspresso-compose-support:<latest_version>"
}
```

To try out the cutting edge kaspresso updates before an official release add a snapshot repository to your `build.gradle`
```groovy
dependencyResolutionManagement {
    repositories {
        maven { url = uri("https://s01.oss.sonatype.org/content/repositories/snapshots") }
    }
}
```
To use a snapshot version of a Kaspresso add a "-SNAPHOT" postfix to the latest Kaspresso version e.g.
```groovy
dependencies {
    androidTestImplementation 'com.kaspersky.android-components:kaspresso:<latest_version>-SNAPSHOT'
}
```

If you are still using the old Android Support libraries, we strongly recommend to migrate to AndroidX.

The last version with Android Support libraries is:

```groovy
dependencies {
    androidTestImplementation 'com.kaspersky.android-components:kaspresso:1.5.3'
}
```

## FAQ
[See our website.](https://kasperskylab.github.io/Kaspresso/en/)
You can also reach out to us on [Discord](https://kas.pr/gh_discord).

## Tutorial *NEW*
To make it easier to learn the framework, a step-by-step tutorial is available on [our website](https://kasperskylab.github.io/Kaspresso/Tutorial/).

## Capabilities of Kaspresso

### Readability

We like the syntax that [Kakao](https://github.com/KakaoCup/Kakao) applies to write UI tests. This wrapper over Espresso uses the Kotlin DSL approach, that makes the code
significantly shorter and more readable. See the difference:

**Espresso**:
```kotlin
@Test
fun testFirstFeature() {
    onView(withId(R.id.toFirstFeature))
        .check(ViewAssertions.matches(
               ViewMatchers.withEffectiveVisibility(
                       ViewMatchers.Visibility.VISIBLE)))
    onView(withId(R.id.toFirstFeature)).perform(click())
}
```
**Kakao**:
```kotlin
@Test
fun testFirstFeature() {
    mainScreen {
        toFirstFeatureButton {
            isVisible()
            click()
        }
    }
}
```
We used the same approach to develop our own wrapper over UI Automator, and we called it *Kautomator*. Take a look at the code below:

**UI Automator**:
```kotlin
val instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation()
val uiDevice = UiDevice.getInstance(instrumentation)
val uiObject = uiDevice.wait(
    Until.findObject(
        By.res(
            "com.kaspersky.kaspresso.sample_kautomator",
            "editText"
        )
    ),
    2_000
)
uiObject.text = "Kaspresso"
assertEquals(uiObject.text, "Kaspresso")
```
**Kautomator**:
```kotlin
MainScreen {
    simpleEditText {
        replaceText("Kaspresso")
        hasText("Kaspresso")
    }
}
```
Since Kakao and Kautomator provide almost identical APIs, you don’t have to care about what is under the hood of your tests, either Espresso or UI Automator. With Kaspresso, you write tests in the same style for both.

However, Kakao and Kautomator themselves don't help you to see the relation between the test and the corresponding test case. Also, a long test often becomes a giant piece of code that is impossible to split into smaller parts.
That's why we have created an additional Kotlin DSL that allows you to read your test more easily.

See the example below:

```kotlin
@Test
fun shouldPassOnNoInternetScanTest() =
    beforeTest {
        activityTestRule.launchActivity(null)
        // some things with the state
    }.afterTest {
        // some things with the state
    }.run {
        step("Open Simple Screen") {
            MainScreen {
                nextButton {
                    isVisible()
                    click()
                }
            }
        }
        step("Click button_1 and check button_2") {
            SimpleScreen {
                button1 {
                    click()
                }
                button2 {
                    isVisible()
                }
            }
        }
        step("Click button_2 and check edit") {
            SimpleScreen {
                button2 {
                    click()
                }
                edit {
                    flakySafely(timeoutMs = 7000) { isVisible() }
                    hasText(R.string.text_edit_text)
                }
            }
        }
        step("Check all possibilities of edit") {
            scenario(
                CheckEditScenario()
            )
        }
    }
```

### Stability

Sometimes your UI test passes ten times, then breaks on the eleventh attempt for some mysterious reason. It’s called *flakiness*.

The most popular reason for flakiness is the instability of the UI tests libraries, such as Espresso and UI Automator. To eliminate this instability, Kaspresso uses DSL wrappers and [interceptors](#Interceptors).

### UI test libraries acceleration

Let’s watch some short video that shows the difference between the original UI Automator (on the right) and the accelerated one (on the left).

![](https://habrastorage.org/webt/ti/kv/ki/tikvkij1vjesnacrxqm-lk0coly.gif)

Here is [a short explanation](https://kasperskylab.github.io/Kaspresso/Wiki/Kautomator-wrapper_over_UI_Automator/#accelerate-ui-automator) of why it is possible.

### Interceptors

We developed [Kaspresso behavior interceptors](https://kasperskylab.github.io/Kaspresso/Wiki/Kaspresso_configuration/#some-words-about-behavior-interceptors) on the base of [Kakao/Kautomator
Interceptors](https://kasperskylab.github.io/Kaspresso/Wiki/Kaspresso_configuration/#kaspresso-interceptors-based-on-kakaokautomator-interceptors) to catch failures.

Thanks to interceptors, you can do a lot of useful things, such as:

* add custom actions to each framework operation like writing a log or taking a screenshot;
* overcome flaky operations by re-running failed actions, scrolling the parent layout or closing the android system dialog;

and many more (see [the manual](https://kasperskylab.github.io/Kaspresso/Wiki/Kaspresso_configuration/#kaspresso-interceptors-based-on-kakaokautomator-interceptors)).

### Writing readable logs

Kaspresso writes its own logs, detailed and readable:

### Ability to call ADB commands

Espresso and UI Automator don't allow to call ADB commands from inside a test. To fix this problem, we developed AdbServer (see the [wiki](https://kasperskylab.github.io/Kaspresso/Wiki/Executing_adb_commands/)).

### Ability to work with Android System

You can use Kaspresso classes to work with Android System.

For example, with the ```Device``` class you can:

* push/pull files,
* enable/disable network,
* give permissions like a user does,
* emulate phone calls,
* take screenshots,
* enable/disable GPS,
* set geolocation,
* enable/disable accessibility,
* change the app language,
* collect and parse the logcat output.

(see more about the [Device class](https://kasperskylab.github.io/Kaspresso/Wiki/Working_with_Android_OS/)).

### Features screenshotting

If you develop an application that is available across the world, you have to *localize* it into different languages. When UI is localized, it’s important for the translator to see the context of a word or a phrase, that is the specific screen.

With Kaspresso, translators can automatically take a screenshot of any screen. It’s incredibly fast, even for legacy screens, and you don't have to refactor or mock anything (see [the manual](https://kasperskylab.github.io/Kaspresso/Wiki/Screenshot_tests/)).

### Configurability

You can tune any part of Kaspresso (read [more](https://kasperskylab.github.io/Kaspresso/Wiki/Kaspresso_configuration/)).

### Robolectric support

You can run your UI-tests on the JVM environment. Additionally, almost all interceptors improving stability, readability and other will work.
Read [more](https://kasperskylab.github.io/Kaspresso/Wiki/Kaspresso_Robolectric/).

### Allure support

Kaspresso can generate very detailed Allure-reports for each test:
![](https://habrastorage.org/webt/tq/t7/ch/tqt7chcdczrgduhoukqhx1ertfc.png)
More information is available [here](https://kasperskylab.github.io/Kaspresso/Wiki/Kaspresso_Allure/).

### Jetpack Compose support

Now, you can write your Kaspresso tests for Jetpack Compose screens! DSL and all principles are the same.
So, you will not see any difference between tests for View screens and for Compose screens.
More information is available [here](https://kasperskylab.github.io/Kaspresso/Wiki/Jetpack_Compose/).

## Samples
All samples are available in the [samples](https://github.com/KasperskyLab/Kaspresso/tree/master/samples) folder.

Most of the samples require AdbServer. To start AdbServer you should do the following steps:

1. Go to the `Kaspresso` folder
```
cd ~/Workspace/Kaspresso
```
2. Start `adbserver-desktop.jar`
```
java -jar artifacts/adbserver-desktop.jar
```

## Existing issues
All existing issues in Kaspresso can be found [here](https://kasperskylab.github.io/Kaspresso/Issues/).

## Breaking changes
Breaking changes can be found [here](https://kasperskylab.github.io/Kaspresso/Home/Breaking-changes/)

## Contribution
Kaspresso is an open source project, so you are welcome to contribute (see the [Contribution Guidelines](https://kasperskylab.github.io/Kaspresso/Home/Contribution_guide/)).

## License
Kaspresso is available under the [Apache License, Version 2.0](https://github.com/KasperskyLab/Kaspresso/blob/master/LICENSE).

## Runner

If you looking for a Runner to execute your UI tests we strongly recommend to use [Marathon](https://github.com/MarathonLabs/marathon). [Marathon](https://github.com/MarathonLabs/marathon) is a fast, platform-independent test runner focused on performance and stability. It offers easy to use platform implementations for Android and iOS as well as an API for use with custom hardware farms and more techstacks.


[![Kotlin](https://img.shields.io/badge/kotlin-1.5.x-blue.svg)](https://kotlinlang.org) [![Kotlin Slack](https://img.shields.io/badge/chat-kotlin%20slack-orange.svg)](https://slack.kotlinlang.org/)

# Overview

Module that adds support for serialization/deserialization of [Kotlin](https://kotlinlang.org)
classes and data classes.
Previously a default constructor must have existed on the Kotlin object for Jackson to deserialize into the object.
With this module, single constructor classes can be used automatically,
and those with secondary constructors or static factories are also supported.

# Status

* release `2.17.0` (for Jackson `2.17.x`) [![GitHub Actions build](https://github.com/FasterXML/jackson-module-kotlin/actions/workflows/main.yml/badge.svg?branch=2.16)](https://github.com/FasterXML/jackson-module-kotlin/actions?query=branch%3A2.17)
* release `2.16.2` (for Jackson `2.16.x`) [![GitHub Actions build](https://github.com/FasterXML/jackson-module-kotlin/actions/workflows/main.yml/badge.svg?branch=2.16)](https://github.com/FasterXML/jackson-module-kotlin/actions?query=branch%3A2.16)
* release `2.15.3` (for Jackson `2.15.x`) [![GitHub Actions build](https://github.com/FasterXML/jackson-module-kotlin/actions/workflows/main.yml/badge.svg?branch=2.15)](https://github.com/FasterXML/jackson-module-kotlin/actions?query=branch%3A2.15)
* release `2.14.3` (for Jackson `2.14.x`) [![GitHub Actions build](https://github.com/FasterXML/jackson-module-kotlin/actions/workflows/main.yml/badge.svg?branch=2.14)](https://github.com/FasterXML/jackson-module-kotlin/actions?query=branch%3A2.14)

Releases require that you have included Kotlin stdlib and reflect libraries already.

Gradle:
```
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.17.+"
```

Maven:
```xml
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-kotlin</artifactId>
    <version>2.17.0</version>
</dependency>
```

# Usage

For any Kotlin class or data class constructor, the JSON property names will be inferred
from the parameters using Kotlin runtime type information.

To use, just register the Kotlin module with your ObjectMapper instance:

```kotlin
// With Jackson 2.12 and later
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
...
val mapper = jacksonObjectMapper()
// or
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
...
val mapper = ObjectMapper().registerKotlinModule()
// or
import com.fasterxml.jackson.module.kotlin.jsonMapper
import com.fasterxml.jackson.module.kotlin.kotlinModule
...
val mapper = jsonMapper {
  addModule(kotlinModule())
}
```

In 2.17 and later, the `jacksonObjectMapper {}` and `registerKotlinModule {}` lambdas allow configuration for `KotlinModule`.
See [#Configuration](#Configuration) for details on the available configuration items.

A simple data class example:
```kotlin
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue

data class MyStateObject(val name: String, val age: Int)

...
val mapper = jacksonObjectMapper()

val state = mapper.readValue<MyStateObject>(json)
// or
val state: MyStateObject = mapper.readValue(json)
// or
myMemberWithType = mapper.readValue(json)
```

All inferred types for the extension functions carry in full generic information (reified generics).
Therefore, using `readValue()` extension without the `Class` parameter will reify the type and automatically create a `TypeReference` for Jackson.

Also, there are some convenient operator overloading extension functions for JsonNode inheritors.
```kotlin
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.databind.node.JsonNodeFactory
import com.fasterxml.jackson.module.kotlin.*

// ...
val objectNode: ObjectNode = JsonNodeFactory.instance.objectNode()
objectNode.put("foo1", "bar").put("foo2", "baz").put("foo3", "bax")
objectNode -= "foo1"
objectNode -= listOf("foo2")
println(objectNode.toString()) // {"foo3":"bax"}

// ...
val arrayNode: ArrayNode = JsonNodeFactory.instance.arrayNode()
arrayNode += "foo"
arrayNode += true
arrayNode += 1
arrayNode += 1.0
arrayNode += "bar".toByteArray()
println(arrayNode.toString()) // ["foo",true,1,1.0,"YmFy"]
```

# Compatibility
## Kotlin
(NOTE: incomplete! Please submit corrections/additions via PRs!)

Different `kotlin-core` versions are supported by different Jackson Kotlin module minor versions.
Here is an incomplete list of supported versions:

* Jackson 2.18.x: Kotlin-core 1.8 - 2.0
* Jackson 2.17.x: Kotlin-core 1.7 - 2.0
* Jackson 2.16.x: Kotlin-core 1.6 - 1.9
* Jackson 2.15.x: Kotlin-core 1.5 - 1.8
* Jackson 2.14.x: Kotlin-core 1.4 - 1.8
* Jackson 2.13.x: Kotlin-core 1.4 - 1.7

Please note that the versions supported by 2.17 are tentative and may change depending on the release date.

## Android
Supported Android SDK versions are determined by `jackson-databind`.
Please see [this link](https://github.com/FasterXML/jackson-databind#android) for details.

# Annotations

You can intermix non-field values in the constructor and `JsonProperty` annotation in the constructor.
Any fields not present in the constructor will be set after the constructor call.
An example of these concepts:

```kotlin
   @JsonInclude(JsonInclude.Include.NON_EMPTY)
   class StateObjectWithPartialFieldsInConstructor(val name: String, @JsonProperty("age") val years: Int)    {
        @JsonProperty("address") lateinit var primaryAddress: String   // set after construction
        var createdDt: DateTime by Delegates.notNull()                // set after construction
        var neverSetProperty: String? = null                          // not in JSON so must be nullable with default
    }
```

Note that using `lateinit` or `Delegates.notNull()` will ensure that the value is never `null` when read, while letting it be instantiated after the construction of the class.

# Caveats

* The `@JsonCreator` annotation is optional unless you have more than one constructor that is valid, or you want to use a static factory method (which also must have `platformStatic` annotation, e.g. `@JvmStatic`).  In these cases, annotate only one method as `JsonCreator`.
* During deserialization, if the definition on `Kotlin` is a non-null primitive and `null` is entered explicitly on `JSON`, processing will continue with an unintended default value. [This problem is fixed by enabling `DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES` on `ObjectMapper`](https://github.com/FasterXML/jackson-module-kotlin/issues/242#issuecomment-792570655).
* Serializing a member or top-level Kotlin class that implements Iterator requires a workaround, see [Issue #4](https://github.com/FasterXML/jackson-module-kotlin/issues/4) for easy workarounds.
* If using proguard:
    * `kotlin.Metadata` annotations may be stripped, preventing deserialization. Add a proguard rule to keep the `kotlin.Metadata` class: `-keep class kotlin.Metadata { *; }`
    * If you're getting `java.lang.ExceptionInInitializerError`, you may also need: `-keep class kotlin.reflect.** { *; }`
    * If you're still running into problems, you might also need to add a proguard keep rule for the specific classes you want to (de-)serialize. For example, if all your models are inside the package `com.example.models`, you could add the rule `-keep class com.example.models.** { *; }`
    * Also, please refer to [this page](https://github.com/FasterXML/jackson-docs/wiki/JacksonOnAndroid) for settings related to `jackson-databind`.

# Support for Kotlin Built-in classes

These Kotlin classes are supported with the following fields for serialization/deserialization
(and other fields are hidden that are not relevant):

* Pair _(first, second)_
* Triple _(first, second, third)_
* IntRange _(start, end)_
* CharRange _(start, end)_
* LongRange _(start, end)_

Deserialization for `value class` is also supported since 2.17.
Please refer to [this page](./docs/value-class-support.md) for more information on using `value class`, including serialization.

(others are likely to work, but may not be tuned for Jackson)

# Sealed classes without @JsonSubTypes
Subclasses can be detected automatically for sealed classes, since all possible subclasses are known
at compile-time to Kotlin. This makes `com.fasterxml.jackson.annotation.JsonSubTypes` redundant.
A `com.fasterxml.jackson.annotation.@JsonTypeInfo` annotation at the base-class is still necessary.

```kotlin
  @JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
  sealed class SuperClass{
      class A: SuperClass()
      class B: SuperClass()
  }

...
val mapper = jacksonObjectMapper()
val root: SuperClass = mapper.readValue(json)
when(root){
    is A -> "It's A"
    is B -> "It's B"
}
```

# Configuration

The Kotlin module may be given a few configuration parameters at construction time;
see the [inline documentation](https://github.com/FasterXML/jackson-module-kotlin/blob/master/src/main/kotlin/com/fasterxml/jackson/module/kotlin/KotlinModule.kt)
for details on what options are available and what they do.

```kotlin
val kotlinModule = KotlinModule.Builder()
    .enable(KotlinFeature.StrictNullChecks)
    .build()
val mapper = JsonMapper.builder()
    .addModule(kotlinModule)
    .build()
```

If your `ObjectMapper` is constructed in Java, there is a builder method
provided for configuring these options:

```java
KotlinModule kotlinModule = new KotlinModule.Builder()
        .enable(KotlinFeature.StrictNullChecks)
        .build();
ObjectMapper objectMapper = JsonMapper.builder()
        .addModule(kotlinModule)
        .build();
```

# Development

## Maintainers

Following developers have committer access to this project.

* Author: Jayson Minard (@apatrida) wrote this module originally (no longer active)
* Active Maintainers:
    * Dmitry Spikhalskiy (@Spikhalskiy) -- since 2.14
    * Drew Stephens (@dinomite)
    * Vyacheslav Artemyev (@viartemev)
    * WrongWrong (@k163377) -- since 2.15
* Co-maintainers:
    * Tatu Saloranta (@cowtowncoder)

You may at-reference maintainers as necessary but please keep in mind that all
maintenance work is strictly voluntary (no one gets paid to work on this
or any other Jackson components) so there is no guarantee for timeliness of
responses.

All Pull Requests should be reviewed by at least one of active maintainers;
bigger architectural/design questions should be agreed upon by majority of
active maintainers.

## Releases & Branches

This module follows the release schedule of the rest of Jackson—the current version is consistent
across all Jackson components & modules. See the [jackson-databind README](https://github.com/FasterXML/jackson#actively-developed-versions) for details.

## Contributing

We welcome any contributions—reports of issues, ideas for enhancements, and pull requests related to either of those.

See the [main Jackson contribution guidelines](https://github.com/FasterXML/jackson/blob/master/CONTRIBUTING.md) for more details.

### Branches

If you are going to write code, choose the appropriate base branch:

- `2.17` for bugfixes against the current stable version
- `2.18` for additive functionality & features or [minor](https://semver.org), backwards compatible changes to existing behavior to be included in the next minor version release
- `master` for significant changes to existing behavior, which will be part of Jackson 3.0

### Failing tests

There are a number of tests for functionality that is broken, mostly in the [failing](https://github.com/FasterXML/jackson-module-kotlin/tree/master/src/test/kotlin/com/fasterxml/jackson/module/kotlin/test/github/failing)
package but a few as part of other test suites.  Instead of ignoring these tests (with JUnit's `@Ignore` annotation)
or excluding them from being run as part of automated testing, the tests are written to demonstrate the failure
(either making a call that throws an exception or with an assertion that fails) but not fail the build, except if the
underlying issue is fixed.  This allows us to know when the tested functionality has been incidentally fixed by
unrelated code changes.

See the [tests readme](https://github.com/FasterXML/jackson-module-kotlin/tree/master/src/test/kotlin/com/fasterxml/jackson/module/kotlin/README.md) for more information.


# What's Ktorm?

Ktorm is a lightweight and efficient ORM Framework for Kotlin directly based on pure JDBC. It provides strong-typed and flexible SQL DSL and convenient sequence APIs to reduce our duplicated effort on database operations. All the SQL statements, of course, are generated automatically. Ktorm is open source and available under the Apache 2.0 license. Please leave a star if you've found this library helpful!

For more documentation, go to our site: [https://www.ktorm.org](https://www.ktorm.org).

:us: English | :cn: [简体中文](README_cn.md) | :jp: [日本語](README_jp.md)

# Features

 - No configuration files, no XML, no annotations, even no third-party dependencies, lightweight, easy to use.
 - Strong typed SQL DSL, exposing low-level bugs at compile time.
 - Flexible queries, fine-grained control over the generated SQLs as you wish.
 - Entity sequence APIs, writing queries via sequence functions such as `filter`, `map`, `sortedBy`, etc., just like using Kotlin's native collections and sequences.
 - Extensible design, write your own extensions to support more operators, data types, SQL functions, database dialects, etc.

# Quick Start

Ktorm was deployed to maven central, so you just need to add a dependency to your `pom.xml` file if you are using maven:

```xml
<dependency>
    <groupId>org.ktorm</groupId>
    <artifactId>ktorm-core</artifactId>
    <version>${ktorm.version}</version>
</dependency>
```

Or Gradle:

```groovy
compile "org.ktorm:ktorm-core:${ktorm.version}"
```

Firstly, create Kotlin objects to [describe your table schemas](https://www.ktorm.org/en/schema-definition.html):

```kotlin
object Departments : Table<Nothing>("t_department") {
    val id = int("id").primaryKey()
    val name = varchar("name")
    val location = varchar("location")
}

object Employees : Table<Nothing>("t_employee") {
    val id = int("id").primaryKey()
    val name = varchar("name")
    val job = varchar("job")
    val managerId = int("manager_id")
    val hireDate = date("hire_date")
    val salary = long("salary")
    val departmentId = int("department_id")
}
```

Then, connect to your database and write a simple query:

```kotlin
fun main() {
    val database = Database.connect("jdbc:mysql://localhost:3306/ktorm", user = "root", password = "***")

    for (row in database.from(Employees).select()) {
        println(row[Employees.name])
    }
}
```

Now you can run this program, Ktorm will generate a SQL `select * from t_employee`, selecting all employees in the table and printing their names. You can use the for-each loop here because the query object returned by the `select` function overloads the iteration operator.

## SQL DSL

Let's add some filter conditions to the query:

```kotlin
database
    .from(Employees)
    .select(Employees.name)
    .where { (Employees.departmentId eq 1) and (Employees.name like "%vince%") }
    .forEach { row ->
        println(row[Employees.name])
    }
```

Generated SQL:

```sql
select t_employee.name as t_employee_name
from t_employee
where (t_employee.department_id = ?) and (t_employee.name like ?)
```

That's the magic of Kotlin, writing a query with Ktorm is easy and natural, the generated SQL is exactly corresponding to the origin Kotlin code. And moreover, it's strong-typed, the compiler will check your code before it runs, and you will be benefited from the IDE's intelligent sense and code completion.

Dynamic query that will apply different filter conditions in different situations:

```kotlin
val query = database
    .from(Employees)
    .select(Employees.name)
    .whereWithConditions {
        if (someCondition) {
            it += Employees.managerId.isNull()
        }
        if (otherCondition) {
            it += Employees.departmentId eq 1
        }
    }
```

Aggregation:

```kotlin
val t = Employees.aliased("t")
database
    .from(t)
    .select(t.departmentId, avg(t.salary))
    .groupBy(t.departmentId)
    .having { avg(t.salary) gt 100.0 }
    .forEach { row ->
        println("${row.getInt(1)}:${row.getDouble(2)}")
    }
```

Union:

```kotlin
val query = database
    .from(Employees)
    .select(Employees.id)
    .unionAll(
        database.from(Departments).select(Departments.id)
    )
    .unionAll(
        database.from(Departments).select(Departments.id)
    )
    .orderBy(Employees.id.desc())
```

Joining:

```kotlin
data class Names(val name: String?, val managerName: String?, val departmentName: String?)

val emp = Employees.aliased("emp")
val mgr = Employees.aliased("mgr")
val dept = Departments.aliased("dept")

val results = database
    .from(emp)
    .leftJoin(dept, on = emp.departmentId eq dept.id)
    .leftJoin(mgr, on = emp.managerId eq mgr.id)
    .select(emp.name, mgr.name, dept.name)
    .orderBy(emp.id.asc())
    .map { row ->
        Names(
            name = row[emp.name],
            managerName = row[mgr.name],
            departmentName = row[dept.name]
        )
    }
```

Insert:

```kotlin
database.insert(Employees) {
    set(it.name, "jerry")
    set(it.job, "trainee")
    set(it.managerId, 1)
    set(it.hireDate, LocalDate.now())
    set(it.salary, 50)
    set(it.departmentId, 1)
}
```

Update:

```kotlin
database.update(Employees) {
    set(it.job, "engineer")
    set(it.managerId, null)
    set(it.salary, 100)
    where {
        it.id eq 2
    }
}
```

Delete:

```kotlin
database.delete(Employees) { it.id eq 4 }
```

Refer to [detailed documentation](https://www.ktorm.org/en/query.html) for more usages about SQL DSL.

## Entities and Column Binding

In addition to SQL DSL, entity objects are also supported just like other ORM frameworks do. We need to define entity classes firstly and bind table objects to them. In Ktorm, entity classes are defined as interfaces extending from `Entity<E>`:

```kotlin
interface Department : Entity<Department> {
    companion object : Entity.Factory<Department>()
    val id: Int
    var name: String
    var location: String
}

interface Employee : Entity<Employee> {
    companion object : Entity.Factory<Employee>()
    val id: Int
    var name: String
    var job: String
    var manager: Employee?
    var hireDate: LocalDate
    var salary: Long
    var department: Department
}
```

Modify the table objects above, binding database columns to entity properties:

```kotlin
object Departments : Table<Department>("t_department") {
    val id = int("id").primaryKey().bindTo { it.id }
    val name = varchar("name").bindTo { it.name }
    val location = varchar("location").bindTo { it.location }
}

object Employees : Table<Employee>("t_employee") {
    val id = int("id").primaryKey().bindTo { it.id }
    val name = varchar("name").bindTo { it.name }
    val job = varchar("job").bindTo { it.job }
    val managerId = int("manager_id").bindTo { it.manager.id }
    val hireDate = date("hire_date").bindTo { it.hireDate }
    val salary = long("salary").bindTo { it.salary }
    val departmentId = int("department_id").references(Departments) { it.department }
}
```

> Naming Strategy: It's highly recommended to name your entity classes by singular nouns, name table objects by plurals (eg. Employee/Employees, Department/Departments).

Now that column bindings are configured, so we can use [sequence APIs](#Entity-Sequence-APIs) to perform many operations on entities. Let's add two extension properties for `Database` first. These properties return new created sequence objects via `sequenceOf` and they can help us improve the readability of the code:

```kotlin
val Database.departments get() = this.sequenceOf(Departments)
val Database.employees get() = this.sequenceOf(Employees)
```

The following code uses the `find` function to obtain an employee by its name:

```kotlin
val employee = database.employees.find { it.name eq "vince" }
```

We can also filter the sequence by the function `filter`. For example, obtaining all the employees whose names are vince:

```kotlin
val employees = database.employees.filter { it.name eq "vince" }.toList()
```

The `find` and `filter` functions both accept a lambda expression, generating a select sql with the condition returned by the lambda. The generated SQL auto left joins the referenced table `t_department`:

```sql
select *
from t_employee
left join t_department _ref0 on t_employee.department_id = _ref0.id
where t_employee.name = ?
```

Save entities to database:

```kotlin
val employee = Employee {
    name = "jerry"
    job = "trainee"
    hireDate = LocalDate.now()
    salary = 50
    department = database.departments.find { it.name eq "tech" }
}

database.employees.add(employee)
```

Flush property changes in memory to database:

```kotlin
val employee = database.employees.find { it.id eq 2 } ?: return
employee.job = "engineer"
employee.salary = 100
employee.flushChanges()
```

Delete an entity from database:

```kotlin
val employee = database.employees.find { it.id eq 2 } ?: return
employee.delete()
```

Detailed usages of entity APIs can be found in the documentation of [column binding](https://www.ktorm.org/en/entities-and-column-binding.html) and [entity query](https://www.ktorm.org/en/entity-finding.html).

## Entity Sequence APIs

Ktorm provides a set of APIs named *Entity Sequence*, which can be used to obtain entity objects from databases. As the name implies, its style and use pattern are highly similar to the sequence APIs in Kotlin standard lib, as it provides many extension functions with the same names, such as `filter`, `map`, `reduce`, etc.

Most of the entity sequence APIs are provided as extension functions, which can be divided into two groups, they are intermediate operations and terminal operations.

### Intermediate Operations

These functions don’t execute the internal queries but return new-created sequence objects applying some modifications. For example, the `filter` function creates a new sequence object with the filter condition given by its parameter. The following code obtains all the employees in department 1 by using `filter`:

```kotlin
val employees = database.employees.filter { it.departmentId eq 1 }.toList()
```

We can see that the usage is almost the same as `kotlin.sequences`, the only difference is the `==` in the lambda is replaced by the `eq` function. The `filter` function can also be called continuously, as all the filter conditions are combined with the `and` operator.

```kotlin
val employees = database.employees
    .filter { it.departmentId eq 1 }
    .filter { it.managerId.isNotNull() }
    .toList()
```

Generated SQL:

```sql
select *
from t_employee
left join t_department _ref0 on t_employee.department_id = _ref0.id
where (t_employee.department_id = ?) and (t_employee.manager_id is not null)
```

Use `sortedBy` or `soretdByDescending` to sort entities in a sequence:

```kotlin
val employees = database.employees.sortedBy { it.salary }.toList()
```

Use `drop` and `take` for pagination:

```kotlin
val employees = database.employees.drop(1).take(1).toList()
```

### Terminal Operations

Terminal operations of entity sequences execute the queries right now, then obtain the query results and perform some calculations on them. The for-each loop is a typical terminal operation, and the following code uses it to print all employees in the sequence:

```kotlin
for (employee in database.employees) {
    println(employee)
}
```

Generated SQL:

```sql
select *
from t_employee
left join t_department _ref0 on t_employee.department_id = _ref0.id
```

The `toCollection` functions (including `toList`, `toSet`, etc.) are used to collect all the elements into a collection:

```kotlin
val employees = database.employees.toCollection(ArrayList())
```

The `mapColumns` function is used to obtain the results of a column:

```kotlin
val names = database.employees.mapColumns { it.name }
```

Additionally, if we want to select two or more columns, we just need to wrap our selected columns by `tupleOf` in the closure, and the function’s return type becomes `List<TupleN<C1?, C2?, .. Cn?>>`.

```kotlin
database.employees
    .filter { it.departmentId eq 1 }
    .mapColumns { tupleOf(it.id, it.name) }
    .forEach { (id, name) ->
        println("$id:$name")
    }
```

Generated SQL:

```sql
select t_employee.id, t_employee.name
from t_employee
where t_employee.department_id = ?
```

Other familiar functions are also supported, such as `fold`, `reduce`, `forEach`, etc. The following code calculates the total salary of all employees:

```kotlin
val totalSalary = database.employees.fold(0L) { acc, employee -> acc + employee.salary }
```

### Sequence Aggregation

The entity sequence APIs not only allow us to obtain entities from databases just like using `kotlin.sequences`, but they also provide rich support for aggregations, so we can conveniently count the columns, sum them, or calculate their averages, etc.

The following code obtains the max salary in department 1:

```kotlin
val max = database.employees
    .filter { it.departmentId eq 1 }
    .aggregateColumns { max(it.salary) }
```

Also, if we want to aggregate two or more columns, we just need to wrap our aggregate expressions by `tupleOf` in the closure, and the function’s return type becomes `TupleN<C1?, C2?, .. Cn?>`. The example below obtains the average and the range of salaries in department 1:

```kotlin
val (avg, diff) = database.employees
    .filter { it.departmentId eq 1 }
    .aggregateColumns { tupleOf(avg(it.salary), max(it.salary) - min(it.salary)) }
```

Generated SQL:

```sql
select avg(t_employee.salary), max(t_employee.salary) - min(t_employee.salary)
from t_employee
where t_employee.department_id = ?
```

Ktorm also provides many convenient helper functions implemented based on `aggregateColumns`, they are `count`, `any`, `none`, `all`, `sumBy`, `maxBy`, `minBy`, `averageBy`.

The following code obtains the max salary in department 1 using `maxBy` instead:

```kotlin
val max = database.employees
    .filter { it.departmentId eq 1 }
    .maxBy { it.salary }
```

Additionally, grouping aggregations are also supported, we just need to call `groupingBy` before calling `aggregateColumns`. The following code obtains the average salaries for each department. Here, the result's type is `Map<Int?, Double?>`, in which the keys are departments' IDs, and the values are the average salaries of the departments.

```kotlin
val averageSalaries = database.employees
    .groupingBy { it.departmentId }
    .aggregateColumns { avg(it.salary) }
```

Generated SQL:

```sql
select t_employee.department_id, avg(t_employee.salary)
from t_employee
group by t_employee.department_id
```

Ktorm also provides many convenient helper functions for grouping aggregations, they are `eachCount(To)`, `eachSumBy(To)`, `eachMaxBy(To)`, `eachMinBy(To)`, `eachAverageBy(To)`. With these functions, we can write the code below to obtain average salaries for each department:

```kotlin
val averageSalaries = database.employees
    .groupingBy { it.departmentId }
    .eachAverageBy { it.salary }
```

Other familiar functions are also supported, such as `aggregate`, `fold`, `reduce`, etc. They have the same names as the extension functions of `kotlin.collections.Grouping`, and the usages are totally the same. The following code calculates the total salaries for each department using `fold`:

```kotlin
val totalSalaries = database.employees
    .groupingBy { it.departmentId }
    .fold(0L) { acc, employee ->
        acc + employee.salary
    }
```

Detailed usages of entity sequence APIs can be found in the documentation of [entity sequence](https://www.ktorm.org/en/entity-sequence.html) and [sequence aggregation](https://www.ktorm.org/en/sequence-aggregation.html).