path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/cuhacking/app/home/domain/UpdateAnnouncementsUseCase.kt | cuhacking | 191,853,083 | false | null | package com.cuhacking.app.home.domain
import com.cuhacking.app.Database
import com.cuhacking.app.data.CoroutinesDispatcherProvider
import com.cuhacking.app.data.Result
import com.cuhacking.app.data.api.ApiService
import kotlinx.coroutines.withContext
import javax.inject.Inject
class UpdateAnnouncementsUseCase @Inject constructor(
private val database: Database,
private val dispatchers: CoroutinesDispatcherProvider,
private val api: ApiService
) {
suspend operator fun invoke(): Result<Unit> = withContext(dispatchers.io) {
val newUpdates = try {
api.getUpdates()
} catch (e: Exception) {
return@withContext Result.Error<Unit>(e)
}
val oldUpdateIds = database.announcementQueries.getAll().executeAsList().map { it.id }
// Insert updates that are not already contained in the database
newUpdates.updates.filter { (id) -> !oldUpdateIds.contains(id) }.forEach { (id, update) ->
database.announcementQueries.insert(
id,
update.name,
update.description,
update.location,
update.deliveryTime
)
}
// Remove updates from the database that are no longer live
val newUpdateIds = newUpdates.updates.keys
oldUpdateIds.filter { !newUpdateIds.contains(it) }.forEach(database.announcementQueries::delete)
return@withContext Result.Success(Unit)
}
} | 3 | Kotlin | 1 | 1 | ceca73d7eddf8c4082992ab30603817058ecfd49 | 1,477 | cuHacking-android | Apache License 2.0 |
app/src/main/java/infixsoft/imrankst1221/android/starter/data/repository/UserRepository.kt | imrankst1221 | 407,743,160 | false | null | package infixsoft.imrankst1221.android.starter.data.repository
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import infixsoft.imrankst1221.android.starter.data.api.SafeApiRequest
import infixsoft.imrankst1221.android.starter.data.api.UserApiService
import infixsoft.imrankst1221.android.starter.data.model.*
import infixsoft.imrankst1221.android.starter.utilities.*
import infixsoft.imrankst1221.android.starter.utilities.Extensions.notifyObserver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
import javax.inject.Singleton
/**
* @author imran.choudhury
* 30/9/21
*
* User Repository
*/
@Singleton
class UserRepository @Inject constructor(
private val networkHelper: NetworkHelper,
private val userDao: UserDao,
private val userDetailsDao: UserDetailsDao,
private val userNoteDao: UserNoteDao,
private val service: UserApiService): SafeApiRequest(){
// notify internet failed
private val isInternetFailed = MutableLiveData<Boolean>()
// notify user list api failed
private val isUserLoadFailed = MutableLiveData<Boolean>()
// notify user details api failed
private val isUserDetailsLoadFailed = MutableLiveData<Boolean>()
// user list
private val users = MutableLiveData<ArrayList<User>>()
// single user details
private val userDetails = MutableLiveData<UserDetails>()
init {
isInternetFailed.value = false
isUserLoadFailed.value = false
isUserDetailsLoadFailed.value = false
users.observeForever{
saveUsers(it)
}
userDetails.observeForever{
saveUserDetails(it)
}
}
private fun saveUsers(users: ArrayList<User>) {
Coroutines.io {
userDao.insertAll(users)
}
}
private fun saveUserDetails(userDetails: UserDetails){
Coroutines.io {
userDetailsDao.insertUserDetails(userDetails)
}
}
fun getUsers(): LiveData<ArrayList<User>> {
Coroutines.io {
val usersWithNote = userDao.getUsersWithNote()
users.postValue(ArrayList(usersWithNote))
}
return users
}
suspend fun loadMoreUsers() {
if (networkHelper.isNetworkConnected()) {
val size = users.value?.size ?: 0
val response = apiRequest { service.getUsers(size) }
isUserLoadFailed.value = false
if (size > 0){
users.value?.addAll(response)
users.notifyObserver()
}else{
users.postValue(response)
}
}else{
isInternetFailed.value = true
isUserLoadFailed.value = true
}
}
suspend fun getUserDetails(userName: String): LiveData<UserDetails> {
return withContext(Dispatchers.IO) {
userDetailsDao.getUserDetailsByLogin(userName)
}
}
suspend fun fetchUserDetails(userName: String) {
if (networkHelper.isNetworkConnected()) {
val response = apiRequest { service.getUserDetails(userName) }
userDetails.postValue(response)
isUserDetailsLoadFailed.value = false
}else{
isInternetFailed.value = true
isUserDetailsLoadFailed.value = true
}
}
suspend fun storeUserNote(note: UserNote){
userNoteDao.insertNote(note)
}
private suspend fun getUserNote(userId: Long): UserNote?{
return userNoteDao.getNote(userId)
}
suspend fun onNoInternetFailed(): LiveData<Boolean>{
return withContext(Dispatchers.IO) {
isInternetFailed
}
}
suspend fun onUserLoadFailed(): LiveData<Boolean>{
return withContext(Dispatchers.IO) {
isUserLoadFailed
}
}
suspend fun onUserDetailsLoadFailed(): LiveData<Boolean>{
return withContext(Dispatchers.IO) {
isUserDetailsLoadFailed
}
}
operator fun <T> MutableLiveData<ArrayList<T>>.plusAssign(values: List<T>) {
val value = this.value ?: arrayListOf()
value.addAll(values)
this.value = value
}
} | 0 | Kotlin | 0 | 0 | 1a122feef780f6b743a162f6648da41a5ed1640d | 4,207 | AndroidStarter | MIT License |
src/main/kotlin/org/intellij/plugin/tracker/data/links/BaseLinks.kt | JetBrains-Research | 277,519,535 | false | null | package org.intellij.plugin.tracker.data.links
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.VcsException
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.elementType
import org.intellij.plugin.tracker.core.change.ChangeTracker
import org.intellij.plugin.tracker.core.change.GitOperationManager
import org.intellij.plugin.tracker.core.update.LinkElement
import org.intellij.plugin.tracker.core.update.LinkElementImpl
import org.intellij.plugin.tracker.data.changes.Change
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownElementTypes.AUTOLINK
import org.intellij.plugins.markdown.lang.MarkdownElementTypes.LINK_DESTINATION
import java.nio.file.Paths
import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* An enum class for web link reference types
*/
enum class WebLinkReferenceType(private val type: String) {
COMMIT("COMMIT"),
BRANCH("BRANCH"),
TAG("TAG"),
INVALID("INVALID")
}
/**
* Base class for links
*/
abstract class Link(
/**
* Information about the link that has been retrieved from processing the markdown files
*/
open val linkInfo: LinkInfo,
/**
* Pattern that corresponds to a certain type of link (e.g. can be a WebLinkToFile pattern)
*/
open val pattern: Pattern? = null,
open var specificCommit: String? = null
) {
/**
* Get the matcher given by the pattern and linkInfo's linkPath property
*/
val matcher: Matcher by lazy {
val returnMatcher: Matcher = pattern!!.matcher(linkInfo.linkPath)
returnMatcher.matches()
returnMatcher
}
/**
* Returns the relative path at which the referenced element is located.
*/
abstract val path: String
/**
* The line number in case of a link to a line
*/
abstract val lineReferenced: Int
/**
* The file name of the element being referenced by the link
* Valid in case of links to files and lines.
*/
abstract val referencedFileName: String
/**
* The start line (inclusive) in case of links to multiple lines
*/
abstract val referencedStartingLine: Int
/**
* The end line (inclusive) in case of links to multiple lines
*/
abstract val referencedEndingLine: Int
/**
* Retrieve the changes of a specific link by passing in an
* implementation of the ChangeTrackerService interface
*/
abstract fun visit(visitor: ChangeTracker): Change
/**
* Performs a deep copy of the link and changes the after path of
* the copied link to be the one that is passed as a parameter
*/
abstract fun copyWithAfterPath(link: Link, afterPath: String): Link
/**
* Method that indicates whether the markdown file in which the link
* is located has been moved
*/
abstract fun markdownFileMoved(afterPath: String): Boolean
}
/**
* Abstract class for relative links
* Each link is bound to a specific change
*/
abstract class RelativeLink<in T : Change>(
override val linkInfo: LinkInfo,
override val pattern: Pattern? = null,
override var specificCommit: String? = null
) : Link(linkInfo, pattern, specificCommit) {
override val path: String
get() = linkInfo.linkPath
val relativePath: String
get() {
var path = linkInfo.linkPath
if (path.contains("%20")) {
path = path.replaceFirst("%20", " ")
}
return checkRelativeLink(path, linkInfo.proveniencePath)
}
/**
* Checks whether the markdown file in which this link is located has been moved
*/
override fun markdownFileMoved(afterPath: String): Boolean = checkRelativeLink(
linkInfo.getAfterPathToOriginalFormat(afterPath)!!,
linkInfo.proveniencePath) != afterPath
/**
* Method that, given
*/
abstract fun updateLink(change: T, index: Int, commitSHA: String?): String?
}
/**
* Abstract class for web links
*
* Includes common functions for web links
* Each link is bound to a specific change
*/
abstract class WebLink<in T : Change>(
override val linkInfo: LinkInfo,
override val pattern: Pattern,
override var specificCommit: String? = null
) : Link(linkInfo, pattern, specificCommit) {
/**
* Retrieves the reference type of this web link
* Be it a commit, tag or branch.
*
* This property is calculated only once per class instance
* due to it's expensive nature.
*/
var referenceType: WebLinkReferenceType? = null
get() {
if (field == null) {
val ref: String = referencingName
val gitOperationManager = GitOperationManager(linkInfo.project)
try {
val result: WebLinkReferenceType = when {
gitOperationManager.isRefABranch(ref) -> WebLinkReferenceType.BRANCH
gitOperationManager.isRefATag(ref) -> WebLinkReferenceType.TAG
gitOperationManager.isRefACommit(ref) -> WebLinkReferenceType.COMMIT
else -> WebLinkReferenceType.INVALID
}
field = result
} catch (e: VcsException) {
return field
}
}
return field
}
/**
* Get the platform name part from the URL
*/
val platformName: String
get() = matcher.group(4)
/**
* Get the project owner name part from the URL
*/
val projectOwnerName: String
get() = matcher.group(5)
/**
* Get the project name part from the URL
*/
val projectName: String
get() = matcher.group(6)
/**
* Get the referencing name part from the URL
*/
val referencingName: String
get() = matcher.group(9) ?: matcher.group(11)
/**
* Checks whether this web link is a permalink
*/
fun isPermalink(): Boolean {
if (referenceType == WebLinkReferenceType.COMMIT) return true
return false
}
/**
* Checks whether this link corresponds to the currently open project
*/
fun correspondsToLocalProject(gitRemoteOriginUrl: String): Boolean {
val remoteOriginUrl = "https://$platformName/$projectOwnerName/$projectName.git"
return gitRemoteOriginUrl == remoteOriginUrl
}
/**
* This method generates a new link based on the change object passed in
*
* If the reference type is a commit, then change the reference part of the link
* to point to the HEAD commit SHA
*
* Each sub-type of WebLink implements it's own new path generation method
*/
fun updateLink(change: T, index: Int, commitSHA: String?): String? {
var newPath: String = linkInfo.linkPath
if (referenceType == WebLinkReferenceType.COMMIT) {
if (commitSHA == null) return null
newPath = newPath.replace(referencingName, commitSHA)
}
// attach link prefix and suffix if specified (e.g. for web links of type <link path>)
if (linkInfo.linkPathPrefix != null) newPath = "${linkInfo.linkPathPrefix}$newPath"
if (linkInfo.linkPathSuffix != null) newPath = "$newPath${linkInfo.linkPathSuffix}"
return generateNewPath(change, index, newPath)
}
/**
* Generates a new, equivalent path, based on the change object passed in as a parameter
*/
abstract fun generateNewPath(change: T, index: Int, newPath: String): String?
/**
* Always return false, web links do not have relative paths and therefore
* are not affected by the markdown file being moved
*/
override fun markdownFileMoved(afterPath: String): Boolean = false
}
/**
* Data class which encapsulates information about links which are not supported and the reasoning
* why they are not supported
*/
data class NotSupportedLink(
override val linkInfo: LinkInfo,
override val pattern: Pattern? = null,
val errorMessage: String? = null
) : Link(linkInfo, pattern) {
override val lineReferenced: Int
get() = -1
override val referencedStartingLine: Int
get() = -1
override val referencedEndingLine: Int
get() = -1
override val referencedFileName: String
get() = ""
override val path: String
get() = linkInfo.linkPath
override fun copyWithAfterPath(link: Link, afterPath: String): NotSupportedLink {
val linkInfoCopy: LinkInfo = link.linkInfo.copy(linkPath = afterPath)
return copy(linkInfo = linkInfoCopy)
}
override fun visit(visitor: ChangeTracker): Change = throw UnsupportedOperationException()
override fun markdownFileMoved(afterPath: String): Boolean = throw UnsupportedOperationException()
}
/**
* Data class containing information about the link, which was retrieved from markdown files
*
*/
data class LinkInfo(
/**
* The link text of the link, as it appears in the markdown file
*/
val linkText: String,
/**
* The path, which could be a relative path or a web URL to a web-hosted repository
*/
var linkPath: String,
/**
* The path, relative to the project root directory, to the markdown file
* in which the link is located
*/
val proveniencePath: String,
/**
* The line number at which this link is found in the markdown file
*/
val foundAtLineNumber: Int,
/**
* The link element which owns the PSI element of the link
*/
var linkElement: LinkElement,
/**
* The name of the file in which the link is located
*/
val fileName: String,
/**
* The project in which the markdown file containing this link is located
*/
val project: Project,
/**
* Any link path prefix of the type '<' that accompanies the link path
*/
val linkPathPrefix: String? = null,
/**
* Any link path prefix of the type '>' that accompanies the link path
*/
val linkPathSuffix: String? = null,
/**
*
*/
val inlineLink: Boolean = true
) {
/**
* Gets the format in which the link appears in the markdown files
*/
fun getMarkDownSyntaxString(): String {
return when {
linkElement.getNode()?.elementType == LINK_DESTINATION && inlineLink -> "[$linkText]($linkPath)"
linkElement.getNode()?.elementType == LINK_DESTINATION && !inlineLink -> "[$linkText]: $linkPath"
linkElement.getNode()?.elementType == AUTOLINK -> {
var retString: String = linkPath
if (linkPathPrefix != null)
retString = linkPathPrefix + retString
if (linkPathSuffix != null)
retString += linkPathSuffix
retString
}
else -> linkPath
}
}
/**
* Get the after path (the newly generated path) into a path
* that is relative to the directory containing the markdown file, which in
* turn contains this link
*/
fun getAfterPathToOriginalFormat(afterPath: String): String? {
val targetPath = Paths.get(afterPath)
val sourcePath = Paths.get(proveniencePath).parent ?: Paths.get(".")
return try {
sourcePath?.relativize(targetPath).toString().replace("\\", "/")
} catch (e: IllegalArgumentException) {
null
}
}
companion object {
fun constructLinkInfoMarkdownLinkDestination(element: PsiElement, document: Document, file: PsiFile, project: Project): LinkInfo {
var inlineLink = true
if (element.parent.elementType == MarkdownElementTypes.LINK_DEFINITION) {
inlineLink = false
}
val linkText = element.parent.firstChild.node.text.replace("[", "").replace("]", "")
val lineNumber = document.getLineNumber(element.node.startOffset) + 1
val linkElement = LinkElementImpl(element)
val provPath = getProveniencePath(project.basePath!!, file)
return LinkInfo(linkText, element.node.text, provPath, lineNumber, linkElement, file.name, project, inlineLink = inlineLink)
}
fun constructLinkInfoAutoLink(element: PsiElement, document: Document, file: PsiFile, project: Project): LinkInfo {
val linkText = element.node.text.replace("<", "").replace(">", "")
val lineNumber = document.getLineNumber(element.node.startOffset) + 1
val linkElement = LinkElementImpl(element)
val provPath = getProveniencePath(project.basePath!!, file)
return LinkInfo(linkText, linkText, provPath, lineNumber, linkElement, file.name, project, "<", ">")
}
fun constructLinkInfoGfmAutoLink(element: PsiElement, document: Document, file: PsiFile, project: Project): LinkInfo {
val linkText = element.node.text
val lineNumber = document.getLineNumber(element.node.startOffset) + 1
val linkElement = LinkElementImpl(element)
val provPath = getProveniencePath(project.basePath!!, file)
return LinkInfo(linkText, linkText, provPath, lineNumber, linkElement, file.name, project)
}
private fun getProveniencePath(projectBasePath: String, file: PsiFile) =
file.virtualFile.path.replace("$projectBasePath/", "")
}
}
| 5 | null | 1 | 2 | 831e3eaa7ead78ffe277cb415b6f993139fb4de3 | 13,587 | linktracker | Apache License 2.0 |
increase-kotlin-core/src/main/kotlin/com/increase/api/models/IntrafiExclusion.kt | Increase | 614,596,742 | false | null | // File generated from our OpenAPI spec by Stainless.
package com.increase.api.models
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonAnySetter
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.increase.api.core.Enum
import com.increase.api.core.ExcludeMissing
import com.increase.api.core.JsonField
import com.increase.api.core.JsonMissing
import com.increase.api.core.JsonValue
import com.increase.api.core.NoAutoDetect
import com.increase.api.core.toUnmodifiable
import com.increase.api.errors.IncreaseInvalidDataException
import java.time.OffsetDateTime
import java.util.Objects
/**
* Certain institutions may be excluded per Entity when sweeping funds into the IntraFi network.
* This is useful when an Entity already has deposits at a particular bank, and does not want to
* sweep additional funds to it. It may take 5 business days for an exclusion to be processed.
*/
@JsonDeserialize(builder = IntrafiExclusion.Builder::class)
@NoAutoDetect
class IntrafiExclusion
private constructor(
private val bankName: JsonField<String>,
private val entityId: JsonField<String>,
private val excludedAt: JsonField<OffsetDateTime>,
private val fdicCertificateNumber: JsonField<String>,
private val id: JsonField<String>,
private val idempotencyKey: JsonField<String>,
private val status: JsonField<Status>,
private val submittedAt: JsonField<OffsetDateTime>,
private val type: JsonField<Type>,
private val additionalProperties: Map<String, JsonValue>,
) {
private var validated: Boolean = false
private var hashCode: Int = 0
/** The name of the excluded institution. */
fun bankName(): String = bankName.getRequired("bank_name")
/** The entity for which this institution is excluded. */
fun entityId(): String = entityId.getRequired("entity_id")
/** When this was exclusion was confirmed by IntraFi. */
fun excludedAt(): OffsetDateTime? = excludedAt.getNullable("excluded_at")
/** The Federal Deposit Insurance Corporation's certificate number for the institution. */
fun fdicCertificateNumber(): String? =
fdicCertificateNumber.getNullable("fdic_certificate_number")
/** The identifier of this exclusion request. */
fun id(): String = id.getRequired("id")
/**
* The idempotency key you chose for this object. This value is unique across Increase and is
* used to ensure that a request is only processed once. Learn more about
* [idempotency](https://increase.com/documentation/idempotency-keys).
*/
fun idempotencyKey(): String? = idempotencyKey.getNullable("idempotency_key")
/** The status of the exclusion request. */
fun status(): Status = status.getRequired("status")
/** When this was exclusion was submitted to IntraFi by Increase. */
fun submittedAt(): OffsetDateTime? = submittedAt.getNullable("submitted_at")
/**
* A constant representing the object's type. For this resource it will always be
* `intrafi_exclusion`.
*/
fun type(): Type = type.getRequired("type")
/** The name of the excluded institution. */
@JsonProperty("bank_name") @ExcludeMissing fun _bankName() = bankName
/** The entity for which this institution is excluded. */
@JsonProperty("entity_id") @ExcludeMissing fun _entityId() = entityId
/** When this was exclusion was confirmed by IntraFi. */
@JsonProperty("excluded_at") @ExcludeMissing fun _excludedAt() = excludedAt
/** The Federal Deposit Insurance Corporation's certificate number for the institution. */
@JsonProperty("fdic_certificate_number")
@ExcludeMissing
fun _fdicCertificateNumber() = fdicCertificateNumber
/** The identifier of this exclusion request. */
@JsonProperty("id") @ExcludeMissing fun _id() = id
/**
* The idempotency key you chose for this object. This value is unique across Increase and is
* used to ensure that a request is only processed once. Learn more about
* [idempotency](https://increase.com/documentation/idempotency-keys).
*/
@JsonProperty("idempotency_key") @ExcludeMissing fun _idempotencyKey() = idempotencyKey
/** The status of the exclusion request. */
@JsonProperty("status") @ExcludeMissing fun _status() = status
/** When this was exclusion was submitted to IntraFi by Increase. */
@JsonProperty("submitted_at") @ExcludeMissing fun _submittedAt() = submittedAt
/**
* A constant representing the object's type. For this resource it will always be
* `intrafi_exclusion`.
*/
@JsonProperty("type") @ExcludeMissing fun _type() = type
@JsonAnyGetter
@ExcludeMissing
fun _additionalProperties(): Map<String, JsonValue> = additionalProperties
fun validate(): IntrafiExclusion = apply {
if (!validated) {
bankName()
entityId()
excludedAt()
fdicCertificateNumber()
id()
idempotencyKey()
status()
submittedAt()
type()
validated = true
}
}
fun toBuilder() = Builder().from(this)
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is IntrafiExclusion &&
this.bankName == other.bankName &&
this.entityId == other.entityId &&
this.excludedAt == other.excludedAt &&
this.fdicCertificateNumber == other.fdicCertificateNumber &&
this.id == other.id &&
this.idempotencyKey == other.idempotencyKey &&
this.status == other.status &&
this.submittedAt == other.submittedAt &&
this.type == other.type &&
this.additionalProperties == other.additionalProperties
}
override fun hashCode(): Int {
if (hashCode == 0) {
hashCode =
Objects.hash(
bankName,
entityId,
excludedAt,
fdicCertificateNumber,
id,
idempotencyKey,
status,
submittedAt,
type,
additionalProperties,
)
}
return hashCode
}
override fun toString() =
"IntrafiExclusion{bankName=$bankName, entityId=$entityId, excludedAt=$excludedAt, fdicCertificateNumber=$fdicCertificateNumber, id=$id, idempotencyKey=$idempotencyKey, status=$status, submittedAt=$submittedAt, type=$type, additionalProperties=$additionalProperties}"
companion object {
fun builder() = Builder()
}
class Builder {
private var bankName: JsonField<String> = JsonMissing.of()
private var entityId: JsonField<String> = JsonMissing.of()
private var excludedAt: JsonField<OffsetDateTime> = JsonMissing.of()
private var fdicCertificateNumber: JsonField<String> = JsonMissing.of()
private var id: JsonField<String> = JsonMissing.of()
private var idempotencyKey: JsonField<String> = JsonMissing.of()
private var status: JsonField<Status> = JsonMissing.of()
private var submittedAt: JsonField<OffsetDateTime> = JsonMissing.of()
private var type: JsonField<Type> = JsonMissing.of()
private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()
internal fun from(intrafiExclusion: IntrafiExclusion) = apply {
this.bankName = intrafiExclusion.bankName
this.entityId = intrafiExclusion.entityId
this.excludedAt = intrafiExclusion.excludedAt
this.fdicCertificateNumber = intrafiExclusion.fdicCertificateNumber
this.id = intrafiExclusion.id
this.idempotencyKey = intrafiExclusion.idempotencyKey
this.status = intrafiExclusion.status
this.submittedAt = intrafiExclusion.submittedAt
this.type = intrafiExclusion.type
additionalProperties(intrafiExclusion.additionalProperties)
}
/** The name of the excluded institution. */
fun bankName(bankName: String) = bankName(JsonField.of(bankName))
/** The name of the excluded institution. */
@JsonProperty("bank_name")
@ExcludeMissing
fun bankName(bankName: JsonField<String>) = apply { this.bankName = bankName }
/** The entity for which this institution is excluded. */
fun entityId(entityId: String) = entityId(JsonField.of(entityId))
/** The entity for which this institution is excluded. */
@JsonProperty("entity_id")
@ExcludeMissing
fun entityId(entityId: JsonField<String>) = apply { this.entityId = entityId }
/** When this was exclusion was confirmed by IntraFi. */
fun excludedAt(excludedAt: OffsetDateTime) = excludedAt(JsonField.of(excludedAt))
/** When this was exclusion was confirmed by IntraFi. */
@JsonProperty("excluded_at")
@ExcludeMissing
fun excludedAt(excludedAt: JsonField<OffsetDateTime>) = apply {
this.excludedAt = excludedAt
}
/** The Federal Deposit Insurance Corporation's certificate number for the institution. */
fun fdicCertificateNumber(fdicCertificateNumber: String) =
fdicCertificateNumber(JsonField.of(fdicCertificateNumber))
/** The Federal Deposit Insurance Corporation's certificate number for the institution. */
@JsonProperty("fdic_certificate_number")
@ExcludeMissing
fun fdicCertificateNumber(fdicCertificateNumber: JsonField<String>) = apply {
this.fdicCertificateNumber = fdicCertificateNumber
}
/** The identifier of this exclusion request. */
fun id(id: String) = id(JsonField.of(id))
/** The identifier of this exclusion request. */
@JsonProperty("id") @ExcludeMissing fun id(id: JsonField<String>) = apply { this.id = id }
/**
* The idempotency key you chose for this object. This value is unique across Increase and
* is used to ensure that a request is only processed once. Learn more about
* [idempotency](https://increase.com/documentation/idempotency-keys).
*/
fun idempotencyKey(idempotencyKey: String) = idempotencyKey(JsonField.of(idempotencyKey))
/**
* The idempotency key you chose for this object. This value is unique across Increase and
* is used to ensure that a request is only processed once. Learn more about
* [idempotency](https://increase.com/documentation/idempotency-keys).
*/
@JsonProperty("idempotency_key")
@ExcludeMissing
fun idempotencyKey(idempotencyKey: JsonField<String>) = apply {
this.idempotencyKey = idempotencyKey
}
/** The status of the exclusion request. */
fun status(status: Status) = status(JsonField.of(status))
/** The status of the exclusion request. */
@JsonProperty("status")
@ExcludeMissing
fun status(status: JsonField<Status>) = apply { this.status = status }
/** When this was exclusion was submitted to IntraFi by Increase. */
fun submittedAt(submittedAt: OffsetDateTime) = submittedAt(JsonField.of(submittedAt))
/** When this was exclusion was submitted to IntraFi by Increase. */
@JsonProperty("submitted_at")
@ExcludeMissing
fun submittedAt(submittedAt: JsonField<OffsetDateTime>) = apply {
this.submittedAt = submittedAt
}
/**
* A constant representing the object's type. For this resource it will always be
* `intrafi_exclusion`.
*/
fun type(type: Type) = type(JsonField.of(type))
/**
* A constant representing the object's type. For this resource it will always be
* `intrafi_exclusion`.
*/
@JsonProperty("type")
@ExcludeMissing
fun type(type: JsonField<Type>) = apply { this.type = type }
fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
this.additionalProperties.clear()
this.additionalProperties.putAll(additionalProperties)
}
@JsonAnySetter
fun putAdditionalProperty(key: String, value: JsonValue) = apply {
this.additionalProperties.put(key, value)
}
fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
this.additionalProperties.putAll(additionalProperties)
}
fun build(): IntrafiExclusion =
IntrafiExclusion(
bankName,
entityId,
excludedAt,
fdicCertificateNumber,
id,
idempotencyKey,
status,
submittedAt,
type,
additionalProperties.toUnmodifiable(),
)
}
class Status
@JsonCreator
private constructor(
private val value: JsonField<String>,
) : Enum {
@com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is Status && this.value == other.value
}
override fun hashCode() = value.hashCode()
override fun toString() = value.toString()
companion object {
val PENDING = Status(JsonField.of("pending"))
val COMPLETED = Status(JsonField.of("completed"))
val ARCHIVED = Status(JsonField.of("archived"))
fun of(value: String) = Status(JsonField.of(value))
}
enum class Known {
PENDING,
COMPLETED,
ARCHIVED,
}
enum class Value {
PENDING,
COMPLETED,
ARCHIVED,
_UNKNOWN,
}
fun value(): Value =
when (this) {
PENDING -> Value.PENDING
COMPLETED -> Value.COMPLETED
ARCHIVED -> Value.ARCHIVED
else -> Value._UNKNOWN
}
fun known(): Known =
when (this) {
PENDING -> Known.PENDING
COMPLETED -> Known.COMPLETED
ARCHIVED -> Known.ARCHIVED
else -> throw IncreaseInvalidDataException("Unknown Status: $value")
}
fun asString(): String = _value().asStringOrThrow()
}
class Type
@JsonCreator
private constructor(
private val value: JsonField<String>,
) : Enum {
@com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is Type && this.value == other.value
}
override fun hashCode() = value.hashCode()
override fun toString() = value.toString()
companion object {
val INTRAFI_EXCLUSION = Type(JsonField.of("intrafi_exclusion"))
fun of(value: String) = Type(JsonField.of(value))
}
enum class Known {
INTRAFI_EXCLUSION,
}
enum class Value {
INTRAFI_EXCLUSION,
_UNKNOWN,
}
fun value(): Value =
when (this) {
INTRAFI_EXCLUSION -> Value.INTRAFI_EXCLUSION
else -> Value._UNKNOWN
}
fun known(): Known =
when (this) {
INTRAFI_EXCLUSION -> Known.INTRAFI_EXCLUSION
else -> throw IncreaseInvalidDataException("Unknown Type: $value")
}
fun asString(): String = _value().asStringOrThrow()
}
}
| 1 | null | 0 | 5 | dc1361d08cb41ff45817c2e7638f53356f15cf8e | 16,132 | increase-kotlin | Apache License 2.0 |
common/src/main/kotlin/juuxel/adorn/lib/AdornSounds.kt | Juuxel | 182,782,106 | false | null | package juuxel.adorn.lib
import juuxel.adorn.AdornCommon
import juuxel.adorn.lib.registry.Registered
import juuxel.adorn.lib.registry.Registrar
import juuxel.adorn.lib.registry.RegistrarFactory
import net.minecraft.registry.RegistryKeys
import net.minecraft.sound.BlockSoundGroup
import net.minecraft.sound.SoundEvent
object AdornSounds {
@JvmField
val SOUNDS: Registrar<SoundEvent> = RegistrarFactory.get().create(RegistryKeys.SOUND_EVENT)
val BLOCK_CHAIN_LINK_FENCE_BREAK = register("block.adorn.chain_link_fence.break")
val BLOCK_CHAIN_LINK_FENCE_STEP = register("block.adorn.chain_link_fence.step")
val BLOCK_CHAIN_LINK_FENCE_PLACE = register("block.adorn.chain_link_fence.place")
val BLOCK_CHAIN_LINK_FENCE_HIT = register("block.adorn.chain_link_fence.hit")
val BLOCK_CHAIN_LINK_FENCE_FALL = register("block.adorn.chain_link_fence.fall")
val CHAIN_LINK_FENCE: BlockSoundGroup = LazyBlockSoundGroup(
1.0F,
1.5F,
BLOCK_CHAIN_LINK_FENCE_BREAK::get,
BLOCK_CHAIN_LINK_FENCE_STEP::get,
BLOCK_CHAIN_LINK_FENCE_PLACE::get,
BLOCK_CHAIN_LINK_FENCE_HIT::get,
BLOCK_CHAIN_LINK_FENCE_FALL::get
)
fun init() {}
private fun register(name: String): Registered<SoundEvent> =
SOUNDS.register(name) { SoundEvent.of(AdornCommon.id(name)) }
private class LazyBlockSoundGroup(
volume: Float, pitch: Float,
private val breakSound: () -> SoundEvent,
private val stepSound: () -> SoundEvent,
private val placeSound: () -> SoundEvent,
private val hitSound: () -> SoundEvent,
private val fallSound: () -> SoundEvent
) : BlockSoundGroup(volume, pitch, null, null, null, null, null) {
override fun getBreakSound() = breakSound()
override fun getStepSound() = stepSound()
override fun getPlaceSound() = placeSound()
override fun getHitSound() = hitSound()
override fun getFallSound() = fallSound()
}
}
| 54 | null | 34 | 93 | 3d47e109812c8be26fc4fb581b9945c39ba6c96a | 1,992 | Adorn | MIT License |
src/main/kotlin/no/nav/poao_gcp_proxy/proxy_filter/PreRequestZuulFilter.kt | navikt | 423,828,208 | false | {"Kotlin": 14612, "Dockerfile": 83} | package no.nav.poao_gcp_proxy.proxy_filter
import com.netflix.zuul.ZuulFilter
import com.netflix.zuul.context.RequestContext
import com.netflix.zuul.exception.ZuulException
import no.nav.security.token.support.core.http.HttpRequest
import no.nav.security.token.support.core.validation.JwtTokenValidationHandler
import org.slf4j.LoggerFactory
class PreRequestZuulFilter(
private val jwtTokenValidationHandler: JwtTokenValidationHandler
) : ZuulFilter() {
companion object {
const val DOWNSTREAM_AUTHORIZATION_HEADER = "downstream-authorization"
const val AUTHORIZATION_HEADER = "authorization"
}
private val log = LoggerFactory.getLogger(this::class.java)
override fun shouldFilter() = true
override fun filterType() = "pre"
override fun filterOrder() = 1
override fun run(): Any? {
val ctx = RequestContext.getCurrentContext()
val request = ctx.request
val tokens = jwtTokenValidationHandler.getValidatedTokens(object : HttpRequest {
override fun getHeader(headerName: String?): String {
return request.getHeader(headerName) ?: ""
}
override fun getCookies(): Array<HttpRequest.NameValue> {
if (request.cookies == null) {
return emptyArray()
}
return request.cookies.iterator().asSequence().toList().map {
return@map object : HttpRequest.NameValue {
override fun getName(): String {
return it.name
}
override fun getValue(): String {
return it.value ?: ""
}
}
}.toTypedArray()
}
})
if (!tokens.hasValidToken()) {
log.warn("Request is not authenticated")
throw ZuulException("Request is not authenticated", 401, "Token is missing or invalid")
}
val downstreamAuthorizationHeader: String? = request.getHeader(DOWNSTREAM_AUTHORIZATION_HEADER)
ctx.addZuulRequestHeader(DOWNSTREAM_AUTHORIZATION_HEADER, null)
ctx.addZuulRequestHeader(AUTHORIZATION_HEADER, downstreamAuthorizationHeader)
return null
}
}
| 20 | Kotlin | 0 | 0 | 47f62bc3803be5fb618d747ced389b7dc1e908e3 | 1,939 | poao-gcp-proxy | MIT License |
app/src/main/java/com/sq26/experience/ui/activity/MediaOperatingActivity.kt | sq26 | 163,916,153 | false | {"Gradle": 3, "YAML": 1, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 43, "XML": 130, "Kotlin": 77, "AIDL": 4, "HTML": 1} | package com.sq26.experience.ui.activity
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.facebook.drawee.view.SimpleDraweeView
import com.sq26.experience.R
import com.sq26.experience.adapter.CommonAdapter
import com.sq26.experience.adapter.ViewHolder
import com.sq26.experience.ui.dialog.ProgressDialog
import com.sq26.experience.util.DensityUtil
import com.sq26.experience.util.FileUtil
import com.sq26.experience.util.media.JImage
import com.sq26.experience.util.media.SimpleDraweeViewUtils
class MediaOperatingActivity : AppCompatActivity() {
@JvmField
@BindView(R.id.preview)
var preview: SimpleDraweeView? = null
@JvmField
@BindView(R.id.imageRecyclerView)
var imageRecyclerView: RecyclerView? = null
private var imageAdapter: CommonAdapter? = null
private val imageArray = JSONArray()
private var context: Context? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_media_management)
ButterKnife.bind(this)
context = this
init()
}
private fun init() {
imageAdapter = object : CommonAdapter(R.layout.item_recyclerview, imageArray) {
override fun bindViewHolder(
viewHolder: ViewHolder,
jsonObject: JSONObject,
position: Int,
payload: Any
) {
viewHolder.setText(R.id.text, jsonObject.getString("name"))
viewHolder.itemView.setOnClickListener {
SimpleDraweeViewUtils.setDraweeController(
jsonObject.getString("path"),
preview,
DensityUtil.dip2px(context, 150f)
)
}
}
}
imageRecyclerView!!.addItemDecoration(
DividerItemDecoration(
this,
DividerItemDecoration.VERTICAL
)
)
imageRecyclerView!!.adapter = imageAdapter
}
@OnClick(R.id.getImage, R.id.getVideo)
fun onViewClicked(view: View) {
when (view.id) {
R.id.getImage -> JImage.initialize(this)
.setImageSource(JImage.ALL)
.isCompression(true)
.success { path: Array<String?> ->
var item: JSONObject
for (p in path) {
Log.d("getImage", p!!)
item = JSONObject()
item["name"] = FileUtil.getFileName(p)
item["path"] = p
imageArray.add(item)
}
imageAdapter!!.notifyDataSetChanged()
}.start()
R.id.getVideo -> {
val progressDialog = ProgressDialog(this)
.setMessage("123")
.show()
progressDialog.setMessage("321")
}
}
}
} | 0 | Kotlin | 0 | 0 | eefde2f206439813e509f86ac7dfea2e3ad8e9f2 | 3,385 | Android-Study-Demo | Apache License 2.0 |
core/src/main/java/com/sailer/core/navigation/InjectingNavHostFragment.kt | Ahmed-Abdelmeged | 273,714,513 | false | null | package com.sailer.core.navigation
import android.content.Context
import android.os.Bundle
import androidx.navigation.fragment.NavHostFragment
import com.sailer.core.di.FragmentInjectionFactory
import javax.inject.Inject
/**
* Created by <NAME> on 7/23/20.
*/
abstract class InjectingNavHostFragment : NavHostFragment() {
@Inject
lateinit var fragmentFactory: FragmentInjectionFactory
abstract fun onPerformInjection()
override fun onAttach(context: Context) {
super.onAttach(context)
onPerformInjection()
}
override fun onCreate(savedInstanceState: Bundle?) {
childFragmentManager.fragmentFactory = fragmentFactory
super.onCreate(savedInstanceState)
}
} | 1 | Kotlin | 8 | 39 | b9d46cd0c3d7aa3841e5020506be84f4038d9fe3 | 722 | sailer | MIT License |
app/src/main/java/com/example/learning3/MainActivity.kt | KrishnarajaSagar | 673,030,916 | false | null | package com.example.learning3
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.room.Room
import com.example.learning3.app.NotesApp
import com.example.learning3.data.NoteDatabase
import com.example.learning3.ui.theme.Learning3Theme
import com.example.learning3.viewmodel.NotesViewModel
class MainActivity : ComponentActivity() {
private val db by lazy {
Room.databaseBuilder(
applicationContext,
NoteDatabase::class.java,
"notes.db"
).build()
}
private val viewModel by viewModels<NotesViewModel>(
factoryProducer = {
object: ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return NotesViewModel(db.noteDao) as T
}
}
}
)
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Learning3Theme {
NotesApp(viewModel)
}
}
}
}
class DemoNote(
val title: String,
val content: String,
)
val notes: List<DemoNote> = listOf(
DemoNote("Title Title Title Title Title", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Suspendisse potenti nullam ac tortor vitae purus. Pharetra magna ac placerat vestibulum lectus mauris ultrices. Enim sit amet venenatis urna cursus eget nunc scelerisque viverra. Auctor eu augue ut lectus arcu bibendum at varius. Viverra orci sagittis eu volutpat. A pellentesque sit amet porttitor eget dolor morbi non. Ipsum consequat nisl vel pretium lectus quam id leo in. Convallis a cras semper auctor neque vitae tempus quam. Orci a scelerisque purus semper eget duis at tellus at. Quam adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus. Porttitor lacus luctus accumsan tortor posuere. Ac ut consequat semper viverra nam libero justo laoreet. Accumsan tortor posuere ac ut consequat semper viverra."),
DemoNote("Title Title Title Title Title", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Suspendisse potenti nullam ac tortor vitae purus. Pharetra magna ac placerat vestibulum lectus mauris ultrices. Enim sit amet venenatis urna cursus eget nunc scelerisque viverra. Auctor eu augue ut lectus arcu bibendum at varius. Viverra orci sagittis eu volutpat. A pellentesque sit amet porttitor eget dolor morbi non. Ipsum consequat nisl vel pretium lectus quam id leo in. Convallis a cras semper auctor neque vitae tempus quam. Orci a scelerisque purus semper eget duis at tellus at. Quam adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus. Porttitor lacus luctus accumsan tortor posuere. Ac ut consequat semper viverra nam libero justo laoreet. Accumsan tortor posuere ac ut consequat semper viverra."),
DemoNote("Title Title Title Title Title", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 4", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 1", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 2", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 3", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 4", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 1", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 2", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 3", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 4", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 1", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 2", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 3", "ih sdi uhsu dasuh xkcn kjn sdj"),
DemoNote("Title 4", "ih sdi uhsu dasuh xkcn kjn sdj"),
)
data class MenuItem(
val index: Int,
val label: String
)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun IndividualNoteView() {
val note: DemoNote = DemoNote("Title Title Title Title Title Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Suspendisse potenti nullam ac tortor vitae purus. Pharetra magna ac placerat vestibulum lectus mauris ultrices.", "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Suspendisse potenti nullam ac tortor vitae purus. Pharetra magna ac placerat vestibulum lectus mauris ultrices. Enim sit amet venenatis urna cursus eget nunc scelerisque viverra. Auctor eu augue ut lectus arcu bibendum at varius. Viverra orci sagittis eu volutpat. A pellentesque sit amet porttitor eget dolor morbi non. Ipsum consequat nisl vel pretium lectus quam id leo in. Convallis a cras semper auctor neque vitae tempus quam. Orci a scelerisque purus semper eget duis at tellus at. Quam adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus. Porttitor lacus luctus accumsan tortor posuere. Ac ut consequat semper viverra nam libero justo laoreet. Accumsan tortor posuere ac ut consequat semper viverra.")
var expanded by remember { mutableStateOf(false) }
val menuItems = listOf<String>(
"Edit note",
"Delete note"
)
Scaffold(
topBar = {
TopAppBar(
title = {},
navigationIcon = {
IconButton(
onClick = {}
) {
Icon(Icons.Default.ArrowBack,contentDescription = "Back")
}
},
actions = {
IconButton(
onClick = {
expanded = true
}
) {
Icon(Icons.Default.MoreVert,
contentDescription = "More options")
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
menuItems.forEachIndexed { index, item ->
DropdownMenuItem(
text = { Text(item) },
onClick = {
expanded = false
}
)
}
}
}
)
}
) { padding ->
Column(
modifier = Modifier
.padding(padding)
.padding(
horizontal = 16.dp
)
) {
Text(
text = note.title,
style = MaterialTheme.typography.bodyLarge.copy(
fontSize = 18.sp,
fontWeight = FontWeight.SemiBold,
lineHeight = 22.sp
),
)
Spacer(
modifier = Modifier
.height(16.dp)
)
Text(
text = note.content,
style = MaterialTheme.typography.bodyMedium.copy(
fontSize = 16.sp,
)
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreateNoteView() {
var title by remember { mutableStateOf(TextFieldValue("")) }
var content by remember { mutableStateOf(TextFieldValue("")) }
Scaffold(
topBar = {
TopAppBar(
title = {},
navigationIcon = {
IconButton(
onClick = {}
) {
Icon(Icons.Default.ArrowBack,contentDescription = "Back")
}
}
)
}
) { padding ->
Column(
modifier = Modifier
.padding(padding)
.padding(
horizontal = 16.dp
)
.padding(
bottom = 16.dp
)
.verticalScroll(rememberScrollState())
) {
TextField(
value = title,
onValueChange = { newTitle ->
title = newTitle
},
placeholder = { Text("Title", style = MaterialTheme.typography.bodyLarge.copy(
fontSize = 18.sp,
fontWeight = FontWeight.SemiBold,
lineHeight = 22.sp,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
),) },
colors = TextFieldDefaults.textFieldColors(
containerColor = MaterialTheme.colorScheme.surface,
textColor = MaterialTheme.colorScheme.onSurface,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent
),
textStyle = MaterialTheme.typography.bodyLarge.copy(
fontSize = 18.sp,
fontWeight = FontWeight.SemiBold,
lineHeight = 22.sp
),
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Next
),
)
Spacer(
modifier = Modifier
.height(16.dp)
)
TextField(
value = content,
onValueChange = { newContent ->
content = newContent
},
placeholder = { Text("Content", style = MaterialTheme.typography.bodyMedium.copy(
fontSize = 16.sp,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
)) },
colors = TextFieldDefaults.textFieldColors(
containerColor = MaterialTheme.colorScheme.surface,
textColor = MaterialTheme.colorScheme.onSurface,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent
),
textStyle = MaterialTheme.typography.bodyMedium.copy(
fontSize = 16.sp,
),
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Done
)
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NoteItem(note: DemoNote) {
Card(
modifier = Modifier
.padding(8.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
),
onClick = {}
) {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxHeight()
) {
Text(
text = note.title,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodyLarge.copy(
fontSize = 18.sp,
fontWeight = FontWeight.SemiBold,
lineHeight = 22.sp
),
)
Spacer(
modifier = Modifier
.height(8.dp)
)
Text(
text = note.content,
maxLines = 8,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodyMedium.copy(
fontSize = 16.sp,
)
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NotesSearchBar() {
Box(
modifier = Modifier
.padding(
16.dp
)
.wrapContentHeight()
.background(
color = MaterialTheme.colorScheme.onSurfaceVariant,
shape = RoundedCornerShape(60.dp)
),
) {
TextField(
value = "",
onValueChange = { },
placeholder = { Text("Search", style = MaterialTheme.typography.bodyMedium.copy(
fontSize = 16.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
)) },
singleLine = true,
colors = TextFieldDefaults.textFieldColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
textColor = MaterialTheme.colorScheme.onSurfaceVariant,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent
),
textStyle = MaterialTheme.typography.bodyMedium.copy(
fontSize = 16.sp,
),
modifier = Modifier
.fillMaxWidth(),
leadingIcon = {
Icon(imageVector = Icons.Default.Search, contentDescription = "Search icon")
},
)
}
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Preview(showBackground = true)
@Composable
fun AppPreview() {
Learning3Theme {
CreateNoteView()
}
} | 4 | Kotlin | 1 | 8 | e1c3b5a59d3c91451210bcf3a5a3b4e9b3859ca6 | 16,246 | NotesAppCompose | Apache License 2.0 |
app/src/main/java/com/android/hhn/kotlintoy/coroutines/TestCoroutine2.kt | Hehaonan | 258,992,249 | false | null | package com.android.hhn.kotlintoy.coroutines
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
/**
* Author: haonan.he ;<p/>
* Date: 2020/4/29,6:23 PM ;<p/>
* Description: 同步任务;<p/>
* Other: ;
*/
fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
GlobalScope.launch {
val token = doSomethingUsefulOne()
doSomethingUsefulTwo(token)
}.join()
}
println("Completed in $time ms")
}
suspend fun doSomethingUsefulOne(): String {
delay(2000L) // 假设我们在这里做了些有用的事
println("doSomethingUsefulOne")
return "token"
}
suspend fun doSomethingUsefulTwo(token: String) {
delay(1000L)
println("doSomethingUsefulTwo need:$token")
} | 0 | Kotlin | 0 | 0 | e653e2edfd0d9e3b34d9fcbed380fcd6630fd1df | 722 | KotlinToy | Apache License 2.0 |
src/main/kotlin/jp/takeda/doma2sample/controller/AddressController.kt | takedasan | 160,204,434 | false | {"Gradle": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Kotlin": 19, "Java": 1, "SQL": 4, "YAML": 1} | package jp.takeda.doma2sample.controller
import jp.takeda.doma2sample.domain.service.AddressService
import jp.takeda.doma2sample.domain.service.FindAddressResult
import jp.takeda.doma2sample.dto.request.insert.WriteAddressRequest
import jp.takeda.doma2sample.dto.response.find.FindAddressResponse
import jp.takeda.doma2sample.dto.response.insert.WriteAddressResponse
import jp.takeda.doma2sample.dto.response.search.SelectAddressListResponse
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("addresses")
class AddressController(
val addressService: AddressService
) {
@GetMapping
fun getAddressList(): SelectAddressListResponse {
return addressService.search()
}
@GetMapping("{id}", produces = ["application/json"])
fun getAddress(@PathVariable("id") id: Int): ResponseEntity<FindAddressResponse> {
val result = addressService.find(id)
return when (result) {
is FindAddressResult.Found -> ResponseEntity.ok(result.response)
is FindAddressResult.NotFound -> ResponseEntity.notFound().build()
}
}
@PostMapping
fun postAddress(request: WriteAddressRequest): WriteAddressResponse {
return addressService.insert(request)
}
} | 1 | null | 2 | 1 | 0776b60968f57eb544c08d31c923f43588dae696 | 1,312 | doma2samplekotlin | MIT License |
compiler/testData/asJava/lightClasses/nullabilityAnnotations/ClassObjectField.kt | chashnikov | 14,658,474 | true | {"Java": 14526655, "Kotlin": 6831811, "JavaScript": 897073, "Groovy": 43935, "CSS": 14421, "Shell": 9248} | // ClassObjectField
class ClassObjectField {
class object {
val x: String? = ""
private val y: String? = ""
}
} | 0 | Java | 0 | 1 | 88a261234860ff0014e3c2dd8e64072c685d442d | 136 | kotlin | Apache License 2.0 |
compiler/testData/asJava/lightClasses/nullabilityAnnotations/ClassObjectField.kt | chashnikov | 14,658,474 | true | {"Java": 14526655, "Kotlin": 6831811, "JavaScript": 897073, "Groovy": 43935, "CSS": 14421, "Shell": 9248} | // ClassObjectField
class ClassObjectField {
class object {
val x: String? = ""
private val y: String? = ""
}
} | 0 | Java | 0 | 1 | 88a261234860ff0014e3c2dd8e64072c685d442d | 136 | kotlin | Apache License 2.0 |
src/main/kotlin/no/nav/familie/ba/mottak/søknad/domene/SøknadSpråkvelgerService.kt | navikt | 221,166,975 | false | null | package no.nav.familie.ba.mottak.søknad.domene
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.module.kotlin.convertValue
import no.nav.familie.kontrakter.ba.søknad.v4.Søknaddokumentasjon
import no.nav.familie.kontrakter.ba.søknad.v4.Søknadsfelt
import org.springframework.stereotype.Service
import no.nav.familie.kontrakter.felles.objectMapper as getObjectMapper
@Service
class SøknadSpråkvelgerService {
private val defaultLocale = "nb"
var valgtLocale = defaultLocale
val objectMapper = getObjectMapper.apply {
registerModule(
SimpleModule().apply {
addSerializer(Søknadsfelt::class.java, SøknadsfeltSerializer())
addSerializer(Søknaddokumentasjon::class.java, SøknaddokumentasjonSerializer())
}
)
}
fun velgSøknadSpråk(versjonertSøknad: VersjonertSøknad, språk: String): String {
valgtLocale = språk
val asMap = objectMapper.convertValue<MutableMap<String, Any>>(
when (versjonertSøknad) {
is SøknadV6 -> versjonertSøknad.søknad
is SøknadV7 -> versjonertSøknad.søknad
}
)
asMap["teksterUtenomSpørsmål"] = when (versjonertSøknad) {
is SøknadV6 -> versjonertSøknad.søknad.teksterUtenomSpørsmål
is SøknadV7 -> versjonertSøknad.søknad.teksterUtenomSpørsmål
}.mapValues { it.value[valgtLocale] }
valgtLocale = defaultLocale
return objectMapper.writeValueAsString(asMap)
}
inner class SøknaddokumentasjonSerializer : JsonSerializer<Søknaddokumentasjon>() {
override fun serialize(dokumentasjon: Søknaddokumentasjon, jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider) {
return jsonGenerator.writeObject(
mapOf(
"dokumentasjonsbehov" to dokumentasjon.dokumentasjonsbehov,
"harSendtInn" to dokumentasjon.harSendtInn,
"opplastedeVedlegg" to dokumentasjon.opplastedeVedlegg,
"dokumentasjonSpråkTittel" to dokumentasjon.dokumentasjonSpråkTittel[valgtLocale]
)
)
}
}
inner class SøknadsfeltSerializer : JsonSerializer<Søknadsfelt<*>>() {
override fun serialize(søknadsFelt: Søknadsfelt<*>, jsonGenerator: JsonGenerator, serializerProvider: SerializerProvider) {
return jsonGenerator.writeObject(
mapOf(
"label" to søknadsFelt.label[valgtLocale],
"verdi" to søknadsFelt.verdi[valgtLocale]
)
)
}
}
}
| 5 | Kotlin | 0 | 1 | eb41486fc5ab103a4334a2d3d08f1d7f50e2cf97 | 2,824 | familie-ba-mottak | MIT License |
src/test/kotlin/dev/shtanko/algorithms/leetcode/RegularExpressionMatchingTest.kt | ashtanko | 203,993,092 | false | null | /*
* Copyright 2020 <NAME>
*
* 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.
*/
package dev.shtanko.algorithms.leetcode
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
abstract class RegularExpressionMatchingStrategyTest<out T : RegularExpressionMatchStrategy>(private val strategy: T) {
companion object {
@JvmStatic
fun dataProvider(): List<Pair<Pair<String, String>, Boolean>> {
return listOf(
"aa" to "a" to false,
"aa" to "a*" to true,
"ab" to ".*" to true,
"aab" to "c*a*b" to true,
"mississippi" to "mis*is*p*." to false,
)
}
}
@ParameterizedTest
@MethodSource("dataProvider")
fun `regular expression matching test`(testCase: Pair<Pair<String, String>, Boolean>) {
val (data, expected) = testCase
val (text, pattern) = data
val actual = strategy.invoke(text = text, pattern = pattern)
assertEquals(expected, actual)
}
}
class RegularExpressionMatchRecursionTest :
RegularExpressionMatchingStrategyTest<RegularExpressionMatchRecursion>(RegularExpressionMatchRecursion())
class RegularExpressionMatchDPTopDownTest :
RegularExpressionMatchingStrategyTest<RegularExpressionMatchDPTopDown>(RegularExpressionMatchDPTopDown())
class RegularExpressionMatchDPBottomUpTest :
RegularExpressionMatchingStrategyTest<RegularExpressionMatchDPBottomUp>(RegularExpressionMatchDPBottomUp())
| 4 | Kotlin | 0 | 18 | a4fe620690f370a9eaaa7f7a5e5b2001aa65502b | 2,104 | kotlab | Apache License 2.0 |
Pokedex/app/src/main/java/com/ivettevaldez/pokedex/ui/MainActivity.kt | ivettevaldez | 635,742,104 | false | {"Kotlin": 70978} | package com.ivettevaldez.pokedex.ui
import android.os.Bundle
import com.ivettevaldez.pokedex.global.BaseActivity
import com.ivettevaldez.pokedex.ui.common.viewbinding.ViewBindingFactory
import javax.inject.Inject
class MainActivity : BaseActivity() {
@Inject
lateinit var viewBindingFactory: ViewBindingFactory
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injector.inject(this)
val binding = viewBindingFactory.newMainBinding()
setContentView(binding.root)
}
} | 0 | Kotlin | 1 | 0 | 02fdb04a72baa1bafa2ae9254bc7dee97ed62003 | 556 | pokedex | Apache License 2.0 |
felles/src/main/kotlin/no/nav/familie/kontrakter/felles/personopplysning/FinnPersonidenterResponse.kt | navikt | 206,793,193 | false | null | package no.nav.familie.kontrakter.felles.personopplysning
data class FinnPersonidenterResponse(val identer: List<PersonIdentMedHistorikk>)
data class PersonIdentMedHistorikk(val personIdent: String, val historisk: Boolean) | 16 | null | 0 | 2 | 597be6d19d00fabd01258b180883b6532ff91c46 | 224 | familie-kontrakter | MIT License |
XiaomiNFCProtocol/src/main/kotlin/lib/xfy9326/xiaomi/nfc/XiaomiNfcProtocol.kt | XFY9326 | 724,531,401 | false | {"Kotlin": 300068} | package lib.xfy9326.xiaomi.nfc
sealed class XiaomiNfcProtocol<T : AppData>(internal val flags: Byte) {
companion object {
private const val FLAG_V1 = 0.toByte()
private const val FLAG_V2 = 1.toByte()
private const val FLAG_HANDOFF = 3.toByte()
fun parse(value: Byte) =
when (value) {
FLAG_V1 -> V1
FLAG_V2 -> V2
FLAG_HANDOFF -> HandOff
else -> error("Unknown protocol flag $value")
}
}
abstract fun decode(bytes: ByteArray): T
data object V1 : XiaomiNfcProtocol<NfcTagAppData>(FLAG_V1) {
override fun decode(bytes: ByteArray): NfcTagAppData = NfcTagAppData.decode(bytes)
}
data object V2 : XiaomiNfcProtocol<NfcTagAppData>(FLAG_V2) {
override fun decode(bytes: ByteArray): NfcTagAppData = NfcTagAppData.decode(bytes)
}
data object HandOff : XiaomiNfcProtocol<HandoffAppData>(FLAG_HANDOFF) {
override fun decode(bytes: ByteArray): HandoffAppData = HandoffAppData.decode(bytes)
}
} | 1 | Kotlin | 4 | 91 | 85489b59c617f3ee8d006c47b73f53bbc4e08bc3 | 1,065 | MiLinkNFC | MIT License |
app/src/main/java/com/vaibhav/taskify/ui/adapters/TaskCountAdapter.kt | Vaibhav2002 | 375,697,442 | false | null | package com.vaibhav.taskify.ui.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.vaibhav.taskify.data.models.TaskCount
import com.vaibhav.taskify.databinding.TaskTypeRecyclerItemBinding
class TaskCountAdapter :
ListAdapter<TaskCount, TaskCountAdapter.TaskCountViewHolder>(TaskCountDiff()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskCountViewHolder {
val binding =
TaskTypeRecyclerItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return TaskCountViewHolder(binding)
}
override fun onBindViewHolder(holder: TaskCountViewHolder, position: Int) {
holder.bind(currentList[position])
}
inner class TaskCountViewHolder(private val binding: TaskTypeRecyclerItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(data: TaskCount) {
binding.task = data
}
}
class TaskCountDiff : DiffUtil.ItemCallback<TaskCount>() {
override fun areItemsTheSame(oldItem: TaskCount, newItem: TaskCount): Boolean {
return oldItem.taskType == newItem.taskType
}
override fun areContentsTheSame(oldItem: TaskCount, newItem: TaskCount): Boolean {
return oldItem == newItem
}
}
} | 1 | null | 29 | 89 | 664a4cd4600a6bfc12082f9f083897fb8b4001c7 | 1,458 | Taskify | MIT License |
src/main/kotlin/de/ukw/ccc/mafrepo/web/UploadRestController.kt | CCC-MF | 655,735,002 | false | {"Kotlin": 80862, "HTML": 15310, "CSS": 5149, "JavaScript": 3872} | /*
* MIT License
*
* Copyright (c) 2023 Comprehensive Cancer Center Mainfranken
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package de.ukw.ccc.mafrepo.web
import de.ukw.ccc.mafrepo.model.MafUploadId
import de.ukw.ccc.mafrepo.model.MafUploadRepository
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController
@RestController
class UploadRestController(
private val mafUploadRepository: MafUploadRepository
) {
@DeleteMapping(path = ["/uploads/{id}"])
fun deleteUpload(@PathVariable id: MafUploadId) {
mafUploadRepository.deleteById(id)
}
} | 1 | Kotlin | 0 | 0 | 996c13c551cfc803d3c4014c919fab4146ffb633 | 1,731 | maf-repo | MIT License |
app/src/main/java/com/example/jpmorgantest/util/extension/ValidationNull.kt | cesarwillymc | 861,347,513 | false | {"Kotlin": 126062, "Java": 3448} | package com.example.jpmorgantest.util.extension
import com.example.jpmorgantest.util.constants.EMPTY_STRING
import com.example.jpmorgantest.util.constants.ZERO
import com.example.jpmorgantest.util.constants.ZERO_D
import com.example.jpmorgantest.util.constants.ZERO_F
fun Int?.orEmpty(): Int = this ?: ZERO
fun Long?.orEmpty(): Long = this ?: ZERO.toLong()
fun Boolean?.orEmpty(): Boolean = this ?: false
fun Double?.orEmpty(): Double = this ?: ZERO_D
fun Float?.orEmpty(): Float = this ?: ZERO_F
fun String?.orEmpty(): String = this ?: EMPTY_STRING
inline fun <reified T> List<T>?.orEmpty(): List<T> = this ?: listOf<T>()
inline fun <reified T> T?.ifNotNull(crossinline block: (T) -> Unit) {
if (this != null) {
block(this)
}
}
| 0 | Kotlin | 0 | 0 | 832154825f03a17ff81b87c0ae9b3e6edefbbd5c | 754 | JPMorganTest | Apache License 2.0 |
app/src/main/java/com/vultisig/wallet/ui/screens/vault_settings/VaultSettingsScreen.kt | vultisig | 789,965,982 | false | null | package com.vultisig.wallet.ui.screens.vault_settings
import android.os.Build
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.vultisig.wallet.R
import com.vultisig.wallet.common.backupVaultToDownloadsDir
import com.vultisig.wallet.ui.components.SettingsItem
import com.vultisig.wallet.ui.components.TopBar
import com.vultisig.wallet.ui.navigation.Destination
import com.vultisig.wallet.ui.navigation.Screen
import com.vultisig.wallet.ui.screens.vault_settings.VaultSettingsUiEvent.BackupFailed
import com.vultisig.wallet.ui.screens.vault_settings.VaultSettingsUiEvent.BackupFile
import com.vultisig.wallet.ui.screens.vault_settings.VaultSettingsUiEvent.BackupSuccess
import com.vultisig.wallet.ui.theme.Theme
@Composable
internal fun VaultSettingsScreen(
navController: NavController,
) {
val viewModel = hiltViewModel<VaultSettingsViewModel>()
val uiModel by viewModel.uiModel.collectAsState()
val context = LocalContext.current
val snackBarHostState = remember { SnackbarHostState() }
LaunchedEffect(key1 = Unit) {
viewModel.channelFlow.collect { event ->
when (event) {
is BackupSuccess ->
snackBarHostState.showSnackbar(
context.getString(
R.string.vault_settings_success_backup_file,
event.backupFileName
)
)
BackupFailed ->
snackBarHostState.showSnackbar(
context.getString(
R.string.vault_settings_error_backup_file,
)
)
is BackupFile ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val isSuccess = context.backupVaultToDownloadsDir(event.json, event.backupFileName)
if (isSuccess)
viewModel.successBackup(event.backupFileName)
else
viewModel.errorBackUp()
}
}
}
}
Scaffold(
snackbarHost = {
SnackbarHost(snackBarHostState)
},
) { padding ->
Column(
modifier = Modifier
.consumeWindowInsets(padding)
.background(Theme.colors.oxfordBlue800)
.fillMaxSize(),
) {
TopBar(
navController = navController,
startIcon = R.drawable.caret_left,
centerText = stringResource(R.string.vault_settings_title)
)
Column(
modifier = Modifier
.fillMaxSize()
.padding(all = 16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
SettingsItem(
title = stringResource(R.string.vault_settings_details_title),
subtitle = stringResource(R.string.vault_settings_details_subtitle),
icon = android.R.drawable.ic_menu_info_details,
) {
uiModel.id.let { vaultName ->
navController.navigate(Destination.Details(vaultName).route)
}
}
SettingsItem(
title = stringResource(R.string.vault_settings_backup_title),
subtitle = stringResource(R.string.vault_settings_backup_subtitle),
icon = R.drawable.download_simple,
onClick = viewModel::backupVault)
SettingsItem(
title = stringResource(R.string.vault_settings_rename_title),
subtitle = stringResource(R.string.vault_settings_rename_subtitle),
icon = R.drawable.pencil
) {
uiModel.id.let { vaultName ->
navController.navigate(Destination.Rename(vaultName).route)
}
}
SettingsItem(
title = stringResource(R.string.vault_settings_reshare_title),
subtitle = stringResource(R.string.vault_settings_reshare_subtitle),
icon = R.drawable.share
) {
navController.navigate(
Screen.Setup.createRoute(
uiModel.id,
)
)
}
SettingsItem(
title = stringResource(R.string.vault_settings_delete_title),
subtitle = stringResource(R.string.vault_settings_delete_subtitle),
icon = R.drawable.trash_outline,
colorTint = Theme.colors.red,
onClick = viewModel::navigateToConfirmDeleteScreen
)
}
}
}
}
@Preview
@Composable
private fun VaultSettingsScreenPreview() {
VaultSettingsScreen(navController = rememberNavController())
} | 36 | null | 2 | 4 | f6be95cf5d32abbdbfb3003c61b960067a6b33cb | 6,111 | vultisig-android | Apache License 2.0 |
ktor-server/ktor-server-test-host/jvmAndNix/src/io/ktor/server/testing/EngineTestBase.kt | ktorio | 40,136,600 | false | null | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.testing
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.routing.*
import io.ktor.util.logging.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
expect abstract class EngineTestBase<TEngine : ApplicationEngine, TConfiguration : ApplicationEngine.Configuration>(
applicationEngineFactory: ApplicationEngineFactory<TEngine, TConfiguration>,
) : BaseTest, CoroutineScope {
override val coroutineContext: CoroutineContext
@Target(AnnotationTarget.FUNCTION)
@Retention
protected annotation class Http2Only()
val applicationEngineFactory: ApplicationEngineFactory<TEngine, TConfiguration>
protected var enableHttp2: Boolean
protected var enableSsl: Boolean
protected var enableCertVerify: Boolean
protected var port: Int
protected var sslPort: Int
protected var server: EmbeddedServer<TEngine, TConfiguration>?
protected fun createAndStartServer(
log: Logger? = null,
parent: CoroutineContext = EmptyCoroutineContext,
routingConfigurer: Route.() -> Unit
): EmbeddedServer<TEngine, TConfiguration>
protected open fun plugins(application: Application, routingConfig: Route.() -> Unit)
protected fun withUrl(
path: String,
builder: suspend HttpRequestBuilder.() -> Unit = {},
block: suspend HttpResponse.(Int) -> Unit
)
}
| 269 | null | 986 | 9,709 | 9e0eb99aa2a0a6bc095f162328525be1a76edb21 | 1,603 | ktor | Apache License 2.0 |
common/src/main/kotlin/no/nav/su/se/bakover/common/application/journal/JournalpostId.kt | navikt | 227,366,088 | false | null | package no.nav.su.se.bakover.common.application.journal
import com.fasterxml.jackson.annotation.JsonValue
data class JournalpostId(
private val value: String,
) {
@JsonValue
override fun toString() = value
}
| 0 | Kotlin | 0 | 1 | d7157394e11b5b3c714a420a96211abb0a53ea45 | 222 | su-se-bakover | MIT License |
cloud/acp-admin-cloud-dependencies/src/main/kotlin/pers/acp/admin/common/AcpAdminFeignClientAutoConfiguration.kt | zhangbin1010 | 162,155,230 | false | null | package pers.acp.admin.common
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.boot.autoconfigure.AutoConfigureAfter
import org.springframework.cloud.loadbalancer.config.BlockingLoadBalancerClientAutoConfiguration
import org.springframework.cloud.openfeign.EnableFeignClients
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import pers.acp.admin.common.hystrix.CommonOauthServerHystrix
import pers.acp.admin.common.hystrix.WorkFlowServerHystrix
import io.github.zhangbinhub.acp.boot.interfaces.LogAdapter
/**
* @author zhang by 12/12/2019
* @since JDK 11
*/
@Configuration(proxyBeanMethods = false)
@EnableFeignClients
@AutoConfigureAfter(BlockingLoadBalancerClientAutoConfiguration::class)
class AcpAdminFeignClientAutoConfiguration {
@Bean
fun commonOauthServerHystrix(logAdapter: LogAdapter, objectMapper: ObjectMapper): CommonOauthServerHystrix =
CommonOauthServerHystrix(logAdapter, objectMapper)
@Bean
fun workFlowServerHystrix(logAdapter: LogAdapter, objectMapper: ObjectMapper): WorkFlowServerHystrix =
WorkFlowServerHystrix(logAdapter, objectMapper)
} | 0 | Kotlin | 4 | 17 | 825a4e70ee6e3ec69518798088d44d6ab6b41e53 | 1,190 | acp-admin-cloud | Apache License 2.0 |
src/main/kotlin/br/com/zup/pix/consulta/ConsultaChavePixResponse.kt | rodrigoananiaszup | 388,532,259 | true | {"Kotlin": 30975, "Smarty": 2172, "Dockerfile": 167} | package br.com.zup.pix.consulta
import br.com.zup.ConsultaChavePixResponse
import br.com.zup.TipoChave
import br.com.zup.TipoConta
import io.micronaut.core.annotation.Introspected
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneOffset
@Introspected
class ConsultaChavePixResponse(chavePixResponse: ConsultaChavePixResponse) {
val clienteId = chavePixResponse.clienteId
val pixId = chavePixResponse.pixId
val tipoChave = when (chavePixResponse.chave.tipo) {
TipoChave.ALEATORIA -> "ALEATORIA"
TipoChave.EMAIL -> "EMAIL"
TipoChave.CELULAR -> "CELULAR"
TipoChave.CPF -> "CPF"
else -> "NAO_RECONHECIDA"
}
val chave = chavePixResponse.chave.chave
val conta = mapOf(
Pair("tipoConta", when (chavePixResponse.chave.conta.tipo) {
TipoConta.CONTA_CORRENTE -> "CONTA_CORRENTE"
TipoConta.CONTA_POUPANCA -> "CONTA_POUPANCA"
else -> "NAO_RECONHECIDA"
}),
Pair("instituicao", chavePixResponse.chave.conta.instituicao),
Pair("nomeTitular", chavePixResponse.chave.conta.nomeDoTitular),
Pair("cpfTitular", chavePixResponse.chave.conta.cpfDoTitular),
Pair("agencia", chavePixResponse.chave.conta.agencia),
Pair("numero", chavePixResponse.chave.conta.numeroDaConta),
)
val registradaEm = chavePixResponse.chave.criadaEm.let {
LocalDateTime.ofInstant(Instant.ofEpochSecond(it.seconds, it.nanos.toLong()), ZoneOffset.UTC)
}
} | 0 | Kotlin | 0 | 0 | 99dc1bb421124c3fee90559177f10d838973e671 | 1,517 | orange-talents-05-template-pix-keymanager-rest | Apache License 2.0 |
app/src/main/java/com/erkindilekci/taskmanager/infrastructure/notification/NotificationUtils.kt | erkindilekci | 662,553,048 | false | null | package com.erkindilekci.taskmanager.infrastructure.notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.os.Build
import androidx.core.app.NotificationCompat
import com.erkindilekci.taskmanager.R
import com.erkindilekci.taskmanager.util.Constants
object NotificationUtils {
fun showNotification(ctx: Context, title: String, description: String) {
val notificationManager = ctx.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
createNotificationChannel(notificationManager)
val builder = createNotificationCompat(ctx, title, description)
notificationManager.notify(1, builder.build())
}
private fun createNotificationChannel(notificationManager: NotificationManager) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
Constants.NOTIFICATION.CHANNEL_ID,
Constants.NOTIFICATION.CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
)
notificationManager.createNotificationChannel(channel)
}
}
private fun createNotificationCompat(
ctx: Context,
title: String,
description: String
): NotificationCompat.Builder {
return NotificationCompat.Builder(ctx, Constants.NOTIFICATION.CHANNEL_ID)
.setContentTitle(title)
.setContentText(description)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_HIGH)
}
}
| 0 | Kotlin | 0 | 0 | c2db26373ce67d7e8019be129f19991846d5f860 | 1,659 | TaskManager | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/ScannerImage.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.ScannerImage: ImageVector
get() {
if (_scannerImage != null) {
return _scannerImage!!
}
_scannerImage = Builder(name = "ScannerImage", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(22.202f, 15.662f)
lineTo(3.64f, 0.231f)
curveToRelative(-0.428f, -0.353f, -1.057f, -0.294f, -1.408f, 0.13f)
curveToRelative(-0.354f, 0.425f, -0.295f, 1.055f, 0.129f, 1.408f)
lineToRelative(15.917f, 13.231f)
lineTo(4.0f, 15.0f)
curveToRelative(-2.206f, 0.0f, -4.0f, 1.794f, -4.0f, 4.0f)
verticalLineToRelative(1.0f)
curveToRelative(0.0f, 2.206f, 1.794f, 4.0f, 4.0f, 4.0f)
horizontalLineToRelative(16.0f)
curveToRelative(2.206f, 0.0f, 4.0f, -1.794f, 4.0f, -4.0f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -1.393f, -0.716f, -2.622f, -1.798f, -3.338f)
close()
moveTo(4.5f, 21.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, -0.672f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f)
close()
moveTo(9.5f, 21.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, -0.672f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f)
close()
}
}
.build()
return _scannerImage!!
}
private var _scannerImage: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,729 | icons | MIT License |
app/src/main/java/net/aiscope/gdd_app/network/SampleDtos.kt | theaiscope | 187,222,295 | false | null | package net.aiscope.gdd_app.network
import android.os.Build
import com.google.gson.annotations.SerializedName
import net.aiscope.gdd_app.BuildConfig
import net.aiscope.gdd_app.model.MicroscopeQuality
import net.aiscope.gdd_app.model.Sample
import net.aiscope.gdd_app.model.SampleMetadata
import net.aiscope.gdd_app.model.SamplePreparation
import java.text.SimpleDateFormat
val ISO_FORMAT = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
data class SampleDto(
@SerializedName("id") val id: String,
@SerializedName("healthFacility") val healthFacility: String,
@SerializedName("microscopist") val microscopist: String,
@SerializedName("disease") val disease: String,
@SerializedName("preparation") val preparation: SamplePreparationDto?,
@SerializedName("microscopeQuality") val microscopeQuality: MicroscopeQualityDto?,
@SerializedName("metadata") val metadata: SampleMetadataDto,
@SerializedName("appVersion") val appVersion: String,
@SerializedName("device") val device: String,
@SerializedName("createdOn") val createdOn: String,
@SerializedName("lastModified") val lastModified: String
)
data class SamplePreparationDto(
@SerializedName("waterType") val waterType: Int,
@SerializedName("usesGiemsa") val usesGiemsa: Boolean,
@SerializedName("giemsaFP") val giemsaFP: Boolean,
@SerializedName("usesPbs") val usesPbs: Boolean,
@SerializedName("usesAlcohol") val usesAlcohol: Boolean,
@SerializedName("reusesSlides") val reusesSlides: Boolean
)
data class MicroscopeQualityDto(
@SerializedName("isDamaged") val isDamaged: Boolean,
@SerializedName("magnification") val magnification: Int
)
data class SampleMetadataDto(
@SerializedName("bloodType") val bloodType: Int,
@SerializedName("species") val species: Int,
@SerializedName("comments") val comments: String
)
fun Sample.toDto() = SampleDto(
id = id,
healthFacility = healthFacility,
microscopist = microscopist,
disease = disease,
preparation = preparation?.toDto(),
microscopeQuality = microscopeQuality?.toDto(),
metadata = metadata.toDto(),
appVersion = "${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})",
device = "${Build.MANUFACTURER} ${Build.MODEL}",
createdOn = ISO_FORMAT.format(createdOn.time),
lastModified = ISO_FORMAT.format(lastModified.time)
)
fun SamplePreparation.toDto() = SamplePreparationDto(
waterType.id,
usesGiemsa,
giemsaFP,
usesPbs,
usesAlcohol,
reusesSlides
)
fun MicroscopeQuality.toDto() = MicroscopeQualityDto(
isDamaged,
magnification
)
fun SampleMetadata.toDto() = SampleMetadataDto(smearType.id, species.id, comments)
| 2 | null | 23 | 9 | d6caecf0cd741408ef1de339ea2bf2e0ea0643d3 | 2,684 | GDD-app | MIT License |
src/main/kotlin/com/exsilicium/scripture/shared/extensions/RangeExtensions.kt | Ex-Silicium | 103,700,839 | false | null | package com.exsilicium.scripture.shared.extensions
import com.exsilicium.scripture.shared.model.Verse
internal fun <T : Comparable<T>> ClosedRange<out T>.isEmptyRange() = start >= endInclusive
internal fun ClosedRange<Verse>.rangeHasSameChapter() = start.chapter == endInclusive.chapter | 14 | Kotlin | 1 | 1 | 4815f70f5736080d7533e0d1316f0aa2c31aa85a | 289 | scripture-core | Apache License 2.0 |
feature-staking-impl/src/main/java/jp/co/soramitsu/staking/impl/data/network/blockhain/updaters/MinBondUpdater.kt | soramitsu | 278,060,397 | false | {"Kotlin": 5738291, "Java": 18796} | package jp.co.soramitsu.staking.impl.data.network.blockhain.updaters
import jp.co.soramitsu.common.utils.staking
import jp.co.soramitsu.core.storage.StorageCache
import jp.co.soramitsu.core.updater.GlobalUpdaterScope
import jp.co.soramitsu.runtime.multiNetwork.ChainRegistry
import jp.co.soramitsu.runtime.network.updaters.SingleStorageKeyUpdater
import jp.co.soramitsu.shared_utils.runtime.RuntimeSnapshot
import jp.co.soramitsu.shared_utils.runtime.metadata.storageKey
import jp.co.soramitsu.shared_utils.runtime.metadata.storageOrNull
import jp.co.soramitsu.staking.api.data.StakingSharedState
import jp.co.soramitsu.staking.impl.data.network.blockhain.updaters.base.StakingUpdater
class MinBondUpdater(
stakingSharedState: StakingSharedState,
chainRegistry: ChainRegistry,
storageCache: StorageCache
) : SingleStorageKeyUpdater<GlobalUpdaterScope>(GlobalUpdaterScope, stakingSharedState, chainRegistry, storageCache), StakingUpdater {
override suspend fun storageKey(runtime: RuntimeSnapshot): String? {
return runtime.metadata.staking().storageOrNull("MinNominatorBond")?.storageKey()
}
}
| 4 | Kotlin | 30 | 89 | 812c6ed5465d19a0616865cbba3e946d046720a1 | 1,125 | fearless-Android | Apache License 2.0 |
sdk/src/main/java/ch/opentransportdata/ojp/data/dto/adapter/ServiceDeliveryAdapter.kt | openTdataCH | 783,593,283 | false | {"Kotlin": 93476} | package ch.opentransportdata.ojp.data.dto.adapter
import ch.opentransportdata.ojp.data.dto.response.ServiceDeliveryDto
import ch.opentransportdata.ojp.data.dto.response.delivery.AbstractDeliveryDto
import ch.opentransportdata.ojp.data.dto.response.delivery.LocationInformationDeliveryDto
import ch.opentransportdata.ojp.data.dto.response.delivery.TripDeliveryDto
import com.tickaroo.tikxml.TikXmlConfig
import com.tickaroo.tikxml.XmlReader
import com.tickaroo.tikxml.XmlWriter
import com.tickaroo.tikxml.typeadapter.ChildElementBinder
import com.tickaroo.tikxml.typeadapter.TypeAdapter
import java.io.IOException
/**
* Created by Michael Ruppen on 14.05.2024
*
* Adapter to map all possible delivery objects correctly
*/
internal class ServiceDeliveryAdapter : TypeAdapter<ServiceDeliveryDto> {
private val childElementBinders: HashMap<String, ChildElementBinder<ValueHolder>> = hashMapOf()
init {
childElementBinders["siri:ResponseTimestamp"] = ChildElementBinder<ValueHolder> { reader, config, value ->
while (reader.hasAttribute()) {
val attributeName = reader.nextAttributeName()
if (config.exceptionOnUnreadXml() && !attributeName.startsWith("xmlns")) {
throw IOException("Unread attribute '" + attributeName + "' at path " + reader.path)
}
reader.skipAttributeValue()
}
value.responseTimestamp = reader.nextTextContent()
}
childElementBinders["siri:ProducerRef"] = ChildElementBinder<ValueHolder> { reader, config, value ->
while (reader.hasAttribute()) {
val attributeName = reader.nextAttributeName()
if (config.exceptionOnUnreadXml() && !attributeName.startsWith("xmlns")) {
throw IOException("Unread attribute '" + attributeName + "' at path " + reader.path)
}
reader.skipAttributeValue()
}
value.producerRef = reader.nextTextContent()
}
childElementBinders["OJPLocationInformationDelivery"] = ChildElementBinder<ValueHolder> { reader, config, value ->
value.ojpDelivery =
config.getTypeAdapter<LocationInformationDeliveryDto>(LocationInformationDeliveryDto::class.java)
.fromXml(reader, config, false)
}
childElementBinders["OJPTripDelivery"] = ChildElementBinder<ValueHolder> { reader, config, value ->
value.ojpDelivery = config.getTypeAdapter<TripDeliveryDto>(TripDeliveryDto::class.java).fromXml(reader, config, false)
}
}
override fun fromXml(reader: XmlReader?, config: TikXmlConfig?, isGenericList: Boolean): ServiceDeliveryDto {
val valueHolder = ValueHolder()
while (reader?.hasAttribute() == true) {
val attributeName = reader.nextAttributeName()
if (config?.exceptionOnUnreadXml() == true && !attributeName.startsWith("xmlns")) {
throw IOException("Could not map the xml attribute with the name '" + attributeName + "' at path " + reader.path + " to java class. Have you annotated such a field in your java class to map this xml attribute? Otherwise you can turn this error message off with TikXml.Builder().exceptionOnUnreadXml(false).build().")
}
reader.skipAttributeValue()
}
while (true) {
if (reader?.hasElement() == true) {
reader.beginElement()
val elementName = reader.nextElementName()
val childElementBinder = childElementBinders[elementName]
if (childElementBinder != null) {
childElementBinder.fromXml(reader, config, valueHolder)
reader.endElement()
} else if (config?.exceptionOnUnreadXml() == true) {
throw IOException("Could not map the xml element with the tag name <" + elementName + "> at path '" + reader.path + "' to java class. Have you annotated such a field in your java class to map this xml attribute? Otherwise you can turn this error message off with TikXml.Builder().exceptionOnUnreadXml(false).build().")
} else {
reader.skipRemainingElement()
}
} else if (reader?.hasTextContent() == true) {
if (config?.exceptionOnUnreadXml() == true) {
throw IOException("Could not map the xml element's text content at path '" + reader.path + " to java class. Have you annotated such a field in your java class to map the xml element's text content? Otherwise you can turn this error message off with TikXml.Builder().exceptionOnUnreadXml(false).build().")
}
reader.skipTextContent()
} else {
break
}
}
return ServiceDeliveryDto(
responseTimestamp = valueHolder.responseTimestamp!!,
producerRef = valueHolder.producerRef,
ojpDelivery = valueHolder.ojpDelivery!!
)
}
override fun toXml(
writer: XmlWriter?,
config: TikXmlConfig?,
value: ServiceDeliveryDto?,
overridingXmlElementTagName: String?
) {
value?.let {
when (overridingXmlElementTagName == null) {
true -> writer?.beginElement("ServiceDelivery")
else -> writer?.beginElement(overridingXmlElementTagName)
}
writer?.beginElement("siri:ResponseTimestamp")
writer?.textContent(it.responseTimestamp)
writer?.endElement()
if (it.producerRef != null) {
writer?.beginElement("siri:ProducerRef")
writer?.textContent(it.producerRef)
writer?.endElement()
}
when (it.ojpDelivery) {
is LocationInformationDeliveryDto -> {
config?.getTypeAdapter<LocationInformationDeliveryDto>(LocationInformationDeliveryDto::class.java)
?.toXml(writer, config, it.ojpDelivery, "OJPLocationInformationDelivery")
}
is TripDeliveryDto -> {
config?.getTypeAdapter<TripDeliveryDto>(TripDeliveryDto::class.java)
?.toXml(writer, config, it.ojpDelivery, "OJPTripDelivery")
}
}
writer?.endElement()
}
}
class ValueHolder {
var responseTimestamp: String? = null
var producerRef: String? = null
var ojpDelivery: AbstractDeliveryDto? = null
}
} | 0 | Kotlin | 0 | 0 | b1996e3f058598a8ddacf0d81dcc8ada4222aa46 | 6,631 | ojp-android | MIT License |
shared/src/commonMain/kotlin/platform/StatusBarColors.kt | Lilytreasure | 700,871,694 | false | {"Kotlin": 81436, "Swift": 592, "Shell": 228} | package platform
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
@Composable
expect fun StatusBarColors(statusBarColor: Color, navBarColor: Color)
| 11 | Kotlin | 0 | 9 | 3344f0e215444ef6a71b2d3555b8419b5c4a4ab1 | 186 | DecomposeNavigation | Apache License 2.0 |
shared/src/commonMain/kotlin/platform/StatusBarColors.kt | Lilytreasure | 700,871,694 | false | {"Kotlin": 81436, "Swift": 592, "Shell": 228} | package platform
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
@Composable
expect fun StatusBarColors(statusBarColor: Color, navBarColor: Color)
| 11 | Kotlin | 0 | 9 | 3344f0e215444ef6a71b2d3555b8419b5c4a4ab1 | 186 | DecomposeNavigation | Apache License 2.0 |
jetbrains-core/src/software/aws/toolkits/jetbrains/services/iam/CreateIamRoleDialog.kt | JetBrains | 223,485,227 | true | {"Kotlin": 4152201, "C#": 95783, "Java": 35575, "Dockerfile": 1985} | // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.iam
import com.intellij.json.JsonLanguage
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import org.intellij.lang.annotations.Language
import org.jetbrains.annotations.TestOnly
import software.amazon.awssdk.services.iam.IamClient
import software.amazon.awssdk.services.iam.model.Role
import software.aws.toolkits.core.utils.getLogger
import software.aws.toolkits.core.utils.warn
import software.aws.toolkits.jetbrains.services.iam.Iam.createRoleWithPolicy
import software.aws.toolkits.jetbrains.utils.ui.formatAndSet
import software.aws.toolkits.resources.message
import java.awt.Component
import javax.swing.JComponent
class CreateIamRoleDialog(
project: Project,
private val iamClient: IamClient,
parent: Component? = null,
@Language("JSON") defaultPolicyDocument: String,
@Language("JSON") defaultAssumeRolePolicyDocument: String
) : DialogWrapper(project, parent, false, IdeModalityType.PROJECT) {
private val view = CreateRolePanel(project)
var iamRole: Role? = null
init {
title = message("iam.create.role.title")
setOKButtonText(message("general.create_button"))
view.policyDocument.formatAndSet(defaultPolicyDocument, JsonLanguage.INSTANCE)
view.assumeRolePolicyDocument.formatAndSet(defaultAssumeRolePolicyDocument, JsonLanguage.INSTANCE)
init()
}
override fun createCenterPanel(): JComponent? = view.component
override fun getPreferredFocusedComponent(): JComponent? = view.roleName
override fun doValidate(): ValidationInfo? {
if (roleName().isEmpty()) {
return ValidationInfo(message("iam.create.role.missing.role.name"), view.roleName)
}
return null
}
override fun doOKAction() {
if (okAction.isEnabled) {
setOKButtonText(message("general.create_in_progress"))
isOKActionEnabled = false
ApplicationManager.getApplication().executeOnPooledThread {
try {
createIamRole()
ApplicationManager.getApplication().invokeLater(
{
close(OK_EXIT_CODE)
},
ModalityState.stateForComponent(view.component)
)
} catch (e: Exception) {
LOG.warn(e) { "Failed to create IAM role '${roleName()}'" }
setErrorText(e.message)
setOKButtonText(message("general.create_button"))
isOKActionEnabled = true
}
}
}
}
private fun roleName() = view.roleName.text.trim()
private fun policyDocument() = view.policyDocument.text.trim()
private fun assumeRolePolicy() = view.assumeRolePolicyDocument.text.trim()
private fun createIamRole() {
iamRole = iamClient.createRoleWithPolicy(roleName(), assumeRolePolicy(), policyDocument())
}
@TestOnly
internal fun createIamRoleForTesting() {
createIamRole()
}
@TestOnly
internal fun getViewForTesting(): CreateRolePanel = view
private companion object {
val LOG = getLogger<CreateIamRoleDialog>()
}
}
| 6 | Kotlin | 4 | 9 | ccee3307fe58ad48f93cd780d4378c336ee20548 | 3,565 | aws-toolkit-jetbrains | Apache License 2.0 |
android/versioned-abis/expoview-abi48_0_0/src/main/java/abi48_0_0/host/exp/exponent/VersionedUtils.kt | betomoedano | 462,599,485 | false | null | // Copyright 2015-present 650 Industries. All rights reserved.
package abi48_0_0.host.exp.exponent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import com.facebook.common.logging.FLog
import abi48_0_0.com.facebook.hermes.reactexecutor.HermesExecutorFactory
import abi48_0_0.com.facebook.react.ReactInstanceManager
import abi48_0_0.com.facebook.react.ReactInstanceManagerBuilder
import abi48_0_0.com.facebook.react.bridge.JavaScriptContextHolder
import abi48_0_0.com.facebook.react.bridge.JavaScriptExecutorFactory
import abi48_0_0.com.facebook.react.bridge.ReactApplicationContext
import abi48_0_0.com.facebook.react.common.LifecycleState
import abi48_0_0.com.facebook.react.common.ReactConstants
import abi48_0_0.com.facebook.react.jscexecutor.JSCExecutorFactory
import abi48_0_0.com.facebook.react.modules.systeminfo.AndroidInfoHelpers
import abi48_0_0.com.facebook.react.packagerconnection.NotificationOnlyHandler
import abi48_0_0.com.facebook.react.packagerconnection.RequestHandler
import abi48_0_0.com.facebook.react.shell.MainReactPackage
import expo.modules.jsonutils.getNullable
import host.exp.exponent.RNObject
import host.exp.exponent.experience.ExperienceActivity
import host.exp.exponent.experience.ReactNativeActivity
import host.exp.expoview.Exponent
import host.exp.expoview.Exponent.InstanceManagerBuilderProperties
import org.json.JSONObject
import java.util.*
object VersionedUtils {
private fun toggleExpoDevMenu() {
val currentActivity = Exponent.instance.currentActivity
if (currentActivity is ExperienceActivity) {
currentActivity.toggleDevMenu()
} else {
FLog.e(
ReactConstants.TAG,
"Unable to toggle the Expo dev menu because the current activity could not be found."
)
}
}
private fun reloadExpoApp() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to reload the app because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
devSupportManager.callRecursive("reloadExpoApp")
}
private fun toggleElementInspector() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to toggle the element inspector because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
devSupportManager.callRecursive("toggleElementInspector")
}
private fun requestOverlayPermission(context: Context) {
// From the unexposed DebugOverlayController static helper
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Get permission to show debug overlay in dev builds.
if (!Settings.canDrawOverlays(context)) {
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + context.packageName)
).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
FLog.w(
ReactConstants.TAG,
"Overlay permissions needs to be granted in order for React Native apps to run in development mode"
)
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
}
}
}
}
private fun togglePerformanceMonitor() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to toggle the performance monitor because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
val devSettings = devSupportManager.callRecursive("getDevSettings")
if (devSettings != null) {
val isFpsDebugEnabled = devSettings.call("isFpsDebugEnabled") as Boolean
if (!isFpsDebugEnabled) {
// Request overlay permission if needed when "Show Perf Monitor" option is selected
requestOverlayPermission(currentActivity)
}
devSettings.call("setFpsDebugEnabled", !isFpsDebugEnabled)
}
}
private fun toggleRemoteJSDebugging() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to toggle remote JS debugging because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
val devSettings = devSupportManager.callRecursive("getDevSettings")
if (devSettings != null) {
val isRemoteJSDebugEnabled = devSettings.call("isRemoteJSDebugEnabled") as Boolean
devSettings.call("setRemoteJSDebugEnabled", !isRemoteJSDebugEnabled)
}
}
private fun reconnectReactDevTools() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the current activity."
)
}
// Emit the `RCTDevMenuShown` for the app to reconnect react-devtools
// https://github.com/facebook/react-native/blob/22ba1e45c52edcc345552339c238c1f5ef6dfc65/Libraries/Core/setUpReactDevTools.js#L80
currentActivity.emitRCTNativeAppEvent("RCTDevMenuShown", null)
}
private fun createPackagerCommandHelpers(): Map<String, RequestHandler> {
// Attach listeners to the bundler's dev server web socket connection.
// This enables tools to automatically reload the client remotely (i.e. in expo-cli).
val packagerCommandHandlers = mutableMapOf<String, RequestHandler>()
// Enable a lot of tools under the same command namespace
packagerCommandHandlers["sendDevCommand"] = object : NotificationOnlyHandler() {
override fun onNotification(params: Any?) {
if (params != null && params is JSONObject) {
when (params.getNullable<String>("name")) {
"reload" -> reloadExpoApp()
"toggleDevMenu" -> toggleExpoDevMenu()
"toggleRemoteDebugging" -> {
toggleRemoteJSDebugging()
// Reload the app after toggling debugging, this is based on what we do in DevSupportManagerBase.
reloadExpoApp()
}
"toggleElementInspector" -> toggleElementInspector()
"togglePerformanceMonitor" -> togglePerformanceMonitor()
"reconnectReactDevTools" -> reconnectReactDevTools()
}
}
}
}
// These commands (reload and devMenu) are here to match RN dev tooling.
// Reload the app on "reload"
packagerCommandHandlers["reload"] = object : NotificationOnlyHandler() {
override fun onNotification(params: Any?) {
reloadExpoApp()
}
}
// Open the dev menu on "devMenu"
packagerCommandHandlers["devMenu"] = object : NotificationOnlyHandler() {
override fun onNotification(params: Any?) {
toggleExpoDevMenu()
}
}
return packagerCommandHandlers
}
@JvmStatic fun getReactInstanceManagerBuilder(instanceManagerBuilderProperties: InstanceManagerBuilderProperties): ReactInstanceManagerBuilder {
// Build the instance manager
var builder = ReactInstanceManager.builder()
.setApplication(instanceManagerBuilderProperties.application)
.setJSIModulesPackage { reactApplicationContext: ReactApplicationContext, jsContext: JavaScriptContextHolder? ->
emptyList()
}
.addPackage(MainReactPackage())
.addPackage(
ExponentPackage(
instanceManagerBuilderProperties.experienceProperties,
instanceManagerBuilderProperties.manifest,
null, null,
instanceManagerBuilderProperties.singletonModules
)
)
.addPackage(
ExpoTurboPackage(
instanceManagerBuilderProperties.experienceProperties,
instanceManagerBuilderProperties.manifest
)
)
.setMinNumShakes(100) // disable the RN dev menu
.setInitialLifecycleState(LifecycleState.BEFORE_CREATE)
.setCustomPackagerCommandHandlers(createPackagerCommandHelpers())
.setJavaScriptExecutorFactory(createJSExecutorFactory(instanceManagerBuilderProperties))
if (instanceManagerBuilderProperties.jsBundlePath != null && instanceManagerBuilderProperties.jsBundlePath!!.isNotEmpty()) {
builder = builder.setJSBundleFile(instanceManagerBuilderProperties.jsBundlePath)
}
return builder
}
private fun getDevSupportManager(reactApplicationContext: ReactApplicationContext): RNObject? {
val currentActivity = Exponent.instance.currentActivity
return if (currentActivity != null) {
if (currentActivity is ReactNativeActivity) {
currentActivity.devSupportManager
} else {
null
}
} else try {
val devSettingsModule = reactApplicationContext.catalystInstance.getNativeModule("DevSettings")
val devSupportManagerField = devSettingsModule!!.javaClass.getDeclaredField("mDevSupportManager")
devSupportManagerField.isAccessible = true
RNObject.wrap(devSupportManagerField[devSettingsModule]!!)
} catch (e: Throwable) {
e.printStackTrace()
null
}
}
private fun createJSExecutorFactory(
instanceManagerBuilderProperties: InstanceManagerBuilderProperties
): JavaScriptExecutorFactory? {
val appName = instanceManagerBuilderProperties.manifest.getName() ?: ""
val deviceName = AndroidInfoHelpers.getFriendlyDeviceName()
val jsEngineFromManifest = instanceManagerBuilderProperties.manifest.jsEngine
return if (jsEngineFromManifest == "hermes") HermesExecutorFactory() else JSCExecutorFactory(
appName,
deviceName
)
}
}
| 668 | null | 5226 | 4 | 52d6405570a39a87149648d045d91098374f4423 | 10,421 | expo | MIT License |
core/presentation/system/src/main/java/com/krossovochkin/core/presentation/system/SystemExt.kt | krossovochkin | 221,648,261 | false | null | package com.krossovochkin.core.presentation.system
import android.app.Activity
import android.graphics.Color
import android.os.Build
import android.view.View
import android.view.WindowInsetsController
import androidx.annotation.ColorInt
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.doOnPreDraw
import androidx.core.view.updateLayoutParams
import androidx.core.view.updateMargins
import androidx.core.view.updatePadding
import com.krossovochkin.core.presentation.color.ColorUtils
@Suppress("DEPRECATION")
fun Activity.setupSystemBars(
@ColorInt
backgroundColor: Int,
@ColorInt
contrastColor: Int
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.setDecorFitsSystemWindows(false)
} else {
this.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
}
this.window.navigationBarColor = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> Color.TRANSPARENT
ColorUtils.isDarkMode(this) || Build.VERSION.SDK_INT < Build.VERSION_CODES.O -> {
Color.parseColor("#B3000000")
}
else -> Color.parseColor("#B3FFFFFF")
}
if (ColorUtils.isDarkMode(this)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.decorView.windowInsetsController
?.setSystemBarsAppearance(
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
)
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.decorView.windowInsetsController
?.setSystemBarsAppearance(
0,
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
this.window.decorView.systemUiVisibility = this.window.decorView.systemUiVisibility or
View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
}
}
this.window.statusBarColor = ColorUtils.getDarkenColor(backgroundColor)
if (contrastColor == Color.WHITE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.decorView.windowInsetsController
?.setSystemBarsAppearance(0, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
this.window.decorView.systemUiVisibility = this.window.decorView.systemUiVisibility or
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.decorView.windowInsetsController
?.setSystemBarsAppearance(
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS,
WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
)
}
}
}
fun View.updateInsetMargins(
activity: Activity,
top: Boolean = false,
bottom: Boolean = false
) {
doOnPreDraw {
val insets = ViewCompat.getRootWindowInsets(activity.window.decorView)
?.getInsets(WindowInsetsCompat.Type.systemBars())
this.updateLayoutParams<ConstraintLayout.LayoutParams> {
if (top) {
updateMargins(top = insets?.top ?: 0)
}
if (bottom) {
updateMargins(bottom = insets?.bottom ?: 0)
}
}
}
}
fun View.updateInsetPaddings(
bottom: Boolean = false
) {
val originalPaddingBottom = paddingBottom
ViewCompat.setOnApplyWindowInsetsListener(this) { v, insets ->
val systemInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars())
if (bottom) {
v.updatePadding(bottom = originalPaddingBottom + systemInsets.bottom)
}
insets
}
requestApplyInsets()
}
| 0 | Kotlin | 0 | 14 | 3eacbce1c0a4e53357e13c748b29146e5d6a3c50 | 4,104 | FiberyUnofficial | Apache License 2.0 |
Kotlin/problems/0041_integer_replacement.kt | oxone-999 | 243,366,951 | true | {"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187} | // Problem Statement
// Given a positive integer n and you can do operations as follow:
//
// If n is even, replace n with n/2.
// If n is odd, you can replace n with either n + 1 or n - 1.
// What is the minimum number of replacements needed for n to become 1?
class Solution{
var memo:HashMap<Int,Int> = HashMap<Int,Int>();
fun integerReplacement(n: Int): Int {
if(n==Int.MAX_VALUE)
return 32;
if(memo.contains(n))
return memo.getValue(n);
var minReplacement:Int = 0;
if(n==1)
return minReplacement;
if(n%2==0){
minReplacement = 1+integerReplacement(n/2);
}else{
minReplacement = 1+minOf(integerReplacement(n+1),integerReplacement(n-1));
}
memo.put(n,minReplacement);
return minReplacement;
}
}
fun main(args:Array<String>){
var sol:Solution = Solution()
println(sol.integerReplacement(8));
}
| 0 | null | 0 | 0 | 52dc527111e7422923a0e25684d8f4837e81a09b | 949 | algorithms | MIT License |
secdra-data/src/main/kotlin/com/junjie/secdradata/database/primary/entity/MessageSettings.kt | lipstick-49 | 208,569,806 | true | {"Kotlin": 244725, "HTML": 4151} | package com.junjie.secdradata.database.primary.entity
import org.hibernate.annotations.GenericGenerator
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
import java.util.*
import javax.persistence.*
/**
* 通知信息设置
* @author fjj
*/
@Entity
@Table(uniqueConstraints = [UniqueConstraint(columnNames = arrayOf("userId"))])
@EntityListeners(AuditingEntityListener::class)
class MessageSettings : Serializable {
@Id
@GenericGenerator(name = "idGenerator", strategy = "uuid") //这个是hibernate的注解/生成32位UUID
@GeneratedValue(generator = "idGenerator")
var id: String? = null
lateinit var userId: String
var commentStatus: Boolean = true
var replyStatus: Boolean = true
var followStatus: Boolean = true
var systemStatus: Boolean = true
@CreatedDate
var createDate: Date? = null
@LastModifiedDate
var modifiedDate: Date? = null
constructor()
constructor(userId: String) {
this.userId = userId
}
} | 0 | null | 0 | 0 | b4317e70fad3256c82a9c418cb2aa25fe14ef62f | 1,134 | secdra | MIT License |
ultron/src/main/java/com/atiurin/ultron/core/espressoweb/operation/WebOperationExecutor.kt | open-tool | 312,407,423 | false | null | package com.atiurin.ultron.core.espressoweb.operation
import com.atiurin.ultron.core.common.Operation
import com.atiurin.ultron.core.common.OperationExecutor
import com.atiurin.ultron.core.common.OperationIterationResult
import com.atiurin.ultron.core.config.UltronConfig
import com.atiurin.ultron.exceptions.UltronWrapperException
internal abstract class WebOperationExecutor<T : Operation>(
override val operation: T
) : OperationExecutor<T, WebOperationResult<T>> {
override val pollingTimeout: Long
get() = UltronConfig.Espresso.ESPRESSO_OPERATION_POLLING_TIMEOUT
override fun generateResult(
success: Boolean,
exceptions: List<Throwable>,
description: String,
lastOperationIterationResult: OperationIterationResult?,
executionTimeMs: Long
): WebOperationResult<T> {
return WebOperationResult(
operation = operation,
success = success,
exceptions = exceptions,
description = description,
operationIterationResult = lastOperationIterationResult,
executionTimeMs = executionTimeMs
)
}
override fun getWrapperException(originalException: Throwable): Throwable {
var modifiedException: Throwable? = null
val isMessageContains =
originalException.message?.contains("Atom evaluation returned null!")
if (isMessageContains != null && isMessageContains) {
modifiedException =
UltronWrapperException("Element not found in WebView!", originalException)
}
return modifiedException ?: originalException
}
} | 7 | null | 9 | 84 | 98599c32934515a4c75e8af2e8723b53e0163bd7 | 1,646 | ultron | Apache License 2.0 |
app/src/main/java/com/akshayteli/kotlinsafeargscustomobject/EmployeDetailFragment.kt | Ak5hay01 | 422,949,615 | false | {"Kotlin": 3974} | package com.akshayteli.kotlinsafeargscustomobject
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.navigation.fragment.navArgs
class EmployeDetailFragment : Fragment() {
private val args by navArgs<EmployeDetailFragmentArgs>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_employe_detail, container, false)
val textView = view.findViewById<TextView>(R.id.textView)
textView.text = "Name : ${args.employee.name} \n Age: ${args.employee.age} \n Address: ${args.employee.address}"
return view
}
} | 0 | Kotlin | 0 | 0 | 8e69f8245f0948b933581ec2578676702003ef62 | 911 | Kotlin-SafeArgs-Custom-Object | MIT License |
src/main/kotlin/org/andrejs/cassandra/answers/Answer.kt | Bhanditz | 168,960,693 | true | {"Kotlin": 8277, "Java": 3791} | package org.andrejs.cassandra.answers
import org.apache.cassandra.transport.messages.ResultMessage
interface Answer {
fun get() : ResultMessage
} | 0 | Kotlin | 0 | 0 | 8f2bd4296b4b46828d9fe031504be1b13306dc31 | 151 | cassandra-spy | Apache License 2.0 |
android/apollo/src/main/java/io/muun/apollo/domain/errors/RevokedVerificationCodeError.kt | muun | 150,655,434 | false | null | package io.muun.apollo.domain.errors
import io.muun.apollo.data.external.UserFacingErrorMessages
class RevokedVerificationCodeError:
UserFacingError(UserFacingErrorMessages.INSTANCE.revokedVerificationCode()) | 21 | null | 21 | 148 | 2c5c2400b8092080dd4edb48bedfb1e4cf13396e | 214 | apollo | MIT License |
app/src/main/java/com/example/affirmations/data/Bedroom.kt | deerHDE | 489,905,288 | false | null | package com.example.affirmations.data
data class Bedroom (
val info: String
){
} | 0 | Kotlin | 0 | 0 | b113431fbf219b9595c204b23ac0700eec70996d | 86 | Image-Explorer | Apache License 2.0 |
src/main/kotlin/xyz/namutree0345/survival/BossBR.kt | R2turnTrue | 381,862,318 | false | null | package xyz.namutree0345.survival
import net.kyori.adventure.bossbar.BossBar
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.NamedTextColor
object BossBR {
lateinit var bossBar: BossBar
fun init() {
bossBar = BossBar.bossBar(Component.text("전장 축소로부터: 300초", NamedTextColor.GREEN), 1.0F, BossBar.Color.GREEN, BossBar.Overlay.NOTCHED_10)
}
} | 0 | Kotlin | 0 | 0 | 8eb48909f4dc7dce09a55b97f1dd8857e9375ea8 | 397 | survival | MIT License |
kotlin-native/runtime/test/native/ref/WeakReferenceTest.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package test.native.ref
import kotlin.native.ref.WeakReference
import kotlin.test.*
class WeakReferenceTest {
@Test
fun string() {
val v = "Hello"
val weak = WeakReference(v)
assertEquals(v, weak.value)
}
@Test
fun int() {
val v = 0
val weak = WeakReference(v)
assertEquals(0, weak.value)
}
@Test
fun long() {
val v = Long.MAX_VALUE
val weak = WeakReference(v)
assertEquals(Long.MAX_VALUE, weak.value)
}
} | 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 727 | kotlin | Apache License 2.0 |
buildSrc/src/main/kotlin/AppConfig.kt | tmvlke | 707,316,658 | false | {"Kotlin": 149898} | import org.gradle.api.JavaVersion
object AppConfig {
const val versionCode = 1
const val versionName = "1.0.0"
const val sdkMin = 23
const val targetSdk = 34
const val buildToolsVersion = "34.0.0"
const val jvmTarget = "17"
val javaVersion = JavaVersion.VERSION_17
const val sdkPreview = "UpsideDownCake"
const val kotlin = "1.8.10"
// https://developer.android.com/jetpack/androidx/releases/compose-kotlin?hl=ko
const val kotlinCompilerExtensionVersion = "1.4.3" // 1.8.10
} | 0 | Kotlin | 0 | 1 | 5823e99c4545f9856696eec27a4afeed4c8228de | 526 | SimpleDutch | Apache License 2.0 |
app/src/test/java/com/jaimegc/covid19tracker/extension/DateExtensionTest.kt | cybernetics | 336,079,946 | true | {"Kotlin": 1020782} | package com.jaimegc.covid19tracker.extension
import com.jaimegc.covid19tracker.ModelFactoryTest.DATE
import com.jaimegc.covid19tracker.ModelFactoryTest.DATE_TIMESTAMP
import com.jaimegc.covid19tracker.common.extensions.dateToMilliseconds
import com.jaimegc.covid19tracker.common.extensions.millisecondsToDate
import com.jaimegc.covid19tracker.common.extensions.toLastUpdated
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import java.util.*
class DateExtensionTest {
@Before
fun setup() {
Locale.setDefault(Locale.US)
}
@Test
fun dateStringToMillisecondsInUTC() {
assertEquals(DATE_TIMESTAMP, DATE.dateToMilliseconds())
}
@Test
fun dateMillisecondsToStringInUTC() {
assertEquals(DATE, DATE_TIMESTAMP.millisecondsToDate())
}
@Test
fun addSpaceLastUpdatedDateUTC() {
assertEquals("$DATE 22:10 UTC", "$DATE 22:10UTC".toLastUpdated())
}
} | 0 | null | 0 | 0 | 69a75a114fc949d262d05924523300ad19f5eaca | 956 | Covid19Tracker | Apache License 2.0 |
zowe-cli/src/jsMain/kotlin/zowe/cli/zosjobs/strings/Temp23.kt | lppedd | 761,812,661 | false | {"Kotlin": 1887051} | package zowe.cli.zosjobs.strings
external interface Temp23 {
var SUMMARY: String
var DESCRIPTION: String
var OPTIONS: Temp24
var EXAMPLES: Temp25
}
| 0 | Kotlin | 0 | 3 | 0f493d3051afa3de2016e5425a708c7a9ed6699a | 157 | kotlin-externals | MIT License |
composeApp/src/commonMain/kotlin/com/takaotech/dashboard/repository/api/AdminGHApi.kt | TakaoTech | 761,297,714 | false | {"Kotlin": 120535, "Swift": 594, "HTML": 369} | package com.takaotech.dashboard.repository.api
import com.takaotech.dashboard.model.github.GHRepositoryDao
import com.takaotech.dashboard.model.github.MainCategory
import com.takaotech.dashboard.model.github.TagDao
import com.takaotech.dashboard.model.github.TagNewDao
import com.takaotech.dashboard.repository.api.ApiConstant.ADMIN_URL_PREFIX
import de.jensklingenberg.ktorfit.http.*
interface AdminGHApi {
@GET("$ADMIN_URL_PREFIX/github")
suspend fun getRepositories(
@Query("category") category: MainCategory? = null
): List<GHRepositoryDao>
@POST("$ADMIN_URL_PREFIX/github/{id}/updateCategory")
suspend fun updateRepositoryCategory(
//TODO newCategory as query param?
@Path("id") repositoryId: Long,
@Query("category") category: MainCategory? = null
)
@GET("$ADMIN_URL_PREFIX/github/tags")
suspend fun getTags(): List<TagDao>
@GET("$ADMIN_URL_PREFIX/github/tags/{id}")
suspend fun getTagById(@Path("id") tagId: Int): TagDao
@PUT("$ADMIN_URL_PREFIX/github/tags")
suspend fun addTag(@Body tag: TagNewDao)
@POST("$ADMIN_URL_PREFIX/github/tags")
suspend fun updateTag(@Body tag: TagDao)
} | 5 | Kotlin | 0 | 1 | fa4aef13fae8c12ab80775503eef291c70b1faa3 | 1,118 | TTD | Apache License 2.0 |
src/main/kotlin/com/iesbpi/redis/rpg/loja/Itens.kt | EmanuelFelipe | 375,858,351 | false | null | package br.iesb.poo.rpg.loja
import br.iesb.poo.rpg.personagem.PersonagemJogador
import java.io.File
import java.nio.file.Paths
open class Itens(){
open fun efeito(jogador: PersonagemJogador, id: String?): String {
var log: String = ""
if(jogador.dinheiro < jogador.nivel * 2) {
log = "VOCE NAO POSSUI MOEDAS DE OURO SUFICIENTES"
} else {
if (id == "vida") {
jogador.pontosVida = jogador.pontosVida * 2
jogador.dinheiro = jogador.dinheiro - jogador.dinheiro/2
} else if (id == "mana") {
jogador.pontosMana = jogador.pontosMana * 2
jogador.dinheiro = jogador.dinheiro - jogador.dinheiro/2
}
log = "PARABENS PELA COMPRA"
}
return log
}
open fun elemento(jogador: PersonagemJogador, elm: Int): String{
jogador.elemento = elm
return "teste"
}
} | 0 | Kotlin | 1 | 0 | 9131b75d120a0ebf89012da062fdc2880744ef55 | 946 | ApiRedis | Apache License 2.0 |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/elasticsearch/DomainProps.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 149148378} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.elasticsearch
import io.cloudshiftdev.awscdk.RemovalPolicy
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import io.cloudshiftdev.awscdk.services.ec2.ISecurityGroup
import io.cloudshiftdev.awscdk.services.ec2.IVpc
import io.cloudshiftdev.awscdk.services.ec2.SubnetSelection
import io.cloudshiftdev.awscdk.services.iam.PolicyStatement
import kotlin.Boolean
import kotlin.Deprecated
import kotlin.Number
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.collections.Map
import kotlin.jvm.JvmName
/**
* (deprecated) Properties for an AWS Elasticsearch Domain.
*
* Example:
*
* ```
* Domain domain = Domain.Builder.create(this, "Domain")
* .version(ElasticsearchVersion.V7_4)
* .ebs(EbsOptions.builder()
* .volumeSize(100)
* .volumeType(EbsDeviceVolumeType.GENERAL_PURPOSE_SSD)
* .build())
* .nodeToNodeEncryption(true)
* .encryptionAtRest(EncryptionAtRestOptions.builder()
* .enabled(true)
* .build())
* .build();
* ```
*
* @deprecated use opensearchservice module instead
*/
public interface DomainProps {
/**
* (deprecated) Domain Access policies.
*
* Default: - No access policies.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun accessPolicies(): List<PolicyStatement> =
unwrap(this).getAccessPolicies()?.map(PolicyStatement::wrap) ?: emptyList()
/**
* (deprecated) Additional options to specify for the Amazon ES domain.
*
* Default: - no advanced options are specified
*
* [Documentation](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-advanced-options)
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun advancedOptions(): Map<String, String> = unwrap(this).getAdvancedOptions() ?:
emptyMap()
/**
* (deprecated) The hour in UTC during which the service takes an automated daily snapshot of the
* indices in the Amazon ES domain.
*
* Only applies for Elasticsearch
* versions below 5.3.
*
* Default: - Hourly automated snapshots not used
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun automatedSnapshotStartHour(): Number? = unwrap(this).getAutomatedSnapshotStartHour()
/**
* (deprecated) The cluster capacity configuration for the Amazon ES domain.
*
* Default: - 1 r5.large.elasticsearch data node; no dedicated master nodes.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun capacity(): CapacityConfig? = unwrap(this).getCapacity()?.let(CapacityConfig::wrap)
/**
* (deprecated) Configures Amazon ES to use Amazon Cognito authentication for Kibana.
*
* Default: - Cognito not used for authentication to Kibana.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun cognitoKibanaAuth(): CognitoOptions? =
unwrap(this).getCognitoKibanaAuth()?.let(CognitoOptions::wrap)
/**
* (deprecated) To configure a custom domain configure these options.
*
* If you specify a Route53 hosted zone it will create a CNAME record and use DNS validation for
* the certificate
*
* Default: - no custom domain endpoint will be configured
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun customEndpoint(): CustomEndpointOptions? =
unwrap(this).getCustomEndpoint()?.let(CustomEndpointOptions::wrap)
/**
* (deprecated) Enforces a particular physical domain name.
*
* Default: - A name will be auto-generated.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun domainName(): String? = unwrap(this).getDomainName()
/**
* (deprecated) The configurations of Amazon Elastic Block Store (Amazon EBS) volumes that are
* attached to data nodes in the Amazon ES domain.
*
* For more information, see
* [Configuring EBS-based Storage]
* (https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-ebs)
* in the Amazon Elasticsearch Service Developer Guide.
*
* Default: - 10 GiB General Purpose (SSD) volumes per node.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun ebs(): EbsOptions? = unwrap(this).getEbs()?.let(EbsOptions::wrap)
/**
* (deprecated) To upgrade an Amazon ES domain to a new version of Elasticsearch rather than
* replacing the entire domain resource, use the EnableVersionUpgrade update policy.
*
* Default: - false
*
* [Documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-updatepolicy.html#cfn-attributes-updatepolicy-upgradeelasticsearchdomain)
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun enableVersionUpgrade(): Boolean? = unwrap(this).getEnableVersionUpgrade()
/**
* (deprecated) Encryption at rest options for the cluster.
*
* Default: - No encryption at rest
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun encryptionAtRest(): EncryptionAtRestOptions? =
unwrap(this).getEncryptionAtRest()?.let(EncryptionAtRestOptions::wrap)
/**
* (deprecated) True to require that all traffic to the domain arrive over HTTPS.
*
* Default: - false
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun enforceHttps(): Boolean? = unwrap(this).getEnforceHttps()
/**
* (deprecated) Specifies options for fine-grained access control.
*
* Requires Elasticsearch version 6.7 or later. Enabling fine-grained access control
* also requires encryption of data at rest and node-to-node encryption, along with
* enforced HTTPS.
*
* Default: - fine-grained access control is disabled
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun fineGrainedAccessControl(): AdvancedSecurityOptions? =
unwrap(this).getFineGrainedAccessControl()?.let(AdvancedSecurityOptions::wrap)
/**
* (deprecated) Configuration log publishing configuration options.
*
* Default: - No logs are published
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun logging(): LoggingOptions? = unwrap(this).getLogging()?.let(LoggingOptions::wrap)
/**
* (deprecated) Specify true to enable node to node encryption.
*
* Requires Elasticsearch version 6.0 or later.
*
* Default: - Node to node encryption is not enabled.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun nodeToNodeEncryption(): Boolean? = unwrap(this).getNodeToNodeEncryption()
/**
* (deprecated) Policy to apply when the domain is removed from the stack.
*
* Default: RemovalPolicy.RETAIN
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun removalPolicy(): RemovalPolicy? =
unwrap(this).getRemovalPolicy()?.let(RemovalPolicy::wrap)
/**
* (deprecated) The list of security groups that are associated with the VPC endpoints for the
* domain.
*
* Only used if `vpc` is specified.
*
* Default: - One new security group is created.
*
* [Documentation](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html)
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun securityGroups(): List<ISecurityGroup> =
unwrap(this).getSecurityGroups()?.map(ISecurityGroup::wrap) ?: emptyList()
/**
* (deprecated) The minimum TLS version required for traffic to the domain.
*
* Default: - TLSSecurityPolicy.TLS_1_0
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun tlsSecurityPolicy(): TLSSecurityPolicy? =
unwrap(this).getTlsSecurityPolicy()?.let(TLSSecurityPolicy::wrap)
/**
* (deprecated) Configures the domain so that unsigned basic auth is enabled.
*
* If no master user is provided a default master user
* with username `admin` and a dynamically generated password stored in KMS is created. The
* password can be retrieved
* by getting `masterUserPassword` from the domain instance.
*
* Setting this to true will also add an access policy that allows unsigned
* access, enable node to node encryption, encryption at rest. If conflicting
* settings are encountered (like disabling encryption at rest) enabling this
* setting will cause a failure.
*
* Default: - false
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun useUnsignedBasicAuth(): Boolean? = unwrap(this).getUseUnsignedBasicAuth()
/**
* (deprecated) The Elasticsearch version that your domain will leverage.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun version(): ElasticsearchVersion
/**
* (deprecated) Place the domain inside this VPC.
*
* Default: - Domain is not placed in a VPC.
*
* [Documentation](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-vpc.html)
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun vpc(): IVpc? = unwrap(this).getVpc()?.let(IVpc::wrap)
/**
* (deprecated) The specific vpc subnets the domain will be placed in.
*
* You must provide one subnet for each Availability Zone
* that your domain uses. For example, you must specify three subnet IDs for a three Availability
* Zone
* domain.
*
* Only used if `vpc` is specified.
*
* Default: - All private subnets.
*
* [Documentation](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html)
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun vpcSubnets(): List<SubnetSelection> =
unwrap(this).getVpcSubnets()?.map(SubnetSelection::wrap) ?: emptyList()
/**
* (deprecated) The cluster zone awareness configuration for the Amazon ES domain.
*
* Default: - no zone awareness (1 AZ)
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun zoneAwareness(): ZoneAwarenessConfig? =
unwrap(this).getZoneAwareness()?.let(ZoneAwarenessConfig::wrap)
/**
* A builder for [DomainProps]
*/
@CdkDslMarker
@Deprecated(message = "deprecated in CDK")
public interface Builder {
/**
* @param accessPolicies Domain Access policies.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun accessPolicies(accessPolicies: List<PolicyStatement>)
/**
* @param accessPolicies Domain Access policies.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun accessPolicies(vararg accessPolicies: PolicyStatement)
/**
* @param advancedOptions Additional options to specify for the Amazon ES domain.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun advancedOptions(advancedOptions: Map<String, String>)
/**
* @param automatedSnapshotStartHour The hour in UTC during which the service takes an automated
* daily snapshot of the indices in the Amazon ES domain.
* Only applies for Elasticsearch
* versions below 5.3.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun automatedSnapshotStartHour(automatedSnapshotStartHour: Number)
/**
* @param capacity The cluster capacity configuration for the Amazon ES domain.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun capacity(capacity: CapacityConfig)
/**
* @param capacity The cluster capacity configuration for the Amazon ES domain.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("b109cdbf131e5550be3edc0e2a9f9c5d3b0806ad4a2b12b80d47266879481b93")
public fun capacity(capacity: CapacityConfig.Builder.() -> Unit)
/**
* @param cognitoKibanaAuth Configures Amazon ES to use Amazon Cognito authentication for
* Kibana.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun cognitoKibanaAuth(cognitoKibanaAuth: CognitoOptions)
/**
* @param cognitoKibanaAuth Configures Amazon ES to use Amazon Cognito authentication for
* Kibana.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("f13e7dab868f11aff645edf400035e30cf13e128d35cf1f2a6662a18b56c6b05")
public fun cognitoKibanaAuth(cognitoKibanaAuth: CognitoOptions.Builder.() -> Unit)
/**
* @param customEndpoint To configure a custom domain configure these options.
* If you specify a Route53 hosted zone it will create a CNAME record and use DNS validation for
* the certificate
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun customEndpoint(customEndpoint: CustomEndpointOptions)
/**
* @param customEndpoint To configure a custom domain configure these options.
* If you specify a Route53 hosted zone it will create a CNAME record and use DNS validation for
* the certificate
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("9c50c1635eb80ee23c1e091e711750a47de582b0aac4fa60cc6786e22aae2639")
public fun customEndpoint(customEndpoint: CustomEndpointOptions.Builder.() -> Unit)
/**
* @param domainName Enforces a particular physical domain name.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun domainName(domainName: String)
/**
* @param ebs The configurations of Amazon Elastic Block Store (Amazon EBS) volumes that are
* attached to data nodes in the Amazon ES domain.
* For more information, see
* [Configuring EBS-based Storage]
* (https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-ebs)
* in the Amazon Elasticsearch Service Developer Guide.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun ebs(ebs: EbsOptions)
/**
* @param ebs The configurations of Amazon Elastic Block Store (Amazon EBS) volumes that are
* attached to data nodes in the Amazon ES domain.
* For more information, see
* [Configuring EBS-based Storage]
* (https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-ebs)
* in the Amazon Elasticsearch Service Developer Guide.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("d97c189489a69fc31417451f8f3508a1b26b53571043e87cbc8245fd61e76ad9")
public fun ebs(ebs: EbsOptions.Builder.() -> Unit)
/**
* @param enableVersionUpgrade To upgrade an Amazon ES domain to a new version of Elasticsearch
* rather than replacing the entire domain resource, use the EnableVersionUpgrade update policy.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun enableVersionUpgrade(enableVersionUpgrade: Boolean)
/**
* @param encryptionAtRest Encryption at rest options for the cluster.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun encryptionAtRest(encryptionAtRest: EncryptionAtRestOptions)
/**
* @param encryptionAtRest Encryption at rest options for the cluster.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("24b48c9a456533b4cae5ca0aca64321babe6a0fccf60c04c4f7214842d7ca6bf")
public fun encryptionAtRest(encryptionAtRest: EncryptionAtRestOptions.Builder.() -> Unit)
/**
* @param enforceHttps True to require that all traffic to the domain arrive over HTTPS.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun enforceHttps(enforceHttps: Boolean)
/**
* @param fineGrainedAccessControl Specifies options for fine-grained access control.
* Requires Elasticsearch version 6.7 or later. Enabling fine-grained access control
* also requires encryption of data at rest and node-to-node encryption, along with
* enforced HTTPS.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun fineGrainedAccessControl(fineGrainedAccessControl: AdvancedSecurityOptions)
/**
* @param fineGrainedAccessControl Specifies options for fine-grained access control.
* Requires Elasticsearch version 6.7 or later. Enabling fine-grained access control
* also requires encryption of data at rest and node-to-node encryption, along with
* enforced HTTPS.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("b7b6f8887a21f8027f7c6f1fd8b7b8ffdd5f60a87ee502da105c9d57077b3dc8")
public
fun fineGrainedAccessControl(fineGrainedAccessControl: AdvancedSecurityOptions.Builder.() -> Unit)
/**
* @param logging Configuration log publishing configuration options.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun logging(logging: LoggingOptions)
/**
* @param logging Configuration log publishing configuration options.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("aba05d229e9246f738f24266f5f3add48200e93225fc0d664a2502ceb2db1738")
public fun logging(logging: LoggingOptions.Builder.() -> Unit)
/**
* @param nodeToNodeEncryption Specify true to enable node to node encryption.
* Requires Elasticsearch version 6.0 or later.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun nodeToNodeEncryption(nodeToNodeEncryption: Boolean)
/**
* @param removalPolicy Policy to apply when the domain is removed from the stack.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun removalPolicy(removalPolicy: RemovalPolicy)
/**
* @param securityGroups The list of security groups that are associated with the VPC endpoints
* for the domain.
* Only used if `vpc` is specified.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun securityGroups(securityGroups: List<ISecurityGroup>)
/**
* @param securityGroups The list of security groups that are associated with the VPC endpoints
* for the domain.
* Only used if `vpc` is specified.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun securityGroups(vararg securityGroups: ISecurityGroup)
/**
* @param tlsSecurityPolicy The minimum TLS version required for traffic to the domain.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun tlsSecurityPolicy(tlsSecurityPolicy: TLSSecurityPolicy)
/**
* @param useUnsignedBasicAuth Configures the domain so that unsigned basic auth is enabled.
* If no master user is provided a default master user
* with username `admin` and a dynamically generated password stored in KMS is created. The
* password can be retrieved
* by getting `masterUserPassword` from the domain instance.
*
* Setting this to true will also add an access policy that allows unsigned
* access, enable node to node encryption, encryption at rest. If conflicting
* settings are encountered (like disabling encryption at rest) enabling this
* setting will cause a failure.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun useUnsignedBasicAuth(useUnsignedBasicAuth: Boolean)
/**
* @param version The Elasticsearch version that your domain will leverage.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun version(version: ElasticsearchVersion)
/**
* @param vpc Place the domain inside this VPC.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun vpc(vpc: IVpc)
/**
* @param vpcSubnets The specific vpc subnets the domain will be placed in.
* You must provide one subnet for each Availability Zone
* that your domain uses. For example, you must specify three subnet IDs for a three
* Availability Zone
* domain.
*
* Only used if `vpc` is specified.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun vpcSubnets(vpcSubnets: List<SubnetSelection>)
/**
* @param vpcSubnets The specific vpc subnets the domain will be placed in.
* You must provide one subnet for each Availability Zone
* that your domain uses. For example, you must specify three subnet IDs for a three
* Availability Zone
* domain.
*
* Only used if `vpc` is specified.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun vpcSubnets(vararg vpcSubnets: SubnetSelection)
/**
* @param zoneAwareness The cluster zone awareness configuration for the Amazon ES domain.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
public fun zoneAwareness(zoneAwareness: ZoneAwarenessConfig)
/**
* @param zoneAwareness The cluster zone awareness configuration for the Amazon ES domain.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("6934866c54ce1ccd7109cd9eb1ec07b2163effc425b9437f5591a2879146a443")
public fun zoneAwareness(zoneAwareness: ZoneAwarenessConfig.Builder.() -> Unit)
}
private class BuilderImpl : Builder {
private val cdkBuilder: software.amazon.awscdk.services.elasticsearch.DomainProps.Builder =
software.amazon.awscdk.services.elasticsearch.DomainProps.builder()
/**
* @param accessPolicies Domain Access policies.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun accessPolicies(accessPolicies: List<PolicyStatement>) {
cdkBuilder.accessPolicies(accessPolicies.map(PolicyStatement.Companion::unwrap))
}
/**
* @param accessPolicies Domain Access policies.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun accessPolicies(vararg accessPolicies: PolicyStatement): Unit =
accessPolicies(accessPolicies.toList())
/**
* @param advancedOptions Additional options to specify for the Amazon ES domain.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun advancedOptions(advancedOptions: Map<String, String>) {
cdkBuilder.advancedOptions(advancedOptions)
}
/**
* @param automatedSnapshotStartHour The hour in UTC during which the service takes an automated
* daily snapshot of the indices in the Amazon ES domain.
* Only applies for Elasticsearch
* versions below 5.3.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun automatedSnapshotStartHour(automatedSnapshotStartHour: Number) {
cdkBuilder.automatedSnapshotStartHour(automatedSnapshotStartHour)
}
/**
* @param capacity The cluster capacity configuration for the Amazon ES domain.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun capacity(capacity: CapacityConfig) {
cdkBuilder.capacity(capacity.let(CapacityConfig.Companion::unwrap))
}
/**
* @param capacity The cluster capacity configuration for the Amazon ES domain.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("b109cdbf131e5550be3edc0e2a9f9c5d3b0806ad4a2b12b80d47266879481b93")
override fun capacity(capacity: CapacityConfig.Builder.() -> Unit): Unit =
capacity(CapacityConfig(capacity))
/**
* @param cognitoKibanaAuth Configures Amazon ES to use Amazon Cognito authentication for
* Kibana.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun cognitoKibanaAuth(cognitoKibanaAuth: CognitoOptions) {
cdkBuilder.cognitoKibanaAuth(cognitoKibanaAuth.let(CognitoOptions.Companion::unwrap))
}
/**
* @param cognitoKibanaAuth Configures Amazon ES to use Amazon Cognito authentication for
* Kibana.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("f13e7dab868f11aff645edf400035e30cf13e128d35cf1f2a6662a18b56c6b05")
override fun cognitoKibanaAuth(cognitoKibanaAuth: CognitoOptions.Builder.() -> Unit): Unit =
cognitoKibanaAuth(CognitoOptions(cognitoKibanaAuth))
/**
* @param customEndpoint To configure a custom domain configure these options.
* If you specify a Route53 hosted zone it will create a CNAME record and use DNS validation for
* the certificate
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun customEndpoint(customEndpoint: CustomEndpointOptions) {
cdkBuilder.customEndpoint(customEndpoint.let(CustomEndpointOptions.Companion::unwrap))
}
/**
* @param customEndpoint To configure a custom domain configure these options.
* If you specify a Route53 hosted zone it will create a CNAME record and use DNS validation for
* the certificate
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("9c50c1635eb80ee23c1e091e711750a47de582b0aac4fa60cc6786e22aae2639")
override fun customEndpoint(customEndpoint: CustomEndpointOptions.Builder.() -> Unit): Unit =
customEndpoint(CustomEndpointOptions(customEndpoint))
/**
* @param domainName Enforces a particular physical domain name.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun domainName(domainName: String) {
cdkBuilder.domainName(domainName)
}
/**
* @param ebs The configurations of Amazon Elastic Block Store (Amazon EBS) volumes that are
* attached to data nodes in the Amazon ES domain.
* For more information, see
* [Configuring EBS-based Storage]
* (https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-ebs)
* in the Amazon Elasticsearch Service Developer Guide.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun ebs(ebs: EbsOptions) {
cdkBuilder.ebs(ebs.let(EbsOptions.Companion::unwrap))
}
/**
* @param ebs The configurations of Amazon Elastic Block Store (Amazon EBS) volumes that are
* attached to data nodes in the Amazon ES domain.
* For more information, see
* [Configuring EBS-based Storage]
* (https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-ebs)
* in the Amazon Elasticsearch Service Developer Guide.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("d97c189489a69fc31417451f8f3508a1b26b53571043e87cbc8245fd61e76ad9")
override fun ebs(ebs: EbsOptions.Builder.() -> Unit): Unit = ebs(EbsOptions(ebs))
/**
* @param enableVersionUpgrade To upgrade an Amazon ES domain to a new version of Elasticsearch
* rather than replacing the entire domain resource, use the EnableVersionUpgrade update policy.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun enableVersionUpgrade(enableVersionUpgrade: Boolean) {
cdkBuilder.enableVersionUpgrade(enableVersionUpgrade)
}
/**
* @param encryptionAtRest Encryption at rest options for the cluster.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun encryptionAtRest(encryptionAtRest: EncryptionAtRestOptions) {
cdkBuilder.encryptionAtRest(encryptionAtRest.let(EncryptionAtRestOptions.Companion::unwrap))
}
/**
* @param encryptionAtRest Encryption at rest options for the cluster.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("24b48c9a456533b4cae5ca0aca64321babe6a0fccf60c04c4f7214842d7ca6bf")
override fun encryptionAtRest(encryptionAtRest: EncryptionAtRestOptions.Builder.() -> Unit):
Unit = encryptionAtRest(EncryptionAtRestOptions(encryptionAtRest))
/**
* @param enforceHttps True to require that all traffic to the domain arrive over HTTPS.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun enforceHttps(enforceHttps: Boolean) {
cdkBuilder.enforceHttps(enforceHttps)
}
/**
* @param fineGrainedAccessControl Specifies options for fine-grained access control.
* Requires Elasticsearch version 6.7 or later. Enabling fine-grained access control
* also requires encryption of data at rest and node-to-node encryption, along with
* enforced HTTPS.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun fineGrainedAccessControl(fineGrainedAccessControl: AdvancedSecurityOptions) {
cdkBuilder.fineGrainedAccessControl(fineGrainedAccessControl.let(AdvancedSecurityOptions.Companion::unwrap))
}
/**
* @param fineGrainedAccessControl Specifies options for fine-grained access control.
* Requires Elasticsearch version 6.7 or later. Enabling fine-grained access control
* also requires encryption of data at rest and node-to-node encryption, along with
* enforced HTTPS.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("b7b6f8887a21f8027f7c6f1fd8b7b8ffdd5f60a87ee502da105c9d57077b3dc8")
override
fun fineGrainedAccessControl(fineGrainedAccessControl: AdvancedSecurityOptions.Builder.() -> Unit):
Unit = fineGrainedAccessControl(AdvancedSecurityOptions(fineGrainedAccessControl))
/**
* @param logging Configuration log publishing configuration options.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun logging(logging: LoggingOptions) {
cdkBuilder.logging(logging.let(LoggingOptions.Companion::unwrap))
}
/**
* @param logging Configuration log publishing configuration options.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("aba05d229e9246f738f24266f5f3add48200e93225fc0d664a2502ceb2db1738")
override fun logging(logging: LoggingOptions.Builder.() -> Unit): Unit =
logging(LoggingOptions(logging))
/**
* @param nodeToNodeEncryption Specify true to enable node to node encryption.
* Requires Elasticsearch version 6.0 or later.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun nodeToNodeEncryption(nodeToNodeEncryption: Boolean) {
cdkBuilder.nodeToNodeEncryption(nodeToNodeEncryption)
}
/**
* @param removalPolicy Policy to apply when the domain is removed from the stack.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun removalPolicy(removalPolicy: RemovalPolicy) {
cdkBuilder.removalPolicy(removalPolicy.let(RemovalPolicy.Companion::unwrap))
}
/**
* @param securityGroups The list of security groups that are associated with the VPC endpoints
* for the domain.
* Only used if `vpc` is specified.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun securityGroups(securityGroups: List<ISecurityGroup>) {
cdkBuilder.securityGroups(securityGroups.map(ISecurityGroup.Companion::unwrap))
}
/**
* @param securityGroups The list of security groups that are associated with the VPC endpoints
* for the domain.
* Only used if `vpc` is specified.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun securityGroups(vararg securityGroups: ISecurityGroup): Unit =
securityGroups(securityGroups.toList())
/**
* @param tlsSecurityPolicy The minimum TLS version required for traffic to the domain.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun tlsSecurityPolicy(tlsSecurityPolicy: TLSSecurityPolicy) {
cdkBuilder.tlsSecurityPolicy(tlsSecurityPolicy.let(TLSSecurityPolicy.Companion::unwrap))
}
/**
* @param useUnsignedBasicAuth Configures the domain so that unsigned basic auth is enabled.
* If no master user is provided a default master user
* with username `admin` and a dynamically generated password stored in KMS is created. The
* password can be retrieved
* by getting `masterUserPassword` from the domain instance.
*
* Setting this to true will also add an access policy that allows unsigned
* access, enable node to node encryption, encryption at rest. If conflicting
* settings are encountered (like disabling encryption at rest) enabling this
* setting will cause a failure.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun useUnsignedBasicAuth(useUnsignedBasicAuth: Boolean) {
cdkBuilder.useUnsignedBasicAuth(useUnsignedBasicAuth)
}
/**
* @param version The Elasticsearch version that your domain will leverage.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun version(version: ElasticsearchVersion) {
cdkBuilder.version(version.let(ElasticsearchVersion.Companion::unwrap))
}
/**
* @param vpc Place the domain inside this VPC.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun vpc(vpc: IVpc) {
cdkBuilder.vpc(vpc.let(IVpc.Companion::unwrap))
}
/**
* @param vpcSubnets The specific vpc subnets the domain will be placed in.
* You must provide one subnet for each Availability Zone
* that your domain uses. For example, you must specify three subnet IDs for a three
* Availability Zone
* domain.
*
* Only used if `vpc` is specified.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun vpcSubnets(vpcSubnets: List<SubnetSelection>) {
cdkBuilder.vpcSubnets(vpcSubnets.map(SubnetSelection.Companion::unwrap))
}
/**
* @param vpcSubnets The specific vpc subnets the domain will be placed in.
* You must provide one subnet for each Availability Zone
* that your domain uses. For example, you must specify three subnet IDs for a three
* Availability Zone
* domain.
*
* Only used if `vpc` is specified.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun vpcSubnets(vararg vpcSubnets: SubnetSelection): Unit =
vpcSubnets(vpcSubnets.toList())
/**
* @param zoneAwareness The cluster zone awareness configuration for the Amazon ES domain.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun zoneAwareness(zoneAwareness: ZoneAwarenessConfig) {
cdkBuilder.zoneAwareness(zoneAwareness.let(ZoneAwarenessConfig.Companion::unwrap))
}
/**
* @param zoneAwareness The cluster zone awareness configuration for the Amazon ES domain.
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("6934866c54ce1ccd7109cd9eb1ec07b2163effc425b9437f5591a2879146a443")
override fun zoneAwareness(zoneAwareness: ZoneAwarenessConfig.Builder.() -> Unit): Unit =
zoneAwareness(ZoneAwarenessConfig(zoneAwareness))
public fun build(): software.amazon.awscdk.services.elasticsearch.DomainProps =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.elasticsearch.DomainProps,
) : CdkObject(cdkObject), DomainProps {
/**
* (deprecated) Domain Access policies.
*
* Default: - No access policies.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun accessPolicies(): List<PolicyStatement> =
unwrap(this).getAccessPolicies()?.map(PolicyStatement::wrap) ?: emptyList()
/**
* (deprecated) Additional options to specify for the Amazon ES domain.
*
* Default: - no advanced options are specified
*
* [Documentation](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-advanced-options)
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun advancedOptions(): Map<String, String> = unwrap(this).getAdvancedOptions() ?:
emptyMap()
/**
* (deprecated) The hour in UTC during which the service takes an automated daily snapshot of
* the indices in the Amazon ES domain.
*
* Only applies for Elasticsearch
* versions below 5.3.
*
* Default: - Hourly automated snapshots not used
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun automatedSnapshotStartHour(): Number? =
unwrap(this).getAutomatedSnapshotStartHour()
/**
* (deprecated) The cluster capacity configuration for the Amazon ES domain.
*
* Default: - 1 r5.large.elasticsearch data node; no dedicated master nodes.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun capacity(): CapacityConfig? = unwrap(this).getCapacity()?.let(CapacityConfig::wrap)
/**
* (deprecated) Configures Amazon ES to use Amazon Cognito authentication for Kibana.
*
* Default: - Cognito not used for authentication to Kibana.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun cognitoKibanaAuth(): CognitoOptions? =
unwrap(this).getCognitoKibanaAuth()?.let(CognitoOptions::wrap)
/**
* (deprecated) To configure a custom domain configure these options.
*
* If you specify a Route53 hosted zone it will create a CNAME record and use DNS validation for
* the certificate
*
* Default: - no custom domain endpoint will be configured
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun customEndpoint(): CustomEndpointOptions? =
unwrap(this).getCustomEndpoint()?.let(CustomEndpointOptions::wrap)
/**
* (deprecated) Enforces a particular physical domain name.
*
* Default: - A name will be auto-generated.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun domainName(): String? = unwrap(this).getDomainName()
/**
* (deprecated) The configurations of Amazon Elastic Block Store (Amazon EBS) volumes that are
* attached to data nodes in the Amazon ES domain.
*
* For more information, see
* [Configuring EBS-based Storage]
* (https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-ebs)
* in the Amazon Elasticsearch Service Developer Guide.
*
* Default: - 10 GiB General Purpose (SSD) volumes per node.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun ebs(): EbsOptions? = unwrap(this).getEbs()?.let(EbsOptions::wrap)
/**
* (deprecated) To upgrade an Amazon ES domain to a new version of Elasticsearch rather than
* replacing the entire domain resource, use the EnableVersionUpgrade update policy.
*
* Default: - false
*
* [Documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-updatepolicy.html#cfn-attributes-updatepolicy-upgradeelasticsearchdomain)
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun enableVersionUpgrade(): Boolean? = unwrap(this).getEnableVersionUpgrade()
/**
* (deprecated) Encryption at rest options for the cluster.
*
* Default: - No encryption at rest
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun encryptionAtRest(): EncryptionAtRestOptions? =
unwrap(this).getEncryptionAtRest()?.let(EncryptionAtRestOptions::wrap)
/**
* (deprecated) True to require that all traffic to the domain arrive over HTTPS.
*
* Default: - false
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun enforceHttps(): Boolean? = unwrap(this).getEnforceHttps()
/**
* (deprecated) Specifies options for fine-grained access control.
*
* Requires Elasticsearch version 6.7 or later. Enabling fine-grained access control
* also requires encryption of data at rest and node-to-node encryption, along with
* enforced HTTPS.
*
* Default: - fine-grained access control is disabled
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun fineGrainedAccessControl(): AdvancedSecurityOptions? =
unwrap(this).getFineGrainedAccessControl()?.let(AdvancedSecurityOptions::wrap)
/**
* (deprecated) Configuration log publishing configuration options.
*
* Default: - No logs are published
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun logging(): LoggingOptions? = unwrap(this).getLogging()?.let(LoggingOptions::wrap)
/**
* (deprecated) Specify true to enable node to node encryption.
*
* Requires Elasticsearch version 6.0 or later.
*
* Default: - Node to node encryption is not enabled.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun nodeToNodeEncryption(): Boolean? = unwrap(this).getNodeToNodeEncryption()
/**
* (deprecated) Policy to apply when the domain is removed from the stack.
*
* Default: RemovalPolicy.RETAIN
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun removalPolicy(): RemovalPolicy? =
unwrap(this).getRemovalPolicy()?.let(RemovalPolicy::wrap)
/**
* (deprecated) The list of security groups that are associated with the VPC endpoints for the
* domain.
*
* Only used if `vpc` is specified.
*
* Default: - One new security group is created.
*
* [Documentation](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html)
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun securityGroups(): List<ISecurityGroup> =
unwrap(this).getSecurityGroups()?.map(ISecurityGroup::wrap) ?: emptyList()
/**
* (deprecated) The minimum TLS version required for traffic to the domain.
*
* Default: - TLSSecurityPolicy.TLS_1_0
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun tlsSecurityPolicy(): TLSSecurityPolicy? =
unwrap(this).getTlsSecurityPolicy()?.let(TLSSecurityPolicy::wrap)
/**
* (deprecated) Configures the domain so that unsigned basic auth is enabled.
*
* If no master user is provided a default master user
* with username `admin` and a dynamically generated password stored in KMS is created. The
* password can be retrieved
* by getting `masterUserPassword` from the domain instance.
*
* Setting this to true will also add an access policy that allows unsigned
* access, enable node to node encryption, encryption at rest. If conflicting
* settings are encountered (like disabling encryption at rest) enabling this
* setting will cause a failure.
*
* Default: - false
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun useUnsignedBasicAuth(): Boolean? = unwrap(this).getUseUnsignedBasicAuth()
/**
* (deprecated) The Elasticsearch version that your domain will leverage.
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun version(): ElasticsearchVersion =
unwrap(this).getVersion().let(ElasticsearchVersion::wrap)
/**
* (deprecated) Place the domain inside this VPC.
*
* Default: - Domain is not placed in a VPC.
*
* [Documentation](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-vpc.html)
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun vpc(): IVpc? = unwrap(this).getVpc()?.let(IVpc::wrap)
/**
* (deprecated) The specific vpc subnets the domain will be placed in.
*
* You must provide one subnet for each Availability Zone
* that your domain uses. For example, you must specify three subnet IDs for a three
* Availability Zone
* domain.
*
* Only used if `vpc` is specified.
*
* Default: - All private subnets.
*
* [Documentation](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html)
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun vpcSubnets(): List<SubnetSelection> =
unwrap(this).getVpcSubnets()?.map(SubnetSelection::wrap) ?: emptyList()
/**
* (deprecated) The cluster zone awareness configuration for the Amazon ES domain.
*
* Default: - no zone awareness (1 AZ)
*
* @deprecated use opensearchservice module instead
*/
@Deprecated(message = "deprecated in CDK")
override fun zoneAwareness(): ZoneAwarenessConfig? =
unwrap(this).getZoneAwareness()?.let(ZoneAwarenessConfig::wrap)
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): DomainProps {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.elasticsearch.DomainProps):
DomainProps = CdkObjectWrappers.wrap(cdkObject) as? DomainProps ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: DomainProps):
software.amazon.awscdk.services.elasticsearch.DomainProps = (wrapped as CdkObject).cdkObject
as software.amazon.awscdk.services.elasticsearch.DomainProps
}
}
| 1 | Kotlin | 0 | 4 | 7a060aa8b6779ab04dc9881993d9598e11d278b1 | 51,143 | kotlin-cdk-wrapper | Apache License 2.0 |
src/main/kotlin/dev/chara/tasks/backend/data/repository/TaskRepository.kt | 19lmyers | 624,219,343 | false | {"Kotlin": 150928, "Python": 9314, "Dockerfile": 922, "Shell": 57} | package dev.chara.tasks.backend.data.repository
import com.github.michaelbull.result.binding
import com.github.michaelbull.result.map
import com.github.michaelbull.result.mapError
import com.github.michaelbull.result.runCatching
import dev.chara.tasks.backend.data.DataError
import dev.chara.tasks.backend.data.DatabaseFactory
import dev.chara.tasks.backend.domain.model.Task
import dev.chara.tasks.backend.domain.model.toModel
import java.util.*
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sign
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
class TaskRepository(databaseFactory: DatabaseFactory) {
private val database = databaseFactory.getDatabase()
fun getById(taskId: String) =
runCatching { database.taskQueries.getById(taskId).executeAsOneOrNull() }
.mapError { DataError.DatabaseError(it) }
.map { it?.toModel() }
fun getByList(listId: String) =
runCatching { database.taskQueries.getByList(listId).executeAsList() }
.mapError { DataError.DatabaseError(it) }
.map { tasks -> tasks.map { it.toModel() } }
private fun getMaxOrdinal(listId: String) =
runCatching { database.taskQueries.getMaxOrdinal(listId).executeAsOneOrNull()?.MAX }
.mapError { DataError.DatabaseError(it) }
fun insert(userId: String, listId: String, task: Task) = binding {
val id = UUID.randomUUID().toString()
val maxOrdinal = getMaxOrdinal(listId).bind()
runCatching {
database.taskQueries.insert(
id,
list_id = listId,
label = task.label,
is_completed = task.isCompleted,
is_starred = task.isStarred,
details = task.details,
reminder_date = task.reminderDate,
due_date = task.dueDate,
last_modified = task.lastModified,
reminder_fired = null,
date_created = Clock.System.now(),
ordinal = maxOrdinal ?: 0,
category = task.category
)
}
.mapError { DataError.DatabaseError(it) }
.bind()
id
}
fun update(taskId: String, task: Task) =
runCatching {
database.taskQueries.update(
label = task.label,
is_completed = task.isCompleted,
is_starred = task.isStarred,
details = task.details,
reminder_date = task.reminderDate,
due_date = task.dueDate,
last_modified = task.lastModified,
id = taskId,
category = task.category
)
}
.mapError { DataError.DatabaseError(it) }
fun move(newListId: String, taskId: String, lastModified: Instant) =
runCatching { database.taskQueries.move(newListId, lastModified, taskId) }
.mapError { DataError.DatabaseError(it) }
fun reorder(
listId: String,
taskId: String,
fromIndex: Int,
toIndex: Int,
lastModified: Instant
) =
runCatching {
database.taskQueries.reorder(
list_id = listId,
task_id = taskId,
ordinal = toIndex.toLong(),
difference_sign = (fromIndex - toIndex).sign,
lower_bound = min(fromIndex, toIndex),
upper_bound = max(fromIndex, toIndex),
last_modified = lastModified
)
}
.mapError { DataError.DatabaseError(it) }
fun delete(taskId: String) =
runCatching { database.taskQueries.delete(taskId) }.mapError { DataError.DatabaseError(it) }
fun clearCompletedTasksByList(listId: String) =
runCatching { database.taskQueries.clearCompletedByList(listId) }
.mapError { DataError.DatabaseError(it) }
}
| 0 | Kotlin | 0 | 1 | 8605f3ea9d2107ad86000d8af2b8d41b3242bc2f | 4,090 | tasks-backend | MIT License |
src/main/kotlin/furhatos/app/cardgame/flow/discussion/StartDiscussing.kt | horotat | 518,806,515 | false | {"Kotlin": 252871, "JavaScript": 58777, "Java": 21569, "FreeMarker": 16510, "HTML": 4928, "CSS": 4484} | package furhatos.app.cardgame.flow.discussion
import furhatos.app.cardgame.*
import furhatos.app.cardgame.game.GameTable
import furhatos.flow.kotlin.*
import furhatos.skills.FurhatAPI
import furhatos.util.Language
val StartDiscussing: State = state(Discussing) {
onEntry {
/*
if(!isThisRoundTwo) {
// Grounding: "By the way, You can touch the screen to move the cards. I don't have hands, you see."
furhat.attendCheck(users.other)
furhat.say(output.by_the_way_name)
furhat.attendCheck(GameTable.centerLocation)
furhat.say(output.explain_you_can_move_cards)
furhat.attendCheck(users.current)
furhat.say (output.no_hands_you_see)
}
*/
Furhat.param.endSilTimeout = endSilTimeoutDiscussion
furhat.attendOneOrAll()
furhat.askCheck(output.ask_where_to_start)
}
} | 0 | Kotlin | 0 | 0 | a95aa619831614f5347cb7ffee762bbb32735211 | 906 | Card-Game-21 | Creative Commons Attribution 4.0 International |
src/main/kotlin/de/hennihaus/models/Contact.kt | hennihaus | 484,714,079 | false | null | package de.hennihaus.models
import java.util.UUID
data class Contact(
val uuid: UUID,
val firstname: String,
val lastname: String,
val email: String,
)
| 32 | Kotlin | 0 | 0 | d9e57a5ca5f0712671cf4e26c578c1fb22c0262f | 170 | bamconfigbackend | Apache License 2.0 |
pixel-core/src/jsMain/kotlin/com/chrynan/pixel/JsConversionFactorProvider.kt | chRyNaN | 157,776,400 | false | null | package com.chrynan.pixel
/**
* A default Javascript implementation of the [ConversionFactorProvider] interface.
*
* Note that in Javascript, a pixel (CSS pixel), is similar to Android's density independent pixel values. Because of
* this, the [Pixels], [DensityIndependentPixels], and [ScaledPixels] are equivalent.
*
* Note that in Javascript, there is no access (to my knowledge) of the physical display size. There is only access to
* the amount of CSS Pixels in a display. Since [PointPixels] are based off the physical display size, and there is no
* way to acquire the display size needed for conversion, [Pixels] and [PointPixels] are equivalent.
*
* @author chRyNaN
*/
class JsConversionFactorProvider : ConversionFactorProvider {
override val dipToPxFactor: Float = 1f
override val spToPxFactor: Float = 1f
override val ptToPxFactor: Float = 1f
} | 0 | Kotlin | 0 | 3 | 7a4c17f5ce58438280c818911f82584020b432ca | 883 | pixel | Apache License 2.0 |
compose-mds/src/main/java/ch/sbb/compose_mds/sbbicons/medium/FaceKingMedium.kt | SchweizerischeBundesbahnen | 853,290,161 | false | {"Kotlin": 6728512} | package ch.sbb.compose_mds.sbbicons.medium
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import ch.sbb.compose_mds.sbbicons.MediumGroup
public val MediumGroup.FaceKingMedium: ImageVector
get() {
if (_faceKingMedium != null) {
return _faceKingMedium!!
}
_faceKingMedium = Builder(name = "FaceKingMedium", defaultWidth = 36.0.dp, defaultHeight =
36.0.dp, viewportWidth = 36.0f, viewportHeight = 36.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveToRelative(9.25f, 2.867f)
lineToRelative(0.757f, 0.454f)
lineToRelative(3.415f, 2.05f)
lineToRelative(1.974f, -1.975f)
lineToRelative(0.354f, -0.353f)
lineToRelative(0.354f, 0.353f)
lineTo(18.0f, 5.293f)
lineToRelative(1.896f, -1.897f)
lineToRelative(0.354f, -0.353f)
lineToRelative(0.354f, 0.353f)
lineToRelative(1.974f, 1.974f)
lineToRelative(3.415f, -2.049f)
lineToRelative(0.757f, -0.454f)
verticalLineToRelative(9.683f)
arcToRelative(11.23f, 11.23f, 0.0f, false, true, 3.0f, 8.468f)
arcToRelative(11.75f, 11.75f, 0.0f, false, true, -23.5f, 0.0f)
arcToRelative(11.23f, 11.23f, 0.0f, false, true, 3.0f, -8.468f)
lineTo(9.25f, 2.867f)
moveToRelative(0.715f, 10.383f)
arcToRelative(10.22f, 10.22f, 0.0f, false, false, -2.716f, 7.714f)
lineToRelative(0.001f, 0.018f)
lineTo(7.25f, 21.0f)
arcToRelative(10.75f, 10.75f, 0.0f, true, false, 21.5f, 0.0f)
verticalLineToRelative(-0.018f)
lineToRelative(0.001f, -0.018f)
arcToRelative(10.22f, 10.22f, 0.0f, false, false, -2.716f, -7.714f)
close()
moveTo(10.25f, 4.633f)
verticalLineToRelative(7.617f)
horizontalLineToRelative(15.5f)
lineTo(25.75f, 4.633f)
lineTo(22.757f, 6.43f)
lineToRelative(-0.335f, 0.2f)
lineToRelative(-0.276f, -0.275f)
lineToRelative(-1.896f, -1.897f)
lineToRelative(-1.896f, 1.897f)
lineToRelative(-0.354f, 0.353f)
lineToRelative(-0.354f, -0.353f)
lineToRelative(-1.896f, -1.897f)
lineToRelative(-1.896f, 1.897f)
lineToRelative(-0.276f, 0.276f)
lineToRelative(-0.335f, -0.201f)
close()
moveTo(22.095f, 18.845f)
arcToRelative(0.52f, 0.52f, 0.0f, true, false, 0.0f, 1.04f)
arcToRelative(0.52f, 0.52f, 0.0f, false, false, 0.0f, -1.04f)
moveToRelative(-1.52f, 0.52f)
arcToRelative(1.52f, 1.52f, 0.0f, true, true, 3.04f, 0.0f)
arcToRelative(1.52f, 1.52f, 0.0f, false, true, -3.04f, 0.0f)
moveToRelative(-7.19f, 0.0f)
arcToRelative(0.52f, 0.52f, 0.0f, true, true, 1.04f, 0.0f)
arcToRelative(0.52f, 0.52f, 0.0f, false, true, -1.04f, 0.0f)
moveToRelative(0.52f, -1.52f)
arcToRelative(1.52f, 1.52f, 0.0f, true, false, 0.0f, 3.04f)
arcToRelative(1.52f, 1.52f, 0.0f, false, false, 0.0f, -3.04f)
moveToRelative(0.68f, 9.546f)
arcToRelative(7.25f, 7.25f, 0.0f, false, true, -2.61f, -2.363f)
lineToRelative(0.83f, -0.556f)
arcToRelative(6.25f, 6.25f, 0.0f, false, false, 10.39f, 0.0f)
lineToRelative(0.83f, 0.556f)
arcToRelative(7.25f, 7.25f, 0.0f, false, true, -9.44f, 2.363f)
}
}
.build()
return _faceKingMedium!!
}
private var _faceKingMedium: ImageVector? = null
| 0 | Kotlin | 0 | 1 | 090a66a40e1e5a44d4da6209659287a68cae835d | 4,572 | mds-android-compose | MIT License |
app/src/main/java/com/example/agenda_musical_reto1/data/repository/ISongRepository.kt | RobsonGarciaJunior | 706,217,359 | false | {"Kotlin": 97375} | package com.example.agenda_musical_reto1.data.repository
import com.example.agenda_musical_reto1.data.Song
import com.example.agenda_musical_reto1.utils.Resource
interface ISongRepository {
suspend fun getSongs() : Resource<List<Song>>
suspend fun getSong(id: Int) : Resource<Song>
suspend fun createSong(song: Song) : Resource<Int>
suspend fun updateSong(id: Int, song: Song) : Resource<Int>
suspend fun deleteSong(id: Int) : Resource<Int>
suspend fun getSongByAuthor(author: String) : Resource<List<Song>>
} | 0 | Kotlin | 0 | 0 | 89cff2ef64ee8e4ae80b5f4452791e5173a085f5 | 535 | Reto1_AgendaMusical_Android | MIT License |
library/src/test/kotlin/com/daniloaraujosilva/mathemagika/library/wasm32/ExampleTests.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.wasm32
import com.daniloaraujosilva.mathemagika.library.wasm32.common.exampleFunction
import kotlin.test.Test
import kotlin.test.assertTrue
/**
*
*/
class ExampleTests {
/**
*
*/
@Test
fun exampleValueCannotBeEmpty() {
assertTrue(exampleFunction().isNotEmpty())
}
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 331 | mathemagika | Apache License 2.0 |
bgw-gui/src/main/kotlin/tools/aqua/bgw/components/gamecomponentviews/DiceView.kt | tudo-aqua | 377,420,862 | false | {"Kotlin": 1198455, "TypeScript": 2013, "JavaScript": 1242, "HTML": 507, "CSS": 359, "Ruby": 131} | /*
* Copyright 2021-2023 The BoardGameWork Authors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
@file:Suppress("unused")
package tools.aqua.bgw.components.gamecomponentviews
import tools.aqua.bgw.core.DEFAULT_DICE_HEIGHT
import tools.aqua.bgw.core.DEFAULT_DICE_WIDTH
import tools.aqua.bgw.observable.lists.ObservableArrayList
import tools.aqua.bgw.visual.Visual
/**
* A [DiceView] may be used to visualize a dice.
*
* Visualization:
*
* The Visual at the [currentSide] value is used to visualize the dice.
*
* @constructor Creates a [DiceView] with given [Visual]s.
*
* @param posX Horizontal coordinate for this [DiceView]. Default: 0.
* @param posY Vertical coordinate for this [DiceView]. Default: 0.
* @param width Width for this [DiceView]. Default: [DEFAULT_DICE_WIDTH].
* @param height Height for this [DiceView]. Default: [DEFAULT_DICE_HEIGHT].
* @param visuals List of visuals to represent the sides of the die.
*/
open class DiceView(
posX: Number = 0,
posY: Number = 0,
width: Number = DEFAULT_DICE_WIDTH,
height: Number = DEFAULT_DICE_HEIGHT,
visuals: List<Visual>
) :
GameComponentView(
posX = posX, posY = posY, width = width, height = height, visual = Visual.EMPTY) {
/** [Visual]s for this [DiceView]. */
internal val visuals: ObservableArrayList<Visual> =
ObservableArrayList(visuals.onEach { it.copy() })
/**
* Current side that is displayed, 0-based.
*
* @throws IllegalArgumentException If index is greater than the amount of visuals stored in
* [visuals] or negative.
*/
var currentSide: Int = 0
set(value) {
if (field != value) {
require(value in visuals.indices) { "No visual for side $value available." }
field = value
visualProperty.value = visuals[value]
}
}
override var visual: Visual
get() = super.visual
set(_) {
throw UnsupportedOperationException(
"Setting a single Visual for a DiceView is not supported. " +
"Use `visuals` setter instead.")
}
init {
visualProperty.value = if (visuals.isNotEmpty()) visuals.first() else Visual.EMPTY
}
/**
* Sets all visuals for this DiceView. Clears old visuals. All [visuals] get copied before being
* added. If [currentSide] is out of range, a [Visual.EMPTY] will be shown.
*/
fun setVisuals(visuals: List<Visual>) {
val snapshot = visuals.toList()
this.visuals.setSilent(visuals.onEach { it.copy() })
this.visuals.notifyChange(oldValue = snapshot, newValue = visuals.toList())
visualProperty.value =
if (currentSide in visuals.indices) visuals[currentSide] else Visual.EMPTY
}
}
| 31 | Kotlin | 16 | 24 | 266db439e4443d10bc1ec7eb7d9032f29daf6981 | 3,228 | bgw | Apache License 2.0 |
src/test/kotlin/br/com/pix/edumatt3/pix/consult/ConsultPixKeyControllerTest.kt | EDUMATT3 | 399,821,207 | true | {"Kotlin": 27495} | package br.com.pix.edumatt3.pix.consult
import br.com.edumatt3.*
import br.com.pix.edumatt3.grpc.GrpcClientFactory
import com.google.protobuf.Timestamp
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.micronaut.context.annotation.Factory
import io.micronaut.context.annotation.Replaces
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpStatus
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import jakarta.inject.Inject
import jakarta.inject.Singleton
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.mockito.BDDMockito.any
import org.mockito.BDDMockito.given
import org.mockito.Mockito
import java.util.*
@MicronautTest
internal class ConsultPixKeyControllerTest{
@Inject
lateinit var grpcClient: ConsultPixKeyServiceGrpc.ConsultPixKeyServiceBlockingStub
@Inject
@field:Client("/")
lateinit var client: HttpClient
@AfterEach
fun cleanUp() {
Mockito.reset(grpcClient)
}
@Test
internal fun `should return a pix key info`() {
val clientId = UUID.randomUUID().toString()
val pixId = UUID.randomUUID().toString()
val grpcRequest = ConsultPixKeyResponse
.newBuilder()
.setClientId(clientId)
.setPixId(pixId)
.setPixKey(ConsultPixKeyResponse.PixKey.newBuilder()
.setKey("50508675847")
.setType(KeyType.EMAIL)
.setCreatedAt(Timestamp.newBuilder().build())
.setAccount(ConsultPixKeyResponse.PixKey.AccountInfo.newBuilder()
.setType(AccountType.CONTA_CORRENTE)
.setAgency("0001")
.setInstituition("ITAU UNIBANCO S.A")
.setCustomerCpf("50508675847")
.setCustomerName("Fulano")
).build()
).build()
given(grpcClient.consult(any())).willReturn(grpcRequest)
val request = HttpRequest.GET<Any>("/api/pix/clients/$clientId/keys/$pixId")
val response = client.toBlocking().exchange(request, Any::class.java)
with(response){
assertEquals(HttpStatus.OK, status)
assertNotNull(body())
}
}
@Test
internal fun `should not return a pix key info when isnt found`() {
val clientId = UUID.randomUUID().toString()
val pixId = UUID.randomUUID().toString()
given(grpcClient.consult(any())).willThrow(StatusRuntimeException(Status.NOT_FOUND))
val request = HttpRequest.GET<Any>("/api/pix/clients/$clientId/keys/$pixId")
val thrown = assertThrows<HttpClientResponseException> {
client.toBlocking().exchange(request, Any::class.java)
}
with(thrown){
assertEquals(HttpStatus.NOT_FOUND, status)
assertEquals(null, response.body())
}
}
@Factory
@Replaces(factory = GrpcClientFactory::class)
internal class ConsultKeyGrpcStub() {
@Singleton
internal fun getConsultService() = Mockito.mock(ConsultPixKeyServiceGrpc.ConsultPixKeyServiceBlockingStub::class.java)
}
} | 0 | Kotlin | 0 | 0 | 134647d3b3e8b5721fbc077b9a9628d779f06259 | 3,412 | orange-talents-06-template-pix-keymanager-rest | Apache License 2.0 |
src/main/kotlin/eZmaxApi/models/EzsigntemplateformfieldgroupMinusResponseCompound.kt | eZmaxinc | 271,950,932 | false | null | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package eZmaxApi.models
import eZmaxApi.models.FieldMinusEEzsigntemplateformfieldgroupSignerrequirement
import eZmaxApi.models.FieldMinusEEzsigntemplateformfieldgroupTooltipposition
import eZmaxApi.models.FieldMinusEEzsigntemplateformfieldgroupType
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* A Ezsigntemplateformfieldgroup Object
*
* @param fkiEzsigntemplatedocumentID The unique ID of the Ezsigntemplatedocument
* @param eEzsigntemplateformfieldgroupType
* @param eEzsigntemplateformfieldgroupSignerrequirement
* @param sEzsigntemplateformfieldgroupLabel The Label for the Ezsigntemplateformfieldgroup
* @param iEzsigntemplateformfieldgroupStep The step when the Ezsigntemplatesigner will be invited to fill the form fields
* @param sEzsigntemplateformfieldgroupDefaultvalue The default value for the Ezsigntemplateformfieldgroup
* @param iEzsigntemplateformfieldgroupFilledmin The minimum number of Ezsigntemplateformfield that must be filled in the Ezsigntemplateformfieldgroup
* @param iEzsigntemplateformfieldgroupFilledmax The maximum number of Ezsigntemplateformfield that must be filled in the Ezsigntemplateformfieldgroup
* @param bEzsigntemplateformfieldgroupReadonly Whether the Ezsigntemplateformfieldgroup is read only or not.
* @param pkiEzsigntemplateformfieldgroupID The unique ID of the Ezsigntemplateformfieldgroup
* @param iEzsigntemplateformfieldgroupMaxlength The maximum length for the value in the Ezsigntemplateformfieldgroup This can only be set if eEzsigntemplateformfieldgroupType is **Text** or **Textarea**
* @param bEzsigntemplateformfieldgroupEncrypted Whether the Ezsigntemplateformfieldgroup is encrypted in the database or not. Encrypted values are not displayed on the Ezsigndocument. This can only be set if eEzsigntemplateformfieldgroupType is **Text** or **Textarea**
* @param sEzsigntemplateformfieldgroupRegexp A regular expression to indicate what values are acceptable for the Ezsigntemplateformfieldgroup. This can only be set if eEzsigntemplateformfieldgroupType is **Text** or **Textarea**
* @param tEzsigntemplateformfieldgroupTooltip A tooltip that will be presented to Ezsigntemplatesigner about the Ezsigntemplateformfieldgroup
* @param eEzsigntemplateformfieldgroupTooltipposition
*/
data class EzsigntemplateformfieldgroupMinusRequest (
/* The unique ID of the Ezsigntemplatedocument */
@Json(name = "fkiEzsigntemplatedocumentID")
val fkiEzsigntemplatedocumentID: kotlin.Int,
@Json(name = "eEzsigntemplateformfieldgroupType")
val eEzsigntemplateformfieldgroupType: FieldMinusEEzsigntemplateformfieldgroupType,
@Json(name = "eEzsigntemplateformfieldgroupSignerrequirement")
val eEzsigntemplateformfieldgroupSignerrequirement: FieldMinusEEzsigntemplateformfieldgroupSignerrequirement,
/* The Label for the Ezsigntemplateformfieldgroup */
@Json(name = "sEzsigntemplateformfieldgroupLabel")
val sEzsigntemplateformfieldgroupLabel: kotlin.String,
/* The step when the Ezsigntemplatesigner will be invited to fill the form fields */
@Json(name = "iEzsigntemplateformfieldgroupStep")
val iEzsigntemplateformfieldgroupStep: kotlin.Int,
/* The default value for the Ezsigntemplateformfieldgroup */
@Json(name = "sEzsigntemplateformfieldgroupDefaultvalue")
val sEzsigntemplateformfieldgroupDefaultvalue: kotlin.String,
/* The minimum number of Ezsigntemplateformfield that must be filled in the Ezsigntemplateformfieldgroup */
@Json(name = "iEzsigntemplateformfieldgroupFilledmin")
val iEzsigntemplateformfieldgroupFilledmin: kotlin.Int,
/* The maximum number of Ezsigntemplateformfield that must be filled in the Ezsigntemplateformfieldgroup */
@Json(name = "iEzsigntemplateformfieldgroupFilledmax")
val iEzsigntemplateformfieldgroupFilledmax: kotlin.Int,
/* Whether the Ezsigntemplateformfieldgroup is read only or not. */
@Json(name = "bEzsigntemplateformfieldgroupReadonly")
val bEzsigntemplateformfieldgroupReadonly: kotlin.Boolean,
/* The unique ID of the Ezsigntemplateformfieldgroup */
@Json(name = "pkiEzsigntemplateformfieldgroupID")
val pkiEzsigntemplateformfieldgroupID: kotlin.Int? = null,
/* The maximum length for the value in the Ezsigntemplateformfieldgroup This can only be set if eEzsigntemplateformfieldgroupType is **Text** or **Textarea** */
@Json(name = "iEzsigntemplateformfieldgroupMaxlength")
val iEzsigntemplateformfieldgroupMaxlength: kotlin.Int? = null,
/* Whether the Ezsigntemplateformfieldgroup is encrypted in the database or not. Encrypted values are not displayed on the Ezsigndocument. This can only be set if eEzsigntemplateformfieldgroupType is **Text** or **Textarea** */
@Json(name = "bEzsigntemplateformfieldgroupEncrypted")
val bEzsigntemplateformfieldgroupEncrypted: kotlin.Boolean? = null,
/* A regular expression to indicate what values are acceptable for the Ezsigntemplateformfieldgroup. This can only be set if eEzsigntemplateformfieldgroupType is **Text** or **Textarea** */
@Json(name = "sEzsigntemplateformfieldgroupRegexp")
val sEzsigntemplateformfieldgroupRegexp: kotlin.String? = null,
/* A tooltip that will be presented to Ezsigntemplatesigner about the Ezsigntemplateformfieldgroup */
@Json(name = "tEzsigntemplateformfieldgroupTooltip")
val tEzsigntemplateformfieldgroupTooltip: kotlin.String? = null,
@Json(name = "eEzsigntemplateformfieldgroupTooltipposition")
val eEzsigntemplateformfieldgroupTooltipposition: FieldMinusEEzsigntemplateformfieldgroupTooltipposition? = null
)
| 0 | Kotlin | 0 | 0 | fad1a7a8b3f744256968e67e5f60044063cb551c | 5,894 | eZmax-SDK-kotlin | MIT License |
app/src/main/java/org/fossasia/openevent/general/event/Event.kt | fossasia | 34,847,604 | false | null | package org.fossasia.openevent.general.event
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import com.fasterxml.jackson.databind.PropertyNamingStrategy
import com.fasterxml.jackson.databind.annotation.JsonNaming
import com.github.jasminb.jsonapi.LongIdHandler
import com.github.jasminb.jsonapi.annotations.Id
import com.github.jasminb.jsonapi.annotations.Relationship
import com.github.jasminb.jsonapi.annotations.Type
import org.fossasia.openevent.general.event.topic.EventTopic
@Type("event")
@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy::class)
@Entity
data class Event(
@Id(LongIdHandler::class)
@PrimaryKey
val id: Long,
val name: String,
val identifier: String,
val startsAt: String,
val endsAt: String,
val timezone: String,
val privacy: String = "public",
val paymentCountry: String? = null,
val paypalEmail: String? = null,
val thumbnailImageUrl: String? = null,
val schedulePublishedOn: String? = null,
val paymentCurrency: String? = null,
val organizerDescription: String? = null,
val originalImageUrl: String? = null,
val onsiteDetails: String? = null,
val organizerName: String? = null,
val largeImageUrl: String? = null,
val deletedAt: String? = null,
val ticketUrl: String? = null,
val locationName: String? = null,
val codeOfConduct: String? = null,
val state: String? = null,
val searchableLocationName: String? = null,
val description: String? = null,
val pentabarfUrl: String? = null,
val xcalUrl: String? = null,
val logoUrl: String? = null,
val externalEventUrl: String? = null,
val iconImageUrl: String? = null,
val icalUrl: String? = null,
val createdAt: String? = null,
val bankDetails: String? = null,
val chequeDetails: String? = null,
val isComplete: Boolean = false,
val latitude: Double? = null,
val longitude: Double? = null,
val refundPolicy: String? = null,
val canPayByStripe: Boolean = false,
val canPayByCheque: Boolean = false,
val canPayByBank: Boolean = false,
val canPayByPaypal: Boolean = false,
val canPayOnsite: Boolean = false,
val isSponsorsEnabled: Boolean = false,
val hasOrganizerInfo: Boolean = false,
val isSessionsSpeakersEnabled: Boolean = false,
val isTicketingEnabled: Boolean = false,
val isTaxEnabled: Boolean = false,
val isMapShown: Boolean = false,
var favorite: Boolean = false,
@ColumnInfo(index = true)
@Relationship("event-topic")
var eventTopic: EventTopic? = null
)
| 73 | null | 562 | 1,942 | e3214589f83c155e477f9e727370d7bbef8fd915 | 2,651 | open-event-attendee-android | Apache License 2.0 |
tools/src/main/kotlin/com/fphoenixcorneae/common/util/toast/IToastStrategy.kt | FPhoenixCorneaE | 303,260,191 | false | {"Kotlin": 991199} | package com.fphoenixcorneae.util.toast
import android.widget.Toast
/**
* Toast 处理策略
*/
interface IToastStrategy {
/**
* 绑定 Toast 对象
*/
fun bind(toast: Toast?)
/**
* 显示 Toast
*/
fun show(text: CharSequence?)
/**
* 取消 Toast
*/
fun cancel()
companion object {
/**
* 短吐司显示的时长
*/
const val SHORT_DURATION_TIMEOUT = 2000
/**
* 长吐司显示的时长
*/
const val LONG_DURATION_TIMEOUT = 3500
}
} | 0 | Kotlin | 1 | 5 | 30fb45aee64e74e36f7a834646096a665b6835a0 | 512 | common-tools | Apache License 2.0 |
app/src/main/java/com/example/buynow/presentation/user/adapter/CategoryNameAdapter.kt | Shanan23 | 794,368,317 | false | {"Kotlin": 220243} | package com.example.buynow.presentation.user.adapter
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.example.buynow.R
import com.example.buynow.data.model.Category
class CategoryNameAdapter(val dataList: List<Category>) :
RecyclerView.Adapter<CategoryNameAdapter.ViewHolder>() {
private var selectedItemPosition = RecyclerView.NO_POSITION
private var onCategoryClickListener: OnCategoryClickListener? = null
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): CategoryNameAdapter.ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.category_name_single, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return dataList.size
}
override fun onBindViewHolder(holder: CategoryNameAdapter.ViewHolder, position: Int) {
val item = dataList[position]
holder.bind(item.Name)
holder.itemView.setOnClickListener {
selectedItemPosition = position
onCategoryClickListener?.onCategoryClicked(item)
notifyDataSetChanged()
}
// Change background color of the selected item
holder.itemView.setBackgroundColor(
if (selectedItemPosition == position) {
ContextCompat.getColor(
holder.itemView.context,
R.color.backgroundLike
)
} else {
Color.WHITE
}
)
val textColor = if (selectedItemPosition == position) ContextCompat.getColor(
holder.itemView.context,
R.color.white
) else ContextCompat.getColor(holder.itemView.context, R.color.mainText)
holder.categoryName.setTextColor(textColor)
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
public val categoryName: TextView = itemView.findViewById(R.id.categoryName)
fun bind(item: String) {
categoryName.text = item
}
}
fun setOnCategoryClickListener(listener: OnCategoryClickListener) {
onCategoryClickListener = listener
}
interface OnCategoryClickListener {
fun onCategoryClicked(category: Category)
}
} | 0 | Kotlin | 0 | 0 | 072435120a602f1818e692ad95a58b0c887b496a | 2,479 | ToSerba | MIT License |
andserver/src/main/java/com/angcyo/server/bean/SchemeReqBean.kt | angcyo | 229,037,684 | false | {"Kotlin": 3528362, "JavaScript": 5542, "HTML": 1598} | package com.angcyo.server.bean
import com.angcyo.library.extend.IJson
/**
* @author <a href="mailto:<EMAIL>">angcyo</a>
* @since 2022/11/17
*/
data class SchemeReqBean(
var scheme: String? = null
) : IJson
| 0 | Kotlin | 4 | 4 | 886faba0130a0ab4dfdf5d46ece507ef6b803ab6 | 215 | UICoreEx | MIT License |
zeapp/android/src/main/java/de/berlindroid/zeapp/zeui/zepages/ZeRandomQuotePage.kt | gdg-berlin-android | 636,343,114 | false | null | package de.berlindroid.zeapp.zeui.zepages
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import de.berlindroid.zeapp.PAGE_HEIGHT
import de.berlindroid.zeapp.PAGE_WIDTH
import de.berlindroid.zeapp.R
/**
* A composable that represents a quote card, to be renderd as a bitmap.
*/
@Composable
@Preview
fun RandomQuotePage(
message: String = "Don't blame others. it won't make you a better person.",
author: String = "Lolly Daskal",
) {
val size by remember { mutableStateOf(6.sp) }
Column(
modifier = Modifier
.background(
color = Color.White,
)
.size(
width = with(LocalDensity.current) { PAGE_WIDTH.toDp() },
height = with(LocalDensity.current) { PAGE_HEIGHT.toDp() },
),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
modifier = Modifier
.fillMaxWidth()
.background(Color.Black),
fontFamily = FontFamily.Monospace,
fontSize = 8.sp,
textAlign = TextAlign.Center,
color = Color.White,
maxLines = 1,
text = stringResource(R.string.quote_of_the_day),
)
Text(
modifier = Modifier
.wrapContentSize()
.weight(1.0f),
fontSize = size,
textAlign = TextAlign.Center,
text = message,
)
Text(
modifier = Modifier
.fillMaxWidth()
.background(Color.Black),
fontFamily = FontFamily.Monospace,
fontSize = 6.sp,
color = Color.White,
textAlign = TextAlign.Center,
maxLines = 1,
text = author,
)
}
}
| 9 | null | 105 | 48 | e06da6dd31962a340427556c40357cfd2fef1b2c | 2,647 | ZeBadge | Apache License 2.0 |
presentation/src/main/java/com/yapp/buddycon/presentation/binding/addcoupon/AddCouponBindingAdapter.kt | YAPP-Github | 561,172,522 | false | null | package com.yapp.buddycon.presentation.binding.addcoupon
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.BindingAdapter
import com.yapp.buddycon.domain.model.CouponInfo
import com.yapp.buddycon.presentation.R
import com.yapp.buddycon.presentation.ui.addCoupon.state.CouponInfoLoadState
import kotlinx.coroutines.flow.StateFlow
@BindingAdapter("android:expireDateDescriptionByState")
fun setSelected(view: TextView, couponInfoLoadState: CouponInfoLoadState<CouponInfo>?){
couponInfoLoadState?.let {
when(couponInfoLoadState) {
is CouponInfoLoadState.NewGifticon -> {
val builder = SpannableStringBuilder()
val textWithStar = view.context.getString(R.string.add_coupon_expire_date_input)
val titleHintSpannable = SpannableString(textWithStar)
titleHintSpannable.setSpan(
ForegroundColorSpan(ContextCompat.getColor(view.context, R.color.orange100)),
textWithStar.length - 1, textWithStar.length, 0
)
builder.append(titleHintSpannable)
view.text = builder
}
else -> {
view.text = view.context.getString(R.string.add_coupon_expire_date)
}
}
}
} | 33 | Kotlin | 0 | 8 | dcd6324f1c313a2af05b328ea21673b096caca51 | 1,487 | 21st-Android-Team-1-Android | Apache License 2.0 |
ui-design-lib/src/main/java/co/electriccoin/zcash/ui/design/component/CommonTag.kt | Electric-Coin-Company | 390,808,594 | false | {"Kotlin": 811780} | package co.electriccoin.zcash.ui.design.component
object CommonTag {
const val CHIP_LAYOUT = "chip_layout"
const val CHIP = "chip"
}
| 159 | Kotlin | 10 | 15 | ff0757b818bffa868d65d1bd82f2a2730839a295 | 142 | zashi-android | MIT License |
Flower/src/main/java/com/hadiyarajesh/flower/NetworkBoundResource.kt | hadiyarajesh | 271,244,717 | false | null | package com.hadiyarajesh.flower
import kotlinx.coroutines.flow.*
/**
* It will handle performing network request, getting result of it and caching it to local database
* @param fetchFromLocal - Retrieve data from local database
* @param shouldFetchFromRemote - Whether or not make network request
* @param fetchFromRemote - Retrieve data from network request
* @param processRemoteResponse - process result of network request (e.g., save response headers)
* @param saveRemoteData - Save result of network request
* @param onFetchFailed - Perform action when network request fails
*/
inline fun <DB, REMOTE> networkBoundResource(
crossinline fetchFromLocal: suspend () -> Flow<DB>,
crossinline shouldFetchFromRemote: suspend (DB?) -> Boolean = { true },
crossinline fetchFromRemote: suspend () -> Flow<ApiResponse<REMOTE>>,
crossinline processRemoteResponse: (response: ApiSuccessResponse<REMOTE>) -> Unit = { },
crossinline saveRemoteData: suspend (REMOTE) -> Unit = { },
crossinline onFetchFailed: (errorBody: String?, statusCode: Int) -> Unit = { _: String?, _: Int -> }
) = flow<Resource<DB>> {
emit(Resource.loading(null))
val localData = fetchFromLocal().first()
if (shouldFetchFromRemote(localData)) {
emit(Resource.loading(localData))
fetchFromRemote().collect { apiResponse ->
when (apiResponse) {
is ApiSuccessResponse -> {
processRemoteResponse(apiResponse)
apiResponse.body?.let { saveRemoteData(it) }
emitAll(fetchFromLocal().map { dbData ->
Resource.success(dbData)
})
}
is ApiErrorResponse -> {
onFetchFailed(apiResponse.errorMessage, apiResponse.statusCode)
emitAll(fetchFromLocal().map { dbData ->
Resource.error(
apiResponse.errorMessage,
dbData
)
})
}
is ApiEmptyResponse -> {
emit(Resource.success(null))
}
}
}
} else {
emitAll(fetchFromLocal().map { Resource.success(it) })
}
} | 1 | null | 15 | 131 | b46ae05bdc16f8c18f3ce97b6d7cc1344e3356d7 | 2,292 | flower | MIT License |
modules/remote/src/main/java/kr/co/knowledgerally/remote/model/ScheduleRequest.kt | YAPP-Github | 475,728,173 | false | {"Kotlin": 454888} | package kr.co.knowledgerally.remote.model
import com.google.gson.annotations.SerializedName
import kr.co.knowledgerally.data.model.ScheduleEntity
import java.time.LocalDateTime
data class ScheduleRequest(
@SerializedName("startAt")
val startAt: LocalDateTime,
@SerializedName("endAt")
val endAt: LocalDateTime,
)
internal fun ScheduleEntity.toRemote() = ScheduleRequest(
startAt = startAt,
endAt = endAt,
)
| 2 | Kotlin | 1 | 4 | 01db68b42594360a9285af458eb812ad83acef70 | 434 | 20th-ALL-Rounder-Team-2-Android | Apache License 2.0 |
core/src/com/mo/stratego/ui/controller/FieldController.kt | GPla | 217,608,618 | false | null | package com.mo.stratego.ui.controller
import com.badlogic.ashley.core.ComponentMapper
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.EntityListener
import com.badlogic.ashley.core.PooledEngine
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.Stage
import com.mo.stratego.model.HighlightType
import com.mo.stratego.model.Piece
import com.mo.stratego.model.component.HighlightComponent
import com.mo.stratego.ui.FieldActor
import com.mo.stratego.ui.input.HighlightInputListener
import com.mo.stratego.ui.input.PieceInputListener
/**
* Singleton class that controls the Actor's displayed on the Stage.
* Implements EntityListener to add a [FieldActor]'s to the Stage if
* a [Piece] or [HighlightComponent] is added to the Engine.
*/
object FieldController : EntityListener {
lateinit var stage: Stage
private lateinit var engine: PooledEngine
private val highMapper =
ComponentMapper.getFor(HighlightComponent::class.java)
private val entityActors: HashMap<Entity, Actor> = HashMap()
/**
* Init the object with this method. If not called before usage
* an error will be thrown.
* @param stage Stage
* @param engine PooledEngines
* @return This for chaining.
*/
fun init(stage: Stage, engine: PooledEngine): FieldController {
FieldController.stage = stage
FieldController.engine = engine
return this
}
/**
* Added an [FieldActor] for [Piece] instances and entities with a
* [HighlightComponent].
* @param entity
*/
override fun entityAdded(entity: Entity?) {
if (entity == null)
return
val highlight = highMapper.get(entity)
if (entity is Piece) {
FieldActor(entity).also {
entityActors[entity] = it
stage.addActor(it)
it.addListener(PieceInputListener(entity,
engine))
}
} else if (highlight != null && highlight.type == HighlightType.CIRCLE) {
FieldActor(entity).also {
entityActors[entity] = it
stage.addActor(it)
it.addListener(HighlightInputListener(entity,
engine))
}
}
}
/**
* Removes the actor that corresponds to the entity
* @param entity
*/
override fun entityRemoved(entity: Entity?) {
if (entityActors.containsKey(entity ?: return)) {
val actor = entityActors.remove(entity)
actor?.remove()
}
}
} | 1 | Kotlin | 1 | 1 | bfcde4983771f6eabfd3060278424549d379dccf | 2,670 | Stratego | MIT License |
src/main/kotlin/quiz/exception/QuizException4.kt | gdg-minsk | 793,403,177 | false | {"Kotlin": 47893} | package quiz.exception
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.supervisorScope
fun main(): Unit = runBlocking {
supervisorScope {
launch {
launch {
delay(500L)
throw Error("Some error")
}
delay(700L)
println("A")
}
launch {
delay(1000)
println("B")
}
}
delay(1000)
println("C")
}
| 0 | Kotlin | 0 | 0 | e2064be3ac4a39a00a369f43be002b4b974fa6ab | 526 | coffe-code-kotlin-coroutines | Apache License 2.0 |
app/src/main/java/com/sample/neuroid/us/constants/NIDGlobalConstants.kt | Neuro-ID | 433,158,128 | false | {"Kotlin": 339612, "JavaScript": 1588, "Shell": 831, "HTML": 755} | package com.sample.neuroid.us.constants
const val NID_GO_TO_SECOND_FRAG = 0x01
const val NID_GO_TO_THIRD_FRAG = 0x02
const val NID_FINISH_ACTIVITY = 0x03
| 2 | Kotlin | 3 | 2 | f0e6d5328dae8a3c45832cd9328604b93c4df3e8 | 155 | neuroid-android-sdk | MIT License |
app/src/main/java/com/pawelsalata/shoppinglist/ui/base/BaseViewModel.kt | PawelSalata | 115,709,103 | false | null | package com.pawelsalata.shoppinglist.ui.base
import android.arch.lifecycle.ViewModel
import com.pawelsalata.shoppinglist.data.DataManager
import io.reactivex.disposables.CompositeDisposable
/**
* Created by LETTUCE on 17.01.2018.
*/
abstract class BaseViewModel<N>(protected val dataManager: DataManager) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
var navigator: N? = null
override fun onCleared() {
compositeDisposable.dispose()
super.onCleared()
}
} | 0 | Kotlin | 0 | 0 | 45b576b537bb7781b6a06ebf8be8f630b6f85f68 | 518 | and_shopping_list | Apache License 2.0 |
clion/src/main/kotlin/org/rust/clion/valgrind/legacy/RsValgrindRunnerLegacy.kt | intellij-rust | 42,619,487 | false | null | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.clion.valgrind.legacy
import com.intellij.execution.configurations.RunProfile
import com.intellij.openapi.util.NlsContexts
import org.rust.RsBundle
import org.rust.cargo.runconfig.buildtool.CargoBuildManager.isBuildToolWindowAvailable
import org.rust.cargo.runconfig.command.CargoCommandConfiguration
import org.rust.cargo.runconfig.legacy.RsAsyncRunner
import org.rust.clion.valgrind.RsValgrindConfigurationExtension
import org.rust.clion.valgrind.ValgrindExecutor
@NlsContexts.DialogTitle
private val ERROR_MESSAGE_TITLE: String = RsBundle.message("dialog.title.unable.to.run.valgrind")
/**
* This runner is used if [isBuildToolWindowAvailable] is false.
*/
class RsValgrindRunnerLegacy : RsAsyncRunner(ValgrindExecutor.EXECUTOR_ID, ERROR_MESSAGE_TITLE) {
override fun getRunnerId(): String = RUNNER_ID
override fun canRun(executorId: String, profile: RunProfile): Boolean {
if (profile !is CargoCommandConfiguration) return false
return RsValgrindConfigurationExtension.isEnabledFor(profile) && super.canRun(executorId, profile)
}
companion object {
const val RUNNER_ID: String = "RsValgrindRunnerLegacy"
}
}
| 1,846 | null | 391 | 4,528 | c6657c02bb62075bf7b7ceb84d000f93dda34dc1 | 1,288 | intellij-rust | MIT License |
KotlinFundamentals/GenericsObjectsExtensions/src/main/kotlin/Main.kt | alghe-global | 718,129,890 | false | {"Kotlin": 815485} | /**
* Not using generics.
*/
class FillInTheBlankQuestion(
val questionText: String,
val answer: String,
val difficulty: String
)
class TrueOrFalseQuestion(
val questionText: String,
val answer: Boolean,
val difficulty: String
)
class NumericQuestion(
val questionText: String,
val answer: Int,
val difficulty: String
)
/**
* Using generics.
*/
class SimpleQuestion<T>(
val questionText: String,
val answer: T,
val difficulty: String
)
/**
* Using generics and enum.
*/
enum class Difficulty {
EASY, MEDIUM, HARD
}
class EnumQuestion<T>(
val questionText: String,
val answer: T,
val difficulty: Difficulty
)
/**
* Data class.
*/
data class DataEnumQuestion<T>(
val questionText: String,
val answer: T,
val difficulty: Difficulty
)
/**
* Singleton object.
*/
object SimpleStudentProgress {
var total: Int = 10
var answered: Int = 3
}
/**
* Class with singleton object within.
*/
class Quiz {
val question10 = DataEnumQuestion<String>("Quoth the raven ___", "nevermore", Difficulty.MEDIUM)
val question11 = DataEnumQuestion<Boolean>(
"The sky is green. True or false",
false,
Difficulty.EASY
)
val question12 = DataEnumQuestion<Int>(
"How many days are there between full moons?",
28,
Difficulty.HARD
)
companion object StudentProgress {
var total: Int = 10
var answered: Int = 3
}
}
/**
* Extension property.
*/
val Quiz.StudentProgress.progressText: String
get() = "$answered of $total answered."
/**
* Extension function.
*/
fun Quiz.StudentProgress.printProgressBar() {
repeat(Quiz.answered) { print("▓") }
repeat(Quiz.total - Quiz.answered) { print("▒") }
println()
println(Quiz.progressText)
}
/**
* Interfaces.
*/
interface ProgressPrintable {
val progressText: String
fun printProgressBar()
}
class InterfaceQuiz : ProgressPrintable {
override val progressText: String
get() = "$answered of $total answered."
override fun printProgressBar() {
repeat(InterfaceQuiz.answered) { print("▓") }
repeat(InterfaceQuiz.total - InterfaceQuiz.answered) { print("▒") }
println()
println(progressText)
}
val question10 = DataEnumQuestion<String>("Quoth the raven ___", "nevermore", Difficulty.MEDIUM)
val question11 = DataEnumQuestion<Boolean>(
"The sky is green. True or false",
false,
Difficulty.EASY
)
val question12 = DataEnumQuestion<Int>(
"How many days are there between full moons?",
28,
Difficulty.HARD
)
companion object StudentProgress {
var total: Int = 10
var answered: Int = 3
}
}
/**
* Scope functions.
*/
class ScopeQuiz : ProgressPrintable {
override val progressText: String
get() = "$answered of $total answered."
override fun printProgressBar() {
repeat(InterfaceQuiz.answered) { print("▓") }
repeat(InterfaceQuiz.total - InterfaceQuiz.answered) { print("▒") }
println()
println(progressText)
}
fun printQuiz() {
question10.let {
println(it.questionText)
println(it.answer)
println(it.difficulty)
}
println()
question11.let {
println(it.questionText)
println(it.answer)
println(it.difficulty)
}
println()
question12.let {
println(it.questionText)
println(it.answer)
println(it.difficulty)
}
println()
}
val question10 = DataEnumQuestion<String>("Quoth the raven ___", "nevermore", Difficulty.MEDIUM)
val question11 = DataEnumQuestion<Boolean>(
"The sky is green. True or false",
false,
Difficulty.EASY
)
val question12 = DataEnumQuestion<Int>(
"How many days are there between full moons?",
28,
Difficulty.HARD
)
companion object StudentProgress {
var total: Int = 10
var answered: Int = 3
}
}
fun main() {
val question1 = SimpleQuestion<String>("Quoth the raven ___", "nevermore", "medium")
val question2 = SimpleQuestion<Boolean>("The sky is green. True or false", false, "easy")
val question3 = SimpleQuestion<Int>(
"How many days are there between full moons?",
28,
"hard"
)
val question4 = EnumQuestion<String>("Quoth the raven ___", "nevermore", Difficulty.MEDIUM)
val question5 = EnumQuestion<Boolean>(
"The sky is green. True or false",
false,
Difficulty.EASY
)
val question6 = EnumQuestion<Int>(
"How many days are there between full moons?",
28,
Difficulty.HARD
)
println(question4.toString()) // SimpleQuestion@eed1f14
val question7 = DataEnumQuestion<String>("Quoth the raven ___", "nevermore", Difficulty.MEDIUM)
val question8 = DataEnumQuestion<Boolean>(
"The sky is green. True or false",
false,
Difficulty.EASY
)
val question9 = DataEnumQuestion<Int>(
"How many days are there between full moons?",
28,
Difficulty.HARD
)
/**
* DataEnumQuestion(questionText=Quoth the raven ___, answer=nevermore, difficulty=MEDIUM)
*/
println(question7.toString())
println("\n****************************\n")
/**
* Accessing a singleton object.
*/
println("${SimpleStudentProgress.answered} of ${SimpleStudentProgress.total} answered.")
println("\n****************************\n")
/**
* Accessing a companion singleton object.
*/
println("${Quiz.answered} of ${Quiz.total} answered.")
println("\n****************************\n")
/**
* Extending classes with new properties and methods.
*/
println(Quiz.progressText)
Quiz.printProgressBar()
println("\n****************************\n")
/**
* Calling method within class that extends an interface.
*/
InterfaceQuiz().printProgressBar()
println("\n****************************\n")
/**
* Scope functions.
*/
val quiz = ScopeQuiz()
quiz.printQuiz()
println("\n****************************\n")
/**
* Call an object's methods without a variable using apply()
*/
ScopeQuiz().apply {
printQuiz()
}
} | 0 | Kotlin | 0 | 0 | 0b4576f34894d57fe37592a5a6be74a0319b4395 | 6,439 | Kotlin | MIT License |
core/src/main/kotlin/com/thomasgorke/storagesolution/core/utils/Helper.kt | ThomasGorke | 346,712,689 | false | null | package com.thomasgorke.storagesolution.core.utils
| 0 | Kotlin | 0 | 0 | 6bf5fd05b7b70a11f5797c0cb7c2975fe7cd6c19 | 52 | StorageSolutions | Apache License 2.0 |
feature/note/src/main/java/com/example/feature/note/screen/shop/ShopListViewModel.kt | llsit | 827,324,299 | false | {"Kotlin": 296104} | package com.example.feature.note.screen.shop
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.core.common.utils.UiState
import com.example.core.data.utils.DataStoreManager
import com.example.core.domain.usecase.note.AddShopUseCase
import com.example.core.domain.usecase.note.DeleteItemUseCase
import com.example.core.domain.usecase.note.DeleteShopUseCase
import com.example.core.domain.usecase.note.GetItemByIdUseCase
import com.example.core.domain.usecase.note.GetShopUseCase
import com.example.core.domain.usecase.note.UpdateShopUseCase
import com.example.core.model.data.ItemModel
import com.example.core.model.data.ShopModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class ShopListViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val addShopUseCase: AddShopUseCase,
private val getShopUseCase: GetShopUseCase,
private val deleteShopUseCase: DeleteShopUseCase,
private val deleteItemUseCase: DeleteItemUseCase,
private val updateShopUseCase: UpdateShopUseCase,
private val getItemByIdUseCase: GetItemByIdUseCase,
private val dataStoreManager: DataStoreManager
) : ViewModel() {
private val itemId = savedStateHandle.get<String>("id") ?: ""
private val _uiStateShop = MutableStateFlow<UiState<Unit>>(UiState.Idle)
val uiStateShop: StateFlow<UiState<Unit>> = _uiStateShop.asStateFlow()
private val _uiStateGetShop = MutableStateFlow<UiState<List<ShopModel>>>(UiState.Idle)
val uiStateGetShop: StateFlow<UiState<List<ShopModel>>> = _uiStateGetShop.asStateFlow()
private val _nameState = MutableStateFlow("")
val nameState: StateFlow<String> = _nameState.asStateFlow()
private val _locationState = MutableStateFlow("")
val locationState: StateFlow<String> = _locationState.asStateFlow()
private val _priceState = MutableStateFlow("")
val priceState: StateFlow<String> = _priceState.asStateFlow()
private val _deleteItemState = MutableStateFlow<UiState<Unit>>(UiState.Idle)
val deleteItemState: StateFlow<UiState<Unit>> = _deleteItemState.asStateFlow()
private val _selectedItem = MutableStateFlow<ItemModel?>(null)
val selectedItem: StateFlow<ItemModel?> = _selectedItem.asStateFlow()
var name by mutableStateOf("")
private set
var location by mutableStateOf("")
private set
var price by mutableStateOf("")
private set
init {
getItemById()
getShop()
}
fun updateName(input: String) {
name = input
}
fun updateLocation(input: String) {
location = input
}
fun updatePrice(input: String) {
price = input
}
fun addShop() {
checkError()
if (name.isNotEmpty() && location.isNotEmpty() && price.isNotEmpty() && price.toDouble() >= 0) {
submitShopData()
}
}
fun updateShop(shopModel: ShopModel?) {
checkError()
if (name.isNotEmpty() && location.isNotEmpty() && price.isNotEmpty() && price.toDouble() >= 0 && shopModel != null) {
updateShopData(shopModel)
}
}
private fun updateShopData(shopModel: ShopModel) = viewModelScope.launch {
val newModel = shopModel.copy(
name = name,
location = location,
price = price.ifEmpty { "0.0" }.toDouble()
)
updateShopUseCase.updateShop(itemId, newModel)
.onStart { _uiStateShop.value = UiState.Loading }
.collect {
when (it) {
is UiState.Error -> {
_uiStateShop.value = UiState.Error(it.message)
}
UiState.Idle -> Unit
UiState.Loading -> _uiStateShop.value = UiState.Loading
is UiState.Success -> {
_uiStateShop.value = UiState.Success(it.data)
}
}
}
}
private fun submitShopData() {
viewModelScope.launch {
addShopUseCase.addShop(name, location, price, itemId)
.onStart { _uiStateShop.value = UiState.Loading }
.collect {
when (it) {
is UiState.Error -> {
_uiStateShop.value = UiState.Error(it.message)
}
UiState.Idle -> Unit
UiState.Loading -> _uiStateShop.value = UiState.Loading
is UiState.Success -> {
_uiStateShop.value = UiState.Success(it.data)
}
}
}
}
}
fun getItemById() = viewModelScope.launch {
getItemByIdUseCase.getItemById(itemId).collect {
when (it) {
is UiState.Error -> {
_selectedItem.value = null
}
is UiState.Success -> {
_selectedItem.value = it.data
}
else -> Unit
}
}
}
fun getShop() = viewModelScope.launch {
getShopUseCase.getShop(itemId).collect {
when (it) {
is UiState.Error -> {
_uiStateGetShop.value = UiState.Error(it.message)
}
UiState.Idle -> Unit
UiState.Loading -> _uiStateGetShop.value = UiState.Loading
is UiState.Success -> {
_uiStateGetShop.value = UiState.Success(it.data)
}
}
}
}
fun deleteShop(shopId: String, itemId: String) = viewModelScope.launch {
deleteShopUseCase.deleteShop(itemId, shopId)
.onStart { _uiStateGetShop.value = UiState.Loading }
.collect {
when (it) {
is UiState.Success -> getShop()
else -> Unit
}
}
}
fun deleteItem(itemId: String) = viewModelScope.launch {
deleteItemUseCase.deleteItem(itemId).collect {
when (it) {
is UiState.Success -> _deleteItemState.value = UiState.Success(it.data)
else -> Unit
}
}
}
fun clearState() {
_uiStateShop.value = UiState.Idle
_nameState.value = ""
_locationState.value = ""
_priceState.value = ""
name = ""
location = ""
price = ""
}
fun setUpdate(model: ShopModel) {
name = model.name
location = model.location
price = model.price.toString()
}
private fun checkError() {
if (name.isEmpty()) {
_nameState.value = "Name cannot be empty"
} else {
_nameState.value = ""
}
if (location.isEmpty()) {
_locationState.value = "Location cannot be empty"
} else {
_locationState.value = ""
}
if (price.isEmpty() || price.toDouble() < 0) {
_priceState.value = "Price cannot be lower than 0"
} else {
_priceState.value = ""
}
}
fun clearSelectedItem() = viewModelScope.launch {
dataStoreManager.clearItemModel()
}
}
| 0 | Kotlin | 0 | 0 | b31cdbad5242be35e03488e69827c8faef87db02 | 7,702 | ItemNote | MIT License |
app/src/main/java/dog/snow/androidrecruittest/repository/model/RawPhoto.kt | Bartusiak | 244,751,094 | false | null | package dog.snow.androidrecruittest.repository.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class RawPhoto(
val id: Int,
val albumId: Int,
val title: String,
val url: String,
val thumbnailUrl: String,
var album : RawAlbum
) : Parcelable | 0 | null | 0 | 1 | 21e95fa974847bc58221215ed042e685b995a675 | 309 | android-recruitment-test | Apache License 2.0 |
increase-kotlin-core/src/main/kotlin/com/increase/api/models/AchTransferCreateParams.kt | Increase | 614,596,742 | false | {"Kotlin": 15608744, "Shell": 1257, "Dockerfile": 305} | package com.increase.api.models
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonAnySetter
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.increase.api.core.ExcludeMissing
import com.increase.api.core.JsonField
import com.increase.api.core.JsonValue
import com.increase.api.core.NoAutoDetect
import com.increase.api.core.toUnmodifiable
import com.increase.api.errors.IncreaseInvalidDataException
import com.increase.api.models.*
import java.time.LocalDate
import java.util.Objects
import java.util.Optional
class AchTransferCreateParams
constructor(
private val accountId: String,
private val accountNumber: String?,
private val addendum: String?,
private val amount: Long,
private val companyDescriptiveDate: String?,
private val companyDiscretionaryData: String?,
private val companyEntryDescription: String?,
private val companyName: String?,
private val effectiveDate: LocalDate?,
private val externalAccountId: String?,
private val funding: Funding?,
private val individualId: String?,
private val individualName: String?,
private val requireApproval: Boolean?,
private val routingNumber: String?,
private val standardEntryClassCode: StandardEntryClassCode?,
private val statementDescriptor: String,
private val additionalQueryParams: Map<String, List<String>>,
private val additionalHeaders: Map<String, List<String>>,
private val additionalBodyProperties: Map<String, JsonValue>,
) {
fun accountId(): String = accountId
fun accountNumber(): Optional<String> = Optional.ofNullable(accountNumber)
fun addendum(): Optional<String> = Optional.ofNullable(addendum)
fun amount(): Long = amount
fun companyDescriptiveDate(): Optional<String> = Optional.ofNullable(companyDescriptiveDate)
fun companyDiscretionaryData(): Optional<String> = Optional.ofNullable(companyDiscretionaryData)
fun companyEntryDescription(): Optional<String> = Optional.ofNullable(companyEntryDescription)
fun companyName(): Optional<String> = Optional.ofNullable(companyName)
fun effectiveDate(): Optional<LocalDate> = Optional.ofNullable(effectiveDate)
fun externalAccountId(): Optional<String> = Optional.ofNullable(externalAccountId)
fun funding(): Optional<Funding> = Optional.ofNullable(funding)
fun individualId(): Optional<String> = Optional.ofNullable(individualId)
fun individualName(): Optional<String> = Optional.ofNullable(individualName)
fun requireApproval(): Optional<Boolean> = Optional.ofNullable(requireApproval)
fun routingNumber(): Optional<String> = Optional.ofNullable(routingNumber)
fun standardEntryClassCode(): Optional<StandardEntryClassCode> =
Optional.ofNullable(standardEntryClassCode)
fun statementDescriptor(): String = statementDescriptor
@JvmSynthetic
internal fun getBody(): AchTransferCreateBody {
return AchTransferCreateBody(
accountId,
accountNumber,
addendum,
amount,
companyDescriptiveDate,
companyDiscretionaryData,
companyEntryDescription,
companyName,
effectiveDate,
externalAccountId,
funding,
individualId,
individualName,
requireApproval,
routingNumber,
standardEntryClassCode,
statementDescriptor,
additionalBodyProperties,
)
}
@JvmSynthetic internal fun getQueryParams(): Map<String, List<String>> = additionalQueryParams
@JvmSynthetic internal fun getHeaders(): Map<String, List<String>> = additionalHeaders
@JsonDeserialize(builder = AchTransferCreateBody.Builder::class)
@NoAutoDetect
class AchTransferCreateBody
internal constructor(
private val accountId: String?,
private val accountNumber: String?,
private val addendum: String?,
private val amount: Long?,
private val companyDescriptiveDate: String?,
private val companyDiscretionaryData: String?,
private val companyEntryDescription: String?,
private val companyName: String?,
private val effectiveDate: LocalDate?,
private val externalAccountId: String?,
private val funding: Funding?,
private val individualId: String?,
private val individualName: String?,
private val requireApproval: Boolean?,
private val routingNumber: String?,
private val standardEntryClassCode: StandardEntryClassCode?,
private val statementDescriptor: String?,
private val additionalProperties: Map<String, JsonValue>,
) {
private var hashCode: Int = 0
/** The Increase identifier for the account that will send the transfer. */
@JsonProperty("account_id") fun accountId(): String? = accountId
/** The account number for the destination account. */
@JsonProperty("account_number") fun accountNumber(): String? = accountNumber
/**
* Additional information that will be sent to the recipient. This is included in the
* transfer data sent to the receiving bank.
*/
@JsonProperty("addendum") fun addendum(): String? = addendum
/**
* The transfer amount in cents. A positive amount originates a credit transfer pushing
* funds to the receiving account. A negative amount originates a debit transfer pulling
* funds from the receiving account.
*/
@JsonProperty("amount") fun amount(): Long? = amount
/**
* The description of the date of the transfer, usually in the format `YYMMDD`. This is
* included in the transfer data sent to the receiving bank.
*/
@JsonProperty("company_descriptive_date")
fun companyDescriptiveDate(): String? = companyDescriptiveDate
/**
* The data you choose to associate with the transfer. This is included in the transfer data
* sent to the receiving bank.
*/
@JsonProperty("company_discretionary_data")
fun companyDiscretionaryData(): String? = companyDiscretionaryData
/**
* A description of the transfer. This is included in the transfer data sent to the
* receiving bank.
*/
@JsonProperty("company_entry_description")
fun companyEntryDescription(): String? = companyEntryDescription
/**
* The name by which the recipient knows you. This is included in the transfer data sent to
* the receiving bank.
*/
@JsonProperty("company_name") fun companyName(): String? = companyName
/**
* The transfer effective date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format.
*/
@JsonProperty("effective_date") fun effectiveDate(): LocalDate? = effectiveDate
/**
* The ID of an External Account to initiate a transfer to. If this parameter is provided,
* `account_number`, `routing_number`, and `funding` must be absent.
*/
@JsonProperty("external_account_id") fun externalAccountId(): String? = externalAccountId
/** The type of the account to which the transfer will be sent. */
@JsonProperty("funding") fun funding(): Funding? = funding
/** Your identifer for the transfer recipient. */
@JsonProperty("individual_id") fun individualId(): String? = individualId
/**
* The name of the transfer recipient. This value is informational and not verified by the
* recipient's bank.
*/
@JsonProperty("individual_name") fun individualName(): String? = individualName
/** Whether the transfer requires explicit approval via the dashboard or API. */
@JsonProperty("require_approval") fun requireApproval(): Boolean? = requireApproval
/**
* The American Bankers' Association (ABA) Routing Transit Number (RTN) for the destination
* account.
*/
@JsonProperty("routing_number") fun routingNumber(): String? = routingNumber
/** The Standard Entry Class (SEC) code to use for the transfer. */
@JsonProperty("standard_entry_class_code")
fun standardEntryClassCode(): StandardEntryClassCode? = standardEntryClassCode
/**
* A description you choose to give the transfer. This will be saved with the transfer
* details, displayed in the dashboard, and returned by the API. If `individual_name` and
* `company_name` are not explicitly set by this API, the `statement_descriptor` will be
* sent in those fields to the receiving bank to help the customer recognize the transfer.
* You are highly encouraged to pass `individual_name` and `company_name` instead of relying
* on this fallback.
*/
@JsonProperty("statement_descriptor")
fun statementDescriptor(): String? = statementDescriptor
@JsonAnyGetter
@ExcludeMissing
fun _additionalProperties(): Map<String, JsonValue> = additionalProperties
fun toBuilder() = Builder().from(this)
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is AchTransferCreateBody &&
this.accountId == other.accountId &&
this.accountNumber == other.accountNumber &&
this.addendum == other.addendum &&
this.amount == other.amount &&
this.companyDescriptiveDate == other.companyDescriptiveDate &&
this.companyDiscretionaryData == other.companyDiscretionaryData &&
this.companyEntryDescription == other.companyEntryDescription &&
this.companyName == other.companyName &&
this.effectiveDate == other.effectiveDate &&
this.externalAccountId == other.externalAccountId &&
this.funding == other.funding &&
this.individualId == other.individualId &&
this.individualName == other.individualName &&
this.requireApproval == other.requireApproval &&
this.routingNumber == other.routingNumber &&
this.standardEntryClassCode == other.standardEntryClassCode &&
this.statementDescriptor == other.statementDescriptor &&
this.additionalProperties == other.additionalProperties
}
override fun hashCode(): Int {
if (hashCode == 0) {
hashCode =
Objects.hash(
accountId,
accountNumber,
addendum,
amount,
companyDescriptiveDate,
companyDiscretionaryData,
companyEntryDescription,
companyName,
effectiveDate,
externalAccountId,
funding,
individualId,
individualName,
requireApproval,
routingNumber,
standardEntryClassCode,
statementDescriptor,
additionalProperties,
)
}
return hashCode
}
override fun toString() =
"AchTransferCreateBody{accountId=$accountId, accountNumber=$accountNumber, addendum=$addendum, amount=$amount, companyDescriptiveDate=$companyDescriptiveDate, companyDiscretionaryData=$companyDiscretionaryData, companyEntryDescription=$companyEntryDescription, companyName=$companyName, effectiveDate=$effectiveDate, externalAccountId=$externalAccountId, funding=$funding, individualId=$individualId, individualName=$individualName, requireApproval=$requireApproval, routingNumber=$routingNumber, standardEntryClassCode=$standardEntryClassCode, statementDescriptor=$statementDescriptor, additionalProperties=$additionalProperties}"
companion object {
@JvmStatic fun builder() = Builder()
}
class Builder {
private var accountId: String? = null
private var accountNumber: String? = null
private var addendum: String? = null
private var amount: Long? = null
private var companyDescriptiveDate: String? = null
private var companyDiscretionaryData: String? = null
private var companyEntryDescription: String? = null
private var companyName: String? = null
private var effectiveDate: LocalDate? = null
private var externalAccountId: String? = null
private var funding: Funding? = null
private var individualId: String? = null
private var individualName: String? = null
private var requireApproval: Boolean? = null
private var routingNumber: String? = null
private var standardEntryClassCode: StandardEntryClassCode? = null
private var statementDescriptor: String? = null
private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()
@JvmSynthetic
internal fun from(achTransferCreateBody: AchTransferCreateBody) = apply {
this.accountId = achTransferCreateBody.accountId
this.accountNumber = achTransferCreateBody.accountNumber
this.addendum = achTransferCreateBody.addendum
this.amount = achTransferCreateBody.amount
this.companyDescriptiveDate = achTransferCreateBody.companyDescriptiveDate
this.companyDiscretionaryData = achTransferCreateBody.companyDiscretionaryData
this.companyEntryDescription = achTransferCreateBody.companyEntryDescription
this.companyName = achTransferCreateBody.companyName
this.effectiveDate = achTransferCreateBody.effectiveDate
this.externalAccountId = achTransferCreateBody.externalAccountId
this.funding = achTransferCreateBody.funding
this.individualId = achTransferCreateBody.individualId
this.individualName = achTransferCreateBody.individualName
this.requireApproval = achTransferCreateBody.requireApproval
this.routingNumber = achTransferCreateBody.routingNumber
this.standardEntryClassCode = achTransferCreateBody.standardEntryClassCode
this.statementDescriptor = achTransferCreateBody.statementDescriptor
additionalProperties(achTransferCreateBody.additionalProperties)
}
/** The Increase identifier for the account that will send the transfer. */
@JsonProperty("account_id")
fun accountId(accountId: String) = apply { this.accountId = accountId }
/** The account number for the destination account. */
@JsonProperty("account_number")
fun accountNumber(accountNumber: String) = apply { this.accountNumber = accountNumber }
/**
* Additional information that will be sent to the recipient. This is included in the
* transfer data sent to the receiving bank.
*/
@JsonProperty("addendum")
fun addendum(addendum: String) = apply { this.addendum = addendum }
/**
* The transfer amount in cents. A positive amount originates a credit transfer pushing
* funds to the receiving account. A negative amount originates a debit transfer pulling
* funds from the receiving account.
*/
@JsonProperty("amount") fun amount(amount: Long) = apply { this.amount = amount }
/**
* The description of the date of the transfer, usually in the format `YYMMDD`. This is
* included in the transfer data sent to the receiving bank.
*/
@JsonProperty("company_descriptive_date")
fun companyDescriptiveDate(companyDescriptiveDate: String) = apply {
this.companyDescriptiveDate = companyDescriptiveDate
}
/**
* The data you choose to associate with the transfer. This is included in the transfer
* data sent to the receiving bank.
*/
@JsonProperty("company_discretionary_data")
fun companyDiscretionaryData(companyDiscretionaryData: String) = apply {
this.companyDiscretionaryData = companyDiscretionaryData
}
/**
* A description of the transfer. This is included in the transfer data sent to the
* receiving bank.
*/
@JsonProperty("company_entry_description")
fun companyEntryDescription(companyEntryDescription: String) = apply {
this.companyEntryDescription = companyEntryDescription
}
/**
* The name by which the recipient knows you. This is included in the transfer data sent
* to the receiving bank.
*/
@JsonProperty("company_name")
fun companyName(companyName: String) = apply { this.companyName = companyName }
/**
* The transfer effective date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)
* format.
*/
@JsonProperty("effective_date")
fun effectiveDate(effectiveDate: LocalDate) = apply {
this.effectiveDate = effectiveDate
}
/**
* The ID of an External Account to initiate a transfer to. If this parameter is
* provided, `account_number`, `routing_number`, and `funding` must be absent.
*/
@JsonProperty("external_account_id")
fun externalAccountId(externalAccountId: String) = apply {
this.externalAccountId = externalAccountId
}
/** The type of the account to which the transfer will be sent. */
@JsonProperty("funding")
fun funding(funding: Funding) = apply { this.funding = funding }
/** Your identifer for the transfer recipient. */
@JsonProperty("individual_id")
fun individualId(individualId: String) = apply { this.individualId = individualId }
/**
* The name of the transfer recipient. This value is informational and not verified by
* the recipient's bank.
*/
@JsonProperty("individual_name")
fun individualName(individualName: String) = apply {
this.individualName = individualName
}
/** Whether the transfer requires explicit approval via the dashboard or API. */
@JsonProperty("require_approval")
fun requireApproval(requireApproval: Boolean) = apply {
this.requireApproval = requireApproval
}
/**
* The American Bankers' Association (ABA) Routing Transit Number (RTN) for the
* destination account.
*/
@JsonProperty("routing_number")
fun routingNumber(routingNumber: String) = apply { this.routingNumber = routingNumber }
/** The Standard Entry Class (SEC) code to use for the transfer. */
@JsonProperty("standard_entry_class_code")
fun standardEntryClassCode(standardEntryClassCode: StandardEntryClassCode) = apply {
this.standardEntryClassCode = standardEntryClassCode
}
/**
* A description you choose to give the transfer. This will be saved with the transfer
* details, displayed in the dashboard, and returned by the API. If `individual_name`
* and `company_name` are not explicitly set by this API, the `statement_descriptor`
* will be sent in those fields to the receiving bank to help the customer recognize the
* transfer. You are highly encouraged to pass `individual_name` and `company_name`
* instead of relying on this fallback.
*/
@JsonProperty("statement_descriptor")
fun statementDescriptor(statementDescriptor: String) = apply {
this.statementDescriptor = statementDescriptor
}
fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
this.additionalProperties.clear()
this.additionalProperties.putAll(additionalProperties)
}
@JsonAnySetter
fun putAdditionalProperty(key: String, value: JsonValue) = apply {
this.additionalProperties.put(key, value)
}
fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
this.additionalProperties.putAll(additionalProperties)
}
fun build(): AchTransferCreateBody =
AchTransferCreateBody(
checkNotNull(accountId) { "`accountId` is required but was not set" },
accountNumber,
addendum,
checkNotNull(amount) { "`amount` is required but was not set" },
companyDescriptiveDate,
companyDiscretionaryData,
companyEntryDescription,
companyName,
effectiveDate,
externalAccountId,
funding,
individualId,
individualName,
requireApproval,
routingNumber,
standardEntryClassCode,
checkNotNull(statementDescriptor) {
"`statementDescriptor` is required but was not set"
},
additionalProperties.toUnmodifiable(),
)
}
}
fun _additionalQueryParams(): Map<String, List<String>> = additionalQueryParams
fun _additionalHeaders(): Map<String, List<String>> = additionalHeaders
fun _additionalBodyProperties(): Map<String, JsonValue> = additionalBodyProperties
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is AchTransferCreateParams &&
this.accountId == other.accountId &&
this.accountNumber == other.accountNumber &&
this.addendum == other.addendum &&
this.amount == other.amount &&
this.companyDescriptiveDate == other.companyDescriptiveDate &&
this.companyDiscretionaryData == other.companyDiscretionaryData &&
this.companyEntryDescription == other.companyEntryDescription &&
this.companyName == other.companyName &&
this.effectiveDate == other.effectiveDate &&
this.externalAccountId == other.externalAccountId &&
this.funding == other.funding &&
this.individualId == other.individualId &&
this.individualName == other.individualName &&
this.requireApproval == other.requireApproval &&
this.routingNumber == other.routingNumber &&
this.standardEntryClassCode == other.standardEntryClassCode &&
this.statementDescriptor == other.statementDescriptor &&
this.additionalQueryParams == other.additionalQueryParams &&
this.additionalHeaders == other.additionalHeaders &&
this.additionalBodyProperties == other.additionalBodyProperties
}
override fun hashCode(): Int {
return Objects.hash(
accountId,
accountNumber,
addendum,
amount,
companyDescriptiveDate,
companyDiscretionaryData,
companyEntryDescription,
companyName,
effectiveDate,
externalAccountId,
funding,
individualId,
individualName,
requireApproval,
routingNumber,
standardEntryClassCode,
statementDescriptor,
additionalQueryParams,
additionalHeaders,
additionalBodyProperties,
)
}
override fun toString() =
"AchTransferCreateParams{accountId=$accountId, accountNumber=$accountNumber, addendum=$addendum, amount=$amount, companyDescriptiveDate=$companyDescriptiveDate, companyDiscretionaryData=$companyDiscretionaryData, companyEntryDescription=$companyEntryDescription, companyName=$companyName, effectiveDate=$effectiveDate, externalAccountId=$externalAccountId, funding=$funding, individualId=$individualId, individualName=$individualName, requireApproval=$requireApproval, routingNumber=$routingNumber, standardEntryClassCode=$standardEntryClassCode, statementDescriptor=$statementDescriptor, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}"
fun toBuilder() = Builder().from(this)
companion object {
@JvmStatic fun builder() = Builder()
}
@NoAutoDetect
class Builder {
private var accountId: String? = null
private var accountNumber: String? = null
private var addendum: String? = null
private var amount: Long? = null
private var companyDescriptiveDate: String? = null
private var companyDiscretionaryData: String? = null
private var companyEntryDescription: String? = null
private var companyName: String? = null
private var effectiveDate: LocalDate? = null
private var externalAccountId: String? = null
private var funding: Funding? = null
private var individualId: String? = null
private var individualName: String? = null
private var requireApproval: Boolean? = null
private var routingNumber: String? = null
private var standardEntryClassCode: StandardEntryClassCode? = null
private var statementDescriptor: String? = null
private var additionalQueryParams: MutableMap<String, MutableList<String>> = mutableMapOf()
private var additionalHeaders: MutableMap<String, MutableList<String>> = mutableMapOf()
private var additionalBodyProperties: MutableMap<String, JsonValue> = mutableMapOf()
@JvmSynthetic
internal fun from(achTransferCreateParams: AchTransferCreateParams) = apply {
this.accountId = achTransferCreateParams.accountId
this.accountNumber = achTransferCreateParams.accountNumber
this.addendum = achTransferCreateParams.addendum
this.amount = achTransferCreateParams.amount
this.companyDescriptiveDate = achTransferCreateParams.companyDescriptiveDate
this.companyDiscretionaryData = achTransferCreateParams.companyDiscretionaryData
this.companyEntryDescription = achTransferCreateParams.companyEntryDescription
this.companyName = achTransferCreateParams.companyName
this.effectiveDate = achTransferCreateParams.effectiveDate
this.externalAccountId = achTransferCreateParams.externalAccountId
this.funding = achTransferCreateParams.funding
this.individualId = achTransferCreateParams.individualId
this.individualName = achTransferCreateParams.individualName
this.requireApproval = achTransferCreateParams.requireApproval
this.routingNumber = achTransferCreateParams.routingNumber
this.standardEntryClassCode = achTransferCreateParams.standardEntryClassCode
this.statementDescriptor = achTransferCreateParams.statementDescriptor
additionalQueryParams(achTransferCreateParams.additionalQueryParams)
additionalHeaders(achTransferCreateParams.additionalHeaders)
additionalBodyProperties(achTransferCreateParams.additionalBodyProperties)
}
/** The Increase identifier for the account that will send the transfer. */
fun accountId(accountId: String) = apply { this.accountId = accountId }
/** The account number for the destination account. */
fun accountNumber(accountNumber: String) = apply { this.accountNumber = accountNumber }
/**
* Additional information that will be sent to the recipient. This is included in the
* transfer data sent to the receiving bank.
*/
fun addendum(addendum: String) = apply { this.addendum = addendum }
/**
* The transfer amount in cents. A positive amount originates a credit transfer pushing
* funds to the receiving account. A negative amount originates a debit transfer pulling
* funds from the receiving account.
*/
fun amount(amount: Long) = apply { this.amount = amount }
/**
* The description of the date of the transfer, usually in the format `YYMMDD`. This is
* included in the transfer data sent to the receiving bank.
*/
fun companyDescriptiveDate(companyDescriptiveDate: String) = apply {
this.companyDescriptiveDate = companyDescriptiveDate
}
/**
* The data you choose to associate with the transfer. This is included in the transfer data
* sent to the receiving bank.
*/
fun companyDiscretionaryData(companyDiscretionaryData: String) = apply {
this.companyDiscretionaryData = companyDiscretionaryData
}
/**
* A description of the transfer. This is included in the transfer data sent to the
* receiving bank.
*/
fun companyEntryDescription(companyEntryDescription: String) = apply {
this.companyEntryDescription = companyEntryDescription
}
/**
* The name by which the recipient knows you. This is included in the transfer data sent to
* the receiving bank.
*/
fun companyName(companyName: String) = apply { this.companyName = companyName }
/**
* The transfer effective date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format.
*/
fun effectiveDate(effectiveDate: LocalDate) = apply { this.effectiveDate = effectiveDate }
/**
* The ID of an External Account to initiate a transfer to. If this parameter is provided,
* `account_number`, `routing_number`, and `funding` must be absent.
*/
fun externalAccountId(externalAccountId: String) = apply {
this.externalAccountId = externalAccountId
}
/** The type of the account to which the transfer will be sent. */
fun funding(funding: Funding) = apply { this.funding = funding }
/** Your identifer for the transfer recipient. */
fun individualId(individualId: String) = apply { this.individualId = individualId }
/**
* The name of the transfer recipient. This value is informational and not verified by the
* recipient's bank.
*/
fun individualName(individualName: String) = apply { this.individualName = individualName }
/** Whether the transfer requires explicit approval via the dashboard or API. */
fun requireApproval(requireApproval: Boolean) = apply {
this.requireApproval = requireApproval
}
/**
* The American Bankers' Association (ABA) Routing Transit Number (RTN) for the destination
* account.
*/
fun routingNumber(routingNumber: String) = apply { this.routingNumber = routingNumber }
/** The Standard Entry Class (SEC) code to use for the transfer. */
fun standardEntryClassCode(standardEntryClassCode: StandardEntryClassCode) = apply {
this.standardEntryClassCode = standardEntryClassCode
}
/**
* A description you choose to give the transfer. This will be saved with the transfer
* details, displayed in the dashboard, and returned by the API. If `individual_name` and
* `company_name` are not explicitly set by this API, the `statement_descriptor` will be
* sent in those fields to the receiving bank to help the customer recognize the transfer.
* You are highly encouraged to pass `individual_name` and `company_name` instead of relying
* on this fallback.
*/
fun statementDescriptor(statementDescriptor: String) = apply {
this.statementDescriptor = statementDescriptor
}
fun additionalQueryParams(additionalQueryParams: Map<String, List<String>>) = apply {
this.additionalQueryParams.clear()
putAllQueryParams(additionalQueryParams)
}
fun putQueryParam(name: String, value: String) = apply {
this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value)
}
fun putQueryParams(name: String, values: Iterable<String>) = apply {
this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values)
}
fun putAllQueryParams(additionalQueryParams: Map<String, Iterable<String>>) = apply {
additionalQueryParams.forEach(this::putQueryParams)
}
fun removeQueryParam(name: String) = apply {
this.additionalQueryParams.put(name, mutableListOf())
}
fun additionalHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply {
this.additionalHeaders.clear()
putAllHeaders(additionalHeaders)
}
fun putHeader(name: String, value: String) = apply {
this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value)
}
fun putHeaders(name: String, values: Iterable<String>) = apply {
this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values)
}
fun putAllHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply {
additionalHeaders.forEach(this::putHeaders)
}
fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) }
fun additionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply {
this.additionalBodyProperties.clear()
this.additionalBodyProperties.putAll(additionalBodyProperties)
}
fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply {
this.additionalBodyProperties.put(key, value)
}
fun putAllAdditionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) =
apply {
this.additionalBodyProperties.putAll(additionalBodyProperties)
}
fun build(): AchTransferCreateParams =
AchTransferCreateParams(
checkNotNull(accountId) { "`accountId` is required but was not set" },
accountNumber,
addendum,
checkNotNull(amount) { "`amount` is required but was not set" },
companyDescriptiveDate,
companyDiscretionaryData,
companyEntryDescription,
companyName,
effectiveDate,
externalAccountId,
funding,
individualId,
individualName,
requireApproval,
routingNumber,
standardEntryClassCode,
checkNotNull(statementDescriptor) {
"`statementDescriptor` is required but was not set"
},
additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(),
additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(),
additionalBodyProperties.toUnmodifiable(),
)
}
class Funding
@JsonCreator
private constructor(
private val value: JsonField<String>,
) {
@com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is Funding && this.value == other.value
}
override fun hashCode() = value.hashCode()
override fun toString() = value.toString()
companion object {
@JvmField val CHECKING = Funding(JsonField.of("checking"))
@JvmField val SAVINGS = Funding(JsonField.of("savings"))
@JvmStatic fun of(value: String) = Funding(JsonField.of(value))
}
enum class Known {
CHECKING,
SAVINGS,
}
enum class Value {
CHECKING,
SAVINGS,
_UNKNOWN,
}
fun value(): Value =
when (this) {
CHECKING -> Value.CHECKING
SAVINGS -> Value.SAVINGS
else -> Value._UNKNOWN
}
fun known(): Known =
when (this) {
CHECKING -> Known.CHECKING
SAVINGS -> Known.SAVINGS
else -> throw IncreaseInvalidDataException("Unknown Funding: $value")
}
fun asString(): String = _value().asStringOrThrow()
}
class StandardEntryClassCode
@JsonCreator
private constructor(
private val value: JsonField<String>,
) {
@com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
return other is StandardEntryClassCode && this.value == other.value
}
override fun hashCode() = value.hashCode()
override fun toString() = value.toString()
companion object {
@JvmField
val CORPORATE_CREDIT_OR_DEBIT =
StandardEntryClassCode(JsonField.of("corporate_credit_or_debit"))
@JvmField
val PREARRANGED_PAYMENTS_AND_DEPOSIT =
StandardEntryClassCode(JsonField.of("prearranged_payments_and_deposit"))
@JvmField
val INTERNET_INITIATED = StandardEntryClassCode(JsonField.of("internet_initiated"))
@JvmStatic fun of(value: String) = StandardEntryClassCode(JsonField.of(value))
}
enum class Known {
CORPORATE_CREDIT_OR_DEBIT,
PREARRANGED_PAYMENTS_AND_DEPOSIT,
INTERNET_INITIATED,
}
enum class Value {
CORPORATE_CREDIT_OR_DEBIT,
PREARRANGED_PAYMENTS_AND_DEPOSIT,
INTERNET_INITIATED,
_UNKNOWN,
}
fun value(): Value =
when (this) {
CORPORATE_CREDIT_OR_DEBIT -> Value.CORPORATE_CREDIT_OR_DEBIT
PREARRANGED_PAYMENTS_AND_DEPOSIT -> Value.PREARRANGED_PAYMENTS_AND_DEPOSIT
INTERNET_INITIATED -> Value.INTERNET_INITIATED
else -> Value._UNKNOWN
}
fun known(): Known =
when (this) {
CORPORATE_CREDIT_OR_DEBIT -> Known.CORPORATE_CREDIT_OR_DEBIT
PREARRANGED_PAYMENTS_AND_DEPOSIT -> Known.PREARRANGED_PAYMENTS_AND_DEPOSIT
INTERNET_INITIATED -> Known.INTERNET_INITIATED
else -> throw IncreaseInvalidDataException("Unknown StandardEntryClassCode: $value")
}
fun asString(): String = _value().asStringOrThrow()
}
}
| 1 | Kotlin | 0 | 2 | 496494b0adf5480bab91f61b7a6decbfe3a129fa | 40,146 | increase-kotlin | Apache License 2.0 |
src/me/anno/ecs/components/player/Player.kt | AntonioNoack | 456,513,348 | false | null | package me.anno.ecs.components.player
import me.anno.ecs.Component
import me.anno.ecs.components.camera.CameraState
import me.anno.ecs.prefab.PrefabSaveable
import me.anno.io.Saveable
import me.anno.io.base.BaseWriter
import me.anno.io.utils.StringMap
// a special component, which can be added to one entity only? idk...
// multiple roots? this sounds like a kind-of-solution :)
open class Player : Component() {
val cameraState = CameraState()
// todo save all kind of information here
val sessionInfo = StringMap()
// todo needs to be saved every once in a while, preferably onSave ;)
val persistentInfo = StringMap()
override fun save(writer: BaseWriter) {
super.save(writer)
// writer.writeMap("session", sessionInfo)
writer.writeObject(null, "persistent", persistentInfo)
}
override fun setProperty(name: String, value: Any?) {
when (name) {
"persistent" -> {
if (value !is StringMap) return
persistentInfo.clear()
persistentInfo.putAll(value)
}
else -> super.setProperty(name, value)
}
}
override fun copyInto(dst: PrefabSaveable) {
super.copyInto(dst)
dst as Player
cameraState.copyInto(dst.cameraState)
dst.sessionInfo.clear()
dst.sessionInfo.putAll(sessionInfo)
dst.persistentInfo.clear()
dst.persistentInfo.putAll(persistentInfo)
}
} | 0 | null | 3 | 9 | b2532f7d40527eb2c9e24e3659dd904aa725a1aa | 1,477 | RemsEngine | Apache License 2.0 |
app/src/test/java/com/akshay/roomaccounting/dao/FakeDatabaseHelperImpl.kt | anandwana001 | 470,781,738 | false | {"Kotlin": 185228} | /**
* Created by anandwana001 on
* 02, March, 2022
**/
package com.akshay.roomaccounting.dao
import com.akshay.roomaccounting.data.dao.InvoiceDao
import com.akshay.roomaccounting.data.helper.DatabaseHelper
import com.akshay.roomaccounting.data.model.Invoice
import com.akshay.roomaccounting.data.model.MinimalInvoice
import com.akshay.roomaccounting.data.model.StatusInvoice
import com.akshay.roomaccounting.data.model.UpdateInvoiceStatus
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
/**
* Fake DatabaseHelperImpl for unit tests.
*/
class FakeDatabaseHelperImpl @Inject constructor(
private val invoiceDao: InvoiceDao
) : DatabaseHelper {
override fun getAllMinimalInvoices(): Flow<List<MinimalInvoice>> =
invoiceDao.getAllMinimalInvoices()
override fun getInvoiceById(id: String): Flow<Invoice?> =
invoiceDao.getInvoice(id)
override suspend fun deleteInvoiceById(id: String) =
invoiceDao.deleteInvoice(id)
override suspend fun markInvoiceAsPaid(id: String) {
val updatedStatusInvoice = UpdateInvoiceStatus(id = id, status = StatusInvoice.PAID)
invoiceDao.markInvoiceAsPaid(updatedStatusInvoice)
}
override suspend fun saveInvoice(invoice: Invoice) =
invoiceDao.insertInvoice(invoice)
}
| 0 | Kotlin | 2 | 29 | 9901444c7e94063f80c244b7b3b54a09a2141727 | 1,255 | RoomAccounting | MIT License |
app/src/main/java/org/oppia/android/app/topic/lessons/ChapterSummarySelector.kt | iamsachin45 | 343,995,919 | true | {"Gradle": 8, "Starlark": 16, "Java Properties": 7, "Shell": 6, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 3, "EditorConfig": 1, "Protocol Buffer": 13, "Proguard": 4, "XML": 618, "Kotlin": 861, "JSON": 43, "CODEOWNERS": 1, "Markdown": 6, "Java": 14} | package org.oppia.android.app.topic.lessons
/** Interface to transfer the selected chapter summary to [TopicLessonsFragmentPresenter]. */
interface ChapterSummarySelector {
fun selectChapterSummary(storyId: String, explorationId: String)
}
| 0 | Kotlin | 0 | 1 | eccfd63d0b5a2565b741665dead864da93d4228d | 243 | oppia-android | Apache License 2.0 |
model/src/main/java/com/infinitepower/newquiz/model/RemainingTime.kt | joaomanaia | 443,198,327 | false | null | package com.infinitepower.newquiz.model
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
@JvmInline
value class RemainingTime constructor(val value: Duration) {
companion object {
val ZERO = RemainingTime(Duration.ZERO)
/**
* Creates a new instance of [RemainingTime] from the given milliseconds value.
*/
fun fromMilliseconds(millis: Long): RemainingTime {
require(millis >= 0L) {
"RemainingTime value must be greater than or equal to 0"
}
return RemainingTime(millis.milliseconds)
}
}
init {
require(value >= Duration.ZERO) { "RemainingTime value must be greater than 0" }
}
/**
* @return the remaining percentage of the time.
* @param maxTime in milliseconds
*/
fun getRemainingPercent(maxTime: Long): Float = value.inWholeMilliseconds.toFloat() / maxTime
/**
* @return the remaining time in minute:second format.
*/
fun minuteSecondFormatted(): String {
val minutes = value.inWholeMinutes
val seconds = value.inWholeSeconds % 60
return if (minutes == 0L) seconds.toString() else "$minutes:$seconds"
}
/**
* Returns the elapsed seconds from the max time.
* @param maxTime in milliseconds
*/
fun getElapsedSeconds(maxTime: Long): Long =
maxTime.milliseconds.inWholeSeconds - value.inWholeSeconds
} | 0 | Kotlin | 10 | 84 | 08ba1d1a2b7152a3eac7a27475dce7b496fdaf0f | 1,462 | newquiz | Apache License 2.0 |
app/src/main/java/com/erman/beeper/utils/Constants.kt | ermanergoz | 330,013,053 | false | null | package com.erman.beeper.utils
const val SHARED_PREF_FILE: String = "beeper_shared_prefs"
const val KEY_IS_ALARM_ON: String = "isAlarmOn"
const val KEY_ALARM_TYPE: String = "alarmType"
const val KEY_ALARM_FULL_HOUR: String = "fullHour"
const val KEY_ALARM_HALF_HOUR: String = "halfHour"
const val VOLUME_BEEP: Int = 100
const val DURATION_ALARM_FULL_HOUR: Int = 500
const val DURATION_ALARM_HALF_HOUR: Int = 250 | 0 | Kotlin | 0 | 0 | bfa06d031e6e43d731580f67a173a86418ad4707 | 412 | beeper | MIT License |
SceytChatUiKit/src/main/java/com/sceyt/chatuikit/presentation/components/channel/input/listeners/action/InputActionsListener.kt | sceyt | 549,073,085 | false | {"Kotlin": 2675924, "Java": 107920} | package com.sceyt.chatuikit.presentation.components.channel.input.listeners.action
import android.text.Editable
import com.sceyt.chat.models.message.Message
import com.sceyt.chatuikit.data.models.messages.LinkPreviewDetails
import com.sceyt.chatuikit.data.models.messages.SceytMessage
import com.sceyt.chatuikit.presentation.components.channel.input.mention.Mention
import com.sceyt.chatuikit.presentation.components.channel.input.format.BodyStyleRange
sealed interface InputActionsListener {
fun interface SendMessageListener : InputActionsListener {
fun sendMessage(message: Message, linkDetails: LinkPreviewDetails?)
}
fun interface SendMessagesListener : InputActionsListener {
fun sendMessages(message: List<Message>, linkDetails: LinkPreviewDetails?)
}
fun interface SendEditMessageListener : InputActionsListener {
fun sendEditMessage(message: SceytMessage, linkDetails: LinkPreviewDetails?)
}
fun interface TypingListener : InputActionsListener {
fun sendTyping(typing: Boolean)
}
fun interface UpdateDraftMessageListener {
fun updateDraftMessage(text: Editable?, mentionUserIds: List<Mention>,
styling: List<BodyStyleRange>?,
replyOrEditMessage: SceytMessage?, isReply: Boolean)
}
/** Use this if you want to implement all callbacks */
interface InputActionListeners : SendMessageListener, SendMessagesListener,
SendEditMessageListener, TypingListener, UpdateDraftMessageListener
} | 0 | Kotlin | 1 | 2 | ce9c1b95555fadaafcd11f0d073fcdb07ca49600 | 1,560 | sceyt-chat-android-uikit | MIT License |
src/main/kotlin/me/ferrandis/textAnalyzer/repository/LanguageRepository.kt | ferrandisme | 689,373,192 | false | {"Kotlin": 10042} | package me.ferrandis.textAnalyzer.repository
import me.ferrandis.textAnalyzer.model.LanguageData
import org.springframework.data.repository.reactive.ReactiveCrudRepository
import org.springframework.stereotype.Repository
@Repository
interface LanguageRepository : ReactiveCrudRepository<LanguageData, Long> {
} | 0 | Kotlin | 0 | 0 | b300e87eac242cb925246266bb0409df21d4c1fe | 312 | textAnalyzer | MIT License |
app/src/main/java/com/chargebee/example/items/ItemActivity.kt | chargebee | 279,238,499 | false | null | package com.chargebee.example.items
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.Observer
import com.chargebee.android.ErrorDetail
import com.chargebee.example.BaseActivity
import com.chargebee.example.R
import com.google.gson.Gson
class ItemActivity: BaseActivity() {
var viewModel: ItemsViewModel? = null
private var itemIdInput: EditText? = null
private var itemButton: Button? = null
private var itemName: TextView? = null
private var itemStatus: TextView? = null
private var errorText: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_item)
itemIdInput = findViewById(R.id.itemIdInput)
itemButton = findViewById(R.id.itemButton)
itemName = findViewById(R.id.itemName)
itemStatus = findViewById(R.id.itemStatus)
errorText = findViewById(R.id.errorText)
this.viewModel = ItemsViewModel()
this.itemButton?.setOnClickListener(View.OnClickListener { view: View? ->
showProgressDialog()
viewModel!!.retrieveItem(itemIdInput?.getText().toString())
})
viewModel?.mItemResult?.observe(this, Observer {
hideProgressDialog()
if (it != null) {
itemName?.setText(it.name)
itemStatus?.setText(it.status)
}
})
viewModel?.mItemsError?.observe(this, Observer {
hideProgressDialog()
if (it != null) {
errorText?.setText(
it
)
}
})
}
} | 8 | null | 7 | 8 | ba3d15dc9e6d19b91a78753d851ff1e1946b2ffc | 1,767 | chargebee-android | MIT License |
buildSrc/src/main/kotlin/Plugins.kt | mbobiosio | 324,425,383 | false | null | /**
* @Author <NAME>
* https://linktr.ee/mbobiosio
*/
object Plugins {
/*
* Module Level
*/
const val ANDROID_APPLICATION = "com.android.application"
const val ANDROID = "android"
const val KAPT = "kapt"
const val PARCELIZE = "kotlin-parcelize"
const val ANDROID_LIBRARY = "com.android.library"
const val DAGGER_HILT = "dagger.hilt.android.plugin"
const val GOOGLE_DAGGER_HILT = "com.google.dagger.hilt.android"
const val NAVIGATION_SAFE_ARGS = "androidx.navigation.safeargs.kotlin"
const val ANDROIDX_NAVIGATION = "androidx.navigation"
}
object PluginVersion {
const val AGP = "7.3.1"
const val KOTLIN = "1.6.21"
const val NAVIGATION = "2.4.2"
const val HILT = "2.41"
}
| 0 | null | 4 | 7 | e6376b3a36d87173ef1d854c12fb61842ae40c36 | 739 | MoviesBoard | MIT License |
app/src/main/java/de/szalkowski/activitylauncher/services/ActivityLauncherService.kt | butzist | 16,923,112 | false | {"Kotlin": 70956, "Python": 3097, "Shell": 265} | package de.szalkowski.activitylauncher.services
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.widget.Toast
import dagger.hilt.android.qualifiers.ActivityContext
import de.szalkowski.activitylauncher.R
import de.szalkowski.activitylauncher.services.internal.getActivityIntent
import java.io.IOException
import java.io.InputStreamReader
import java.io.Reader
import java.nio.charset.StandardCharsets
import java.util.regex.Pattern
import javax.inject.Inject
interface ActivityLauncherService {
fun launchActivity(
activity: ComponentName,
asRoot: Boolean,
showToast: Boolean
)
}
class ActivityLauncherServiceImpl @Inject constructor(@ActivityContext private val context: Context) : ActivityLauncherService {
/**
* Got reference from stackoverflow.com URL
* https://stackoverflow.com/questions/9194725/run-android-program-as-root
* https://stackoverflow.com/questions/12343227/escaping-bash-function-arguments-for-use-by-su-c
*/
override fun launchActivity(
activity: ComponentName,
asRoot: Boolean,
showToast: Boolean
) {
val intent = getActivityIntent(activity, null)
if (showToast) Toast.makeText(
context,
String.format(
context.getText(R.string.starting_activity).toString(),
activity.flattenToShortString()
),
Toast.LENGTH_LONG
).show()
try {
if (!asRoot) {
context.startActivity(intent)
} else {
startRootActivity(activity)
}
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(
context,
context.getText(R.string.error).toString() + ": " + e,
Toast.LENGTH_LONG
).show()
}
}
@Throws(IOException::class, InterruptedException::class, IllegalArgumentException::class)
private fun startRootActivity(activity: ComponentName) {
val component = activity.flattenToShortString()
val isValid = validateComponentName(component)
require(isValid) {
String.format(
context.getString(R.string.exception_invalid_component_name),
component
)
}
val process = Runtime.getRuntime().exec(
arrayOf(
"su", "-c",
"am start -n $component"
)
)
val output = getProcessOutput(process)
val exitValue = process.waitFor()
if (exitValue > 0) {
throw RuntimeException(
String.format(
context.getString(R.string.exception_command_error),
exitValue,
output
)
)
}
}
/**
* Got reference from stackoverflow.com URL:
* https://stackoverflow.com/questions/309424/how-do-i-read-convert-an-inputstream-into-a-string-in-java
*/
@Throws(IOException::class)
private fun getProcessOutput(process: Process): String {
val stream = process.errorStream
val bufferSize = 1024
val buffer = CharArray(bufferSize)
val out = StringBuilder()
val `in`: Reader = InputStreamReader(stream, StandardCharsets.UTF_8)
var numRead: Int
while (`in`.read(buffer, 0, buffer.size).also { numRead = it } > 0) {
out.appendRange(buffer, 0, numRead)
}
return out.toString()
}
/**
* In order to be on the safe side, validate component name before merging it into a root shell command
*
* @param component component name
* @return true, if valid
*/
private fun validateComponentName(component: String): Boolean {
val p = Pattern.compile("^[./a-zA-Z0-9]+$")
val m = p.matcher(component)
return m.matches()
}
}
| 16 | Kotlin | 149 | 774 | 5af0d87146ccbfa5a26789f0f94925599a8cb548 | 3,990 | ActivityLauncher | ISC License |
spigot/src/main/kotlin/me/honkling/commando/spigot/types/PlayerType.kt | honkling | 601,352,297 | false | {"Kotlin": 41243} | package me.honkling.commando.spigot.types
import me.honkling.commando.common.generic.ICommandSender
import me.honkling.commando.common.types.Type
import org.bukkit.Bukkit
import org.bukkit.OfflinePlayer
object PlayerType : Type<OfflinePlayer> {
override fun validate(sender: ICommandSender<*>, input: String): Boolean {
return Bukkit.getPlayerExact(input.split(" ")[0]) != null
}
override fun parse(sender: ICommandSender<*>, input: String): Pair<OfflinePlayer, Int> {
return Bukkit.getPlayerExact(input.split(" ")[0])!! to 1
}
override fun complete(sender: ICommandSender<*>, input: String): List<String> {
return Bukkit
.getOnlinePlayers()
.map { it.name }
.filter { input.split(" ")[0].lowercase() in it.lowercase() }
}
} | 2 | Kotlin | 0 | 8 | 31a8607772e0a4fbbadf7008559b1add2a860a3b | 824 | commando | MIT License |
data/src/main/java/org/oppia/android/data/backends/gae/model/GaeStateClassifier.kt | oppia | 148,093,817 | false | {"Kotlin": 12439223, "Starlark": 673462, "Java": 33231, "Shell": 12951} | package org.oppia.android.data.backends.gae.model
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Data class for StateClassifier model
* https://github.com/oppia/oppia/blob/15516a/core/controllers/reader.py#L239
*/
@JsonClass(generateAdapter = true)
data class GaeStateClassifier(
@Json(name = "algorithm_id") val algorithmId: String?,
@Json(name = "classifier_data") val classifierData: Any?,
@Json(name = "data_schema_version") val dataSchemaVersion: Int?
)
| 497 | Kotlin | 497 | 296 | 98257dbad55c2a9a03f898a38fa7ec57b27713a5 | 498 | oppia-android | Apache License 2.0 |
src/main/kotlin/TagManagement.kt | Trip-kun | 853,581,459 | false | {"Kotlin": 53512} | package org.example
import io.javalin.http.Context
import org.example.data.*
import java.net.URI
import java.util.*
fun createOrUpdateTag(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val filterName = context.headerMap()["TAG_name"]
if (filterName == null) {
context.status(400)
context.result("No filter name provided.")
return
}
var filter: Filter = Filter()
filterDao.queryForFieldValuesArgs(mapOf("name" to filterName))?.forEach {
filter = it
}
filter.name = filterName
val rawFilter = context.headerMap()["TAG_filter"]
var filterWeb = false
val filterWebString = context.headerMap()["TAG_filterWeb"]
if (filterWebString != null) {
filterWeb = filterWebString.toBoolean()
}
filter.filterWeb = filterWeb
val username = context.headerMap()["LOGIN_username"]
?: // It won't be null, as it's checked in testAuthentication.
return
val user = userDao.queryForFieldValuesArgs(mapOf("username" to username))?.firstOrNull()
filter.user = user
if (rawFilter != null) {
filter.filter = rawFilter
} else {
context.status(400)
context.result("No filter provided.")
return
}
var filterAll: Boolean = false
val filterAllString = context.headerMap()["TAG_filterAll"]
if (filterAllString != null) {
filterAll = filterAllString.toBoolean()
}
var filterRegex: Boolean = false
val filterRegexString = context.headerMap()["TAG_useRegex"]
if (filterRegexString != null) {
filterRegex = filterRegexString.toBoolean()
}
filter.useRegex = filterRegex
filter.filterAll = filterAll
filterDao.createOrUpdate(filter)
filterDao.refresh(filter)
var count = 1
while (context.headerMap()["TAG_channel$count"] != null) {
val channelId = context.headerMap()["TAG_channel$count"]
try {
Integer.parseInt(channelId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid channel ID: $channelId")
return
}
val channel = channelDao.queryForId(channelId?.toInt())
var filterChannelLink: FilterChannelLink = FilterChannelLink()
filterChannelLinkDao.queryForFieldValuesArgs(mapOf("channel_id" to channel?.id, "filter_id" to filter.id))?.forEach {
filterChannelLink = it
}
filterChannelLink.channel = channel
filterChannelLink.filter = filter
filterChannelLinkDao.create(filterChannelLink)
count++
}
count = 1
while (context.headerMap()["TAG_removeChannel$count"] != null) {
val channelId = context.headerMap()["TAG_removeChannel$count"]
try {
Integer.parseInt(channelId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid channel ID: $channelId")
return
}
val channel = channelDao.queryForId(channelId?.toInt())
var filterChannelLink: FilterChannelLink = FilterChannelLink()
filterChannelLinkDao.queryForFieldValuesArgs(mapOf("channel_id" to channel?.id, "filter_id" to filter.id))?.forEach {
filterChannelLink = it
}
if (filterChannelLink.filter!=null) {
filterChannelLinkDao.delete(filterChannelLink)
}
count++
}
context.status(200)
context.result("Tag created or updated.")
}
fun runTagOnEntry(filter: Filter, entry: Entry): Boolean {
filterEntryLinkDao.queryForFieldValuesArgs(mapOf("entry_id" to entry.id, "filter_id" to filter.id))?.forEach { _ ->
return true
}
if (!filter.filterAll) {
var go = false
filterChannelLinkDao.queryForFieldValuesArgs(mapOf("channel_id" to entry.channel?.id, "filter_id" to filter.id))
?.forEach { _ ->
go = true
}
if (!go) {
return false
}
} else {
var go = false
filter.user?.userChannelLinks?.forEach { userChannelLink ->
val channel = userChannelLink.channel
if (channel != null) {
if (channel.id == entry.channel?.id) {
go = true
}
}
}
if (!go) {
return false
}
}
var urlContent = ""
try {
if (filter.filterWeb) {
val urlConnection = URI(entry.url.toString()).toURL().openConnection()
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0")
urlConnection.connect()
val scanner = Scanner(urlConnection.getInputStream())
scanner.useDelimiter("\\Z")
if (scanner.hasNext()) {
urlContent = scanner.next()
}
scanner.close()
}
} catch (ignored: Exception) {
}
val fullEntryContent = entry.title + entry.description + urlContent + entry.url + entry.authors + entry.categories + entry.contributors + entry.comments + entry.enclosures + entry.contents + entry.foreignMarkup + entry.links + entry.publishedDate + entry.source + entry.modules
if (!runFilter(filter, fullEntryContent) && !filter.useRegex) {
return false
}
if (!runFilterRegex(filter, fullEntryContent) && filter.useRegex) {
return false
}
val filterEntryLink = FilterEntryLink()
filterEntryLink.filter = filter
filterEntryLink.entry = entry
filterEntryLinkDao.create(filterEntryLink)
return true
}
fun runFilter(filter: Filter, input: String): Boolean {
return input.lowercase().contains(filter.filter.lowercase())
}
fun runFilterRegex(filter: Filter, input: String): Boolean {
return Regex(filter.filter).containsMatchIn(input)
}
fun getTags(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val username = context.headerMap()["LOGIN_username"]
?: // It won't be null, as it's checked in testAuthentication.
return
val user = userDao.queryForFieldValuesArgs(mapOf("username" to username))?.firstOrNull()
val filters = filterDao.queryForFieldValuesArgs(mapOf("user_id" to user?.id))
val filtersJson = mutableListOf<Map<String, Any>>()
filters?.forEach { filter ->
filtersJson.add(mapOf(
"id" to filter.id,
"name" to filter.name,
"filter" to filter.filter,
"filterAll" to filter.filterAll
))
}
context.json(filtersJson)
}
fun getTaggedEntriesForUser(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val username = context.headerMap()["LOGIN_username"]
?: // It won't be null, as it's checked in testAuthentication.
return
val user = userDao.queryForFieldValuesArgs(mapOf("username" to username))?.firstOrNull()
val filters = user?.filters
val entriesJson = mutableListOf<Map<String, Any>>()
filters?.forEach { filter ->
val filterEntryLinks = filterEntryLinkDao.queryForFieldValuesArgs(mapOf("filter_id" to filter.id))
filterEntryLinks?.forEach {
val entry = it.entry
if (entry != null) {
entriesJson.add(mapOf(
"entryid" to entry.id,
"filterid" to filter.id,
))
}
}
}
context.json(entriesJson)
}
fun runTag(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val filterId = context.headerMap()["TAG_id"]
if (filterId == null) {
context.status(400)
context.result("No filter ID provided.")
return
}
try {
Integer.parseInt(filterId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid filter ID.")
return
}
val filter = filterDao.queryForId(filterId.toInt())
if (filter == null) {
context.status(400)
context.result("Filter not found.")
return
}
if (filter.filterAll) {
val user = filter.user
user?.userChannelLinks?.forEach { userChannelLink ->
val channel = userChannelLink.channel
channel?.entries?.forEach { entry ->
runTagOnEntry(filter, entry)
}
}
} else {
filter.filterChannelLinks?.forEach { filterChannelLink ->
val channel = filterChannelLink.channel
channel?.entries?.forEach { entry ->
runTagOnEntry(filter, entry)
}
}
}
}
fun deleteTag(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val filterId = context.headerMap()["TAG_id"]
if (filterId == null) {
context.status(400)
context.result("No filter ID provided.")
return
}
try {
Integer.parseInt(filterId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid filter ID.")
return
}
val filter = filterDao.queryForId(filterId.toInt())
if (filter == null) {
context.status(400)
context.result("Filter not found.")
return
}
filterEntryLinkDao.queryForFieldValuesArgs(mapOf("filter_id" to filter.id))?.forEach {
filterEntryLinkDao.delete(it)
}
filterChannelLinkDao.queryForFieldValuesArgs(mapOf("filter_id" to filter.id))?.forEach {
filterChannelLinkDao.delete(it)
}
filterDao.delete(filter)
context.status(200)
context.result("Tag deleted.")
}
fun clearFilterEntries(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val filterId = context.headerMap()["TAG_id"]
if (filterId == null) {
context.status(400)
context.result("No filter ID provided.")
return
}
try {
Integer.parseInt(filterId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid filter ID.")
return
}
val filter = filterDao.queryForId(filterId.toInt())
if (filter == null) {
context.status(400)
context.result("Filter not found.")
return
}
filterEntryLinkDao.queryForFieldValuesArgs(mapOf("filter_id" to filter.id))?.forEach {
filterEntryLinkDao.delete(it)
}
context.status(200)
context.result("Filter entries cleared.")
}
fun removeSingleTagEntry(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val filterId = context.headerMap()["TAG_id"]
if (filterId == null) {
context.status(400)
context.result("No filter ID provided.")
return
}
try {
Integer.parseInt(filterId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid filter ID.")
return
}
val filter = filterDao.queryForId(filterId.toInt())
if (filter == null) {
context.status(400)
context.result("Filter not found.")
return
}
val entryId = context.headerMap()["ENTRY_id"]
if (entryId == null) {
context.status(400)
context.result("No entry ID provided.")
return
}
try {
Integer.parseInt(entryId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid entry ID.")
return
}
val entry = entryDao.queryForId(entryId.toInt())
if (entry == null) {
context.status(400)
context.result("Entry not found.")
return
}
filterEntryLinkDao.queryForFieldValuesArgs(mapOf("filter_id" to filter.id, "entry_id" to entry.id))?.forEach {
filterEntryLinkDao.delete(it)
}
context.status(200)
context.result("Entry removed from tag.")
}
fun addSingleTagEntry(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val filterId = context.headerMap()["TAG_id"]
if (filterId == null) {
context.status(400)
context.result("No filter ID provided.")
return
}
try {
Integer.parseInt(filterId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid filter ID.")
return
}
val filter = filterDao.queryForId(filterId.toInt())
if (filter == null) {
context.status(400)
context.result("Filter not found.")
return
}
val entryId = context.headerMap()["ENTRY_id"]
if (entryId == null) {
context.status(400)
context.result("No entry ID provided.")
return
}
try {
Integer.parseInt(entryId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid entry ID.")
return
}
val entry = entryDao.queryForId(entryId.toInt())
if (entry == null) {
context.status(400)
context.result("Entry not found.")
return
}
val filterEntryLink = FilterEntryLink()
filterEntryLink.filter = filter
filterEntryLink.entry = entry
filterEntryLinkDao.create(filterEntryLink)
context.status(200)
context.result("Entry added to tag.")
}
// TODO: Autodelete channels and cull entries.
// TODO: Split up big methods with helper function that checks if a certain map exists in a dao query.
// TODO: Delete users, Auto-trim entries with a configurable maximum entries per channel
// Doing this would require moving more stuff to kotlin, as java doesn't have template functions.
// Or just typechecking within the function but that's ugly.
// https://kotlinlang.org/docs/generics.html#generic-functions | 0 | Kotlin | 0 | 0 | 717058eabcc3ec097dab575fe283061c3384308d | 13,641 | RSS_Tagging_Server | The Unlicense |
src/main/kotlin/TagManagement.kt | Trip-kun | 853,581,459 | false | {"Kotlin": 53512} | package org.example
import io.javalin.http.Context
import org.example.data.*
import java.net.URI
import java.util.*
fun createOrUpdateTag(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val filterName = context.headerMap()["TAG_name"]
if (filterName == null) {
context.status(400)
context.result("No filter name provided.")
return
}
var filter: Filter = Filter()
filterDao.queryForFieldValuesArgs(mapOf("name" to filterName))?.forEach {
filter = it
}
filter.name = filterName
val rawFilter = context.headerMap()["TAG_filter"]
var filterWeb = false
val filterWebString = context.headerMap()["TAG_filterWeb"]
if (filterWebString != null) {
filterWeb = filterWebString.toBoolean()
}
filter.filterWeb = filterWeb
val username = context.headerMap()["LOGIN_username"]
?: // It won't be null, as it's checked in testAuthentication.
return
val user = userDao.queryForFieldValuesArgs(mapOf("username" to username))?.firstOrNull()
filter.user = user
if (rawFilter != null) {
filter.filter = rawFilter
} else {
context.status(400)
context.result("No filter provided.")
return
}
var filterAll: Boolean = false
val filterAllString = context.headerMap()["TAG_filterAll"]
if (filterAllString != null) {
filterAll = filterAllString.toBoolean()
}
var filterRegex: Boolean = false
val filterRegexString = context.headerMap()["TAG_useRegex"]
if (filterRegexString != null) {
filterRegex = filterRegexString.toBoolean()
}
filter.useRegex = filterRegex
filter.filterAll = filterAll
filterDao.createOrUpdate(filter)
filterDao.refresh(filter)
var count = 1
while (context.headerMap()["TAG_channel$count"] != null) {
val channelId = context.headerMap()["TAG_channel$count"]
try {
Integer.parseInt(channelId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid channel ID: $channelId")
return
}
val channel = channelDao.queryForId(channelId?.toInt())
var filterChannelLink: FilterChannelLink = FilterChannelLink()
filterChannelLinkDao.queryForFieldValuesArgs(mapOf("channel_id" to channel?.id, "filter_id" to filter.id))?.forEach {
filterChannelLink = it
}
filterChannelLink.channel = channel
filterChannelLink.filter = filter
filterChannelLinkDao.create(filterChannelLink)
count++
}
count = 1
while (context.headerMap()["TAG_removeChannel$count"] != null) {
val channelId = context.headerMap()["TAG_removeChannel$count"]
try {
Integer.parseInt(channelId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid channel ID: $channelId")
return
}
val channel = channelDao.queryForId(channelId?.toInt())
var filterChannelLink: FilterChannelLink = FilterChannelLink()
filterChannelLinkDao.queryForFieldValuesArgs(mapOf("channel_id" to channel?.id, "filter_id" to filter.id))?.forEach {
filterChannelLink = it
}
if (filterChannelLink.filter!=null) {
filterChannelLinkDao.delete(filterChannelLink)
}
count++
}
context.status(200)
context.result("Tag created or updated.")
}
fun runTagOnEntry(filter: Filter, entry: Entry): Boolean {
filterEntryLinkDao.queryForFieldValuesArgs(mapOf("entry_id" to entry.id, "filter_id" to filter.id))?.forEach { _ ->
return true
}
if (!filter.filterAll) {
var go = false
filterChannelLinkDao.queryForFieldValuesArgs(mapOf("channel_id" to entry.channel?.id, "filter_id" to filter.id))
?.forEach { _ ->
go = true
}
if (!go) {
return false
}
} else {
var go = false
filter.user?.userChannelLinks?.forEach { userChannelLink ->
val channel = userChannelLink.channel
if (channel != null) {
if (channel.id == entry.channel?.id) {
go = true
}
}
}
if (!go) {
return false
}
}
var urlContent = ""
try {
if (filter.filterWeb) {
val urlConnection = URI(entry.url.toString()).toURL().openConnection()
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0")
urlConnection.connect()
val scanner = Scanner(urlConnection.getInputStream())
scanner.useDelimiter("\\Z")
if (scanner.hasNext()) {
urlContent = scanner.next()
}
scanner.close()
}
} catch (ignored: Exception) {
}
val fullEntryContent = entry.title + entry.description + urlContent + entry.url + entry.authors + entry.categories + entry.contributors + entry.comments + entry.enclosures + entry.contents + entry.foreignMarkup + entry.links + entry.publishedDate + entry.source + entry.modules
if (!runFilter(filter, fullEntryContent) && !filter.useRegex) {
return false
}
if (!runFilterRegex(filter, fullEntryContent) && filter.useRegex) {
return false
}
val filterEntryLink = FilterEntryLink()
filterEntryLink.filter = filter
filterEntryLink.entry = entry
filterEntryLinkDao.create(filterEntryLink)
return true
}
fun runFilter(filter: Filter, input: String): Boolean {
return input.lowercase().contains(filter.filter.lowercase())
}
fun runFilterRegex(filter: Filter, input: String): Boolean {
return Regex(filter.filter).containsMatchIn(input)
}
fun getTags(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val username = context.headerMap()["LOGIN_username"]
?: // It won't be null, as it's checked in testAuthentication.
return
val user = userDao.queryForFieldValuesArgs(mapOf("username" to username))?.firstOrNull()
val filters = filterDao.queryForFieldValuesArgs(mapOf("user_id" to user?.id))
val filtersJson = mutableListOf<Map<String, Any>>()
filters?.forEach { filter ->
filtersJson.add(mapOf(
"id" to filter.id,
"name" to filter.name,
"filter" to filter.filter,
"filterAll" to filter.filterAll
))
}
context.json(filtersJson)
}
fun getTaggedEntriesForUser(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val username = context.headerMap()["LOGIN_username"]
?: // It won't be null, as it's checked in testAuthentication.
return
val user = userDao.queryForFieldValuesArgs(mapOf("username" to username))?.firstOrNull()
val filters = user?.filters
val entriesJson = mutableListOf<Map<String, Any>>()
filters?.forEach { filter ->
val filterEntryLinks = filterEntryLinkDao.queryForFieldValuesArgs(mapOf("filter_id" to filter.id))
filterEntryLinks?.forEach {
val entry = it.entry
if (entry != null) {
entriesJson.add(mapOf(
"entryid" to entry.id,
"filterid" to filter.id,
))
}
}
}
context.json(entriesJson)
}
fun runTag(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val filterId = context.headerMap()["TAG_id"]
if (filterId == null) {
context.status(400)
context.result("No filter ID provided.")
return
}
try {
Integer.parseInt(filterId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid filter ID.")
return
}
val filter = filterDao.queryForId(filterId.toInt())
if (filter == null) {
context.status(400)
context.result("Filter not found.")
return
}
if (filter.filterAll) {
val user = filter.user
user?.userChannelLinks?.forEach { userChannelLink ->
val channel = userChannelLink.channel
channel?.entries?.forEach { entry ->
runTagOnEntry(filter, entry)
}
}
} else {
filter.filterChannelLinks?.forEach { filterChannelLink ->
val channel = filterChannelLink.channel
channel?.entries?.forEach { entry ->
runTagOnEntry(filter, entry)
}
}
}
}
fun deleteTag(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val filterId = context.headerMap()["TAG_id"]
if (filterId == null) {
context.status(400)
context.result("No filter ID provided.")
return
}
try {
Integer.parseInt(filterId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid filter ID.")
return
}
val filter = filterDao.queryForId(filterId.toInt())
if (filter == null) {
context.status(400)
context.result("Filter not found.")
return
}
filterEntryLinkDao.queryForFieldValuesArgs(mapOf("filter_id" to filter.id))?.forEach {
filterEntryLinkDao.delete(it)
}
filterChannelLinkDao.queryForFieldValuesArgs(mapOf("filter_id" to filter.id))?.forEach {
filterChannelLinkDao.delete(it)
}
filterDao.delete(filter)
context.status(200)
context.result("Tag deleted.")
}
fun clearFilterEntries(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val filterId = context.headerMap()["TAG_id"]
if (filterId == null) {
context.status(400)
context.result("No filter ID provided.")
return
}
try {
Integer.parseInt(filterId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid filter ID.")
return
}
val filter = filterDao.queryForId(filterId.toInt())
if (filter == null) {
context.status(400)
context.result("Filter not found.")
return
}
filterEntryLinkDao.queryForFieldValuesArgs(mapOf("filter_id" to filter.id))?.forEach {
filterEntryLinkDao.delete(it)
}
context.status(200)
context.result("Filter entries cleared.")
}
fun removeSingleTagEntry(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val filterId = context.headerMap()["TAG_id"]
if (filterId == null) {
context.status(400)
context.result("No filter ID provided.")
return
}
try {
Integer.parseInt(filterId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid filter ID.")
return
}
val filter = filterDao.queryForId(filterId.toInt())
if (filter == null) {
context.status(400)
context.result("Filter not found.")
return
}
val entryId = context.headerMap()["ENTRY_id"]
if (entryId == null) {
context.status(400)
context.result("No entry ID provided.")
return
}
try {
Integer.parseInt(entryId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid entry ID.")
return
}
val entry = entryDao.queryForId(entryId.toInt())
if (entry == null) {
context.status(400)
context.result("Entry not found.")
return
}
filterEntryLinkDao.queryForFieldValuesArgs(mapOf("filter_id" to filter.id, "entry_id" to entry.id))?.forEach {
filterEntryLinkDao.delete(it)
}
context.status(200)
context.result("Entry removed from tag.")
}
fun addSingleTagEntry(context: Context) {
val go = testAuthentication(context)
if (!go) {
return
}
val filterId = context.headerMap()["TAG_id"]
if (filterId == null) {
context.status(400)
context.result("No filter ID provided.")
return
}
try {
Integer.parseInt(filterId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid filter ID.")
return
}
val filter = filterDao.queryForId(filterId.toInt())
if (filter == null) {
context.status(400)
context.result("Filter not found.")
return
}
val entryId = context.headerMap()["ENTRY_id"]
if (entryId == null) {
context.status(400)
context.result("No entry ID provided.")
return
}
try {
Integer.parseInt(entryId)
} catch (e: Exception) {
context.status(400)
context.result("Invalid entry ID.")
return
}
val entry = entryDao.queryForId(entryId.toInt())
if (entry == null) {
context.status(400)
context.result("Entry not found.")
return
}
val filterEntryLink = FilterEntryLink()
filterEntryLink.filter = filter
filterEntryLink.entry = entry
filterEntryLinkDao.create(filterEntryLink)
context.status(200)
context.result("Entry added to tag.")
}
// TODO: Autodelete channels and cull entries.
// TODO: Split up big methods with helper function that checks if a certain map exists in a dao query.
// TODO: Delete users, Auto-trim entries with a configurable maximum entries per channel
// Doing this would require moving more stuff to kotlin, as java doesn't have template functions.
// Or just typechecking within the function but that's ugly.
// https://kotlinlang.org/docs/generics.html#generic-functions | 0 | Kotlin | 0 | 0 | 717058eabcc3ec097dab575fe283061c3384308d | 13,641 | RSS_Tagging_Server | The Unlicense |
src/main/kotlin/io/github/reugn/kotlin/backoff/Backoff.kt | reugn | 240,526,193 | false | null | package io.github.reugn.kotlin.backoff
import io.github.reugn.kotlin.backoff.util.Result
interface Backoff<T> {
/**
* Retries the specified operation with delays and returns the result.
*/
suspend fun retry(operation: suspend () -> T): Result<T, Throwable>
/**
* Executes the specified operation with retries and returns the result.
* The difference from [retry] is that the first time the operation is performed without delay.
*/
suspend fun withRetries(operation: suspend () -> T): Result<T, Throwable>
}
| 0 | Kotlin | 0 | 40 | 6c65f4264deb0cd4adafa7f2b8328b02033361e1 | 552 | kotlin-backoff | Apache License 2.0 |
roboquant-tiingo/src/test/kotlin/org/roboquant/samples/TiingoSamples.kt | neurallayer | 406,929,056 | false | {"JavaScript": 3009148, "Kotlin": 1562253, "CSS": 1372} | /*
* Copyright 2020-2023 Neural Layer
*
* 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.
*/
package org.roboquant.samples
import org.roboquant.Roboquant
import org.roboquant.common.*
import org.roboquant.feeds.AggregatorLiveFeed
import org.roboquant.loggers.ConsoleLogger
import org.roboquant.loggers.MemoryLogger
import org.roboquant.metrics.ProgressMetric
import org.roboquant.strategies.EMAStrategy
import org.roboquant.tiingo.TiingoHistoricFeed
import org.roboquant.tiingo.TiingoLiveFeed
import kotlin.test.Ignore
import kotlin.test.Test
internal class TiingoSamples {
@Test
@Ignore
internal fun testLiveFeed() {
val feed = TiingoLiveFeed.iex()
feed.subscribe("AAPL", "TSLA")
val rq = Roboquant(EMAStrategy(), ProgressMetric(), logger = ConsoleLogger())
rq.run(feed, Timeframe.next(10.minutes))
println(rq.broker.account.fullSummary())
}
@Test
@Ignore
internal fun aggregatorLiveFeed() {
val iex = TiingoLiveFeed.iex()
iex.subscribe()
val feed = AggregatorLiveFeed(iex, 5.seconds)
val rq = Roboquant(EMAStrategy(), ProgressMetric(), logger = MemoryLogger())
rq.run(feed, Timeframe.next(3.minutes))
println(rq.broker.account.fullSummary())
}
@Test
@Ignore
internal fun testLiveFeedFX() {
val feed = TiingoLiveFeed.fx()
feed.subscribe("EURUSD")
val rq = Roboquant(EMAStrategy(), ProgressMetric(), logger = ConsoleLogger())
rq.run(feed, Timeframe.next(1.minutes))
println(rq.broker.account.fullSummary())
}
@Test
@Ignore
internal fun testLiveFeedCrypto() {
val feed = TiingoLiveFeed.crypto()
val asset = Asset("BNBFDUSD", AssetType.CRYPTO, "FDUSD")
feed.subscribeAssets(asset)
val rq = Roboquant(EMAStrategy(), ProgressMetric(), logger = ConsoleLogger())
rq.run(feed, Timeframe.next(1.minutes))
println(rq.broker.account.fullSummary())
}
@Test
@Ignore
internal fun historic() {
val feed = TiingoHistoricFeed()
val tf = Timeframe.past(3.years)
feed.retrieve("AAPL", "TSLA", "ERROR_SYMBOL", timeframe=tf)
println(feed.assets)
println(feed.timeframe)
val rq = Roboquant(EMAStrategy(), ProgressMetric())
rq.run(feed)
println(rq.broker.account.fullSummary())
}
@Test
@Ignore
internal fun historicIntraDay() {
val feed = TiingoHistoricFeed()
val tf = Timeframe.past(10.days)
feed.retrieveIntraday("AAPL", "TSLA", "ERROR_SYMBOL", timeframe=tf, frequency = "1hour")
println(feed.assets)
println(feed.timeframe)
val rq = Roboquant(EMAStrategy(), ProgressMetric())
rq.run(feed)
println(rq.broker.account.fullSummary())
}
}
| 8 | JavaScript | 38 | 279 | 9d3c21fc1cc4d7a5d054959f5be2c92f879246d6 | 3,337 | roboquant | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin/src/functionalTest/kotlin/org/jetbrains/kotlin/gradle/regressionTests/KT60462WithJavaZombieCompilationTest.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("FunctionName")
package org.jetbrains.kotlin.gradle.regressionTests
import org.jetbrains.kotlin.gradle.dsl.multiplatformExtension
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinJvmCompilation
import org.jetbrains.kotlin.gradle.util.buildProjectWithMPP
import org.jetbrains.kotlin.gradle.util.runLifecycleAwareTest
import kotlin.test.Test
import kotlin.test.assertNull
import kotlin.test.assertSame
class KT60462WithJavaZombieCompilationTest {
/**
* Regression was introduced by:
*
* ```
* [Gradle] Ensure java source sets being created eagerly for 'withJava' <NAME>* 07.07.23, 20:49
* 817e3de8f546e34974b89fef0f4f93b425e7e607
* ```
*
* The commit was ensuring that jvm compilations will create their associated java source sets
* as eager as possible. The solution chosen in the commit was that already the construction of the compilation
* will spawn a coroutine that waits for the `withJavaEnabled` callback to create the java source set.
*
* However, a buildscript like
*
* ```kotlin
* kotlin {
* jvm().withJava()
* val customCompilation = jvm().compilations.create("custom")
* // ^
* // Zombie
* }
* ```
*
* would therefore try to create the java source set right in the constructor call of the 'custom' compilation.
* This would have triggered a listener on `javaSourceSets.all {}` which would ensure that all
* java source sets have a corresponding kotlin compilation created.
*
* Since the current stack is currently inside the constructor of the first compilation, the
* used `compilations.maybeCreate` would trigger the creation of another custom compilation.
*
* The initial buildscript call creating the initial custom compilation will therefore return a Zombie instance
* ```kotlin
* kotlin {
* val customCompilation = jvm().compilations.create("custom")
* customCompilation != jvm().compilations.getByName("custom")
* // ^ ^
* // Zombie Real instance created by the javaSourceSets.all listener
* }
* ```
*/
@Test
fun `test - custom compilation`() = buildProjectWithMPP().runLifecycleAwareTest {
multiplatformExtension.jvm().apply {
withJava()
var instanceUsedForConfigureBlock: KotlinJvmCompilation? = null
val instanceReturnedFromCreate = compilations.create("custom") { instance ->
assertNull(instanceUsedForConfigureBlock)
instanceUsedForConfigureBlock = instance
}
val instanceReturnedFromGet = compilations.getByName("custom")
assertSame(instanceReturnedFromCreate, instanceUsedForConfigureBlock)
assertSame(instanceReturnedFromGet, instanceUsedForConfigureBlock)
}
}
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 3,171 | kotlin | Apache License 2.0 |
app/src/test/java/org/p2p/wallet/striga/user/repository/StrigaUserRepositoryMapperTest.kt | p2p-org | 306,035,988 | false | null | package org.p2p.wallet.striga.user.repository
import com.google.gson.GsonBuilder
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.math.BigDecimal
import kotlin.test.assertNotNull
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.p2p.solanaj.utils.crypto.Base64String
import org.p2p.wallet.BuildConfig
import org.p2p.wallet.home.model.Base58TypeAdapter
import org.p2p.wallet.home.model.Base64TypeAdapter
import org.p2p.wallet.home.model.BigDecimalTypeAdapter
import org.p2p.wallet.infrastructure.network.data.transactionerrors.RpcTransactionError
import org.p2p.wallet.infrastructure.network.data.transactionerrors.RpcTransactionErrorTypeAdapter
import org.p2p.wallet.infrastructure.network.data.transactionerrors.RpcTransactionInstructionErrorParser
import org.p2p.wallet.striga.model.StrigaDataLayerError
import org.p2p.wallet.striga.signup.repository.model.StrigaSignupData
import org.p2p.wallet.striga.signup.repository.model.StrigaSignupDataType
import org.p2p.wallet.striga.user.api.request.StrigaCreateUserRequest
import org.p2p.wallet.striga.user.api.response.StrigaCreateUserResponse
import org.p2p.wallet.striga.user.model.StrigaUserVerificationStatus
import org.p2p.wallet.utils.Base58String
@OptIn(ExperimentalCoroutinesApi::class)
class StrigaUserRepositoryMapperTest {
@Test
fun `GIVEN invalid striga signup data WHEN toNetwork THEN error occurred`() = runTest {
val data = listOf<StrigaSignupData>()
val mapper = StrigaUserRepositoryMapper()
var error: Throwable? = null
try {
mapper.toNetwork(data)
} catch (e: Throwable) {
error = e
}
assertNotNull(error)
}
@Test
fun `GIVEN given wrong birthday format WHEN toNetwork THEN error occurred`() = runTest {
val data = listOf(
StrigaSignupData(StrigaSignupDataType.DATE_OF_BIRTH, "2020-01-01")
)
val mapper = StrigaUserRepositoryMapper()
var error: Throwable? = null
try {
mapper.toNetwork(data)
} catch (e: IllegalStateException) {
error = e
}
assertNotNull(error)
}
@Test
fun `GIVEN correct signup data without placeOfBirth WHEN toNetwork THEN check is error occurred`() = runTest {
val data = listOf(
StrigaSignupData(StrigaSignupDataType.EMAIL, "aaa"),
StrigaSignupData(StrigaSignupDataType.PHONE_CODE_WITH_PLUS, "aaa"),
StrigaSignupData(StrigaSignupDataType.PHONE_NUMBER, "aaa"),
StrigaSignupData(StrigaSignupDataType.FIRST_NAME, "aaa"),
StrigaSignupData(StrigaSignupDataType.LAST_NAME, "aaa"),
StrigaSignupData(StrigaSignupDataType.DATE_OF_BIRTH, "05.05.2005"),
StrigaSignupData(StrigaSignupDataType.OCCUPATION, "Loafer"),
StrigaSignupData(StrigaSignupDataType.SOURCE_OF_FUNDS, "NOTHING"),
StrigaSignupData(StrigaSignupDataType.COUNTRY_ALPHA_2, "TR"),
StrigaSignupData(StrigaSignupDataType.CITY, "Antalya"),
StrigaSignupData(StrigaSignupDataType.CITY_ADDRESS_LINE, "Hurma mahalesi, Ataturk prospect 1"),
StrigaSignupData(StrigaSignupDataType.CITY_POSTAL_CODE, "056987"),
StrigaSignupData(StrigaSignupDataType.CITY_STATE, "Antalya"),
)
val mapper = StrigaUserRepositoryMapper()
var error: Throwable? = null
try {
mapper.toNetwork(data)
} catch (e: StrigaDataLayerError) {
error = e
}
assertNotNull(error)
error as StrigaDataLayerError.InternalError
assertEquals("Key COUNTRY_OF_BIRTH_ALPHA_3 not found in map", error.message)
}
@Test
fun `GIVEN correct signup data WHEN toNetwork THEN everything is ok`() = runTest {
val data = listOf(
StrigaSignupData(StrigaSignupDataType.EMAIL, "aaa"),
StrigaSignupData(StrigaSignupDataType.PHONE_CODE_WITH_PLUS, "aaa"),
StrigaSignupData(StrigaSignupDataType.PHONE_NUMBER, "aaa"),
StrigaSignupData(StrigaSignupDataType.FIRST_NAME, "aaa"),
StrigaSignupData(StrigaSignupDataType.LAST_NAME, "aaa"),
StrigaSignupData(StrigaSignupDataType.DATE_OF_BIRTH, "05.05.2005"),
StrigaSignupData(StrigaSignupDataType.COUNTRY_OF_BIRTH_ALPHA_3, "TUR"),
StrigaSignupData(StrigaSignupDataType.OCCUPATION, "Loafer"),
StrigaSignupData(StrigaSignupDataType.SOURCE_OF_FUNDS, "NOTHING"),
StrigaSignupData(StrigaSignupDataType.COUNTRY_ALPHA_2, "TR"),
StrigaSignupData(StrigaSignupDataType.CITY, "Antalya"),
StrigaSignupData(StrigaSignupDataType.CITY_ADDRESS_LINE, "Hurma mahalesi, Ataturk prospect 1"),
StrigaSignupData(StrigaSignupDataType.CITY_POSTAL_CODE, "056987"),
StrigaSignupData(StrigaSignupDataType.CITY_STATE, "Antalya"),
)
val mapper = StrigaUserRepositoryMapper()
var error: Throwable? = null
try {
mapper.toNetwork(data)
} catch (e: IllegalStateException) {
error = e
}
assertNull(error)
}
@Test
fun `GIVEN state can be empty string WHEN toNetwork THEN everything is ok`() = runTest {
val data = listOf(
StrigaSignupData(StrigaSignupDataType.EMAIL, "aaa"),
StrigaSignupData(StrigaSignupDataType.PHONE_CODE_WITH_PLUS, "aaa"),
StrigaSignupData(StrigaSignupDataType.PHONE_NUMBER, "aaa"),
StrigaSignupData(StrigaSignupDataType.FIRST_NAME, "aaa"),
StrigaSignupData(StrigaSignupDataType.LAST_NAME, "aaa"),
StrigaSignupData(StrigaSignupDataType.DATE_OF_BIRTH, "05.05.2005"),
StrigaSignupData(StrigaSignupDataType.COUNTRY_OF_BIRTH_ALPHA_3, "TUR"),
StrigaSignupData(StrigaSignupDataType.OCCUPATION, "Loafer"),
StrigaSignupData(StrigaSignupDataType.SOURCE_OF_FUNDS, "NOTHING"),
StrigaSignupData(StrigaSignupDataType.COUNTRY_ALPHA_2, "TR"),
StrigaSignupData(StrigaSignupDataType.CITY, "Antalya"),
StrigaSignupData(StrigaSignupDataType.CITY_ADDRESS_LINE, "Hurma mahalesi, Ataturk prospect 1"),
StrigaSignupData(StrigaSignupDataType.CITY_POSTAL_CODE, "056987"),
StrigaSignupData(StrigaSignupDataType.CITY_STATE, ""),
)
val mapper = StrigaUserRepositoryMapper()
var error: Throwable? = null
var request: StrigaCreateUserRequest? = null
try {
request = mapper.toNetwork(data)
} catch (e: IllegalStateException) {
error = e
request = null
}
assertNull(error)
assertNotNull(request)
assertNull(request.address.state)
assertNull(request.address.addressLine2)
val transactionErrorTypeAdapter = RpcTransactionErrorTypeAdapter(RpcTransactionInstructionErrorParser())
val gson = GsonBuilder()
.apply { if (BuildConfig.DEBUG) setPrettyPrinting() }
.registerTypeAdapter(BigDecimal::class.java, BigDecimalTypeAdapter)
.registerTypeAdapter(Base58String::class.java, Base58TypeAdapter)
.registerTypeAdapter(Base64String::class.java, Base64TypeAdapter)
.registerTypeAdapter(RpcTransactionError::class.java, transactionErrorTypeAdapter)
.setLenient()
.disableHtmlEscaping()
.create()
val json = gson.toJson(request)
assertTrue(!json.contains("state"))
assertTrue(!json.contains("addressLine2"))
}
@Test
fun `GIVEN create user response with unknown status WHEN fromNetwork THEN check MappingError`() {
val mapper = StrigaUserRepositoryMapper()
val response = StrigaCreateUserResponse(
userId = "user_id",
email = "email",
kycDetails = StrigaCreateUserResponse.KycDataResponse(
status = "some_status",
isEmailVerified = false,
isMobileVerified = false
)
)
var error: Throwable? = null
try {
mapper.fromNetwork(response)
} catch (e: StrigaDataLayerError) {
error = e
}
assertNotNull(error)
assertTrue(error is StrigaDataLayerError.InternalError)
error as StrigaDataLayerError.InternalError
assertEquals("StrigaUserInitialDetails mapping failed", error.message)
assertEquals("Unsupported KYC status: some_status", error.cause?.message)
}
@Test
fun `GIVEN valid create user response WHEN fromNetwork THEN check everything is ok`() {
val mapper = StrigaUserRepositoryMapper()
val response = StrigaCreateUserResponse(
userId = "user_id",
email = "email",
kycDetails = StrigaCreateUserResponse.KycDataResponse(
status = StrigaUserVerificationStatus.NOT_STARTED.toString(),
isEmailVerified = false,
isMobileVerified = false
)
)
val responseData = mapper.fromNetwork(response)
assertEquals("user_id", responseData.userId)
assertEquals("email", responseData.email)
assertEquals(StrigaUserVerificationStatus.NOT_STARTED, responseData.kycStatus.status)
assertFalse(responseData.kycStatus.isEmailVerified)
assertFalse(responseData.kycStatus.isMobileVerified)
}
}
| 8 | null | 18 | 34 | d091e18b7d88c936b7c6c627f4fec96bcf4a0356 | 9,607 | key-app-android | MIT License |
jetpack/src/main/java/com/zb/jetpack/activity/UseBindingAdapterActivity.kt | zbzbhahae | 412,424,768 | false | null | package com.zb.jetpack.activity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import com.zb.jetpack.R
import com.zb.jetpack.databinding.ActivityUseBindingAdapterBinding
class UseBindingAdapterActivity : BaseActivity() {
private lateinit var binding : ActivityUseBindingAdapterBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this,R.layout.activity_use_binding_adapter)
binding.imageUrlInXML = "https://img1.baidu.com/it/u=1540482440,3576916641&fm=26&fmt=auto&gp=0.jpg"
binding.localImageInXML = R.mipmap.zhouxingchi
}
} | 1 | null | 1 | 1 | f41edf7998e050c89f96ab3303512c349e070be9 | 680 | androidworks | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.