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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
test/contributors/MockGithubServiceSuspend.kt | nfmohammed | 536,687,196 | false | {"Kotlin": 45541} | package contributors
import kotlinx.coroutines.delay
import retrofit2.Response
object MockGithubServiceSuspend : GitHubServiceSuspend {
override suspend fun getOrgRepos(org: String): Response<List<Repo>> {
delay(reposDelay)
return Response.success(repos)
}
override suspend fun getRepoContributors(owner: String, repo: String): Response<List<User>> {
val testRepo = reposMap.getValue(repo)
delay(testRepo.delay)
return Response.success(testRepo.users)
}
}
| 0 | Kotlin | 0 | 0 | 037561f99ebb35a596074c8170314b1eee4c8ac0 | 516 | intro-coroutines | Apache License 2.0 |
domain/src/iosMain/kotlin/io/github/lazyengineer/castaway/domain/SwiftCoroutines.kt | lazy-engineer | 321,396,462 | false | {"Kotlin": 285918, "Swift": 86110, "Ruby": 1720} | package io.github.lazyengineer.castaway.domain
import kotlin.native.concurrent.freeze
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
/**
* https://github.com/touchlab/SwiftCoroutines/blob/master/shared/src/iosMain/kotlin/co/touchlab/swiftcoroutines/SwiftCoroutines.kt
*/
sealed class SuspendWrapperParent<T>(private val suspender: suspend () -> T) {
init {
freeze()
}
fun subscribe(
scope: CoroutineScope,
onSuccess: (item: T) -> Unit,
onThrow: (error: Throwable) -> Unit
) = scope.launch {
try {
onSuccess(suspender().freeze())
} catch (error: Throwable) {
onThrow(error.freeze())
}
}.freeze()
}
class SuspendWrapper<T : Any>(suspender: suspend () -> T) : SuspendWrapperParent<T>(suspender)
class NullableSuspendWrapper<T>(suspender: suspend () -> T) : SuspendWrapperParent<T>(suspender)
sealed class FlowWrapperParent<T>(private val flow: Flow<T>) {
init {
freeze()
}
fun subscribe(
scope: CoroutineScope,
onEach: (item: T) -> Unit,
onComplete: () -> Unit,
onThrow: (error: Throwable) -> Unit
) = flow
.onEach { onEach(it.freeze()) }
.catch { onThrow(it.freeze()) } // catch{} before onCompletion{} or else completion hits first and ends stream
.onCompletion { onComplete() }
.launchIn(scope)
.freeze()
}
class FlowWrapper<T : Any>(flow: Flow<T>) : FlowWrapperParent<T>(flow)
class NullableFlowWrapper<T>(flow: Flow<T>) : FlowWrapperParent<T>(flow)
| 0 | Kotlin | 0 | 2 | 556234559b4f94cdcd5b6c2e5046c9a07ce47e4f | 1,682 | castaway | MIT License |
csp-framework/src/main/kotlin/com/tsovedenski/csp/Solution.kt | RedShuhart | 152,120,429 | false | null | package com.tsovedenski.csp
/**
* Created by <NAME> on 14/10/2018.
*/
/**
* A solution of a problem.
*
* It can be either [Solved] or [NoSolution].
*
* @param V the type of variable identifier.
* @param D the type of domain values.
*/
sealed class Solution <out V, out D> {
/**
* Pretty-print the solution.
*/
abstract fun print()
}
/**
* Represents a successful solution to a problem.
*
* @param assignment see [CompleteAssignment].
* @param statistics see [Statistics].
*/
data class Solved <V, D> (val assignment: CompleteAssignment<V, D>, val statistics: Statistics) : Solution<V, D>() {
override fun print() {
assignment.print()
statistics.print()
}
}
/**
* Represents the case when no solution was found.
*/
object NoSolution : Solution<Nothing, Nothing>() {
override fun print() {
println("No solution found")
}
}
| 0 | Kotlin | 1 | 4 | 29d59ec7ff4f0893c0d1ec895118f961dd221c7f | 900 | csp-framework | MIT License |
app/app/src/main/java/mx/ipn/upiiz/darcazaa/ui/screens/DriverActivity.kt | RamiroEda | 484,149,972 | false | null | package mx.ipn.upiiz.darcazaa.ui.screens
import android.os.Bundle
import android.view.WindowManager
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.PressGestureScope
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Switch
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import dagger.hilt.android.AndroidEntryPoint
import mx.ipn.upiiz.darcazaa.data.models.PreferenceKeys
import mx.ipn.upiiz.darcazaa.data.models.SystemStatus
import mx.ipn.upiiz.darcazaa.data.models.UserPreferences
import mx.ipn.upiiz.darcazaa.data.models.WebSocketDataSource
import mx.ipn.upiiz.darcazaa.ui.components.VideoPlayer
import mx.ipn.upiiz.darcazaa.ui.components.rememberExoPlayer
import mx.ipn.upiiz.darcazaa.ui.theme.DARCAZAATheme
import mx.ipn.upiiz.darcazaa.view_models.ChargingStationViewModel
import mx.ipn.upiiz.darcazaa.view_models.DriverViewModel
import javax.inject.Inject
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.sqrt
val JOYSTICK_SIZE = 168.dp
val JOYSTICK_BALL_SIZE = 56.dp
val BUTTON_SIZE = 64.dp
@AndroidEntryPoint
class DriverActivity : AppCompatActivity() {
private val driverViewModel: DriverViewModel by viewModels()
private val chargingStationViewModel: ChargingStationViewModel by viewModels()
@Inject
lateinit var preferences: UserPreferences
@OptIn(ExperimentalMaterial3Api::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
setContent {
val exoPlayer = rememberExoPlayer()
DARCAZAATheme {
Scaffold(
containerColor = Color.White
) {
VideoPlayer(
modifier = Modifier.fillMaxSize(),
exoPlayer = exoPlayer,
)
Box(
modifier = Modifier.fillMaxSize()
) {
var isDrivingEnabled by remember {
mutableStateOf(false)
}
Box(
modifier = Modifier
.align(Alignment.BottomStart)
.padding(16.dp)
.size(168.dp)
) {
val density = LocalDensity.current
val joystickBallCenter = with(density) {
JOYSTICK_SIZE.div(2).minus(
JOYSTICK_BALL_SIZE.div(2)
).toPx()
}
val joystickCenter = with(density) {
JOYSTICK_SIZE.div(2).toPx()
}
Box(
modifier = Modifier
.fillMaxSize()
.clip(CircleShape)
.background(
MaterialTheme.colorScheme.primaryContainer.copy(
alpha = 0.3f
)
)
) {}
var offsetAbsoluteX by remember {
mutableStateOf(joystickBallCenter)
}
var offsetAbsoluteY by remember {
mutableStateOf(joystickBallCenter)
}
var offsetX by remember {
mutableStateOf(offsetAbsoluteX)
}
var offsetY by remember {
mutableStateOf(offsetAbsoluteY)
}
Box(
Modifier
.offset {
IntOffset(
offsetX.roundToInt(),
offsetY.roundToInt()
)
}
.clip(CircleShape)
.background(MaterialTheme.colorScheme.primary)
.size(56.dp)
.pointerInput(Unit) {
detectDragGestures(
onDragEnd = {
offsetAbsoluteX = joystickBallCenter
offsetAbsoluteY = joystickBallCenter
offsetX = joystickBallCenter
offsetY = joystickBallCenter
driverViewModel.setVelocity(
x = 0.0,
y = 0.0
)
},
onDrag = { change, dragAmount ->
change.consume()
offsetAbsoluteX += dragAmount.x
offsetAbsoluteY += dragAmount.y
val magX = offsetX - joystickBallCenter
val magY = offsetY - joystickBallCenter
val magnitude = magnitude(
offsetAbsoluteX,
offsetAbsoluteY,
joystickBallCenter,
joystickBallCenter
)
if (magnitude <= joystickCenter) {
offsetX = offsetAbsoluteX
offsetY = offsetAbsoluteY
} else {
val ratio = joystickCenter / magnitude
val x = offsetAbsoluteX - joystickBallCenter
val y = offsetAbsoluteY - joystickBallCenter
offsetX = joystickBallCenter + (x * ratio)
offsetY = joystickBallCenter + (y * ratio)
}
driverViewModel.setVelocity(
y = magX
.div(joystickCenter)
.times(10)
.toDouble(),
x = magY
.times(-1)
.div(joystickCenter)
.times(10)
.toDouble()
)
}
)
}
)
}
Box(
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(16.dp)
.size(BUTTON_SIZE * 3)
) {
CustomFab(
modifier = Modifier.align(Alignment.TopCenter),
icon = Icons.Rounded.ArrowUpward,
onPress = {
driverViewModel.setVelocity(z = -1.0)
awaitRelease()
driverViewModel.setVelocity(z = 0.0)
}
)
CustomFab(
modifier = Modifier.align(Alignment.BottomCenter),
icon = Icons.Rounded.ArrowDownward,
onPress = {
driverViewModel.setVelocity(z = 1.0)
awaitRelease()
driverViewModel.setVelocity(z = 0.0)
}
)
CustomFab(
modifier = Modifier.align(Alignment.CenterStart),
icon = Icons.Rounded.Undo,
onPress = {
driverViewModel.rotate(-1)
awaitRelease()
driverViewModel.rotate(0)
}
)
CustomFab(
modifier = Modifier.align(Alignment.CenterEnd),
icon = Icons.Rounded.Redo,
onPress = {
driverViewModel.rotate(1)
awaitRelease()
driverViewModel.rotate(0)
}
)
}
Row(
modifier = Modifier.align(Alignment.TopEnd),
verticalAlignment = Alignment.CenterVertically
) {
AnimatedVisibility(visible = isDrivingEnabled) {
if (chargingStationViewModel.systemStatus.value == SystemStatus.FLYING) {
CustomFab(
icon = Icons.Rounded.FlightLand,
onPress = {
awaitRelease()
driverViewModel.land()
}
)
} else if (chargingStationViewModel.systemStatus.value == SystemStatus.IDLE
|| chargingStationViewModel.systemStatus.value == SystemStatus.WAITING_FOR_WEATHER
) {
CustomFab(
icon = Icons.Rounded.FlightTakeoff,
onPress = {
awaitRelease()
driverViewModel.takeoff()
}
)
}
}
Card(
modifier = Modifier
.padding(16.dp)
) {
Row(
modifier = Modifier.padding(
vertical = 4.dp,
horizontal = 16.dp
),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Habiltar conducción",
color = MaterialTheme.colorScheme.onSurface
)
Switch(
modifier = Modifier.padding(start = 4.dp),
checked = isDrivingEnabled,
onCheckedChange = {
isDrivingEnabled = it
if (it) {
driverViewModel.setMode("GUIDED")
} else {
driverViewModel.setMode("AUTO")
}
}
)
}
}
}
}
}
}
LaunchedEffect(key1 = exoPlayer) {
exoPlayer.setMediaSource(
ProgressiveMediaSource.Factory(WebSocketDataSource.Factory()).createMediaSource(
MediaItem
.fromUri("ws://${preferences.get(PreferenceKeys.Url)}/camera")
)
)
exoPlayer.prepare()
exoPlayer.playWhenReady = true
exoPlayer.play()
}
}
}
private fun magnitude(x: Float, y: Float, pivotX: Float = 0f, pivotY: Float = 0f) =
sqrt(((x - pivotX).pow(2) + (y - pivotY).pow(2)).toDouble()).toFloat()
}
@Composable
fun CustomFab(
modifier: Modifier = Modifier,
icon: ImageVector,
onPress: suspend PressGestureScope.(Offset) -> Unit
) {
Box(
modifier = modifier
.size(BUTTON_SIZE)
.clip(RoundedCornerShape(16.dp))
.background(MaterialTheme.colorScheme.surfaceVariant)
.pointerInput(Unit) {
detectTapGestures(
onPress = onPress
)
},
contentAlignment = Alignment.Center
) {
Icon(
imageVector = icon,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
}
} | 0 | Kotlin | 0 | 0 | 73e055a4bae7fb1753be717eed2279980717755c | 15,813 | tt_darcazaa_monorepo | MIT License |
app/src/main/java/sample/kanda/mvvm/detail/ViewModel.kt | jcaiqueoliveira | 120,309,199 | false | null | package sample.kanda.mvvm.detail
import android.arch.lifecycle.ViewModel
import sample.kanda.domain.Label
import sample.kanda.domain.RemoveContact
import sample.kanda.domain.RetrieveContacts
import sample.kanda.domain.RetrieveLabels
/**
* Created by jcosilva on 2/15/2018.
*/
class DetailViewModel(
private val retriveContact: RetrieveContacts,
private val removeContact: RemoveContact,
private val fieldDataSource: RetrieveLabels) : ViewModel() {
fun getContactInfo(id: Int): Pair<DetailedContact, Label> {
return retriveContact
.getContact(id)
.map { ContactToDetailedMapper(it) }
.zip(fieldDataSource.getScreenLabels())
.first()
}
fun excludeContact(id: Int) {
removeContact.excludeContact(id)
}
} | 0 | Kotlin | 0 | 3 | 95f5293e5c6a1112d5033ea854eb3b902bb1fef5 | 828 | sample-mvvm | MIT License |
app/src/main/java/com/carplayground/room/CarDatabase.kt | deepakkanyan | 603,557,330 | false | null | package com.carplayground.room
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.carplayground.room.converter.AppConverters
import com.carplayground.room.dao.CarDao
import com.carplayground.room.tables.Car
@Database(entities = [Car::class], version = 1, exportSchema = false)
@TypeConverters(AppConverters::class)
public abstract class CarDatabase : RoomDatabase() {
abstract fun carDao(): CarDao
} | 0 | Kotlin | 0 | 0 | df1c64227efc8b44e0dd4e484f98ae5c9f4a01ab | 466 | Car_Playground | MIT License |
onixlabs-corda-test-contract/src/main/kotlin/io/onixlabs/corda/test/contract/CustomerEntity.kt | onix-labs | 326,621,863 | false | null | /*
* Copyright 2020-2022 ONIXLabs
*
* 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.onixlabs.corda.test.contract
import net.corda.core.crypto.NullKeys.NULL_PARTY
import net.corda.core.identity.AbstractParty
import net.corda.core.schemas.MappedSchema
import net.corda.core.schemas.PersistentState
import java.time.Instant
import java.util.*
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Table
@Entity
@Table(name = "onixlabs_customer_states")
class CustomerEntity(
@Column(name = "linear_id", nullable = false)
val linearId: UUID = UUID.randomUUID(),
@Column(name = "external_id", nullable = true)
val externalId: String? = null,
@Column(name = "owner", nullable = false)
val owner: AbstractParty = NULL_PARTY,
@Column(name = "first_name", nullable = false)
val firstName: String = "",
@Column(name = "last_name", nullable = false)
val lastName: String = "",
@Column(name = "birthday", nullable = true)
val birthday: Instant = Instant.MIN,
/**
* Since chain state previous state references should start at null,
* including this in the schema allows queries for all new/un-evolved states.
*/
@Column(name = "previous_state_ref")
val previousStateRef: String? = null,
@Column(name = "hash", nullable = false, unique = true)
val hash: String = ""
) : PersistentState() {
companion object CustomerSchema {
object CustomerSchemaV1 : MappedSchema(CustomerSchema::class.java, 1, listOf(CustomerEntity::class.java)) {
override val migrationResource = "customer-schema.changelog-master"
}
}
}
| 0 | Kotlin | 0 | 4 | 82197de7830ee3ca5646004ed8ac23116ef4bba1 | 2,180 | onixlabs-corda-core | Apache License 2.0 |
shared/src/iosMain/kotlin/com.thomaskioko.tvmaniac.shared/base/wrappers/SeasonDetailsStateMachineWrapper.kt | c0de-wizard | 361,393,353 | false | null | package com.thomaskioko.tvmaniac.shared.base.wrappers
import com.thomaskioko.tvmaniac.presentation.seasondetails.SeasonDetailsAction
import com.thomaskioko.tvmaniac.presentation.seasondetails.SeasonDetailsState
import com.thomaskioko.tvmaniac.presentation.seasondetails.SeasonDetailsStateMachine
import com.thomaskioko.tvmaniac.util.model.AppCoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import me.tatarka.inject.annotations.Inject
/**
* A wrapper class around [SeasonDetailsStateMachine] handling `Flow` and suspend functions on iOS.
*/
@Inject
class SeasonDetailsStateMachineWrapper(
private val scope: AppCoroutineScope,
private val stateMachine: (Long) -> SeasonDetailsStateMachine,
) {
fun start(showId: Long, stateChangeListener: (SeasonDetailsState) -> Unit) {
scope.main.launch {
stateMachine(showId).state.collect {
stateChangeListener(it)
}
}
}
fun dispatch(showId: Long, action: SeasonDetailsAction) {
scope.main.launch {
stateMachine(showId).dispatch(action)
}
}
fun cancel() {
scope.main.cancel()
}
}
| 9 | Kotlin | 13 | 98 | 8bc3853d84c58520dffe26ddb260a2e7b6482ae9 | 1,180 | tv-maniac | Apache License 2.0 |
app/src/main/java/org/michaelbel/moviemade/data/dao/MoviesResponse.kt | 1jGabriel | 158,454,027 | true | {"Java": 395746, "Kotlin": 53645} | package org.michaelbel.moviemade.data.dao
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class MoviesResponse(
@SerializedName("page") val page: Int,
@SerializedName("results") val movies: List<Movie>,
@SerializedName("dates") val dates: Dates,
@SerializedName("total_pages") val totalPages: Int,
@SerializedName("total_results") val totalResults: Int
) : Serializable | 0 | Java | 0 | 0 | 34d73c64aef9121652e2e24adda7998a7599f260 | 426 | Moviemade | Apache License 2.0 |
common/src/main/java/com/kernel/finch/common/listeners/LogListener.kt | kernel0x | 197,173,098 | false | null | package com.kernel.finch.common.listeners
interface LogListener {
fun onAdded(tag: String?, message: CharSequence, payload: CharSequence?)
}
| 2 | null | 9 | 46 | 4f098309de71b690af5e2a7503444ad1959bf004 | 146 | finch | Apache License 2.0 |
sqldelight-studio-plugin/src/main/kotlin/com/squareup/sqldelight/psi/ColumnNameElementRef.kt | msdgwzhy6 | 52,407,141 | true | {"Kotlin": 118618, "Java": 63248, "ANTLR": 20800, "Shell": 939} | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.sqldelight.psi
import com.intellij.psi.PsiElement
import com.squareup.sqldelight.SqliteParser
import com.squareup.sqldelight.lang.SqliteFile
import com.squareup.sqldelight.lang.SqliteTokenTypes.RULE_ELEMENT_TYPES
import com.squareup.sqldelight.psi.SqliteElement.ColumnNameElement
import com.squareup.sqldelight.psi.SqliteElement.TableNameElement
import com.squareup.sqldelight.util.childOfType
import com.squareup.sqldelight.util.doRename
import com.squareup.sqldelight.util.elementType
import com.squareup.sqldelight.util.findUsages
import com.squareup.sqldelight.util.parentOfType
import com.squareup.sqldelight.util.prevSiblingOfType
internal class ColumnNameElementRef(idNode: IdentifierElement, ruleName: String)
: SqliteElementRef(idNode, ruleName) {
private var leftTableDef: TableNameElement? = null
override val identifierDefinitionRule = RULE_ELEMENT_TYPES[SqliteParser.RULE_column_def]
override fun getVariants(): Array<Any> {
setLeftTable()
return super.getVariants()
}
override fun resolve(): PsiElement? {
val columnName = element.parentOfType<ColumnNameElement>()
if (columnName != null && columnName.parent.elementType === identifierDefinitionRule) {
// If this is already a column definition return ourselves.
return columnName
}
setLeftTable()
return super.resolve()
}
override fun handleElementRename(newElementName: String): PsiElement {
val file = myElement.containingFile as SqliteFile
val usageInfo = myElement.findUsages(newElementName)
myElement.doRename(newElementName, usageInfo, file, null)
return myElement
}
override fun isAccepted(element: PsiElement) =
when (leftTableDef) {
null -> super.isAccepted(element) || element is TableNameElement
&& element.getParent().elementType === RULE_ELEMENT_TYPES[SqliteParser.RULE_create_table_stmt]
else -> super.isAccepted(element)
&& leftTableDef!!.isSameTable(element.parent.parent.childOfType<TableNameElement>())
}
private fun setLeftTable() {
leftTableDef = element.parentOfType<ColumnNameElement>()?.prevSiblingOfType<TableNameElement>()
}
}
| 0 | Kotlin | 0 | 1 | 92add547334b5810467d2729e87ac6648c26162d | 2,784 | sqldelight | Apache License 2.0 |
app/src/main/java/com/bftv/facetime/lab/RingActivity.kt | battleground | 126,471,925 | false | null | package com.bftv.facetime.lab
import android.app.Instrumentation
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import com.abooc.util.Debug
import kotlinx.android.synthetic.main.facetime_calling_menu_v.*
import kotlinx.android.synthetic.main.facetime_calling_user.*
class RingActivity : AppCompatActivity() {
private lateinit var aRing: Ring
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ring)
aRing = Ring(this)
fullScreenTextV1.text = "呼叫"
fullScreenV1?.setOnClickListener { v ->
v.isSelected = !v.isSelected
if (v.isSelected) {
fullScreenTextV1.text = "取消呼叫"
startAnim()
aRing.run()
} else {
fullScreenTextV1.text = "呼叫"
stopAnim()
aRing.stop()
}
}
muteVideoTextV1.text = "播放错误"
muteVideoV1?.setOnClickListener { v ->
v.isSelected = !v.isSelected
if (v.isSelected) {
muteVideoTextV1.text = "停止播放"
aRing.error()
} else {
muteVideoTextV1.text = "播放错误"
aRing.stop()
}
}
muteAudioTextV1.text = "发送'MENU'"
muteAudioV1?.setOnClickListener {
sendKeyEvent()
return@setOnClickListener
}
}
override fun onStart() {
super.onStart()
aRing.requestFocus()
}
override fun onStop() {
super.onStop()
aRing.releaseFocus()
}
private fun sendKeyEvent() {
Thread(Runnable {
val inst = Instrumentation()
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU)
}).start()
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_MENU) {
Debug.error()
}
return super.onKeyDown(keyCode, event)
}
val animHandler = Handler()
fun startAnim() {
Debug.anchor("++++++++++++")
animHandler.postDelayed(run1, 100L)
animHandler.postDelayed(run2, 900L)
animHandler.postDelayed(run3, 1800L)
}
fun stopAnim() {
Debug.anchor("------------")
animHandler.removeCallbacksAndMessages(null)
imageV1.clearAnimation()
imageV2.clearAnimation()
imageV3.clearAnimation()
}
var run1: () -> Unit = { imageV1.startAnimation(Anim.createAnimationSet()) }
var run2: () -> Unit = { imageV2.startAnimation(Anim.createAnimationSet()) }
var run3: () -> Unit = { imageV3.startAnimation(Anim.createAnimationSet()) }
override fun onDestroy() {
super.onDestroy()
}
}
| 1 | null | 1 | 1 | 1565af49fc623c6086f65300f1cf82a2bc9773c3 | 2,873 | facetime-lab | Apache License 2.0 |
incubator.clients.kroviz/src/test/kotlin/org/apache/isis/client/kroviz/snapshots/simpleapp1_16_0/RESTFUL_USER.kt | joerg-rade | 163,651,410 | false | null | package org.apache.isis.client.kroviz.snapshots.simpleapp1_16_0
import org.apache.isis.client.kroviz.snapshots.Response
object RESTFUL_USER : Response(){
override val url = "http://localhost:8080/restful/user"
override val str = """{
"userName": "sven",
"roles": ["iniRealm:admin_role"],
"links": [{
"rel": "self",
"href": "http://localhost:8080/restful/user",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/user\""
}, {
"rel": "up",
"href": "http://localhost:8080/restful/",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/homepage\""
}, {
"rel": "urn:org.apache.isis.restfulobjects:rels/logout",
"href": "http://localhost:8080/restful/user/logout",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/homepage\""
}],
"extensions": {}
}"""
}
| 20 | null | 1 | 10 | 07e7ed9aa6dabc7e8a9a0100451d89ae18e46950 | 1,068 | kroviz | Apache License 2.0 |
core/src/main/java/com/victorlh/android/framework/core/idioma/IIdioma.kt | victor-lh | 220,492,777 | false | null | package com.victorlh.android.framework.core.idioma
import java.util.*
/**
* @author Victor
* 01/09/2018
*/
interface IIdioma {
val codigoIdioma: String
val descripcionIdioma: String
val locale: Locale
} | 0 | Kotlin | 0 | 0 | 5d5dfeae76a4fe1b8f6c3cdd75fabc1994c30eaf | 210 | AndroidFramework | Apache License 2.0 |
core/src/test/kotlin/org/stellar/anchor/util/AssetHelperTest.kt | stellar | 452,893,461 | false | null | package org.stellar.anchor.util
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
class AssetHelperTest {
@ParameterizedTest
@CsvSource(value = ["USD,", "JPY,", "BRL,"])
fun `check valid iso4217 assets`(assetCode: String, assetIssuer: String?) {
assertTrue(AssetHelper.isISO4217(assetCode, assetIssuer))
}
@ParameterizedTest
@CsvSource(value = ["USD,non-empty", "BADISO,", ",", ",non-empty"])
fun `check invalid iso4217 assets`(assetCode: String?, assetIssuer: String?) {
assertFalse(AssetHelper.isISO4217(assetCode, assetIssuer))
}
@Test
fun `check valid native assets`() {
assertTrue(AssetHelper.isNativeAsset("native", ""))
}
@ParameterizedTest
@CsvSource(
value =
[
"USDC,GDJJES5JOST5VTBLDVVQRAW26LZ5IIJJFVN5IJOMICM73HLGGB3G74SS",
"BRLC,GDECIOEWJLWMVILZCJILY7FIWUY6VOXVRTAD5AJ57YKRHP2SWPEWYGDG",
]
)
fun `check valid issued assets`(assetCode: String?, assetIssuer: String?) {
assertTrue(AssetHelper.isNonNativeAsset(assetCode, assetIssuer))
}
@ParameterizedTest
@CsvSource(
value =
[
"USDC,MDJJES5JOST5VTBLDVVQRAW26LZ5IIJJFVN5IJOMICM73HLGGB3G6AAAAAAAAAAAPOBAM",
"USDC,",
"USDC,BAD_WALLET",
"BADASSET,BAD_WALLET",
"BADASSET,",
",BAD_WALLET",
"native,MDJJES5JOST5VTBLDVVQRAW26LZ5IIJJFVN5IJOMICM73HLGGB3G6AAAAAAAAAAAPOBAM",
"native,"
]
)
fun `test invalid stellar assets`(assetCode: String?, assetIssuer: String?) {
assertFalse(AssetHelper.isNonNativeAsset(assetCode, assetIssuer))
}
@ParameterizedTest
@CsvSource(
value =
[
"USDC,GDJJES5JOST5VTBLDVVQRAW26LZ5IIJJFVN5IJOMICM73HLGGB3G74SS,stellar:USDC:GDJJES5JOST5VTBLDVVQRAW26LZ5IIJJFVN5IJOMICM73HLGGB3G74SS",
"USDC,BAD_WALLET,",
"USD,,iso4217:USD",
"USD,BAD_WALLET,",
",GDJJES5JOST5VTBLDVVQRAW26LZ5IIJJFVN5IJOMICM73HLGGB3G74SS,",
"native,,stellar:native"
]
)
fun `test getAssetId`(assetCode: String?, assetIssuer: String?, assetId: String?) {
assertEquals(assetId, AssetHelper.getAssetId(assetCode, assetIssuer))
}
}
| 190 | null | 30 | 29 | d59cb09af116e79e46a3f3db97629f20b80b3222 | 2,253 | java-stellar-anchor-sdk | Apache License 2.0 |
ref_code/leetcode-main/kotlin/0992-subarrays-with-k-different-integers.kt | yennanliu | 66,194,791 | false | {"Java": 5396849, "Python": 4422387, "JavaScript": 490755, "Kotlin": 464977, "C++": 351516, "C": 246034, "C#": 177156, "Rust": 152545, "Jupyter Notebook": 152285, "TypeScript": 139873, "Go": 129930, "Swift": 102644, "Ruby": 41941, "Scala": 34913, "Dart": 9957, "Shell": 4032, "Dockerfile": 2000, "PLpgSQL": 1348} | class Solution {
fun subarraysWithKDistinct(nums: IntArray, k: Int): Int {
val count = HashMap<Int, Int>()
var res = 0
var l = 0
var m = 0
for (r in 0 until nums.size) {
count[nums[r]] = (count[nums[r]] ?: 0) + 1
while (count.size > k) {
count[nums[m]] = (count[nums[m]] ?: 0) - 1
if ((count[nums[m]] ?: 0) == 0) count.remove(nums[m])
m++
l = m
}
while ((count[nums[m]] ?: 0) > 1) {
count[nums[m]] = (count[nums[m]] ?: 0) - 1
m++
}
if (count.size == k) res += (m - l + 1)
}
return res
}
}
| 0 | Java | 42 | 98 | 209db7daa15718f54f32316831ae269326865f40 | 758 | CS_basics | The Unlicense |
src/test/kotlin/ru/job4j/oop/SimpleLinkedListTest.kt | staskorobeynikov | 315,352,877 | false | {"Gradle": 2, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Kotlin": 51, "Java": 1} | package ru.job4j.oop
import io.kotlintest.shouldBe
import io.kotlintest.specs.StringSpec
internal class SimpleLinkedListTest : StringSpec({
"Test add and iterator" {
val list = SimpleLinkedList<String>()
list.add("one")
list.add("two")
list.add("three")
val iterator = list.iterator()
iterator.hasNext() shouldBe true
iterator.next() shouldBe "three"
iterator.hasNext() shouldBe true
iterator.next() shouldBe "two"
iterator.hasNext() shouldBe true
iterator.next() shouldBe "one"
iterator.hasNext() shouldBe false
}
"Test listIterator" {
val list = SimpleLinkedList<String>()
list.add("one")
list.add("two")
list.add("three")
val listIterator = list.listIterator()
listIterator.hasNext() shouldBe true
listIterator.nextIndex() shouldBe 0
listIterator.next() shouldBe "three"
listIterator.hasNext() shouldBe true
listIterator.nextIndex() shouldBe 1
listIterator.next() shouldBe "two"
listIterator.hasNext() shouldBe true
listIterator.nextIndex() shouldBe 2
listIterator.next() shouldBe "one"
listIterator.hasNext() shouldBe false
listIterator.hasPrevious() shouldBe true
listIterator.previousIndex() shouldBe 2
listIterator.previous() shouldBe "one"
listIterator.hasPrevious() shouldBe true
listIterator.previousIndex() shouldBe 1
listIterator.previous() shouldBe "two"
listIterator.hasPrevious() shouldBe true
listIterator.previousIndex() shouldBe 0
listIterator.previous() shouldBe "three"
listIterator.hasPrevious() shouldBe false
}
})
| 0 | Kotlin | 1 | 0 | 57af21679b44763a36335e6368554998571cc10f | 1,759 | job4j_kotlin | Apache License 2.0 |
app/src/main/java/com/osome/stickydecorator/SectionItemAdapter.kt | OsomePteLtd | 222,447,484 | false | null | package com.osome.stickydecorator
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class SectionItemAdapter(private val items: List<Item>) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), ViewHolderStickyDecoration.Condition {
companion object {
const val TYPE_HEADER = R.layout.section
const val TYPE_ITEM = R.layout.list_item
}
override fun getItemCount(): Int = items.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
if (viewType == R.layout.list_item) {
val view = LayoutInflater.from(parent.context).inflate(viewType, parent, false)
return ItemHolder(view)
}
val view = LayoutInflater.from(parent.context).inflate(viewType, parent, false)
return SectionHolder(view)
}
override fun getItemViewType(position: Int): Int {
if (isHeader(position))
return TYPE_HEADER
return TYPE_ITEM
}
override fun isHeader(position: Int): Boolean {
return getItem(position) is SectionItem
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder.itemViewType == TYPE_ITEM) {
(holder as ItemHolder).bind(getItem(position))
} else if (holder.itemViewType == TYPE_HEADER) {
(holder as SectionHolder).bind(getItem(position) as SectionItem)
}
}
private fun getItem(position: Int): Item {
return items[position]
}
class ItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val tvItem = itemView.findViewById<TextView>(R.id.tvItem)
@SuppressLint("SetTextI18n")
fun bind(item: Item) {
tvItem.text = "Item with number ${item.value}"
}
}
class SectionHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val tv = itemView as TextView
fun bind(item: SectionItem) {
tv.text = "${item.value}th"
}
}
} | 1 | Java | 4 | 16 | c3151a10f86c67576d3d28095fd48841d5d22261 | 2,180 | StickyDecorator | MIT License |
idea/idea-frontend-fir/idea-fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/trasformers/FirDesignatedImplicitTypesTransformerForIDE.kt | neetopia | 182,176,999 | true | {"Markdown": 66, "Gradle": 728, "Gradle Kotlin DSL": 559, "Java Properties": 15, "Shell": 10, "Ignore List": 12, "Batchfile": 9, "Git Attributes": 8, "Kotlin": 61093, "Protocol Buffer": 12, "Java": 6639, "Proguard": 12, "XML": 1602, "Text": 12271, "INI": 179, "JavaScript": 275, "JAR Manifest": 2, "Roff": 213, "Roff Manpage": 38, "AsciiDoc": 1, "HTML": 494, "SVG": 50, "Groovy": 33, "JSON": 179, "JFlex": 3, "Maven POM": 107, "CSS": 5, "JSON with Comments": 9, "Ant Build System": 50, "Graphviz (DOT)": 77, "C": 1, "Ruby": 5, "Objective-C": 8, "OpenStep Property List": 5, "Swift": 5, "Scala": 1, "YAML": 16} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.fir.low.level.api.trasformers
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirDeclaration
import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
import org.jetbrains.kotlin.fir.resolve.ResolutionMode
import org.jetbrains.kotlin.fir.resolve.ScopeSession
import org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.FirImplicitAwareBodyResolveTransformer
import org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.ImplicitBodyResolveComputationSession
import org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.createReturnTypeCalculatorForIDE
import org.jetbrains.kotlin.fir.visitors.CompositeTransformResult
import org.jetbrains.kotlin.fir.visitors.compose
import org.jetbrains.kotlin.idea.fir.low.level.api.element.builder.FirIdeDesignatedBodyResolveTransformerForReturnTypeCalculator
internal class FirDesignatedImplicitTypesTransformerForIDE(
private val designation: Iterator<FirElement>,
session: FirSession,
scopeSession: ScopeSession,
implicitBodyResolveComputationSession: ImplicitBodyResolveComputationSession = ImplicitBodyResolveComputationSession(),
) : FirImplicitAwareBodyResolveTransformer(
session,
implicitBodyResolveComputationSession = implicitBodyResolveComputationSession,
phase = FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE,
implicitTypeOnly = true,
scopeSession = scopeSession,
returnTypeCalculator = createReturnTypeCalculatorForIDE(
session,
scopeSession,
implicitBodyResolveComputationSession,
::FirIdeDesignatedBodyResolveTransformerForReturnTypeCalculator
)
) {
override fun transformDeclarationContent(declaration: FirDeclaration, data: ResolutionMode): CompositeTransformResult<FirDeclaration> {
if (designation.hasNext()) {
designation.next().visitNoTransform(this, data)
return declaration.compose()
}
return super.transformDeclarationContent(declaration, data)
}
}
| 0 | Kotlin | 0 | 1 | 66bc142f92085047a1ca64f9a291f0496e33dd98 | 2,288 | kotlin | Apache License 2.0 |
src/test/kotlin/org/graphomance/usecases/pole/PersonKnowSubgraphAlgorithms.kt | grzegorz-aniol | 161,749,625 | false | null | package org.graphomance.usecases.pole
import org.assertj.core.api.Assertions.assertThat
import org.graphomance.api.DbType
import org.graphomance.api.Session
import org.graphomance.engine.QueryTimer
import org.junit.jupiter.api.Test
class PersonKnowSubgraphAlgorithms : PoleTestBase() {
@Test
fun `betweenness centrality`(session: Session, testTimer: QueryTimer) {
val query = when (session.getDbType()) {
// undirected graph projection, without normalization, 4 threads
DbType.NEO4J ->
// In Neo4j projection can be created once and reused multiple times.
// But it's not supported in Memgraph. So to be fair, the Neo4j query creates projection every time
"""
CALL {
CALL gds.graph.drop('social', false) YIELD graphName as _
}
CALL {
CALL gds.graph.project('social', 'Person', {KNOWS: {orientation:'UNDIRECTED'}}) YIELD graphName as _
}
CALL gds.betweenness.stream('social', {concurrency: 4})
YIELD nodeId, score AS centrality
WITH gds.util.asNode(nodeId) AS node, centrality
RETURN node.name AS name, node.surname AS surname, node.nhs_no AS id, toInteger(centrality) AS score
ORDER BY centrality DESC
LIMIT 10;
""".trimIndent()
DbType.MEMGRAPH ->
"""
MATCH p=(:Person)-[:KNOWS]-()
WITH project(p) as persons_graph
CALL betweenness_centrality.get(persons_graph, false, false, 4) YIELD node, betweenness_centrality as centrality
RETURN node.name AS name, node.surname AS surname, node.nhs_no AS id, toInteger(centrality) AS score
ORDER BY centrality DESC
LIMIT 10;
""".trimIndent()
else -> throw RuntimeException("Unsupported database type")
}
repeat(200) {
val result = testTimer.timeMeasureWithResult { session.runQuery(query).rows.toList() }
assertThat(result).hasSize(10)
assertThat(result[0].values.asString("id")).isEqualTo("863-96-9468")
}
}
/*
Expected result
╒════════╤═══════════╤═════════════╤═════╕
│name │surname │id │score│
╞════════╪═══════════╪═════════════╪═════╡
│"Annie" │"Duncan" │"863-96-9468"│5275 │
├────────┼───────────┼─────────────┼─────┤
│"Ann" │"Fox" │"576-99-9244"│5116 │
├────────┼───────────┼─────────────┼─────┤
│"Amanda"│"Alexander"│"893-63-6176"│4599 │
├────────┼───────────┼─────────────┼─────┤
│"Bruce" │"Baker" │"576-82-7408"│4193 │
├────────┼───────────┼─────────────┼─────┤
│"Andrew"│"Foster" │"214-77-6416"│3693 │
├────────┼───────────┼─────────────┼─────┤
│"Anne" │"Rice" │"612-83-6356"│3418 │
├────────┼───────────┼─────────────┼─────┤
│"Alan" │"Hicks" │"852-52-0933"│3347 │
├────────┼───────────┼─────────────┼─────┤
│"Amy" │"Murphy" │"367-54-3328"│3282 │
├────────┼───────────┼─────────────┼─────┤
│"Adam" │"Bradley" │"237-02-1263"│3275 │
├────────┼───────────┼─────────────┼─────┤
│"Arthur"│"Willis" │"271-78-8919"│3259 │
└────────┴───────────┴─────────────┴─────┘
*/
} | 1 | null | 1 | 4 | 4107d3a7ff5599659ded084f62a954f0c8d557d3 | 3,370 | graphomance | MIT License |
ktor-backend/clipboard/src/main/kotlin/com/steiner/workbench/clipboard/ValidateClipboard.kt | nesteiner | 693,014,583 | false | {"Kotlin": 366481, "Dart": 247737, "C++": 24228, "CMake": 19460, "HTML": 1843, "C": 1425} | package com.steiner.workbench.clipboard
import com.steiner.workbench.clipboard.request.PostTextRequest
import io.ktor.server.plugins.requestvalidation.*
fun RequestValidationConfig.validateClipboard() {
validate<PostTextRequest> {
it.validate()
}
} | 1 | Kotlin | 0 | 0 | e0fe7a0f9aca965bc74736f1364153a695597bfe | 266 | Workbench | MIT License |
App News - Android + Kotlin + Retrofit + Coroutines + Room/app_news_mvvm/app/src/main/java/com/lvb/projects/app_news_mvvm/util/state/ArticleListEvent.kt | Velosofurioso | 454,964,649 | false | {"Kotlin": 368162, "Dart": 70010, "C++": 16868, "CMake": 9414, "Swift": 3232, "HTML": 1847, "C": 734, "Objective-C": 304} | package com.lvb.projects.app_news_mvvm.util.state
sealed class ArticleListEvent {
object Fetch : ArticleListEvent()
} | 0 | Kotlin | 0 | 0 | 8256f68ae16541677e65306118968904fe467c71 | 122 | Mobile-Development-Courses | MIT License |
enode/src/main/java/org/enodeframework/messaging/impl/QueueMessageDispatching.kt | anruence | 165,245,292 | false | null | package org.enodeframework.messaging.impl
import org.enodeframework.messaging.Message
import java.util.concurrent.ConcurrentLinkedQueue
class QueueMessageDispatching(
private val dispatcher: DefaultMessageDispatcher,
rootDispatching: RootDispatching,
messages: List<Message>
) {
private val rootDispatching: RootDispatching
private val messageQueue: ConcurrentLinkedQueue<Message> = ConcurrentLinkedQueue()
init {
messageQueue.addAll(messages)
this.rootDispatching = rootDispatching
this.rootDispatching.addChildDispatching(this)
}
fun dequeueMessage(): Message? {
return messageQueue.poll()
}
fun onMessageHandled() {
val nextMessage = dequeueMessage()
if (nextMessage == null) {
rootDispatching.onChildDispatchingFinished(this)
return
}
dispatcher.dispatchSingleMessage(nextMessage, this)
}
}
| 1 | null | 55 | 205 | 22c81b98b36a6a221d026272594eaf7817145e0f | 932 | enode | MIT License |
app/src/main/java/dev/patrickgold/florisboard/ime/media/emoji/EmojiKey.kt | florisboard | 254,202,848 | false | null | /*
* Copyright (C) 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 dev.patrickgold.florisboard.ime.media.emoji
import dev.patrickgold.florisboard.ime.keyboard.Key
import dev.patrickgold.florisboard.ime.keyboard.KeyData
import dev.patrickgold.florisboard.ime.popup.PopupSet
class EmojiKey(override val data: KeyData) : Key(data) {
var computedData: EmojiKeyData = EmojiKeyData(listOf())
private set
var computedPopups: PopupSet<EmojiKeyData> = PopupSet()
private set
companion object {
val EMPTY = EmojiKey(EmojiKeyData.EMPTY)
}
fun dummyCompute() {
computedData = data as? EmojiKeyData ?: computedData
computedPopups = PopupSet(relevant = (data as? EmojiKeyData)?.popup ?: listOf())
}
}
| 392 | null | 178 | 2,387 | 8674a04a5cdc7200590e8877afeee3fbf81d99c6 | 1,287 | florisboard | Apache License 2.0 |
src/main/kotlin/frc/sciborgs/scilib/config/MotorConfig.kt | SciBorgs | 568,205,792 | false | {"Kotlin": 21009, "Java": 1703} | package frc.sciborgs.scilib.config
import com.ctre.phoenix.motorcontrol.NeutralMode
import com.ctre.phoenix.motorcontrol.can.WPI_TalonFX
import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX
import com.revrobotics.CANSparkMax
import com.revrobotics.CANSparkMaxLowLevel.MotorType
/**
* MotorConfig is a builder class for standardizing vendor motor controllers.
*
* ### Example usage for a CANSparkMax differential drive
*
* ```kotlin
* val leftMotor = MotorConfig(neutralBehavior = NeutralBehavior.BRAKE, currentLimit = 80)
* val rightMotor = leftMotor.copy(inverted = true)
*
* val leftPorts = intArrayOf(1, 2, 3)
* val rightPorts = intArrayOf(4, 5, 6)
*
* val leftGroup = MotorControllerGroup(leftMotor.buildCanSparkMax(*leftPorts, motorType = MotorType.kBrushless))
* val rightGroup = MotorControllerGroup(rightMotor.buildCanSparkMax(*rightPorts, motorType = MotorType.kBrushless))
* val driveTrain = DifferentialDrive(leftGroup, rightGroup)
* ```
*
* @author <NAME>
*/
data class MotorConfig(
var inverted: Boolean = false,
var neutralBehavior: NeutralBehavior = NeutralBehavior.COAST,
var openLoopRampRate: Double = 0.0,
var currentLimit: Int = 80,
var pidConstants: PIDConstants? = null,
) {
/**
* Creates a CANSparkMax based on configured values
*
* @param id the motor controller's device id
* @param motorType the [MotorType] of the physical motor ***This could break your motor if it is
* not set correctly***
* @return a new CANSparkMax object
*/
fun buildCanSparkMax(id: Int, motorType: MotorType): CANSparkMax {
val motor = CANSparkMax(id, motorType)
motor.restoreFactoryDefaults()
motor.inverted = inverted
motor.idleMode = neutralBehavior.rev()
motor.openLoopRampRate = openLoopRampRate
motor.setSmartCurrentLimit(currentLimit)
pidConstants?.also {
val pid = motor.pidController
pid.p = it.kp
pid.i = it.ki
pid.d = it.kd
}
motor.burnFlash()
return motor
}
/**
* Creates an array of CANSparkMax objects based on configured values.
*
* One motor controller will be created per id, in order
*
* @param ids any number of motor ids
* @param motorType the [MotorType] of the physical motors ***This could break your motors if it
* is not set correctly***
* @return array of CANSparkMax objects
*/
fun buildCanSparkMax(vararg ids: Int, motorType: MotorType) =
Array(ids.size) { buildCanSparkMax(it, motorType) }
/**
* Creates a TalonSRX based on configured values
*
* @param id the motor controller's device id
* @param pidSlot the pidSlot of the controller
* @return a new WPI_TalonSRX object
*/
fun buildTalonSRX(id: Int, pidSlot: Int = 0): WPI_TalonSRX {
val motor = WPI_TalonSRX(id)
motor.configFactoryDefault()
motor.inverted = this.inverted
motor.setNeutralMode(neutralBehavior.ctre())
motor.configOpenloopRamp(openLoopRampRate)
motor.configPeakCurrentLimit(currentLimit)
motor.enableCurrentLimit(true)
pidConstants?.also {
motor.config_kP(pidSlot, it.kp)
motor.config_kI(pidSlot, it.ki)
motor.config_kD(pidSlot, it.kd)
}
return motor
}
/**
* Creates an array of TalonSRX objects based on configured values
*
* One motor controller will be created per id, in order
*
* @param ids any number of motor ids
* @param pidSlot the pidSlot of the controller
* @return array of WPI_TalonSRX objects
*/
fun buildTalonSRX(vararg ids: Int, pidSlot: Int = 0) =
Array(ids.size) { buildTalonSRX(it, pidSlot) }
/**
* Creates a TalonFX based on configured values
*
* @param id the motor controller's device id
* @param pidSlot the pidSlot of the controller
* @return a new WPI_TalonFX object
*/
fun buildTalonFX(id: Int, pidSlot: Int = 0): WPI_TalonFX {
val motor = WPI_TalonFX(id)
motor.configFactoryDefault()
motor.inverted = inverted
motor.setNeutralMode(neutralBehavior.ctre())
motor.configOpenloopRamp(openLoopRampRate)
pidConstants?.also {
motor.config_kP(pidSlot, it.kp)
motor.config_kI(pidSlot, it.ki)
motor.config_kD(pidSlot, it.kd)
}
return motor
}
/**
* Creates an array of TalonFX objects based on configured values
*
* One motor controller will be created per id, in order
*
* @param ids any number of motor ids
* @param pidSlot the pidSlot of the controller
* @return array of WPI_TalonFX objects
*/
fun buildTalonFX(vararg ids: Int, pidSlot: Int = 0) =
Array(ids.size) { buildTalonFX(it, pidSlot) }
}
/** Enum to represent a generic neutral behvavior */
enum class NeutralBehavior(private val coast: Boolean) {
COAST(true),
BRAKE(false);
/** Gets the rev compatible neutral mode */
fun rev() = if (coast) CANSparkMax.IdleMode.kCoast else CANSparkMax.IdleMode.kBrake
/** Gets the ctre compatible neutral mode */
fun ctre() = if (coast) NeutralMode.Coast else NeutralMode.Brake
}
| 0 | Kotlin | 0 | 2 | 44ae8b361aa6ebb213c1dfaeffa5605704e73e06 | 5,004 | SciLib | MIT License |
app/src/main/java/me/ssttkkl/mrmemorizer/ui/viewnote/GraphAdapter.kt | ssttkkl | 437,893,611 | false | {"Kotlin": 77581} | package me.ssttkkl.mrmemorizer.ui.viewnote
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import dev.bandb.graphview.AbstractGraphAdapter
import dev.bandb.graphview.graph.Graph
import me.ssttkkl.mrmemorizer.R
import me.ssttkkl.mrmemorizer.ui.viewnote.GraphAdapter.ViewHolder
class GraphAdapter(val lifecycleOwner: LifecycleOwner) : AbstractGraphAdapter<ViewHolder>() {
private val observer = Observer<Graph?> {
submitGraph(it)
notifyDataSetChanged()
}
var data: LiveData<Graph?>? = null
set(value) {
field?.removeObserver(observer)
field = value
field?.observe(lifecycleOwner, observer)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.textView.text = getNodeData(position).toString()
}
override fun onCreateViewHolder(parent: ViewGroup, i: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_graph_node, parent, false)
return ViewHolder(view)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView: TextView = itemView.findViewById(R.id.text)
}
} | 0 | Kotlin | 0 | 2 | 3b2ef323465c71c5bfd214a6a71bf2c85c635882 | 1,431 | Mr.MEMORIZER | MIT License |
app/src/main/java/com/turtleteam/turtleapp/di/featureModule/GroupModule.kt | Egor-Liadsky | 711,194,733 | false | {"Kotlin": 212857} | package com.turtleteam.turtleapp.di.featureModule
import com.turtleteam.api.data.repository.GroupRepository
import com.turtleteam.api.navigation.GroupNavigation
import com.turtleteam.impl.data.repository.GroupRepositoryImpl
import com.turtleteam.impl.navigation.GroupNavigationImpl
import com.turtleteam.impl.navigation.GroupNavigator
import com.turtleteam.impl.presentation.group.viewModel.GroupViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val groupModule = module {
single<GroupNavigation> { GroupNavigationImpl() }
single<GroupRepository> { GroupRepositoryImpl(get()) }
single { navController -> GroupNavigator(navController.get()) }
viewModel { params ->
GroupViewModel(params.get())
}
}
| 0 | Kotlin | 0 | 0 | 318a323f34b9d622a43870fe20da30068db5d8d4 | 763 | TurtleAppAndroid | Apache License 2.0 |
app/src/main/java/io/github/alessandrojean/toshokan/presentation/ui/settings/backup/BackupSettingsScreen.kt | alessandrojean | 495,493,156 | false | null | package io.github.alessandrojean.toshokan.presentation.ui.settings.backup
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import cafe.adriel.voyager.androidx.AndroidScreen
import cafe.adriel.voyager.hilt.getViewModel
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import io.github.alessandrojean.toshokan.R
import io.github.alessandrojean.toshokan.data.backup.SheetBackupRestorer
import io.github.alessandrojean.toshokan.presentation.ui.settings.components.GenericPreference
import io.github.alessandrojean.toshokan.presentation.ui.settings.components.SettingsListScaffold
import io.github.alessandrojean.toshokan.util.extension.toast
class BackupSettingsScreen : AndroidScreen() {
@Composable
override fun Content() {
val viewModel = getViewModel<BackupSettingsViewModel>()
val navigator = LocalNavigator.currentOrThrow
val context = LocalContext.current
val sheetBackupPickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetContent(),
onResult = { uri ->
uri?.let {
viewModel.restoreFromSheet(it)
}
}
)
SettingsListScaffold(
title = stringResource(R.string.settings_backup),
onNavigationClick = { navigator.pop() }
) {
item("restore_from_sheet") {
GenericPreference(
title = stringResource(R.string.pref_restore_from_sheet),
summary = stringResource(R.string.pref_restore_from_sheet_summary),
onClick = {
if (!viewModel.restoreRunning) {
sheetBackupPickerLauncher.launch(SheetBackupRestorer.BACKUP_MIME)
} else {
context.toast(R.string.restore_in_progress)
}
}
)
}
}
}
} | 11 | Kotlin | 1 | 5 | 96717312b7a5090901c8604cd069d9468995e99e | 2,018 | toshokan-android | MIT License |
app/src/main/java/com/puutaro/commandclick/proccess/edit/lib/ScriptContentsLister.kt | puutaro | 596,852,758 | false | null | package com.puutaro.commandclick.proccess.edit.lib
import android.widget.EditText
import android.widget.LinearLayout
import com.puutaro.commandclick.common.variable.edit.RecordNumToMapNameValueInHolderColumn
import com.puutaro.commandclick.util.CompleteQuote
class ScriptContentsLister(
private val editLinearLayout: LinearLayout,
) {
fun update(
recordNumToMapNameValueInHolder: Map<Int, Map<String, String>?>,
scriptContentsList: List<String>,
startIdNum: Int
): List<String> {
val factRecordNumToNameToValueInHolderSize = recordNumToMapNameValueInHolder.size - 1
if(factRecordNumToNameToValueInHolderSize <= -1) return scriptContentsList
val editedRecordNumToNameToValue = (0..factRecordNumToNameToValueInHolderSize).map {
val currentId = startIdNum + it
val editTextView = editLinearLayout.findViewById<EditText>(currentId)
val currentRecordNumToMapNameValue = recordNumToMapNameValueInHolder.entries.elementAt(it)
val currentVriableValue = editTextView.text.toString()
currentRecordNumToMapNameValue.key to
mapOf(
RecordNumToMapNameValueInHolderColumn.VARIABLE_NAME.name
to editTextView.tag.toString(),
RecordNumToMapNameValueInHolderColumn.VARIABLE_VALUE.name
to CompleteQuote.comp(currentVriableValue)
)
}.toMap()
val processScriptSize = scriptContentsList.size - 1
if(processScriptSize <= -1) return scriptContentsList
return (0..processScriptSize).map {
currentOrder ->
val getReplaceValue = editedRecordNumToNameToValue.get(currentOrder)
if(getReplaceValue.isNullOrEmpty()){
scriptContentsList[currentOrder]
} else {
val currentVariableName = getReplaceValue.get(
RecordNumToMapNameValueInHolderColumn.VARIABLE_NAME.name
)
val currentVariableValue = getReplaceValue.get(
RecordNumToMapNameValueInHolderColumn.VARIABLE_VALUE.name
)?.let {
CompleteQuote.comp(it)
}
"${currentVariableName}=${currentVariableValue}"
}
}
}
}
| 2 | null | 3 | 54 | 000db311f5780b2861a2143f7985507b06cae5f1 | 2,384 | CommandClick | MIT License |
kotest-assertions/kotest-assertions-core/src/jvmMain/kotlin/io/kotest/matchers/atomic/AtomicBooleanMatchers.kt | kotest | 47,071,082 | false | null | package io.kotest.matchers.atomic
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe
import java.util.concurrent.atomic.AtomicBoolean
/**
* Asserts that this [AtomicBoolean] is true
*
* Verifies that this [AtomicBoolean] or AtomicBoolean expression is true.
* Opposite of [AtomicBoolean.shouldNotBeTrue]
*
* ```
* AtomicBoolean(true).shouldBeTrue // Assertion passes
* AtomicBoolean(false).shouldBeTrue // Assertion fails
*
* AtomicBoolean(3 + 3 == 6).shouldBeTrue // Assertion passes
* AtomicBoolean(3 + 3 == 42).shouldBeTrue // Assertion fails
* ```
* @see [AtomicBoolean.shouldNotBeFalse]
* @see [AtomicBoolean.shouldBeFalse]
*/
fun AtomicBoolean.shouldBeTrue() = get() shouldBe true
/**
* Asserts that this [AtomicBoolean] is not true
*
* Verifies that this [AtomicBoolean] or AtomicBoolean expression is not true.
* Opposite of [AtomicBoolean.shouldBeTrue]
*
* ```
* AtomicBoolean(false).shouldNotBeTrue // Assertion passes
* AtomicBoolean(true).shouldNotBeTrue // Assertion fails
*
* AtomicBoolean(3 + 3 == 42).shouldNotBeTrue // Assertion passes
* AtomicBoolean(3 + 3 == 6).shouldNotBeTrue // Assertion fails
* ```
* @see [AtomicBoolean.shouldBeFalse]
* @see [AtomicBoolean.shouldNotBeFalse]
*/
fun AtomicBoolean.shouldNotBeTrue() = get() shouldNotBe true
/**
* Asserts that this [AtomicBoolean] is false
*
* Verifies that this [AtomicBoolean] or AtomicBoolean expression is false.
* Opposite of [AtomicBoolean.shouldNotBeFalse]
*
* ```
* AtomicBoolean(false).shouldBeFalse // Assertion passes
* AtomicBoolean(true).shouldBeFalse // Assertion fails
*
* AtomicBoolean(3 + 3 == 42).shouldBeFalse // Assertion passes
* AtomicBoolean(3 + 3 == 6).shouldBeFalse // Assertion fails
* ```
* @see [AtomicBoolean.shouldNotBeTrue]
* @see [AtomicBoolean.shouldBeTrue]
*/
fun AtomicBoolean.shouldBeFalse() = get() shouldBe false
/**
* Asserts that this [AtomicBoolean] is not false
*
* Verifies that this [AtomicBoolean] or AtomicBoolean expression is not false.
* Opposite of [AtomicBoolean.shouldBeFalse]
*
* ```
* AtomicBoolean(true).shouldNotBeFalse // Assertion passes
* AtomicBoolean(false).shouldNotBeFalse // Assertion fails
*
* AtomicBoolean(3 + 3 == 6).shouldNotBeFalse // Assertion passes
* AtomicBoolean(3 + 3 == 42).shouldNotBeFalse // Assertion fails
* ```
* @see [AtomicBoolean.shouldBeTrue]
* @see [AtomicBoolean.shouldNotBeTrue]
*/
fun AtomicBoolean.shouldNotBeFalse() = get() shouldNotBe false
| 141 | null | 648 | 4,435 | 2ce83d0f79e189c90e2d7bb3d16bd4f75dec9c2f | 2,525 | kotest | Apache License 2.0 |
src/main/kotlin/com/xbaimiao/chatchannel/ChatChannel.kt | Craftray | 446,662,996 | true | {"Kotlin": 8724, "Java": 356} | package com.xbaimiao.chatchannel
import com.xbaimiao.chatchannel.Switch.isSwitch
import com.xbaimiao.chatchannel.Switch.setSwitch
import me.albert.amazingbot.bot.Bot
import me.clip.placeholderapi.PlaceholderAPI
import org.bukkit.entity.Player
import taboolib.common.env.RuntimeDependency
import taboolib.common.platform.Plugin
import taboolib.common.platform.command.PermissionDefault
import taboolib.common.platform.command.command
import taboolib.module.chat.uncolored
import taboolib.module.configuration.Config
import taboolib.module.configuration.SecuredFile
import taboolib.module.nms.sendMap
import taboolib.platform.BukkitPlugin
import taboolib.platform.util.sendLang
@RuntimeDependency(
value = "!org.jetbrains.kotlin:kotlin-stdlib:1.5.31"
)
object ChatChannel : Plugin() {
@Config(value = "config.yml")
lateinit var config: SecuredFile
private set
val plugin by lazy { BukkitPlugin.getInstance() }
override fun onEnable() {
command(
name = "qq",
permissionDefault = PermissionDefault.TRUE
) {
literal("look", optional = true) {
dynamic {
execute<Player> { sender, context, argument ->
sender.sendMap(argument)
}
}
}
literal("send", optional = true) {
dynamic {
execute<Player> { sender, context, argument ->
var message = PlaceholderAPI.setPlaceholders(
sender,
config.getString("GameToGroup")
)
message = message.replace("%msg%", argument.uncolored())
sender.chat(argument)
Bot.getApi().bot.groups.forEach {
Bot.getApi().sendGroupMsg(it.id.toString(), message)
}
}
}
}
literal("onOff", optional = true) {
execute<Player> { sender, context, argument ->
if (sender.isSwitch()) {
sender.setSwitch(false)
sender.sendLang("off")
} else {
sender.setSwitch(true)
sender.sendLang("on")
}
}
}
}
}
} | 0 | null | 0 | 0 | 4167170c6dc553b827abc52cc3cf0075c0556b12 | 2,442 | ChatChannel | Creative Commons Zero v1.0 Universal |
src/main/kotlin/org/typedb/typeql/plugin/jetbrains/psi/PsiTypeQLStatementType.kt | typedb-osi | 365,569,922 | false | {"Kotlin": 135027, "HTML": 1030} | /*
* Copyright (C) 2022 Vaticle
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.typedb.typeql.plugin.jetbrains.psi
import com.intellij.lang.ASTNode
/**
* @author [<NAME>](mailto:<EMAIL>)
*/
class PsiTypeQLStatementType(node: ASTNode) : PsiTypeQLElement(node) {
override fun getName(): String? = firstChild.text
val subType: String?
get() = node.firstChildNode?.treeNext?.treeNext?.lastChildNode?.text
// TODO: Uncomment and revalidate while returning the inspection package.
// fun findRelatesTypeProperties(): List<PsiRelatesTypeConstraint> {
// val relatesTypes: MutableList<PsiRelatesTypeConstraint> = ArrayList()
// for (child in children) {
// val element = TypeQLParserDefinition.getRuleTypePropertyElement(child.node)
// if (element is PsiRelatesTypeConstraint) {
// relatesTypes.add(element)
// }
// }
// return relatesTypes
// }
//
// fun findPlaysTypeProperties(): List<PsiPlaysTypeConstraint> {
// val playsTypes: MutableList<PsiPlaysTypeConstraint> = ArrayList()
// for (child in children) {
// val element = TypeQLParserDefinition.getRuleTypePropertyElement(child.node)
// if (element is PsiPlaysTypeConstraint) {
// playsTypes.add(element)
// }
// }
// return playsTypes
// }
//
// fun findOwnsTypeProperties(): List<PsiOwnsTypeConstraint> {
// val ownsTypes: MutableList<PsiOwnsTypeConstraint> = ArrayList()
// for (child in children) {
// val element = TypeQLParserDefinition.getRuleTypePropertyElement(child.node)
// if (element is PsiOwnsTypeConstraint) {
// ownsTypes.add(element)
// }
// }
// return ownsTypes
// }
//
// fun findSubTypeProperties(): List<PsiSubTypeConstraint> {
// val subTypes: MutableList<PsiSubTypeConstraint> = ArrayList()
// for (child in children) {
// val element = TypeQLParserDefinition.getRuleTypePropertyElement(child.node)
// if (element is PsiSubTypeConstraint) {
// subTypes.add(element)
// }
// }
// return subTypes
// }
//
// fun findTypeProperties(): List<PsiTypeConstraint> {
// val relatesTypes: MutableList<PsiTypeConstraint> = ArrayList()
// for (child in children) {
// val element = TypeQLParserDefinition.getRuleTypeElement(child.node)
// if (element is PsiTypeConstraint) {
// relatesTypes.add(element)
// }
// }
// return relatesTypes
// }
}
| 4 | Kotlin | 6 | 9 | 92d63a44f80d05f3defc9918ae58fdd218b343ad | 3,416 | typeql-plugin-jetbrains | MIT License |
core/core-data/src/main/java/com/prmto/core_data/repository/firebase/FirebaseCoreMovieRepositoryImpl.kt | tolgaprm | 541,709,201 | false | {"Kotlin": 540597} | package com.prmto.core_data.repository.firebase
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.SetOptions
import com.prmto.core_data.remote.mapper.movie.toFavoriteMovie
import com.prmto.core_data.remote.mapper.movie.toMovieWatchListItem
import com.prmto.core_data.util.Constants
import com.prmto.core_data.util.Constants.FIREBASE_MOVIES_FIELD_NAME
import com.prmto.core_data.util.returnResourceByTaskResult
import com.prmto.core_data.util.safeCallWithForFirebase
import com.prmto.core_domain.models.movie.Movie
import com.prmto.core_domain.repository.firebase.FirebaseCoreMovieRepository
import com.prmto.core_domain.util.SimpleResource
import com.prmto.database.entity.movie.FavoriteMovie
import com.prmto.database.entity.movie.MovieWatchListItem
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
class FirebaseCoreMovieRepositoryImpl @Inject constructor(
private val firestore: FirebaseFirestore
) : FirebaseCoreMovieRepository {
override suspend fun addMovieToFavoriteList(
userUid: String,
movieInFavoriteList: List<Movie>
): SimpleResource {
return safeCallWithForFirebase {
val data = mapOf(
FIREBASE_MOVIES_FIELD_NAME to movieInFavoriteList
)
val task =
firestore.collection(userUid)
.document(Constants.FIREBASE_FAVORITE_MOVIE_DOCUMENT_NAME)
.set(data.toConvertToFavoriteMovieMap(), SetOptions.merge())
task.await()
return task.returnResourceByTaskResult(Unit)
}
}
override suspend fun addMovieToWatchList(
userUid: String,
moviesInWatchList: List<Movie>
): SimpleResource {
return safeCallWithForFirebase {
val data = mapOf(
FIREBASE_MOVIES_FIELD_NAME to moviesInWatchList
)
val result =
firestore.collection(userUid).document(Constants.FIREBASE_MOVIE_WATCH_DOCUMENT_NAME)
.set(data.toConvertToMovieWatchMap(), SetOptions.merge())
result.await()
result.returnResourceByTaskResult(Unit)
}
}
private fun Map<String, List<Movie>>.toConvertToFavoriteMovieMap(): Map<String, List<FavoriteMovie>> {
return this.mapValues {
it.value.map { it.toFavoriteMovie() }
}
}
private fun Map<String, List<Movie>>.toConvertToMovieWatchMap(): Map<String, List<MovieWatchListItem>> {
return this.mapValues {
it.value.map { it.toMovieWatchListItem() }
}
}
} | 0 | Kotlin | 4 | 85 | d9365e5339cb5daa231a8fe77c7376ab828d289b | 2,618 | Mova-MovieApp | Apache License 2.0 |
increase-kotlin-core/src/test/kotlin/com/increase/api/services/blocking/simulations/CardReversalServiceTest.kt | Increase | 614,596,742 | false | {"Kotlin": 10575238, "Shell": 3638, "Dockerfile": 399} | // File generated from our OpenAPI spec by Stainless.
package com.increase.api.services.blocking.simulations
import com.increase.api.TestServerExtension
import com.increase.api.client.okhttp.IncreaseOkHttpClient
import com.increase.api.models.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(TestServerExtension::class)
class CardReversalServiceTest {
@Test
fun callCreate() {
val client =
IncreaseOkHttpClient.builder()
.baseUrl(TestServerExtension.BASE_URL)
.apiKey("My API Key")
.build()
val cardReversalService = client.simulations().cardReversals()
val cardPayment =
cardReversalService.create(
SimulationCardReversalCreateParams.builder()
.cardPaymentId("card_payment_id")
.amount(123L)
.build()
)
println(cardPayment)
cardPayment.validate()
}
}
| 0 | Kotlin | 0 | 5 | dc1361d08cb41ff45817c2e7638f53356f15cf8e | 1,017 | increase-kotlin | Apache License 2.0 |
app/src/main/java/es/fnmtrcm/ceres/certificadoDigitalFNMT/piracy_checker/PiracyChecker.kt | CodeNationDev | 757,931,525 | false | {"Kotlin": 1417005, "C": 485745, "C++": 480977, "CMake": 283671, "Java": 166491} | package es.fnmtrcm.ceres.certificadoDigitalFNMT.piracy_checker
import android.content.Context
import es.fnmtrcm.ceres.certificadoDigitalFNMT.piracy_checker.models.InstallerID
import es.fnmtrcm.ceres.certificadoDigitalFNMT.piracy_checker.models.PiracyCheckerError
class PiracyChecker(private var context: Context?) {
private var allowCallback: AllowCallback? = null
private var doNotAllowCallback: DoNotAllowCallback? = null
private var onErrorCallback: OnErrorCallback? = null
private var enableSigningCertificate: Boolean = false
private var signatures: Array<String> = arrayOf()
private val installerIDs: MutableList<InstallerID> = mutableListOf()
private var enableEmulatorCheck: Boolean = false
private var enableRootCheck: Boolean = false
fun enableSigningCertificates(vararg signatures: String): PiracyChecker {
this.enableSigningCertificate = true
this.signatures = arrayOf(*signatures)
return this
}
fun enableInstallerId(vararg installerID: InstallerID): PiracyChecker {
this.installerIDs.addAll(listOf(*installerID))
return this
}
fun enableEmulatorCheck(): PiracyChecker {
this.enableEmulatorCheck = true
return this
}
fun enableRootCheck(): PiracyChecker {
this.enableRootCheck = true
return this
}
fun allowCallback(allowCallback: AllowCallback): PiracyChecker {
this.allowCallback = allowCallback
return this
}
fun doNotAllowCallback(doNotAllowCallback: DoNotAllowCallback): PiracyChecker {
this.doNotAllowCallback = doNotAllowCallback
return this
}
fun onErrorCallback(errorCallback: OnErrorCallback): PiracyChecker {
this.onErrorCallback = errorCallback
return this
}
fun start() {
verify()
}
private fun verify() {
if (!verifySigningCertificate()) {
doNotAllowCallback?.doNotAllow(PiracyCheckerError.SIGNATURE_NOT_VALID)
return
}
if (!verifyInstallerId()) {
doNotAllowCallback?.doNotAllow(PiracyCheckerError.INVALID_INSTALLER_ID)
return
}
if (verifyIsInEmulator()) {
doNotAllowCallback?.doNotAllow(PiracyCheckerError.USING_APP_IN_EMULATOR)
return
}
if (verifyDeviceRooted()) {
doNotAllowCallback?.doNotAllow(PiracyCheckerError.DEVICE_ROOTED)
return
}
allowCallback?.allow()
}
private fun verifySigningCertificate(): Boolean {
return !enableSigningCertificate || (context?.verifySigningCertificates(signatures) == true)
}
private fun verifyInstallerId(): Boolean {
return installerIDs.isEmpty() || (context?.verifyInstallerId(installerIDs) == true)
}
private fun verifyIsInEmulator(): Boolean {
return if (enableEmulatorCheck) {
isInEmulator()
} else false
}
private fun verifyDeviceRooted(): Boolean {
return if (enableRootCheck) {
checkTestKeys() || checkSuCommands() || checkSuperuserApps() || crashlyticsCheck()
} else false
}
fun destroy() {
context = null
}
}
| 0 | Kotlin | 0 | 0 | 9c5d7b9355c406992ff9126d4bd01d49d4778048 | 3,220 | FabricK | MIT License |
godot-kotlin/godot-library/src/nativeGen/kotlin/godot/BoneAttachment.kt | utopia-rise | 238,721,773 | false | {"Kotlin": 655494, "Shell": 171} | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! ALL CHANGES TO IT WILL BE OVERWRITTEN ON EACH BUILD
package godot
import godot.icalls._icall_String
import godot.icalls._icall_Unit_String
import godot.internal.utils.getMethodBind
import godot.internal.utils.invokeConstructor
import kotlin.String
import kotlinx.cinterop.COpaquePointer
open class BoneAttachment : Spatial() {
open var boneName: String
get() {
val mb = getMethodBind("BoneAttachment","get_bone_name")
return _icall_String(mb, this.ptr)
}
set(value) {
val mb = getMethodBind("BoneAttachment","set_bone_name")
_icall_Unit_String(mb, this.ptr, value)
}
override fun __new(): COpaquePointer = invokeConstructor("BoneAttachment", "BoneAttachment")
open fun getBoneName(): String {
val mb = getMethodBind("BoneAttachment","get_bone_name")
return _icall_String( mb, this.ptr)
}
open fun setBoneName(boneName: String) {
val mb = getMethodBind("BoneAttachment","set_bone_name")
_icall_Unit_String( mb, this.ptr, boneName)
}
}
| 17 | Kotlin | 17 | 286 | 8d51f614df62a97f16e800e6635ea39e7eb1fd62 | 1,059 | godot-kotlin-native | MIT License |
leetcode2/src/leetcode/ImplementStackUsinQueues.kt | hewking | 68,515,222 | false | {"Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 104, "Java": 88, "JSON": 1, "XML": 5} | package leetcode
import java.util.*
/**
* 225. 用队列实现栈
* https://leetcode-cn.com/problems/implement-stack-using-queues/
* Created by test
* Date 2019/5/21 0:30
* Description
* 使用队列实现栈的下列操作:
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
*/
object ImplementStackUsinQueues{
/**
* 思路:
* 1.通过一个队列肯定是不行的
* 2.思路跟通过栈实现队列差不多
*/
class MyStack() {
/** Initialize your data structure here. */
val first = ArrayDeque<Int>()
val last = ArrayDeque<Int>()
/** Push element x onto stack. */
fun push(x: Int) {
first.clear()
while (last.isNotEmpty()) {
first.push(last.pollLast())
}
first.push(x)
last.clear()
while (first.isNotEmpty()) {
last.push(first.pollLast())
}
}
/** Removes the element on top of the stack and returns that element. */
fun pop(): Int {
return last.pop()
}
/** Get the top element. */
fun top(): Int {
return last.peek()
}
/** Returns whether the stack is empty. */
fun empty(): Boolean {
return last.isEmpty()
}
}
/**
* Your MyStack object will be instantiated and called as such:
* var obj = MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,691 | leetcode | MIT License |
src/test/kotlin/org/installmation/javafx/test/ComboHelper.kt | SergeMerzliakov | 215,456,643 | false | null | /*
* Copyright 2019 <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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.installmation.javafx.test
import javafx.application.Platform
import javafx.collections.FXCollections
import javafx.scene.control.ComboBox
import org.testfx.framework.junit.ApplicationTest
import org.testfx.util.WaitForAsyncUtils
/**
* JavaFX util functions for ComboBox
*/
class ComboHelper(private val test: ApplicationTest) {
fun <T> selectByIndex(id: String, index: Int): T {
var combo: ComboBox<T>? = null
Platform.runLater {
val fxId = FXIdentity.cleanFxId(id)
test.clickOn(fxId)
combo = test.lookup(fxId).query()
combo?.selectionModel?.select(index)
}
// wait a bit for JavaFX Thread to execute. FXRobot is by design quite slow
WaitForAsyncUtils.waitForFxEvents(3)
return combo?.selectionModel!!.selectedItem
}
fun <T> populateItems(id: String, vararg item: T) {
val model = FXCollections.observableArrayList<T>()
val fxId = FXIdentity.cleanFxId(id)
val combo = test.lookup(fxId).query<ComboBox<T>>()
combo.items = model
for (i in item)
model.add(i)
}
} | 1 | Kotlin | 5 | 45 | eb1c151e70e7fe7c3b096154f1f63d47a50bea19 | 1,693 | installmation | Apache License 2.0 |
app/src/main/java/com/romandevyatov/bestfinance/ui/adapters/more/settings/settingswallets/SettingsWalletsAdapter.kt | RomanDevyatov | 587,557,441 | false | {"Kotlin": 569123} | package com.romandevyatov.bestfinance.ui.adapters.more.settings.settingswallets
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.romandevyatov.bestfinance.databinding.CardWalletItemBinding
import com.romandevyatov.bestfinance.ui.adapters.more.settings.settingswallets.models.SettingsWalletItem
class SettingsWalletsAdapter(
private val onWalletItemCheckedChangeListener: OnWalletItemCheckedChangeListener? = null,
private val walletItemDeleteListener: OnWalletItemDeleteListener? = null,
private val walletItemClickedListener: OnWalletItemClickedListener? = null
) : RecyclerView.Adapter<SettingsWalletsAdapter.WalletItemViewHolder>() {
interface OnWalletItemCheckedChangeListener {
fun onWalletChecked(settingsWalletItem: SettingsWalletItem, isChecked: Boolean)
}
interface OnWalletItemDeleteListener {
fun onWalletItemDelete(settingsWalletItem: SettingsWalletItem)
}
interface OnWalletItemClickedListener {
fun navigateToUpdateWallet(wallet: SettingsWalletItem)
}
private val differentCallback = object: DiffUtil.ItemCallback<SettingsWalletItem>() {
override fun areItemsTheSame(oldItem: SettingsWalletItem, newItem: SettingsWalletItem): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: SettingsWalletItem, newItem: SettingsWalletItem): Boolean {
return oldItem == newItem
}
}
private val differ = AsyncListDiffer(this, differentCallback)
fun submitList(settingsWalletItems: List<SettingsWalletItem>) {
differ.submitList(settingsWalletItems)
}
fun removeItem(settingsWalletItem: SettingsWalletItem) {
val position = differ.currentList.indexOf(settingsWalletItem)
if (position != -1) {
val updatedList = differ.currentList.toMutableList()
updatedList.removeAt(position)
differ.submitList(updatedList)
}
}
inner class WalletItemViewHolder(
private val binding: CardWalletItemBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bindSubgroup(settingsWalletItem: SettingsWalletItem) {
binding.walletTextView.text = settingsWalletItem.name
binding.deleteButton.setOnClickListener {
walletItemDeleteListener?.onWalletItemDelete(settingsWalletItem)
}
binding.switchCompat.isChecked = settingsWalletItem.isExist
binding.switchCompat.setOnCheckedChangeListener { _, isChecked ->
onWalletItemCheckedChangeListener?.onWalletChecked(settingsWalletItem, isChecked)
}
binding.root.setOnClickListener {
walletItemClickedListener?.navigateToUpdateWallet(settingsWalletItem)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WalletItemViewHolder {
val binding = CardWalletItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return WalletItemViewHolder(binding)
}
override fun onBindViewHolder(holder: WalletItemViewHolder, position: Int) {
val walletItem = differ.currentList[position]
holder.bindSubgroup(walletItem)
}
override fun getItemCount(): Int {
return differ.currentList.size
}
}
| 0 | Kotlin | 0 | 1 | bacad4ca4c12fdef63d1e1e746439751cb891776 | 3,505 | BestFinance | Apache License 2.0 |
library/src/main/java/cloud/pace/sdk/api/user/generated/model/Error.kt | pace | 303,641,261 | false | null | /*
* PLEASE DO NOT EDIT!
*
* Generated by SwagGen with Kotlin template.
* https://github.com/pace/SwagGen
*/
package cloud.pace.sdk.api.poi.generated.model
import com.google.gson.annotations.SerializedName
import com.squareup.moshi.Json
import moe.banana.jsonapi2.HasMany
import moe.banana.jsonapi2.HasOne
import moe.banana.jsonapi2.JsonApi
import moe.banana.jsonapi2.Resource
import java.util.*
/* Error objects provide additional information about problems encountered while performing an operation.
Errors also contain codes besides title and message which can be used for checks even if the detailed messages might change.
* `1000`: generic error
* `1001`: payment processing temporarily unavailable
* `1002`: requested amount exceeds the authorized amount of the provided token
* `1003`: implicit payment methods cannot be modified
* `1004`: payment method rejected by provider
* `provider:payment-method-rejected`: payment method rejected by provider (identical to `1004`)
* `rule:product-denied`: Product restrictions forbid transaction, e.g., forbidden fuel type - token authorized only for Diesel but attempted to fuel Super.
*/
class Error {
var errors: List<Errors>? = null
/* Error objects provide additional information about problems encountered while performing an operation.
Errors also contain codes besides title and message which can be used for checks even if the detailed messages might change.
* `1000`: generic error
* `1001`: payment processing temporarily unavailable
* `1002`: requested amount exceeds the authorized amount of the provided token
* `1003`: implicit payment methods cannot be modified
* `1004`: payment method rejected by provider
* `provider:payment-method-rejected`: payment method rejected by provider (identical to `1004`)
* `rule:product-denied`: Product restrictions forbid transaction, e.g., forbidden fuel type - token authorized only for Diesel but attempted to fuel Super.
*/
class Errors {
/* an application-specific error code, expressed as a string value.
*/
var code: String? = null
/* a human-readable explanation specific to this occurrence of the problem. Like title, this field’s value can be localized.
*/
var detail: String? = null
var links: Links? = null
/* a meta object containing non-standard meta-information about the error.
*/
var meta: Map<String, Any>? = null
/* An object containing references to the source of the error.
*/
var source: Source? = null
/* the HTTP status code applicable to this problem, expressed as a string value.
*/
var status: String? = null
/* A short, human-readable summary of the problem that SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization.
*/
var title: String? = null
/* Error objects provide additional information about problems encountered while performing an operation.
Errors also contain codes besides title and message which can be used for checks even if the detailed messages might change.
* `1000`: generic error
* `1001`: payment processing temporarily unavailable
* `1002`: requested amount exceeds the authorized amount of the provided token
* `1003`: implicit payment methods cannot be modified
* `1004`: payment method rejected by provider
* `provider:payment-method-rejected`: payment method rejected by provider (identical to `1004`)
* `rule:product-denied`: Product restrictions forbid transaction, e.g., forbidden fuel type - token authorized only for Diesel but attempted to fuel Super.
*/
class Links {
/* A link that leads to further details about this particular occurrence of the problem.
*/
var about: String? = null
}
/* An object containing references to the source of the error.
*/
class Source {
/* A string indicating which URI query parameter caused the error.
*/
var parameter: String? = null
/* A JSON Pointer [RFC6901] to the associated entity in the request document [e.g. "/data" for a primary data object, or "/data/attributes/title" for a specific attribute].
*/
var pointer: String? = null
}
}
}
| 0 | Kotlin | 0 | 3 | 4b4a5e8ad5861a777d20ab7de2c1c8d04b5e1d42 | 4,521 | cloud-sdk-android | MIT License |
device-server/src/main/kotlin/com/badoo/automation/deviceserver/data/AppBundleDto.kt | badoo | 133,063,088 | false | {"Kotlin": 528224, "Ruby": 19586, "Shell": 7939, "Java": 956} | package com.badoo.automation.deviceserver.data
import com.fasterxml.jackson.annotation.JsonProperty
data class AppBundleDto(
@JsonProperty("app_url")
val appUrl: String,
@JsonProperty("dsym_url")
val dsymUrl: String?
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AppBundleDto
if (appUrl != other.appUrl) return false
return true
}
override fun hashCode(): Int {
return appUrl.hashCode()
}
}
| 3 | Kotlin | 11 | 42 | 5f746abbeeca944f127eeb9fb6ac7bd4b30bf913 | 569 | ios-device-server | MIT License |
feature/watch_list/src/main/kotlin/com/mobiledevpro/watchlist/view/ext/RecyclerViewExtension.kt | mobiledevpro | 434,560,335 | false | {"Kotlin": 98027, "Java": 3283} | /*
* Copyright 2020 | <NAME> | http://mobile-dev.pro
*
*
* 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.mobiledevpro.alertlog.view.ext
import android.graphics.drawable.Drawable
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import com.mobiledevpro.recycler.RecyclerItem
import com.mobiledevpro.recycler.RecyclerViewHandler
import com.mobiledevpro.recycler.ext.set
/**
* Extension for RecyclerView with Data Binding
*
*
* NOTE:
* it should be placed in the same module with XML layout for RecyclerView adapter,
* otherwise you will have an error like "Cannot find a setter for... bind:items, bind:eventHandler, etc."
*
*/
object RecyclerViewExtension {
@BindingAdapter(
value = [
"bind:items",
"bind:eventHandler",
"bind:divider"
],
requireAll = false
)
@JvmStatic
fun RecyclerView.setItems(
items: List<RecyclerItem>?,
handler: RecyclerViewHandler?,
divider: Drawable?
) {
this.set(
items,
handler,
divider
)
//Scroll to top
this.smoothScrollToPosition(0)
}
} | 1 | Kotlin | 1 | 3 | 374a766ae6e3c7a038465ae5f45a08549a6c78e8 | 1,722 | Android-WorkManager-Demo | Apache License 2.0 |
app/src/main/java/com/arm/peliondevicemanagement/helpers/converters/WTasksListConverter.kt | ameerirsh | 310,142,487 | true | {"Kotlin": 524618, "Java": 7898} | /*
* Copyright 2020 ARM Ltd.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arm.peliondevicemanagement.helpers.converters
import androidx.room.TypeConverter
import com.arm.peliondevicemanagement.components.models.workflow.device.WorkflowDevice
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlin.collections.ArrayList
class WDevicesListConverter {
@TypeConverter
fun fromString(value: String?): ArrayList<WorkflowDevice>? {
val type = object: TypeToken<ArrayList<WorkflowDevice>?>() {}.type
return Gson().fromJson(value, type)
}
@TypeConverter
fun fromList(list: ArrayList<WorkflowDevice>?): String {
val type = object: TypeToken<ArrayList<WorkflowDevice>?>() {}.type
return Gson().toJson(list, type)
}
} | 0 | null | 0 | 1 | c32f4e24bdcd9a99df7d98f50427932c4cf2ecd0 | 1,358 | peliondevicemanagement-for-android | Apache License 2.0 |
app/src/main/java/io/fluks/feature/login/view/LoginUI.kt | yaneq6 | 169,347,692 | false | {"Gradle": 10, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Kotlin": 82, "XML": 34, "SVG": 2, "Java": 1} | package io.fluks.feature.login.view
import android.app.Activity
import android.content.Context
import android.content.Intent
import io.fluks.App
import io.fluks.R
import io.fluks.base.Action
import io.fluks.base.UI
import io.fluks.base.android.BaseActivity
import io.fluks.core.EventsManager
import io.fluks.databinding.LoginBinding
import io.fluks.di.provide
import io.fluks.di.provider.weakSingleton
object LoginUI {
interface Component :
UI.Component<LoginBinding>,
BaseActivity.Component,
EventsManager.Component
class Module(
app: App.Component
) : Component,
App.Component by app {
override val layoutId = R.layout.login
override val disposable by provide(weakSingleton()) {
LoginViewModel(
dispatch = dispatch,
store = sessionStore
)
}
override fun LoginBinding.init() {
model = disposable
}
}
data class Navigate(
override val finishCurrent: Boolean = false
) : Action.Navigate<Context> {
override fun Context.navigate() {
startActivity(Intent(this, LoginActivity::class.java))
if (finishCurrent && this is Activity) finish()
}
}
} | 0 | Kotlin | 0 | 2 | 96ab0f8c34f52cf6f6e287e2317cb144c0b954e9 | 1,276 | fluKs | MIT License |
access-checkout/src/main/java/com/worldpay/access/checkout/api/discovery/DiscoverLinks.kt | Worldpay | 186,591,910 | false | {"Kotlin": 818601, "Shell": 8062, "Java": 6550} | package com.worldpay.access.checkout.api.discovery
import com.worldpay.access.checkout.session.api.client.ACCEPT_HEADER
import com.worldpay.access.checkout.session.api.client.CONTENT_TYPE_HEADER
import com.worldpay.access.checkout.session.api.client.SESSIONS_MEDIA_TYPE
import com.worldpay.access.checkout.session.api.client.VERIFIED_TOKENS_MEDIA_TYPE
import java.io.Serializable
internal class DiscoverLinks(val endpoints: List<Endpoint>) : Serializable {
internal companion object {
val verifiedTokens = DiscoverLinks(
listOf(
Endpoint("service:verifiedTokens"),
Endpoint(
"verifiedTokens:sessions",
mapOf(
ACCEPT_HEADER to VERIFIED_TOKENS_MEDIA_TYPE,
CONTENT_TYPE_HEADER to VERIFIED_TOKENS_MEDIA_TYPE
)
)
)
)
val sessions = DiscoverLinks(
listOf(
Endpoint("service:sessions"),
Endpoint(
"sessions:paymentsCvc",
mapOf(
ACCEPT_HEADER to SESSIONS_MEDIA_TYPE,
CONTENT_TYPE_HEADER to SESSIONS_MEDIA_TYPE
)
)
)
)
}
}
| 1 | Kotlin | 3 | 8 | 3160cfede3319436be824667a731d122286c07f2 | 1,318 | access-checkout-android | MIT License |
domain/src/main/kotlin/com/oz/meow/annotation/Create.kt | voncho-zero | 742,285,196 | false | {"Kotlin": 21206} | package com.oz.meow.annotation
import com.oz.meow.convert.MetaConvert
import org.beetl.sql.annotation.builder.Builder
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
@Builder(MetaConvert::class)
annotation class Create()
| 0 | Kotlin | 0 | 0 | 9a35e9436f1b8ac9ce1b119ca4691b4ebc3ccfe6 | 247 | meow | Apache License 2.0 |
livelogger/src/main/kotlin/MainUi.kt | lambdapioneer | 650,185,708 | false | {"Kotlin": 153164, "Jupyter Notebook": 92840, "Rust": 15505, "Python": 13604, "C++": 3065, "OpenSCAD": 2520, "Shell": 639, "Dockerfile": 551} | import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.event.WindowEvent
import java.io.File
import javax.swing.*
private val FRAME_DIMENSIONS = Dimension(1200, 800)
private val DIALOG_DIMENSIONS = Dimension(800, 600)
class MainUi {
private val frame = JFrame("LiveLogger")
private lateinit var graphController: GraphController
fun start() {
val controlPanel = createControlPanel()
val graphView = GraphView()
val helpText = createHelpText()
val pane = frame.contentPane
pane.apply {
add(controlPanel, BorderLayout.PAGE_START)
add(graphView, BorderLayout.CENTER)
add(helpText, BorderLayout.PAGE_END)
}
frame.apply {
isVisible = true
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
size = FRAME_DIMENSIONS
setLocationRelativeTo(null)
addWindowStateListener { if (it.id == WindowEvent.WINDOW_CLOSED) graphController.close() }
}
graphController = GraphController(graphView, EmptyDataSource())
graphView.requestFocusInWindow()
}
private fun createControlPanel(): JPanel {
val panel = JPanel()
val buttonCsvOpen = JButton("Read from CSV file...")
val buttonCsvTail = JButton("Tail CSV file...")
val buttonCsvSave = JButton("Save visible to CSV file...")
panel.add(buttonCsvOpen)
panel.add(buttonCsvTail)
panel.add(buttonCsvSave)
buttonCsvOpen.addActionListener {
val file = showOpenFileDialog()
file?.also {
val csvDataSource = readCsv(it)
graphController.replaceDataSource(csvDataSource)
graphController.requestFocus()
}
}
buttonCsvTail.addActionListener {
val file = showOpenFileDialog()
file?.also {
val csvDataSource = FileTrailingDataSource(file)
csvDataSource.start()
graphController.replaceDataSource(csvDataSource)
graphController.requestFocus()
}
}
buttonCsvSave.addActionListener {
val file = showSaveFileDialog()
file?.also {
writeCsv(graphController.getDataCopy(), file)
graphController.requestFocus()
}
}
return panel
}
private fun showOpenFileDialog(): File? {
val fileChooser = JFileChooser()
fileChooser.currentDirectory = getCsvDir()
fileChooser.preferredSize = DIALOG_DIMENSIONS
val result = fileChooser.showOpenDialog(frame)
return if (result == JFileChooser.APPROVE_OPTION) fileChooser.selectedFile else null
}
private fun showSaveFileDialog(): File? {
val fileChooser = JFileChooser()
fileChooser.currentDirectory = getCsvDir()
fileChooser.preferredSize = DIALOG_DIMENSIONS
val result = fileChooser.showSaveDialog(frame)
return if (result == JFileChooser.APPROVE_OPTION) fileChooser.selectedFile else null
}
private fun getCsvDir(): File {
val workingDir = File(System.getProperty("user.dir"))
return File(workingDir.parent, "measurements")
}
private fun createHelpText(): JTextPane {
val helpText = JTextPane()
helpText.contentType = "text/html"
helpText.text = HELP_TEXT_HTML
helpText.isEditable = false
return helpText
}
}
private val HELP_TEXT_HTML = """
<html>
<b>Usage</b> <tt>[home]</tt> or <tt>[right-click]</tt> resets to full data view.
<tt>[end]</tt> enters trailing mode.
<tt>[space]</tt> freezes/unfreezes the data.
<tt>[left-click-drag]</tt> for zooming into selected area.
<tt>[mouse wheel]</tt> for zooming in and out in trailing and zoomed-in mode.
<tt>[arrow keys]</tt> for zooming and panning in trailing/zoomed-in mode.
<tt>[0]</tt> sets 0 as minimum for Y-Axis.
<tt>[a]</tt> toggle anti-alias.
<tt>[S]/[s]</tt> increase/decrease sampling.
</html>
""".trimIndent()
| 0 | Kotlin | 0 | 1 | 2bd0df00f68a149ed61801d45f1a9396673daab8 | 4,109 | powering-privacy | MIT License |
compiler/testData/codegen/boxInline/suspend/capturedVariables.kt | JakeWharton | 99,388,807 | false | null | // FILE: test.kt
// WITH_RUNTIME
import kotlin.coroutines.experimental.*
suspend inline fun test1(c: suspend () -> Unit) {
c()
}
suspend inline fun test2(crossinline c: suspend () -> Unit) {
val l: suspend () -> Unit = { c() }
l()
}
// FILE: box.kt
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
fun builder(c: suspend () -> Unit) {
c.startCoroutine(object: Continuation<Unit> {
override val context: CoroutineContext
get() = EmptyCoroutineContext
override fun resume(value: Unit) {
}
override fun resumeWithException(exception: Throwable) {
throw exception
}
})
}
suspend fun calculate() = suspendCoroutineOrReturn<String> {
it.resume("OK")
COROUTINE_SUSPENDED
}
fun box() : String {
var res = "FAIL 1"
builder {
val a = 1
test2 {
val b = 2
test1 {
val c = a + b // 3
run {
val a = c + 1 // 4
test1 {
val b = c + c // 6
test2 {
val c = b - a // 2
res = "${calculate()} $a$b$c"
}
}
}
}
}
}
if (res != "OK 462") return res
return "OK"
} | 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,397 | kotlin | Apache License 2.0 |
app/src/main/java/com/realform/macropaytestpokemon/data/local/network/NetworkVerifier.kt | IvanMedinaH | 809,257,969 | false | {"Kotlin": 194139} | package com.realform.macropaytestpokemon.data.local.network
interface NetworkVerifier {
fun isNetworkAvailable(): Boolean
} | 0 | Kotlin | 0 | 0 | d6bdc416600f99f80af5264db420929796e109b2 | 128 | Pokedex | MIT License |
src/test/kotlin/br/com/acmattos/hdc/odontogram/application/OdontogramCommandHandlerServiceTest.kt | acmattos | 225,613,144 | false | {"Kotlin": 955728, "JavaScript": 151772, "HTML": 26378, "CSS": 4190} | package br.com.acmattos.hdc.odontogram.application
import br.com.acmattos.hdc.common.context.domain.cqs.EventStore
import br.com.acmattos.hdc.common.context.domain.model.Repository
import br.com.acmattos.hdc.common.tool.assertion.AssertionFailedException
import br.com.acmattos.hdc.common.tool.page.EqFilter
import br.com.acmattos.hdc.odontogram.config.MessageTrackerIdEnum.ODONTOGRAM_ALREADY_DEFINED
import br.com.acmattos.hdc.odontogram.config.MessageTrackerIdEnum.ODONTOGRAM_NOT_DEFINED
import br.com.acmattos.hdc.odontogram.domain.cqs.*
import br.com.acmattos.hdc.odontogram.domain.model.CommandBuilder
import br.com.acmattos.hdc.odontogram.domain.model.EventBuilder
import br.com.acmattos.hdc.odontogram.domain.model.Odontogram
import br.com.acmattos.hdc.odontogram.domain.model.OdontogramAttributes
import br.com.acmattos.hdc.odontogram.port.persistence.mongodb.DocumentIndexedField.EVENT_ODONTOGRAM_ID_ID
import br.com.acmattos.hdc.odontogram.port.rest.OdontogramCreateRequest
import br.com.acmattos.hdc.odontogram.port.rest.OdontogramUpdateRequest
import io.kotest.core.spec.style.FreeSpec
import io.mockk.*
import org.assertj.core.api.AbstractThrowableAssert
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatCode
private const val EXCEPTION_MESSAGE_1 = "There is an odontogram already defined for the given id [01FK96GENJKTN1BYZW6BRHFZFJ]!"
private const val EXCEPTION_MESSAGE_2 = "There is no odontogram defined for the given id [01FK96GENJKTN1BYZW6BRHFZFJ]!"
private const val EXCEPTION_MESSAGE_3 = "Upper left must contain exactly 8 teeth!"
private const val EXCEPTION_MESSAGE_4 = "There is no odontogram defined for the given id [01FK96GENJKTN1BYZW6BRHFZFJ]!"
/**
* @author ACMattos
* @since 20/03/2022.
*/
class OdontogramCommandHandlerServiceTest: FreeSpec({
"Feature: OdontogramCommandHandlerService usage - creating a odontogram flows" - {
"Scenario: handling OdontogramCreateCommand successfully" - {
lateinit var command: OdontogramCreateCommand
lateinit var eventStore: EventStore<OdontogramEvent>
lateinit var repository: Repository<Odontogram>
lateinit var service: OdontogramCommandHandlerService
lateinit var event: OdontogramCreateEvent
"Given: a ${EventStore::class.java.simpleName} mock" {
eventStore = mockk()
}
"And: eventStore#findAllByFilter returns empty list" {
every {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
OdontogramAttributes.VOMID
)
)
} returns listOf()
}
"And: eventStore#addEvent just runs" {
every { eventStore.addEvent(any<OdontogramCreateEvent>()) } just Runs
}
"And: a ${Repository::class.java.simpleName} mock" {
repository = mockk()
}
"And: repository#save just runs" {
every { repository.save(any()) } just Runs
}
"And: a ${OdontogramCreateCommand::class.java.simpleName} generated" {
command = CommandBuilder.buildCreateCommand()
}
"And: a ${OdontogramCommandHandlerService::class.java.simpleName} successfully instantiated" {
service = OdontogramCommandHandlerService(eventStore, repository)
}
"When: #handle is executed" {
event = service.handle(command) as OdontogramCreateEvent
}
"Then: ${OdontogramCreateEvent::class.java.simpleName} matches event´s class" {
assertThat(event::class).hasSameClassAs(OdontogramCreateEvent::class)
}
"And: the event store is accessed in the right order" {
verifyOrder {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
command.odontogramId.id
)
)
eventStore.addEvent(any<OdontogramCreateEvent>())
}
}
"And: the repository is accessed once" {
verify(exactly = 1) {
repository.save(any())
}
}
}
"Scenario: handling OdontogramCreateCommand for a already registered odontogram" - {
lateinit var command: OdontogramCreateCommand
lateinit var eventStore: EventStore<OdontogramEvent>
lateinit var repository: Repository<Odontogram>
lateinit var service: OdontogramCommandHandlerService
lateinit var assertion: AbstractThrowableAssert<*, out Throwable>
"Given: a ${EventStore::class.java.simpleName} mock" {
eventStore = mockk()
}
"And: eventStore#findAllByFilter returns an event" {
every {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
OdontogramAttributes.VOMID
)
)
} returns listOf(EventBuilder.buildCreateEvent())
}
"And: eventStore#addEvent just runs" {
every { eventStore.addEvent(any<OdontogramCreateEvent>()) } just Runs
}
"And: a ${Repository::class.java.simpleName} mock" {
repository = mockk()
}
"And: a ${OdontogramCreateCommand::class.java.simpleName} generated" {
command = CommandBuilder.buildCreateCommand()
}
"And: a ${OdontogramCommandHandlerService::class.java.simpleName} successfully instantiated" {
service = OdontogramCommandHandlerService(eventStore, repository)
}
"When: #handle is executed" {
assertion = assertThatCode {
service.handle(command) as OdontogramCreateEvent
}
}
"Then: ${AssertionFailedException::class.java.simpleName} is raised with message" {
assertion.hasSameClassAs(
AssertionFailedException(
EXCEPTION_MESSAGE_1,
ODONTOGRAM_ALREADY_DEFINED.messageTrackerId
)
)
}
"And: the message is $EXCEPTION_MESSAGE_1" {
assertion.hasMessage(EXCEPTION_MESSAGE_1)
}
"And: exception has messageTrackerId ${ODONTOGRAM_ALREADY_DEFINED.messageTrackerId}" {
assertion.hasFieldOrPropertyWithValue("code", ODONTOGRAM_ALREADY_DEFINED.messageTrackerId)
}
"And: the eventStore#findAllByFilter is accessed" {
verify(exactly = 1) {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
OdontogramAttributes.VOMID
)
)
}
}
"And: the repository#save is not accessed" {
verify(exactly = 0) {
repository.save(any())
}
}
"And: the event store#addEvent is not accessed" {
verify(exactly = 0) {
eventStore.addEvent(any<OdontogramCreateEvent>())
}
}
}
"Scenario: handling OdontogramCreateCommand for an invalid description" - {
lateinit var command: OdontogramCreateCommand
lateinit var eventStore: EventStore<OdontogramEvent>
lateinit var repository: Repository<Odontogram>
lateinit var service: OdontogramCommandHandlerService
lateinit var assertion: AbstractThrowableAssert<*, out Throwable>
"Given: a ${EventStore::class.java.simpleName} mock" {
eventStore = mockk()
}
"And: eventStore#findAllByFilter returns empty list" {
every {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
OdontogramAttributes.VOMID
)
)
} returns listOf()
}
"And: a ${Repository::class.java.simpleName} mock" {
repository = mockk()
}
"And: a ${OdontogramCreateCommand::class.java.simpleName} generated" {
command = CommandBuilder.buildInvalidCreateCommand()
}
"And: a ${OdontogramCommandHandlerService::class.java.simpleName} successfully instantiated" {
service = OdontogramCommandHandlerService(eventStore, repository)
}
"When: #handle is executed" {
assertion = assertThatCode {
service.handle(command) as OdontogramCreateEvent
}
}
"Then: ${AssertionFailedException::class.java.simpleName} is raised with message" {
// assertion.hasSameClassAs(
// AssertionFailedException(
// EXCEPTION_MESSAGE_3,
// DESCRIPTION_INVALID_LENGTH.messageTrackerId
// )
// )
}
"And: the message is $EXCEPTION_MESSAGE_3" {
assertion.hasMessage(EXCEPTION_MESSAGE_3)
}
// "And: exception has messageTrackerId ${DESCRIPTION_INVALID_LENGTH.messageTrackerId}" {
// assertion.hasFieldOrPropertyWithValue("code", DESCRIPTION_INVALID_LENGTH.messageTrackerId)
// }
"And: the eventStore#findAllByFilter is accessed" {
verify(exactly = 1) {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
OdontogramAttributes.VOMID
)
)
}
}
"And: the repository#save is not accessed" {
verify(exactly = 0) {
repository.save(any())
}
}
"And: the event store#addEvent is not accessed " {
verify(exactly = 0) {
eventStore.addEvent(any<OdontogramCreateEvent>())
}
}
}
}
"Feature: OdontogramCommandHandlerService usage - upserting a odontogram flows" - {
"Scenario: handling OdontogramUpsertCommand successfully" - {
lateinit var command: OdontogramCreateCommand
lateinit var eventStore: EventStore<OdontogramEvent>
lateinit var repository: Repository<Odontogram>
lateinit var service: OdontogramCommandHandlerService
lateinit var event: OdontogramUpsertEvent
"Given: a ${EventStore::class.java.simpleName} mock" {
eventStore = mockk()
}
"And: eventStore#findAllByFilter returns delete event" {
every {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
OdontogramAttributes.VOMID
)
)
} returns listOf(EventBuilder.buildDeleteEvent())
}
"And: eventStore#addEvent just runs" {
every { eventStore.addEvent(any<OdontogramCreateEvent>()) } just Runs
}
"And: a ${Repository::class.java.simpleName} mock" {
repository = mockk()
}
"And: repository#save just runs" {
every { repository.save(any()) } just Runs
}
"And: a ${OdontogramCreateCommand::class.java.simpleName} generated" {
command = CommandBuilder.buildCreateCommand()
}
"And: a ${OdontogramCommandHandlerService::class.java.simpleName} successfully instantiated" {
service = OdontogramCommandHandlerService(eventStore, repository)
}
"When: #handle is executed" {
event = service.handle(command) as OdontogramUpsertEvent
}
"Then: ${OdontogramUpsertEvent::class.java.simpleName} matches event´s class" {
assertThat(event::class).hasSameClassAs(OdontogramUpsertEvent::class)
}
"And: the event store is accessed in the right order" {
verifyOrder {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
command.odontogramId.id
)
)
eventStore.addEvent(any<OdontogramCreateEvent>())
}
}
"And: the repository is accessed once" {
verify(exactly = 1) {
repository.save(any())
}
}
}
"Scenario: handling OdontogramUpsertCommand for a already registered odontogram" - {
lateinit var command: OdontogramCreateCommand
lateinit var eventStore: EventStore<OdontogramEvent>
lateinit var repository: Repository<Odontogram>
lateinit var service: OdontogramCommandHandlerService
lateinit var assertion: AbstractThrowableAssert<*, out Throwable>
"Given: a ${EventStore::class.java.simpleName} mock" {
eventStore = mockk()
}
"And: eventStore#findAllByFilter returns an event" {
every {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
OdontogramAttributes.VOMID
)
)
} returns listOf(EventBuilder.buildCreateEvent())
}
"And: a ${Repository::class.java.simpleName} mock" {
repository = mockk()
}
"And: a ${OdontogramCreateCommand::class.java.simpleName} generated" {
command = CommandBuilder.buildCreateCommand()
}
"And: a ${OdontogramCommandHandlerService::class.java.simpleName} successfully instantiated" {
service = OdontogramCommandHandlerService(eventStore, repository)
}
"When: #handle is executed" {
assertion = assertThatCode {
service.handle(command) as OdontogramCreateEvent
}
}
"Then: ${AssertionFailedException::class.java.simpleName} is raised with message" {
assertion.hasSameClassAs(
AssertionFailedException(
EXCEPTION_MESSAGE_1,
ODONTOGRAM_ALREADY_DEFINED.messageTrackerId
)
)
}
"And: the message is $EXCEPTION_MESSAGE_1" {
assertion.hasMessage(EXCEPTION_MESSAGE_1)
}
"And: exception has messageTrackerId ${ODONTOGRAM_ALREADY_DEFINED.messageTrackerId}" {
assertion.hasFieldOrPropertyWithValue("code", ODONTOGRAM_ALREADY_DEFINED.messageTrackerId)
}
"And: the eventStore#findAllByFilter is accessed" {
verify(exactly = 1) {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
command.odontogramId.id
)
)
}
}
"And: the repository#save is not accessed" {
verify(exactly = 0) {
repository.save(any())
}
}
"And: the event store#addEvent is not accessed" {
verify(exactly = 0) {
eventStore.addEvent(any<OdontogramCreateEvent>())
}
}
}
"Scenario: handling OdontogramUpsertCommand for an invalid description" - {
lateinit var command: OdontogramCreateCommand
lateinit var eventStore: EventStore<OdontogramEvent>
lateinit var repository: Repository<Odontogram>
lateinit var service: OdontogramCommandHandlerService
lateinit var assertion: AbstractThrowableAssert<*, out Throwable>
"Given: a ${EventStore::class.java.simpleName} mock" {
eventStore = mockk()
}
"And: eventStore#findAllByFilter returns delete event" {
every {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
OdontogramAttributes.VOMID
)
)
} returns listOf(EventBuilder.buildDeleteEvent())
}
"And: a ${Repository::class.java.simpleName} mock" {
repository = mockk()
}
"And: a ${OdontogramCreateCommand::class.java.simpleName} generated" {
command = CommandBuilder.buildInvalidCreateCommand()
}
"And: a ${OdontogramCommandHandlerService::class.java.simpleName} successfully instantiated" {
service = OdontogramCommandHandlerService(eventStore, repository)
}
"When: #handle is executed" {
assertion = assertThatCode {
service.handle(command)
}
}
"Then: ${AssertionFailedException::class.java.simpleName} is raised with message" {
// assertion.hasSameClassAs(
// AssertionFailedException(
// EXCEPTION_MESSAGE_3,
// DESCRIPTION_INVALID_LENGTH.messageTrackerId
// )
// )
}
"And: the message is $EXCEPTION_MESSAGE_3" {
assertion.hasMessage(EXCEPTION_MESSAGE_3)
}
// "And: exception has messageTrackerId ${DESCRIPTION_INVALID_LENGTH.messageTrackerId}" {
// assertion.hasFieldOrPropertyWithValue("code", DESCRIPTION_INVALID_LENGTH.messageTrackerId)
// }
"And: the eventStore#findAllByFilter is accessed" {
verify(exactly = 1) {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
command.odontogramId.id
)
)
}
}
"And: the repository#save is not accessed" {
verify(exactly = 0) {
repository.save(any())
}
}
"And: the event store#addEvent is not accessed " {
verify(exactly = 0) {
eventStore.addEvent(any<OdontogramCreateEvent>())
}
}
}
}
"Feature: OdontogramCommandHandlerService usage - updating a odontogram flows" - {
"Scenario: handling OdontogramUpdateCommand successfully" - {
lateinit var command: OdontogramUpdateCommand
lateinit var eventStore: EventStore<OdontogramEvent>
lateinit var repository: Repository<Odontogram>
lateinit var service: OdontogramCommandHandlerService
lateinit var event: OdontogramUpdateEvent
"Given: a ${EventStore::class.java.simpleName} mock" {
eventStore = mockk()
}
"And: eventStore#findAllByFilter returns an event" {
every {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
OdontogramAttributes.VOMID
)
)
} returns listOf(EventBuilder.buildCreateEvent())
}
"And: eventStore#addEvent just runs" {
every { eventStore.addEvent(any<OdontogramUpdateEvent>()) } just Runs
}
"And: a ${Repository::class.java.simpleName} mock" {
repository = mockk()
}
"And: repository#update just runs" {
every { repository.update(any(), any()) } just Runs
}
"And: a ${OdontogramUpdateCommand::class.java.simpleName} generated from ${OdontogramCreateRequest::class.java.simpleName}" {
command = CommandBuilder.buildUpdateCommand()
}
"And: a ${OdontogramCommandHandlerService::class.java.simpleName} successfully instantiated" {
service = OdontogramCommandHandlerService(eventStore, repository)
}
"When: #handle is executed" {
event = service.handle(command) as OdontogramUpdateEvent
}
"Then: ${OdontogramUpdateEvent::class.java.simpleName} matches event´s class" {
assertThat(event::class).hasSameClassAs(OdontogramUpdateEvent::class)
}
"And: the event store is accessed in the right order" {
verifyOrder {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
command.odontogramId.id
)
)
eventStore.addEvent(any<OdontogramUpdateEvent>())
}
}
"And: the repository is accessed once" {
verify(exactly = 1) {
repository.update(any(), any())
}
}
}
"Scenario: handling OdontogramUpdateCommand for non registered odontogram" - {
lateinit var command: OdontogramUpdateCommand
lateinit var eventStore: EventStore<OdontogramEvent>
lateinit var repository: Repository<Odontogram>
lateinit var service: OdontogramCommandHandlerService
lateinit var assertion: AbstractThrowableAssert<*, out Throwable>
"Given: a ${EventStore::class.java.simpleName} mock" {
eventStore = mockk()
}
"And: eventStore#findAllByFilter returns empty list" {
every {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
OdontogramAttributes.VOMID
)
)
} returns listOf()
}
"And: a ${Repository::class.java.simpleName} mock" {
repository = mockk()
}
"And: a ${OdontogramUpdateCommand::class.java.simpleName} generated" {
command = CommandBuilder.buildUpdateCommand()
}
"And: a ${OdontogramCommandHandlerService::class.java.simpleName} successfully instantiated" {
service = OdontogramCommandHandlerService(eventStore, repository)
}
"When: #handle is executed" {
assertion = assertThatCode {
service.handle(command) as OdontogramUpdateEvent
}
}
"Then: ${AssertionFailedException::class.java.simpleName} is raised with message" {
assertion.hasSameClassAs(
AssertionFailedException(
EXCEPTION_MESSAGE_4,
ODONTOGRAM_NOT_DEFINED.messageTrackerId
)
)
}
"And: the message is $EXCEPTION_MESSAGE_4" {
assertion.hasMessage(EXCEPTION_MESSAGE_4)
}
"And: exception has messageTrackerId ${ODONTOGRAM_NOT_DEFINED.messageTrackerId}" {
assertion.hasFieldOrPropertyWithValue("code", ODONTOGRAM_NOT_DEFINED.messageTrackerId)
}
"And: the eventStore#findAllByFilter is accessed" {
verify(exactly = 1) {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
OdontogramAttributes.VOMID
)
)
}
}
"And: the repository#update is not accessed" {
verify(exactly = 0) {
repository.update(any(), any())
}
}
"And: the event store#addEvent is not accessed" {
verify(exactly = 0) {
eventStore.addEvent(any<OdontogramCreateEvent>())
}
}
}
"Scenario: handling OdontogramUpdateCommand for an invalid description"- {
lateinit var command: OdontogramUpdateCommand
lateinit var eventStore: EventStore<OdontogramEvent>
lateinit var repository: Repository<Odontogram>
lateinit var service: OdontogramCommandHandlerService
lateinit var assertion: AbstractThrowableAssert<*, out Throwable>
"Given: a ${EventStore::class.java.simpleName} mock" {
eventStore = mockk()
}
"And: eventStore#findAllByFilter returns create event" {
every {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
OdontogramAttributes.VOMID
)
)
} returns listOf(EventBuilder.buildCreateEvent())
}
"And: a ${Repository::class.java.simpleName} mock" {
repository = mockk()
}
"And: a ${OdontogramCreateCommand::class.java.simpleName} generated}" {
command = CommandBuilder.buildInvalidUpdateCommand()
}
"And: a ${OdontogramCommandHandlerService::class.java.simpleName} successfully instantiated" {
service = OdontogramCommandHandlerService(eventStore, repository)
}
"When: #handle is executed" {
assertion = assertThatCode {
service.handle(command)
}
}
"Then: ${AssertionFailedException::class.java.simpleName} is raised with message" {
// assertion.hasSameClassAs(
// AssertionFailedException(
// EXCEPTION_MESSAGE_3,
// DESCRIPTION_INVALID_LENGTH.messageTrackerId
// )
// )
}
"And: the message is $EXCEPTION_MESSAGE_3" {
assertion.hasMessage(EXCEPTION_MESSAGE_3)
}
// "And: exception has messageTrackerId ${DESCRIPTION_INVALID_LENGTH.messageTrackerId}" {
// assertion.hasFieldOrPropertyWithValue("code", DESCRIPTION_INVALID_LENGTH.messageTrackerId)
// }
"And: the eventStore#findAllByFilter is accessed" {
verify(exactly = 1) {
eventStore.findAllByFilter(
EqFilter<String, String>(
EVENT_ODONTOGRAM_ID_ID.fieldName,
command.odontogramId.id
)
)
}
}
"And: the repository#save is not accessed" {
verify(exactly = 0) {
repository.save(any())
}
}
"And: the event store#addEvent is not accessed " {
verify(exactly = 0) {
eventStore.addEvent(any<OdontogramCreateEvent>())
}
}
}
}
"Feature: OdontogramCommandHandlerService usage - deleting a odontogram flows" - {
"Scenario: handling OdontogramDeleteCommand successfully" - {
lateinit var command: OdontogramDeleteCommand
lateinit var eventStore: EventStore<OdontogramEvent>
lateinit var repository: Repository<Odontogram>
lateinit var service: OdontogramCommandHandlerService
lateinit var event: OdontogramDeleteEvent
"Given: a ${EventStore::class.java.simpleName} mock" {
eventStore = mockk()
}
"And: eventStore#findAllByFilter returns an event" {
every {
eventStore.findAllByFilter(
any<EqFilter<String, String>>()
// EqFilter<String, String>(
// EVENT_ODONTOGRAM_ID_ID.fieldName,
// OdontogramAttributes.VPRID
// )
)
} returns listOf(EventBuilder.buildCreateEvent())
}
"And: eventStore#addEvent just runs" {
every { eventStore.addEvent(any<OdontogramDeleteEvent>()) } just Runs
}
"And: a ${Repository::class.java.simpleName} mock" {
repository = mockk()
}
"And: repository#delete just runs" {
every { repository.delete(any()) } just Runs
}
"And: a ${OdontogramDeleteCommand::class.java.simpleName} generated" {
command = CommandBuilder.buildDeleteCommand()
}
"And: a ${OdontogramCommandHandlerService::class.java.simpleName} successfully instantiated" {
service = OdontogramCommandHandlerService(eventStore, repository)
}
"When: #handle is executed" {
event = service.handle(command) as OdontogramDeleteEvent
}
"Then: ${OdontogramDeleteEvent::class.java.simpleName} matches event´s class" {
assertThat(event::class).hasSameClassAs(OdontogramDeleteEvent::class)
}
"And: the event store is accessed in the right order" {
verifyOrder {
eventStore.findAllByFilter(
any<EqFilter<String, String>>()
)
eventStore.addEvent(any<OdontogramDeleteEvent>())
}
}
"And: the repository is accessed once" {
verify(exactly = 1) {
repository.delete(any())
}
}
}
"Scenario: handling OdontogramDeleteCommand for non registered odontogram" - {
lateinit var command: OdontogramDeleteCommand
lateinit var eventStore: EventStore<OdontogramEvent>
lateinit var repository: Repository<Odontogram>
lateinit var service: OdontogramCommandHandlerService
lateinit var assertion: AbstractThrowableAssert<*, out Throwable>
"Given: a ${EventStore::class.java.simpleName} mock" {
eventStore = mockk()
}
"And: eventStore#findAllByFilter returns empty list" {
every {
eventStore.findAllByFilter(
any<EqFilter<String, String>>()
)
} returns listOf()
}
"And: a ${Repository::class.java.simpleName} mock" {
repository = mockk()
}
"And: a ${OdontogramDeleteCommand::class.java.simpleName} generated from ${OdontogramUpdateRequest::class.java.simpleName}" {
command = CommandBuilder.buildDeleteCommand()
}
"And: a ${OdontogramCommandHandlerService::class.java.simpleName} successfully instantiated" {
service = OdontogramCommandHandlerService(eventStore, repository)
}
"When: #handle is executed" {
assertion = assertThatCode {
service.handle(command)
}
}
"Then: ${AssertionFailedException::class.java.simpleName} is raised with message" {
assertion.hasSameClassAs(
AssertionFailedException(
EXCEPTION_MESSAGE_2,
ODONTOGRAM_NOT_DEFINED.messageTrackerId
)
)
}
"And: the message is $EXCEPTION_MESSAGE_2" {
assertion.hasMessage(EXCEPTION_MESSAGE_2)
}
"And: exception has messageTrackerId ${ODONTOGRAM_NOT_DEFINED.messageTrackerId}" {
assertion.hasFieldOrPropertyWithValue("code", ODONTOGRAM_NOT_DEFINED.messageTrackerId)
}
"And: the eventStore#findAllByFilter is accessed" {
verify(exactly = 1) {
eventStore.findAllByFilter(
any<EqFilter<String, String>>()
// EqFilter<String, String>(
// EVENT_ODONTOGRAM_ID_ID.fieldName,
// OdontogramAttributes.VPRID
// )
)
}
}
"And: the repository#delete is not accessed" {
verify(exactly = 0) {
repository.delete(any())
}
}
"And: the event store#addEvent is not accessed" {
verify(exactly = 0) {
eventStore.addEvent(any<OdontogramCreateEvent>())
}
}
}
}
})
| 0 | Kotlin | 0 | 0 | 8d7aec8840ff9cc87eb17921058d23cfc0d2ca6c | 34,461 | hdc | MIT License |
sample/src/main/java/ru/cleverpumpkin/calendar/sample/MainActivity.kt | CleverPumpkin | 134,849,459 | false | null | package ru.cleverpumpkin.calendar.sample
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentTransaction
import ru.cleverpumpkin.calendar.sample.customstyle.CodeStylingDemoFragment
import ru.cleverpumpkin.calendar.sample.dateboundaries.DateBoundariesDemoFragment
import ru.cleverpumpkin.calendar.sample.demolist.DemoItem
import ru.cleverpumpkin.calendar.sample.demolist.DemoListFragment
import ru.cleverpumpkin.calendar.sample.dialog.DialogDemoFragment
import ru.cleverpumpkin.calendar.sample.events.EventListDemoFragment
import ru.cleverpumpkin.calendar.sample.selection.SelectionModesDemoFragment
class MainActivity : AppCompatActivity(), DemoListFragment.OnDemoItemSelectionListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.add(R.id.fragmentContainer, DemoListFragment())
.commit()
}
}
override fun onDemoItemSelected(demoItem: DemoItem) {
val demoFragment = when (demoItem) {
DemoItem.SELECTION -> SelectionModesDemoFragment()
DemoItem.DATE_BOUNDARIES -> DateBoundariesDemoFragment()
DemoItem.STYLING -> CodeStylingDemoFragment()
DemoItem.EVENTS -> EventListDemoFragment()
DemoItem.DIALOG -> DialogDemoFragment()
}
if (demoFragment is DialogDemoFragment) {
demoFragment.show(supportFragmentManager, null)
} else {
supportFragmentManager.beginTransaction()
.replace(R.id.fragmentContainer, demoFragment)
.addToBackStack(null)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit()
}
}
} | 11 | Kotlin | 44 | 472 | e2b43f7b1b93f2771a39e069147f92814b170467 | 1,912 | CrunchyCalendar | MIT License |
app/src/main/java/com/cobresun/brun/pantsorshorts/MainViewModel.kt | Cobresun | 144,660,254 | false | null | package com.cobresun.brun.pantsorshorts
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.cobresun.brun.pantsorshorts.Clothing.PANTS
import com.cobresun.brun.pantsorshorts.Clothing.SHORTS
import com.cobresun.brun.pantsorshorts.Feeling.COLD
import com.cobresun.brun.pantsorshorts.Feeling.HOT
import com.cobresun.brun.pantsorshorts.preferences.SharedPrefsUserDataRepository
import com.cobresun.brun.pantsorshorts.weather.WeatherRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.*
import javax.inject.Inject
import kotlin.math.max
import kotlin.math.roundToInt
@HiltViewModel
class MainViewModel @Inject constructor(
private val userDataRepository: SharedPrefsUserDataRepository,
private val weatherRepository: WeatherRepository,
) : ViewModel() {
private val _isLoading: MutableLiveData<Boolean> = MutableLiveData()
val isLoading: LiveData<Boolean> = _isLoading
private val _currentTemp: MutableLiveData<Temperature> = MutableLiveData()
val currentTemp: LiveData<Temperature> = _currentTemp
private val _highTemp: MutableLiveData<Temperature> = MutableLiveData()
val highTemp: LiveData<Temperature> = _highTemp
private val _lowTemp: MutableLiveData<Temperature> = MutableLiveData()
val lowTemp: LiveData<Temperature> = _lowTemp
private val _clothingSuggestion: MutableLiveData<Clothing> = MutableLiveData()
val clothingSuggestion: LiveData<Clothing> = _clothingSuggestion
private val _cityName: MutableLiveData<String> = MutableLiveData()
val cityName: LiveData<String> = _cityName
private var hourlyTemps = IntArray(24) // TODO: Must change to account for TemperatureUnit
private fun updateUserThreshold(howTheyFelt: Feeling) {
var currentPreference = userDataRepository.userThreshold
when (howTheyFelt) {
COLD -> {
while (pantsOrShorts(currentPreference) == SHORTS) {
currentPreference += 1
}
}
HOT -> {
while (pantsOrShorts(currentPreference) == PANTS) {
currentPreference -= 1
}
}
}
userDataRepository.userThreshold = currentPreference
}
private fun pantsOrShorts(preference: Int): Clothing {
val hoursSpentOut = 4
val averageHomeTime = 18
val currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
var average = 0
val hoursToInclude = max(hoursSpentOut, averageHomeTime - currentHour)
for (i in 0 until hoursToInclude) {
when {
hourlyTemps[i] >= preference -> average++
else -> average--
}
}
return when {
average >= 0 -> SHORTS
else -> PANTS
}
}
fun calibrateThreshold() {
when (clothingSuggestion.value) {
PANTS -> updateUserThreshold(HOT)
SHORTS -> updateUserThreshold(COLD)
}
updateClothing()
}
private fun updateClothing() {
val clothing = pantsOrShorts(userDataRepository.userThreshold)
_clothingSuggestion.value = clothing
}
fun shouldFetchWeather(): Boolean {
val millisecondsInASecond = 1000
val millisecondsInAMinute = 60 * millisecondsInASecond
val lastFetched = userDataRepository.lastTimeFetchedWeather
val timeSinceFetched = System.currentTimeMillis() - lastFetched
// Rate limiting to fetching only after 10 minutes
return (timeSinceFetched > millisecondsInAMinute * 10)
}
suspend fun fetchWeather(latitude: Double, longitude: Double) {
val forecastResponse = withContext(Dispatchers.IO) {
weatherRepository.getWeather(latitude, longitude)
}
_currentTemp.value = Temperature(forecastResponse.currently.apparentTemperature.roundToInt(), TemperatureUnit.CELSIUS)
_highTemp.value = Temperature(forecastResponse.daily.data[0].apparentTemperatureMax.roundToInt(), TemperatureUnit.CELSIUS)
_lowTemp.value = Temperature(forecastResponse.daily.data[0].apparentTemperatureMin.roundToInt(), TemperatureUnit.CELSIUS)
for (i in hourlyTemps.indices) {
hourlyTemps[i] = forecastResponse.hourly.data[i].apparentTemperature.roundToInt()
}
}
fun writeAndDisplayNewData() {
userDataRepository.lastFetchedTemp = currentTemp.value!!.value
userDataRepository.lastFetchedTempHigh = highTemp.value!!.value
userDataRepository.lastFetchedTempLow = lowTemp.value!!.value
userDataRepository.writeLastFetchedHourlyTemps(hourlyTemps)
userDataRepository.lastTimeFetchedWeather = System.currentTimeMillis()
updateClothing()
_isLoading.value = false
}
fun loadAndDisplayPreviousData() {
_currentTemp.value = Temperature(userDataRepository.lastFetchedTemp, TemperatureUnit.CELSIUS)
_highTemp.value = Temperature(userDataRepository.lastFetchedTempHigh, TemperatureUnit.CELSIUS)
_lowTemp.value = Temperature(userDataRepository.lastFetchedTempLow, TemperatureUnit.CELSIUS)
hourlyTemps = userDataRepository.readLastFetchedHourlyTemps()
updateClothing()
_isLoading.value = false
}
fun setCityName(city: String) {
_cityName.value = city
}
}
| 9 | Kotlin | 0 | 6 | 2d0f44294aff95b7eeeefd20a998462ee9539ac3 | 5,503 | PantsOrShorts | MIT License |
library/src/main/java/com/jiwenjie/basepart/views/BaseDialog.kt | jiwenjie | 179,411,368 | false | null | package com.jiwenjie.basepart.views
import android.app.Dialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import com.jiwenjie.basepart.R
/**
* author:Jiwenjie
* email:<EMAIL>
* time:2018/12/14
* desc:
* version:1.0
*/
abstract class BaseDialog(context: Context, themeId: Int = R.style.AlertDialogStyle):
Dialog(context, themeId) {
protected val mContext = context
private val mInflater = LayoutInflater.from(mContext)
protected val mDialogView: View
private var mProportion: Double = 0.0
init {
mDialogView = mInflater.inflate(this.getLayoutId(), null, false)
this.initDialogView()
this.setContentView(mDialogView)
this.setDialogHeight(WindowManager.LayoutParams.WRAP_CONTENT)
if (mProportion > 0 && mProportion <= 1) this.setDialogWidth((mContext.resources.displayMetrics.widthPixels * mProportion).toInt())
}
fun setProportion(proportion: Double) {
this.mProportion = proportion
}
open fun setDialogHeight(height: Int) {
val lp = window!!.attributes
lp.height = height
window!!.attributes = lp
}
open fun setDialogWidth(width: Int) {
val lp = window!!.attributes
lp.width = width
window!!.attributes = lp
}
abstract fun getLayoutId(): Int
protected open fun initDialogView() {}
}
| 1 | Kotlin | 3 | 9 | a3730f1758f8fe8d13cdd1d53045fa229f7e166d | 1,454 | Graduation_App | Apache License 2.0 |
app/src/main/java/com/mudrichenko/evgeniy/selfstudy/system/model/RequestPermissionData.kt | mudrichenko-evgeny | 556,368,937 | false | {"Kotlin": 281705} | package com.mudrichenko.evgeniy.selfstudy.system.model
class RequestPermissionData(
val permission: String,
val granted: Boolean
) | 0 | Kotlin | 0 | 0 | 9044880a291fcb8539cb01e5c9704b18e7a96572 | 139 | self-study | Apache License 2.0 |
app/src/main/java/com/example/kmvvm/data/network/QuoteApiClient.kt | MJackson22-bit | 473,395,803 | false | {"Kotlin": 10448} | package com.example.kmvvm.data.network
import com.example.kmvvm.data.model.QuoteModel
import retrofit2.Response
import retrofit2.http.GET
interface QuoteApiClient {
@GET("/.json")
suspend fun getAllQuotes(): Response<List<QuoteModel>>
} | 0 | Kotlin | 0 | 0 | ac7fb195ac3f592a4efe36b4d34724719abb0645 | 246 | Architecture-MVVM | MIT License |
src/test/kotlin/com/github/kerubistan/kerub/utils/PercentsKtTest.kt | kerubistan | 19,528,622 | false | null | package com.github.kerubistan.kerub.utils
import org.junit.Assert.assertEquals
import org.junit.Test
class PercentsKtTest {
@Test
fun asPercentOf() {
(0..200).forEach {
assertEquals(" $it ", it, it.asPercentOf(100))
}
assertEquals(10, 1.asPercentOf(10))
assertEquals(20, 2.asPercentOf(10))
assertEquals(10, 25.asPercentOf(250))
assertEquals(20, 2.asPercentOf(10))
}
} | 109 | Kotlin | 4 | 14 | 99cb43c962da46df7a0beb75f2e0c839c6c50bda | 388 | kerub | Apache License 2.0 |
KeepNotesPhone/src/main/java/net/geeksempire/ready/keep/notes/Notes/Revealing/Mediate/PrepareDocument.kt | eliasdfazel | 320,059,275 | false | {"Gradle": 9, "Markdown": 1, "Java Properties": 3, "Shell": 1, "Text": 2, "Ignore List": 10, "Batchfile": 1, "JSON": 17, "Proguard": 6, "Kotlin": 131, "XML": 159, "Java": 71, "INI": 4, "Cloud Firestore Security Rules": 1, "HTML": 2, "JavaScript": 1} | /*
* Copyright © 2021 By Geeks Empire.
*
* Created by <NAME>
* Last modified 4/12/21 8:50 AM
*
* Licensed Under MIT License.
* https://opensource.org/licenses/MIT
*/
package net.geeksempire.ready.keep.notes.Notes.Revealing.Mediate
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.geeksempire.ready.keep.notes.Database.DataStructure.NotesTemporaryModification
import net.geeksempire.ready.keep.notes.KeepNoteApplication
import net.geeksempire.ready.keep.notes.Notes.Taking.TakeNote
import net.geeksempire.ready.keep.notes.ReminderConfigurations.DataStructure.Reminder
class PrepareDocument : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent.hasExtra(Reminder.ReminderDocumentId)) {
val documentId = intent.getStringExtra(Reminder.ReminderDocumentId)!!
CoroutineScope(Dispatchers.IO).launch {
val notesDatabaseDataAccessObject = (application as KeepNoteApplication).notesRoomDatabaseConfiguration.prepareRead()
val specificDocument = notesDatabaseDataAccessObject.getSpecificNoteData(documentId.toLong())
specificDocument?.let {
val paintingPathsJsonArray = specificDocument.noteHandwritingPaintingPaths
if (paintingPathsJsonArray.isNullOrEmpty()) {
TakeNote.open(context = applicationContext,
incomingActivityName = [email protected],
extraConfigurations = TakeNote.NoteConfigurations.KeyboardTyping,
uniqueNoteId = documentId.toLong(),
noteTile = specificDocument.noteTile,
contentText = specificDocument.noteTextContent,
encryptedTextContent = true,
updateExistingNote = true,
pinnedNote = when (specificDocument.notePinned) {
NotesTemporaryModification.NoteUnpinned -> {
false
}
NotesTemporaryModification.NotePinned -> {
true
} else -> {
false
}
}
)
} else {
TakeNote.open(context = applicationContext,
incomingActivityName = [email protected],
extraConfigurations = TakeNote.NoteConfigurations.KeyboardTyping,
uniqueNoteId = documentId.toLong(),
noteTile = specificDocument.noteTile,
contentText = specificDocument.noteTextContent,
paintingPath = paintingPathsJsonArray,
encryptedTextContent = true,
updateExistingNote = true,
pinnedNote = when (specificDocument.notePinned) {
NotesTemporaryModification.NoteUnpinned -> {
false
}
NotesTemporaryModification.NotePinned -> {
true
} else -> {
false
}
}
)
}
}
[email protected]()
}
} else {
[email protected]()
}
}
} | 0 | Kotlin | 0 | 2 | 0294e1d30a24b7703c803223451dce1d4bff9fbd | 4,009 | ReadyKeepNotes | MIT License |
app/src/main/java/com/jetpackcomposedemo/model/data/GithubUsersApi.kt | mohdaquib | 468,718,226 | false | null | package com.jetpackcomposedemo.model.data
import com.jetpackcomposedemo.model.response.GithubUserResponse
import okhttp3.ResponseBody
import retrofit2.http.GET
import retrofit2.http.Query
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class GithubUsersApi @Inject constructor(private val service: Service){
suspend fun getGithubUsers(since: Int): ResponseBody = service.getGithubUsers(since)
interface Service {
@GET("users")
suspend fun getGithubUsers(@Query("since") since: Int): ResponseBody
}
companion object {
const val API_URL = "https://api.github.com/"
}
} | 0 | Kotlin | 0 | 0 | af02c587e54c5fef9fe85398cb2b766543c9a794 | 634 | JetpackComposeDemo | Apache License 2.0 |
src/main/kotlin/com/jetbrains/handson/httpapi/routes/HealthRoutes.kt | rsantaeulalia | 270,488,662 | false | null | package com.jetbrains.handson.httpapi.routes
import io.ktor.application.Application
import io.ktor.application.call
import io.ktor.response.respondText
import io.ktor.routing.Route
import io.ktor.routing.get
import io.ktor.routing.routing
fun Application.registerHealthRoutes() {
routing {
healtCheckRoute()
}
}
fun Route.healtCheckRoute() {
get("/health") {
call.respondText("I'm a healthy server")
}
} | 0 | Kotlin | 0 | 0 | 680d2f22136daf6db1c3f1e8513021393859f788 | 438 | ktor-api-example | Apache License 2.0 |
src/main/kotlin/net/spyman/backpackmod/init/ModItemGroups.kt | SpyMan10 | 731,115,715 | false | {"Kotlin": 23406, "Java": 522} | package net.spyman.backpackmod.init
import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup
import net.minecraft.item.ItemStack
import net.minecraft.item.Items
import net.minecraft.registry.Registries
import net.minecraft.registry.Registry
import net.minecraft.text.Text
import net.spyman.backpackmod.BackpackMod
object ModItemGroups {
val mainGroup = FabricItemGroup.builder()
.displayName(Text.translatable("itemGroup.backpackmod.main_item_group"))
.entries { _, entries ->
Registries.ITEM.ids
.filter { it.namespace == BackpackMod.modid }
.forEach { entries.add(Registries.ITEM[it]) }
}
.icon { ItemStack(Items.APPLE) }
.build()
fun init() {
Registry.register(
Registries.ITEM_GROUP,
BackpackMod.identify("main_item_group"),
mainGroup
)
}
} | 0 | Kotlin | 0 | 0 | 5afbf39763d93feb5607cc85edd349c66a83124a | 825 | backpackmod | MIT License |
app/src/main/java/com/mohammadfayaz/hn/domain/usecases/stories/top/GetTopStoryIdsUseCase.kt | fayaz07 | 431,064,021 | false | {"Kotlin": 109519} | package com.mohammadfayaz.hn.domain.usecases.stories.top
import com.mohammadfayaz.hn.data.repository.IdsRepo
import com.mohammadfayaz.hn.domain.models.ApiResult
import com.mohammadfayaz.hn.domain.models.StoryType
import com.mohammadfayaz.hn.domain.usecases.BaseUseCase
import javax.inject.Inject
class GetTopStoryIdsUseCase @Inject constructor(private val idsRepo: IdsRepo) : BaseUseCase() {
suspend fun invoke(): ApiResult<List<Int>> {
return idsRepo.fetchStoryIds(StoryType.TOP)
}
}
| 13 | Kotlin | 2 | 4 | 498917164eeea6b7808ff30b8f772cf557e1c4e6 | 495 | HackerNews | MIT License |
src/main/kotlin/com/github/shatteredsuite/scrolls/extensions/LocationExt.kt | ShatteredSoftware | 263,253,802 | false | {"Gradle": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 2, "Java": 13, "JSON": 1, "Kotlin": 73, "YAML": 4} | package com.github.shatteredsuite.scrolls.extensions
import com.github.shatteredsuite.core.commands.ArgParser
import com.github.shatteredsuite.scrolls.data.scroll.binding.BindingData
import com.github.shatteredsuite.scrolls.data.scroll.binding.LocationBindingData
import org.bukkit.Location
import org.bukkit.Material
import org.bukkit.block.BlockFace
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import java.util.*
fun Location.getNearestSafe(maxCount: Int = 100): Location? {
if (this.isSafe()) {
return this
}
var count = 0
val toVisit = LinkedList<Location>()
while (toVisit.size > 0) {
val next = toVisit.poll()
for (bf in BlockFace.values()) {
val loc = next.block.getRelative(bf).location
if (loc.isSafe()) {
return loc
}
toVisit.add(loc)
count++
}
if (count >= maxCount) {
return null
}
}
return null
}
fun locationFromCommandArgs(args: Array<out String>, sender: CommandSender): Location {
return if(sender is Player && args.isEmpty()) {
sender.location
}
else if(sender is Player && args.size == 3) {
ArgParser.validShortLocation(args, 0, sender)
}
else ArgParser.validLocation(args, 0)
}
fun Location.isSafe(): Boolean {
val block = this.block
if (!block.isEmpty || !block.getRelative(BlockFace.UP).isEmpty) {
return false
}
if (this.isDamaging()) {
return false
}
if (this.isAboveAir()) {
return false
}
return true
}
fun Location.isDamaging(): Boolean {
val mat = this.world!!.getBlockAt(this).type
return mat == Material.FIRE || mat == Material.LAVA || mat == Material.CAMPFIRE
}
fun Location.isAboveAir(): Boolean {
return this.blockY > this.world!!.maxHeight || this.world!!.getBlockAt(this.add(0.0, -1.0, 0.0)).isEmpty
} | 1 | null | 1 | 1 | b4d65a8d18a3842032f302a871e7a64f7dfe1d88 | 1,938 | ShatteredScrolls2 | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/pecs/jpc/spreadsheet/LongHaulMovesSheet.kt | uk-gov-mirror | 356,783,334 | true | {"Kotlin": 428549, "HTML": 83335, "CSS": 12598, "Shell": 6092, "Mustache": 4485, "Dockerfile": 945} | package uk.gov.justice.digital.hmpps.pecs.jpc.spreadsheet
import org.apache.poi.ss.usermodel.Workbook
import uk.gov.justice.digital.hmpps.pecs.jpc.move.Move
class LongHaulMovesSheet(workbook: Workbook, header: Header) : PriceSheet(workbook.getSheet("Long haul")!!, header) {
override fun writeMove(move: Move) {
writeMoveRow(move)
writeJourneyRows(move.journeys)
}
}
| 0 | Kotlin | 0 | 0 | 448660ac4b18cc4c8cf3c137a902ed7a99a9fff4 | 382 | ministryofjustice.calculate-journey-variable-payments | MIT License |
idea/idea-completion/testData/basic/common/ExtensionWithInternalGenericParameters.kt | JakeWharton | 99,388,807 | false | null | // FIR_COMPARISON
import java.util.HashSet
open class Base
fun <T: Base> Set<List<T>>.extensionInternal() = 12
fun some() {
HashSet<List<Base>>().ex<caret>
}
// EXIST: extensionInternal | 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 193 | kotlin | Apache License 2.0 |
androidApp/src/main/java/app/suprsend/android/preference/UserPreferenceActivity.kt | suprsend | 440,860,884 | false | {"Kotlin": 280346} | package app.suprsend.android.preference
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import app.suprsend.SSApi
import app.suprsend.android.BuildConfig
import app.suprsend.android.databinding.UserPreferenceActivityBinding
import app.suprsend.android.isLast
import app.suprsend.android.logInfo
import app.suprsend.android.myToast
import app.suprsend.exception.NoInternetException
import app.suprsend.user.preference.ChannelPreferenceOptions
import app.suprsend.user.preference.PreferenceCallback
import app.suprsend.user.preference.PreferenceData
import app.suprsend.user.preference.PreferenceOptions
import app.suprsend.user.preference.Preferences
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class UserPreferenceActivity : AppCompatActivity() {
lateinit var binding: UserPreferenceActivityBinding
lateinit var adapter: UserPreferenceRecyclerViewAdapter
lateinit var preferences: Preferences
private val coroutineScope = CoroutineScope(Dispatchers.IO)
private val expandedIds = hashMapOf<String, Boolean>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
title = "Preferences"
binding = UserPreferenceActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.categoriesRV.layoutManager = LinearLayoutManager(this@UserPreferenceActivity)
adapter = UserPreferenceRecyclerViewAdapter(categoryItemClick = { category, checked ->
coroutineScope.launch {
val response = SSApi.getInstance().getUser().getPreferences().updateCategoryPreference(
category = category,
preference = PreferenceOptions.from(checked),
tenantId = BuildConfig.SS_TENANT_ID
)
if (response.getException() is NoInternetException) {
withContext(Dispatchers.Main) {
myToast("Please check internet connection")
}
}
}
}, channelItemClick = { category, channel, checked ->
coroutineScope.launch {
val response = SSApi.getInstance().getUser().getPreferences().updateChannelPreferenceInCategory(
category = category,
channel = channel,
preference = PreferenceOptions.from(checked),
tenantId = BuildConfig.SS_TENANT_ID
)
if (response.getException() is NoInternetException) {
withContext(Dispatchers.Main) {
myToast("Please check internet connection")
}
}
}
},
channelPreferenceArrowClick = { category, expanded ->
expandedIds[category] = expanded
},
channelPreferenceChangeClick = { channel: String, channelPreferenceOptions: ChannelPreferenceOptions ->
logInfo("Updated channelPreferenceOptions channel:$channel channelPreferenceOptions: $channelPreferenceOptions ")
coroutineScope.launch {
val response = SSApi.getInstance().getUser().getPreferences().updateOverallChannelPreference(
channel = channel,
channelPreferenceOptions = channelPreferenceOptions
)
if (response.getException() is NoInternetException) {
withContext(Dispatchers.Main) {
myToast("Please check internet connection")
}
}
}
})
binding.categoriesRV.adapter = adapter
preferences = SSApi.getInstance().getUser().getPreferences()
coroutineScope.launch {
val data = preferences.fetchUserPreference(
tenantId = BuildConfig.SS_TENANT_ID
).getData() ?: return@launch
showData(data)
}
}
override fun onResume() {
super.onResume()
preferences.registerCallback(object : PreferenceCallback {
override fun onUpdate() {
coroutineScope.launch {
val data = preferences.fetchUserPreference(
fetchRemote = false,
tenantId = BuildConfig.SS_TENANT_ID
).getData() ?: return@launch
showData(data)
}
}
})
}
override fun onPause() {
super.onPause()
preferences.unRegisterCallback()
}
override fun onDestroy() {
super.onDestroy()
coroutineScope.cancel()
}
private suspend fun showData(preferenceData: PreferenceData) {
withContext(Dispatchers.Main) {
adapter.setItems(preferenceData.toUIItems())
}
}
private fun PreferenceData?.toUIItems(): List<RecyclerViewItem> {
if (this == null) return listOf()
val itemsList = arrayListOf<RecyclerViewItem>()
sections.forEachIndexed { sIndex, section ->
if (section.name.isNotBlank())
itemsList.add(RecyclerViewItem.SectionVo(idd = section.name, title = section.name, description = section.description))
section.subCategories.forEachIndexed { scIndex, subCategory ->
itemsList.add(RecyclerViewItem.SubCategoryVo(subCategory, section.subCategories.isLast(scIndex)))
}
}
itemsList.add(
RecyclerViewItem.SectionVo(
"Over all section divider",
"What notifications to allow for channel?"
)
)
channelPreferences.forEach { channelPreference ->
val isExpanded = expandedIds[channelPreference.channel] ?: false
itemsList.add(RecyclerViewItem.ChannelPreferenceVo(channelPreference, isExpanded))
}
return itemsList
}
}
| 4 | Kotlin | 1 | 6 | 6d31470ec366fa1efe1595e32dfeb86159d2c717 | 6,187 | suprsend-android-sdk | MIT License |
app/src/main/kotlin/info/dvkr/screenstream/service/ServiceMessage.kt | Angelika123456 | 213,605,060 | false | null | package info.dvkr.screenstream.service
import android.os.Bundle
import android.os.Messenger
import android.os.Parcelable
import info.dvkr.screenstream.data.model.AppError
import info.dvkr.screenstream.data.model.HttpClient
import info.dvkr.screenstream.data.model.NetInterface
import info.dvkr.screenstream.data.model.TrafficPoint
import kotlinx.android.parcel.Parcelize
sealed class ServiceMessage : Parcelable {
internal companion object {
private const val MESSAGE_PARCELABLE = "MESSAGE_PARCELABLE"
fun fromBundle(bundle: Bundle?): ServiceMessage? = bundle?.run {
classLoader = ServiceMessage::class.java.classLoader
getParcelable(MESSAGE_PARCELABLE)
}
}
@Parcelize data class RegisterActivity(val relyTo: Messenger) : ServiceMessage()
@Parcelize data class UnRegisterActivity(val relyTo: Messenger) : ServiceMessage()
@Parcelize object FinishActivity : ServiceMessage()
@Parcelize data class ServiceState(
val isStreaming: Boolean,
val isBusy: Boolean,
val isWaitingForPermission: Boolean,
val netInterfaces: List<NetInterface>,
val appError: AppError?
) : ServiceMessage()
@Parcelize data class Clients(val clients: List<HttpClient>) : ServiceMessage()
@Parcelize data class TrafficHistory(val trafficHistory: List<TrafficPoint>) : ServiceMessage() {
override fun toString(): String = this::class.java.simpleName
}
fun toBundle(): Bundle = Bundle().apply { putParcelable(MESSAGE_PARCELABLE, this@ServiceMessage) }
override fun toString(): String = this::class.java.simpleName
} | 0 | null | 0 | 2 | c72f566cb78bf10b8781b1bc732ab4524ee1376e | 1,634 | ScreenStream | MIT License |
app/src/main/kotlin/info/dvkr/screenstream/service/ServiceMessage.kt | Angelika123456 | 213,605,060 | false | null | package info.dvkr.screenstream.service
import android.os.Bundle
import android.os.Messenger
import android.os.Parcelable
import info.dvkr.screenstream.data.model.AppError
import info.dvkr.screenstream.data.model.HttpClient
import info.dvkr.screenstream.data.model.NetInterface
import info.dvkr.screenstream.data.model.TrafficPoint
import kotlinx.android.parcel.Parcelize
sealed class ServiceMessage : Parcelable {
internal companion object {
private const val MESSAGE_PARCELABLE = "MESSAGE_PARCELABLE"
fun fromBundle(bundle: Bundle?): ServiceMessage? = bundle?.run {
classLoader = ServiceMessage::class.java.classLoader
getParcelable(MESSAGE_PARCELABLE)
}
}
@Parcelize data class RegisterActivity(val relyTo: Messenger) : ServiceMessage()
@Parcelize data class UnRegisterActivity(val relyTo: Messenger) : ServiceMessage()
@Parcelize object FinishActivity : ServiceMessage()
@Parcelize data class ServiceState(
val isStreaming: Boolean,
val isBusy: Boolean,
val isWaitingForPermission: Boolean,
val netInterfaces: List<NetInterface>,
val appError: AppError?
) : ServiceMessage()
@Parcelize data class Clients(val clients: List<HttpClient>) : ServiceMessage()
@Parcelize data class TrafficHistory(val trafficHistory: List<TrafficPoint>) : ServiceMessage() {
override fun toString(): String = this::class.java.simpleName
}
fun toBundle(): Bundle = Bundle().apply { putParcelable(MESSAGE_PARCELABLE, this@ServiceMessage) }
override fun toString(): String = this::class.java.simpleName
} | 0 | null | 0 | 2 | c72f566cb78bf10b8781b1bc732ab4524ee1376e | 1,634 | ScreenStream | MIT License |
app/src/main/java/com/grupo2/elorchat/data/repository/CommonGroupRepository.kt | AgerAlPe | 741,038,643 | false | {"Kotlin": 163323} | package com.grupo2.elorchat.data.repository
import com.grupo2.elorchat.data.ChangePasswordRequest
import com.grupo2.elorchat.data.ChatUser
import com.grupo2.elorchat.data.ChatUserEmailRequest
import com.grupo2.elorchat.data.ChatUserMovementResponse
import com.grupo2.elorchat.data.Group
import com.grupo2.elorchat.data.Message
import com.grupo2.elorchat.utils.Resource
interface CommonGroupRepository {
suspend fun getGroups() : Resource<List<Group>>
suspend fun createGroup(group: Group) : Resource<Int>
suspend fun getMessagesFromGroup(groupId : Int) : Resource<List<Message>>
suspend fun joinChat (chatUser: ChatUser) : Resource<ChatUser>
suspend fun leaveChat (userId : Int , chatId : Int) : Resource<Void>
suspend fun getUserGroups(userId : Int) : Resource<List<Group>>
suspend fun changePassword(changePasswordRequest: ChangePasswordRequest) : Resource<Void>
suspend fun getChatsWhereUserIsAdmin(userId: Int) : Resource<List<Group>>
suspend fun makeAnUserJoinAChat(chatUserEmailRequest: ChatUserEmailRequest) : Resource<ChatUserMovementResponse>
suspend fun makeAnUserLeaveAChat(chatUserEmailRequest: ChatUserEmailRequest) : Resource<ChatUserMovementResponse>
suspend fun deleteGroup(chatId: Int) : Resource<Void>
} | 0 | Kotlin | 0 | 0 | 04453137a7e9021fca0103aef81709533020a03e | 1,279 | Reto2_DAM2_PMDM | MIT License |
feature/monster-content-manager/state-holder/src/commonMain/kotlin/br/alexandregpereira/hunter/monster/content/preview/MonsterContentPreviewAnalytics.kt | alexandregpereira | 347,857,709 | false | {"Kotlin": 1443810, "Swift": 754, "Shell": 139} | package br.alexandregpereira.hunter.monster.content.preview
import br.alexandregpereira.hunter.analytics.Analytics
import br.alexandregpereira.hunter.monster.compendium.domain.model.MonsterCompendiumItem
import br.alexandregpereira.hunter.monster.compendium.domain.model.TableContentItem
internal class MonsterContentPreviewAnalytics(
private val analytics: Analytics
) {
fun trackLoaded(sourceAcronym: String, items: List<MonsterCompendiumItem>) {
analytics.track(
eventName = "MonsterContentPreview - loaded",
params = mapOf(
"itemsSize" to items.size,
"sourceAcronym" to sourceAcronym,
)
)
}
fun logException(throwable: Throwable, sourceAcronym: String) {
analytics.track(
eventName = "MonsterContentPreview - error loaded",
params = mapOf(
"sourceAcronym" to sourceAcronym,
)
)
analytics.logException(throwable)
}
fun trackClose(sourceAcronym: String) {
analytics.track(
eventName = "MonsterContentPreview - close",
params = mapOf(
"sourceAcronym" to sourceAcronym,
)
)
}
fun trackTableContentOpened() {
analytics.track(eventName = "MonsterContentPreview - popup opened")
}
fun trackTableContentIndexClicked(position: Int, tableContent: List<TableContentItem>) {
analytics.track(
eventName = "MonsterContentPreview - table content index clicked",
params = mapOf(
"position" to position,
"tableContent" to tableContent.getOrNull(position)?.text.orEmpty(),
)
)
}
fun trackTableContentClosed() {
analytics.track(
eventName = "MonsterContentPreview - table content closed",
)
}
} | 3 | Kotlin | 5 | 85 | 46a636ec6fe5a60101e761847c85776180c6f5b2 | 1,887 | Monster-Compendium | Apache License 2.0 |
app/src/main/java/com/app/myarticleapp/apiSource/converter/SubMediaArticleConverter.kt | sunday58 | 531,985,278 | false | {"Kotlin": 44667} | package com.app.myarticleapp.apiSource.converter
import androidx.room.TypeConverter
import com.app.myarticleapp.apiSource.responseEntity.MediaMetadata
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type
class SubMediaArticleConverter {
@TypeConverter
fun fromString(value: String?): List<MediaMetadata>? {
val listType: Type = object : TypeToken<List<MediaMetadata?>?>() {}.type
return Gson().fromJson<List<MediaMetadata>>(value, listType)
}
@TypeConverter
fun listToString(list: List<MediaMetadata?>?): String? {
val gson = Gson()
return gson.toJson(list)
}
} | 0 | Kotlin | 0 | 0 | 6fd20d7dfed82dcfed6cd90bbe0a1b4b9c669cfc | 666 | MyArticleApp | Apache License 2.0 |
app/src/main/java/com/elhady/movies/ui/home/homeUiState/HomeUiEvent.kt | islamelhady | 301,591,032 | false | {"Kotlin": 400229} | package com.elhady.movies.ui.home.homeUiState
import com.elhady.movies.domain.enums.AllMediaType
import com.elhady.movies.domain.enums.SeeAllType
sealed interface HomeUiEvent {
data class ClickMovieEvent(val movieID: Int) : HomeUiEvent
data class ClickSeeAllMoviesEvent(val mediaType: SeeAllType) : HomeUiEvent
object ClickSeeAllActorsEvent : HomeUiEvent
data class ClickActorEvent(val actorID: Int): HomeUiEvent
data class ClickSeeAllSeriesEvent(val mediaType: SeeAllType): HomeUiEvent
data class ClickSeriesEvent(val mediaID: Int): HomeUiEvent
} | 1 | Kotlin | 0 | 0 | 58ea34448572405d6ea12eeb0708cfeecfa42f93 | 573 | movie-night-v2 | Apache License 2.0 |
app/src/main/java/com/gmail/cities/domain/common/ResultState.kt | shtukar | 280,606,502 | false | null | package com.gmail.cities.domain.common
import com.gmail.cities.domain.entity.ErrorState
sealed class ResultState<T> {
/**
* A state of [data] which shows that we know there is still an update to come.
*/
data class Loading<T>(val data: T) : ResultState<T>()
/**
* A state that shows the [data] is the last known update.
*/
data class Success<T>(val data: T) : ResultState<T>()
/**
* A state to show a [error] is thrown.
*/
data class Error<T>(val error: ErrorState, val data: T?) : ResultState<T>()
}
| 0 | Kotlin | 0 | 0 | dcd976bba281e87f07af4934e7cc6425252e023d | 560 | Cities-list | Apache License 2.0 |
database-sqlite-jdbc/src/commonMain/kotlin/com/github/mejiomah17/yasb/sqlite/jdbc/parameter/LongParameter.kt | MEJIOMAH17 | 492,593,605 | false | {"Kotlin": 307256} | package com.github.mejiomah17.yasb.sqlite.jdbc.parameter
import com.github.mejiomah17.yasb.core.jdbc.JDBCDatabaseType
import com.github.mejiomah17.yasb.sqlite.jdbc.type.LongDatabaseType
import java.sql.PreparedStatement
class LongParameter(
override val value: Long?
) : SqliteParameter<Long>() {
override val databaseType: JDBCDatabaseType<Long> = LongDatabaseType
override fun applyToStatement(
statement: PreparedStatement,
index: Int
) {
statement.setObject(index, value)
}
}
| 0 | Kotlin | 0 | 8 | 82116cd3674fedd789dd10463be5f22a9b4024c5 | 527 | yasb | MIT License |
android-app/src/main/kotlin/com/addhen/fosdem/android/app/App.kt | eyedol | 170,208,282 | false | {"Kotlin": 553132, "Shell": 3075, "Swift": 1713} | // Copyright 2023, Addhen Limited and the FOSDEM Event app project contributors
// SPDX-License-Identifier: Apache-2.0
package com.addhen.fosdem.android.app
import android.app.Application
import android.os.Build
import android.os.StrictMode
import com.addhen.fosdem.android.app.di.AppComponent
import com.addhen.fosdem.android.app.di.create
class App : Application() {
val component: AppComponent by lazy {
AppComponent.create(this)
}
override fun onCreate() {
super.onCreate()
setupStrictMode()
}
private fun setupStrictMode() {
StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build(),
)
StrictMode.setVmPolicy(
StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectActivityLeaks()
.detectLeakedClosableObjects()
.detectLeakedRegistrationObjects()
.detectFileUriExposure()
.detectCleartextNetwork()
.apply {
if (Build.VERSION.SDK_INT >= 26) {
detectContentUriWithoutPermission()
}
if (Build.VERSION.SDK_INT >= 29) {
detectCredentialProtectedWhileLocked()
}
if (Build.VERSION.SDK_INT >= 31) {
detectIncorrectContextUse()
detectUnsafeIntentLaunch()
}
}
.penaltyLog()
.build(),
)
}
}
| 5 | Kotlin | 0 | 1 | 753c02296d95191a0b7ace595c01f1952111236d | 1,406 | fosdem-event-app | Apache License 2.0 |
app/src/main/java/com/example/kinetic/presentation/main/MainScreen.kt | BENJAHJP | 593,154,677 | false | null | package com.example.kinetic.presentation.main
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Home
import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.NavigationRail
import androidx.compose.material3.NavigationRailItem
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.example.kinetic.presentation.navigation.MainNavGraph
import com.example.kinetic.presentation.screen.Screens
@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun MainScreen(
navController: NavHostController,
onDarkOn: () -> Unit,
onLightOn: () -> Unit,
onFollowSystem: () -> Unit,
onDynamicColorOn: () -> Unit
) {
Scaffold(
bottomBar = {
BottomNavigationBar(
modifier = Modifier.navigationBarsPadding(),
items = listOf(
BottomNavItem(
name = "Home",
route = Screens.HomeScreen.route,
icon = Icons.Rounded.Home
),
BottomNavItem(
name = "Search",
route = Screens.SearchScreen.route,
icon = Icons.Rounded.Search
),
BottomNavItem(
name = "Settings",
route = Screens.SettingsScreen.route,
icon = Icons.Rounded.Settings
)
),
navController = navController,
onItemClick = { navController.navigate(it.route){
popUpTo(navController.graph.findStartDestination().id)
launchSingleTop = true
} })
}
) {
MainNavGraph(
navHostController = navController,
onDarkOn = onDarkOn,
onLightOn = onLightOn,
onFollowSystem = onFollowSystem,
onDynamicColorOn = onDynamicColorOn
)
}
} | 0 | Kotlin | 0 | 1 | 7131bbba3b7a98ba5676622eec80e0761fdde17c | 2,657 | Inverse | MIT License |
src/main/kotlin/server/Server.kt | rafted | 505,495,265 | false | null | package server
import chat.ChatComponent
import chat.color.ChatColor
import event.EventBus
import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.Channel
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.logging.LogLevel
import io.netty.handler.logging.LoggingHandler
import kotlinx.serialization.Serializable
import kotlinx.serialization.StringFormat
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import logic.listeners.ConnectionListener
import logic.listeners.HandshakeListener
import logic.listeners.LoginListener
import logic.listeners.PingListener
import org.tinylog.kotlin.Logger
import protocol.packet.impl.status.clientbound.Players
import protocol.packet.impl.status.clientbound.Response
import protocol.packet.impl.status.clientbound.Version
import server.connection.Connection
import server.connection.ConnectionClosedEvent
import java.io.File
@Serializable
data class ServerConfig(
val host: String = "0.0.0.0",
val port: Int = 25565,
var description: ChatComponent = ChatComponent()
.text("Krafted - Server")
.color(ChatColor.CYAN),
var maxPlayers: Int = 20,
var favicon: String = ""
)
object Server {
lateinit var config: ServerConfig
lateinit var format: StringFormat
val connections = mutableListOf<Connection>()
val eventBus: EventBus = EventBus
fun start(format: StringFormat) {
this.format = format
this.config = loadServerConfig()
this.registerListeners()
val bossGroup = NioEventLoopGroup(1)
val workerGroup = NioEventLoopGroup()
try {
val bootstrap = ServerBootstrap().apply {
this.group(bossGroup, workerGroup)
this.channel(NioServerSocketChannel::class.java)
this.handler(LoggingHandler(LogLevel.DEBUG))
this.childHandler(ServerInitializer)
}
val channel = bootstrap.bind(this.config.host, this.config.port)
.sync()
.channel()
channel.closeFuture().sync()
} finally {
bossGroup.shutdownGracefully()
workerGroup.shutdownGracefully()
}
}
private fun registerListeners() {
EventBus.subscribe(HandshakeListener)
EventBus.subscribe(ConnectionListener)
EventBus.subscribe(PingListener)
EventBus.subscribe(LoginListener)
}
fun findConnection(channel: Channel): Connection? {
return this.connections.find { it.channel == channel }
}
fun closeConnection(connection: Connection) {
Logger.info("Removing Connection: ${connection.id}")
this.connections.remove(connection)
this.eventBus.post(ConnectionClosedEvent(connection))
}
private fun createServerConfig(file: File) {
file.createNewFile()
file.writeText(
format.encodeToString(ServerConfig())
)
}
private fun loadServerConfig(): ServerConfig {
val file = File(
"server.${
format.javaClass
.simpleName
.lowercase()
.replace("impl", "")
}"
)
if (!file.exists()) {
createServerConfig(file)
}
val contents = file.readText()
return format.decodeFromString(contents)
}
fun makeStatusRespose(): Response {
return Response(
version = Version(
protocol = 47,
name = "1.8.9"
),
players = Players(config.maxPlayers, 0, emptyList()),
description = config.description,
favicon = config.favicon
)
}
}
| 0 | Kotlin | 1 | 5 | 7f20c8b585d1d63993cda5fb25195ec699a159c1 | 3,801 | krafted | MIT License |
app/src/main/java/com/example/dotoring_neoul/dto/CommonErrorResponse.kt | Team-Neoul | 678,390,604 | false | {"Kotlin": 315932} | package com.example.dotoring_neoul.dto
// 공통 에러 응답
data class CommonErrorResponse(
val message: String,
val code: Int,
val status: Int
)
| 5 | Kotlin | 3 | 0 | a5e380e2ccec0766ae0e04b62e868fcafb82e7e0 | 150 | Neoul_Dotoring-AOS | MIT License |
app/src/main/java/al10101/android/decimalai/programs/DebugShaderProgram.kt | al10101 | 557,614,847 | false | null | package al10101.android.decimalai.programs
import al10101.android.decimalai.*
import android.content.Context
import android.opengl.GLES20.*
class DebugShaderProgram(
context: Context
): ShaderProgram(
context,
R.raw.debug_vertex_shader,
R.raw.debug_fragment_shader
) {
private val uTextureUnitLocation by lazy {
glGetUniformLocation(program, U_TEXTURE_UNIT)
}
val aPositionLocation by lazy {
glGetAttribLocation(program, A_POSITION)
}
val aTextureCoordinatesLocation by lazy {
glGetAttribLocation(program, A_TEXTURE_COORDINATES)
}
fun setUniforms(textureId: Int) {
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, textureId)
glUniform1i(uTextureUnitLocation, 0)
}
} | 0 | Kotlin | 0 | 0 | 29ea993fc44c647c4fc9fa1f4f85dbeaed3d9b54 | 777 | DecimalAI | MIT License |
core/src/jvmTest/kotlin/com/huanshankeji/codec/BasicCodecsTest.kt | huanshankeji | 407,303,262 | false | null | package com.huanshankeji.codec
import io.kotest.property.Arb
import io.kotest.property.Exhaustive
import io.kotest.property.arbitrary.byteArray
import io.kotest.property.arbitrary.default
import io.kotest.property.arbitrary.list
import io.kotest.property.checkAll
import io.kotest.property.exhaustive.of
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestResult
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
class BasicCodecsTest {
@OptIn(ExperimentalUnsignedTypes::class, ExperimentalCoroutinesApi::class)
@Test
fun testConversionBetweenLongAndBigEndianBytes(): TestResult {
val long = 0x0123456789ABCDEFU.toLong()
val bytes = ubyteArrayOf(0x01U, 0x23U, 0x45U, 0x67U, 0x89U, 0xABU, 0xCDU, 0xEFU).asByteArray()
assertContentEquals(bytes, long.toBigEndianBytes())
assertEquals(long, bytes.bigEndianToLong())
@OptIn(ExperimentalCoroutinesApi::class)
return runTest {
checkAll<Long> {
assertEquals(it, it.toBigEndianBytes().bigEndianToLong())
assertEquals(it, it.toBigEndianBytes().asList().bigEndianToLong())
}
checkAll<ByteArray>(Arb.byteArray(Exhaustive.of(8), Arb.default())) {
assertContentEquals(it, it.bigEndianToLong().toBigEndianBytes())
}
checkAll<List<Byte>>(Arb.list(Arb.default(), 8..8)) {
assertEquals(it, it.bigEndianToLong().toBigEndianBytes().asList())
}
}
}
} | 4 | Kotlin | 0 | 5 | 85d264d037c9d0af28d56a6353d31c2784aacf3c | 1,609 | kotlin-common | Apache License 2.0 |
app/src/main/java/io/eugenethedev/taigamobile/ui/screens/main/MainViewModel.kt | TrendingTechnology | 366,557,432 | true | {"Kotlin": 317219} | package io.eugenethedev.taigamobile.ui.screens.main
import androidx.lifecycle.*
import io.eugenethedev.taigamobile.Session
import io.eugenethedev.taigamobile.Settings
import io.eugenethedev.taigamobile.TaigaApp
import io.eugenethedev.taigamobile.ThemeSetting
import javax.inject.Inject
class MainViewModel : ViewModel() {
@Inject lateinit var session: Session
@Inject lateinit var settings: Settings
val isLogged get() = session.isLogged
val isProjectSelected get() = session.isProjectSelected
val theme = MutableLiveData<ThemeSetting>()
init {
TaigaApp.appComponent.inject(this)
theme.value = settings.themeSetting
settings.themeSettingCallback = { theme.value = it }
}
} | 0 | null | 0 | 0 | 06d6d2856072c0c97fb43a310caa4095d375e61f | 730 | TaigaMobile | Apache License 2.0 |
accelerators/corda/service-bus-integration/commons/src/main/kotlin/net/corda/workbench/commons/event/FileEventRepo.kt | Azure-Samples | 175,045,447 | false | null | package net.corda.workbench.commons.event
import org.json.JSONObject
import java.io.File
import java.util.ArrayList
import java.util.Collections
/**
* A simple file based event store with an in memory cache. Good for
* simple use cases with not too many events
*/
class FileEventStore : EventStore {
private var directory: String? = null
private val events = ArrayList<Event>()
/**
* Used to load a set of events from JSON files stored on disk. Any new events
* will also ve written to this directory
*/
fun load(directory: String): FileEventStore {
this.directory = directory
if (File(directory).exists()) {
// using extension function walk
File(directory).walk().forEach {
if (it.name.endsWith(".json")) {
val content = it.readText()
val json = JSONObject(content)
events.add(Event.ModelMapper.fromJSON(json))
}
}
} else {
File(directory).mkdirs()
}
return this;
}
/**
* Stores (saves) the provided events.
*/
override fun storeEvents(events: List<Event>) {
synchronized(this) {
var internalId = this.events.size + 1
for (ev in events) {
if (directory != null) {
val json = Event.ModelMapper.toJSON(ev).toString(2)
val prefix = "%06d".format(internalId)
File("$directory/$prefix-event.json").writeText(json)
internalId++
}
this.events.add(ev)
}
}
}
/**
* Retrieves all events, without any filtering.
*/
override fun retrieve(): List<Event> {
return this.events
}
/**
* Drop all events (similar to TRUNCATE TABLE in the SQL world)
*
*/
fun truncate() {
events.clear()
}
/**
* Retrieves events with filtering applied
*/
override fun retrieve(filter: Filter): List<Event> {
if (filter.lastId != null) {
for (i in events.indices) {
if (events[i].id == filter.lastId) {// not the last event
val filtered = this.events
.subList(i + 1, events.size)
.filter { it -> matchesFilter(it, filter) }
if (filter.pageSize != null) {
return filtered.take(filter.pageSize)
} else {
return filtered
}
}
}
return Collections.emptyList()
} else {
val filtered = this.events.filter { it -> matchesFilter(it, filter) }
if (filter.pageSize != null) {
return filtered.take(filter.pageSize)
} else {
return filtered
}
}
}
private fun matchesFilter(ev: Event, filter: Filter): Boolean {
val matchedType = if (filter.type != null) (ev.type == filter.type) else true
val matchedAggregate = if (filter.aggregateId != null) (ev.aggregateId == filter.aggregateId) else true
return matchedType && matchedAggregate
}
}
| 18 | null | 116 | 138 | 5b55efd24d2239a7a2d57fb395b0a230e687dc73 | 3,296 | blockchain-devkit | MIT License |
samples/todo/shared/src/commonMain/kotlin/com/eygraber/virtue/samples/todo/shared/TodoAppComponent.kt | eygraber | 807,438,503 | false | {"Kotlin": 120450, "Shell": 1747} | package com.eygraber.virtue.samples.todo.shared
import com.eygraber.virtue.config.VirtueConfig
import com.eygraber.virtue.di.components.VirtueAppComponent
import com.eygraber.virtue.di.components.VirtuePlatformComponent
import me.tatarka.inject.annotations.Component
@Component
abstract class TodoAppComponent(
@Component override val platformComponent: VirtuePlatformComponent,
override val config: VirtueConfig,
) : VirtueAppComponent {
companion object
}
| 1 | Kotlin | 0 | 4 | fa2cda69e0da0a4d8ccfb0d917dd2a3284c45346 | 466 | virtue | MIT License |
telegram-bot/src/commonMain/kotlin/eu/vendeli/tgbot/types/stars/TransactionPartner.kt | vendelieu | 496,567,172 | false | {"Kotlin": 1040778, "Python": 12809, "Shell": 1249, "CSS": 356} | package eu.vendeli.tgbot.types.stars
import eu.vendeli.tgbot.annotations.internal.TgAPI
import eu.vendeli.tgbot.types.User
import eu.vendeli.tgbot.types.media.PaidMedia
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* This object describes the source of a transaction, or its recipient for outgoing transactions. Currently, it can be one of
* - TransactionPartnerUser
* - TransactionPartnerFragment
* - TransactionPartnerTelegramAds
* - TransactionPartnerOther
*
* [Api reference](https://core.telegram.org/bots/api#transactionpartner)
*
*/
@Serializable
sealed class TransactionPartner(
val type: String,
) {
@Serializable
@SerialName("fragment")
data class Fragment(
val withdrawalState: RevenueWithdrawalState? = null,
) : TransactionPartner("fragment")
@Serializable
@SerialName("user")
@TgAPI.Name("TransactionPartnerUser")
data class UserPartner(
val user: User,
val invoicePayload: String? = null,
val paidMedia: List<PaidMedia>? = null,
val paidMediaPayload: String? = null,
) : TransactionPartner("user")
@Serializable
@SerialName("other")
data object Other : TransactionPartner("other")
@Serializable
@SerialName("telegram_ads")
data object TelegramAds : TransactionPartner("telegram_ads")
}
| 6 | Kotlin | 14 | 176 | 41d50ea8fd014cb31b61eb5c2f4a4bebf4736b45 | 1,359 | telegram-bot | Apache License 2.0 |
app/src/main/java/org/firezenk/foodieapp/domain/usecases/MakeReservation.kt | FireZenk | 132,938,078 | false | null | package org.firezenk.foodieapp.domain.usecases
import org.firezenk.foodieapp.domain.repositories.VenuesRepository
import javax.inject.Inject
class MakeReservation @Inject constructor(private val repository: VenuesRepository) {
fun execute(venueId: String) = repository.makeReservation(venueId)
} | 0 | Kotlin | 0 | 0 | 456adb63fbc77a5cf420c77d35059eb7d2b7f806 | 302 | foodieapp | The Unlicense |
app/src/main/java/com/jacquessmuts/rxstarter/kotlin/ASingleActivity.kt | JacquesSmuts | 149,759,257 | false | null | package com.jacquessmuts.rxstarter.kotlin
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.widget.TextView
import com.jacquessmuts.rxstarter.R
import io.reactivex.Single
import io.reactivex.disposables.Disposable
class ASingleActivity : AppCompatActivity() {
private var singleDisposable: Disposable? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val textView = findViewById<TextView>(R.id.textView)
val fab = findViewById<FloatingActionButton>(R.id.fab)
fab.setOnClickListener {
// Create a single. This is not ideal.
Single.just(getAGreeting())
.subscribe { resultString -> textView.text = resultString }
// Create a single, and make sure it's disposed of in onDestroy. This is better.
singleDisposable = Single.just(getAGreeting())
.subscribe { resultString -> textView.text = resultString }
}
}
override fun onDestroy() {
// dispose of all your Subscriptions in onDestroy, to prevent memory leaks
singleDisposable?.dispose()
super.onDestroy()
}
private fun getAGreeting(): String {
return "Hello ~World~ GDG"
}
}
| 2 | null | 4 | 13 | a74fdc8cee80b21f2b1c97c5a2230cc0c14fdbbf | 1,547 | RxStarter | MIT License |
core/src/main/kotlin/me/wieku/danser/beatmap/TrackManager.kt | Wieku | 173,530,017 | false | null | package me.wieku.danser.beatmap
import me.wieku.danser.beatmap.parsing.BeatmapParser
import me.wieku.framework.animation.Glider
import me.wieku.framework.di.bindable.Bindable
import me.wieku.framework.logging.Logging
import me.wieku.framework.resource.FileHandle
import me.wieku.framework.resource.FileType
import org.koin.core.KoinComponent
import org.koin.core.inject
import java.util.*
import kotlin.math.min
object TrackManager : KoinComponent {
private val logger = Logging.getLogger("runtime")
private val bindableBeatmap: Bindable<Beatmap?> by inject()
private val playlistHistory = ArrayList<BeatmapSet>()
private val volumeGlider = Glider(0f)
private var currentPlayIndex = -1
fun start(time: Double) {
var beatmap = Beatmap("cYsmix - Peer Gynt (Wieku) [Danser Intro].osu")
BeatmapParser().parse(
FileHandle(
"assets/beatmaps/cYsmix - Peer Gynt/cYsmix - Peer Gynt (Wieku) [Danser Intro].osu",
FileType.Classpath
), beatmap
)
startBeatmap(beatmap, true, -1300f)
volumeGlider.addEvent(time, time + 1300f, 0f, 1f)
}
fun backwards() {
if (currentPlayIndex == -1) return
currentPlayIndex--
if (currentPlayIndex >= 0) {
val beatmapSet = playlistHistory[currentPlayIndex]
startBeatmap(beatmapSet.beatmaps[beatmapSet.beatmaps.size - 1])
} else {
currentPlayIndex = 0
}
}
fun forward() {
if (BeatmapManager.beatmapSets.size == 0) return
currentPlayIndex++
if (currentPlayIndex >= playlistHistory.size) {
var beatmapSet: BeatmapSet
var lastIndex: Int
do {
beatmapSet = BeatmapManager.beatmapSets.random()
lastIndex = playlistHistory.lastIndexOf(beatmapSet)
} while (lastIndex > -1 && playlistHistory.size - lastIndex < min(BeatmapManager.beatmapSets.size, 20))
playlistHistory.add(beatmapSet)
startBeatmap(beatmapSet.beatmaps[beatmapSet.beatmaps.size - 1])
} else {
val beatmapSet = playlistHistory[currentPlayIndex]
startBeatmap(beatmapSet.beatmaps[beatmapSet.beatmaps.size - 1])
}
}
fun update(time: Double) {
volumeGlider.update(time)
bindableBeatmap.value?.let { beatmap ->
beatmap.getTrack().setVolume(volumeGlider.value)
if (beatmap.getTrack().getPosition() >= beatmap.getTrack().getLength()) {
forward()
}
}
}
private fun startBeatmap(beatmap: Beatmap, startAtPreview: Boolean = false, previewOffset: Float = 0f) {
bindableBeatmap.value?.getTrack()?.stop()
logger.info("Changed current beatmap to: ${beatmap.beatmapMetadata.artist} - ${beatmap.beatmapMetadata.title}")
beatmap.loadTrack(startAtPreview)
beatmap.getTrack().play(volumeGlider.value)
if (startAtPreview) {
beatmap.getTrack().setPosition((beatmap.beatmapMetadata.previewTime.toDouble() + previewOffset) / 1000)
} else {
beatmap.getTrack().setPosition((previewOffset / 1000).toDouble())
}
bindableBeatmap.value = beatmap
}
} | 3 | null | 10 | 75 | a7b594becb304d8f96d8ca587461e9c90767919e | 3,278 | danser | MIT License |
app/src/main/java/xyz/teamgravity/weatherforecast/core/util/WeatherType.kt | raheemadamboev | 513,131,865 | false | {"Kotlin": 40673} | package xyz.teamgravity.weatherforecast.core.util
import androidx.annotation.DrawableRes
import xyz.teamgravity.weatherforecast.R
sealed class WeatherType(
val name: UniversalText,
@DrawableRes val icon: Int,
) {
companion object {
fun fromWeatherCode(code: Int): WeatherType {
return when (code) {
0 -> ClearSky
1 -> MainlyClear
2 -> PartlyCloudy
3 -> Overcast
45 -> Foggy
48 -> DepositingRimeFog
51 -> LightDrizzle
53 -> ModerateDrizzle
55 -> DenseDrizzle
56 -> LightFreezingDrizzle
57 -> DenseFreezingDrizzle
61 -> SlightRain
63 -> ModerateRain
65 -> HeavyRain
66 -> LightFreezingDrizzle
67 -> HeavyFreezingRain
71 -> SlightSnowFall
73 -> ModerateSnowFall
75 -> HeavySnowFall
77 -> SnowGrains
80 -> SlightRainShowers
81 -> ModerateRainShowers
82 -> ViolentRainShowers
85 -> SlightSnowShowers
86 -> HeavySnowShowers
95 -> ModerateThunderstorm
96 -> SlightHailThunderstorm
99 -> HeavyHailThunderstorm
else -> ClearSky
}
}
}
object ClearSky : WeatherType(
name = UniversalText.Resource(id = R.string.clear_sky),
icon = R.drawable.ic_sunny
)
object MainlyClear : WeatherType(
name = UniversalText.Resource(id = R.string.mainly_clear),
icon = R.drawable.ic_cloudy
)
object PartlyCloudy : WeatherType(
name = UniversalText.Resource(id = R.string.partly_cloudy),
icon = R.drawable.ic_cloudy
)
object Overcast : WeatherType(
name = UniversalText.Resource(id = R.string.overcast),
icon = R.drawable.ic_cloudy
)
object Foggy : WeatherType(
name = UniversalText.Resource(id = R.string.foggy),
icon = R.drawable.ic_very_cloudy
)
object DepositingRimeFog : WeatherType(
name = UniversalText.Resource(id = R.string.depositing_rime_fog),
icon = R.drawable.ic_very_cloudy
)
object LightDrizzle : WeatherType(
name = UniversalText.Resource(id = R.string.light_drizzle),
icon = R.drawable.ic_rainshower
)
object ModerateDrizzle : WeatherType(
name = UniversalText.Resource(id = R.string.moderate_drizzle),
icon = R.drawable.ic_rainshower
)
object DenseDrizzle : WeatherType(
name = UniversalText.Resource(id = R.string.dense_drizzle),
icon = R.drawable.ic_rainshower
)
object LightFreezingDrizzle : WeatherType(
name = UniversalText.Resource(id = R.string.light_freezing_drizzle),
icon = R.drawable.ic_snowyrainy
)
object DenseFreezingDrizzle : WeatherType(
name = UniversalText.Resource(id = R.string.dense_freezing_drizzle),
icon = R.drawable.ic_snowyrainy
)
object SlightRain : WeatherType(
name = UniversalText.Resource(id = R.string.slight_rain),
icon = R.drawable.ic_rainy
)
object ModerateRain : WeatherType(
name = UniversalText.Resource(id = R.string.moderate_rain),
icon = R.drawable.ic_rainy
)
object HeavyRain : WeatherType(
name = UniversalText.Resource(id = R.string.heavy_rain),
icon = R.drawable.ic_rainy
)
object HeavyFreezingRain : WeatherType(
name = UniversalText.Resource(id = R.string.heavy_freezing_rain),
icon = R.drawable.ic_snowyrainy
)
object SlightSnowFall : WeatherType(
name = UniversalText.Resource(id = R.string.slight_snow_fall),
icon = R.drawable.ic_snowy
)
object ModerateSnowFall : WeatherType(
name = UniversalText.Resource(id = R.string.moderate_snow_fall),
icon = R.drawable.ic_heavysnow
)
object HeavySnowFall : WeatherType(
name = UniversalText.Resource(id = R.string.heavy_snow_fall),
icon = R.drawable.ic_heavysnow
)
object SnowGrains : WeatherType(
name = UniversalText.Resource(id = R.string.snow_grains),
icon = R.drawable.ic_heavysnow
)
object SlightRainShowers : WeatherType(
name = UniversalText.Resource(id = R.string.slight_rain_showers),
icon = R.drawable.ic_rainshower
)
object ModerateRainShowers : WeatherType(
name = UniversalText.Resource(id = R.string.moderate_rain_showers),
icon = R.drawable.ic_rainshower
)
object ViolentRainShowers : WeatherType(
name = UniversalText.Resource(id = R.string.violent_rain_showers),
icon = R.drawable.ic_rainshower
)
object SlightSnowShowers : WeatherType(
name = UniversalText.Resource(id = R.string.slight_snow_showers),
icon = R.drawable.ic_snowy
)
object HeavySnowShowers : WeatherType(
name = UniversalText.Resource(id = R.string.heavy_snow_showers),
icon = R.drawable.ic_snowy
)
object ModerateThunderstorm : WeatherType(
name = UniversalText.Resource(id = R.string.moderate_thunderstorm),
icon = R.drawable.ic_thunder
)
object SlightHailThunderstorm : WeatherType(
name = UniversalText.Resource(id = R.string.slight_hail_thunderstorm),
icon = R.drawable.ic_rainythunder
)
object HeavyHailThunderstorm : WeatherType(
name = UniversalText.Resource(id = R.string.heavy_hail_thunderstorm),
icon = R.drawable.ic_rainythunder
)
} | 0 | Kotlin | 0 | 0 | 9bec0d2a8644c2956f2b06255470892dfe1b6cd5 | 5,706 | weather-forecast | Apache License 2.0 |
app/src/main/java/com/cektrend/cekinhome/core/base/BaseViewModel.kt | saipulmuiz | 388,676,085 | false | null | package com.cektrend.cekinhome.core.base
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
/**
* Created by <NAME> on 7/30/2021.
* Cekinhome | Made with love
* Check our website -> Cektrend Studio | https://cektrend.com for more information
* For question and project collaboration contact me to <EMAIL>
*/
abstract class BaseViewModel : ViewModel() {
override fun onCleared() {
super.onCleared()
}
} | 0 | Kotlin | 0 | 0 | efd1213e95ed222bbd86a5d2600ae6dfa6340da8 | 461 | Cekinhome | The Unlicense |
finch-kotlin-core/src/main/kotlin/com/tryfinch/api/services/async/hris/CompanyServiceAsync.kt | Finch-API | 688,609,420 | false | {"Kotlin": 2724344, "Shell": 3626, "Dockerfile": 399} | // File generated from our OpenAPI spec by Stainless.
package com.tryfinch.api.services.async.hris
import com.tryfinch.api.core.RequestOptions
import com.tryfinch.api.models.Company
import com.tryfinch.api.models.HrisCompanyRetrieveParams
interface CompanyServiceAsync {
/** Read basic company data */
suspend fun retrieve(
params: HrisCompanyRetrieveParams,
requestOptions: RequestOptions = RequestOptions.none()
): Company
}
| 0 | Kotlin | 1 | 0 | a2353cecd2bc5509396efebbb9dbeb60c71ea1cf | 459 | finch-api-kotlin | Apache License 2.0 |
teamcity-kotlin-trigger-remote/src/toCompile/ErroneousTriggerPolicy.kt | JetBrains | 307,772,250 | false | {"Kotlin": 82041, "Java": 14780, "Makefile": 599, "CSS": 181} | package jetbrains.buildServer.buildTriggers.remote.compiled
import jetbrains.buildServer.buildTriggers.remote.*
class ErroneousTriggerPolicy : CustomTriggerPolicy {
override fun triggerBuild(context: TriggerContext, restApiClient: RestApiClient): Boolean {
throw RuntimeException("I'm the Evil")
}
} | 2 | Kotlin | 3 | 2 | fd314a0e7d22522e6146557eb550af7a5089de0f | 317 | teamcity-kotlin-trigger | Apache License 2.0 |
app/src/main/kotlin/com/ybook/app/ui/home/HomeFragment.kt | noproxy | 27,573,470 | false | null | /*
Copyright 2015 Carlos
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.ybook.app.ui.home
import android.view.LayoutInflater
import android.view.KeyEvent
import android.widget.EditText
import android.content.Intent
import android.app.SearchManager
import com.ybook.app.R
import android.app.Activity
import com.umeng.analytics.MobclickAgent
import com.ybook.app.util.EVENT_SEARCH
import java.util.HashMap
import android.widget.AutoCompleteTextView
import android.content.Context
import java.util.ArrayList
import android.widget.ArrayAdapter
import com.ybook.app.net.PostHelper
import android.os.Handler
import android.os.Message
import com.ybook.app.net.MSG_SUCCESS
import android.util.Log
import com.ybook.app.net.MSG_ERROR
import com.squareup.picasso.Picasso
import android.widget.ImageView
import com.ybook.app.bean.BookListResponse
import android.widget.TextView
import android.support.v4.app.Fragment
import android.widget.ExpandableListView
import android.widget.BaseExpandableListAdapter
import com.ybook.app.id
import com.ybook.app.util.ListViewUtil
import com.ybook.app.util.EVENT_ADD_FROM_DETAIL
import com.ybook.app.util.EVENT_OPEN_RECOMMEND_LIST
import com.ybook.app.ui.search.SearchActivity
import android.widget.ScrollView
import android.widget.LinearLayout
import android.support.v7.widget.CardView
import com.ybook.app.ui.main.MainActivity
import android.view.ViewTreeObserver.OnScrollChangedListener
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.view.ViewGroup
import android.os.AsyncTask
import java.net.URL
import com.ybook.app.net.getMainUrl
import me.toxz.kotlin.makeTag
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpGet
import org.apache.http.HttpStatus
import com.ybook.app.util.JSONHelper
import org.apache.http.util.EntityUtils
import org.apache.http.protocol.HTTP
import android.support.v4.app.LoaderManager
import android.support.v4.content.Loader
import android.support.v4.content.AsyncTaskLoader
import me.toxz.kotlin.after
import android.os.Bundle
import com.ybook.app.ui.list.NewBookListActivity
import com.ybook.app.util.ACache
import java.io.Serializable
/**
* Created by carlos on 11/13/14.
*/
//TODO show one BookList at once it loaded
public val KEY_BOOK_LIST_RESPONSE_EXTRA: String = "bookList"
public class HomeFragment() : Fragment(), View.OnClickListener, OnScrollChangedListener, LoaderManager.LoaderCallbacks<List<BookListResponse>> {
val BUNDLE_KEY_POSITION = "position"
val mListData = HashMap<Int, BookListResponse>(4)
var mAdapter: BookListRecyclerViewAdapter? = null
override fun onCreateLoader(id: Int, args: Bundle?): Loader<List<BookListResponse>>? {
Log.d(TAG, "load is created: " + id)
return when ( id ) {
BOOK_LIST_LOADER_ID -> BookListsLoader(mActivity!!)
SINGLE_BOOK_LIST_LOADER_ID -> SingleBookListLoader(mActivity!!, args!!.getInt(BUNDLE_KEY_POSITION))
else -> null
}
}
override fun onLoadFinished(loader: Loader<List<BookListResponse>>?, data: List<BookListResponse>?) {
Log.i(TAG, "onLoadFinished,data: " + data + ", adapter: " + mAdapter)
if (data != null) {
ACache.get(mActivity).put("list", data as Serializable)
}
data?.forEach { mListData.put(it.id, it);Log.d(TAG, it.toString()) }
mAdapter?.notifyDataSetChanged()
}
override fun onLoaderReset(loader: Loader<List<BookListResponse>>?) {
mListData.clear()
}
val TAG: String = makeTag()
var mBookListLoadTasks: Array<AsyncTask<URL, Void, BookListResponse>>? = null
override fun onCreateView(inflater: android.view.LayoutInflater?, container: ViewGroup?, s: android.os.Bundle?) = initViews(inflater?.inflate(R.layout.fragment_home, container, false)!!)
override fun onClick(v: View) {
val t = v.getTag()
when (t) {
is BookListResponse -> {
MobclickAgent.onEvent(getActivity(), EVENT_OPEN_RECOMMEND_LIST)
startActivity(Intent(mActivity, javaClass<NewBookListActivity>()).putExtra(KEY_BOOK_LIST_RESPONSE_EXTRA, t))
}
is View -> {
if (t.getVisibility() == View.VISIBLE) {
t setVisibility View.GONE
(v id R.id.homeHeadArrow) as ImageView setImageResource R.drawable.ic_arrow_drop_down
} else {
t setVisibility View.VISIBLE
(v id R.id.homeHeadArrow) as ImageView setImageResource R.drawable.ic_arrow_drop_up
mScrollView?.post { mScrollView!!.smoothScrollTo(0, t.getBottom()) }
}
}
}
}
var mScrollView: android.widget.ScrollView? = null
fun initViews(mainView: View): View {
mScrollView = mainView as android.widget.ScrollView
val mRecyclerView = mainView.id(R.id.recyclerView) as RecyclerView
mRecyclerView.setHasFixedSize(true)
val mLayoutManager = LinearLayoutManager(mRecyclerView.getContext(), LinearLayoutManager.HORIZONTAL, false)
mRecyclerView.setLayoutManager(mLayoutManager)
mRecyclerView setAdapter BookListRecyclerViewAdapter().after { mAdapter = it }
array(
R.id.mapHeadA to R.id.mapItemA,
R.id.mapHeadB to R.id.mapItemB,
R.id.mapHeadC to R.id.mapItemC,
R.id.mapHeadD to R.id.mapItemD
).forEach { pair ->
(mainView id pair.first).let {
it.setTag(mainView id pair.second)
it.setOnClickListener(this)
}
}
//TODO no animation if (mActivity is OnFragmentScrollChangedListener) {
// Log.i("HomeFragment", "listener" + mScrollView)
// mScrollView?.getViewTreeObserver()?.addOnScrollChangedListener(this)
// }
return mainView
}
fun getSearchHistory(): Array<String?> {
val sp = getActivity()?.getSharedPreferences(SEARCH_HISTORY, Context.MODE_PRIVATE)
val count = sp?.getInt("count", 0) ?: 0
val arrayList = java.util.ArrayList<String>()
for (i in 1..count) {
val s = sp?.getString(i.toString(), null)
if (s != null) arrayList add s
}
return arrayList.copyToArray()
}
val SEARCH_HISTORY = "searchHistory"
fun saveSearchHistory(key: String) {
val sp = getActivity()?.getSharedPreferences(SEARCH_HISTORY, Context.MODE_PRIVATE)
val all = sp?.getAll()
if (!(all?.containsValue(key) ?: true)) {
val count = sp?.getInt("count", 0)
sp?.edit()?.putString((count!!.toInt() + 1).toString(), key)?.putInt("count", count + 1)?.commit()
}
}
override fun onResume() {
super<Fragment>.onResume()
// searchView?.setAdapter(object : ArrayAdapter<String>(getActivity(), R.layout.search_suggest_item, getSearchHistory()) {})
}
var mActivity: Activity? = null
override fun onAttach(activity: Activity?) {
super<Fragment>.onAttach(activity)
(activity as MainActivity).onSectionAttached(0)
mActivity = activity
}
val BOOK_LIST_LOADER_ID = 0
val SINGLE_BOOK_LIST_LOADER_ID = 1
override fun onActivityCreated(savedInstanceState: Bundle?) {
super<Fragment>.onActivityCreated(savedInstanceState)
Log.i(TAG, "activity created")
val cache = ACache.get(mActivity).getAsObject("list") as? List<*>
onLoadFinished(null, cache as List<BookListResponse>?)
getLoaderManager().initLoader(BOOK_LIST_LOADER_ID, Bundle().after { it.putInt(BUNDLE_KEY_POSITION, 0) }, this)
}
override fun onScrollChanged() {
Log.i("HomeFragment", "onScrollChanged:${mScrollView!!.getScrollY()}")
(mActivity as? OnFragmentScrollChangedListener )?.onScrollChanged(mScrollView!!.getScrollY())
}
override fun onDetach() {
super<Fragment>.onDetach()
mScrollView?.getViewTreeObserver()?.removeOnScrollChangedListener(this)
mActivity = null
}
trait OnFragmentScrollChangedListener {
fun onScrollChanged(y: Int)
}
private class BookListCardHolder(val cardView: View) : RecyclerView.ViewHolder(cardView) {
val titleText = ( cardView id R.id.cardText )as TextView
val coverImage = ( cardView id R.id.cardImage )as ImageView
}
private inner class BookListRecyclerViewAdapter() : RecyclerView.Adapter<BookListCardHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookListCardHolder? {
val card = (LayoutInflater.from(parent.getContext()).inflate(R.layout.book_card, parent, false) as CardView ).after {
it setOnClickListener this@HomeFragment
}
return BookListCardHolder(card)
}
override fun onBindViewHolder(holder: BookListCardHolder, position: Int) {
holder.coverImage.setImageResource(R.drawable.ic_empty)
holder.titleText.setText("")
holder.cardView setTag null
holder.coverImage setTag null
holder.titleText setTag null
if (mListData.size() > position) {
mListData.get(position + 1)?.into(holder)
}
}
private fun BookListResponse.into(holder: BookListCardHolder) {
Picasso.with(holder.cardView.getContext()).load(this.coverImgUrl).into(holder.coverImage)
holder.titleText.setText(this.title)
holder.cardView setTag this
holder.coverImage setTag this
holder.titleText setTag this
}
override fun getItemCount(): Int = 4
}
private class BookListsLoader(con: Context) : AsyncTaskLoader<List<BookListResponse>>(con) {
{
onContentChanged()
}
val TAG = makeTag()
override fun loadInBackground(): List<BookListResponse>? {
val result = ArrayList<BookListResponse>(4)
for (num in 1..4) {
val url = getMainUrl() + "/static/temp/bookrec0" + num.toString() + ".json"
Log.i(TAG, "url: " + url)
try {
val rep = DefaultHttpClient().execute(HttpGet(url))
if (rep.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result add JSONHelper.readBookListResponse(EntityUtils.toString(rep.getEntity(), HTTP.UTF_8), num)
}
} catch(e: Exception) {
e.printStackTrace()
}
}
return result
}
override fun onStartLoading() {
if (takeContentChanged())
forceLoad();
}
override fun onStopLoading() {
cancelLoad();
}
}
private class SingleBookListLoader(con: Context, val listId: Int) : AsyncTaskLoader<List<BookListResponse>>(con) {
{
onContentChanged()
}
val TAG = makeTag()
override fun loadInBackground(): List<BookListResponse>? {
val url = getMainUrl() + "/static/temp/bookrec0" + listId.toString() + ".json"
Log.i(TAG, "url: " + url)
try {
val rep = DefaultHttpClient().execute(HttpGet(url))
if (rep.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return arrayListOf(JSONHelper.readBookListResponse(EntityUtils.toString(rep.getEntity(), HTTP.UTF_8), listId))
}
} catch(e: Exception) {
e.printStackTrace()
}
return null
}
override fun onStartLoading() {
if (takeContentChanged())
forceLoad();
}
override fun onStopLoading() {
cancelLoad();
}
}
}
| 1 | null | 1 | 5 | 02240e526ea515d73cdbe44cbca68f08c63c3c24 | 12,529 | Ybook | Apache License 2.0 |
amiibolist/src/test/java/com/oscarg798/amiibowiki/amiibolist/GetAmiiboFilteredUseCaseTest.kt | oscarg798 | 275,942,605 | false | null | /*
* Copyright 2020 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
*/
package com.oscarg798.amiibowiki.amiibolist
import com.oscarg798.amiibowiki.amiibolist.mvi.AmiiboListFailure
import com.oscarg798.amiibowiki.amiibolist.usecases.GetAmiiboFilteredUseCase
import com.oscarg798.amiibowiki.core.failures.FilterAmiiboFailure
import com.oscarg798.amiibowiki.core.models.Amiibo
import com.oscarg798.amiibowiki.core.models.AmiiboReleaseDate
import com.oscarg798.amiibowiki.core.models.AmiiboType
import com.oscarg798.amiibowiki.core.repositories.AmiiboRepositoryImpl
import com.oscarg798.amiibowiki.core.usecases.GetDefaultAmiiboTypeUseCase
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.runBlocking
import org.amshove.kluent.shouldBeEqualTo
import org.junit.Before
import org.junit.Test
class GetAmiiboFilteredUseCaseTest {
private val getDefaultAmiiboTypeUseCase = mockk<GetDefaultAmiiboTypeUseCase>()
private val repository = mockk<AmiiboRepositoryImpl>()
private lateinit var usecase: GetAmiiboFilteredUseCase
@Before
fun setup() {
every { getDefaultAmiiboTypeUseCase.execute() }.answers { DEFAULT_FILTER }
coEvery { repository.getAmiibosFilteredByTypeName(any()) } answers {
FILTERED_AMIIBOS
}
coEvery { repository.getAmiibosWithoutFilters() } answers { flowOf(NO_FILTERED_AMIIBOS) }
usecase = GetAmiiboFilteredUseCase(
getDefaultAmiiboTypeUseCase,
repository
)
}
@Test
fun `given non default filter when is executed then it should return filtered amiibos`() {
val result = runBlocking {
usecase.execute(FILTER).first()
}
FILTERED_AMIIBOS shouldBeEqualTo result
}
@Test
fun `given default filter when is executed then it should return all the amiibos`() {
coEvery { repository.getAmiibos() } answers { flowOf(NO_FILTERED_AMIIBOS) }
val result = runBlocking {
usecase.execute(DEFAULT_FILTER).first()
}
NO_FILTERED_AMIIBOS shouldBeEqualTo result
}
@Test(expected = AmiiboListFailure::class)
fun `given there is a failure filtering the amiibos when usecae is executed then it should throw an amiibo list failure`() {
coEvery { repository.getAmiibosFilteredByTypeName(any()) } answers {
throw FilterAmiiboFailure.Unknown(null)
}
runBlocking {
usecase.execute(FILTER).first()
}
}
@Test(expected = Exception::class)
fun `given there is an exception the amiibos when usecae is executed then it should throw it`() {
coEvery { repository.getAmiibosFilteredByTypeName(any()) } answers {
throw Exception()
}
runBlocking {
usecase.execute(FILTER).first()
}
}
}
private val DEFAULT_FILTER = AmiiboType("3", "3")
private val FILTER = AmiiboType("1", "2")
private val FILTERED_AMIIBOS = listOf(
Amiibo(
"1",
"2",
"3",
"4",
"5",
"6",
AmiiboReleaseDate("7", "8", "9", "10"),
"11", "12"
)
)
private val NO_FILTERED_AMIIBOS = listOf(
Amiibo(
"12",
"22",
"32",
"42",
"52",
"62",
AmiiboReleaseDate("72", "82", "92", "102"),
"112", "122"
)
)
| 0 | Kotlin | 3 | 10 | e3f7f3f97af3ffb4998a3e8d4cb2144c82a5221c | 4,458 | AmiiboWiki | MIT License |
plugin/jetbrains/src/main/kotlin/com/sourceplusplus/sourcemarker/psi/EndpointNameDetector.kt | chess-equality | 297,668,044 | false | null | package com.sourceplusplus.sourcemarker.psi
import com.sourceplusplus.marker.source.mark.api.MethodSourceMark
import com.sourceplusplus.sourcemarker.activities.PluginSourceMarkerStartupActivity.Companion.vertx
import com.sourceplusplus.sourcemarker.psi.endpoint.SkywalkingTrace
import com.sourceplusplus.sourcemarker.psi.endpoint.SpringMVC
import io.vertx.core.Future
import io.vertx.core.Promise
import io.vertx.kotlin.coroutines.await
import io.vertx.kotlin.coroutines.dispatcher
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.jetbrains.uast.UMethod
import java.util.*
/**
* todo: description.
*
* @since 0.0.1
* @author [<NAME>](mailto:<EMAIL>)
*/
class EndpointNameDetector {
private val detectorSet = setOf(
SkywalkingTrace(),
SpringMVC()
)
fun determineEndpointName(sourceMark: MethodSourceMark): Future<Optional<String>> {
return determineEndpointName(sourceMark.getPsiMethod())
}
fun determineEndpointName(uMethod: UMethod): Future<Optional<String>> {
val promise = Promise.promise<Optional<String>>()
GlobalScope.launch(vertx.dispatcher()) {
detectorSet.forEach {
try {
val endpointName = it.determineEndpointName(uMethod).await()
if (endpointName.isPresent) promise.complete(endpointName)
} catch (throwable: Throwable) {
promise.fail(throwable)
}
}
promise.tryComplete(Optional.empty())
}
return promise.future()
}
interface EndpointNameDeterminer {
fun determineEndpointName(uMethod: UMethod): Future<Optional<String>>
}
}
| 0 | Kotlin | 0 | 0 | 7c157711d11b4836d38209daf32d4ee3b3d831de | 1,721 | SourceMarker-Alpha | Apache License 2.0 |
src/test/kotlin/algorithmic_toolbox/week2/TestEuclidianAlgorithm.kt | eniltonangelim | 369,331,780 | false | null | package algorithmic_toolbox.week2
import algorithmic_toolbox.week1.euclideanAlgorithm
import org.junit.Test
import kotlin.test.assertEquals
class TestEuclidianAlgorithm {
@Test
fun test0() {
val result = euclideanAlgorithm(18, 35)
assertEquals(1, result)
}
@Test
fun test1() {
val result = euclideanAlgorithm(28851538, 1183019)
assertEquals(17657, result)
}
} | 0 | Kotlin | 0 | 0 | 031bccb323339bec05e8973af7832edc99426bc1 | 421 | AlgorithmicToolbox | MIT License |
ddd/event/framework/pulsar/materialised-view/src/main/kotlin/org/sollecitom/chassis/ddd/event/framework/pulsar/materialised/view/PulsarSubscriber.kt | sollecitom | 669,483,842 | false | {"Kotlin": 676990} | package org.sollecitom.chassis.ddd.event.framework.pulsar.materialised.view
import kotlinx.coroutines.flow.Flow
import org.apache.pulsar.client.api.*
import org.sollecitom.chassis.core.domain.lifecycle.Startable
import org.sollecitom.chassis.core.domain.lifecycle.Stoppable
import org.sollecitom.chassis.kotlin.extensions.async.await
import org.sollecitom.chassis.pulsar.utils.PulsarTopic
import org.sollecitom.chassis.pulsar.utils.messages
class PulsarSubscriber<VALUE : Any>(private val topics: Set<PulsarTopic>, private val schema: Schema<VALUE>, private val consumerName: String, private val subscriptionName: String, private val pulsar: PulsarClient, private val subscriptionType: SubscriptionType = SubscriptionType.Failover, private val customizeConsumer: ConsumerBuilder<VALUE>.() -> Unit = {}) : Startable, Stoppable {
private lateinit var consumer: Consumer<VALUE>
val messages: Flow<Message<VALUE>> by lazy { consumer.messages }
override suspend fun start() {
consumer = createConsumer()
}
override suspend fun stop() = consumer.close()
suspend fun acknowledge(message: Message<VALUE>) = consumer.acknowledgeAsync(message).await()
private fun createConsumer(): Consumer<VALUE> {
return pulsar.newConsumer(schema).topics(topics.map { it.fullName.value }).consumerName(consumerName).subscriptionName(subscriptionName).subscriptionType(subscriptionType).also(customizeConsumer).subscribe()
}
} | 0 | Kotlin | 0 | 1 | b82713a486e2d362e8fb745d1fa62d5e79fd24ba | 1,459 | chassis | MIT License |
android/src/main/java/com/tolgahanarikan/reactnativewindowinsetsanimation/RNWindowInsetsAnimationModule.kt | tolgahan-arikan | 390,323,817 | false | {"JavaScript": 15462, "Kotlin": 7735, "TypeScript": 2676, "Swift": 2113, "Ruby": 1241, "Starlark": 602, "Objective-C": 589} | package com.tolgahanarikan.reactnativewindowinsetsanimation
import android.content.res.Resources.getSystem
import android.view.WindowInsets
import android.view.WindowInsetsAnimation
import androidx.core.view.WindowInsetsCompat
import com.facebook.react.bridge.*
import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter
class RNWindowInsetsAnimationModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
override fun getName() = "RNWindowInsetsAnimationModule"
@ReactMethod
fun listenForWindowInsetEvents() {
val activity = currentActivity ?: return
val window = activity.window
val rootView = window.decorView.rootView
val cb = object : WindowInsetsAnimation.Callback(DISPATCH_MODE_STOP) {
override fun onProgress(insets: WindowInsets, animations: MutableList<WindowInsetsAnimation>): WindowInsets {
val posBottom = (insets.getInsets(WindowInsetsCompat.Type.ime()).bottom -
insets.getInsets(WindowInsetsCompat.Type.systemBars()).bottom)
.dp.coerceIn(0 , 1000)
val params = Arguments.createMap()
params.putInt("bottomInset", posBottom)
sendEvent(reactApplicationContext, "RNWindowInsetEvent", params)
return insets
}
}
rootView.setWindowInsetsAnimationCallback(cb)
}
private fun sendEvent(reactContext: ReactContext,
eventName: String,
params: WritableMap) {
reactContext
.getJSModule(RCTDeviceEventEmitter::class.java)
.emit(eventName, params)
}
val Int.dp: Int get() = (this / getSystem().displayMetrics.density).toInt()
} | 0 | JavaScript | 0 | 1 | b9a82bfb11522e8cfe6ecedc53f5300f50a7bbef | 1,816 | rn-android-window-inset | MIT License |
fontawesome/src/de/msrd0/fontawesome/icons/FA_TRUCK_PLANE.kt | msrd0 | 363,665,023 | false | null | /* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* 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 de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
/** Truck Plane */
object FA_TRUCK_PLANE: Icon {
override val name get() = "Truck Plane"
override val unicode get() = "e58f"
override val styles get() = setOf(SOLID)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path d="M256 86.06L256 182.9L256 184V411.5L256.1 411.6C257.3 433.8 269.8 452.9 288 463.4V496C288 501.2 288.8 506.3 290.4 510.1L200 480.9L109.1 511.2C104.2 512.8 98.82 511.1 94.64 508.1C90.47 505.1 88 501.1 88 496V464C88 459.1 90.21 454.5 94 451.5L144 411.5V330.3L20.6 367.3C15.75 368.8 10.51 367.9 6.449 364.8C2.391 361.8 0 357.1 0 352V288C0 282.4 2.949 277.2 7.768 274.3L144 192.5V86.06C144 54.68 169.4 0 200 0C231.5 0 256 54.68 256 86.06V86.06zM288 176C288 149.5 309.5 128 336 128H592C618.5 128 640 149.5 640 176V400C640 420.9 626.6 438.7 608 445.3V488C608 501.3 597.3 512 584 512H568C554.7 512 544 501.3 544 488V448H384V488C384 501.3 373.3 512 360 512H344C330.7 512 320 501.3 320 488V445.3C301.4 438.7 288 420.9 288 400V176zM367.8 254.7L352 304H576L560.2 254.7C556.9 246 548.9 240 539.7 240H388.3C379.1 240 371.1 246 367.8 254.7H367.8zM568 400C581.3 400 592 389.3 592 376C592 362.7 581.3 352 568 352C554.7 352 544 362.7 544 376C544 389.3 554.7 400 568 400zM360 352C346.7 352 336 362.7 336 376C336 389.3 346.7 400 360 400C373.3 400 384 389.3 384 376C384 362.7 373.3 352 360 352z"/></svg>"""
else -> null
}
}
| 0 | Kotlin | 0 | 0 | b2fdb74278104be68c95e8f083fc75ab74395112 | 2,296 | fontawesome-kt | Apache License 2.0 |
core/src/test/kotlin/org/predicode/predicator/terms/AtomTest.kt | robstoll | 154,004,921 | true | {"Java": 146808, "Kotlin": 62142} | package org.predicode.predicator.terms
import ch.tutteli.atrium.api.cc.en_GB.toBe
import ch.tutteli.atrium.verbs.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.predicode.predicator.Knowns
import org.predicode.predicator.predicates.Predicate
import org.predicode.predicator.predicates.TestPredicateResolver
import org.predicode.predicator.testutils.isEmpty
import org.predicode.predicator.testutils.notToBeEmpty
import org.predicode.predicator.testutils.toContain
import reactor.test.StepVerifier
class AtomTest {
lateinit var knowns: Knowns
lateinit var resolver: Predicate.Resolver
@BeforeEach
fun `create knowns`() {
knowns = Knowns.none()
resolver = TestPredicateResolver(knowns)
}
@Test
fun `string representation`() {
assertThat(Atom.named("atom").toString())
.toBe("'atom'")
}
@Test
fun `matches atom with the same name`() {
assertThat(Atom.named("name1").match(Atom.named("name1"), knowns))
.toContain(knowns)
}
@Test
fun `matches placeholder`() {
assertThat(Atom.named("name1").match(Placeholder.placeholder(), knowns))
.toContain(knowns)
}
@Test
fun `does not match atom with another name`() {
assertThat(Atom.named("name1").match(Atom.named("name2"), knowns)).isEmpty()
}
@Test
fun `resolves variable`() {
val atom = Atom.named("name")
val variable = Variable.named("var")
knowns = Knowns.forVariables(variable)
assertThat(atom.match(variable, knowns)).notToBeEmpty {
assertThat(subject.resolution(variable).value())
.toContain(atom)
}
}
@Test
fun `does not match other terms`() {
val atom = Atom.named("name")
assertThat(atom.match(Keyword.named("name"), knowns)).isEmpty()
assertThat(atom.match(Value.raw(123), knowns)).isEmpty()
}
@Test
fun `expands to itself`() {
val atom = Atom.named("name")
StepVerifier.create(atom.expand(resolver))
.expectNext(Term.Expansion(atom, knowns))
.verifyComplete()
}
}
| 0 | Java | 0 | 0 | bc229b1c574e7d1fe880f8a730e7bd6d759e9945 | 2,229 | predicator | MIT License |
expandablrecyclerview/src/main/java/com/umut/expandablrecyclerview/adapter/holder/ViewType.kt | umutyusuf | 113,978,859 | false | null | package com.umut.expandablrecyclerview.adapter.holder
data class ViewType(
val externalViewType: Int,
val isParent: Boolean
) | 0 | Kotlin | 1 | 15 | 293a389e1d1dcb38bd425e078ff9edae71a2e730 | 134 | expandablerecyclerview | Apache License 2.0 |
rulebook-ktlint/src/main/kotlin/com/hanggrian/rulebook/ktlint/BlockTagPunctuationRule.kt | hanggrian | 556,969,715 | false | {"Kotlin": 303482, "Python": 79976, "Java": 19336, "CSS": 1653, "Groovy": 321} | package com.hanggrian.rulebook.ktlint
import com.hanggrian.rulebook.ktlint.internals.Messages
import com.hanggrian.rulebook.ktlint.internals.endOffset
import com.pinterest.ktlint.rule.engine.core.api.ElementType.KDOC_TAG
import com.pinterest.ktlint.rule.engine.core.api.ElementType.KDOC_TAG_NAME
import com.pinterest.ktlint.rule.engine.core.api.ElementType.KDOC_TEXT
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.CommaSeparatedListValueParser
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig
import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfigProperty
import org.ec4j.core.model.PropertyType.LowerCasingPropertyType
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.tree.TokenSet
/**
* [See wiki](https://github.com/hanggrian/rulebook/wiki/Rules/#block-tag-punctuation)
*/
public class BlockTagPunctuationRule :
Rule(
"block-tag-punctuation",
setOf(PUNCTUATED_BLOCK_TAGS_PROPERTY),
) {
private var punctuatedTags = PUNCTUATED_BLOCK_TAGS_PROPERTY.defaultValue
override val tokens: TokenSet = TokenSet.create(KDOC_TAG)
override fun beforeFirstNode(editorConfig: EditorConfig) {
punctuatedTags = editorConfig[PUNCTUATED_BLOCK_TAGS_PROPERTY]
}
override fun visitToken(node: ASTNode, emit: Emit) {
// only enforce certain tags
val blockTag =
node
.findChildByType(KDOC_TAG_NAME)
?.text
?.takeIf { it in punctuatedTags }
?: return
// long descriptions have multiple lines, take only the last one
val kdocText =
node
.lastChildNode
?.takeIf { it.elementType == KDOC_TEXT && it.text.isNotBlank() }
?: return
// checks for violation
kdocText.text
.trimComment()
.lastOrNull()
?.takeUnless { it in END_PUNCTUATIONS }
?: return
emit(kdocText.endOffset, Messages.get(MSG, blockTag), false)
}
internal companion object {
const val MSG = "block.tag.punctuation"
private val END_PUNCTUATIONS = setOf('.', ')')
val PUNCTUATED_BLOCK_TAGS_PROPERTY =
EditorConfigProperty(
type =
LowerCasingPropertyType(
"rulebook_punctuated_block_tags",
"Block tags that have to end with a period.",
CommaSeparatedListValueParser(),
),
defaultValue =
setOf(
"@constructor",
"@receiver",
"@property",
"@param",
"@return",
),
propertyWriter = { it.joinToString() },
)
private fun String.trimComment(): String =
indexOf("//")
.takeUnless { it == -1 }
?.let { substring(0, it).trimEnd() }
?: this
}
}
| 0 | Kotlin | 0 | 1 | f17fdaf419ff55368bdee7275ebba02f47ae7a71 | 3,130 | rulebook | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.