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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mahout-gradle-plugin/src/main/kotlin/com/rickbusarow/mahout/publishing/PublishingMavenSubExtension.kt | rickbusarow | 710,392,543 | false | {"Kotlin": 290594, "Shell": 4276} | /*
* Copyright (C) 2024 <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 com.rickbusarow.mahout.publishing
import com.rickbusarow.kgx.get
import com.rickbusarow.kgx.gradleLazy
import com.rickbusarow.kgx.javaExtension
import com.rickbusarow.kgx.named
import com.rickbusarow.kgx.names.SourceSetName.Companion.addSuffix
import com.rickbusarow.kgx.names.SourceSetName.Companion.asSourceSetName
import com.rickbusarow.kgx.names.SourceSetName.Companion.isMain
import com.rickbusarow.kgx.names.TaskName.Companion.asTaskName
import com.rickbusarow.kgx.newInstance
import com.rickbusarow.kgx.register
import com.rickbusarow.mahout.api.SubExtension
import com.rickbusarow.mahout.api.SubExtensionInternal
import com.rickbusarow.mahout.config.mahoutProperties
import com.rickbusarow.mahout.conventions.AbstractHasSubExtension
import com.rickbusarow.mahout.conventions.AbstractSubExtension
import com.rickbusarow.mahout.core.stdlib.letIf
import com.rickbusarow.mahout.core.versionIsSnapshot
import com.rickbusarow.mahout.dokka.DokkatooConventionPlugin.Companion.dokkaJavadocJar
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.model.ObjectFactory
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.publish.maven.internal.publication.DefaultMavenPom
import org.gradle.api.tasks.bundling.Jar
import org.gradle.plugins.signing.Sign
import javax.inject.Inject
/** */
public interface HasPublishingMavenSubExtension : java.io.Serializable {
/** */
public val publishing: PublishingMavenSubExtension
/** */
public fun publishing(action: Action<in PublishingMavenSubExtension>) {
action.execute(publishing)
}
}
internal abstract class DefaultHasPublishingMavenSubExtension @Inject constructor(
override val objects: ObjectFactory
) : AbstractHasSubExtension(),
HasPublishingMavenSubExtension,
SubExtensionInternal {
override val publishing: PublishingMavenSubExtension by
subExtension(DefaultPublishingMavenSubExtension::class)
}
/** */
public interface PublishingMavenSubExtension : SubExtension<PublishingMavenSubExtension> {
/** */
public val defaultPom: DefaultMavenPom
/** */
public fun publishMaven(
artifactId: String? = null,
pomDescription: String? = null,
groupId: String? = null,
versionName: String? = null,
sourceSetName: String = "main",
publicationName: String? = null,
configureAction: Action<in MavenPublication>? = null
)
}
/** */
public abstract class DefaultPublishingMavenSubExtension @Inject constructor(
target: Project,
objects: ObjectFactory
) : AbstractSubExtension(target, objects),
PublishingMavenSubExtension,
SubExtensionInternal {
override val defaultPom: DefaultMavenPom by gradleLazy {
objects.newInstance<DefaultMavenPom>()
.also { pom ->
pom.url.convention(mahoutProperties.publishing.pom.url)
pom.name.convention(mahoutProperties.publishing.pom.name)
pom.description.convention(mahoutProperties.publishing.pom.description)
pom.inceptionYear.convention(mahoutProperties.publishing.pom.inceptionYear)
pom.licenses { licenseSpec ->
licenseSpec.license { license ->
license.name.convention(mahoutProperties.publishing.pom.license.name)
license.url.convention(mahoutProperties.publishing.pom.license.url)
license.distribution.convention(mahoutProperties.publishing.pom.license.dist)
}
}
pom.scm { scm ->
scm.url.convention(mahoutProperties.publishing.pom.scm.url)
scm.connection.convention(mahoutProperties.publishing.pom.scm.connection)
scm.developerConnection.convention(mahoutProperties.publishing.pom.scm.devConnection)
}
pom.developers { developerSpec ->
developerSpec.developer { developer ->
developer.id.convention(mahoutProperties.publishing.pom.developer.id)
developer.name.convention(mahoutProperties.publishing.pom.developer.name)
developer.url.convention(mahoutProperties.publishing.pom.developer.url)
}
}
}
}
override fun publishMaven(
artifactId: String?,
pomDescription: String?,
groupId: String?,
versionName: String?,
sourceSetName: String,
publicationName: String?,
configureAction: Action<in MavenPublication>?
) {
val ssName = sourceSetName.asSourceSetName()
val pubName = publicationName
?: PublicationName.forSourceSetName(baseName = "maven", sourceSetName = ssName).value
val sourcesJarTaskName = "sourcesJar".asTaskName()
.letIf(!ssName.isMain()) { ssName.addSuffix(it) }
target.tasks.register(sourcesJarTaskName, Jar::class) {
it.archiveClassifier.set("sources")
it.from(target.javaExtension.sourceSets[ssName].allSource)
}
target.gradlePublishingExtension.publications
.register(pubName, MavenPublication::class.java) { publication ->
publication.artifactId = artifactId
?: mahoutProperties.publishing.pom.artifactId.orNull
?: target.name
publication.groupId = groupId
?: target.mahoutProperties.group.orNull
?: target.group.toString()
publication.version = versionName
?: target.mahoutProperties.versionName.orNull
?: target.version.toString()
val sourcesJar = target.tasks.named(sourcesJarTaskName)
publication.from(target.components.getByName("java"))
publication.artifact(sourcesJar)
publication.artifact(target.tasks.dokkaJavadocJar)
publication.pom.description.set(pomDescription)
val default = defaultPom
publication.pom { mavenPom ->
mavenPom.url.convention(default.url)
mavenPom.name.convention(default.name)
mavenPom.description.convention(default.description)
mavenPom.inceptionYear.convention(default.inceptionYear)
mavenPom.licenses { licenseSpec ->
for (defaultLicense in default.licenses) {
licenseSpec.license { license ->
license.name.convention(defaultLicense.name)
license.url.convention(defaultLicense.url)
license.distribution.convention(defaultLicense.distribution)
}
}
}
mavenPom.scm { scm ->
default.scm?.url?.let { scm.url.convention(it) }
default.scm?.connection?.let { scm.connection.convention(it) }
default.scm?.developerConnection?.let { scm.developerConnection.convention(it) }
}
mavenPom.developers { developerSpec ->
for (defaultDeveloper in default.developers) {
developerSpec.developer { developer ->
developer.id.convention(defaultDeveloper.id)
developer.name.convention(defaultDeveloper.name)
developer.url.convention(defaultDeveloper.url)
}
}
}
}
}
target.tasks.withType(Sign::class.java).configureEach {
// skip signing for -SNAPSHOT publishing
it.onlyIf { !target.versionIsSnapshot }
}
}
}
| 1 | Kotlin | 0 | 0 | 37aa4047150d3b30cfe11c82bef6142a9398a9bb | 7,702 | mahout | Apache License 2.0 |
app/src/main/kotlin/io/github/beomjo/search/base/BaseViewModel.kt | beomjo | 388,829,504 | false | null | /*
* Designed and developed by 2021 beomjo
*
* 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 io.github.beomjo.search.base
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.beomjo.compilation.util.Event
import com.bumptech.glide.load.HttpException
import com.skydoves.bindables.BindingViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
abstract class BaseViewModel : BindingViewModel() {
val toast = MutableLiveData<Event<String>>()
val event = MutableLiveData<Event<Action>>()
fun launch(
block: suspend () -> Unit,
): Job {
return launchBlock(block, null)
}
fun launchWithErrorHandle(
block: suspend () -> Unit,
handleException: (() -> Unit?)? = null,
): Job {
return launchBlock(block, handleException)
}
private fun launchBlock(
block: suspend () -> Unit,
handleException: (() -> Unit?)? = null,
): Job {
return viewModelScope.launch {
try {
block()
} catch (e: HttpException) {
handleException?.let { handleException() }
toast.value = Event(e.message ?: "Error")
}
}
}
fun finish() {
event.value = Event(Action.Finish)
}
sealed class Action {
object Finish : Action()
}
}
| 2 | Kotlin | 1 | 2 | 8f4ad1d4b769fee069d5d4ed7f8bf3d00ee032f9 | 1,900 | kakao-search | Apache License 2.0 |
Core/src/commonMain/kotlin/io/nacular/doodle/drawing/Font.kt | nacular | 108,631,782 | false | {"Kotlin": 3150677} | package io.nacular.doodle.drawing
import io.nacular.measured.units.Angle
import io.nacular.measured.units.Measure
/**
* Represents a font used to render text. NOTE: this interface is only intended
* to be implemented by the framework. This ensures that instances always
* represent a loaded Font that can be used to render text without issue.
*
* @author Nicholas Eddy
* @see Canvas.text
*/
public interface Font {
public val size : Int
public val style : Style
public val weight: Int
public val family: String
public sealed class Style {
public object Normal: Style()
public object Italic: Style()
public class Oblique(public val angle: Measure<Angle>? = null): Style()
}
public companion object {
public const val Thinnest: Int = 100
public const val Thinner: Int = 200
public const val Thin: Int = 300
public const val Normal: Int = 400
public const val Thick: Int = 500
public const val Thicker: Int = 600
public const val Bold: Int = 700
public const val Bolder: Int = 800
public const val Boldest: Int = 900
}
} | 3 | Kotlin | 26 | 613 | f7414d4c30cdd7632992071234223653e52b978c | 1,177 | doodle | MIT License |
src/jsMain/kotlin/com/sparetimedevs/win/candidates/CandidatesPage.kt | sparetimedevs | 230,339,318 | false | null | /*
* Copyright (c) 2019 sparetimedevs and respective authors and developers.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sparetimedevs.win.candidates
import com.sparetimedevs.win.CandidateViewModel
import com.sparetimedevs.win.client.getCandidates
import com.sparetimedevs.win.loader.Loader
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.w3c.dom.HTMLDivElement
class CandidatesPage(
private val contentDiv: HTMLDivElement
) : Loader() {
init {
show()
}
private fun show() {
GlobalScope.launch {
showLoader()
val candidates = getCandidates(this.coroutineContext)
hideLoader()
showCandidates(candidates)
}
}
private fun showCandidates(candidateViewModels: List<CandidateViewModel>) {
candidateViewModels.forEachIndexed { index, candidate ->
contentDiv.appendChild(candidate.toElement(index))
}
}
}
| 0 | Kotlin | 0 | 0 | 70e0bb7827628274cbf97f569ca13cd73607f02c | 1,496 | win-app | Apache License 2.0 |
app/src/main/java/dev/shreyaspatil/permissionFlow/example/ui/multipermission/MultiPermissionActivity.kt | PatilShreyas | 504,894,810 | false | null | /**
* Copyright 2022 <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.shreyaspatil.permissionFlow.example.ui.multipermission
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import dev.shreyaspatil.permissionFlow.MultiplePermissionState
import dev.shreyaspatil.permissionFlow.PermissionFlow
import dev.shreyaspatil.permissionFlow.example.databinding.ActivityMultipermissionBinding
import dev.shreyaspatil.permissionFlow.utils.registerForPermissionFlowRequestsResult
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
/**
* This example activity shows how to use [PermissionFlow] to request multiple permissions at once
* and observe multiple permissions at once.
*/
class MultiPermissionActivity : AppCompatActivity() {
private lateinit var binding: ActivityMultipermissionBinding
private val permissionFlow = PermissionFlow.getInstance()
private val permissionLauncher = registerForPermissionFlowRequestsResult()
private val permissions = arrayOf(
android.Manifest.permission.CAMERA,
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.READ_CALL_LOG,
android.Manifest.permission.READ_CONTACTS,
android.Manifest.permission.READ_PHONE_STATE,
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMultipermissionBinding.inflate(layoutInflater)
setContentView(binding.root)
initViews()
observePermissions()
}
private fun initViews() {
binding.buttonAskPermission.setOnClickListener {
permissionLauncher.launch(permissions)
}
}
private fun observePermissions() {
permissionFlow.getMultiplePermissionState(*permissions) // or use `getPermissionState()` for observing a single permission
.flowWithLifecycle(lifecycle)
.onEach { onPermissionStateChange(it) }
.launchIn(lifecycleScope)
}
private fun onPermissionStateChange(state: MultiplePermissionState) {
if (state.allGranted) {
Toast.makeText(this, "All permissions are granted!", Toast.LENGTH_SHORT).show()
}
binding.textViewGrantedPermissions.text =
"Granted permissions: ${state.grantedPermissions.joinToStringByNewLine()}"
binding.textViewDeniedPermissions.text =
"Denied permissions: ${state.deniedPermissions.joinToStringByNewLine()}"
}
private fun List<String>.joinToStringByNewLine(): String {
return joinToString(prefix = "\n", postfix = "\n", separator = ",\n")
}
}
| 6 | null | 21 | 557 | 016837505eb08a388ba15365312636479a4f708e | 3,299 | permission-flow-android | Apache License 2.0 |
src/main/kotlin/org/veupathdb/lib/ldap/LDAP.kt | VEuPathDB | 602,674,566 | false | null | package org.veupathdb.lib.ldap
import com.unboundid.ldap.sdk.*
import org.slf4j.LoggerFactory
class LDAP(private val config: LDAPConfig) {
private val log = LoggerFactory.getLogger(javaClass)
private var ldapConnection: LDAPConnection? = null
init {
if (config.hosts.isEmpty())
throw IllegalArgumentException("Passed the $javaClass constructor a config with 0 hosts entries")
}
fun requireSingularOracleNetDesc(commonName: String): OracleNetDesc {
log.trace("requireSingularOracleNetDesc(commonName={})", commonName)
val tmp = lookupOracleNetDesc(commonName)
if (tmp.isEmpty())
throw IllegalStateException("no OracleNetDescs found for common name $commonName")
if (tmp.size > 1)
throw IllegalStateException("multiple OracleNetDescs found for common name $commonName")
return tmp[0]
}
fun lookupOracleNetDesc(commonName: String): List<OracleNetDesc> {
log.trace("lookupOracleNetDesc(commonName={})", commonName)
return getConnection()
.search(SearchRequest(
config.oracleBaseDN,
SearchScope.SUB,
Filter.createANDFilter(
Filter.create("cn=$commonName"),
Filter.create("objectClass=orclNetService")
),
"orclNetDescString"
))
.searchEntries
.map { OracleNetDesc(it.getAttribute("orclNetDescString").value!!) }
}
private fun getConnection(): LDAPConnection {
log.trace("getConnection()")
// Synchronized because this thing is gonna be called from who knows where.
synchronized(this) {
// If we've already got an LDAP connection
if (ldapConnection != null) {
// If the LDAP connection we've already got is still connected
if (ldapConnection!!.isConnected)
// then return it
return ldapConnection!!
// else, the LDAP connection we've already got is _not_ still connected
else
// then disregard it
ldapConnection = null
}
log.debug("Attempting to establish a connection to a configured LDAP server")
for (host in config.hosts) {
log.trace("Trying to connect to {}:{}", host.host, host.port)
try {
ldapConnection =LDAPConnection(host.host, host.port.toInt())
.also { log.debug("Connected to {}:{}", host.host, host.port) }
break
} catch (e: Throwable) {
log.debug("Failed to connect to {}:{}", host.host, host.port)
}
}
if (ldapConnection == null) {
log.error("Failed to establish a connection to any configured LDAP server.")
throw RuntimeException("Failed to establish a connection to any configured LDAP server.")
}
return ldapConnection!!
}
}
}
| 0 | Kotlin | 0 | 0 | ef64e82eb8a1d05e0da2f5fb306bcbf51435e438 | 2,740 | lib-ldap-util | Apache License 2.0 |
klogic-core/src/main/kotlin/org/klogic/core/Stream.kt | UnitTestBot | 594,002,694 | false | null | package org.klogic.core
/**
* Stream type to represent an infinite sequence of results for a relational query.
*/
sealed interface RecursiveStream<out T> {
/**
* Returns the list of first [n] elements of this stream.
*/
@Suppress("NAME_SHADOWING")
infix fun take(n: Int): List<T> {
val result = mutableListOf<T>()
var n = n
var curStream = this
while (n > 0) {
when (curStream) {
NilStream -> return result
is ThunkStream -> curStream = curStream.elements()
is ConsStream -> {
result += curStream.head
curStream = curStream.tail
--n
}
}
}
return result
}
/**
* Concatenates two streams, the resulting stream contains elements of both input streams in an interleaved order.
*/
infix fun mplus(other: RecursiveStream<@UnsafeVariance T>): RecursiveStream<T>
/**
* Maps function [f] over values of this stream, obtaining a stream of streams, and then flattens this stream.
*/
infix fun <R> bind(f: (T) -> RecursiveStream<R>): RecursiveStream<R>
/**
* Forces calculating elements of this Stream.
*/
fun force(): RecursiveStream<T>
/**
* Splits this stream to head and tail, if possible, and returns null otherwise.
*/
fun msplit(): Pair<T, RecursiveStream<T>>?
operator fun invoke(): RecursiveStream<T> = force()
operator fun plus(head: @UnsafeVariance T): RecursiveStream<T> = ConsStream(head, this)
companion object {
fun <T> nilStream(): RecursiveStream<T> = NilStream
fun <T> emptyStream(): RecursiveStream<T> = nilStream()
fun <T> streamOf(vararg elements: T): RecursiveStream<T> {
if (elements.isEmpty()) {
return NilStream
}
return elements.fold(nilStream()) { acc, e ->
ConsStream(e, acc)
}
}
fun <T> single(element: T): RecursiveStream<T> = ConsStream(element, NilStream)
}
}
/**
* Represents an empty [RecursiveStream].
*/
private object NilStream : RecursiveStream<Nothing> {
override infix fun mplus(other: RecursiveStream<Nothing>): RecursiveStream<Nothing> = other.force()
override infix fun <R> bind(f: (Nothing) -> RecursiveStream<R>): RecursiveStream<R> = NilStream
override fun force(): RecursiveStream<Nothing> = this
override fun msplit(): Pair<Nothing, RecursiveStream<Nothing>>? = null
}
/**
* Represents a [RecursiveStream], consisting of first element [head] and other elements in stream [tail].
*/
data class ConsStream<T>(val head: T, val tail: RecursiveStream<T>) : RecursiveStream<T> {
override infix fun mplus(other: RecursiveStream<@UnsafeVariance T>): RecursiveStream<T> =
ConsStream(head, ThunkStream { other() mplus tail })
override infix fun <R> bind(f: (T) -> RecursiveStream<R>): RecursiveStream<R> =
f(head) mplus ThunkStream { tail() bind f }
override fun force(): RecursiveStream<T> = this
override fun msplit(): Pair<T, RecursiveStream<T>> = head to tail
}
/**
* Represents not already evaluated [RecursiveStream].
*/
@JvmInline
value class ThunkStream<T>(val elements: () -> RecursiveStream<T>) : RecursiveStream<T> {
override infix fun mplus(other: RecursiveStream<@UnsafeVariance T>): RecursiveStream<T> =
ThunkStream { other() mplus this }
override infix fun <R> bind(f: (T) -> RecursiveStream<R>): RecursiveStream<R> = ThunkStream { elements() bind f }
override fun force(): RecursiveStream<T> = elements()
override fun msplit(): Pair<T, RecursiveStream<T>>? = force().msplit()
}
| 3 | Kotlin | 0 | 0 | cf0fd0702f0a571e53b90a9bfd45c999e033f289 | 3,755 | klogic | MIT License |
app/src/main/java/com/a10miaomiao/bilimiao/page/filter/FilterWordListFragment.kt | 10miaomiao | 142,169,120 | false | null | package com.a10miaomiao.bilimiao.page.filter
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import androidx.fragment.app.Fragment
import androidx.lifecycle.coroutineScope
import androidx.navigation.findNavController
import androidx.navigation.fragment.FragmentNavigatorDestinationBuilder
import androidx.recyclerview.widget.LinearLayoutManager
import cn.a10miaomiao.miao.binding.android.view.*
import cn.a10miaomiao.miao.binding.android.widget._text
import cn.a10miaomiao.miao.binding.miaoEffect
import com.a10miaomiao.bilimiao.comm.mypage.MyPage
import com.a10miaomiao.bilimiao.comm.mypage.myMenuItem
import com.a10miaomiao.bilimiao.comm.mypage.myPageConfig
import com.a10miaomiao.bilimiao.comm.mypage.MenuItemPropInfo
import com.a10miaomiao.bilimiao.comm.recycler.*
import com.a10miaomiao.bilimiao.config.config
import com.a10miaomiao.bilimiao.R
import com.a10miaomiao.bilimiao.comm.*
import com.a10miaomiao.bilimiao.comm.mypage.MenuKeys
import com.a10miaomiao.bilimiao.comm.navigation.FragmentNavigatorBuilder
import com.a10miaomiao.bilimiao.store.WindowStore
import com.chad.library.adapter.base.listener.OnItemClickListener
import kotlinx.coroutines.launch
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.instance
import splitties.dimensions.dip
import splitties.views.dsl.core.*
import splitties.views.dsl.recyclerview.recyclerView
import splitties.views.horizontalPadding
import splitties.views.rightPadding
import splitties.views.topPadding
// 屏蔽标题关键字设置
class FilterWordListFragment : Fragment(), DIAware, MyPage {
companion object : FragmentNavigatorBuilder() {
override val name = "filter.word.list"
override fun FragmentNavigatorDestinationBuilder.init() {
deepLink("bilimiao://filter/word/list")
}
}
override val pageConfig = myPageConfig {
title = "屏蔽管理\n-\n关键字"
menus = listOf(
myMenuItem {
key = MenuKeys.add
iconResource = R.drawable.ic_add_white_24dp
title = "添加"
},
myMenuItem {
key = MenuKeys.delete
title = "删除已选"
},
myMenuItem {
key = MenuKeys.select
title = if (viewModel.isSelectAll) {
"全不选"
} else {
"全选"
}
}
)
}
override fun onMenuItemClick(view: View, menuItem: MenuItemPropInfo) {
super.onMenuItemClick(view, menuItem)
when(menuItem.key) {
MenuKeys.add -> {
val nav = requireActivity().findNavController(R.id.nav_bottom_sheet_fragment)
nav.navigate(Uri.parse("bilimiao://filter/word/add"))
}
MenuKeys.delete -> {
viewModel.deleteSelected()
}
MenuKeys.select -> {
if (viewModel.isSelectAll) {
viewModel.unSelectAll()
} else {
viewModel.selectAll()
}
}
}
}
override val di: DI by lazyUiDi(ui = { ui })
private val viewModel by diViewModel<FilterWordListViewModel>(di)
private val windowStore by instance<WindowStore>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ui.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
lifecycle.coroutineScope.launch {
windowStore.connectUi(ui)
}
}
val handleItemClick = OnItemClickListener { adapter, view, position ->
val item = viewModel.list[position]
val nav = requireActivity().findNavController(R.id.nav_bottom_sheet_fragment)
nav.navigate(Uri.parse("bilimiao://filter/word/edit/" + item))
}
val handleCheckedChange = CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
val tag = buttonView.tag
if (tag is String) {
viewModel.selectedChange(tag, isChecked)
pageConfig.notifyConfigChanged()
}
}
val itemUi = miaoBindingItemUi<String> { item, index ->
horizontalLayout {
horizontalPadding = config.pagePadding
topPadding = config.dividerSize
gravity = Gravity.CENTER_VERTICAL
setBackgroundResource(config.selectableItemBackground)
layoutParams = lParams(matchParent, wrapContent)
views {
+checkBox {
rightPadding = config.dividerSize
val isSelected = viewModel.selectedList.contains(item)
miaoEffect(listOf(item, isSelected)) {
tag = item
isChecked = isSelected
}
setOnCheckedChangeListener(handleCheckedChange)
}
+textView {
textSize = 20f
_text = item
}..lParams { weight = 1f }
}
}
}
val ui = miaoBindingUi {
val insets = windowStore.getContentInsets(parentView)
miaoEffect(viewModel.isSelectAll) {
pageConfig.notifyConfigChanged()
}
recyclerView {
_leftPadding = insets.left
_rightPadding = insets.right
// val divide = RecycleViewDivider(context, LinearLayoutManager.VERTICAL, 2, Color.BLUE)
// addItemDecoration(divide)
_miaoLayoutManage(LinearLayoutManager(requireContext()))
val mAdapter = _miaoAdapter(
itemUi = itemUi,
items = viewModel.list,
isForceUpdate = true,
) {
setOnItemClickListener(handleItemClick)
}
headerViews(mAdapter) {
+frameLayout {
_topPadding = insets.top
}
}
footerViews(mAdapter) {
+verticalLayout {
gravity = Gravity.CENTER
_show = viewModel.count == 0
views {
+textView {
text = "空空如也"
gravity = Gravity.CENTER
}
+textView {
text = "去添加关键字"
gravity = Gravity.CENTER
}
}
}..lParams(matchParent, dip(400))
+frameLayout {
_topPadding = insets.bottom
}
}
}
}
} | 5 | null | 38 | 977 | 1d59b82ba30b4c2e83c781479d09c48c3a82cd47 | 6,926 | bilimiao2 | Apache License 2.0 |
android/src/main/java/com/mattermost/pasteinput/PasteInputListener.kt | mattermost | 310,133,680 | false | {"Objective-C": 33511, "TypeScript": 21327, "Kotlin": 21234, "JavaScript": 18959, "Ruby": 2266, "Swift": 1790, "Objective-C++": 657, "C": 104} | package com.mattermost.pasteinput
import android.content.ClipboardManager
import android.content.Context
import android.net.Uri
import android.os.Build
import android.util.Patterns
import android.webkit.MimeTypeMap
import android.webkit.URLUtil
import androidx.annotation.RequiresApi
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
import com.facebook.react.uimanager.events.RCTEventEmitter
import java.io.FileNotFoundException
class PasteInputListener(editText: PasteInputEditText) : IPasteInputListener {
val mEditText = editText
@RequiresApi(Build.VERSION_CODES.KITKAT)
override fun onPaste(itemUri: Uri) {
val reactContext = mEditText.context as ReactContext
val uriMimeType = reactContext.contentResolver.getType(itemUri) ?: return
var uriString: String = itemUri.toString()
var extension: String
var mimeType: String
var fileName: String
var fileSize: Long
var files: WritableArray? = null
var error: WritableMap? = null
// Special handle for Google docs
if (uriString.equals("content://com.google.android.apps.docs.editors.kix.editors.clipboard")) {
val clipboardManager = reactContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clipData = clipboardManager.primaryClip ?: return
val item = clipData.getItemAt(0) ?: return
val htmlText = item.htmlText
// Find uri from html
val matcher = Patterns.WEB_URL.matcher(htmlText)
if (matcher.find()) {
uriString = htmlText.substring(matcher.start(1), matcher.end())
}
} else if (uriString.startsWith("http")) {
val pastImageFromUrlThread = Thread(PasteInputFileFromUrl(reactContext, mEditText, uriString))
pastImageFromUrlThread.start()
return
}
uriString = RealPathUtil.getRealPathFromURI(reactContext, itemUri) ?: return
extension = MimeTypeMap.getFileExtensionFromUrl(uriString) ?: return
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: return
fileName = URLUtil.guessFileName(uriString, null, mimeType)
try {
val contentResolver = reactContext.contentResolver
val assetFileDescriptor = contentResolver.openAssetFileDescriptor(itemUri, "r") ?: return
val file = Arguments.createMap()
files = Arguments.createArray()
fileSize = assetFileDescriptor.length
file.putString("type", mimeType)
file.putDouble("fileSize", fileSize.toDouble())
file.putString("fileName", fileName)
file.putString("uri", "file://$uriString")
files.pushMap(file)
} catch (e: FileNotFoundException) {
error = Arguments.createMap()
error.putString("message", e.localizedMessage)
}
val event = Arguments.createMap()
event.putArray("data", files)
event.putMap("error", error)
reactContext.getJSModule(RCTEventEmitter::class.java)
.receiveEvent(mEditText.id, "onPaste", event)
}
}
| 11 | Objective-C | 15 | 88 | 9e9a193c0928934a29fd4beafe52db4cf6a3c718 | 3,055 | react-native-paste-input | MIT License |
src/main/kotlin/deaktator/ex4/app4.kt | deaktator | 169,763,679 | false | null | package deaktator.ex4
import arrow.Kind
import arrow.core.Option
import arrow.core.fix
import arrow.core.toOption
import arrow.instances.option.monad.monad
import arrow.typeclasses.Monad
import arrow.typeclasses.Semigroup
import arrow.instances.IntContext
import arrow.instances.option.applicative.applicative
import arrow.typeclasses.Applicative
fun main(args: Array<String>) {
val a: Int? = 1
val b: Int? = 2
val oa = a.toOption()
val ob = b.toOption()
val x: Int? =
Option
.monad()
.combineValues(IntContext, oa, ob)
.fix()
.orNull()
val y: Int? =
Option
.applicative()
.combineValues(IntContext, oa, ob)
.fix()
.orNull()
println(x)
println(y)
}
// NOTE: If this function is present, it will be called.
// If it is omitted (commented out), the applicative version will be
// called since Monads are Applicatives.
//
// This shows that resolution works well. The most specialized
// implementation of combineValues will be found.
fun <M, A> Monad<M>.combineValues(s: Semigroup<A>, x: Kind<M, A>, y: Kind<M, A>): Kind<M, A> =
binding {
val a = x.bind()
val b = y.bind()
s.run { a.combine(b) }
}
fun <M, A> Applicative<M>.combineValues(s: Semigroup<A>, x: Kind<M, A>, y: Kind<M, A>): Kind<M, A> =
map(x, y){(a, b) -> s.run { a.combine(b) }}
| 0 | Kotlin | 0 | 0 | 6ee6c534248a2cd397e0e71460687024048da9d4 | 1,524 | learning-kotlin-arrow | Apache License 2.0 |
core/common/src/main/java/com/ariefzuhri/gizee/core/common/util/RecyclerViewUtils.kt | ariefzuhri | 388,739,293 | false | null | package com.ariefzuhri.gizee.core.common.util
import androidx.recyclerview.widget.RecyclerView
fun RecyclerView.Adapter<*>.isNotEmpty(): Boolean {
return itemCount > 0
} | 4 | Kotlin | 4 | 3 | f6a7d8c329cd218e48e928498a64f424eb4b631c | 175 | Gizee | MIT License |
virtualjoystick/src/main/java/com/yoimerdr/android/virtualjoystick/geometry/Plane.kt | yoimerdr | 752,392,779 | false | {"Kotlin": 112504, "CSS": 2645} | package com.yoimerdr.android.virtualjoystick.geometry
import androidx.annotation.FloatRange
import androidx.annotation.IntRange
import kotlin.math.atan2
import kotlin.math.hypot
object Plane {
enum class MaxQuadrants {
FOUR,
EIGHT;
fun toInt(): Int {
return if(this == FOUR) 4
else 8
}
}
/**
* Gets the quadrant of the given angle.
* @param angle The angle (degrees) of the position. Must be positive.
* @param maxQuadrants The max quadrants in the circle.
* @param useMiddle Sets true if you want to use the middle of angle quadrant.
* @return if [maxQuadrants] is [MaxQuadrants.FOUR], a value in the range 1 to 4;
* otherwise, a value in the range 1 to 8.
* @throws IllegalArgumentException If the [angle] is negative.
*/
@JvmStatic
@Throws(IllegalArgumentException::class)
fun quadrantOf(angle: Double, maxQuadrants: MaxQuadrants, useMiddle: Boolean): Int {
if(angle < 0)
throw IllegalArgumentException("The angle must be greater than 0.")
val quadrants = maxQuadrants.toInt()
val angleQuadrant = Circle.DEGREE_SPIN / quadrants
var startAngle = 0.0f
var end = if(useMiddle) angleQuadrant / 2 else angleQuadrant
val mAngle = if(angle > Circle.DEGREE_SPIN) angle.mod(Circle.DEGREE_SPIN) else angle
for(quadrant in 0 .. quadrants) {
if(mAngle in startAngle .. end) {
return if(useMiddle && quadrant == quadrants) 1
else quadrant + 1
}
startAngle = end
end += if(useMiddle && quadrant == quadrants) angleQuadrant / 2
else angleQuadrant
}
return quadrants
}
/**
* Gets the quadrant of the given angle.
* @param angle The angle (degrees) of the position. Must be positive.
* @param maxQuadrants The max quadrants in the circle.
* @return if [maxQuadrants] is [MaxQuadrants.FOUR], a value in the range 1 to 4;
* otherwise, a value in the range 1 to 8.
* @throws IllegalArgumentException If the [angle] is negative.
*/
@JvmStatic
@Throws(IllegalArgumentException::class)
fun quadrantOf(angle: Double, maxQuadrants: MaxQuadrants): Int {
return quadrantOf(angle, maxQuadrants, false)
}
/**
* Gets the quadrant of the given angle.
* @param angle The degree of the position. Must be in range 0 to 360.
* @param useMiddle Sets true if you want to use the middle of angle quadrant.
* @return A value in the range 1 to 4.
* @throws IllegalArgumentException If the [angle] is negative.
*/
@JvmStatic
@IntRange(from = 1, to = 4)
@Throws(IllegalArgumentException::class)
fun quadrantOf(angle: Double, useMiddle: Boolean): Int {
return quadrantOf(angle, MaxQuadrants.FOUR, useMiddle)
}
/**
* Gets the quadrant of the given angle.
* @param angle The degree of the position. Must be in range 0 to 360.
* @return A value in the range 1 to 4.
* @throws IllegalArgumentException If the [angle] is negative.
*/
@JvmStatic
@IntRange(from = 1, to = 4)
@Throws(IllegalArgumentException::class)
fun quadrantOf(angle: Double): Int {
return quadrantOf(angle, false)
}
/**
* Calculates the distance between the given positions.
* @param positionA The position A.
* @param positionB The position B
* @return The distance between the 2 positions.
*/
@JvmStatic
fun distanceBetween(positionA: ImmutablePosition, positionB: ImmutablePosition): Float {
return hypot(positionA.deltaX(positionB), positionA.deltaY(positionB))
}
/**
* Calculates the distance between the given coordinates.
* @param xA The x coordinate of position the A.
* @param yA The y coordinate of position the A.
* @param xB The x coordinate of position the B.
* @param yB The y coordinate of position the B.
* @return The distance between the coordinates.
*/
@JvmStatic
fun distanceBetween(xA: Float, yA: Float, xB: Float, yB: Float): Float {
return hypot(xA - xB, yA - yB)
}
/**
* Calculates the angle between the given positions.
*
* The method use the [Math.atan2] for gets the angle.
* @param positionA The position A.
* @param positionB The position B
* @return A value in the range from 0 to 2PI radians clockwise.
*/
@JvmStatic
@FloatRange(from = 0.0, to = Circle.RADIAN_SPIN)
fun angleBetween(positionA: ImmutablePosition, positionB: ImmutablePosition): Double {
var angle = atan2(positionA.deltaY(positionB), positionA.deltaX(positionB)).toDouble()
if(angle < 0)
angle += Circle.RADIAN_SPIN
return angle
}
/**
* Calculates the angle between the given positions.
*
* The method use the [Math.atan2] for gets the angle.
* @param xA The x coordinate of the position A.
* @param yA The y coordinate of the position A.
* @param xB The x coordinate of the position B.
* @param yB The y coordinate of the position B.
* @see [Plane.angleBetween]
* @return A value in the range from 0 to 2PI radians clockwise.
*/
@JvmStatic
@FloatRange(from = 0.0, to = Circle.RADIAN_SPIN)
fun angleBetween(xA: Float, yA: Float, xB: Float, yB: Float): Double {
return Plane.angleBetween(FixedPosition(xA, yA), FixedPosition(xB, yB))
}
} | 0 | Kotlin | 0 | 0 | 1ede27026dae3058a37b52ce6fc91272441fb601 | 5,535 | AndroidVirtualJoystick | Apache License 2.0 |
android/app/src/main/java/com/eathemeat/easytimer/ui/fragment/DetailFragment.kt | peter12757 | 616,378,789 | false | null | package com.eathemeat.easytimer.ui.fragment
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.eathemeat.easytimer.data.DataManager
import com.eathemeat.easytimer.data.Task
import com.eathemeat.easytimer.data.TimeSegment
import com.eathemeat.easytimer.databinding.FragmentDetailBinding
import com.eathemeat.easytimer.databinding.ItemSegmentListBinding
import com.eathemeat.easytimer.util.TimeUtil
class DetailFragment() : Fragment() {
companion object {
fun newInstance() = DetailFragment()
const val KEY_POS = "pos"
}
private lateinit var viewModel: DetailViewModel
private lateinit var binding:FragmentDetailBinding
lateinit var mTask: Task
lateinit var mLayoutManager:LinearLayoutManager
lateinit var mAdapter:SegmentAdapter
var mSegment:TimeSegment? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDetailBinding.inflate(inflater)
binding.txtName.text = mTask.name
binding.txtDesc.text = mTask.desc
//list
mAdapter = SegmentAdapter(mTask)
mLayoutManager = LinearLayoutManager(context,RecyclerView.VERTICAL,false)
binding.rvSegment.layoutManager = mLayoutManager
binding.rvSegment.adapter = mAdapter
binding.btnStart.setOnCheckedChangeListener { buttonView, isChecked ->
if (isChecked) {
mSegment = TimeSegment(SystemClock.elapsedRealtime(),0,"")
mSegment!!.start()
} else {
mSegment?.let {
it.end()
mTask.timeList.add(it)
DataManager.sIntance.notifyDataChanged(mTask)
mAdapter.notifyDataSetChanged()
}
}
}
viewModel = ViewModelProvider(this).get(DetailViewModel::class.java)
return binding.root
}
override fun setArguments(args: Bundle?) {
super.setArguments(args)
Log.d(TAG, "setArguments() called with: args = $args")
var pos = args!!.getInt(KEY_POS)
mTask = DataManager.sIntance.mTaskList[pos]
}
class SegmentViewHolder(val binding: ItemSegmentListBinding) : RecyclerView.ViewHolder(binding.root) {
}
class SegmentAdapter(var task:Task): RecyclerView.Adapter<SegmentViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SegmentViewHolder {
var itemBinding = ItemSegmentListBinding.inflate(LayoutInflater.from(parent.context))
itemBinding.root.layoutParams = ViewGroup.LayoutParams(
RecyclerView.LayoutParams.MATCH_PARENT,
RecyclerView.LayoutParams.WRAP_CONTENT)
return SegmentViewHolder(itemBinding)
}
override fun onBindViewHolder(holder: SegmentViewHolder, position: Int) {
var segment = task.timeList[position]
holder.binding.txtStartTime.text = TimeUtil.Time2String(segment.startTime)
holder.binding.txtEndTime.text = TimeUtil.Time2String(segment.endTime)
}
override fun getItemCount(): Int {
return task.timeList.size
}
}
} | 0 | Kotlin | 0 | 0 | d06995a2d56a1de7cefc9599bda78255896e1e88 | 3,562 | EasyTimer | Apache License 2.0 |
sample/src/main/kotlin/gtk3/ActionBar.kt | kropp | 91,442,994 | false | null | package gtk3
import kotlin.Unit
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.reinterpret
import libgtk3.GtkActionBar
import libgtk3.GtkWidget
import libgtk3.gtk_action_bar_get_center_widget
import libgtk3.gtk_action_bar_new
import libgtk3.gtk_action_bar_pack_end
import libgtk3.gtk_action_bar_pack_start
import libgtk3.gtk_action_bar_set_center_widget
inline fun Container.actionBar(init: ActionBar.() -> Unit = {}): ActionBar =
ActionBar().apply { init(); [email protected](this) }
/**
* GtkActionBar is designed to present contextual actions. It is
* expected to be displayed below the content and expand horizontally
* to fill the area.
*
* It allows placing children at the start or the end. In addition, it
* contains an internal centered box which is centered with respect to
* the full width of the box, even if the children at either side take
* up different amounts of space.
*
* # CSS nodes
*
* GtkActionBar has a single CSS node with name actionbar.
*/
@GtkDsl
open class ActionBar internal constructor(override val widgetPtr: CPointer<GtkWidget>? = null) :
Bin() {
private val self: CPointer<GtkActionBar>?
get() = widgetPtr!!.reinterpret()
val actionBar: CPointer<GtkActionBar>?
get() = widgetPtr!!.reinterpret()
/**
* Retrieves the center bar widget of the bar.
*
* Sets the center widget for the #GtkActionBar. */
var centerWidget: CPointer<GtkWidget>
get() = gtk_action_bar_get_center_widget(self)!!.reinterpret()
set(value) {
gtk_action_bar_set_center_widget(self, value?.reinterpret())
}
/**
* Creates a new #GtkActionBar widget. */
constructor() : this(gtk_action_bar_new()?.reinterpret())
/**
* Adds @child to @action_bar, packed with reference to the
* end of the @action_bar.
*/
fun packEnd(child: CPointer<GtkWidget>): Unit = gtk_action_bar_pack_end(self, child)
/**
* Adds @child to @action_bar, packed with reference to the
* end of the @action_bar.
*/
fun packEnd(child: Widget): Unit = gtk_action_bar_pack_end(self, child.widgetPtr?.reinterpret())
/**
* Adds @child to @action_bar, packed with reference to the
* start of the @action_bar.
*/
fun packStart(child: CPointer<GtkWidget>): Unit = gtk_action_bar_pack_start(self, child)
/**
* Adds @child to @action_bar, packed with reference to the
* start of the @action_bar.
*/
fun packStart(child: Widget): Unit = gtk_action_bar_pack_start(self,
child.widgetPtr?.reinterpret())
}
| 6 | Kotlin | 12 | 90 | 9609e7ab19064d27f05fc76fccd03139306d0001 | 2,607 | kotlin-native-gtk | Apache License 2.0 |
common/src/main/kotlin/dev/notypie/jwt/utils/CookieProvider.kt | TrulyNotMalware | 705,567,812 | false | {"Kotlin": 20099, "Shell": 421} | package dev.notypie.jwt.utils
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Profile
import org.springframework.http.ResponseCookie
import org.springframework.stereotype.Component
@Component
@Profile("jwt")
class CookieProvider(
@Value("\${jwt.token.refreshTokenExpiredTime}") private val refreshTokenExpiredTime: String
) {
private val log = logger()
fun createRefreshTokenCookie(refreshToken: String): ResponseCookie {
return ResponseCookie.from("refresh-token", refreshToken)
.httpOnly(true)
.secure(true)
.path("/")
.maxAge(this.refreshTokenExpiredTime.toLong())
.build()
}
fun removeRefreshTokenCookie() : ResponseCookie{
return ResponseCookie.from("refresh-token", "")
.maxAge(0)
.path("/")
.build()
}
} | 0 | Kotlin | 0 | 0 | 0ce5c087e3ebd2831fb6082587c20e7e8e26d638 | 906 | Spring-Kotlin-Stack | MIT License |
JetpackCompose/MovieApp/app/src/main/java/com/example/movieapp/widgets/MovieRow.kt | renatobentorocha | 337,590,446 | false | null | package com.example.movieapp.widgets
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.rememberImagePainter
import coil.transform.CircleCropTransformation
import com.example.movieapp.model.Movie
import com.example.movieapp.model.getMovies
@ExperimentalAnimationApi
@Preview
@Composable
fun MovieRow(movie: Movie = getMovies()[0], onClick: (String) -> Unit = {} ) {
var expanded by remember {
mutableStateOf(false)
}
Card(
modifier = Modifier
.padding(4.dp)
.fillMaxWidth()
//.height(130.dp)
.clickable {
onClick(movie.id)
},
shape = RoundedCornerShape(corner = CornerSize(16.dp)),
elevation = 6.dp
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start
) {
Surface(
modifier = Modifier
.padding(12.dp)
.size(100.dp),
shape = RectangleShape,
elevation = 4.dp
) {
Image(
painter = rememberImagePainter(
movie.images[0],
builder = {
crossfade(true)
transformations(CircleCropTransformation())
}
),
contentDescription = "Movie poster"
)
}
Column(
modifier = Modifier.padding(4.dp)
) {
Text(
text = movie.title,
style = MaterialTheme.typography.h6
)
Text(
text = "Director: ${movie.director}",
style = MaterialTheme.typography.caption
)
Text(
text = "Released: ${movie.year}",
style = MaterialTheme.typography.caption
)
AnimatedVisibility(visible = expanded) {
Column {
Text(
buildAnnotatedString {
withStyle(
style = SpanStyle(
color = Color.DarkGray,
fontSize = 13.sp
)
) {
append("Plot: ")
}
withStyle(
style = SpanStyle(
color = Color.DarkGray,
fontSize = 13.sp,
fontWeight = FontWeight.Light
)
) {
append(movie.plot)
}
},
modifier = Modifier.padding(6.dp)
)
Divider()
Text(
text = "Director: ${movie.director}",
style = MaterialTheme.typography.caption
)
Text(
text = "Actors: ${movie.actors}",
style = MaterialTheme.typography.caption
)
Text(
text = "Ratings: ${movie.rating}",
style = MaterialTheme.typography.caption
)
}
}
Icon(
imageVector = if(expanded) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown,
contentDescription = "Arrow Down",
modifier = Modifier
.size(25.dp)
.clickable {
expanded = !expanded
}
)
}
}
}
} | 0 | Kotlin | 0 | 0 | debbc2b725c293ed85ca968cac86296d983fa515 | 5,302 | android | MIT License |
tilbakekreving/domain/src/main/kotlin/tilbakekreving/domain/kravgrunnlag/OppdaterKravgrunnlagCommand.kt | navikt | 227,366,088 | false | {"Kotlin": 9476111, "Shell": 4372, "TSQL": 1233, "Dockerfile": 800} | package tilbakekreving.domain.kravgrunnlag
import no.nav.su.se.bakover.common.CorrelationId
import no.nav.su.se.bakover.common.brukerrolle.Brukerrolle
import no.nav.su.se.bakover.common.ident.NavIdentBruker
import no.nav.su.se.bakover.hendelse.domain.DefaultHendelseMetadata
import no.nav.su.se.bakover.hendelse.domain.Hendelsesversjon
import no.nav.su.se.bakover.hendelse.domain.SakshendelseCommand
import tilbakekreving.domain.TilbakekrevingsbehandlingId
import java.util.UUID
data class OppdaterKravgrunnlagCommand(
override val sakId: UUID,
override val correlationId: CorrelationId?,
override val brukerroller: List<Brukerrolle>,
val oppdatertAv: NavIdentBruker.Saksbehandler,
val behandlingId: TilbakekrevingsbehandlingId,
val klientensSisteSaksversjon: Hendelsesversjon,
) : SakshendelseCommand {
override val utførtAv: NavIdentBruker = oppdatertAv
fun toDefaultHendelsesMetadata() = DefaultHendelseMetadata(
correlationId = correlationId,
ident = this.utførtAv,
brukerroller = brukerroller,
)
}
| 7 | Kotlin | 1 | 1 | 3ce64a0ecce2f1c3cdd68583472e3c4e53e983be | 1,066 | su-se-bakover | MIT License |
AndroidApp/app/src/main/java/com/example/artmaster/adminPanel/AdminPanelActivity.kt | maxtheprogrammer98 | 713,080,646 | false | {"Kotlin": 509369} | package com.example.artmaster.adminPanel
import android.content.Intent
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Icon
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Build
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.rememberScaffoldState
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
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.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.artmaster.MainActivity
import com.example.artmaster.R
import com.example.artmaster.adminPaths.PathsActivity
import com.example.artmaster.adminTutorials.TutorialsActivity
import com.example.artmaster.adminUsers.UsersActivity
import com.example.artmaster.ui.theme.ArtMasterTheme
class AdminPanelActivity: MainActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ArtMasterTheme {
Surface(color = MaterialTheme.colorScheme.background) {
AdminPanelScreen(
navigateToUsers = {
Intent(applicationContext, UsersActivity::class.java).also {
startActivity(it)
}
},
navigateToTutoriales = {
Intent(applicationContext, TutorialsActivity::class.java).also {
startActivity(it)
}
},
navigateToRutas = {
Intent(applicationContext, PathsActivity::class.java).also {
startActivity(it)
}
}
)
}
}
}
}
@Composable
fun AdminPanelScreen(
navigateToUsers: () -> Unit,
navigateToTutoriales: () -> Unit,
navigateToRutas: () -> Unit
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val scaffoldState = rememberScaffoldState()
var multiFloatingState by remember {
mutableStateOf(MultiFloatingState.Collapse)
}
val items = listOf(
MinFabItem(
icon = ImageBitmap.imageResource(id = R.drawable.ic_add_user),
label = "Agregar usuarios",
identifier = Identifier.Users.name
),
MinFabItem(
icon = ImageBitmap.imageResource(id = R.drawable.ic_add_guide),
label = "Agregar tutoriales",
identifier = Identifier.Tutorials.name
),
MinFabItem(
icon = ImageBitmap.imageResource(id = R.drawable.ic_paths),
label = "Agregar rutas",
identifier = Identifier.Paths.name
),
)
Scaffold(
scaffoldState = scaffoldState,
floatingActionButton = {
MultiFloatingButton(
multiFloatingState = multiFloatingState,
onMultiFabStateChange = {
multiFloatingState = it
},
items = items,
context = context
)
},
topBar = {
// Custom top bar from the MainActivity
super.TobBarMain()
},
bottomBar = {
// Custom bottom bar from the MainActivity
super.BottomBar()
},
) { padding ->
// Box to hold the main content and background image
Box(
modifier = Modifier
.fillMaxSize()
) {
Image(
painter = painterResource(id = R.drawable.bg05),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
Column(
modifier = Modifier
.padding(vertical = 42.dp)
.padding(16.dp)
.background(
MaterialTheme.colorScheme.background,
shape = RoundedCornerShape(20.dp)
)
) {
LazyColumn(
modifier = Modifier
.padding(vertical = 16.dp)
.fillMaxWidth()
.background(
color = MaterialTheme.colorScheme.background,
shape = RoundedCornerShape(20.dp)
)
.padding(16.dp),
contentPadding = PaddingValues(16.dp)
) {
item {
AdminCard("Usuarios", Icons.Default.Person, navigateToUsers)
Spacer(modifier = Modifier.height(42.dp))
AdminCard("Tutoriales", Icons.Default.Edit, navigateToTutoriales)
Spacer(modifier = Modifier.height(42.dp))
AdminCard("Rutas", Icons.Default.Build, navigateToRutas)
}
}
}
}
}
}
}
@Composable
fun AdminCard(title: String, icon: ImageVector, onClick: () -> Unit) {
Card(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
) {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(
imageVector = icon,
contentDescription = null,
modifier = Modifier
.size(48.dp)
.padding(8.dp),
tint = MaterialTheme.colorScheme.onBackground
)
Spacer(modifier = Modifier.height(8.dp))
Text(text = title, fontWeight = FontWeight.Bold, fontSize = 16.sp)
}
}
}
| 0 | Kotlin | 0 | 2 | 6b6fd6e7fda8c94f09da5d7411e01af10aa5265a | 8,104 | ArtMaster | Apache License 2.0 |
composeApp/src/commonMain/kotlin/tab/CommunityTab.kt | SaigyoujiNexas | 778,354,892 | false | {"Kotlin": 66853, "Swift": 594} | package tab
import PaddingTab
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.Navigator
import cafe.adriel.voyager.navigator.currentOrThrow
import cafe.adriel.voyager.navigator.tab.TabOptions
import com.mohamedrejeb.richeditor.model.rememberRichTextState
import com.mohamedrejeb.richeditor.ui.material3.RichTextEditor
import community.CommunityEdit
import community.CommunityMain
object CommunityTab: PaddingTab {
@Composable
override fun Content(paddingValues: PaddingValues) {
CommunityMain(paddingValues).Content()
}
override val options: TabOptions
@Composable
get() {
val title = "社区"
val icon = rememberVectorPainter(Icons.Outlined.Person)
return TabOptions(
index = 1u,
title = title,
icon = icon
)
}
} | 0 | Kotlin | 0 | 0 | 69bc9002c3658ec4432b792b2dfa92332f5adf72 | 1,691 | SafeTalk | Apache License 2.0 |
app/src/main/java/cn/animekid/animeswallpaper/ui/ForgetPasswordActivity.kt | Salvatores71 | 267,265,918 | true | {"Kotlin": 93841} | package cn.animekid.animeswallpaper.ui
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import cn.animekid.animeswallpaper.R
import cn.animekid.animeswallpaper.api.Requester
import cn.animekid.animeswallpaper.data.BasicResponse
import cn.animekid.animeswallpaper.utils.ToolsHelper
import kotlinx.android.synthetic.main.forget_password.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class ForgetPasswordActivity: BaseAAppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
forget.setOnClickListener {
val user_email = email.text.toString()
if (TextUtils.isEmpty(user_email) || ToolsHelper.isEmailValid(user_email) != true) {
Toast.makeText(this, "邮箱不能为空或者邮箱格式不正确!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
Toast.makeText(this, "重置链接已发送,请注意查收!", Toast.LENGTH_SHORT).show()
Requester.AuthService().forgetPassword(email = user_email).enqueue(object: Callback<BasicResponse> {
override fun onResponse(call: Call<BasicResponse>, response: Response<BasicResponse>) {
val c = response.body()!!
if (c.code == 200) {
finish()
}
}
override fun onFailure(call: Call<BasicResponse>, t: Throwable) {
Log.d("send_captcha", t.message)
Toast.makeText(this@ForgetPasswordActivity, "发送失败,请稍后再试.", Toast.LENGTH_SHORT).show()
}
})
}
login.setOnClickListener { finish() }
}
override fun getLayoutId(): Int {
return R.layout.forget_password
}
} | 0 | null | 0 | 0 | 162181cf0aee9e80acd138152dc27999ff3a47ce | 1,835 | animes-wallpaper | Apache License 2.0 |
src/models/ConversionRates.kt | Benjiko99 | 319,434,064 | false | null | package models
import java.time.ZonedDateTime
import java.util.*
data class ConversionRates(
val baseCurrency: Currency,
val validityDate: ZonedDateTime,
val rates: List<ConversionRate>
)
| 0 | Kotlin | 0 | 0 | c7fde4869eca547f19e92caaf9f0238261db9451 | 202 | Backend-Sample | The Unlicense |
app/src/main/java/com/revolgenx/anilib/ui/viewmodel/home/discover/ShowCaseViewModel.kt | rev0lgenX | 244,410,204 | false | null | package com.revolgenx.anilib.ui.viewmodel.home.discover
import androidx.lifecycle.LiveData
import androidx.lifecycle.liveData
import com.revolgenx.anilib.data.model.EntryListEditorMediaModel
import com.revolgenx.anilib.infrastructure.repository.util.Resource
import com.revolgenx.anilib.infrastructure.service.media.MediaListEntryService
import com.revolgenx.anilib.ui.viewmodel.BaseViewModel
class ShowCaseViewModel(
private val mediaListEntryService: MediaListEntryService
):BaseViewModel() {
fun saveMediaListEntry(model: EntryListEditorMediaModel): LiveData<Resource<EntryListEditorMediaModel>> {
return liveData {
emit(Resource.loading<EntryListEditorMediaModel>(null))
emitSource(
mediaListEntryService.saveMediaListEntry(
model,
compositeDisposable
))
}
}
}
| 3 | Kotlin | 1 | 24 | 355d2b5510682d869f18e0113453237af8a1f1cc | 880 | AniLib | Apache License 2.0 |
app/src/main/java/com/aliernfrog/pftool/ui/component/AppModalBottomSheet.kt | aliernfrog | 491,592,330 | false | {"Kotlin": 215219} | package com.aliernfrog.pftool.ui.component
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.BottomSheetDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.SheetState
import androidx.compose.material3.SheetValue
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.aliernfrog.pftool.ui.viewmodel.InsetsViewModel
import kotlinx.coroutines.launch
import org.koin.androidx.compose.koinViewModel
/*
// this is not yet used by the app, uncomment when needed
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AppModalBottomSheet(
title: String? = null,
sheetState: SheetState,
sheetScrollState: ScrollState = rememberScrollState(),
dragHandle: @Composable (() -> Unit)? = { BottomSheetDefaults.DragHandle() },
sheetContent: @Composable ColumnScope.() -> Unit
) {
BaseModalBottomSheet(
sheetState = sheetState,
dragHandle = dragHandle
) { bottomPadding ->
Column(
modifier = Modifier
.fillMaxWidth()
.clip(AppBottomSheetShape)
.verticalScroll(sheetScrollState)
.padding(bottom = bottomPadding)
) {
title?.let {
Text(
text = it,
fontSize = 30.sp,
modifier = Modifier.padding(bottom = 8.dp).align(Alignment.CenterHorizontally)
)
}
sheetContent()
}
}
}*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BaseModalBottomSheet(
sheetState: SheetState,
insetsViewModel: InsetsViewModel = koinViewModel(),
dragHandle: @Composable (() -> Unit)? = { BottomSheetDefaults.DragHandle() },
content: @Composable ColumnScope.(bottomPadding: Dp) -> Unit
) {
val scope = rememberCoroutineScope()
if (sheetState.currentValue != SheetValue.Hidden || sheetState.targetValue != SheetValue.Hidden) ModalBottomSheet(
onDismissRequest = { scope.launch {
sheetState.hide()
} },
modifier = Modifier
.padding(top = insetsViewModel.topPadding),
sheetState = sheetState,
dragHandle = dragHandle,
windowInsets = WindowInsets(0.dp)
) {
content(
// Adding top padding since Modifier.padding causes an offset on the bottom sheet
insetsViewModel.topPadding+insetsViewModel.bottomPadding
)
}
}
@Composable
fun SmallDragHandle() {
Box(
modifier = Modifier
.padding(vertical = 8.dp)
.size(32.dp, 4.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f))
)
} | 1 | Kotlin | 0 | 3 | 494f30f4718a52836cbba1b7c183296a2e545f62 | 3,132 | pf-tool | MIT License |
app/src/main/java/com/example/newsapp/AllNewsScreens/SavedScreen.kt | mar19a | 764,483,306 | false | {"Kotlin": 114366} | package com.example.newsapp.AllNewsScreens
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DismissDirection
import androidx.compose.material3.DismissValue
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.SwipeToDismiss
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDismissState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.newsapp.NewsState
import com.example.newsapp.R
import com.example.newsapp.network.Article
import kotlinx.coroutines.launch
import java.time.LocalDateTime
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SavedScreen(state: NewsState, isClicked:(Article) -> Unit, onSwiped:(Article)->Unit) {
if(state.savedNews.isEmpty()){
Column(modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center) {
Text(textAlign = TextAlign.Center, text = "No saved news!",
modifier = Modifier.padding(top = 30.dp),
style = MaterialTheme.typography.headlineLarge,
color = Color.Gray)
}
}
Text(text = "Saved News", modifier = Modifier.padding(10.dp), style = MaterialTheme.typography.headlineLarge)
LazyColumn(modifier = Modifier.padding(top = 50.dp)){
items(items = state.savedNews, key = { article -> article.id!! }) { article->
val stat = rememberDismissState(confirmValueChange = {
if (it == DismissValue.DismissedToStart){
onSwiped(article)
true
}
else{
false
}
})
SwipeToDismiss(state = stat, background = {
val iconScale by animateFloatAsState(
targetValue = if (stat.targetValue == DismissValue.DismissedToStart) 1.3f else 0.8f,
label = ""
)
Box(modifier = Modifier
.padding(vertical = 9.dp, horizontal = 16.dp)
.fillMaxSize()
.background(Color.Transparent, shape = RoundedCornerShape(12.dp))){
Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete",
modifier = Modifier
.align(Alignment.CenterEnd)
.padding(end = 20.dp)
.scale(iconScale))
}
}, dismissContent = {
SavedNewsCard(article = article, isClicked = {
isClicked(it)
})
},directions = setOf(DismissDirection.EndToStart))
}
}
}
@Composable
fun SavedNewsCard(article: Article, isClicked: (Article) -> Unit) {
Card(
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 5.dp)
.fillMaxWidth()
.clickable { isClicked(article) },
shape = RoundedCornerShape(16.dp),
elevation = CardDefaults.elevatedCardElevation(4.dp),
) {
Row(
modifier = Modifier
.fillMaxSize()
.padding(8.dp)
) {
AsyncImage(model = ImageRequest.Builder(context = LocalContext.current)
.data(article.urlToImage)
.crossfade(true)
.build(),
placeholder = painterResource(R.drawable._33_2332677_image_500580_placeholder_transparent),
error = painterResource(R.drawable.nope_not_here),
contentDescription = null,
contentScale= ContentScale.Crop,
modifier = Modifier
.size(120.dp)
.clip(RoundedCornerShape(11.dp)))
Column(
modifier = Modifier
.padding(start = 16.dp)
.fillMaxHeight()
) {
Text(
text = article.title.toString(),
maxLines = 3,
overflow = TextOverflow.Ellipsis,
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.weight(1f))
Text(
text = article.publishedAt.toString(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.secondary
)
}
}
}
} | 0 | Kotlin | 0 | 0 | 157a79b35104a00fd3e5d676e56c97a07d169bcb | 6,698 | NewsApp | MIT License |
app/src/main/java/com/tiixel/periodictableprofessor/presentation/study/model/ElementModel.kt | remiberthoz | 135,941,479 | false | {"Kotlin": 213503} | package com.tiixel.periodictableprofessor.presentation.study.model
import android.graphics.Bitmap
data class ElementModel(
val number: String,
val symbol: String,
val name: String,
val column: Byte,
val row: Byte,
val mnemonicPicture: Bitmap?,
val mnemonicPhrase: String?,
val userNote: String?
) | 0 | Kotlin | 0 | 0 | c9b878171db42d7ed01852f144f32c35acb91816 | 330 | periodic-table-professor | MIT License |
app/src/main/java/com/zeynelerdi/app/security/applocker/ui/newpattern/CreateNewPatternViewModel.kt | ZeynelErdiKarabulut | 318,662,198 | false | null | package com.zeynelerdi.app.security.applocker.ui.newpattern
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.andrognito.patternlockview.PatternLockView
import com.zeynelerdi.app.security.applocker.util.extensions.convertToPatternDot
import com.zeynelerdi.app.security.applocker.data.database.pattern.PatternDao
import com.zeynelerdi.app.security.applocker.data.database.pattern.PatternDotMetadata
import com.zeynelerdi.app.security.applocker.data.database.pattern.PatternEntity
import com.zeynelerdi.app.security.applocker.ui.RxAwareViewModel
import com.zeynelerdi.app.security.applocker.util.extensions.doOnBackground
import com.zeynelerdi.app.security.applocker.util.helper.PatternChecker
import javax.inject.Inject
class CreateNewPatternViewModel @Inject constructor(val patternDao: PatternDao) : RxAwareViewModel() {
enum class PatternEvent {
INITIALIZE, FIRST_COMPLETED, SECOND_COMPLETED, ERROR
}
private val patternEventLiveData = MutableLiveData<CreateNewPatternViewState>().apply {
value = CreateNewPatternViewState(PatternEvent.INITIALIZE)
}
private var firstDrawedPattern: ArrayList<PatternLockView.Dot> = arrayListOf()
private var redrawedPattern: ArrayList<PatternLockView.Dot> = arrayListOf()
fun getPatternEventLiveData(): LiveData<CreateNewPatternViewState> = patternEventLiveData
fun setFirstDrawedPattern(pattern: List<PatternLockView.Dot>?) {
pattern?.let {
this.firstDrawedPattern.clear()
this.firstDrawedPattern.addAll(pattern)
patternEventLiveData.value = CreateNewPatternViewState(PatternEvent.FIRST_COMPLETED)
}
}
fun setRedrawnPattern(pattern: List<PatternLockView.Dot>?) {
pattern?.let {
this.redrawedPattern.clear()
this.redrawedPattern.addAll(pattern)
if (PatternChecker.checkPatternsEqual(
firstDrawedPattern.convertToPatternDot(),
redrawedPattern.convertToPatternDot()
)
) {
saveNewCreatedPattern(firstDrawedPattern)
patternEventLiveData.value = CreateNewPatternViewState(PatternEvent.SECOND_COMPLETED)
} else {
firstDrawedPattern.clear()
redrawedPattern.clear()
patternEventLiveData.value = CreateNewPatternViewState(PatternEvent.ERROR)
}
}
}
fun isFirstPattern(): Boolean = firstDrawedPattern.isEmpty()
private fun saveNewCreatedPattern(pattern: List<PatternLockView.Dot>){
doOnBackground {
val patternMetadata = PatternDotMetadata(pattern.convertToPatternDot())
val patternEntity = PatternEntity(patternMetadata)
patternDao.createPattern(patternEntity)
}
}
} | 0 | Kotlin | 1 | 1 | 6261f2e048aff0586e5aac1293cd84070b87b12e | 2,839 | AppLocker | Apache License 2.0 |
app/src/main/java/net/hwyz/iov/ui/page/login/LoginViewModel.kt | hwyzleo | 649,753,962 | false | null | package net.hwyz.iov.ui.page.login
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import net.hwyz.iov.base.presentation.BaseViewModel
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(
override val actionProcessor: LoginProcessor
) : BaseViewModel<LoginIntent, LoginState, LoginAction, LoginResult>() {
var viewStates by mutableStateOf(LoginState())
private val _viewEvents = Channel<LoginViewEvent>(Channel.BUFFERED)
val viewEvents = _viewEvents.receiveAsFlow()
fun dispatch(intent: LoginIntent) {
var action = actionFromIntent(intent)
viewModelScope.launch {
flow {
var result = actionProcessor.executeAction(action)
emit(reducer(result))
}.collect()
}
}
override fun actionFromIntent(intent: LoginIntent): LoginAction {
return when (intent) {
is LoginIntent.InitIntent -> TODO()
is LoginIntent.SelectCountryRegionIntent -> LoginAction.SelectCountryRegionAction(intent.countryRegionCode)
is LoginIntent.UpdateMobileIntent -> LoginAction.UpdateMobileAction(intent.mobile)
is LoginIntent.ClearMobileIntent -> LoginAction.ClearMobileAction
is LoginIntent.UpdateAgreeIntent -> TODO()
is LoginIntent.SendVerifyCodeIntent -> LoginAction.SendVerifyCodeAction(
intent.countryRegionCode,
viewStates.mobile
)
is LoginIntent.UpdateVerifyCodeIntent -> LoginAction.UpdateVerifyCodeAction(intent.verifyCode)
is LoginIntent.ClearVerifyCodeIntent -> LoginAction.ClearVerifyCodeAction
is LoginIntent.VerifyCodeLoginIntent -> LoginAction.VerifyCodeLoginAction(
viewStates.countryRegionCode,
viewStates.mobile,
viewStates.verifyCode
)
}
}
override suspend fun reducer(result: LoginResult) {
when (result) {
is LoginResult.InitResult -> TODO()
is LoginResult.SelectCountryRegionResult -> updateCountryRegion(result.countryRegionCode)
is LoginResult.UpdateMobileResult -> updateMobile(result.mobile)
is LoginResult.ClearMobileResult -> clearMobile()
is LoginResult.SendVerifyCodeResult.Success -> sendVerifyCodeSuccess(result.countryRegionCode, result.mobile)
is LoginResult.SendVerifyCodeResult.Failure -> sendVerifyCodeFailure(
result.error.message ?: ""
)
is LoginResult.UpdateVerifyCodeResult -> updateVerifyCode(result.verifyCode)
is LoginResult.ClearVerifyCodeResult -> clearVerifyCode()
is LoginResult.VerifyCodeLoginResult.Success -> verifyCodeLoginSuccess()
is LoginResult.VerifyCodeLoginResult.Failure -> verifyCodeLoginFailure(
result.error.message ?: ""
)
}
}
private fun updateCountryRegion(countryRegionCode: String) {
viewStates = viewStates.copy(countryRegionCode = countryRegionCode)
}
private fun updateMobile(mobile: String) {
viewStates = viewStates.copy(mobile = mobile)
}
private fun clearMobile() {
viewStates = viewStates.copy(mobile = "")
}
private fun updateAgree(isAgree: Boolean) {
viewStates = viewStates.copy(isAgree = isAgree)
}
private fun sendVerifyCodeSuccess(countryRegionCode: String, mobile: String) {
viewStates = viewStates.copy(
isSendVerifyCode = true,
countryRegionCode = countryRegionCode,
mobile = mobile
)
}
private suspend fun sendVerifyCodeFailure(error: String) {
_viewEvents.send(LoginViewEvent.ErrorMessage(error))
}
private fun updateVerifyCode(verifyCode: String) {
viewStates = viewStates.copy(verifyCode = verifyCode)
}
private fun clearVerifyCode() {
viewStates = viewStates.copy(verifyCode = "")
}
private suspend fun verifyCodeLoginSuccess() {
viewStates = viewStates.copy(isLogged = true)
_viewEvents.send(LoginViewEvent.PopBack)
}
private suspend fun verifyCodeLoginFailure(error: String) {
_viewEvents.send(LoginViewEvent.ErrorMessage(error))
}
}
/**
* 一次性事件
*/
sealed class LoginViewEvent {
object PopBack : LoginViewEvent()
data class ErrorMessage(val message: String) : LoginViewEvent()
} | 0 | Kotlin | 0 | 0 | 7f67e8e7bb747a0e1f807ea7251fd30b54634775 | 4,818 | iov-android-app | Apache License 2.0 |
app/src/main/java/com/bluerayfsm/features/nearbyshops/presentation/ShopStatusListner.kt | DebashisINT | 772,059,684 | false | {"Kotlin": 14146263, "Java": 1002625} | package com.bluerayfsm.features.nearbyshops.presentation
interface ShopStatusListner {
fun getStatusInfoOnLick(pos:String)
} | 0 | Kotlin | 0 | 0 | 875bc5a3927897d1daa465a4f122c35df513a7ec | 131 | BluerayFSM | Apache License 2.0 |
ComposeAdvanced/app/src/main/java/com/example/android/wearable/composeadvanced/presentation/ui/theme/ThemeScreen.kt | android | 192,007,253 | false | null | /*
* Copyright 2022 The Android Open Source Project
*
* 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 com.example.android.wearable.composeadvanced.presentation.ui.theme
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.wear.compose.material.Colors
import androidx.wear.compose.material.ListHeader
import androidx.wear.compose.material.RadioButton
import androidx.wear.compose.material.ScalingLazyColumn
import androidx.wear.compose.material.ScalingLazyListState
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.ToggleChip
import androidx.wear.compose.material.ToggleChipDefaults
import com.example.android.wearable.composeadvanced.presentation.theme.ThemeValues
import com.google.android.horologist.compose.navscaffold.scrollableColumn
@Composable
internal fun ThemeScreen(
scalingLazyListState: ScalingLazyListState,
focusRequester: FocusRequester,
currentlySelectedColors: Colors,
availableThemes: List<ThemeValues>,
onValueChange: (Colors) -> Unit
) {
ScalingLazyColumn(
modifier = Modifier.scrollableColumn(focusRequester, scalingLazyListState),
state = scalingLazyListState
) {
item {
ListHeader {
Text("Color Schemes")
}
}
for (listItem in availableThemes) {
val checked = listItem.colors == currentlySelectedColors
item {
ToggleChip(
checked = checked,
toggleControl = {
RadioButton(
selected = checked,
modifier = Modifier.semantics {
this.contentDescription = if (checked) "On" else "Off"
}
)
},
onCheckedChange = { onValueChange(listItem.colors) },
// Override the default toggle control color to show the user the current
// primary selected color.
colors = ToggleChipDefaults.toggleChipColors(
checkedToggleControlColor = currentlySelectedColors.primary
),
label = {
Text(listItem.description)
},
modifier = Modifier.fillMaxWidth()
)
}
}
}
}
| 23 | Kotlin | 522 | 859 | 239d62e376dbd23266b2e9558b71937f0a1546c5 | 3,181 | wear-os-samples | Apache License 2.0 |
src/main/kotlin/no/nav/tiltaksarrangor/service/NavAnsattService.kt | navikt | 616,496,742 | false | {"Kotlin": 565964, "PLpgSQL": 635, "Dockerfile": 161} | package no.nav.tiltaksarrangor.service
import no.nav.tiltaksarrangor.client.amtperson.AmtPersonClient
import no.nav.tiltaksarrangor.client.amtperson.NavAnsattResponse
import no.nav.tiltaksarrangor.ingest.model.NavAnsatt
import no.nav.tiltaksarrangor.model.DeltakerHistorikk
import no.nav.tiltaksarrangor.repositories.NavAnsattRepository
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.util.UUID
@Service
class NavAnsattService(
private val repository: NavAnsattRepository,
private val amtPersonClient: AmtPersonClient,
) {
private val log = LoggerFactory.getLogger(javaClass)
fun hentEllerOpprettNavAnsatt(id: UUID): NavAnsatt {
repository
.get(id)
?.let { return it }
log.info("Fant ikke oppdatert nav-ansatt med nummer $id, henter fra amt-person-service")
return fetchNavAnsatt(id)
}
private fun fetchNavAnsatt(id: UUID): NavAnsatt {
val navAnsatt = amtPersonClient.hentNavAnsatt(id).toModel()
repository.upsert(navAnsatt)
log.info("Lagret nav-ansatt $id")
return navAnsatt
}
fun upsert(navAnsatt: NavAnsatt) {
repository.upsert(navAnsatt)
log.info("Lagret nav-ansatt med id ${navAnsatt.id}")
}
fun hentAnsatteForHistorikk(historikk: List<DeltakerHistorikk>): Map<UUID, NavAnsatt> {
val ider = historikk.flatMap { it.navAnsatte() }.distinct()
return hentAnsatte(ider)
}
private fun hentAnsatte(veilederIder: List<UUID>) = repository.getMany(veilederIder).associateBy { it.id }
}
fun NavAnsattResponse.toModel() = NavAnsatt(
id = id,
navident = navIdent,
navn = navn,
epost = epost,
telefon = telefon,
)
| 0 | Kotlin | 0 | 1 | f42ef5c00d6204169517f4f201f9d0cdbfcba6e0 | 1,602 | amt-tiltaksarrangor-bff | MIT License |
app/src/main/java/com/zhong/cardinals/sample/mode/PasswordLogin.kt | zhonglikui | 98,945,750 | false | null | package com.zhong.cardinals.sample.mode
/**
* Created by zhong on 2017/3/28.
*/
class PasswordLogin {
var phone: String? = null
var regionCode: String? = null
var password: String? = null
}
| 0 | Java | 0 | 56 | bd56c4e8c143563d5fc23a3b63b6547dcd291cee | 207 | cardinals | Apache License 2.0 |
app/app/src/main/kotlin/tech/nagual/phoenix/tools/gps/RestarterReceiver.kt | overphoenix | 621,371,055 | false | null | package tech.nagual.phoenix.tools.gps
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.content.ContextCompat
import tech.nagual.phoenix.tools.gps.common.IntentConstants
class RestarterReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val wasRunning = intent.getBooleanExtra("was_running", false)
val serviceIntent = Intent(context, GpsService::class.java)
if (wasRunning) {
serviceIntent.putExtra(IntentConstants.IMMEDIATE_START, true)
} else {
serviceIntent.putExtra(IntentConstants.IMMEDIATE_STOP, true)
}
ContextCompat.startForegroundService(context, serviceIntent)
}
} | 0 | Kotlin | 0 | 0 | 64264f261c2138d5f1932789702661917bbfae28 | 770 | phoenix-android | Apache License 2.0 |
tibiakt-core/src/main/kotlin/com/galarzaa/tibiakt/core/models/bazaar/BazaarFilters.kt | Galarzaa90 | 285,669,589 | false | null | /*
* Copyright © 2022 <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 com.galarzaa.tibiakt.core.models.bazaar
import com.galarzaa.tibiakt.core.enums.AuctionBattlEyeFilter
import com.galarzaa.tibiakt.core.enums.AuctionOrderBy
import com.galarzaa.tibiakt.core.enums.AuctionOrderDirection
import com.galarzaa.tibiakt.core.enums.AuctionSearchType
import com.galarzaa.tibiakt.core.enums.AuctionSkillFilter
import com.galarzaa.tibiakt.core.enums.AuctionVocationFilter
import com.galarzaa.tibiakt.core.enums.PvpType
import kotlinx.serialization.Serializable
/**
* Filtering parameters for the [CharacterBazaar]
*
* All values are optional, only set values are considered when filtering.
*
* @property world Only show auctions of characters of this world.
* @property pvpType Only show auctions of characters in worlds with this PvP type.
* @property battlEyeType Only show auctions of characters in worlds with this BattlEye type.
* @property vocation Only show auctions of characters of this vocation, including promoted vocations.
* @property minimumLevel Only show characters above this level.
* @property maximumLevel Only show characters below this level.
* @property skill The skill to use for filtering by [minimumSkillLevel] and [maximumSkillLevel].
* @property minimumSkillLevel Only show characters with a level on the selected [skill] above this.
* @property maximumSkillLevel Only show characters with a level on the selected [skill] below this.
* @property orderDirection The ordering direction for the results.
* @property orderBy The column or value to order by.
* @property searchString The string used to search based on the [searchType].
* @property searchType The type of search to perform.
*/
@Serializable
public data class BazaarFilters(
val world: String? = null,
val pvpType: PvpType? = null,
val battlEyeType: AuctionBattlEyeFilter? = null,
val vocation: AuctionVocationFilter? = null,
val minimumLevel: Int? = null,
val maximumLevel: Int? = null,
val skill: AuctionSkillFilter? = null,
val minimumSkillLevel: Int? = null,
val maximumSkillLevel: Int? = null,
val orderDirection: AuctionOrderDirection? = null,
val orderBy: AuctionOrderBy? = null,
val searchString: String? = null,
val searchType: AuctionSearchType? = null,
)
| 0 | Kotlin | 1 | 1 | 5b995f40e64684ec2de505469c36fc27c8c61576 | 2,847 | TibiaKt | Apache License 2.0 |
buildLogic/serenador-plugin/src/main/kotlin/io/github/thanosfisherman/serenador/listeners/MyBuildListener.kt | ThanosFisherman | 436,064,516 | false | null | package io.github.thanosfisherman.serenador.listeners
import io.github.thanosfisherman.serenador.commandexecutors.CommandExecutor
import io.github.thanosfisherman.serenador.extensions.SerenadorExtension
import io.github.thanosfisherman.serenador.repositories.PhraseRepo
import org.gradle.BuildListener
import org.gradle.BuildResult
import org.gradle.api.initialization.Settings
import org.gradle.api.invocation.Gradle
class MyBuildListener constructor(
private val commandExecutor: CommandExecutor,
private val phraseRepo: PhraseRepo,
private val serenadorExt: SerenadorExtension
) : BuildListener {
override fun settingsEvaluated(settings: Settings) {
}
override fun projectsLoaded(gradle: Gradle) {
}
override fun projectsEvaluated(gradle: Gradle) {
}
override fun buildFinished(result: BuildResult) {
if (result.failure != null) {
customOrDefault(serenadorExt.phraseBook.failPhrases, true, commandExecutor)
} else {
customOrDefault(serenadorExt.phraseBook.successPhrases, false, commandExecutor)
}
}
private fun customOrDefault(phrases: List<String>, isFail: Boolean, executor: CommandExecutor) {
if (phrases.isEmpty() && isFail) {
val result = executor.execute(phraseRepo.getFailPhrasesWithVoice().random())
if (result.exitValue == 1) {
executor.execute(phraseRepo.getFailPhrases().random())
}
} else if (phrases.isEmpty()) {
val result = executor.execute(phraseRepo.getSuccessPhrasesWithVoice().random())
if (result.exitValue == 1) {
executor.execute(phraseRepo.getSuccessPhrases().random())
}
} else {
executor.execute(phraseRepo.getCustomPhrases(phrases).random())
}
}
}
| 0 | Kotlin | 1 | 7 | 51efb7298af45a3e42e4b899ce0be42323fac294 | 1,833 | serenador | Apache License 2.0 |
library/src/main/java/com/kernel/colibri/core/strategy/Monkey.kt | kernel0x | 199,272,056 | false | null | package com.kernel.colibri.core.strategy
import com.kernel.colibri.core.models.Screen
class Monkey : DepthFirst() {
override fun handleCurrentScreen(currentScreen: Screen) {
super.handleCurrentScreen(currentScreen)
currentScreen.elementsList.shuffle()
}
} | 0 | Kotlin | 0 | 9 | 7e91341238549b41a5bb710e6706f3d3e2b16b51 | 281 | colibri | Apache License 2.0 |
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/TaxiAlertRounded.kt | karakum-team | 387,062,541 | false | {"Kotlin": 3059969, "TypeScript": 2249, "HTML": 724, "CSS": 86} | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/TaxiAlertRounded")
package mui.icons.material
@JsName("default")
external val TaxiAlertRounded: SvgIconComponent
| 0 | Kotlin | 5 | 35 | 45ca2eabf1d75a64ab7454fa62a641221ec0aa25 | 196 | mui-kotlin | Apache License 2.0 |
rekoil/src/main/kotlin/tech/muso/rekoil/core/RekoilScopeImpl.kt | musotec | 272,858,232 | false | null | package tech.muso.rekoil.core
import kotlinx.coroutines.CoroutineScope
open class SupervisorScopeImpl(
val parent: RekoilContext?,
rootNode: RekoilContext.Node,
val coroutineScope: CoroutineScope
) : RekoilScope {
// allow for the nodes within this scope to be watched, so that we can invalidate them
internal val _rekoil: SupervisorRekoilContextImpl = SupervisorRekoilContextImpl(parent, rootNode)
// FIXME: this can probably be private/internal.
override val rekoilContext: RekoilContext
get() = _rekoil
override fun <R : Any> atom(
coroutineScope: CoroutineScope,
key: RekoilContext.Key<Atom<R>>?,
isAsync: Boolean,
cache: Boolean,
value: () -> R
): Atom<R> {
return _rekoil.Atom(coroutineScope, value)
}
override fun <R> selector(
scope: CoroutineScope,
key: RekoilContext.Key<Selector<R>>?,
value: suspend SelectorScope.() -> R
): Selector<R?> {
return _rekoil.Selector(parent ?: _rekoil, scope, value)
}
override fun <R> withScope(
borrowedRekoilScope: RekoilScope,
coroutineScope: CoroutineScope,
key: RekoilContext.Key<Selector<R>>?,
value: suspend SelectorScope.() -> R
): Selector<R?> {
// TODO: FIXME: the passed parent context should be the joined context.
// create selector that has the passed scope as it's official parent
return borrowedRekoilScope.selector(coroutineScope, key, value)
.also {
// but also register the node with the context it was created in.
_rekoil.register(it)
}
}
override fun releaseScope() {
_rekoil.releaseScope()
}
}
/**
* Create a RekoilScope with a new RootRekoilNode.
*
* The root node is used for bookkeeping across all suspended coroutines in the scope.
*/
internal open class RekoilScopeImpl(
coroutineScope: CoroutineScope
) : SupervisorScopeImpl(null, RootRekoilNode(coroutineScope), coroutineScope)
/**
* Create a Selector (child) scope, which also extends the [ValueNode] to hold its data.
*/
internal abstract class SelectorRekoilScopeImpl<T>(
private val parent: RekoilContext,
private val rootNode: RekoilContext.Node,
coroutineScope: CoroutineScope
) : ValueNodeImpl<T>(coroutineScope),
RekoilScope by SupervisorScopeImpl(parent, rootNode, coroutineScope),
RekoilContext.ValueNode<T> {
// override fun <R> selector(
// coroutineScope: CoroutineScope,
// key: RekoilContext.Key<Selector<R>>?,
// value: suspend SelectorScope.() -> R
// ): Selector<R?> {
// return _rekoil.Selector(parent, coroutineScope, value)
// }
//
// override fun <R> withScope(
// rekoilScope: RekoilScope,
// coroutineScope: CoroutineScope,
// key: RekoilContext.Key<Selector<R>>?,
// value: suspend SelectorScope.() -> R
// ): Selector<R?> {
// return _rekoil.Selector(rekoilScope.rekoilContext, coroutineScope, value)
// .also {
// // also register the node with the context it was created in.
// _rekoil.register(it)
// }
// }
} | 0 | Kotlin | 0 | 4 | 43976b5e992ed60aa46cfcb9ebef9c968b20e112 | 3,347 | rekoil | Apache License 2.0 |
src/main/kotlin/org/tty/dailyset/dailyset_cloud/bean/resp/TicketInfoResp.kt | h1542462994 | 482,193,075 | false | null | package org.tty.dailyset.dailyset_cloud.bean.resp
import org.tty.dailyset.dailyset_cloud.bean.enums.TicketStatus
class TicketInfoResp(
val status: TicketStatus,
val uid: String,
val departmentName: String,
val className: String,
val name: String,
val grade: Int
) | 0 | Kotlin | 0 | 0 | e3fe192c227da0c0a7c18c8bf3a2cd42a0de4e14 | 289 | dailyset_cloud | MIT License |
app/src/main/java/com/example/listadapterdraganddropapplication/MyItemTouchHelperCallback.kt | ExpensiveBelly | 202,797,380 | false | null | package com.example.listadapterdraganddropapplication
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
open class MyItemTouchHelperCallback(
dragDirs: Int = 0,
private val dragCallback: (Int, Int) -> Unit = { _, _ -> }
) : ItemTouchHelper.SimpleCallback(dragDirs, 0) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
val from = viewHolder.adapterPosition
val to = target.adapterPosition
dragCallback(from, to)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}
override fun isLongPressDragEnabled() = true
} | 0 | Kotlin | 0 | 1 | 7276bb2b29d0a95c8b55cd6fab71e53dcf5ede29 | 774 | ListAdapterDragAndDropApplication | MIT License |
app/src/main/java/com/tripod/durust/domain/repositories/GeminiChatRepo.kt | HemangMishra1234 | 810,640,873 | false | {"Kotlin": 551569} | package com.tripod.durust.domain.repositories
import android.util.Log
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.tripod.durust.presentation.chats.data.BotComponent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext
class GeminiChatRepository(private val auth: FirebaseAuth) {
private val db = FirebaseFirestore.getInstance()
suspend fun uploadChatData(chatData: BotComponent): Boolean {
if(auth.currentUser == null) {
Log.e("GeminiChatRepository", "Error uploading chat data: uid mismatch")
return false
}
return withContext(Dispatchers.IO) {
try {
db.collection("users")
.document(auth.currentUser!!.uid)
.collection("chats")
.document("chatData")
.set(chatData)
.await()
true
} catch (e: Exception) {
Log.e("GeminiChatRepository", "Error uploading chat data", e)
false
}
}
}
suspend fun fetchChatData(): BotComponent? {
if(auth.currentUser == null) {
Log.e("GeminiChatRepository", "Error fetching chat data: uid mismatch")
return null
}
return withContext(Dispatchers.IO) {
try {
val document = db.collection("users")
.document(auth.currentUser!!.uid)
.collection("chats")
.document("chatData")
.get()
.await()
document.toObject(BotComponent::class.java)
} catch (e: Exception) {
Log.e("GeminiChatRepository", "Error fetching chat data", e)
null
}
}
}
} | 0 | Kotlin | 0 | 0 | d0ee78699dbb05b7fbaec487962f756798b26dd3 | 1,924 | Durust | Apache License 2.0 |
halopinview/src/main/java/com/halilozcan/halopinlib/PinItem.kt | halilozcan | 319,462,739 | false | null | package com.halilozcan.halopinlib
import com.halilozcan.halopinlib.HaloPinView.Companion.EMPTY_PLACE_HOLDER
// Code with ❤
//┌─────────────────────────────┐
//│ Created by <NAME> │
//│ ─────────────────────────── │
//│ <EMAIL> │
//│ ─────────────────────────── │
//│ 12/7/20 │
//└─────────────────────────────┘
data class PinItem(val pin: String = EMPTY_PLACE_HOLDER, val isEntered: Boolean = false) | 0 | Kotlin | 0 | 17 | a943ec1e3eb62409bd36821271db078218caba90 | 436 | HaloPinView | Apache License 2.0 |
app/src/main/java/com/example/moviecompose/ui/series/seasonDetail/SeasonDetailScreen.kt | Rohit-2602 | 437,358,869 | false | {"Kotlin": 166198} | package com.example.moviecompose.ui.series.seasonDetail
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.rememberImagePainter
import com.example.moviecompose.model.network.Episode
import com.example.moviecompose.network.MovieDBApi
import com.example.moviecompose.ui.RetrySection
@Composable
fun SeasonDetailScreen(
seriesId: Int,
seriesName: String,
seasonNumber: Int,
viewModel: SeasonDetailViewModel = hiltViewModel()
) {
val season by remember {
viewModel.getSeasonDetails(seriesId = seriesId, seasonNumber = seasonNumber)
}
val isLoading by remember {
viewModel.isLoading
}
val loadError by remember {
viewModel.loadError
}
Surface(modifier = Modifier.fillMaxSize()) {
if (loadError.isNotEmpty()) {
RetrySection(error = loadError) {
viewModel.getSeasonDetails(seriesId = seriesId, seasonNumber = seasonNumber)
}
}
if (isLoading) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator()
}
}
if (!isLoading && loadError.isEmpty() && season != null) {
LazyColumn {
item {
val posterImage =
rememberImagePainter(data = MovieDBApi.getPosterPath(season!!.poster_path),
builder = {
size(240)
})
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = posterImage,
contentDescription = "Season Poster",
modifier = Modifier.size(240.dp)
)
Text(
text = seriesName,
style = TextStyle(
color = Color.White,
fontWeight = FontWeight.Bold,
fontSize = 20.sp
)
)
Text(
text = "Season $seasonNumber",
style = TextStyle(
color = Color.Gray,
fontSize = 16.sp
)
)
}
}
item {
Text(
text = "Episodes",
style = TextStyle(
color = Color.White,
fontWeight = FontWeight.Bold,
fontSize = 20.sp
),
modifier = Modifier.padding(10.dp)
)
}
items(season!!.episodes.size) {
Episode(episode = season!!.episodes[it], index = it)
}
}
}
}
}
@Composable
fun Episode(episode: Episode, index: Int) {
val painter =
rememberImagePainter(data = MovieDBApi.getPosterPath(episode.still_path))
Row(
modifier = Modifier
.padding(bottom = 10.dp, start = 10.dp, end = 10.dp)
.shadow(5.dp, RoundedCornerShape(5.dp))
.clip(RoundedCornerShape(5.dp))
.background(MaterialTheme.colors.background)
) {
Image(
painter = painter,
contentDescription = "Episode Image",
modifier = Modifier
.width(160.dp)
.height(90.dp)
.fillMaxHeight()
.shadow(5.dp, RoundedCornerShape(5.dp))
.clip(RoundedCornerShape(5.dp))
)
Column {
Text(
text = "Episode ${index + 1}",
style = TextStyle(
color = Color.Gray,
fontSize = 12.sp,
),
modifier = Modifier.padding(start = 10.dp)
)
Text(
text = episode.name,
style = TextStyle(
color = Color.White,
fontSize = 15.sp,
fontWeight = FontWeight.Bold
),
modifier = Modifier.padding(start = 10.dp)
)
Text(
text = episode.overview,
style = TextStyle(
color = Color.Gray,
fontSize = 13.sp
),
maxLines = 2,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(start = 10.dp)
)
}
}
} | 0 | Kotlin | 1 | 5 | 33c8ab83be812338cd4c7464a89a2e613e5621e7 | 5,873 | Movie-Compose | Apache License 2.0 |
base/base-common-android/src/main/java/dev/dexsr/klio/base/theme/md3/compose/shape/Shape.kt | flammky | 462,795,948 | false | {"Kotlin": 5222947} | package dev.dexsr.klio.base.theme.md3.compose.shape
import androidx.compose.foundation.shape.RoundedCornerShape as ComposeRoundedCornerShape
import dev.dexsr.klio.base.theme.shape.RoundedCornerShape as ThemeRoundedCornerShape
fun ThemeRoundedCornerShape.toComposeShape(): ComposeRoundedCornerShape {
return ComposeRoundedCornerShape(
topStart = topLeft,
topEnd = topRight,
bottomStart = bottomLeft,
bottomEnd = bottomRight
)
}
| 0 | Kotlin | 6 | 56 | a452c453815851257462623be704559d306fb383 | 439 | Music-Player | Apache License 2.0 |
webscripts/src/main/kotlin/com/github/dynamicextensionsalfresco/webscripts/AnnotationWebScriptRequest.kt | yregaieg | 96,100,822 | true | {"Gradle": 12, "INI": 4, "Shell": 1, "Text": 6, "Ignore List": 1, "YAML": 1, "Markdown": 1, "Java": 277, "XML": 34, "Kotlin": 39, "Java Properties": 3, "JavaScript": 6, "CSS": 5, "FreeMarker": 6, "Fluent": 4, "Groovy": 10} | package com.github.dynamicextensionsalfresco.webscripts
import org.springframework.extensions.webscripts.WebScriptRequest
import org.springframework.extensions.webscripts.WrappingWebScriptRequest
import java.util.LinkedHashMap
public class AnnotationWebScriptRequest(val webScriptRequest: WebScriptRequest) : WebScriptRequest by webScriptRequest, WrappingWebScriptRequest {
override fun toString(): String {
return next.toString()
}
public val model: MutableMap<String, Any> = LinkedHashMap()
public var thrownException: Throwable? = null
set
override fun getNext(): WebScriptRequest {
if (webScriptRequest is WrappingWebScriptRequest) {
return webScriptRequest.next
} else {
return webScriptRequest
}
}
}
| 0 | Java | 0 | 0 | fbebab021dee67bd59e06c12f088013a5e23f548 | 799 | dynamic-extensions-for-alfresco | Apache License 2.0 |
src/main/java/com/wald/mainject/inject/Provides.kt | Waldemared | 338,810,220 | false | null | package com.wald.mainject.inject
annotation class Provides
| 1 | null | 1 | 1 | eb8ea2dc2697f1d96636cceb1e97ca044b2fd89f | 60 | mainject-core | MIT License |
bukkit/rpk-kit-lib-bukkit/src/main/kotlin/com/rpkit/kit/bukkit/kit/RPKKitService.kt | RP-Kit | 54,840,905 | false | null | /*
* Copyright 2021 <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 com.rpkit.kit.bukkit.kit
import com.rpkit.core.service.Service
import org.bukkit.inventory.ItemStack
interface RPKKitService : Service {
val kits: List<RPKKit>
fun getKit(name: RPKKitName): RPKKit?
fun addKit(kit: RPKKit)
fun createKit(name: RPKKitName, items: List<ItemStack>): RPKKit
fun updateKit(kit: RPKKit)
fun removeKit(kit: RPKKit)
} | 51 | Kotlin | 11 | 22 | aee4060598dc25cd8e4f3976ed5e70eb1bf874a2 | 966 | RPKit | Apache License 2.0 |
dokka-subprojects/core/src/test/kotlin/utilities/DokkaConfigurationJsonTest.kt | Kotlin | 21,763,603 | false | {"Text": 4, "Gradle Kotlin DSL": 231, "Java Properties": 41, "Markdown": 102, "Shell": 12, "Ignore List": 10, "Batchfile": 9, "Git Attributes": 2, "JSON": 12, "Kotlin": 1142, "TOML": 2, "YAML": 12, "HTML": 145, "SVG": 85, "CSS": 36, "Gradle": 15, "Java": 22, "JavaScript": 28, "Diff": 3, "XML": 13, "INI": 1, "Maven POM": 2, "JAR Manifest": 1, "JSON with Comments": 1, "TSX": 7, "SCSS": 3, "Fluent": 3, "FreeMarker": 2} | /*
* Copyright 2014-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package utilities
import org.jetbrains.dokka.DokkaConfigurationImpl
import org.jetbrains.dokka.DokkaSourceSetID
import org.jetbrains.dokka.DokkaSourceSetImpl
import org.jetbrains.dokka.testApi.assertDokkaConfigurationEquals
import org.jetbrains.dokka.toCompactJsonString
import java.io.File
import kotlin.test.Test
class DokkaConfigurationJsonTest {
@Test
fun `simple configuration toJsonString then parseJson`() {
val configuration = DokkaConfigurationImpl(
moduleName = "moduleName",
outputDir = File("customOutputDir"),
pluginsClasspath = listOf(File("plugins/customPlugin.jar")),
sourceSets = listOf(
DokkaSourceSetImpl(
sourceRoots = setOf(File("customSourceRoot")),
sourceSetID = DokkaSourceSetID("customModuleName", "customSourceSetName")
)
)
)
val jsonString = configuration.toCompactJsonString()
val parsedConfiguration = DokkaConfigurationImpl(jsonString)
assertDokkaConfigurationEquals(configuration, parsedConfiguration)
}
@Test
fun `parse simple configuration json`() {
val json = """
{
"moduleName": "moduleName",
"outputDir": "customOutputDir",
"pluginsClasspath": [ "plugins/customPlugin.jar" ],
"sourceSets": [
{
"sourceSetID": {
"scopeId": "customModuleName",
"sourceSetName": "customSourceSetName"
},
"sourceRoots": [ "customSourceRoot" ],
"classpath": [ "classpath/custom1.jar", "classpath/custom2.jar" ]
}
]
}
""".trimIndent()
val parsedConfiguration = DokkaConfigurationImpl(json)
assertDokkaConfigurationEquals(
DokkaConfigurationImpl(
moduleName = "moduleName",
outputDir = File("customOutputDir"),
pluginsClasspath = listOf(File("plugins/customPlugin.jar")),
sourceSets = listOf(
DokkaSourceSetImpl(
sourceRoots = setOf(File("customSourceRoot")),
sourceSetID = DokkaSourceSetID("customModuleName", "customSourceSetName"),
classpath = listOf(File("classpath/custom1.jar"), File("classpath/custom2.jar"))
)
)
),
parsedConfiguration,
)
}
}
| 1 | null | 1 | 1 | 09437c33bae16dd6432129db7b5706577103d3ba | 2,681 | dokka | Apache License 2.0 |
app/src/main/kotlin/org/eurofurence/connavigator/ui/views/NonScrollingLinearLayout.kt | TempestTraxx | 141,691,187 | false | {"Java Properties": 2, "Gradle": 4, "Shell": 1, "Markdown": 84, "Batchfile": 1, "Text": 1, "Ignore List": 2, "Proguard": 1, "JSON": 1, "Java": 79, "XML": 47, "Kotlin": 90} | package org.eurofurence.connavigator.ui.views
import android.content.Context
import android.support.v7.widget.LinearLayoutManager
/**
* Created by David on 6/5/2016.
*/
class NonScrollingLinearLayout(val context: Context) : LinearLayoutManager(context) {
override fun canScrollVertically(): Boolean = false
} | 1 | null | 1 | 1 | a7328c6d0a3b92bd95b3c180c5724f1025ac7a23 | 316 | cesfur-app_android | MIT License |
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/psi/UastFakeSourceLightAccessorBase.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.uast.kotlin.psi
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiType
import com.intellij.psi.PsiTypes
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.utils.SmartSet
internal open class UastFakeSourceLightAccessorBase<T: KtDeclaration>(
internal val property: KtProperty,
original: T,
containingClass: PsiClass,
internal val isSetter: Boolean,
) : UastFakeSourceLightMethodBase<T>(original, containingClass) {
override fun getName(): String {
val propertyName = property.name ?: ""
// TODO: what about @JvmName w/ use-site target?
return if (isSetter) JvmAbi.setterName(propertyName) else JvmAbi.getterName(propertyName)
}
override fun getReturnType(): PsiType? {
if (isSetter) {
return PsiTypes.voidType()
}
return super.getReturnType()
}
override fun computeAnnotations(annotations: SmartSet<PsiAnnotation>) {
// Annotations on property accessor
super.computeAnnotations(annotations)
// Annotations on property, along with use-site target
val useSiteTarget = if (isSetter) AnnotationUseSiteTarget.PROPERTY_SETTER else AnnotationUseSiteTarget.PROPERTY_GETTER
property.annotationEntries
.filter { it.useSiteTarget?.getAnnotationUseSiteTarget() == useSiteTarget }
.mapTo(annotations) { it.toPsiAnnotation() }
}
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 1,764 | intellij-community | Apache License 2.0 |
kotlin/코틀린 완벽 가이드/080250/Chapter14/KoTest/src/test/kotlin/ConfigExample.kt | devYSK | 461,887,647 | false | {"Java": 3507759, "JavaScript": 659549, "Kotlin": 563136, "HTML": 455168, "CSS": 446825, "Shell": 57444, "Groovy": 54414, "Batchfile": 47890, "Go": 26805, "Python": 9963, "Handlebars": 8554, "Makefile": 7837, "Vue": 5706, "TypeScript": 5172, "Dockerfile": 436, "Vim Snippet": 362, "Assembly": 278, "Procfile": 199} | import io.kotest.core.config.AbstractProjectConfig
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.core.spec.style.StringSpec
import io.kotest.core.test.TestCaseConfig
import io.kotest.matchers.shouldBe
import kotlin.time.ExperimentalTime
import kotlin.time.minutes
class StringSpecWithConfig : StringSpec({
"2 + 2 should be 4".config(invocations = 10) { (2 + 2) shouldBe 4 }
})
@OptIn(ExperimentalTime::class)
class ShouldSpecWithConfig : ShouldSpec({
context("Addition") {
context("1 + 2") {
should("be equal to 3").config(threads = 2, invocations = 100) {
(1 + 2) shouldBe 3
}
should("be equal to 2 + 1").config(timeout = 1.minutes) {
(1 + 2) shouldBe (2 + 1)
}
}
}
})
class BehaviorSpecWithConfig : BehaviorSpec({
Given("Arithmetic") {
When("x is 1") {
val x = 1
And("increased by 1") {
then("result is 2").config(invocations = 100) {
(x + 1) shouldBe 2
}
}
}
}
})
object ProjectConfig : AbstractProjectConfig() {
override val parallelism = 4
}
class StringSpecWithConfig2 : StringSpec({
"2 + 2 should be 4" { (2 + 2) shouldBe 4 }
}) {
override fun defaultConfig(): TestCaseConfig =
TestCaseConfig(invocations = 10, threads = 2)
} | 1 | null | 1 | 1 | 7a7c6b1bab3dc2c84527f8c528b06b9408872635 | 1,317 | study_repo | MIT License |
navigation/sample-standard/src/main/java/ru/surfstudio/android/navigation/sample_standard/di/ui/screen/RouteScreenModule.kt | surfstudio | 139,034,657 | false | null | package ru.surfstudio.android.navigation.sample_standard.di.ui.screen
import dagger.Module
import dagger.Provides
import ru.surfstudio.android.dagger.scope.PerScreen
import ru.surfstudio.android.navigation.route.Route
@Module
abstract class RouteScreenModule<R : Route>(val route: R) : ScreenModule() {
@Provides
@PerScreen
fun provideRoute(): R = route
} | 5 | null | 30 | 249 | 6d73ebcaac4b4bd7186e84964cac2396a55ce2cc | 370 | SurfAndroidStandard | Apache License 2.0 |
navigation/sample-standard/src/main/java/ru/surfstudio/android/navigation/sample_standard/di/ui/screen/RouteScreenModule.kt | surfstudio | 139,034,657 | false | null | package ru.surfstudio.android.navigation.sample_standard.di.ui.screen
import dagger.Module
import dagger.Provides
import ru.surfstudio.android.dagger.scope.PerScreen
import ru.surfstudio.android.navigation.route.Route
@Module
abstract class RouteScreenModule<R : Route>(val route: R) : ScreenModule() {
@Provides
@PerScreen
fun provideRoute(): R = route
} | 5 | null | 30 | 249 | 6d73ebcaac4b4bd7186e84964cac2396a55ce2cc | 370 | SurfAndroidStandard | Apache License 2.0 |
vector/src/main/java/im/vector/app/core/utils/RingtoneUtils.kt | tchapgouv | 340,329,238 | false | null | /*
* Copyright 2018 New Vector Ltd
*
* 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 im.vector.app.core.utils
import android.content.Context
import android.content.SharedPreferences
import android.media.Ringtone
import android.media.RingtoneManager
import android.net.Uri
import androidx.core.content.edit
import im.vector.app.core.di.DefaultPreferences
import im.vector.app.features.settings.VectorPreferences
import javax.inject.Inject
/**
* This class manages the sound ringtone for calls.
* It allows you to use the default Element Ringtone, or the standard ringtone or set a different one from the available choices
* in Android.
*/
class RingtoneUtils @Inject constructor(
@DefaultPreferences
private val sharedPreferences: SharedPreferences,
private val context: Context,
) {
/**
* Returns a Uri object that points to a specific Ringtone.
*
* If no Ringtone was explicitly set using Riot, it will return the Uri for the current system
* ringtone for calls.
*
* @return the [Uri] of the currently set [Ringtone]
* @see Ringtone
*/
fun getCallRingtoneUri(): Uri? {
val callRingtone: String? = sharedPreferences
.getString(VectorPreferences.SETTINGS_CALL_RINGTONE_URI_PREFERENCE_KEY, null)
callRingtone?.let {
return Uri.parse(it)
}
return try {
// Use current system notification sound for incoming calls per default (note that it can return null)
RingtoneManager.getActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE)
} catch (e: SecurityException) {
// Ignore for now
null
}
}
/**
* Returns a Ringtone object that can then be played.
*
* If no Ringtone was explicitly set using Riot, it will return the current system ringtone
* for calls.
*
* @return the currently set [Ringtone]
* @see Ringtone
*/
fun getCallRingtone(): Ringtone? {
getCallRingtoneUri()?.let {
// Note that it can also return null
return RingtoneManager.getRingtone(context, it)
}
return null
}
/**
* Returns a String with the name of the current Ringtone.
*
* If no Ringtone was explicitly set using Riot, it will return the name of the current system
* ringtone for calls.
*
* @return the name of the currently set [Ringtone], or null
* @see Ringtone
*/
fun getCallRingtoneName(): String? {
return getCallRingtone()?.getTitle(context)
}
/**
* Sets the selected ringtone for riot calls.
*
* @param ringtoneUri
* @see Ringtone
*/
fun setCallRingtoneUri(ringtoneUri: Uri) {
sharedPreferences
.edit {
putString(VectorPreferences.SETTINGS_CALL_RINGTONE_URI_PREFERENCE_KEY, ringtoneUri.toString())
}
}
/**
* Set using Riot default ringtone.
*/
fun useRiotDefaultRingtone(): Boolean {
return sharedPreferences.getBoolean(VectorPreferences.SETTINGS_CALL_RINGTONE_USE_RIOT_PREFERENCE_KEY, true)
}
/**
* Ask if default Riot ringtone has to be used.
*/
fun setUseRiotDefaultRingtone(useRiotDefault: Boolean) {
sharedPreferences
.edit {
putBoolean(VectorPreferences.SETTINGS_CALL_RINGTONE_USE_RIOT_PREFERENCE_KEY, useRiotDefault)
}
}
}
| 91 | null | 4 | 9 | a2c060c687b0aa69af681138c5788d6933d19860 | 4,020 | tchap-android | Apache License 2.0 |
plugins/performanceTesting/event-bus/src/com/intellij/tools/ide/starter/bus/EventsBus.kt | JetBrains | 2,489,216 | false | null | package com.intellij.tools.ide.starter.bus
import com.intellij.tools.ide.starter.bus.events.Event
import com.intellij.tools.ide.starter.bus.shared.SharedEventsFlow
import com.intellij.tools.ide.starter.bus.shared.client.LocalEventBusServerClient
import com.intellij.tools.ide.starter.bus.shared.events.SharedEvent
import com.intellij.tools.ide.starter.bus.shared.server.LocalEventBusServer
import com.intellij.tools.ide.starter.bus.local.LocalEventsFlow
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
object EventsBus {
val EVENTS_FLOW = LocalEventsFlow()
val SHARED_EVENTS_FLOW = SharedEventsFlow(LocalEventBusServerClient(LocalEventBusServer), EVENTS_FLOW)
/**
* Different events can be processed in parallel
*/
fun <T : Event> postAndWaitProcessing(event: T) {
if ((event is SharedEvent))
SHARED_EVENTS_FLOW.postAndWaitProcessing(event)
else
EVENTS_FLOW.postAndWaitProcessing(event)
}
/** Can have only one subscription by pair subscriber + event
* Subscriber might be invoked multiple times on different events since unsubscription happens only after end of test.
* */
inline fun <reified EventType : Event> subscribe(
subscriber: Any,
timeout: Duration = 2.minutes,
noinline callback: suspend (event: EventType) -> Unit
): EventsBus {
if (SharedEvent::class.java.isAssignableFrom(EventType::class.java)) {
SHARED_EVENTS_FLOW.subscribe(eventClass = EventType::class.java, subscriber = subscriber, timeout, callback)
SHARED_EVENTS_FLOW.startServerPolling()
}
else
EVENTS_FLOW.subscribe(eventClass = EventType::class.java, subscriber = subscriber, timeout, callback)
return this
}
fun unsubscribeAll() {
SHARED_EVENTS_FLOW.unsubscribeAll()
EVENTS_FLOW.unsubscribeAll()
}
fun startServerProcess() {
SHARED_EVENTS_FLOW.starterServerProcess()
}
fun endServerProcess() {
SHARED_EVENTS_FLOW.endServerProcess()
}
} | 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 1,970 | intellij-community | Apache License 2.0 |
app/k9mail/src/main/java/com/fsck/k9m_m/resources/KoinModule.kt | EverlastingHopeX | 226,972,945 | false | {"Java": 4218628, "Kotlin": 754602, "Shell": 3176, "HTML": 292} | package com.fsck.k9m_m.resources
import com.fsck.k9m_m.CoreResourceProvider
import com.fsck.k9m_m.autocrypt.AutocryptStringProvider
import org.koin.dsl.module.applicationContext
val resourcesModule = applicationContext {
bean { K9CoreResourceProvider(get()) as CoreResourceProvider }
bean { K9AutocryptStringProvider(get()) as AutocryptStringProvider}
}
| 1 | null | 1 | 1 | f611b289828f5b1f27d4274af76c0082c119dec0 | 364 | K-9-Modularization | Apache License 2.0 |
app/src/main/java/eu/darken/androidkotlinstarter/common/dagger/ApplicationContext.kt | d4rken | 187,688,567 | false | null | package eu.darken.androidkotlinstarter.common.dagger
import javax.inject.Qualifier
@Qualifier
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class ApplicationContext | 1 | Kotlin | 1 | 9 | 3f97c595e4a0ba385100702ebd77ed126174b2b0 | 189 | android-kotlin-starter-v2 | Apache License 2.0 |
app/src/main/java/com/diplom/map/utils/model/ESRIFeatureData.kt | DonGlebon | 175,883,786 | false | null | package com.diplom.map.utils.model
data class ESRIFeatureData(
val columnName: String,
val value: String
) | 1 | null | 1 | 1 | 45f2e59eed6f228f42d0b2b45ad374746a7dc9d3 | 115 | Diplom | MIT License |
platform/collaboration-tools/src/com/intellij/collaboration/api/graphql/GraphQLDataSerializer.kt | EsolMio | 169,598,741 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.collaboration.api.graphql
import com.intellij.collaboration.api.jsonhttp.JsonDataSerializer
import java.io.InputStream
interface GraphQLDataSerializer : JsonDataSerializer {
fun <T> readAndTraverseGQLResponse(body: String, pathFromData: Array<out String>, clazz: Class<T>): T?
fun <T> readAndTraverseGQLResponse(body: InputStream, pathFromData: Array<out String>, clazz: Class<T>): T?
}
| 1 | null | 1 | 1 | 4eb05cb6127f4dd6cbc09814b76b80eced9e4262 | 535 | intellij-community | Apache License 2.0 |
uniswapkit/src/main/java/io/horizontalsystems/uniswapkit/v3/router/ExactOutputSingleMethod.kt | horizontalsystems | 152,531,605 | false | null | package io.horizontalsystems.uniswapkit.v3.router
import io.horizontalsystems.ethereumkit.contracts.ContractMethod
import io.horizontalsystems.ethereumkit.contracts.ContractMethodFactory
import io.horizontalsystems.ethereumkit.contracts.ContractMethodHelper
import io.horizontalsystems.ethereumkit.models.Address
import java.math.BigInteger
class ExactOutputSingleMethod(
val tokenIn: Address,
val tokenOut: Address,
val fee: BigInteger,
val recipient: Address,
val amountOut: BigInteger,
val amountInMaximum: BigInteger,
val sqrtPriceLimitX96: BigInteger,
) : ContractMethod() {
override val methodSignature = Companion.methodSignature
override fun getArguments() = listOf(
tokenIn,
tokenOut,
fee,
recipient,
amountOut,
amountInMaximum,
sqrtPriceLimitX96
)
companion object {
private const val methodSignature =
"exactOutputSingle((address,address,uint24,address,uint256,uint256,uint160))"
}
class Factory : ContractMethodFactory {
override val methodId = ContractMethodHelper.getMethodId(methodSignature)
override fun createMethod(inputArguments: ByteArray): ContractMethod {
val parsedArguments = ContractMethodHelper.decodeABI(
inputArguments, listOf(
Address::class,
Address::class,
BigInteger::class,
Address::class,
BigInteger::class,
BigInteger::class,
BigInteger::class,
)
)
return ExactOutputSingleMethod(
tokenIn = parsedArguments[0] as Address,
tokenOut = parsedArguments[1] as Address,
fee = parsedArguments[2] as BigInteger,
recipient = parsedArguments[3] as Address,
amountOut = parsedArguments[4] as BigInteger,
amountInMaximum = parsedArguments[5] as BigInteger,
sqrtPriceLimitX96 = parsedArguments[6] as BigInteger,
)
}
}
}
| 10 | null | 53 | 98 | f4957a971be56ed15719cf640d27e514909be123 | 2,136 | ethereum-kit-android | MIT License |
app/src/main/java/com/github/amazingweather/di/scope/FragmentScoped.kt | Edydaoud | 264,558,030 | false | null | package com.github.amazingweather.di.scope
import javax.inject.Scope
@Scope
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@kotlin.annotation.Target(
AnnotationTarget.TYPE,
AnnotationTarget.FUNCTION,
AnnotationTarget.CLASS
)
annotation class FragmentScoped | 0 | Kotlin | 0 | 1 | 5f974711242a596d8cf46ff4f16a4104f4e341ba | 281 | AmazingWeather | Apache License 2.0 |
infra/web/src/main/kotlin/dev/marcal/chatvault/web/LegacyImporterController.kt | vitormarcal | 681,327,674 | false | {"Kotlin": 98526, "Vue": 26081, "TypeScript": 5471, "Dockerfile": 764} | package dev.marcal.chatvault.web
import dev.marcal.chatvault.service.legacy.ChatLegacyImporter
import dev.marcal.chatvault.service.legacy.AttachmentLegacyImporter
import dev.marcal.chatvault.service.legacy.EventSourceLegacyImporter
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/api/legacy")
class LegacyImporterController(
private val chatLegacyImporter: ChatLegacyImporter,
private val eventSourceLegacyImporter: EventSourceLegacyImporter,
private val attachmentLegacyImporter: AttachmentLegacyImporter
) {
@GetMapping("import/event-source")
fun importLegacy() {
chatLegacyImporter.importToEventSource()
}
@GetMapping("legacy/import/event-source/messages")
fun importLegacyEventSourceMessages() {
eventSourceLegacyImporter.importMessagesFromEventSource()
}
@GetMapping("legacy/import/event-source/attachments")
fun importLegacyEventSourceAttachments() {
attachmentLegacyImporter.execute()
}
} | 9 | Kotlin | 0 | 1 | d58f487d7f7bc2ff2cf88533999dbf77baf97f0b | 1,143 | chatvault | MIT License |
app/src/main/kotlin/ca/allanwang/mo/Application.kt | AllanWang | 311,893,055 | false | null | package ca.allanwang.mo
| 0 | Kotlin | 0 | 0 | 448c91b289ba8eef6d76300b7badc7cf31a35e65 | 25 | MO | Apache License 2.0 |
echoframework/src/main/kotlin/org/echo/mobile/framework/model/BalanceObject.kt | echoprotocol | 151,734,824 | false | null | package org.echo.mobile.framework.model
import com.google.gson.*
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import org.echo.mobile.framework.core.mapper.ObjectMapper
import java.lang.reflect.Type
import java.math.BigInteger
import java.util.*
/**
* Represents balance model in Graphene blockchain
*
* @author <NAME>
*/
class BalanceObject(id: String,
@Expose var owner: String,
@SerializedName(ASSET_TYPE_KEY) @Expose var asset: Asset?,
@SerializedName(LAST_CLAIM_DATE_KEY) @Expose var lastClaimData: Date?,
@Expose var balance: BigInteger
) : GrapheneObject(id) {
/**
* Deserializer used to build a [AccountBalance] instance from JSON
*/
class BalanceDeserializer : JsonDeserializer<BalanceObject> {
override fun deserialize(
json: JsonElement?,
typeOfT: Type?,
context: JsonDeserializationContext?
): BalanceObject? {
if (json == null || !json.isJsonObject) return null
val balanceObject = json.asJsonObject
println(balanceObject.toString())
val id = balanceObject[ID_KEY].asString
val owner = balanceObject[OWNER_KEY].asString
val asset = parseAsset(balanceObject)
val lastClaimDate = Date(balanceObject[LAST_CLAIM_DATE_KEY].asLong)
val balance = balanceObject[BALANCE_KEY].asLong.toBigInteger()
return BalanceObject(id, owner, asset,
lastClaimDate,
balance)
}
private fun parseAsset(
operationObject: JsonObject
): Asset? {
val assetsJson = operationObject[ASSET_TYPE_KEY].asString
return Asset(assetsJson)
}
}
companion object {
private const val ID_KEY = "id"
private const val OWNER_KEY = "owner"
private const val ASSET_TYPE_KEY = "asset_type"
private const val LAST_CLAIM_DATE_KEY = "last_claim_date"
private const val BALANCE_KEY = "balance"
}
/**
* Json mapper for [BalanceObject] model
*/
class BalanceObjectMapper : ObjectMapper<BalanceObject> {
override fun map(data: String): BalanceObject? =
data.tryMapWithdraw()
private fun String.tryMapWithdraw() =
this.tryMap(BalanceObject::class.java)
private fun <T> String.tryMap(resultType: Class<T>): T? =
try {
GsonBuilder().registerTypeAdapter(
BalanceObject::class.java,
BalanceDeserializer()
)
.create()
.fromJson(this, resultType)
} catch (exception: Exception) {
null
}
}
}
| 0 | Kotlin | 2 | 5 | 92036a0665d706c219d183a4a7582f02b87b9f88 | 2,940 | echo-android-framework | MIT License |
ui/src/main/java/kiwi/orbit/compose/ui/controls/Card.kt | kiwicom | 289,355,053 | false | null | package kiwi.orbit.compose.ui.controls
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.layout
import androidx.compose.ui.unit.dp
import kiwi.orbit.compose.icons.Icons
import kiwi.orbit.compose.ui.OrbitTheme
import kiwi.orbit.compose.ui.controls.internal.CustomPlaceholder
import kiwi.orbit.compose.ui.controls.internal.OrbitPreviews
import kiwi.orbit.compose.ui.controls.internal.Preview
import kiwi.orbit.compose.ui.foundation.ProvideMergedTextStyle
/**
* Rectangular surface that separates content into sections.
* For rounded and elevated card see [SurfaceCard].
*
* The [content] is by default surrounded with appropriate padding.
*
* You can override the default padding with the [contentPadding] parameter. This allows the [Card] to be
* combined with other components that handle padding on their own, e.g. [ListChoice].
*
* Optionally, you can supply [title] and [action] that together make up a header for the [Card].
* Appropriate text styles are provided. These slots are vertically aligned by their baselines.
*/
@Composable
public fun Card(
modifier: Modifier = Modifier,
title: @Composable () -> Unit = {},
action: @Composable () -> Unit = {},
contentPadding: PaddingValues = PaddingValues(16.dp),
content: @Composable () -> Unit,
) {
Surface(modifier) {
Column {
Row(
modifier = Modifier
.padding(horizontal = 16.dp)
.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
// Header has 16dp top padding but only if it has some content in it.
val topPadding = if (placeable.height > 0) 16.dp.roundToPx() else 0
val width = placeable.width
val height = (placeable.height + topPadding).coerceAtMost(constraints.maxHeight)
layout(width, height) {
placeable.placeRelative(0, topPadding)
}
},
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Box(
modifier = Modifier
.alignByBaseline()
.weight(1f),
) {
ProvideMergedTextStyle(OrbitTheme.typography.title4) {
title()
}
}
Box(Modifier.alignByBaseline()) {
ProvideMergedTextStyle(OrbitTheme.typography.bodyNormalMedium) {
action()
}
}
}
Box(Modifier.padding(contentPadding)) {
content()
}
}
}
}
@OrbitPreviews
@Composable
internal fun CardPreview() {
Preview(Modifier.background(OrbitTheme.colors.surface.normal)) {
Card {
CustomPlaceholder()
}
Card(
title = { Text("Card title") },
action = { ButtonTextLinkPrimary("Action", onClick = {}) },
) {
CustomPlaceholder()
}
Card(
title = { Text("Card title", style = OrbitTheme.typography.title1) },
action = { ButtonTextLinkPrimary("Action", onClick = {}) },
) {
CustomPlaceholder()
}
Card(
title = { Text("Card title") },
contentPadding = PaddingValues(vertical = 12.dp),
) {
Column {
ListChoice(
onClick = {},
icon = { Icon(Icons.AirplaneTakeoff, contentDescription = null) },
trailingIcon = { Icon(Icons.ChevronForward, contentDescription = null) },
) {
Text("Takeoff")
}
ListChoice(
onClick = {},
icon = { Icon(Icons.AirplaneLanding, contentDescription = null) },
trailingIcon = { Icon(Icons.ChevronForward, contentDescription = null) },
) {
Text("Landing")
}
}
}
}
}
| 15 | Kotlin | 14 | 76 | dc119a5f6ef2a7afa117a86445eb6049d4a21e80 | 4,609 | orbit-compose | MIT License |
common/build/generated/sources/schemaCode/kotlin/main/io/portone/sdk/server/schemas/SumOfPartsExceedsTotalAmountError.kt | portone-io | 809,427,199 | false | {"Kotlin": 385115, "Java": 331} | package io.portone.sdk.server.schemas
import kotlin.String
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* 면세 금액 등 하위 항목들의 합이 전체 결제 금액을 초과한 경우
*/
@Serializable
@SerialName("SUM_OF_PARTS_EXCEEDS_TOTAL_AMOUNT")
internal data class SumOfPartsExceedsTotalAmountError(
override val message: String? = null,
) : CreatePaymentScheduleError,
PayWithBillingKeyError,
PayInstantlyError
| 0 | Kotlin | 0 | 2 | 506e194123552bb5be7939fb72ee8c0a625c04e6 | 430 | server-sdk-jvm | MIT License |
src/main/kotlin/com/github/hank9999/kook/handler/types/MessageFuncHandler.kt | hank9999 | 505,054,380 | false | null | package com.github.hank9999.kook.handler.types
import com.github.hank9999.kook.types.Message
import com.github.hank9999.kook.types.types.ChannelPrivacyTypes
import kotlinx.coroutines.CoroutineScope
data class MessageFuncHandler(
val channelPrivacyTypes: ChannelPrivacyTypes,
val function: (msg: Message, cs: CoroutineScope) -> Unit
)
| 0 | Kotlin | 3 | 5 | bb285d9c131203934b66e8ef562ebcf28b0284e3 | 344 | kook-kt | MIT License |
client/src/commonMain/kotlin/com/algolia/search/model/settings/AdvancedSyntaxFeatures.kt | algolia | 153,273,215 | false | null | package com.algolia.search.model.settings
import com.algolia.search.model.internal.Raw
import com.algolia.search.serialize.internal.Key
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.Serializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
@Serializable(AdvancedSyntaxFeatures.Companion::class)
public sealed class AdvancedSyntaxFeatures(override val raw: String) : Raw<String> {
public object ExactPhrase : AdvancedSyntaxFeatures(Key.ExactPhrase)
public object ExcludeWords : AdvancedSyntaxFeatures(Key.ExcludeWords)
public data class Other(override val raw: String) : AdvancedSyntaxFeatures(raw)
@OptIn(ExperimentalSerializationApi::class)
@Serializer(AdvancedSyntaxFeatures::class)
public companion object : KSerializer<AdvancedSyntaxFeatures> {
private val serializer = String.serializer()
override val descriptor: SerialDescriptor = serializer.descriptor
override fun serialize(encoder: Encoder, value: AdvancedSyntaxFeatures) {
return serializer.serialize(encoder, value.raw)
}
override fun deserialize(decoder: Decoder): AdvancedSyntaxFeatures {
return when (val string = serializer.deserialize(decoder)) {
Key.ExactPhrase -> ExactPhrase
Key.ExcludeWords -> ExcludeWords
else -> Other(string)
}
}
}
}
| 8 | null | 23 | 59 | 21f0c6bd3c6c69387d1dd4ea09f69a220c5eaff4 | 1,654 | algoliasearch-client-kotlin | MIT License |
backend/data/src/main/kotlin/io/tolgee/constants/BillingPeriod.kt | tolgee | 303,766,501 | false | {"TypeScript": 2960870, "Kotlin": 2463774, "JavaScript": 19327, "Shell": 12678, "Dockerfile": 9468, "PLpgSQL": 663, "HTML": 439} | package io.tolgee.constants
enum class BillingPeriod {
MONTHLY,
YEARLY,
}
| 170 | TypeScript | 188 | 1,837 | 6e01eec3a19c151a6e0aca49e187e2d0deef3082 | 79 | tolgee-platform | Apache License 2.0 |
clvr-back/platform/src/main/kotlin/com/clvr/platform/impl/plugins/Sockets.kt | spbu-math-cs | 698,591,633 | false | {"Kotlin": 94320, "TypeScript": 49419, "JavaScript": 8395, "Python": 8353, "CSS": 738} | package com.clvr.platform.impl.plugins
import com.clvr.platform.impl.ClvrSessionStorage
import com.clvr.platform.api.ClvrGameView
import com.clvr.platform.logger
import com.clvr.platform.api.EventPayloadInterface
import com.clvr.platform.api.RequestEvent
import com.clvr.platform.api.SessionId
import com.clvr.platform.impl.SessionManager
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.routing.*
import io.ktor.server.websocket.*
import io.ktor.websocket.*
import kotlinx.coroutines.cancel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import java.lang.Exception
private suspend fun <Req: EventPayloadInterface, Resp: EventPayloadInterface> DefaultWebSocketServerSession.configureHostSession(
sessionStorage: ClvrSessionStorage<Req, Resp>
) {
val logger = application.logger
val sessionId = SessionId(
call.parameters["session_id"] ?: throw IllegalArgumentException("failed to get session id")
)
val hostEndpoint: String = endpoint(call.request.origin)
val sessionManager: SessionManager<Req, Resp> = sessionStorage.getSessionManager(sessionId)
val gameView: ClvrGameView<Req, Resp> = sessionStorage.getGameView(sessionId)
val hostChannel = sessionManager.hostChannel
logger.info { "Host $hostEndpoint connected to game $sessionId" }
gameView.hostView.forEach { initialEvent ->
outgoing.send(Frame.Text(gameView.encodeEventToJson(initialEvent)))
}
coroutineScope {
launch {
for (event in hostChannel) {
try {
val jsonEvent: String = gameView.encodeEventToJson(event)
outgoing.send(Frame.Text(jsonEvent))
logger.debug { "Send event $jsonEvent to host $hostEndpoint in $sessionId game" }
} catch (e: Exception) {
logger.error { "Failed to send event to host $hostEndpoint because of $e" }
hostChannel.send(event)
}
}
}
launch {
for (frame in incoming) {
try {
if (frame !is Frame.Text) {
continue
}
val jsonEvent: String = frame.readText()
logger.debug { "Receive event $jsonEvent from host $hostEndpoint in $sessionId game" }
val event: RequestEvent<Req> = gameView.decodeJsonToEvent(jsonEvent)
sessionManager.handleHostEvent(event)
} catch (e: Exception) {
logger.error { "Failed to process event incoming frame because of error $e" }
}
}
}
val closeReason = closeReason.await()
logger.info { "Connection with host $hostEndpoint was closed because of $closeReason" }
cancel("Connection with host was closed because of $closeReason")
}
}
private suspend fun <Req: EventPayloadInterface, Resp: EventPayloadInterface> DefaultWebSocketServerSession.configureClientSession(
sessionStorage: ClvrSessionStorage<Req, Resp>
) {
val logger = application.logger
val sessionId = SessionId(
call.parameters["session_id"] ?: throw IllegalArgumentException("failed to get session id")
)
val clientEndpoint: String = call.request.origin.remoteAddress + ":" + call.request.origin.remotePort
val sessionManager: SessionManager<Req, Resp> = sessionStorage.getSessionManager(sessionId)
val gameView: ClvrGameView<Req, Resp> = sessionStorage.getGameView(sessionId)
val clientChannel = sessionManager.registerClient(clientEndpoint)
logger.info { "Client $clientEndpoint connected to game $sessionId" }
gameView.clientView.forEach { initialEvent ->
outgoing.send(Frame.Text(gameView.encodeEventToJson(initialEvent)))
}
try {
coroutineScope {
launch {
for (event in clientChannel) {
try {
val jsonEvent: String = gameView.encodeEventToJson(event)
outgoing.send(Frame.Text(jsonEvent))
logger.debug { "Send event $jsonEvent to client $clientEndpoint in $sessionId game" }
} catch (e: Exception) {
logger.error { "Failed to send event to client $clientEndpoint because of $e" }
}
}
}
val closeReason = closeReason.await()
logger.info { "Connection with client $clientEndpoint was closed because of $closeReason" }
cancel("Connection with client was closed because of $closeReason")
}
} finally {
sessionManager.unregisterClient(clientEndpoint)
}
}
internal fun Application.configureSockets() {
install(WebSockets) {
// pingPeriod = Duration.ofSeconds(15)
// timeout = Duration.ofSeconds(15)
// maxFrameSize = Long.MAX_VALUE
// masking = false
}
routing {
// Leave it in order to test simple connection
webSocket("/ws") { // websocketSession
for (frame in incoming) {
if (frame is Frame.Text) {
val text = frame.readText()
outgoing.send(Frame.Text("YOU SAID: $text"))
if (text.equals("bye", ignoreCase = true)) {
close(CloseReason(CloseReason.Codes.NORMAL, "Client said BYE"))
}
}
}
}
}
}
internal fun Application.addWebsocketRouting(activityName: String, storage: ClvrSessionStorage<*, *>) {
routing {
webSocket("/ws/${activityName}/host/{session_id}") {
configureHostSession(storage)
}
webSocket("/ws/${activityName}/client/{session_id}") {
configureClientSession(storage)
}
}
}
private fun endpoint(endpoint: RequestConnectionPoint): String = endpoint.remoteAddress + ":" + endpoint.remotePort | 16 | Kotlin | 0 | 0 | d5b1b910047bf60d22f628c20ebda1d329d743f5 | 6,052 | ig-platform | Apache License 2.0 |
todos/ui/view/src/main/java/com/moataz/todos/ui/view/theme/Color.kt | MoatazBadawy | 608,275,729 | false | {"Kotlin": 120856} | package com.moataz.todos.ui.view.theme
import androidx.compose.ui.graphics.Color
val WhiteLight = Color(0xFFF8F8F8)
val White50 = Color(0xFFF5F5F5)
val GrayLight = Color(0xFFE7E7E7)
val MainColor = Color(0xFFE7E7E7)
val Black = Color(0xFF000000)
val Red = Color(0xFFDA0303) | 1 | Kotlin | 4 | 31 | 1741defe7efc5d6523342145194b63cabcf53f9f | 275 | Mawaqeet-Todo_and_Habits | Apache License 2.0 |
test/dorkboxTest/network/app/Stopwatch.kt | dorkbox | 53,281,134 | false | {"Kotlin": 1427302, "Java": 82773} | /*
* Copyright 2023 dorkbox, llc
*
* 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.
*/
/*
* Copyright (C) 2008 The Guava Authors
*
* 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 dorkboxTest.network.app
import java.time.Duration
import java.util.concurrent.*
/**
* An object that measures elapsed time in nanoseconds. It is useful to measure elapsed time using
* this class instead of direct calls to [System.nanoTime] for a few reasons:
*
*
* * An alternate time source can be substituted, for testing or performance reasons.
* * As documented by `nanoTime`, the value returned has no absolute meaning, and can only
* be interpreted as relative to another timestamp returned by `nanoTime` at a different
* time. `Stopwatch` is a more effective abstraction because it exposes only these
* relative values, not the absolute ones.
*
*
*
* Basic usage:
*
* <pre>`Stopwatch stopwatch = Stopwatch.createStarted();
* doSomething();
* stopwatch.stop(); // optional
*
* Duration duration = stopwatch.elapsed();
*
* log.info("time: " + stopwatch); // formatted string like "12.3 ms"
`</pre> *
*
*
* Stopwatch methods are not idempotent; it is an error to start or stop a stopwatch that is
* already in the desired state.
*
*
* When testing code that uses this class, use [.createUnstarted] or [ ][.createStarted] to supply a fake or mock ticker. This allows you to simulate any valid
* behavior of the stopwatch.
*
*
* **Note:** This class is not thread-safe.
*
*
* **Warning for Android users:** a stopwatch with default behavior may not continue to keep
* time while the device is asleep. Instead, create one like this:
*
* <pre>`Stopwatch.createStarted(
* new Ticker() {
* public long read() {
* return android.os.SystemClock.elapsedRealtimeNanos();
* }
* });
`</pre> *
*
* @author <NAME>
* @since 10.0
*/
class Stopwatch {
private val ticker: Ticker
/**
* Returns `true` if [.start] has been called on this stopwatch, and [.stop]
* has not been called since the last call to `start()`.
*/
var isRunning = false
private set
private var elapsedNanos: Long = 0
private var startTick: Long = 0
internal constructor() {
ticker = Ticker.systemTicker()
}
internal constructor(ticker: Ticker?) {
if (ticker == null) {
throw NullPointerException("ticker")
}
this.ticker = ticker
}
/**
* Starts the stopwatch.
*
* @return this `Stopwatch` instance
*
* @throws IllegalStateException if the stopwatch is already running.
*/
fun start(): Stopwatch {
check(!isRunning) { "This stopwatch is already running." }
isRunning = true
startTick = ticker.read()
return this
}
/**
* Stops the stopwatch. Future reads will return the fixed duration that had elapsed up to this
* point.
*
* @return this `Stopwatch` instance
*
* @throws IllegalStateException if the stopwatch is already stopped.
*/
fun stop(): Stopwatch {
val tick = ticker.read()
check(isRunning) { "This stopwatch is already stopped." }
isRunning = false
elapsedNanos += tick - startTick
return this
}
/**
* Sets the elapsed time for this stopwatch to zero, and places it in a stopped state.
*
* @return this `Stopwatch` instance
*/
fun reset(): Stopwatch {
elapsedNanos = 0
isRunning = false
return this
}
fun elapsedNanos(): Long {
return if (isRunning) ticker.read() - startTick + elapsedNanos else elapsedNanos
}
/**
* Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit,
* with any fraction rounded down.
*
*
* **Note:** the overhead of measurement can be more than a microsecond, so it is generally
* not useful to specify [TimeUnit.NANOSECONDS] precision here.
*
*
* It is generally not a good idea to use an ambiguous, unitless `long` to represent
* elapsed time. Therefore, we recommend using [.elapsed] instead, which returns a
* strongly-typed [Duration] instance.
*
* @since 14.0 (since 10.0 as `elapsedTime()`)
*/
fun elapsed(desiredUnit: TimeUnit): Long {
return desiredUnit.convert(elapsedNanos(), TimeUnit.NANOSECONDS)
}
/**
* Returns the current elapsed time shown on this stopwatch as a [Duration]. Unlike [ ][.elapsed], this method does not lose any precision due to rounding.
*
* @since 22.0
*/
fun elapsed(): Duration {
return Duration.ofNanos(elapsedNanos())
}
/**
* Returns a string representation of the current elapsed time.
*/
override fun toString(): String {
return toString(elapsedNanos())
}
companion object {
/**
* Creates (but does not start) a new stopwatch using [System.nanoTime] as its time source.
*
* @since 15.0
*/
fun createUnstarted(): Stopwatch {
return Stopwatch()
}
/**
* Creates (but does not start) a new stopwatch, using the specified time source.
*
* @since 15.0
*/
fun createUnstarted(ticker: Ticker?): Stopwatch {
return Stopwatch(ticker)
}
/**
* Creates (and starts) a new stopwatch using [System.nanoTime] as its time source.
*
* @since 15.0
*/
fun createStarted(): Stopwatch {
return Stopwatch().start()
}
/**
* Creates (and starts) a new stopwatch, using the specified time source.
*
* @since 15.0
*/
fun createStarted(ticker: Ticker?): Stopwatch {
return Stopwatch(ticker).start()
}
fun toString(nanos: Long): String {
val unit = chooseUnit(nanos)
val value = nanos.toDouble() / TimeUnit.NANOSECONDS.convert(1, unit)
// Too bad this functionality is not exposed as a regular method call
return String.format("%.4g %s", value, abbreviate(unit))
}
fun chooseUnit(nanos: Long): TimeUnit {
if (TimeUnit.DAYS.convert(nanos, TimeUnit.NANOSECONDS) > 0) {
return TimeUnit.DAYS
}
if (TimeUnit.HOURS.convert(nanos, TimeUnit.NANOSECONDS) > 0) {
return TimeUnit.HOURS
}
if (TimeUnit.MINUTES.convert(nanos, TimeUnit.NANOSECONDS) > 0) {
return TimeUnit.MINUTES
}
if (TimeUnit.SECONDS.convert(nanos, TimeUnit.NANOSECONDS) > 0) {
return TimeUnit.SECONDS
}
if (TimeUnit.MILLISECONDS.convert(nanos, TimeUnit.NANOSECONDS) > 0) {
return TimeUnit.MILLISECONDS
}
return if (TimeUnit.MICROSECONDS.convert(nanos, TimeUnit.NANOSECONDS) > 0) {
TimeUnit.MICROSECONDS
} else TimeUnit.NANOSECONDS
}
private fun abbreviate(unit: TimeUnit): String {
return when (unit) {
TimeUnit.NANOSECONDS -> "ns"
TimeUnit.MICROSECONDS -> "\u03bcs" // μs
TimeUnit.MILLISECONDS -> "ms"
TimeUnit.SECONDS -> "s"
TimeUnit.MINUTES -> "min"
TimeUnit.HOURS -> "h"
TimeUnit.DAYS -> "d"
else -> throw AssertionError()
}
}
}
}
| 1 | Kotlin | 2 | 7 | 3f77af5894b45070a7e09ee9a47b977cf2f8e5d9 | 8,576 | Network | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/techholding/android/posts/ui/view/post/details/PostDetailsViewModel.kt | daniel553 | 716,448,409 | false | {"Kotlin": 64283} | package com.techholding.android.posts.ui.view.post.details
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.techholding.android.posts.domain.FetchPostDetailsUseCase
import com.techholding.android.posts.domain.SubscribeToPostsUseCase
import com.techholding.android.posts.model.Post
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class PostDetailsViewModel @Inject constructor(
private val fetchPostDetailsUseCase: FetchPostDetailsUseCase,
private val subscribeToPostsUseCase: SubscribeToPostsUseCase
) : ViewModel() {
private val _uiState = MutableStateFlow(PostDetailUiState())
val uiState = _uiState.asStateFlow()
fun setId(id: Long?) {
id?.let { postId ->
_uiState.update { it.copy(id = postId) }
getPostDetails()
}
}
private fun getPostDetails() {
viewModelScope.launch(Dispatchers.IO) {
subscribeToPost()
fetchPostDetailsUseCase(_uiState.value.id)
}
}
private suspend fun subscribeToPost() {
subscribeToPostsUseCase(_uiState.value.id).onEach { post ->
_uiState.update { it.copy(post = post) }
}.stateIn(viewModelScope, SharingStarted.Eagerly, null)
}
}
data class PostDetailUiState(
val id: Long = 0L,
val loading: Boolean = false,
val post: Post? = null
) | 0 | Kotlin | 0 | 0 | 44abafea506d66f5785f7a3f7b46b0ea4e3ba0f1 | 1,736 | TechHoldingPosts | FSF All Permissive License |
module-common/src/main/kotlin/io/klaytn/commons/model/mapper/Mapper.kt | klaytn | 678,353,482 | false | {"Kotlin": 1733058, "Solidity": 71874, "Shell": 3957} | package io.klaytn.commons.model.mapper
interface Mapper<SOURCE, OUTPUT> {
fun transform(source: SOURCE): OUTPUT
}
interface ListMapper<SOURCE, OUTPUT> {
fun transform(source: List<SOURCE>): List<OUTPUT>
}
| 6 | Kotlin | 0 | 0 | a7af1eea2a494bacaa7a91a383c7f5a0666a4bbf | 215 | finder-api | MIT License |
src/main/kotlin/threed/example/ScaleAndRotateTriangle.kt | comexos | 107,757,317 | true | {"Kotlin": 660502, "HTML": 262} | package threed.example
import org.khronos.webgl.Float32Array
import org.khronos.webgl.WebGLRenderingContext
import threed.*
fun scaleAndRotateTriangle(gl: WebGLRenderingContext) {
val vertices = arrayOf(
0.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f
)
val vertexBuffer = gl.createBuffer()
gl.bindBuffer(WebGLRenderingContext.ARRAY_BUFFER, vertexBuffer)
gl.bufferData(WebGLRenderingContext.ARRAY_BUFFER, Float32Array(vertices), WebGLRenderingContext.STATIC_DRAW)
val vertexShaderCode =
"""
attribute vec3 vertices;
uniform mat4 modelMatrix;
void main(void) {
gl_Position = modelMatrix*vec4(vertices, 1.0);
}
"""
val fragmentShaderCode =
"""
precision mediump float;
void main(void) {
gl_FragColor = vec4(0.9, 0.2, 0.2, 1.0);
}
"""
val vertexShader = gl.createShader(WebGLRenderingContext.VERTEX_SHADER)
gl.shaderSource(vertexShader, vertexShaderCode)
gl.compileShader(vertexShader)
val fragmentShader = gl.createShader(WebGLRenderingContext.FRAGMENT_SHADER)
gl.shaderSource(fragmentShader, fragmentShaderCode)
gl.compileShader(fragmentShader)
val shaderProgram = gl.createProgram()
gl.attachShader(shaderProgram, vertexShader)
gl.attachShader(shaderProgram, fragmentShader)
gl.linkProgram(shaderProgram)
gl.useProgram(shaderProgram)
gl.clearColor(0.5f, 0.5f, 0.5f, 0.9f)
gl.clear(WebGLRenderingContext.COLOR_BUFFER_BIT)
val verticesAttribute = gl.getAttribLocation(shaderProgram, "vertices")
gl.vertexAttribPointer(verticesAttribute, 3, WebGLRenderingContext.FLOAT, false, 0, 0)
gl.enableVertexAttribArray(verticesAttribute)
// Translate * Rotate * Scale -> First scale, then rotate, then translate
val modeMatrix =
translateMatrix(0.5f, 0.5f, 0.0f) *
rotateXMatrix(0.0.asRad.toFloat()) *
rotateYMatrix(0.0.asRad.toFloat()) *
rotateZMatrix(10.0.asRad.toFloat()) *
scaleMatrix(0.5f, 0.5f, 1.0f)
val modelMatrixUniform = gl.getUniformLocation(shaderProgram, "modelMatrix")
gl.uniformMatrix4fv(modelMatrixUniform, false, modeMatrix)
gl.drawArrays(WebGLRenderingContext.TRIANGLES, 0, 3)
} | 0 | Kotlin | 0 | 0 | 4bdf6bdcd29d3b4023c1b840e84462c59826ec3f | 2,416 | 3d-playground | Apache License 2.0 |
app/src/admin/java/com/twoplaytech/drbetting/admin/ui/ticket/navigation/TicketNavigation.kt | iamdamjanmiloshevski | 346,013,436 | false | null | package com.twoplaytech.drbetting.admin.ui.ticket.navigation
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.runtime.Composable
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.twoplaytech.drbetting.admin.ui.ticket.screens.AddBettingTip
import com.twoplaytech.drbetting.admin.ui.ticket.screens.AddOrUpdateTicket
import com.twoplaytech.drbetting.admin.ui.ticket.screens.Tickets
import com.twoplaytech.drbetting.admin.ui.viewmodels.TicketsViewModel
/*
Author: <NAME>
Created on 15.2.22 15:01
Project: Dr.Betting
© 2Play Technologies 2022. All rights reserved
*/
@Composable
fun TicketNavigation(activity: AppCompatActivity? = null) {
val navController = rememberNavController()
val ticketsViewModel = hiltViewModel<TicketsViewModel>()
NavHost(navController, startDestination = TicketRoute.Tickets.name) {
composable(TicketRoute.route(TicketRoute.Tickets)) {
activity?.let {
Tickets(activity, navController, ticketsViewModel)
}
}
composable(TicketRoute.route(TicketRoute.AddOrUpdateTicket)){
AddOrUpdateTicket(navController, ticketsViewModel = ticketsViewModel)
}
composable(
TicketRoute.route(TicketRoute.AddOrUpdateBettingTip).plus("?ticketId={ticketId},?tipId={tipId}"),
arguments = listOf(navArgument("ticketId") {
nullable = true
defaultValue = null
type = NavType.StringType
},navArgument("tipId") {
nullable = true
defaultValue = null
type = NavType.StringType
})
) { backStackEntry ->
val arguments = backStackEntry.arguments
arguments?.let { args ->
val ticketId = args["ticketId"] as String?
val tipId = args["tipId"] as String?
AddBettingTip(ticketId,tipId, activity, navController,ticketsViewModel)
} ?: throw Exception(
"Please provide arguments for destination ${
TicketRoute.route(
TicketRoute.AddOrUpdateBettingTip
)
}"
)
}
}
} | 0 | Kotlin | 2 | 2 | 6f4998dde4c0ed20f2f6300b8a32fc88608abc1d | 2,480 | betting-doctor | MIT License |
print_inverted_full_pyramid.kt | MarcosFloresta | 223,296,767 | false | null | fun main(args: Array<String>) {
val rows = 5
for (i in rows downTo 1) {
for (space in 1..rows - i) {
print(" ")
}
for (j in i..2 * i - 1) {
print("* ")
}
for (j in 0..i - 1 - 1) {
print("* ")
}
println()
}
} | 0 | Kotlin | 0 | 1 | eed7ca2520491200579253e95acd6ee94a0fa92e | 312 | kotlin-examples | MIT License |
library/src/main/kotlin/org/mjdev/libs/barcodescanner/bysquare/data/pay/DirectDebitScheme.kt | mimoccc | 804,873,510 | false | {"Kotlin": 244846, "Shell": 336} | package org.mjdev.libs.barcodescanner.bysquare.data.pay
@Suppress("unused")
enum class DirectDebitScheme(val value: Int) {
OTHER(0),
SEPA(1);
companion object {
operator fun invoke(value: Int) = entries.find { it.value == value }
}
}
| 0 | Kotlin | 0 | 0 | 6f99b62284c335faeef849c5cee8771ffc760ed6 | 260 | barcodescanner | Apache License 2.0 |
projects/unpaid-work-and-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/controller/casedetails/model/CaseDetails.kt | ministryofjustice | 500,855,647 | false | null | package uk.gov.justice.digital.hmpps.controller.casedetails.model
import uk.gov.justice.digital.hmpps.controller.casedetails.entity.AliasEntity
import uk.gov.justice.digital.hmpps.controller.casedetails.entity.CaseEntity
import uk.gov.justice.digital.hmpps.controller.casedetails.entity.CasePersonalContactEntity
import uk.gov.justice.digital.hmpps.integrations.common.model.Address
import uk.gov.justice.digital.hmpps.integrations.common.model.Name
import uk.gov.justice.digital.hmpps.integrations.common.model.PersonalCircumstance
import uk.gov.justice.digital.hmpps.integrations.common.model.PersonalContact
import uk.gov.justice.digital.hmpps.integrations.common.model.Type
import java.time.LocalDate
data class CaseDetails(
val crn: String,
val name: Name,
val dateOfBirth: LocalDate,
val gender: String?,
val genderIdentity: String?,
val croNumber: String?,
val pncNumber: String?,
val aliases: List<Alias>? = listOf(),
val emailAddress: String?,
val phoneNumbers: List<PhoneNumber>? = listOf(),
val mainAddress: Address?,
val ethnicity: String?,
val disabilities: List<Disability>? = listOf(),
val language: Language?,
val personalCircumstances: List<PersonalCircumstance>? = listOf(),
val personalContacts: List<PersonalContact>? = listOf(),
val mappaRegistration: MappaRegistration?,
val registerFlags: List<RegisterFlag>? = listOf(),
val sentence: Sentence?
)
data class Alias(
val name: Name,
val dateOfBirth: LocalDate
)
data class PhoneNumber(
val type: String,
val number: String
)
data class Disability(
val type: Type,
val provisions: List<String>?,
val notes: String
)
data class Language(
val requiresInterpreter: Boolean = false,
val primaryLanguage: String = "",
)
data class MappaRegistration(
val startDate: LocalDate,
val level: Type,
val category: Type
)
data class RegisterFlag(
val code: String,
val description: String,
val riskColour: String?
)
data class Sentence(
val startDate: LocalDate,
val mainOffence: MainOffence,
)
data class MainOffence(
val category: Type,
val subCategory: Type
)
fun CaseEntity.name() = Name(forename, listOfNotNull(secondName, thirdName).joinToString(" "), surname)
fun AliasEntity.name() = Name(forename, listOfNotNull(secondName, thirdName).joinToString(" "), surname)
fun CasePersonalContactEntity.name() = Name(forename, middleName, surname)
| 4 | Kotlin | 0 | 2 | 9f6663d820fb8123d915107edfa9abc5f82d3fb6 | 2,467 | hmpps-probation-integration-services | MIT License |
app/src/main/java/com/pixels/blockies/game/game/figures/FigureZ.kt | crazzle | 17,808,587 | false | {"Kotlin": 57221} | package com.pixels.blockies.game.game.figures
import com.pixels.blockies.game.game.Grid
class FigureZ : AbstractFigure() {
private val figures = arrayOf(
arrayOf<IntArray?>(
intArrayOf(5, Grid.Companion.EMPTY),
intArrayOf(5, 5),
intArrayOf(Grid.Companion.EMPTY, 5)
),
arrayOf<IntArray?>(
intArrayOf(Grid.Companion.EMPTY, 5, 5),
intArrayOf(5, 5, Grid.Companion.EMPTY)
)
)
override fun getFigureCount(): Int {
return figures.size
}
override fun get(): Array<IntArray?> {
return figures[currentRotation]
}
override fun getNext(): Array<IntArray?> {
return figures[nextRotation]
}
} | 0 | Kotlin | 2 | 2 | e8e6dccaa662b28b1025577a17efcfc38d6d8596 | 731 | Blockies | MIT License |
src/test/kotlin/no/nav/utsjekk/iverksetting/util/IverksettMockUtil.kt | navikt | 611,752,955 | false | {"Kotlin": 411877, "Gherkin": 60800, "Shell": 669, "Dockerfile": 116} | package no.nav.utsjekk.iverksetting.util
import no.nav.utsjekk.iverksetting.domene.AndelTilkjentYtelse
import no.nav.utsjekk.iverksetting.domene.Behandlingsdetaljer
import no.nav.utsjekk.iverksetting.domene.Fagsakdetaljer
import no.nav.utsjekk.iverksetting.domene.Iverksetting
import no.nav.utsjekk.iverksetting.domene.Iverksettingsresultat
import no.nav.utsjekk.iverksetting.domene.OppdragResultat
import no.nav.utsjekk.iverksetting.domene.Periode
import no.nav.utsjekk.iverksetting.domene.Stønadsdata
import no.nav.utsjekk.iverksetting.domene.StønadsdataDagpenger
import no.nav.utsjekk.iverksetting.domene.Søker
import no.nav.utsjekk.iverksetting.domene.TilkjentYtelse
import no.nav.utsjekk.iverksetting.domene.Vedtaksdetaljer
import no.nav.utsjekk.iverksetting.domene.transformer.RandomOSURId
import no.nav.utsjekk.kontrakter.felles.Fagsystem
import no.nav.utsjekk.kontrakter.felles.StønadTypeDagpenger
import no.nav.utsjekk.kontrakter.oppdrag.Utbetalingsoppdrag
import java.time.LocalDate
import java.time.LocalDateTime
fun enAndelTilkjentYtelse(
beløp: Int = 5000,
fra: LocalDate = LocalDate.of(2021, 1, 1),
til: LocalDate = LocalDate.of(2021, 12, 31),
periodeId: Long? = null,
forrigePeriodeId: Long? = null,
stønadsdata: Stønadsdata = StønadsdataDagpenger(stønadstype = StønadTypeDagpenger.DAGPENGER_ARBEIDSSØKER_ORDINÆR, meldekortId = "M1"),
) = AndelTilkjentYtelse(
beløp = beløp,
periode = Periode(fra, til),
periodeId = periodeId,
forrigePeriodeId = forrigePeriodeId,
stønadsdata = stønadsdata,
)
fun enTilkjentYtelse(
behandlingId: String = RandomOSURId.generate(),
andeler: List<AndelTilkjentYtelse> = listOf(enAndelTilkjentYtelse()),
sisteAndelIKjede: AndelTilkjentYtelse? = null,
utbetalingsoppdrag: Utbetalingsoppdrag? = null,
) = TilkjentYtelse(
id = behandlingId,
utbetalingsoppdrag = utbetalingsoppdrag,
andelerTilkjentYtelse = andeler,
sisteAndelIKjede = sisteAndelIKjede,
sisteAndelPerKjede = andeler.firstOrNull()?.let { mapOf(it.stønadsdata.tilKjedenøkkel() to it) } ?: emptyMap(),
)
fun behandlingsdetaljer(
behandlingId: String = RandomOSURId.generate(),
forrigeBehandlingId: String? = null,
iverksettingId: String? = null,
forrigeIverksettingId: String? = null,
) = Behandlingsdetaljer(
behandlingId = behandlingId,
forrigeBehandlingId = forrigeBehandlingId,
iverksettingId = iverksettingId,
forrigeIverksettingId = forrigeIverksettingId,
)
fun vedtaksdetaljer(
andeler: List<AndelTilkjentYtelse> = listOf(enAndelTilkjentYtelse()),
vedtakstidspunkt: LocalDateTime = LocalDateTime.of(2021, 5, 12, 0, 0),
) = Vedtaksdetaljer(
vedtakstidspunkt = vedtakstidspunkt,
saksbehandlerId = "A12345",
beslutterId = "B23456",
tilkjentYtelse = enTilkjentYtelse(andeler),
)
private fun enTilkjentYtelse(andeler: List<AndelTilkjentYtelse>): TilkjentYtelse =
TilkjentYtelse(
id = RandomOSURId.generate(),
utbetalingsoppdrag = null,
andelerTilkjentYtelse = andeler,
)
fun enIverksetting(
fagsystem: Fagsystem = Fagsystem.DAGPENGER,
sakId: String? = null,
behandlingsdetaljer: Behandlingsdetaljer = behandlingsdetaljer(),
vedtaksdetaljer: Vedtaksdetaljer = vedtaksdetaljer(),
) = Iverksetting(
fagsak =
Fagsakdetaljer(
fagsakId = sakId ?: RandomOSURId.generate(),
fagsystem = fagsystem,
),
behandling = behandlingsdetaljer,
søker =
Søker(
personident = "15507600333",
),
vedtak = vedtaksdetaljer,
)
fun enIverksetting(
behandlingId: String = RandomOSURId.generate(),
forrigeBehandlingId: String? = null,
andeler: List<AndelTilkjentYtelse> = listOf(enAndelTilkjentYtelse()),
sakId: String = RandomOSURId.generate(),
iverksettingId: String? = null,
forrigeIverksettingId: String? = null,
): Iverksetting {
val fagsystem =
andeler
.firstOrNull()
?.stønadsdata
?.stønadstype
?.tilFagsystem() ?: Fagsystem.DAGPENGER
return Iverksetting(
fagsak = Fagsakdetaljer(fagsakId = sakId, fagsystem = fagsystem),
behandling =
Behandlingsdetaljer(
behandlingId = behandlingId,
iverksettingId = iverksettingId,
forrigeBehandlingId = forrigeBehandlingId,
forrigeIverksettingId = forrigeIverksettingId,
),
søker =
Søker(
personident = "15507600333",
),
vedtak =
vedtaksdetaljer(
andeler = andeler,
),
)
}
fun etIverksettingsresultat(
fagsystem: Fagsystem = Fagsystem.DAGPENGER,
sakId: String = RandomOSURId.generate(),
behandlingId: String = RandomOSURId.generate(),
tilkjentYtelse: TilkjentYtelse? = null,
iverksettingId: String? = null,
oppdragResultat: OppdragResultat? = null,
) = Iverksettingsresultat(
fagsystem = fagsystem,
sakId = sakId,
behandlingId = behandlingId,
iverksettingId = iverksettingId,
tilkjentYtelseForUtbetaling = tilkjentYtelse,
oppdragResultat = oppdragResultat,
)
fun etTomtUtbetalingsoppdrag() =
Utbetalingsoppdrag(
aktør = "12345678911",
avstemmingstidspunkt = LocalDateTime.now(),
brukersNavKontor = null,
erFørsteUtbetalingPåSak = true,
fagsystem = Fagsystem.DAGPENGER,
saksnummer = RandomOSURId.generate(),
saksbehandlerId = "en-saksbehandler",
utbetalingsperiode = emptyList(),
iverksettingId = null,
)
| 8 | Kotlin | 1 | 0 | a62fb761f5184348a284ed6fff2ba0dac056c6f9 | 5,623 | utsjekk | MIT License |
src/main/kotlin/no/nav/pensjon/opptjening/omsorgsopptjening/felles/domene/periode/Periode.kt | navikt | 601,019,188 | false | {"Kotlin": 10474} | package no.nav.pensjon.opptjening.omsorgsopptjening.felles.domene.periode
import java.time.Month
import java.time.YearMonth
data class Periode private constructor(private val months: Set<YearMonth> = setOf()) {
constructor(fom: YearMonth, tom: YearMonth) : this((fom..tom).toSet())
constructor() : this(setOf())
constructor(år: Int): this(YearMonth.of(år, Month.JANUARY), YearMonth.of(år, Month.DECEMBER))
fun antallMoneder(): Int = alleMåneder().size
fun overlapper(vararg ar: Int): Boolean = months.map{it.year}.any { ar.contains(it) }
infix fun begrensTilAr(ar: Int): Periode = Periode(months.filter { it.year == ar }.toSet())
operator fun plus(other: Periode) = Periode(this.months + other.months)
operator fun minus(other: Periode) = Periode(this.months - other.months)
fun overlappendeMåneder(år: Int): Periode {
return months.filter { it.year == år }
.let {
if(it.isEmpty()) Periode() else Periode(it.min(), it.max())
}
}
fun overlappendeMåneder(måneder: Set<YearMonth>): Set<YearMonth> {
return months.union(måneder)
}
fun inneholderMåned(måned: YearMonth): Boolean {
return months.contains(måned)
}
fun min(): YearMonth {
return months.min()
}
fun max(): YearMonth {
return months.max()
}
fun alleMåneder(): Set<YearMonth>{
return months
}
}
| 0 | Kotlin | 0 | 0 | b294c6a1f4618efd4237605fc2df823ab2477433 | 1,435 | omsorgsopptjening-domene-lib | MIT License |
arrow-libs/core/arrow-core/src/jvmTest/kotlin/examples/example-option-23.kt | arrow-kt | 86,057,409 | false | {"Kotlin": 2793646, "Java": 7691} | // This file was automatically generated from Option.kt by Knit tool. Do not edit.
package arrow.core.examples.exampleOption18
import arrow.core.Some
import arrow.core.None
import arrow.core.Option
fun main() {
Some(12).isSome { it > 10 } // Result: true
Some(7).isSome { it > 10 } // Result: false
val none: Option<Int> = None
none.isSome { it > 10 } // Result: false
}
| 38 | Kotlin | 436 | 5,958 | 5f0da6334b834bad481c7e3c906bee5a34c1237b | 388 | arrow | Apache License 2.0 |
src/main/kotlin/uk/co/edgeorgedev/versionkontrol/VersionCode.kt | ed-george | 114,883,256 | false | null | package uk.co.edgeorgedev.versionkontrol
import java.util.*
/**
* A class to represent a version code
*
* The version code is determined from the [rawValue] string and split using the [delimiter] value which defaults
* to the punctuation character regular expression class
*
* @author <NAME> (<EMAIL>)
* @since 0.1.0
*/
class VersionCode(rawValue: String, delimiter: String = VersionCode.DEFAULT_DELIMITER): Comparable<VersionCode> {
companion object {
// By default use the Punctuation character class as the version delimiter
// This includes common version code characters such as '.' or '-'
val DEFAULT_DELIMITER = "\\p{Punct}+"
}
// Private version code split by the provided delimiter as a RegEx
private val splitVersion: Array<String> = rawValue.split(delimiter.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
override fun equals(other: Any?): Boolean {
return when (other) {
// If supplied type is a VersionCode, directly compare
is VersionCode -> this.compareTo(other) == 0
// If supplied type is a String, compare after conversion
is String -> this.compareTo(VersionCode(other)) == 0
// Otherwise, equality is false
else -> false
}
}
override fun compareTo(other: VersionCode): Int {
// Access split version array from compared version code
val comparedVersionSplit = other.splitVersion
// Determine length of largest version code in terms of the number of splits
val maxVersionLength = Math.max(splitVersion.size, comparedVersionSplit.size)
// Iterate over the split version code arrays up-to the max length
for (index in 0 until maxVersionLength) {
// Check if current index is greater than or equal to relevant array's size. If true, use 0 as current int
// If false, attempt to convert the current split's index String to an int. If this conversion fails,
// it falls back to 0.
// TODO: Check if this fallback to 0 produces undesirable results when comparing 'invalid' version codes
val originalVersionInt: Int = if (index >= this.splitVersion.size) 0 else splitVersion[index].toSafeInt()
val comparedVersionInt: Int = if (index >= comparedVersionSplit.size) 0 else comparedVersionSplit[index].toSafeInt()
// If the int being compared is GT the original then the version being compared is greater
if (comparedVersionInt > originalVersionInt) {
return -1
} else if (originalVersionInt > comparedVersionInt) {
// If the int of the original is GT the compared int then the version being compared is lower
return 1
}
// If the numbers were the same, continue loop
}
// Version codes compared are equal
return 0
}
override fun hashCode(): Int {
return Arrays.hashCode(splitVersion)
}
override fun toString(): String {
// Re-write version using . as separator
return splitVersion.joinToString(separator = ".")
}
} | 1 | Kotlin | 1 | 5 | 7ada91cc5ef0ee7d0a64f307a35113a07b6b1744 | 3,190 | VersionKontrol | MIT License |
app/src/main/java/edu/syr/smalltalk/ui/main/group/GroupListFragment.kt | tacticalmixtu | 305,933,286 | true | {"Kotlin": 181475} | package edu.syr.smalltalk.ui.main.group
import android.content.Context
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.findNavController
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.LinearLayoutManager
import edu.syr.smalltalk.R
import edu.syr.smalltalk.service.ISmallTalkServiceProvider
import edu.syr.smalltalk.service.KVPConstant
import edu.syr.smalltalk.service.model.logic.SmallTalkApplication
import edu.syr.smalltalk.service.model.logic.SmallTalkViewModel
import edu.syr.smalltalk.service.model.logic.SmallTalkViewModelFactory
import edu.syr.smalltalk.ui.main.MainFragmentDirections
import kotlinx.android.synthetic.main.fragment_groups.*
class GroupListFragment: Fragment(), GroupListAdapter.GroupClickListener {
private val adapter = GroupListAdapter()
private val viewModel: SmallTalkViewModel by viewModels {
SmallTalkViewModelFactory(requireContext().applicationContext as SmallTalkApplication)
}
private lateinit var serviceProvider: ISmallTalkServiceProvider
override fun onAttach(context: Context) {
super.onAttach(context)
serviceProvider = requireActivity() as ISmallTalkServiceProvider
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_groups, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
adapter.setGroupClickListener(this)
recycler_view_group.layoutManager = LinearLayoutManager(context)
recycler_view_group.adapter = adapter
val userId: Int = PreferenceManager
.getDefaultSharedPreferences(requireActivity().applicationContext)
.getInt(KVPConstant.K_CURRENT_USER_ID, 0)
viewModel.getCurrentUserInfo(userId).observe(viewLifecycleOwner, { user ->
if (user.isEmpty()) {
if (serviceProvider.hasService()) {
serviceProvider.getService()!!.loadUser()
}
} else {
for (groupId in user[0].groupList) {
viewModel.getCurrentGroup(groupId).observe(viewLifecycleOwner, { group ->
if (group.isEmpty()) {
if (serviceProvider.hasService()) {
serviceProvider.getService()!!.loadGroup(groupId)
}
}
})
}
}
})
viewModel.getGroupList(userId).observe(viewLifecycleOwner, { groupList ->
groupList.let {
adapter.submitList(it)
}
})
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menu.clear()
inflater.inflate(R.menu.menu_groups, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.navigation_join_group -> {
val action = MainFragmentDirections.groupListSearchGroup()
requireView().findNavController().navigate(action)
}
R.id.navigation_create_group -> {
val action = MainFragmentDirections.groupListCreateGroup()
requireView().findNavController().navigate(action)
}
}
return true
}
override fun onItemClickListener(view: View, groupId: Int) {
val action = MainFragmentDirections.groupListViewGroup(groupId, true)
requireView().findNavController().navigate(action)
}
override fun onItemLongClickListener(view: View, groupId: Int) {
}
}
| 0 | Kotlin | 0 | 0 | 8aa1b6a399e0dd3c0837f783c12f6acf1069c3d4 | 4,073 | SmallTalk | MIT License |
http4k-connect/src/test/kotlin/extending_http4k_connect/FakeExpensesSystem.kt | http4k | 294,899,969 | false | {"Kotlin": 109361, "HTML": 9602, "TypeScript": 5684, "JavaScript": 1836, "Shell": 1783, "Dockerfile": 1125, "Handlebars": 353, "CSS": 270} | package extending_http4k_connect
import extending_http4k_connect.model.Expense
import org.http4k.chaos.ChaoticHttpHandler
import org.http4k.chaos.start
import org.http4k.connect.storage.InMemory
import org.http4k.connect.storage.Storage
import org.http4k.routing.routes
import java.util.concurrent.atomic.AtomicInteger
class FakeExpensesSystem(
storage: Storage<Expense> = Storage.InMemory(),
counter: AtomicInteger = AtomicInteger()
) : ChaoticHttpHandler() {
override val app = routes(
addExpense(storage, counter),
expenseReport(storage)
)
}
// if you run this you will see the (static) port which is allocated automatically by http4k
fun main() {
FakeExpensesSystem().start()
}
| 1 | Kotlin | 11 | 85 | 4e689b3f6cee49c3bd8c02fbe53119f1dc59e581 | 721 | examples | Apache License 2.0 |
components/updater/impl/src/test/kotlin/com/flipperdevices/updater/impl/FirmwareVersionBuildHelperTest.kt | flipperdevices | 288,258,832 | false | null | package com.flipperdevices.updater.impl
import com.flipperdevices.updater.impl.api.FirmwareVersionBuilderApiImpl
import com.flipperdevices.updater.model.FirmwareChannel
import com.flipperdevices.updater.model.FirmwareVersion
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class FirmwareVersionBuildHelperTest(
private val version: String,
private val firmwareVersion: FirmwareVersion?
) {
@Test
fun `Correct firmware`() {
val firmware = FirmwareVersionBuilderApiImpl().buildFirmwareVersionFromString(version)
Assert.assertEquals(firmware, firmwareVersion)
}
companion object {
@JvmStatic
@Parameterized.Parameters
fun data() = listOf(
arrayOf(
"fc15d5cc 0.61.1 1333 28-06-2022",
FirmwareVersion(
channel = FirmwareChannel.RELEASE,
version = "0.61.1",
buildDate = "28-06-2022"
)
),
arrayOf(
"577a4ba5 0.62.1-rc 1327 12-07-2022",
FirmwareVersion(
channel = FirmwareChannel.RELEASE_CANDIDATE,
version = "0.62.1",
buildDate = "12-07-2022"
)
),
arrayOf(
"2a8ea142 dev 2270 11-07-2022",
FirmwareVersion(
channel = FirmwareChannel.DEV,
version = "2a8ea142",
buildDate = "11-07-2022"
)
),
arrayOf(
"532082f3 dev-cfw 1784 10-07-2022",
FirmwareVersion(
channel = FirmwareChannel.UNKNOWN,
version = "dev-cfw",
buildDate = "10-07-2022"
)
),
arrayOf(
"532082f3 1784 10-07-2022",
null
)
)
}
}
| 21 | null | 174 | 999 | ef27b6b6a78a59b603ac858de2c88f75b743f432 | 2,044 | Flipper-Android-App | MIT License |
composeApp/src/commonMain/kotlin/dev/anvith/binanceninja/data/NotificationService.kt | humblerookie | 734,842,239 | false | {"Kotlin": 159018, "Swift": 4768} | package dev.anvith.binanceninja.data
import dev.anvith.binanceninja.domain.models.NotificationModel
expect class NotificationService {
fun notify(items: List<NotificationModel>)
} | 2 | Kotlin | 1 | 1 | 351e3924e3333663d2b43fe3b8e97139c97a7a6c | 186 | binance-ninja | Apache License 2.0 |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/secretsmanager/SecretRotationPropsDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION")
package cloudshift.awscdk.dsl.services.secretsmanager
import cloudshift.awscdk.common.CdkDslMarker
import cloudshift.awscdk.dsl.services.ec2.SubnetSelectionDsl
import software.amazon.awscdk.Duration
import software.amazon.awscdk.services.ec2.IConnectable
import software.amazon.awscdk.services.ec2.IInterfaceVpcEndpoint
import software.amazon.awscdk.services.ec2.ISecurityGroup
import software.amazon.awscdk.services.ec2.IVpc
import software.amazon.awscdk.services.ec2.SubnetSelection
import software.amazon.awscdk.services.secretsmanager.ISecret
import software.amazon.awscdk.services.secretsmanager.SecretRotationApplication
import software.amazon.awscdk.services.secretsmanager.SecretRotationProps
import kotlin.Boolean
import kotlin.String
import kotlin.Unit
/**
* Construction properties for a SecretRotation.
*
* Example:
*
* ```
* Secret myUserSecret;
* Secret myMasterSecret;
* IConnectable myDatabase;
* Vpc myVpc;
* SecretRotation.Builder.create(this, "SecretRotation")
* .application(SecretRotationApplication.MYSQL_ROTATION_MULTI_USER)
* .secret(myUserSecret) // The secret that will be rotated
* .masterSecret(myMasterSecret) // The secret used for the rotation
* .target(myDatabase)
* .vpc(myVpc)
* .build();
* ```
*/
@CdkDslMarker
public class SecretRotationPropsDsl {
private val cdkBuilder: SecretRotationProps.Builder = SecretRotationProps.builder()
/**
* @param application The serverless application for the rotation.
*/
public fun application(application: SecretRotationApplication) {
cdkBuilder.application(application)
}
/**
* @param automaticallyAfter Specifies the number of days after the previous rotation before
* Secrets Manager triggers the next automatic rotation.
*/
public fun automaticallyAfter(automaticallyAfter: Duration) {
cdkBuilder.automaticallyAfter(automaticallyAfter)
}
/**
* @param endpoint The VPC interface endpoint to use for the Secrets Manager API.
* If you enable private DNS hostnames for your VPC private endpoint (the default), you don't
* need to specify an endpoint. The standard Secrets Manager DNS hostname the Secrets Manager
* CLI and SDKs use by default (https://secretsmanager.<region>.amazonaws.com) automatically
* resolves to your VPC endpoint.
*/
public fun endpoint(endpoint: IInterfaceVpcEndpoint) {
cdkBuilder.endpoint(endpoint)
}
/**
* @param excludeCharacters Characters which should not appear in the generated password.
*/
public fun excludeCharacters(excludeCharacters: String) {
cdkBuilder.excludeCharacters(excludeCharacters)
}
/**
* @param masterSecret The master secret for a multi user rotation scheme.
*/
public fun masterSecret(masterSecret: ISecret) {
cdkBuilder.masterSecret(masterSecret)
}
/**
* @param rotateImmediatelyOnUpdate Specifies whether to rotate the secret immediately or wait
* until the next scheduled rotation window.
*/
public fun rotateImmediatelyOnUpdate(rotateImmediatelyOnUpdate: Boolean) {
cdkBuilder.rotateImmediatelyOnUpdate(rotateImmediatelyOnUpdate)
}
/**
* @param secret The secret to rotate. It must be a JSON string with the following format:.
* ```
* {
* "engine": <required: database engine>,
* "host": <required: instance host name>,
* "username": <required: username>,
* "password": <required: <PASSWORD>>,
* "dbname": <optional: database name>,
* "port": <optional: if not specified, default port will be used>,
* "masterarn": <required for multi user rotation: the arn of the master secret which will be
* used to create users/change passwords>
* }
* ```
*
* This is typically the case for a secret referenced from an
* `AWS::SecretsManager::SecretTargetAttachment`
* or an `ISecret` returned by the `attach()` method of `Secret`.
*/
public fun secret(secret: ISecret) {
cdkBuilder.secret(secret)
}
/**
* @param securityGroup The security group for the Lambda rotation function.
*/
public fun securityGroup(securityGroup: ISecurityGroup) {
cdkBuilder.securityGroup(securityGroup)
}
/**
* @param target The target service or database.
*/
public fun target(target: IConnectable) {
cdkBuilder.target(target)
}
/**
* @param vpc The VPC where the Lambda rotation function will run.
*/
public fun vpc(vpc: IVpc) {
cdkBuilder.vpc(vpc)
}
/**
* @param vpcSubnets The type of subnets in the VPC where the Lambda rotation function will run.
*/
public fun vpcSubnets(vpcSubnets: SubnetSelectionDsl.() -> Unit = {}) {
val builder = SubnetSelectionDsl()
builder.apply(vpcSubnets)
cdkBuilder.vpcSubnets(builder.build())
}
/**
* @param vpcSubnets The type of subnets in the VPC where the Lambda rotation function will run.
*/
public fun vpcSubnets(vpcSubnets: SubnetSelection) {
cdkBuilder.vpcSubnets(vpcSubnets)
}
public fun build(): SecretRotationProps = cdkBuilder.build()
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 5,431 | awscdk-dsl-kotlin | Apache License 2.0 |
src/main/kotlin/com/amulet/cavinist/service/wine/RegionService.kt | antoine-mulet | 254,576,347 | false | null | package com.amulet.cavinist.service.wine
import com.amulet.cavinist.persistence.data.wine.*
import com.amulet.cavinist.persistence.repository.wine.RegionRepository
import org.springframework.stereotype.Service
import reactor.core.publisher.*
import java.util.UUID
@Service
class RegionService(val repository: RegionRepository, val entityFactory: WineEntityFactory) {
fun getRegion(id: UUID, userId: UUID): Mono<RegionEntity> = repository.findForUser(id, userId)
fun listRegions(userId: UUID): Flux<RegionEntity> = repository.findAllForUser(userId)
fun createRegion(newRegion: NewRegion, userId: UUID): Mono<RegionEntity> =
repository.save(entityFactory.newRegion(newRegion.name, newRegion.country, userId))
} | 0 | Kotlin | 0 | 0 | 8696e46534547287c8f18c99753d878e8654f4cf | 733 | cavinist | Apache License 2.0 |
androidApp/src/main/java/dev/vengateshm/kotlin_multiplatform_samples/android/di/LoggerModule.kt | vengateshm | 767,983,517 | false | {"Kotlin": 47549, "Swift": 7392} | package dev.vengateshm.kotlin_multiplatform_samples.android.di
import dev.vengateshm.kotlin_multiplatform_samples.AndroidAppLogger
import dev.vengateshm.kotlin_multiplatform_samples.AppLogger
import org.koin.dsl.module
val appLoggerModule = module {
single<AppLogger> { AndroidAppLogger() }
} | 0 | Kotlin | 0 | 1 | 298d73f03ef51c44b3316a2248da999f6f0568bb | 298 | KMP-Udemy-Course-Practice | Apache License 2.0 |
app/src/main/java/com/example/bodima/models/Grocery.kt | sandarujayathilaka | 636,263,395 | false | {"Kotlin": 283279} | package com.example.bodima.models
data class Grocery(var title:String?=null,
var subtitle:String?=null,
var discount:String?=null,
var price:String?=null,
var tpNO:String?=null,
var locate:String?=null,
var about:String?=null,
var category:String?=null,
var id:String?=null,
var email:String?=null,
var groceryimg:String?=""
){
}
| 0 | Kotlin | 1 | 1 | 4b92e63d451877a11c9628c613e5a187ff499069 | 540 | Bodima-App | MIT License |
src/test/kotlin/com/doist/gradle/changelog/ChangelogProcessorTest.kt | AfzalivE | 385,803,292 | true | {"Kotlin": 15135} | package com.doist.gradle.changelog
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class ChangelogProcessorTest {
@get:Rule
var testFolder = TemporaryFolder()
@Test
fun `inserting entries`() {
val changelogFile = testFolder.newFile()
val changelog = """
# Changelog
## 0.0.1
- Bug fix 1
- Bug fix 2
""".trimIndent()
changelogFile.writeText(changelog)
val changelogProcessor = ChangelogProcessor(
CommitConfig(
prefix = "## 0.0.2",
postfix = "",
entryPrefix = "- ",
insertAtLine = 2
)
)
changelogProcessor.insertEntries(changelogFile, listOf("Feature 1", "Feature 2"))
val expectedChangelog = """
# Changelog
## 0.0.2
- Feature 1
- Feature 2
## 0.0.1
- Bug fix 1
- Bug fix 2
""".trimIndent()
assertEquals(expectedChangelog, changelogFile.readText())
}
}
| 0 | null | 0 | 0 | 7ad0702cac7e9d34a86caa29e2299247db675259 | 1,156 | changelog-gradle-plugin | MIT License |
app/src/main/java/com/akashi/notesapp/presentation/MainActivity.kt | akashigamedev | 875,121,701 | false | {"Kotlin": 6528} | package com.akashi.notesapp.presentation
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.modifier.modifierLocalMapOf
import androidx.compose.ui.res.colorResource
import androidx.core.provider.FontsContractCompat.Columns
import com.akashi.notesapp.presentation.components.Note
import com.akashi.notesapp.ui.theme.NotesAppTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
NotesAppTheme {
Column(modifier = Modifier.fillMaxSize().background(Color.Black)) {
Note()
Note()
Note()
Note()
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 33165b2ec073cb05bc5f4d507715f7b126cd4d90 | 1,112 | Notes_App | Apache License 2.0 |
app/src/main/java/com/crrl/beatplayer/ui/binding/BindingAdapter.kt | bg-write | 391,164,835 | true | {"Kotlin": 507543} | /*
* Copyright (c) 2020. <NAME>. All rights reserved.
* 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 com.crrl.beatplayer.ui.binding
import android.annotation.SuppressLint
import android.content.ContentUris
import android.support.v4.media.session.PlaybackStateCompat.*
import android.text.Html
import android.view.View
import android.view.View.*
import android.widget.*
import androidx.appcompat.content.res.AppCompatResources.getDrawable
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.crrl.beatplayer.R
import com.crrl.beatplayer.extensions.*
import com.crrl.beatplayer.models.*
import com.crrl.beatplayer.utils.BeatConstants
import com.crrl.beatplayer.utils.BeatConstants.ALBUM_TYPE
import com.crrl.beatplayer.utils.BeatConstants.ARTIST_TYPE
import com.crrl.beatplayer.utils.BeatConstants.FAVORITE_TYPE
import com.crrl.beatplayer.utils.BeatConstants.FOLDER_TYPE
import com.crrl.beatplayer.utils.GeneralUtils
import com.crrl.beatplayer.utils.GeneralUtils.PORTRAIT
import com.crrl.beatplayer.utils.GeneralUtils.getOrientation
import com.crrl.beatplayer.utils.SettingsUtility
import com.github.florent37.kotlin.pleaseanimate.please
import jp.wasabeef.glide.transformations.BlurTransformation
import rm.com.audiowave.AudioWaveView
import timber.log.Timber
import java.util.*
/**
* @param view is the target view.
* @param albumId is the id that will be used to get the image form the DB.
* @param recycled, if it is true the placeholder will be the last song cover selected.
* */
@BindingAdapter("app:albumId", "app:recycled", "app:blurred", requireAll = false)
fun setAlbumId(
view: ImageView,
albumId: Long,
recycled: Boolean = false,
blurred: Boolean = false
) {
view.clipToOutline = true
val uri = ContentUris.withAppendedId(BeatConstants.ARTWORK_URI, albumId)
val drawable = getDrawable(view.context, R.drawable.ic_empty_cover)
Glide.with(view).asBitmap().load(uri).apply {
if (recycled) placeholder(R.color.transparent) else placeholder(drawable)
if (blurred) transform(BlurTransformation(25, 5))
if (blurred) error(R.color.transparent) else error(drawable)
centerCrop()
into(view)
}
}
@BindingAdapter("app:width", "app:height", "app:check_navbar_height", requireAll = false)
fun setImageSize(
view: View,
width: Int? = null,
height: Int? = null,
checkNavbarHeight: Boolean = false
) {
val navBarHeight = if (checkNavbarHeight) GeneralUtils.getNavigationBarHeight(view.resources) else 0
view.layoutParams.apply {
if(width ?: this.width == this.width && (height ?: this.height) - navBarHeight == this.height) return
this.width = width ?: this.width
this.height = (height ?: this.height) - navBarHeight
}
if (view is ImageView) view.scaleType = ImageView.ScaleType.CENTER_CROP
if (checkNavbarHeight){
view.visibility = GONE
view.visibility = VISIBLE
}
}
@BindingAdapter("app:html")
fun setTextHtml(view: TextView, html: String) {
view.setText(Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE)
}
@BindingAdapter("app:track_number")
fun setTrackNumber(view: TextView, trackNumber: Int) {
val numberStr = when (trackNumber) {
0 -> "-"
else -> trackNumber.toString()
}
view.text = numberStr
}
@BindingAdapter("app:queue_position")
fun setQueuePosition(view: TextView, queuePosition: String) {
view.text = ExtraInfo.fromString(queuePosition).queuePosition
}
@SuppressLint("SetTextI18n")
@BindingAdapter("app:extra_info")
fun setExtraInfo(view: TextView, extraInfo: String) {
val info = ExtraInfo.fromString(extraInfo)
view.text = "${info.frequency} ${info.bitRate} ${info.fileType}".toUpperCase(Locale.ROOT)
val visibility = if (view.text.isNullOrEmpty() || !SettingsUtility(view.context).isExtraInfo) {
GONE
} else VISIBLE
(view.parent as LinearLayout).visibility = visibility
}
@BindingAdapter("app:isFav")
fun isSongFav(view: ImageButton, isFav: Boolean) {
if (isFav) {
view.setImageDrawable(getDrawable(view.context, R.drawable.ic_favorite))
} else {
view.setImageDrawable(getDrawable(view.context, R.drawable.ic_no_favorite))
}
}
@BindingAdapter("app:playState")
fun setPlayState(view: ImageView, state: Int) {
when (state) {
STATE_PLAYING -> view.setImageResource(R.drawable.ic_pause)
else -> view.setImageResource(R.drawable.ic_play)
}
}
@BindingAdapter("app:repeatState")
fun setRepeatState(view: ImageView, state: Int) {
when (state) {
REPEAT_MODE_ONE -> view.apply { setImageResource(R.drawable.ic_repeat_one) }
REPEAT_MODE_ALL -> view.setImageResource(R.drawable.ic_repeat_all)
else -> view.setImageResource(R.drawable.ic_repeat)
}
}
@BindingAdapter("app:shuffleState")
fun setShuffleState(view: ImageView, state: Int) {
when (state) {
SHUFFLE_MODE_ALL -> view.setImageResource(R.drawable.ic_shuffle_all)
else -> view.setImageResource(R.drawable.ic_shuffle)
}
}
@BindingAdapter("app:raw")
fun updateRawData(view: AudioWaveView, raw: ByteArray) {
try {
view.setRawData(raw)
} catch (e: IllegalStateException) {
Timber.e(e)
}
}
@BindingAdapter("app:selectedSongs")
fun setTextTitle(view: TextView, selectedSongs: MutableList<Song>) {
if (selectedSongs.size == 0) {
view.setText(R.string.select_tracks)
} else {
view.text = "${selectedSongs.size}"
}
}
@BindingAdapter("app:type")
fun setTextByType(view: TextView, type: String) {
view.apply {
text = when (type) {
ARTIST_TYPE -> context.getString(R.string.artist)
ALBUM_TYPE -> context.getString(R.string.albums)
FOLDER_TYPE -> context.getString(R.string.folders)
else -> {
view.visibility = GONE
""
}
}
}
}
@BindingAdapter("app:title", "app:detail", requireAll = false)
fun setTextTitle(view: TextView, favorite: Favorite, detail: Boolean = false) {
view.apply {
text = if (favorite.type == FAVORITE_TYPE) {
context.getString(R.string.favorite_music)
} else {
favorite.title
}
}
}
@BindingAdapter("app:type", "app:count")
fun setCount(view: TextView, type: String, count: Int) {
view.text = view.resources.getQuantityString(
if (type == ARTIST_TYPE) {
R.plurals.number_of_albums
} else {
R.plurals.number_of_songs
},
count,
count
)
}
@BindingAdapter("app:by", "app:data")
fun setTextCount(view: TextView, type: String, data: SearchData) {
val count = when (type) {
ARTIST_TYPE -> data.artistList.size
ALBUM_TYPE -> data.albumList.size
else -> data.songList.size
}
val id = when (type) {
ARTIST_TYPE -> R.plurals.number_of_artists
ALBUM_TYPE -> R.plurals.number_of_albums
else -> R.plurals.number_of_songs
}
view.text = view.resources.getQuantityString(id, count, count)
}
@SuppressLint("SetTextI18n")
@BindingAdapter("app:album")
fun fixArtistLength(view: TextView, album: Album) {
val maxSize = if (getOrientation(view.context) == PORTRAIT) 13 else 8
album.apply {
view.text = "${
if (artist.length > maxSize) {
artist.substring(0, maxSize)
} else {
artist
}
} ${view.resources.getString(R.string.separator)} ${
view.resources.getQuantityString(
R.plurals.number_of_songs,
songCount,
songCount
)
}"
}
}
@BindingAdapter("app:clipToOutline")
fun setClipToOutline(view: View, clipToOutline: Boolean) {
view.clipToOutline = clipToOutline
}
@BindingAdapter("app:textUnderline")
fun textUnderline(view: TextView, textUnderline: Boolean) {
if (textUnderline)
view.text = Html.fromHtml("<u>${view.text}</u>", Html.FROM_HTML_MODE_LEGACY)
}
@BindingAdapter("app:type")
fun setMarginByType(view: View, type: String) {
val padding = view.resources.getDimensionPixelSize(R.dimen.padding_12)
when (type) {
ARTIST_TYPE, ALBUM_TYPE -> view.setPaddings(top = padding, right = padding)
}
}
@BindingAdapter("app:visible", "app:animate", requireAll = false)
fun setVisibility(view: View, visible: Boolean = true, animate: Boolean = false) {
view.toggleShow(visible, animate)
}
@BindingAdapter("app:hide", "app:state")
fun setHide(view: View, hide: Boolean, state: Int) {
if (hide) {
if (state == STATE_PLAYING) view.visibility = INVISIBLE else view.visibility = VISIBLE
} else view.visibility = VISIBLE
setSelectedTextColor(view as TextView, hide, hide)
}
@BindingAdapter("app:selected", "app:marquee")
fun setSelectedTextColor(view: TextView, selected: Boolean, marquee: Boolean) {
please(200) {
animate(view) {
if (selected) {
val color = view.context.getColorByTheme(R.attr.colorAccent)
textColor(color)
view.setCustomColor(color, opacity = !marquee)
view.isSelected = marquee
} else {
val color = view.context.getColorByTheme(
if (marquee) R.attr.titleTextColor
else R.attr.subTitleTextColor
)
view.setCustomColor(color)
}
}
}
}
@BindingAdapter("app:show", "app:state")
fun setVisualizerVisibility(view: LinearLayout, visible: Boolean, state: Int) {
if (visible) {
if (state == STATE_PLAYING) view.show(false) else view.hide(false)
} else view.hide(false)
}
@BindingAdapter("app:slide", "app:state")
fun setContainer(view: RelativeLayout, visible: Boolean, state: Int) {
if (visible) {
if (state == STATE_PLAYING) {
view.slideRight(true)
} else {
view.slideLeft(true)
}
} else view.slideLeft(false)
}
@BindingAdapter("app:state")
fun setScale(view: View, state: Int) {
if (state == STATE_PLAYING) {
view.scaleUp()
} else {
view.scaleDown()
}
}
@BindingAdapter("app:album", "app:artist")
fun setArtistAlbum(view: TextView, artist: String?, album: String?) {
view.text = if (artist != null && album != null)
view.context.getString(R.string.with_separator, artist, album)
else artist ?: album ?: ""
}
@BindingAdapter("app:isSelected", requireAll = true)
fun setSelected(view: View, selected: Boolean) {
view.isSelected = selected
}
| 0 | null | 0 | 1 | 3daa6902cdaa51837669b7916b362da429e23959 | 11,155 | BeatPlayer | Apache License 2.0 |
presentation/src/main/java/com/htecgroup/androidcore/presentation/viewmodel/CoreViewModel.kt | htecgroup | 614,231,356 | false | null | /*
* Copyright 2023 HTEC Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.htecgroup.androidcore.presentation.viewmodel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.htecgroup.androidcore.presentation.model.DataUiState
import com.htecgroup.androidcore.presentation.model.DataUiState.Idle
/**
* Base [ViewModel] class, where [T] is enum representing actions.
*/
abstract class CoreViewModel<T : Any> : ViewModel() {
var uiState by mutableStateOf<DataUiState<T>>(Idle())
protected set
open fun clearState() {
uiState = Idle()
}
}
| 0 | Kotlin | 1 | 3 | f995c32c19b1a794f9b0e841a4d05266e28d9683 | 1,225 | android-core | Apache License 2.0 |
app/src/main/kotlin/io/github/andrewfitzy/day09/Task02.kt | andrewfitzy | 747,793,365 | false | {"Kotlin": 79067, "Shell": 1211} | package io.github.andrewfitzy.day09
class Task02(puzzleInput: List<String>) {
private val input: List<String> = puzzleInput
fun solve(): Long {
val line = input.first()
val length = getDecompressedChunkLength(line)
return length
}
private fun getDecompressedChunkLength(chunk: String): Long {
var pointer = 0
var length = 0L
while (pointer < chunk.length) {
if (chunk[pointer] == '(') {
val subs = chunk.substring(pointer + 1, chunk.indexOf(')', pointer))
pointer += subs.length + 2
val chars = subs.split("x")[0].toInt()
val repeats = subs.split("x")[1].toInt()
val repeatString = chunk.substring(pointer, pointer + chars)
if (repeatString.contains("(")) {
length += repeats * getDecompressedChunkLength(repeatString)
} else {
length += chars * repeats
}
pointer += repeatString.length
} else {
pointer++
length++
}
}
return length
}
}
| 0 | Kotlin | 0 | 0 | 3391908bcfcc8562c1efc72bc1f4e316179b98d2 | 1,179 | 2016-advent-of-code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/org/bonitasoft/engine/dsl/process/ExclusiveGateway.kt | baptistemesta | 166,183,548 | false | null | package org.bonitasoft.engine.dsl.process
import org.bonitasoft.engine.bpm.flownode.GatewayType
import org.bonitasoft.engine.bpm.process.impl.FlowElementContainerBuilder
import org.bonitasoft.engine.bpm.process.impl.ProcessDefinitionBuilder
class ExclusiveGateway(parent: org.bonitasoft.engine.dsl.process.DataContainer, name: String) : FlowNode(parent, name) {
override fun buildFlowNode(builder: ProcessDefinitionBuilder): FlowElementContainerBuilder {
return builder.addGateway(name, GatewayType.EXCLUSIVE)
}
}
| 0 | Kotlin | 0 | 0 | 2313c8a69e690c4083bde6425de4307cb2233644 | 532 | process-kotlin-dsl | MIT License |
app/src/main/java/com/example/todo/adapters/TodoRVAdapter.kt | xtanion | 389,537,870 | false | null | package com.example.todo.adapters
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.todo.R
import com.example.todo.data.TodoEntity
import com.example.todo.databinding.SingleColumnBinding
import kotlinx.android.synthetic.main.single_column.view.*
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.time.format.DateTimeFormatter
import java.util.*
class TodoRVAdapter(val rvInterface: RVInterface): RecyclerView.Adapter<TodoRVAdapter.TodoViewHolder>(){
private var DataList = emptyList<TodoEntity>()
var _binding : SingleColumnBinding? = null
val binding get() = _binding!!
private lateinit var context:Context
private var lastPosition: Int = -1
inner class TodoViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
init {
itemView.checkbox_column.setOnClickListener {
val position: Int = adapterPosition
val data:TodoEntity = DataList[position]
rvInterface.onCheckboxClick(data)
}
itemView.star_icon_column.setOnClickListener{
val position: Int = adapterPosition
val data: TodoEntity = DataList[position]
rvInterface.onStarClick(data)
}
itemView.setOnClickListener{
val position: Int = adapterPosition
val data: TodoEntity = DataList[position]
rvInterface.onViewClick(data)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {
_binding = SingleColumnBinding.inflate(LayoutInflater.from(parent.context),parent,false)
context = parent.context
return TodoViewHolder(binding.root)
}
@SuppressLint("ResourceAsColor")
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
val currentItem = DataList[position]
val star_icon: ImageView = binding.starIconColumn
val due = currentItem.dueDate
var formattedDate:String? = null
var dateObject:Date? = null
if (due!=null) {
val format = SimpleDateFormat("dd/MM/yyyy")
dateObject = format.parse(due)
formattedDate = getFormattedDate(dateObject!!)
}
if (holder.adapterPosition > lastPosition) {
val animation: Animation =
AnimationUtils.loadAnimation(holder.itemView.context, R.anim.fall_down)
holder.itemView.startAnimation(animation)
}
binding.checkboxTextColumn.text = currentItem.title
if (currentItem.completed) {
binding.checkboxColumn.isChecked = true
binding.checkboxTextColumn.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG
} else {
binding.checkboxColumn.isChecked = false
}
if (currentItem.important == true) {
binding.starIconColumn.isVisible = true
binding.starIconColumn.imageTintList =
(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.red)))
}
if (currentItem.alarmTime!=null){
val timeCombined = currentItem.alarmTime.toInt()
val hrs:Int = timeCombined/100
val min:Int = timeCombined%100
if (due!=null){
binding.checkboxAdditionalText.apply{
text = String.format("%02d:%02d \u2022 Due %s",hrs,min,formattedDate)
if (Date().after(dateObject)){
setTextColor(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.red)))
//binding.alarmIconColumn.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.red))
}
}
}else{
binding.checkboxAdditionalText.
text = String.format("%02d:%02d",hrs,min)
}
binding.checkboxAdditionalText.visibility = View.VISIBLE
binding.alarmIconColumn.visibility = View.VISIBLE
}else{
if (due!=null){
binding.checkboxAdditionalText.apply {
text = String.format("Due %s",formattedDate)
if (Date().after(dateObject)){
setTextColor(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.red)))
//binding.alarmIconColumn.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.red))
}
visibility = View.VISIBLE
}
binding.alarmIconColumn.apply{
setImageResource(R.drawable.ic_calender_figma)
visibility = View.VISIBLE
}
}
}
}
private fun getFormattedDate(d: Date): String {
val today:Boolean = DateUtils.isToday(d.time)
val tomorrow:Boolean = DateUtils.isToday(d.time - DateUtils.DAY_IN_MILLIS)
val yesterday:Boolean = DateUtils.isToday(d.time + DateUtils.DAY_IN_MILLIS)
return when {
today -> {
"Today"
}
tomorrow -> {
"Tomorrow"
}
yesterday -> {
"Yesterday"
}
else -> {
val formatter = SimpleDateFormat("d MMM")
formatter.format(d)
}
}
}
override fun getItemCount(): Int {
return DataList.size
}
class TodoDiffCallback(var oldList:List<TodoEntity>,var newList: List<TodoEntity>):DiffUtil.Callback(){
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return (oldList.get(oldItemPosition).id == newList.get(newItemPosition).id)
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return (oldList.get(oldItemPosition).equals(newList.get(newItemPosition)))
}
}
@SuppressLint("NotifyDataSetChanged")
fun NotifyChanges(DataList:List<TodoEntity>){
val oldList = this.DataList
val diffResult: DiffUtil.DiffResult = DiffUtil.calculateDiff(
TodoDiffCallback(oldList,DataList)
)
this.DataList = DataList
//notifyDataSetChanged()
diffResult.dispatchUpdatesTo(this)
}
fun removeItemChange(position:Int){
val oldList = this.DataList
val newList = oldList.toMutableList()
newList.removeAt(position)
newList.toList()
val diffResult: DiffUtil.DiffResult = DiffUtil.calculateDiff(
TodoDiffCallback(oldList,newList)
)
this.DataList = newList
//notifyDataSetChanged()
diffResult.dispatchUpdatesTo(this)
}
fun addItemChange(entity: TodoEntity,position: Int){
val oldList = this.DataList
val newList = oldList.toMutableList()
newList.add(position,entity)
newList.toList()
val diffResult: DiffUtil.DiffResult = DiffUtil.calculateDiff(
TodoDiffCallback(oldList,newList)
)
this.DataList = newList
//notifyDataSetChanged()
diffResult.dispatchUpdatesTo(this)
}
interface RVInterface{
fun onCheckboxClick(data:TodoEntity)
fun onStarClick(data: TodoEntity)
fun onViewClick(data: TodoEntity)
}
} | 2 | Kotlin | 4 | 6 | e38ace85ef3eaa0895adda7819c12bb04bee549a | 8,381 | To-do-android | Apache License 2.0 |
src/main/kotlin/jp/co/soramitsu/load/TransactionOnly.kt | soramitsu | 676,030,478 | false | {"Kotlin": 46722, "Java": 37836} | package jp.co.soramitsu.load
import io.gatling.javaapi.core.CoreDsl
import io.gatling.javaapi.core.ScenarioBuilder
import jp.co.soramitsu.iroha2.client.Iroha2Client
import jp.co.soramitsu.iroha2.client.blockstream.BlockStreamStorage
import jp.co.soramitsu.iroha2.client.blockstream.BlockStreamSubscription
import jp.co.soramitsu.iroha2.query.QueryBuilder
import jp.co.soramitsu.load.infrastructure.config.SimulationConfig
import jp.co.soramitsu.load.objects.AnotherDevs
import jp.co.soramitsu.load.objects.CustomHistogram
import jp.co.soramitsu.load.toolbox.Wrench13
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.time.withTimeout
import org.apache.http.client.utils.URIBuilder
import java.time.Duration
import kotlin.random.Random
class TransactionOnly: Wrench13() {
companion object {
@JvmStatic
fun apply() = runBlocking {
TransactionOnly().applyScn()
}
}
fun applyScn(): ScenarioBuilder {
return transferAssetsOnlyScn
}
/*val peers = arrayOf("peer-0/api", "peer-1/api", "peer-2/api", "peer-3/api", "peer-4/api")
fun buildClient(peer : String): Iroha2Client {
val peerUrl = URIBuilder().let {
it.scheme = SimulationConfig.simulation.targetProtocol()
it.host = SimulationConfig.simulation.targetURL()
it.port = 0
//it.path = SimulationConfig.simulation.targetPath()
it.path = peer
it.build().toURL()
}
urls.add(peerUrl)
return Iroha2Client(
urls[0],
urls[0],
urls[0],
log = false,
credentials = SimulationConfig.simulation.remoteLogin() + ":" + SimulationConfig.simulation.remotePass(),
eventReadTimeoutInMills = 10000,
eventReadMaxAttempts = 20
)
}*/
val transferAssetsOnlyScn = CoreDsl.scenario("TransferAssets")
.repeat(SimulationConfig.simulation.attemptsToTransaction)
.on(
CoreDsl.exec { Session ->
var currentDevIndex: Int = Random.nextInt(0, AnotherDevs.list.size - 1)
currentDevAccountId = AnotherDevs.list[currentDevIndex].anotherDevAccountId
currentDevKeyPair = AnotherDevs.list[currentDevIndex].anotherDevKeyPair
currentDevAssetId = AnotherDevs.list[currentDevIndex].anotherDevAssetId
currentDevAssetIdBeforeTransferring = AnotherDevs.list[currentDevIndex].assetValue
do {
var targetDevIndex: Int = Random.nextInt(0, AnotherDevs.list.size - 1)
targetDevAccountId = AnotherDevs.list[targetDevIndex].anotherDevAccountId
targetDevKeyPair = AnotherDevs.list[targetDevIndex].anotherDevKeyPair
} while (targetDevAccountId.name.string == currentDevAccountId.name.string)
Session
}
.exec { Session ->
val randomIndex = (0 until peers.size).random()
val randomPeer = peers[randomIndex]
val Iroha2Client: Iroha2Client = buildClient(randomPeer)
timer = CustomHistogram.subscriptionToBlockStreamTimer.labels(
"gatling",
System.getProperty("user.dir").substringAfterLast("/").substringAfterLast("\\"),
Iroha2SetUp::class.simpleName
).startTimer()
try {
val idToSubscription: Pair<Iterable<BlockStreamStorage>, BlockStreamSubscription> = Iroha2Client.subscribeToBlockStream(1, 2)
subscription = idToSubscription.component2()
} finally {
timer.observeDuration()
CustomHistogram.subscriptionToBlockStreamCount.labels(
"gatling",
System.getProperty("user.dir").substringAfterLast("/").substringAfterLast("\\"),
Iroha2SetUp::class.simpleName
).inc()
sendMetricsToPrometheus(CustomHistogram.subscriptionToBlockStreamCount, "transaction")
sendMetricsToPrometheus(CustomHistogram.subscriptionToBlockStreamTimer, "transaction")
}
timer = CustomHistogram.transferAssetTimer.labels(
"gatling",
System.getProperty("user.dir").substringAfterLast("/").substringAfterLast("\\"),
Iroha2SetUp::class.simpleName
).startTimer()
try {
println("SEND_TRANSACTION: TRANSFER ASSET")
runBlocking {
Iroha2Client.sendTransaction {
account(currentDevAccountId)
transferAsset(currentDevAssetId, 1, targetDevAccountId)
buildSigned(currentDevKeyPair)
}.also { d ->
withTimeout(Duration.ofSeconds(transactionWaiter)) { d.await() }
}
subscription.close()
}
} catch (ex: RuntimeException) {
println(ex.message)
} finally {
timer.observeDuration()
CustomHistogram.transferAssetCount.labels(
"gatling",
System.getProperty("user.dir").substringAfterLast("/").substringAfterLast("\\"),
Iroha2SetUp::class.simpleName
).inc()
sendMetricsToPrometheus(CustomHistogram.transferAssetCount, "transaction")
sendMetricsToPrometheus(CustomHistogram.transferAssetTimer, "transaction")
}
val newSession = Session.set("condition", false)
newSession
}
)
} | 0 | Kotlin | 1 | 0 | fa19bc84cfec8315d12f3171477edececb4415a0 | 6,322 | iroha2-perf | Apache License 2.0 |
app/src/main/java/com/gitrend/data/remote/dto/ReposResultDto.kt | Ghedeon | 620,377,460 | false | null | package com.gitrend.data.remote.dto
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
internal data class ReposResultDto(@SerialName("items") val items: List<RepoDto>)
| 0 | Kotlin | 0 | 0 | d737053c406f196c9bb58e0246974bc3023eda19 | 216 | Gitrend | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.