path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
756M
is_fork
bool
2 classes
languages_distribution
stringlengths
12
2.44k
content
stringlengths
6
6.29M
issues
float64
0
10k
main_language
stringclasses
128 values
forks
int64
0
54.2k
stars
int64
0
157k
commit_sha
stringlengths
40
40
size
int64
6
6.29M
name
stringlengths
1
100
license
stringclasses
104 values
org.librarysimplified.audiobook.feedbooks/src/main/java/org/librarysimplified/audiobook/feedbooks/FeedbooksRightsChecks.kt
NYPL-Simplified
139,462,999
false
{"Kotlin": 544969, "Java": 2451}
package org.librarysimplified.audiobook.feedbooks import org.joda.time.LocalDateTime import org.librarysimplified.audiobook.license_check.spi.SingleLicenseCheckParameters import org.librarysimplified.audiobook.license_check.spi.SingleLicenseCheckProviderType import org.librarysimplified.audiobook.license_check.spi.SingleLicenseCheckType class FeedbooksRightsChecks : SingleLicenseCheckProviderType { override val name: String = "FeedbooksRightsCheck" override fun createLicenseCheck( parameters: SingleLicenseCheckParameters ): SingleLicenseCheckType { return FeedbooksRightsCheck( parameters = parameters, timeNow = LocalDateTime.now() ) } }
1
Kotlin
2
2
6633bcd1006ead70bc2ffd945cacb6b38af8e8e5
685
audiobook-android
Apache License 2.0
godot-kotlin/godot-library/src/nativeCore/kotlin/godot/core/type/pool/PoolVector2Array.kt
utopia-rise
238,721,773
false
{"Kotlin": 655494, "Shell": 171}
@file:Suppress("unused", "MemberVisibilityCanBePrivate") package godot.core import godot.gdnative.godot_pool_vector2_array_layout import godot.internal.type.* import kotlinx.cinterop.* class PoolVector2Array : NativeCoreType<godot_pool_vector2_array_layout>, Iterable<Vector2> { //PROPERTIES val size: Int get() = this.size() //CONSTRUCTOR constructor() { _handle = cValue{} callNative { nullSafe(Godot.gdnative.godot_pool_vector2_array_new)(it) } } constructor(other: PoolVector2Array) { _handle = cValue{} callNative { nullSafe(Godot.gdnative.godot_pool_vector2_array_new_copy)(it, other._handle.ptr) } } internal constructor(native: CValue<godot_pool_vector2_array_layout>) { memScoped { [email protected](native.ptr) } } internal constructor(mem: COpaquePointer) { this.setRawMemory(mem) } //INTEROP override fun getRawMemory(memScope: MemScope): COpaquePointer { return _handle.getPointer(memScope) } override fun setRawMemory(mem: COpaquePointer) { _handle = mem.reinterpret<godot_pool_vector2_array_layout>().pointed.readValue() } //POOL ARRAY API SHARED /** * Appends an element at the end of the array (alias of push_back). */ fun append(vector: Vector2) { callNative { nullSafe(Godot.gdnative.godot_pool_vector2_array_append)(it, vector.getRawMemory(this).reinterpret()) } } /** * Appends a PoolVector2Array at the end of this array. */ fun appendArray(array: PoolVector2Array) { callNative { nullSafe(Godot.gdnative.godot_pool_vector2_array_append_array)(it, array._handle.ptr) } } /** * Returns true if the array is empty. */ fun empty() { callNative { nullSafe(Godot.gdnative12.godot_pool_vector2_array_empty)(it) } } /** * Retrieve the element at the given index. */ operator fun get(idx: Int): Vector2 { return Vector2( callNative { nullSafe(Godot.gdnative.godot_pool_vector2_array_get)(it, idx) } ) } /** * Inserts a new element at a given position in the array. * The position must be valid, or at the end of the array (idx == size()). */ fun insert(idx: Int, data: Vector2) { callNative { nullSafe(Godot.gdnative.godot_pool_vector2_array_insert)(it, idx, data.getRawMemory(this).reinterpret()) } } /** * Reverses the order of the elements in the array. */ fun invert() { callNative { nullSafe(Godot.gdnative.godot_pool_vector2_array_invert)(it) } } /** * Appends a value to the array. */ fun pushBack(data: Vector2) { callNative { nullSafe(Godot.gdnative.godot_pool_vector2_array_push_back)(it, data.getRawMemory(this).reinterpret()) } } /** * Removes an element from the array by index. */ fun remove(idx: Int) { callNative { nullSafe(Godot.gdnative.godot_pool_vector2_array_remove)(it, idx) } } /** * Sets the size of the array. If the array is grown, reserves elements at the end of the array. * If the array is shrunk, truncates the array to the new size. */ fun resize(size: Int) { callNative { nullSafe(Godot.gdnative.godot_pool_vector2_array_resize)(it, size) } } /** * Changes the vector at the given index. */ operator fun set(idx: Int, data: Vector2) { callNative { nullSafe(Godot.gdnative.godot_pool_vector2_array_set)(it, idx, data.getRawMemory(this).reinterpret()) } } /** * Returns the size of the array. */ fun size(): Int { return callNative { nullSafe(Godot.gdnative.godot_pool_vector2_array_size)(it) } } //UTILITIES override fun toVariant() = Variant(this) operator fun plus(other: Vector2) { this.append(other) } operator fun plus(other: PoolVector2Array) { this.appendArray(other) } override fun toString(): String { return "PoolVector2Array(${size()})" } override fun iterator(): Iterator<Vector2> { return IndexedIterator(size(), this::get) } /** * WARNING: no equals function is available in the Gdnative API for this Coretype. * This methods implementation works but is not the fastest one. */ override fun equals(other: Any?): Boolean { return if (other is PoolVector2Array) { val list1 = this.toList() val list2 = other.toList() list1 == list2 } else { false } } override fun hashCode(): Int { return _handle.hashCode() } internal inline fun <T> callNative(block: MemScope.(CPointer<godot_pool_vector2_array_layout>) -> T): T { return callNative(this, block) } }
15
Kotlin
16
275
8d51f614df62a97f16e800e6635ea39e7eb1fd62
5,148
godot-kotlin-native
MIT License
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/usecases/coroutines/usecase2/callbacks/SequentialNetworkRequestsCallbacksViewModel.kt
fbertanha
504,533,733
false
{"Kotlin": 157495}
package com.lukaslechner.coroutineusecasesonandroid.usecases.coroutines.usecase2.callbacks import com.lukaslechner.coroutineusecasesonandroid.base.BaseViewModel class SequentialNetworkRequestsCallbacksViewModel( private val mockApi: CallbackMockApi = mockApi() ) : BaseViewModel<UiState>() { fun perform2SequentialNetworkRequest() { } }
0
Kotlin
0
0
b44bcd478330ffe37274869619a18a250146be6a
352
coroutines_use_cases_android
Apache License 2.0
core/ui/src/main/java/com/devfalah/ui/screen/clubs/ClubsScreen.kt
Salmon-family
569,890,321
false
{"Kotlin": 837143}
package com.devfalah.ui.screen.clubs import androidx.compose.animation.* import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.items import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.Lifecycle import androidx.navigation.NavController import com.devfalah.ui.R import com.devfalah.ui.composable.* import com.devfalah.ui.screen.clubCreation.CLUB_CREATION_ROUTE import com.devfalah.ui.screen.clubs.composable.EmptyClubsItem import com.devfalah.ui.screen.clubs.composable.SpecialClubItem import com.devfalah.ui.screen.clubsDetail.navigateToClubDetails import com.devfalah.ui.theme.AppTypography import com.devfalah.ui.theme.LightPrimaryBrandColor import com.devfalah.ui.util.observeAsState import com.devfalah.viewmodels.myClubs.MyClubsUiState import com.devfalah.viewmodels.myClubs.MyClubsViewModel import com.google.accompanist.systemuicontroller.rememberSystemUiController @Composable fun ClubsScreen( navController: NavController, viewModel: MyClubsViewModel = hiltViewModel(), ) { val state by viewModel.uiState.collectAsState() val systemUIController = rememberSystemUiController() val lifecycleState = LocalLifecycleOwner.current.lifecycle.observeAsState() LaunchedEffect(key1 = lifecycleState.value) { if (lifecycleState.value == Lifecycle.Event.ON_RESUME) { viewModel.refreshClub() } } ClubsContent( state = state, onClickCreateClub = { navController.navigate(CLUB_CREATION_ROUTE) }, onClubClick = { navController.navigateToClubDetails(it) }, onRetry = viewModel::getData ) val color = MaterialTheme.colors.background LaunchedEffect(true) { setStatusBarColor( systemUIController = systemUIController, color = color, ) } } @OptIn(ExperimentalAnimationApi::class) @Composable fun ClubsContent( state: MyClubsUiState, onClickCreateClub: () -> Unit, onClubClick: (Int) -> Unit, onRetry: () -> Unit, ) { Scaffold( topBar = { AppBar( title = stringResource(R.string.clubs), showBackButton = false, actions = { IconButton(onClick = onClickCreateClub) { Icon( imageVector = ImageVector.vectorResource(id = R.drawable.create_club), contentDescription = "create club icon", tint = MaterialTheme.colors.primaryVariant ) } } ) } ) { scaffoldPadding -> var animationState by remember { mutableStateOf(0) } Column( modifier = Modifier .fillMaxSize() .padding(scaffoldPadding) .background(MaterialTheme.colors.background) ) { SegmentControls( items = listOf( stringResource(id = R.string.my_clubs), stringResource(R.string.special_clubs) ), onItemSelection = { animationState = it }, modifier = Modifier.padding(horizontal = 8.dp) ) HeightSpacer8() AnimatedContent( targetState = animationState, transitionSpec = { slideInHorizontally(tween(300)) with fadeOut(tween(300)) } ) { when (it) { 0 -> MyClubsScreen(state = state, onClubClick = onClubClick, onRetry = onRetry) 1 -> SpecialClubsScreen(state = state, onClubClick = onClubClick) } } } } } @Composable fun MyClubsScreen( state: MyClubsUiState, onClubClick: (Int) -> Unit, onRetry: () -> Unit, ) { Box(modifier = Modifier.fillMaxSize()) { if (state.error.isNotBlank()) { ErrorItem(onClickRetry = onRetry) } else if (state.isLoading) { Loading() } else if (state.myClubs.isEmpty() && state.mySpecialClubs.isEmpty()) { EmptyClubsItem() } else { LazyColumn( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colors.background), contentPadding = if (state.mySpecialClubs.isNotEmpty()) PaddingValues(vertical = 16.dp) else PaddingValues(vertical = 0.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { if (state.mySpecialClubs.isNotEmpty()) { item { Row(modifier = Modifier.padding(horizontal = 16.dp)) { Icon( painter = painterResource(id = R.drawable.star), contentDescription = null, modifier = Modifier.size(24.dp), tint = LightPrimaryBrandColor ) Text( text = stringResource(R.string.my_special_clubs), modifier = Modifier.padding(start = 8.dp), style = AppTypography.subtitle1, color = MaterialTheme.colors.primaryVariant ) } } } item { LazyRow( horizontalArrangement = Arrangement.spacedBy(16.dp), contentPadding = PaddingValues(horizontal = 16.dp), modifier = Modifier.fillMaxWidth() ) { items(state.mySpecialClubs) { club -> SpecialClubItem( state = club, iconId = club.image, clubTitle = club.name, modifier = Modifier.size(98.dp), onClick = { onClubClick(club.id) } ) } } } if(state.myClubs.isNotEmpty()) { item { Text( text = stringResource(R.string.my_clubs), style = AppTypography.subtitle1, color = MaterialTheme.colors.primaryVariant, modifier = Modifier.padding(horizontal = 16.dp) ) } } items(state.myClubs) { ClubItem( state = it, onClubSelected = onClubClick, modifier = Modifier .padding(horizontal = 16.dp) ) } } } } } @Composable fun SpecialClubsScreen( state: MyClubsUiState, onClubClick: (Int) -> Unit, ) { LazyVerticalGrid( columns = GridCells.Fixed(count = 3), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier .fillMaxSize() .background(MaterialTheme.colors.background) ) { items(state.specialClubs) { club -> SpecialClubItem( state = club, iconId = club.image, clubTitle = club.name, modifier = Modifier.aspectRatio(1f), onClick = onClubClick ) } } } @Preview @Composable private fun Preview() { }
11
Kotlin
19
24
7589d73a400c78ecfa94b24d87189b4f5e01de9b
8,730
Clubs
Apache License 2.0
src/org/elixir_lang/elixir/configuration/Factory.kt
Deni7777
329,010,568
true
{"Java": 1870668, "Kotlin": 1739687, "Elixir": 912079, "HTML": 74766, "Lex": 69192, "Makefile": 499}
package org.elixir_lang.elixir.configuration import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.RunConfiguration import com.intellij.openapi.project.Project import org.elixir_lang.elixir.Configuration object Factory : ConfigurationFactory(Type.getInstance()) { override fun createTemplateConfiguration(project: Project): RunConfiguration = Configuration("Elixir", project, this) }
0
Java
0
1
aca1883ea06722a469a5b4bee61e1781d315c45a
459
intellij-elixir
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppslaunchpadauth/service/authentication/BasicAuthenticationTest.kt
ministryofjustice
650,525,398
false
{"Kotlin": 210577, "HTML": 2363, "Dockerfile": 1146}
package uk.gov.justice.digital.hmpps.hmppslaunchpadauth.service.authentication import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.Mock import org.mockito.Mockito import org.mockito.junit.jupiter.MockitoExtension import org.springframework.http.HttpStatus import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.constant.AuthServiceConstant.Companion.ACCESS_DENIED_MSG import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.exception.ApiException import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.model.AuthorizationGrantType import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.model.Client import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.model.Scope import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.service.ClientService import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.utils.LOGO_URI import uk.gov.justice.digital.hmpps.hmppslaunchpadauth.utils.REDIRECT_URI import java.util.* @ExtendWith(MockitoExtension::class) class BasicAuthenticationTest { @Mock private lateinit var clientService: ClientService private lateinit var encoder: BCryptPasswordEncoder private lateinit var basicAuthentication: BasicAuthentication @BeforeEach fun setUp() { encoder = BCryptPasswordEncoder() basicAuthentication = BasicAuthentication(clientService, encoder) } @AfterEach fun tearDown() { } @Test fun `authenticate valid username and password`() { val password = UUID.randomUUID().toString() val scopes = setOf(Scope.USER_BASIC_READ, Scope.USER_BOOKING_READ) val grants = setOf(AuthorizationGrantType.AUTHORIZATION_CODE) val redirectUri = REDIRECT_URI val logoUri = LOGO_URI val id = UUID.randomUUID() val client = Client( id, encoder.encode(password), scopes, grants, setOf(redirectUri), true, true, "Test App", logoUri, "Test Description", ) Mockito.`when`(clientService.getClientById(id)).thenReturn(Optional.of(client)) val authHeader = "Basic " + Base64.getEncoder().encodeToString("$id:$password".toByteArray(Charsets.UTF_8)) val authenticationInfo = basicAuthentication.authenticate(authHeader) assertEquals(authenticationInfo.clientId, id) } @Test fun `authenticate invalid username and password`() { val password = <PASSWORD>() val scopes = setOf(Scope.USER_BASIC_READ, Scope.USER_BOOKING_READ) val grants = setOf(AuthorizationGrantType.AUTHORIZATION_CODE) val redirectUri = REDIRECT_URI val logoUri = LOGO_URI val id = UUID.randomUUID() val client = Client( id, encoder.encode(password), scopes, grants, setOf(redirectUri), true, true, "Test App", logoUri, "Test Description", ) Mockito.`when`(clientService.getClientById(id)).thenReturn(Optional.of(client)) val authHeader = "Basic " + Base64.getEncoder().encodeToString("$id:randompassword".toByteArray(Charsets.UTF_8)) val exception = assertThrows(ApiException::class.java) { basicAuthentication.authenticate(authHeader) } assertEquals(exception.message, ACCESS_DENIED_MSG) assertEquals(HttpStatus.FORBIDDEN, exception.code) } @Test fun `authenticate when client do not exist`() { val password = UUID.randomUUID().toString() val scopes = setOf(Scope.USER_BASIC_READ, Scope.USER_BOOKING_READ) val grants = setOf(AuthorizationGrantType.AUTHORIZATION_CODE) val redirectUri = REDIRECT_URI val logoUri = LOGO_URI val id = UUID.randomUUID() val client = Client( id, encoder.encode(password), scopes, grants, setOf(redirectUri), true, true, "Test App", logoUri, "Test Description", ) Mockito.`when`(clientService.getClientById(id)).thenReturn(Optional.empty()) val authHeader = "Basic " + Base64.getEncoder().encodeToString("$id:$password".toByteArray(Charsets.UTF_8)) val exception = assertThrows(ApiException::class.java) { basicAuthentication.authenticate(authHeader) } assertEquals(HttpStatus.FORBIDDEN, exception.code) } @Test fun `authenticate when client is not enabled`() { val password = UUID.randomUUID().toString() val scopes = setOf(Scope.USER_BASIC_READ, Scope.USER_BOOKING_READ) val grants = setOf(AuthorizationGrantType.AUTHORIZATION_CODE) val redirectUri = REDIRECT_URI val logoUri = LOGO_URI val id = UUID.randomUUID() val client = Client( id, encoder.encode(password), scopes, grants, setOf(redirectUri), false, true, "Test App", logoUri, "Test Description", ) Mockito.`when`(clientService.getClientById(id)).thenReturn(Optional.of(client)) val authHeader = "Basic " + Base64.getEncoder().encodeToString("$id:$password".toByteArray(Charsets.UTF_8)) val exception = assertThrows(ApiException::class.java) { basicAuthentication.authenticate(authHeader) } assertEquals(HttpStatus.FORBIDDEN, exception.code) } @Test fun `authenticate when auth header do not contain Basic`() { val authHeader = Base64.getEncoder().encodeToString("xxx:yyy".toByteArray(Charsets.UTF_8)) val exception = assertThrows(ApiException::class.java) { basicAuthentication.authenticate(authHeader) } assertEquals(HttpStatus.FORBIDDEN, exception.code) } }
1
Kotlin
0
0
b5445d86dbf33428e6e91cdad1495f768b5da134
5,692
hmpps-launchpad-auth
MIT License
solana/src/main/java/com/solana/api/getFeeRateGovernor.kt
metaplex-foundation
378,984,962
false
{"Kotlin": 557848}
package com.solana.api import com.solana.networking.RpcRequest import com.solana.networking.SolanaResponseSerializer import com.solana.networking.makeRequestResult import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlinx.serialization.Serializable class GetFeeRateGovernorRequest : RpcRequest() { override val method: String = "getFeeRateGovernor" } @Serializable data class FeeRateGovernor ( val burnPercent: Long, val maxLamportsPerSignature: Long, val minLamportsPerSignature: Long, val targetLamportsPerSignature: Long, val targetSignaturesPerSlot: Long ) @Serializable data class FeeRateGovernorInfo ( val feeRateGovernor: FeeRateGovernor ) internal fun GetFeeRateGovernorSerializer() = SolanaResponseSerializer(FeeRateGovernorInfo.serializer()) fun Api.getFeeRateGovernor(onComplete: ((Result<FeeRateGovernorInfo>) -> Unit)) { CoroutineScope(dispatcher).launch { onComplete(getFeeRateGovernor()) } } suspend fun Api.getFeeRateGovernor(): Result<FeeRateGovernorInfo> = router.makeRequestResult(GetFeeRateGovernorRequest(), GetFeeRateGovernorSerializer()) .let { result -> @Suppress("UNCHECKED_CAST") if (result.isSuccess && result.getOrNull() == null) Result.failure(Error("Can not be null")) else result as Result<FeeRateGovernorInfo> // safe cast, null case handled above }
16
Kotlin
29
58
5e1f014573147284a806d569ca0d7a2f6f1619fb
1,435
SolanaKT
MIT License
Referrer/src/main/java/com/cafebazaar/referrersdk/model/ReferrerDetails.kt
cafebazaar
398,568,692
false
{"Kotlin": 17167, "AIDL": 973}
package com.cafebazaar.referrersdk.model interface ReferrerDetails { val referrer: String? val referrerClickTimestampMilliseconds: Long val installBeginTimestampMilliseconds: Long val appVersion: String? }
0
Kotlin
0
1
5ed368e49ecd7a1d0d86ba6c26db1628371e3236
226
ReferrerSDK
Apache License 2.0
android/app/src/main/java/org/haobtc/onekey/bean/RPCInfoBean.kt
liuzjalex
345,008,092
true
{"Python": 5600099, "Java": 3605223, "Objective-C": 1261302, "Kotlin": 196108, "C": 112074, "Shell": 75462, "Objective-C++": 38491, "HTML": 18116, "Dockerfile": 10616, "NSIS": 7342, "C++": 4476, "JavaScript": 2732, "Makefile": 969, "Ruby": 944}
package org.haobtc.onekey.bean import com.google.gson.annotations.SerializedName data class RPCInfoBean( @SerializedName("chain_id") val chainId: Int, @SerializedName("rpc") val rpc: String ) data class SignTxResponseBean( @SerializedName("raw") val raw: String?, @SerializedName("tx") val tx: Tx ) data class Tx( @SerializedName("data") val `data`: String, @SerializedName("gas") val gas: String, @SerializedName("gasPrice") val gasPrice: String, @SerializedName("hash") val hash: String, @SerializedName("nonce") val nonce: String, @SerializedName("r") val r: String, @SerializedName("s") val s: String, @SerializedName("to") val to: String, @SerializedName("v") val v: String, @SerializedName("value") val value: String )
8
Python
0
0
99360b85faaab746257b04590f8ebb77d5e8263b
841
electrum
MIT License
elaichi/android/app/src/main/kotlin/org/dscnitrourkela/elaichi/adapters/MailItemsAdapter.kt
Chinmay-KB
329,033,278
true
{"Dart": 190892, "Kotlin": 87210, "Swift": 404, "Objective-C": 37}
package org.dscnitrourkela.elaichi.adapters import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.appcompat.app.AppCompatDelegate import androidx.core.view.isVisible import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.RecyclerView import androidx.webkit.WebSettingsCompat import androidx.webkit.WebViewFeature import org.dscnitrourkela.elaichi.R import org.dscnitrourkela.elaichi.api.data.ParsedMail import org.dscnitrourkela.elaichi.databinding.MailItemsBinding import org.dscnitrourkela.elaichi.others.ApiConstants import org.dscnitrourkela.elaichi.utils.showToast class MailItemsAdapter( private val colors: IntArray, // private val attachmentAdapter: AttachmentAdapter, ) : PagingDataAdapter<ParsedMail, MailItemsAdapter.MailItemsViewHolder>( object : DiffCallBack<ParsedMail>() { override fun areItemsTheSame(oldItem: ParsedMail, newItem: ParsedMail) = oldItem.id == newItem.id }) { private val colorsLength = colors.lastIndex class MailItemsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) var id = 0 var token: String? = null var css: String? = null var view: TextView? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = MailItemsViewHolder( LayoutInflater.from(parent.context).inflate(R.layout.mail_items, parent, false) ) override fun onBindViewHolder(holder: MailItemsViewHolder, position: Int) { val binding = MailItemsBinding.bind(holder.itemView) getItem(position)?.let { mail -> if (position == itemCount - 1) { binding.divider.isVisible = false } view?.text = mail.subject setupWebView(binding) setContent(binding, mail) holder.itemView.setOnClickListener { binding.apply { webView.isVisible = !webView.isVisible // recyclerViewAttachments.isVisible = webView.isVisible textViewEmailDetails.isVisible = webView.isVisible && textViewMailBody.isVisible textViewMailBody.setOnClickListener { textViewEmailDetails.isVisible = !textViewEmailDetails.isVisible } } } } } @SuppressLint("SimpleDateFormat") private fun setContent(binding: MailItemsBinding, mail: ParsedMail) { val color = colors[mail.id % colorsLength] val sender = mail.from?.split(' ') val body = (mail.body + mail.attachments).replace("auth=co", "auth=qp&amp;zauthtoken=$token") + css var address = "" val mailBody = "${sender?.last()}\n${mail.time}" mail.address?.forEach { address += it } binding.apply { textViewSenderName.text = sender?.first() textViewMailBody.text = mailBody textViewEmailDetails.text = address // if (mail.flag?.contains('f') == true) { // imageViewStared.isVisible = true // } if (mail.attachments?.isEmpty() == true) { imageViewAttachment.isVisible = false } // if (mail.flag?.contains('r') == true) { // imageViewReply.isVisible = true // } webView.loadDataWithBaseURL(ApiConstants.BASE_URL, body, "text/html", "utf-8", null) // recyclerViewAttachments.apply { // attachmentAdapter.attachmentsName = mail.attachmentsName // attachmentAdapter.attachmentsLink = mail.attachmentsLink ?: emptyList() // adapter = attachmentAdapter // layoutManager = // LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) // } if (mail.id == id) { // recyclerViewAttachments.isVisible = true if (mail.body.isNullOrEmpty()) { root.showToast("This mail has no content") } } else { webView.isVisible = false } } } @SuppressLint("SetJavaScriptEnabled") private fun setupWebView(binding: MailItemsBinding) { binding.webView.apply { if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) { val darkMode = when (AppCompatDelegate.getDefaultNightMode()) { AppCompatDelegate.MODE_NIGHT_NO -> WebSettingsCompat.FORCE_DARK_OFF else -> WebSettingsCompat.FORCE_DARK_ON } WebSettingsCompat.setForceDark(this.settings, darkMode) } isVerticalScrollBarEnabled = false settings.javaScriptEnabled = true settings.loadsImagesAutomatically = true } } fun setupOnItemClickListener(onClick: ((String) -> Unit)) { // attachmentAdapter.onItemClickListener = onClick } }
0
Dart
0
0
62155984fe02b942b127a0c40d896e8112a1092c
5,132
project-elaichi
MIT License
lib/src/main/java/io/github/staakk/cchart/renderer/LineRenderer.kt
SCOTT-HAMILTON
407,885,345
false
{"Kotlin": 115803, "Shell": 1352}
package io.github.staakk.cchart.renderer import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.* import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.DrawStyle import androidx.compose.ui.graphics.drawscope.Stroke import io.github.staakk.cchart.data.Data fun interface LineDrawer { /** * Draws the line based on provided [points]. * * @param points Points to draw the line with. */ fun RendererScope.draw(points: List<LinePoint>) } fun interface LineBoundingShapeProvider { /** * Provides bounding shapes used for data labels and on click listener of the * [io.github.staakk.cchart.Chart]. * * @param points Points to provide [BoundingShape]s for. */ fun RendererScope.provide(points: List<LinePoint>): List<BoundingShape> } data class LinePoint( val chartPoint: Data<*>, val rendererPoint: Data<*> ) /** * Creates [SeriesRenderer] that renders a line. * * @param lineDrawer A function drawing the line. * @param boundingShapeProvider Provider of the [BoundingShape]s for the rendered line. */ fun lineRenderer( lineDrawer: LineDrawer = lineDrawer(), boundingShapeProvider: LineBoundingShapeProvider = lineBoundingShapeProvider() ) = SeriesRenderer { series -> val rendererScope = RendererScope(this, chartContext) if (series.size < 2) return@SeriesRenderer emptyList() series.getLineInViewport(chartContext.viewport) .map { LinePoint(it, it.toRendererData(chartContext)) } .let { with(rendererScope) { with(lineDrawer) { draw(it) } with(boundingShapeProvider) { provide(it) } } } } fun lineDrawer( brush: Brush = SolidColor(Color.Black), style: DrawStyle = Stroke(width = 5f, cap = StrokeCap.Round), colorFilter: ColorFilter? = null, alpha: Float = 1.0f, blendMode: BlendMode = DrawScope.DefaultBlendMode, ) = LineDrawer { pointsToRender -> drawPath( path = Path().apply { pointsToRender.windowed(2) { moveTo(it[0].rendererPoint.toOffset()) lineTo(it[1].rendererPoint.toOffset()) } close() }, alpha = alpha, brush = brush, style = style, colorFilter = colorFilter, blendMode = blendMode ) } fun lineBoundingShapeProvider(radius: Float = 20f) = LineBoundingShapeProvider { points -> points.map { BoundingShape.Circle( data = it.chartPoint, labelAnchorX = it.rendererPoint.x, labelAnchorY = it.rendererPoint.y, center = it.rendererPoint.toOffset(), radius = radius ) } } private fun Path.moveTo(offset: Offset) = moveTo(offset.x, offset.y) private fun Path.lineTo(offset: Offset) = lineTo(offset.x, offset.y)
0
Kotlin
0
0
39e1b68d22fe0a446466b50e3fd805d107d0a2fc
2,900
PiFan
Apache License 2.0
widgets/src/androidMain/kotlin/dev/icerock/moko/widgets/core/screen/FragmentNavigation.kt
icerockdev
218,209,603
false
null
/* * Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package dev.icerock.moko.widgets.core.screen import androidx.fragment.app.Fragment internal class FragmentNavigation( private val fragment: Fragment ) { fun <S : Screen<*>> routeToScreen(screen: S) { val fm = fragment.childFragmentManager fm.beginTransaction() .replace(android.R.id.content, screen) .addToBackStack(null) .commit() } fun <S : Screen<*>> setScreen(screen: S) { val fm = fragment.childFragmentManager val backStackCount = fm.backStackEntryCount @Suppress("UnusedPrivateMember") for (i in 0 until backStackCount) { fm.popBackStack() } fm.beginTransaction() .replace(android.R.id.content, screen) .commit() } }
40
Kotlin
29
333
63ea65d622f702432a5b5d1f587ba0fb8a81f95e
892
moko-widgets
Apache License 2.0
util/common-util/src/main/kotlin/me/jiniworld/demohx/DateTimeUtils.kt
jiniya22
572,053,773
false
{"Kotlin": 61869}
package me.jiniworld.demohx import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.format.DateTimeFormatter import java.time.temporal.TemporalAdjusters object DateTimeUtils { private const val SIMPLE_PATTERN_MONTH = "yyyyMM" private const val SIMPLE_PATTERN_DATE = "yyyyMMdd" private const val DEFAULT_PATTERN_DATE = "yyyy-MM-dd" private const val DEFAULT_PATTERN_DATETIME = "yyyy-MM-dd HH:mm:ss" private const val DEFAULT_PATTERN_TIME = "HH:mm:ss" private val LOCALTIME_START = LocalTime.of(0, 0) private val LOCALTIME_END = LocalTime.of(23, 59, 59) val FORMATTER_MONTH_SIMPLE: DateTimeFormatter = DateTimeFormatter.ofPattern(SIMPLE_PATTERN_MONTH) val FORMATTER_DATE_SIMPLE: DateTimeFormatter = DateTimeFormatter.ofPattern(SIMPLE_PATTERN_DATE) val FORMATTER_DATE: DateTimeFormatter = DateTimeFormatter.ofPattern(DEFAULT_PATTERN_DATE) val FORMATTER_DATETIME: DateTimeFormatter = DateTimeFormatter.ofPattern(DEFAULT_PATTERN_DATETIME) val FORMATTER_TIME: DateTimeFormatter = DateTimeFormatter.ofPattern(DEFAULT_PATTERN_TIME) fun getFirstDate(month: String): LocalDate = LocalDate.of(Integer.parseInt(month.substring(0, 4)), Integer.parseInt(month.substring(4, 6)), 1) fun getLastDate(month: String): LocalDate = getFirstDate(month).with(TemporalAdjusters.lastDayOfMonth()) fun getFirstDateTime(date: LocalDate): LocalDateTime = LocalDateTime.of(date, LOCALTIME_START) fun getLastDateTime(date: LocalDate): LocalDateTime = LocalDateTime.of(date.with(TemporalAdjusters.lastDayOfMonth()), LOCALTIME_END) fun toString(date: LocalDate): String = date.format(FORMATTER_DATE) fun toString(dateTime: LocalDateTime): String = dateTime.format(FORMATTER_DATETIME) fun toDateString(dateTime: LocalDateTime) : String = dateTime.format(FORMATTER_DATE) }
0
Kotlin
3
6
5a4a6b33553b202f6b0d4bed7e15dfdb4fce80fb
1,903
demo-hexagonal
MIT License
app/src/main/java/com/ribsky/simpleweatherapp/model/days/Forecast.kt
nexy791
374,828,350
false
null
package com.ribsky.simpleweatherapp.model.days import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Forecast( @Json(name = "forecastday") val forecastday: List<Forecastday> )
0
Kotlin
1
2
26dd3e57715db9efcba5d9d1e0bc582e86a3f74c
245
weather
Apache License 2.0
app/src/main/java/org/xm/secret/photo/album/test/EnDecodeListener.kt
devallever
193,356,539
false
{"Java": 483531, "Kotlin": 381585}
package org.xm.secret.photo.album.test //package org.xm.secret.photo.album.function.endecode // //interface EnDecodeListener { // fun onStart() // fun onSuccess(path: String) // fun onFail() //}
1
Java
0
6
d47f46e0f9e61a1fbf32d7cfae0dce135ab75487
204
SecurityPhotoBrowser
Apache License 2.0
src/main/kotlin/com/chaosprojectbr/usermanagerservice/domain/exceptions/UserNotFoundException.kt
chaos-project-br
667,160,108
false
{"Kotlin": 11912}
package com.chaosprojectbr.usermanagerservice.domain.exceptions import org.springframework.http.HttpStatus class UserNotFoundException( reason: String = "User not found!" ) : ApiException(httpStatus = HttpStatus.NOT_FOUND, reason = reason)
0
Kotlin
0
1
083b00079493004912f066f28228bca3e7f445cd
245
user-manager-service
MIT License
src/jsMain/kotlin/app/obyte/client/util/Buffer.kt
pmiklos
279,186,572
false
null
package app.obyte.client.util external class Buffer { companion object { fun from(array: ByteArray): Buffer } fun toString(encoding: String): String }
0
Kotlin
0
0
764c1d779b7b5cdfcb98994cae100ba0b161704d
173
obyte.kt
MIT License
plugins/kotlin/idea/tests/testData/inspectionsLocal/floatingPointLiteralPrecision/doubleRounding6.kt
06needhamt
391,653,369
true
null
// WITH_RUNTIME val x = <caret>1.0000000000000001
0
null
0
0
63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b
51
intellij-community
Apache License 2.0
releases/glory-v0.1/application/src/main/kotlin/notes/application/Main.kt
hua0-richard
743,583,390
false
{"Kotlin": 134039, "Java": 980, "Dockerfile": 164}
package notes.application import javafx.application.Application import javafx.scene.Scene import javafx.scene.control.ScrollPane import javafx.scene.control.SplitPane import javafx.scene.layout.BorderPane import javafx.scene.layout.VBox import javafx.stage.Stage import notes.model.Model import notes.view.Menubar import notes.view.Toolbar import notes.view.View class Main : Application() { private val noteModel = Model() private val noteView = View( noteModel ) override fun start(stage: Stage) { stage.scene = Scene(noteView, 250.0, 150.0) stage.isResizable = true stage.minWidth = 600.0 stage.minHeight = 400.0 stage.isResizable = true stage.title = "Notes" stage.show() } }
0
Kotlin
0
0
5d4a2c0cc5526c1c698854076b94aa79ff9bde14
755
notes
MIT License
app/src/main/java/com/example/jetweatherforecast/navigation/WeatherScreens.kt
ziadesm
456,104,042
false
{"Kotlin": 24739}
package com.example.jetweatherforecast.navigation enum class WeatherScreens { SplashScreen, MainScreen, AboutScreen, FavouriteScreen, SettingsScreen, SearchScreen, }
0
Kotlin
0
0
f5e0b6469b5512d5eb8ae85c43b06026e5265603
190
WeatherCast
Apache License 2.0
android/sdk/src/main/java/clover/studio/sdk/model/Participant.kt
cloverstudio
381,606,636
false
null
package clover.studio.sdk.model class Participant( val displayName: String?, val avatarUrl: String? = null, val isMe: Boolean = false )
0
Kotlin
0
2
3f7e7f4c88b0f95d914645ba235993c46560664b
148
SpikaBroadcast_old
MIT License
subprojects/test-runner/device-provider/model/src/testFixtures/kotlin/com/avito/runner/service/worker/device/StubDeviceCoordinate.kt
avito-tech
230,265,582
false
{"Kotlin": 3574228, "Java": 67252, "Shell": 27656, "Dockerfile": 12799, "Makefile": 7970}
package com.avito.runner.service.worker.device public fun DeviceCoordinate.Local.Companion.createStubInstance( serial: String = "stub" ): DeviceCoordinate.Local = DeviceCoordinate.Local( serial = Serial.Local(serial) )
10
Kotlin
48
390
9d60abdd26fc779dd57aa4f1ad51658b6a245d1e
228
avito-android
MIT License
database-postgres-jdbc/src/commonTest/kotlin/com/github/mejiomah17/yasb/postgres/jdbc/PostgresFromTest.kt
MEJIOMAH17
492,593,605
false
{"Kotlin": 282541}
package com.github.mejiomah17.yasb.postgres.jdbc import com.github.mejiomah17.yasb.core.dsl.from import com.github.mejiomah17.yasb.core.dsl.select import com.github.mejiomah17.yasb.core.jdbc.transaction.JdbcTransactionRepeatableRead import com.github.mejiomah17.yasb.dsl.FromTest import io.kotest.matchers.shouldBe import org.junit.Test import java.sql.PreparedStatement import java.sql.ResultSet import java.sql.Timestamp class PostgresFromTest : FromTest<PostgresJdbcTestTable, ResultSet, PreparedStatement, PostgresJdbcDatabaseDialect, JdbcTransactionRepeatableRead>, PostgresTest() { override fun initSqlScripts(): List<String> { return listOf( "TRUNCATE TABLE test", """INSERT INTO test (a,b,c,d) values ( |'the a', |'the b', |'3e2220cd-e6a5-4eae-a258-6ed41e91c221', |'2022-05-13 02:09:09.683194'::timestamp | ) """.trimMargin() ) } @Test override fun `from_returns_columns`() { transactionFactory().readUncommitted { val row = select(tableTest().a, tableTest().b, PostgresJdbcTestTable.c, PostgresJdbcTestTable.d) .from(tableTest()) .execute() .single() row[tableTest().a] shouldBe "the a" row[tableTest().b] shouldBe "the b" row[PostgresJdbcTestTable.c].toString() shouldBe "3e2220cd-e6a5-4eae-a258-6ed41e91c221" row[PostgresJdbcTestTable.d] shouldBe Timestamp.valueOf("2022-05-13 02:09:09.683194") } } }
0
Kotlin
0
1
9c362916380cb80ded2d8cf2d8b1ec03b34461b7
1,620
yasb
MIT License
AppCheck-ins/app/src/main/java/com/example/iram/check_ins/Util/Network.kt
IramML
141,610,474
false
null
package com.example.iram.check_ins.Util import android.content.Context import android.net.ConnectivityManager import android.support.v7.app.AppCompatActivity import android.util.Log import com.android.volley.Request import com.android.volley.Response import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import com.example.iram.check_ins.Interfaces.HttpResponse import com.example.iram.check_ins.Messages.Errors import com.example.iram.check_ins.Messages.Message class Network(var activity: AppCompatActivity){ fun availableNetwok():Boolean { val connectivityManager = activity.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo = connectivityManager.activeNetworkInfo return networkInfo != null && networkInfo.isConnected } fun httpRequest(context: Context, url:String, httpResponse: HttpResponse){ if(availableNetwok()) { Log.d("URL_SERVICE","$activity $url") val queue = Volley.newRequestQueue(context) val request = StringRequest(Request.Method.GET, url, Response.Listener<String> { response -> httpResponse.httpResponseSuccess(response) }, Response.ErrorListener { error -> Log.d("HTTP_REQUEST", error.message.toString()) Message.messageError(context, Errors.HTTP_ERROR) }) queue.add(request) }else{ Message.messageError(context, Errors.NO_NETWORK_AVAILABLE) } } fun httpPOSTRequest(context: Context, url:String, httpResponse: HttpResponse){ if(availableNetwok()) { val queue = Volley.newRequestQueue(context) val request = StringRequest(Request.Method.POST, url, Response.Listener<String> { response -> httpResponse.httpResponseSuccess(response) }, Response.ErrorListener { error -> Log.d("HTTP_REQUEST", error.message.toString()) Message.messageError(context, Errors.HTTP_ERROR) }) queue.add(request) }else{ Message.messageError(context, Errors.NO_NETWORK_AVAILABLE) } } }
0
Kotlin
0
0
511b10c4207402c0ddd99efde5e8689f07b07fd0
2,202
CheckinsApp
MIT License
shared/src/commonMain/kotlin/com/faltenreich/rhyme/shared/networking/NetworkingClient.kt
Faltenreich
563,960,209
false
{"Kotlin": 49760, "Ruby": 1722, "Swift": 602}
package com.faltenreich.rhyme.shared.networking interface NetworkingClient { suspend fun request(url: String): String }
0
Kotlin
0
1
06846daa015db7875ff0a06111cf7c316e4c2ea2
125
rhyme-kmm
Apache License 2.0
flaircore/src/main/java/com/rasalexman/flaircore/ext/MediatorExt.kt
Rasalexman
134,755,003
false
null
package com.rasalexman.flaircore.ext import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import com.rasalexman.flaircore.interfaces.IAnimator import com.rasalexman.flaircore.interfaces.IMediator /** * Inflate current view component */ fun IMediator.inflateView(layoutId: Int): View = LayoutInflater.from(activity).inflate(layoutId, null) /** * Start Activity with given intant and request code */ fun IMediator.startActivityForResult(intent: Intent, requestCode: Int, options: Bundle? = null) { facade.view.startActivityForResult(intent, requestCode, options) } /** * Start another activity with bundle options or not */ fun IMediator.startActivity(intent: Intent, bundle: Bundle? = null) { bundle?.let { activity.startActivity(intent, it) } ?: activity.startActivity(intent) } /** * Request Permissions from user */ fun IMediator.requestPermissions(permissions: Array<String>, requestCode: Int) { facade.view.requestPermissions(permissions, requestCode) } /** * Check the given permission to be approved by user or system */ fun IMediator.checkSelfPermission(permissionToCheck: String): Int = facade.view.checkSelfPermission(permissionToCheck) /** * Should we show permission description dialog for user */ fun IMediator.shouldShowRequestPermissionRationale(permission: String): Boolean = facade.view.shouldShowRequestPermissionRationale(permission) /** * Register a list of `INotification` interests. * * @param listNotification * array of string notification names * * @param notificator * the callback function * */ fun IMediator.registerListObservers(listNotification: List<String>, notificator: INotificator): IMediator { listNotification.forEach { registerObserver(it, notificator) } return this } /** * Register observer function with notifName * * @param notifName * Name of notification that recieve notificator * * @param notificator * This is simple closure function callback * */ fun IMediator.registerObserver(notifName: String, notificator: INotificator): IMediator { listNotificationInterests.add(notifName) facade.registerObserver(notifName, notificator) return this } /** * Remove observer by given notification name * * @param notifName * Name of notification that recieve notificator */ fun IMediator.removeObserver(notifName: String) { listNotificationInterests.remove(notifName) facade.removeObserver(notifName, this.multitonKey) } /** * Remove all notifications from current IMediator implementation instance */ fun IMediator.removeAllObservers() { listNotificationInterests.forEach { facade.removeObserver(it, this.multitonKey) } listNotificationInterests.clear() } /** * Add current mediator to view stage * * @param popLast * Flag that indicates to need remove last showing mediator from backstack */ fun IMediator.show(animation: IAnimator? = null, popLast: Boolean = false) { facade.showMediator<IMediator>(this.mediatorName, popLast, animation) } /** * Remove current mediator from view stage * * @param animation * Current hide animation * * @param popIt * Flag that indicates to need remove current mediator from backstack */ fun IMediator.hide(animation: IAnimator? = null, popIt: Boolean = false) { facade.hideMediator(this.mediatorName, popIt, animation) } /** * Hide current mediator and remove it from backstack * Then show last added mediator from backstack * * @param animation * Current hiding animation for pop */ fun IMediator.popToBack(animation: IAnimator? = null) { facade.popMediator(this.mediatorName, animation) } /** * Retrieve lazy mediator core by given generic class * * @param mediatorName * Mediator name to be retrieved by lazy function */ inline fun <reified T : IMediator> IMediator.mediatorLazy(mediatorName: String? = null): Lazy<T> = lazy { mediator<T>(mediatorName) } /** * Retrieve lazy mediator core by given generic class * * @param mediatorName * Mediator name to be retrieved */ inline fun <reified T : IMediator> IMediator.mediator(mediatorName: String? = null): T = facade.retrieveMediator(mediatorName) /** * Remove an `IMediator` from the `View` core. */ inline fun <reified T : IMediator> IMediator.removeMediator(mediatorName: String? = null) { facade.removeMediator<T>(mediatorName) } /** * GO Back to given mediatorName(high priority) or Generic class name. * * @param mediatorName * Mediator to which you go back, so if there is no registered mediatorLazy by this name new instance is create as back stacked * * @param animation * Current hiding animation for pop */ inline fun <reified T : IMediator> IMediator.popTo(mediatorName: String? = null, animation: IAnimator? = null) { facade.retrieveMediator<T>(mediatorName).show(animation, true) } /** * Show the given generic mediatorLazy or by name * * @param mediatorName * Mediator name to be showed * * @param builder * Mediator builder lambda use to instantiate */ inline fun <reified T : IMediator> IMediator.showMediator(animation: IAnimator? = null, mediatorName: String? = null, noinline builder:(()->T)? = null) { return when { facade.hasMediator<T>(mediatorName) -> facade.retrieveMediator<T>(mediatorName).show(animation) builder != null -> facade.registerMediator(mediatorName, builder).show(animation) else -> throw RuntimeException("You need to register your mediator first with `builder` function or use reflection package instead") } }
1
Kotlin
6
31
bb4325e958993d8a51f91361080ef6a30018c4b0
5,583
Flair
The Unlicense
app/src/main/java/com/stark/emoji_status_app/ViewUtil.kt
AdityaJain09
461,629,178
false
{"Kotlin": 20955}
package com.stark.emoji_status_app import android.content.Context import android.widget.Toast fun Context.createToast( message: String, length: Int ) = Toast.makeText(this, message, length)
1
Kotlin
0
0
5508052b73d2baf79dc789d61da9318bbe460b6f
200
EmojiStatusApp
Apache License 2.0
server-api/src/main/kotlin/io/github/oleksivio/tl/kbot/server/api/objects/inline/queryresult/InlineQueryResultVideo.kt
oleksivio
145,889,451
false
null
package io.github.oleksivio.tl.kbot.server.api.objects.inline.queryresult import com.fasterxml.jackson.annotation.JsonProperty /** * [InlineQueryResultVideo](https://core.telegram.org/bots/api/#inlinequeryresultvideo) */ data class InlineQueryResultVideo( /** * video_url String A valid URL for the embedded video player or video file */ @JsonProperty("video_url") var videoUrl: String, /** * mime_type String Mime type of the content of video url, “text/html” or “video/mp4” */ @JsonProperty("mime_type") var mimeType: String, /** * thumb_url String URL of the thumbnail (jpeg only) for the video */ @JsonProperty("thumb_url") var thumbUrl: String, /** * video_width Integer Optional. Video width */ @JsonProperty("video_width") var videoWidth: Int? = null, /** * video_height Integer Optional. Video height */ @JsonProperty("video_height") var videoHeight: Int? = null, /** * video_duration Integer Optional. Video duration in seconds */ @JsonProperty("video_duration") var videoDuration: Int? = null, /** * description [String] Optional. Short description of the result */ @JsonProperty("description") var description: String? = null, /** * type String Type of the result */ @JsonProperty("type") val type: String = "video" ) : TitledInlineResult()
0
Kotlin
0
4
d38b5be33c5217a3f91e44394995f112fd6b0ab9
1,443
tl-kbot
Apache License 2.0
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/http/UnsafeTrustManager.kt
Waboodoo
34,525,124
false
{"Kotlin": 1818178, "HTML": 179455, "CSS": 2092, "Python": 1548}
package ch.rmy.android.http_shortcuts.http import android.annotation.SuppressLint import ch.rmy.android.framework.extensions.toChunkedHexString import java.security.MessageDigest import java.security.NoSuchAlgorithmException import java.security.cert.CertificateEncodingException import java.security.cert.CertificateException import java.security.cert.X509Certificate import javax.net.ssl.X509TrustManager @SuppressLint("CustomX509TrustManager") class UnsafeTrustManager(private val expectedFingerprint: ByteArray? = null) : X509TrustManager { @Throws(CertificateException::class) override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) { } @Throws(CertificateException::class) override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) { if (expectedFingerprint == null) { return } val certificate = chain.firstOrNull() ?: throw CertificateException("No certificate found in trust chain") val algorithm = if (expectedFingerprint.size == 32) "SHA-256" else "SHA-1" val fingerprint = certificate.getFingerprint(algorithm) ?: throw CertificateException("Failed to read $algorithm fingerprint") if (!fingerprint.contentEquals(expectedFingerprint)) { throw CertificateException( "Provided certificate did not match expected $algorithm fingerprint.\n" + "Expected ${expectedFingerprint.toChunkedHexString()}\nbut was ${fingerprint.toChunkedHexString()}" ) } } private fun X509Certificate.getFingerprint(algorithm: String): ByteArray? = try { MessageDigest.getInstance(algorithm) .apply { update(encoded) } .digest() } catch (e: NoSuchAlgorithmException) { null } catch (e: CertificateEncodingException) { null } override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray() }
28
Kotlin
102
875
9a11aca0607c965c02de433443a0e57afd8bc2a4
2,057
HTTP-Shortcuts
MIT License
lib/build.gradle.kts
goto1134
576,714,910
false
{"D2": 88216, "Kotlin": 36634, "ASL": 3929}
import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { alias(libs.plugins.kotlin) alias(libs.plugins.dokka) alias(libs.plugins.git.versioning) `maven-publish` signing } description = "Exports Structurizr models and views to D2 format" group = "io.github.goto1134" version = "1.0.1-SNAPSHOT" gitVersioning.apply { refs { tag("v(?<version>.*)") { version = "\${ref.version}" } } } repositories { // Use Maven Central for resolving dependencies. mavenCentral() } dependencies { implementation(kotlin("stdlib-jdk8")) implementation(libs.structurizr.export) testImplementation(libs.structurizr.client) testImplementation(libs.junit.jupyter) testImplementation(kotlin("test-junit5")) } base { archivesName.set(rootProject.name) } val dokkaJavadocJar = tasks.register<Jar>("dokkaJavadocJar") { dependsOn(tasks.dokkaJavadoc) from(tasks.dokkaJavadoc.flatMap { it.outputDirectory }) archiveClassifier.set("javadoc") } tasks.named<Test>("test") { useJUnitPlatform() } tasks.withType<Jar> { manifest { attributes( mapOf( "Implementation-Title" to rootProject.name, "Implementation-Version" to project.version, "Implementation-Vendor" to "goto1134" ) ) } } java { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } tasks.withType<KotlinCompile> { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } } publishing { repositories { maven { val releasesUrl = uri("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") val snapshotsUrl = uri("https://s01.oss.sonatype.org/content/repositories/snapshots/") url = if (version.toString().endsWith("SNAPSHOT")) snapshotsUrl else releasesUrl name = "OSSRH" credentials { val ossrhUsername: String? by project val ossrhPassword: String? by project username = ossrhUsername password = <PASSWORD> } } } publications { create<MavenPublication>("mavenJava") { from(components["java"]) artifactId = base.archivesName.get() artifact(dokkaJavadocJar) artifact(tasks.kotlinSourcesJar) pom { name.set("Structurizr D2 Exporter") description.set(project.description) url.set("https://github.com/goto1134/structurizr-d2-exporter") scm { connection.set("scm:https://github.com/goto1134/structurizr-d2-exporter.git") developerConnection.set("scm:[email protected]:goto1134/structurizr-d2-exporter.git") url.set("https://github.com/goto1134/structurizr-d2-exporter.git") } licenses { license { name.set("The Apache License, Version 2.0") url.set("https://www.apache.org/licenses/LICENSE-2.0.txt") } } developers { developer { id.set("goto1134") name.set("<NAME>") email.set("<EMAIL>") } } } } } } signing { val signingKey: String? by project val signingPassword: String? by project useInMemoryPgpKeys(signingKey, signingPassword) sign(publishing.publications) }
0
D2
1
11
a7699a0a9cf36c54326981c6983935333b05df36
3,721
structurizr-d2-exporter
Apache License 2.0
roboquant/src/main/kotlin/org/roboquant/brokers/sim/FeeModel.kt
neurallayer
406,929,056
false
{"JavaScript": 3008153, "Kotlin": 1583428, "CSS": 1977}
/* * Copyright 2020-2024 Neural Layer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.roboquant.brokers.sim import org.roboquant.brokers.Trade import org.roboquant.brokers.sim.execution.Execution import java.time.Instant /** * Calculate the broker fee/commissions to be used for executed trades. */ interface FeeModel { /** * Returns the fees or commissions applicable for the provided [execution]. The returned value is denoted in the * currency of the underlying asset. * * More advanced fee models can look at past [trades] to avoid over-billing in case of a multi-fill order and * use [time] to perform relevant currency conversions * * Typically, a fee should be a positive value, unless you want to model rebates and other rewards. */ fun calculate(execution: Execution, time: Instant, trades: List<Trade>): Double }
8
JavaScript
38
286
0402d626324d159d2eab9e65977490b1444c5c32
1,408
roboquant
Apache License 2.0
usbhid/src/main/java/co/sedco/usbhid/UsbHidDevice.kt
siqneibi
560,002,451
false
{"Kotlin": 14931}
package co.sedco.usbhid import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.hardware.usb.* import android.util.Log open class UsbHidDevice(appContext: Context, connectionHandler: IUsbConnectionHandler, vid: Int, pid: Int) { companion object { const val TAG = "UsbHidDevice" //USB permission const val ACTION_USB_PERMISSION = "co.sedco.android.USB_PERMISSION" } private val mApplicationContext: Context //USB connection monitoring, if it is your own USB, the connection will return true, and the disconnect will return false private var mConnectionHandler: IUsbConnectionHandler // Vendor ID var vendorId: Int // Device ID var productId: Int // USB management var mUsbManager: UsbManager // Register broadcast private var mPermissionIntent: PendingIntent? = null // Whether there is USB permission var hasPermission = false // USB device var device: UsbDevice? = null // Interface var usbInterface: UsbInterface? = null // Endpoint, write var usbEndpointOut: UsbEndpoint? = null // Endpoint, read var usbEndpointIn: UsbEndpoint? = null // Whether USB is found var status = false // Connect var usbConnection: UsbDeviceConnection? = null // Prompting the user whether to grant permission to use the USB device private val mUsbReceiver: BroadcastReceiver // Find USB device private fun find(vendorId: Int, productId: Int): Boolean { val deviceList = mUsbManager.deviceList if (deviceList.size == 0) Log.w(TAG,"No USB devices") val deviceIterator: Iterator<UsbDevice> = deviceList.values.iterator() var deviceTemp: UsbDevice while (deviceIterator.hasNext()) { deviceTemp = deviceIterator.next() if ((deviceTemp.vendorId == vendorId) && deviceTemp.productId == productId) { device = deviceTemp break } } if (device == null) { mConnectionHandler.onDeviceNotFound() return false } if (mUsbManager.hasPermission(device)) { open() } else { val mPermissionIntent = PendingIntent.getBroadcast( mApplicationContext, 0, Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_ONE_SHOT ) mUsbManager.requestPermission(device, mPermissionIntent) } return true } private fun open(): Boolean { try { if (device == null) return false usbConnection = mUsbManager.openDevice(device) if (usbConnection == null) return false usbInterface = device?.getInterface(0) if (usbInterface == null) return false if (!usbConnection!!.claimInterface(usbInterface, true)) return false for (ii in 0 until usbInterface!!.endpointCount) { val type = usbInterface!!.getEndpoint(ii).type val direction = usbInterface!!.getEndpoint(ii).direction val number = usbInterface!!.getEndpoint(ii).endpointNumber if (type == UsbConstants.USB_ENDPOINT_XFER_INT) { if (direction == UsbConstants.USB_DIR_IN) usbEndpointIn = usbInterface!!.getEndpoint(ii) else usbEndpointOut = usbInterface!!.getEndpoint(ii) } } if (usbEndpointOut == null) return false if (usbEndpointIn == null) return false status = true mConnectionHandler.onDeviceConnected() return true } catch (e: Exception) { return false } } /** * Close the USB connection */ fun close() { if (usbConnection != null) { if (usbInterface != null) { usbConnection?.releaseInterface(usbInterface) usbInterface = null } usbConnection?.close() usbConnection = null } usbEndpointIn = null usbEndpointOut = null device = null status = false mConnectionHandler.onDeviceDisconnected() } /** * Delay to close the USB connection, close the connection after sleep milliseconds * @sleep rest milliseconds */ fun close(sleep: Long) { Thread.sleep(sleep) close() } @Synchronized fun sendCommandWaitResponse(data: ByteArray): Pair<Boolean, ByteArray> { if (!status || (usbConnection == null) || (usbEndpointOut == null) || (usbEndpointIn == null)) return false to ByteArray(0) val response = ByteArray(64) var result = usbConnection?.bulkTransfer(usbEndpointOut, data, data.size, 0) if (result != -1) { result = usbConnection?.bulkTransfer(usbEndpointIn, response, response.size, 3000) } return (result != -1) to response } fun onDestroy() { close() mApplicationContext.unregisterReceiver(mUsbReceiver) } init { mApplicationContext = appContext mConnectionHandler = connectionHandler mUsbManager = mApplicationContext .getSystemService(Context.USB_SERVICE) as UsbManager vendorId = vid productId = pid mUsbReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val action = intent.action // Permission if (ACTION_USB_PERMISSION == action) { synchronized(this) { val device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as UsbDevice? if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { if (device != null) { hasPermission = true open() } } else { if (device != null) { hasPermission = false connectionHandler.onDevicePermissionDenied() } } } } // USB connect monitor if (UsbManager.ACTION_USB_DEVICE_ATTACHED == action) { val dev = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as UsbDevice? if (dev != null) { //In case the user needs to judge both vendorId and productId if (dev.vendorId == vendorId && dev.productId == productId) { device = dev if (mUsbManager.hasPermission(device)) { open() } else { val mPermissionIntent = PendingIntent.getBroadcast( mApplicationContext, 0, Intent(ACTION_USB_PERMISSION), 0) mUsbManager.requestPermission(device, mPermissionIntent) } } } } // USB disconnect monitor if (UsbManager.ACTION_USB_DEVICE_DETACHED == action) { val dev = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as UsbDevice? if (dev != null) { if (device != null && device == dev) { close() } } } } } // Initialize broadcast receiver mPermissionIntent = PendingIntent.getBroadcast(mApplicationContext, 0, Intent( ACTION_USB_PERMISSION ), 0) val filter = IntentFilter(ACTION_USB_PERMISSION) filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED) filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED) mApplicationContext.registerReceiver(mUsbReceiver, filter) // Find USB device find(vendorId, productId) } }
0
Kotlin
1
4
dbdbe1b962d5e93e29c31add63b84a0cc2e1d966
8,541
UsbHid
MIT License
reflekt-plugin/src/main/kotlin/org/jetbrains/reflekt/plugin/generation/ir/IrBuilderExtension.kt
JetBrains-Research
293,503,377
false
{"Kotlin": 397259, "Java": 35379}
package org.jetbrains.reflekt.plugin.generation.ir import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.ir.* import org.jetbrains.kotlin.ir.builders.* import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrEnumEntry import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.impl.* import org.jetbrains.kotlin.ir.symbols.IrClassSymbol import org.jetbrains.kotlin.ir.symbols.impl.IrAnonymousInitializerSymbolImpl import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.name.Name import org.jetbrains.reflekt.plugin.analysis.ir.makeTypeProjection import org.jetbrains.reflekt.plugin.analysis.processor.toReflektVisibility import org.jetbrains.reflekt.plugin.generation.ir.util.* import org.jetbrains.reflekt.plugin.generation.ir.util.irCall import org.jetbrains.reflekt.plugin.utils.getValueArguments /** * Provides utilities for IR generation and transformation: extensions to [IrClass], and to [IrBuilder]. */ interface IrBuilderExtension { val pluginContext: IrPluginContext val irBuiltIns: IrBuiltIns get() = pluginContext.irBuiltIns val generationSymbols: GenerationSymbols @OptIn(ObsoleteDescriptorBasedAPI::class) fun IrClass.contributeAnonymousInitializer(body: IrBlockBodyBuilder.() -> Unit) { factory.createAnonymousInitializer(startOffset, endOffset, origin, IrAnonymousInitializerSymbolImpl(descriptor)) .also { it.parent = this declarations += it it.body = DeclarationIrBuilder(pluginContext, it.symbol, startOffset, endOffset).irBlockBody( startOffset, endOffset, body ) } } fun IrBuilderWithScope.irCheckNotNull(value: IrExpression) = irCall( irBuiltIns.checkNotNullSymbol, typeArguments = listOf(value.type.makeNotNull()), valueArguments = listOf(value), ) fun IrBuilderWithScope.irMapGet(map: IrExpression, key: IrExpression) = irCall(generationSymbols.mapGet, dispatchReceiver = map, valueArguments = listOf(key)) fun IrBuilderWithScope.irTo(left: IrExpression, right: IrExpression) = irCall( generationSymbols.to, typeArguments = listOf(left.type, right.type), extensionReceiver = left, valueArguments = listOf(right) ) fun IrBuilderWithScope.irHashMapOf(keyType: IrType, valueType: IrType, pairs: List<IrExpression>) = irCall( generationSymbols.hashMapOf, typeArguments = listOf(keyType, valueType), valueArguments = listOf( irVarargOut( generationSymbols.pairClass.createType( false, listOf(keyType.makeTypeProjection(), valueType.makeTypeProjection()), ), pairs, ), ), ) fun IrBuilderWithScope.irMutableSetAdd(mutableSet: IrExpression, element: IrExpression) = irCall(generationSymbols.mutableSetAdd, dispatchReceiver = mutableSet, valueArguments = listOf(element)) fun IrBuilderWithScope.irReflektClassImplConstructor(irClassSymbol: IrClassSymbol): IrFunctionAccessExpression { val irClass = irClassSymbol.owner return irCall( generationSymbols.reflektClassImplConstructor, typeArguments = listOf(irClassSymbol.defaultType), valueArguments = listOf( irClassReference(irClassSymbol), irCall( generationSymbols.hashSetOf, typeArguments = listOf(irBuiltIns.annotationType), valueArguments = listOf( irVarargOut(irBuiltIns.annotationType, irClass.annotations.map { irCall( it.symbol, valueArguments = it.getValueArguments().map { arg -> arg?.shallowCopyUndefinedOffset() }) }), ), ), irBoolean(irClass.modality == Modality.ABSTRACT), irBoolean(irClass.isCompanion), irBoolean(irClass.isData), irBoolean(irClass.modality == Modality.FINAL), irBoolean(irClass.isFun), irBoolean(irClass.isInner), irBoolean(irClass.modality == Modality.OPEN), irBoolean(irClass.modality == Modality.SEALED), irBoolean(irClass.isValue), irString(irClass.kotlinFqName.toString()), irCall(generationSymbols.hashSetConstructor), irCall(generationSymbols.hashSetConstructor), irString(irClass.kotlinFqName.shortName().toString()), irGetEnumValue( generationSymbols.reflektVisibilityClass.defaultType, generationSymbols.reflektVisibilityClass .owner .declarations .filterIsInstance<IrEnumEntry>() .first { it.name == Name.identifier( checkNotNull(irClass.visibility.toReflektVisibility()) { "Unsupported visibility of IrClass: ${irClass.visibility}" }.name, ) } .symbol, ), if (irClass.isObject) irGetObject(irClassSymbol) else irNull(), ), ) } } private fun IrExpression.shallowCopyUndefinedOffset(): IrExpression = shallowCopyOrNullUndefinedOffset() ?: error("Not a copyable expression: ${render()}") private fun <T> IrConst<T>.shallowCopyUndefinedOffset() = IrConstImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, type, kind, value ) private fun IrExpression.shallowCopyOrNullUndefinedOffset(): IrExpression? = when (this) { is IrConst<*> -> shallowCopyUndefinedOffset() is IrGetEnumValue -> IrGetEnumValueImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, type, symbol ) is IrGetObjectValue -> IrGetObjectValueImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, type, symbol ) is IrGetValueImpl -> IrGetValueImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, type, symbol, origin ) is IrErrorExpressionImpl -> IrErrorExpressionImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, type, description ) is IrConstructorCall -> IrConstructorCallImpl( startOffset, endOffset, type, symbol, typeArgumentsCount, constructorTypeArgumentsCount, valueArgumentsCount, origin, source, ).also { it.copyTypeAndValueArgumentsFrom(this) } else -> null }
13
Kotlin
9
325
ae53618880e5eb610ddeb2792d63208eade951a8
7,343
reflekt
Apache License 2.0
app/src/main/java/com/example/hobbyfi/paging/sources/MessageSearchSource.kt
GGLozanov
310,078,278
false
null
package com.example.hobbyfi.paging.sources import androidx.paging.PagingSource import androidx.paging.PagingState import com.example.hobbyfi.api.HobbyfiAPI import com.example.hobbyfi.models.data.Message import com.example.hobbyfi.shared.PrefConfig class MessageSearchSource( private val prefConfig: PrefConfig, private val hobbyfiAPI: HobbyfiAPI, private val chatroomId: Long, private val query: String ): PagingSource<Int, Message>() { override fun getRefreshKey(state: PagingState<Int, Message>): Int? { return state.anchorPosition?.let { anchorPosition -> val anchorPage = state.closestPageToPosition(anchorPosition) anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1) } } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Message> = try { // Start refresh at page 1 if undefined. val nextPage = params.key ?: 1 val response = hobbyfiAPI.fetchMessages( prefConfig.getAuthUserToken()!!, chatroomId, nextPage, query ) LoadResult.Page( response.modelList, prevKey = if (nextPage == DEFAULT_PAGE_INDEX) null else nextPage - 1, nextKey = if (response.modelList.isEmpty()) null else nextPage + 1 ) } catch (e: Exception) { LoadResult.Error(e) } companion object { const val DEFAULT_PAGE_INDEX = 1 } }
0
Kotlin
3
1
afb30f72a4213c924fdf8e3cb5eefd76d6a0d320
1,518
Hobbyfi
Apache License 2.0
kalexa-model/src/main/kotlin/com/hp/kalexa/model/response/dsl/TestStatusCodeBuilder.kt
HPInc
164,478,295
false
null
/* * Copyright 2018 HP Development Company, L.P. * SPDX-License-Identifier: MIT */ package com.hp.kalexa.model.response.dsl import com.hp.kalexa.model.connections.Context import com.hp.kalexa.model.connections.test.TestStatusCode import com.hp.kalexa.model.response.annotation.AlexaResponseDsl @AlexaResponseDsl class TestStatusCodeBuilder { var version: String = "" var context: Context? = null lateinit var code: String fun build() = TestStatusCode(code, version, context) }
0
Kotlin
1
17
e6674eeb24c255aef1859a62a65b805effdc9676
500
kalexa-sdk
MIT License
app/src/main/java/com/example/quiz/data/remote/QuestionService.kt
nikitamarysolomanpvt
427,849,376
false
{"Kotlin": 44795, "Java": 790}
package com.example.quiz.data.remote import com.example.quiz.data.entities.SearchResults import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface QuestionService { @GET("photos_public.gne?format=json&nojsoncallback=1") suspend fun getAllQuestions(@Query(value = "tags") searchTitle: String): Response<SearchResults> }
0
Kotlin
0
0
02d2401abe10cf49a9ccfe240670c9c773951e83
362
FlickrSearchAssignment
Apache License 2.0
android/app/src/main/kotlin/com/example/tepatEngineerFlutter/MainActivity.kt
arifikhsan
387,397,548
false
{"Dart": 10675, "HTML": 3735, "Shell": 571, "Swift": 404, "Kotlin": 137, "Objective-C": 38}
package com.example.tepatEngineerFlutter import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
eb2f975c040eb1ccc8a66a5155835a89635e4512
137
tepat_engineer_flutter
MIT License
data-model/src/main/kotlin/dev/arli/sunnyday/model/LocationWithCurrentWeather.kt
alipovatyi
614,818,086
false
null
package dev.arli.sunnyday.model import dev.arli.sunnyday.model.location.Coordinates data class LocationWithCurrentWeather( val coordinates: Coordinates, val name: String?, val isCurrent: Boolean, val currentWeather: CurrentWeather? )
0
Kotlin
0
0
f272db479e91de350368a8573df6ddebb22e0742
252
sunny-day-android
Apache License 2.0
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/configuration/ui/PackageSearchGeneralConfigurable.kt
06needhamt
391,653,369
true
null
package com.jetbrains.packagesearch.intellij.plugin.configuration.ui import com.intellij.openapi.options.SearchableConfigurable import com.intellij.openapi.project.Project import com.intellij.ui.TitledSeparator import com.intellij.ui.components.labels.LinkLabel import com.intellij.util.ui.FormBuilder import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.extensibility.ConfigurableContributor import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel class PackageSearchGeneralConfigurable(project: Project) : SearchableConfigurable { companion object { const val ID = "preferences.packagesearch.PackageSearchGeneralConfigurable" } override fun getId(): String = ID override fun getDisplayName(): String = PackageSearchBundle.message("packagesearch.configuration.title") private val extensions = ConfigurableContributor.extensionsForProject(project) .sortedBy { it.javaClass.simpleName } .map { it.createDriver() } private var modified: Boolean = false private val builder = FormBuilder.createFormBuilder() override fun createComponent(): JComponent? { // Extensions extensions.forEach { it.contributeUserInterface(builder) } // General options builder.addComponent( TitledSeparator(PackageSearchBundle.message("packagesearch.configuration.general")), 0 ) // Reset defaults builder.addComponent(JLabel()) builder.addComponent( LinkLabel<Any>( PackageSearchBundle.message("packagesearch.configuration.restore.defaults"), null ) { _, _ -> restoreDefaults() } ) builder.addComponentFillVertically(JPanel(), 0) return builder.panel } override fun isModified() = modified || extensions.any { it.isModified() } override fun reset() { for (contributor in extensions) { contributor.reset() } modified = false PackageSearchEventsLogger.logPreferencesReset() } private fun restoreDefaults() { for (contributor in extensions) { contributor.restoreDefaults() } modified = true } override fun apply() { for (contributor in extensions) { contributor.apply() } } }
0
null
0
0
63d7b8030e4fdefeb4760e511e289f7e6b3a5c5b
2,528
intellij-community
Apache License 2.0
app/src/androidTest/java/com/akmere/iddog/LoginActivityInstrumentedTest.kt
akmerejf
288,873,364
false
null
package com.akmere.iddog import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.MutableLiveData import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.* import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.RootMatchers.withDecorView import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.ActivityTestRule import com.akmere.iddog.ui.dogfeed.DogFeedViewModel import com.akmere.iddog.ui.login.* import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.MockK import kotlinx.coroutines.ExperimentalCoroutinesApi import org.hamcrest.Matchers.containsString import org.hamcrest.Matchers.not import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.context.loadKoinModules import org.koin.core.context.stopKoin import org.koin.dsl.module import org.koin.test.KoinTest /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @ExperimentalCoroutinesApi @RunWith(AndroidJUnit4::class) class LoginActivityInstrumentedTest : KoinTest { @get:Rule val instantExecutorTask = InstantTaskExecutorRule() @get:Rule var activityRule: ActivityTestRule<LoginActivity> = ActivityTestRule(LoginActivity::class.java, true, false) @MockK(relaxed = true) private lateinit var loginViewModel: LoginViewModel @MockK(relaxed = true) private lateinit var dogFeedViewModel: DogFeedViewModel @Before fun setup() { MockKAnnotations.init(this) loadKoinModules(module { viewModel { loginViewModel } viewModel { dogFeedViewModel } }) } @After fun tearDown() { activityRule.finishActivity() stopKoin() } private val loginResult = MutableLiveData<LoginResult>() private val loginFormState = MutableLiveData<LoginFormState>() @Test fun loginSuccessful() { val mockEmail = "<EMAIL>" every { loginViewModel.loginResult } returns loginResult every { loginViewModel.loginFormState } returns loginFormState every { loginViewModel.loginDataChanged(any()) } returns Unit activityRule.launchActivity(null) onView(withId(R.id.email)).perform( typeText(mockEmail), closeSoftKeyboard() ) activityRule.runOnUiThread { loginFormState.postValue(LoginFormState(emailError = null, isDataValid = true)) } onView(withId(R.id.login)).check(matches(isEnabled())) onView(withId(R.id.login)).perform(click()) onView(withId(R.id.loading)) .check(matches(isDisplayed())) activityRule.runOnUiThread { loginResult.postValue(LoginResult(LoggedInUserView(mockEmail))) } onView(withId(R.id.loading)) .check(matches(withEffectiveVisibility(Visibility.GONE))) onView( withText( containsString( activityRule.activity.getString( R.string.welcome, mockEmail ) ) ) ).inRoot(withDecorView(not(activityRule.activity.window.decorView))) .check(matches(isDisplayed())) } }
0
Kotlin
0
0
7b5eb4283fe95d9c51c745f6e53cc7ee8abc040a
3,590
iddog
MIT License
src/test/kotlin/br/com/zup/matheuscarv69/pix/endpoints/registra/RegistrarChaveEndpointTest.kt
matheuscarv69
385,392,461
true
{"Kotlin": 90937, "Smarty": 2172, "Dockerfile": 163}
package br.com.zup.matheuscarv69.pix.endpoints.registra import br.com.zup.matheuscarv69.KeyManagerRegistraGrpcServiceGrpc import br.com.zup.matheuscarv69.RegistraChavePixRequest import br.com.zup.matheuscarv69.TipoDeChaveGrpc import br.com.zup.matheuscarv69.TipoDeContaGrpc import br.com.zup.matheuscarv69.clients.bcb.* import br.com.zup.matheuscarv69.clients.itau.ContasDeClientesItauClient import br.com.zup.matheuscarv69.clients.itau.DadosDaContaResponse import br.com.zup.matheuscarv69.clients.itau.InstituicaoResponse import br.com.zup.matheuscarv69.clients.itau.TitularResponse import br.com.zup.matheuscarv69.pix.entities.chave.ChavePix import br.com.zup.matheuscarv69.pix.entities.chave.ContaAssociada import br.com.zup.matheuscarv69.pix.entities.chave.TipoDeChave import br.com.zup.matheuscarv69.pix.entities.chave.TipoDeConta import br.com.zup.matheuscarv69.pix.repositories.ChavePixRepository import io.grpc.ManagedChannel import io.grpc.Status import io.grpc.StatusRuntimeException import io.micronaut.context.annotation.Factory import io.micronaut.grpc.annotation.GrpcChannel import io.micronaut.grpc.server.GrpcServerChannel import io.micronaut.http.HttpResponse import io.micronaut.test.annotation.MockBean import io.micronaut.test.extensions.junit5.annotation.MicronautTest import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.mockito.Mockito import java.time.LocalDateTime import java.util.* import javax.inject.Inject import javax.inject.Singleton @MicronautTest(transactional = false) internal class RegistrarChaveEndpointTest( @Inject val repository: ChavePixRepository, @Inject val grpcClient: KeyManagerRegistraGrpcServiceGrpc.KeyManagerRegistraGrpcServiceBlockingStub ) { @Inject lateinit var itauClient: ContasDeClientesItauClient @Inject lateinit var bcbClient: BcbClient companion object { val CLIENT_ID = UUID.randomUUID()!! } /** * 1. Cenario feliz - OK * 2. Nao deve registrar quando a chave pix ja existe - OK * 3. Nao deve registrar chave pix quando o cliente nao for encontrado - OK * 4. Nao deve registrar chave pix quando os parametros estiverem invalidos - OK * */ @BeforeEach fun setup() { repository.deleteAll() } @Test fun `Deve cadastrar a chave pix`() { // Cenario Mockito.`when`(itauClient.buscaContaPorTipo(CLIENT_ID.toString(), TipoDeConta.CONTA_CORRENTE.name)) .thenReturn(HttpResponse.ok(dadosDaContaResponse())) Mockito.`when`(bcbClient.registraPix(createPixKeyRequest())) .thenReturn(HttpResponse.created(createPixKeyResponse())) // acao val response = grpcClient.registrar( RegistraChavePixRequest .newBuilder() .setClienteId(CLIENT_ID.toString()) .setTipoDeChave(TipoDeChaveGrpc.CPF) .setChave("02467781054") .setTipoDeConta(TipoDeContaGrpc.CONTA_CORRENTE) .build() ) // validacao with(response) { assertNotNull(pixId) assertTrue(repository.existsByPixId(pixId)) } } @Test fun `Nao deve registrar chave pix quando ocorrer erro no BcbClient`() { // cenario Mockito.`when`(itauClient.buscaContaPorTipo(CLIENT_ID.toString(), TipoDeConta.CONTA_CORRENTE.name)) .thenReturn(HttpResponse.ok(dadosDaContaResponse())) Mockito.`when`(bcbClient.registraPix(createPixKeyRequest())) .thenReturn(HttpResponse.unprocessableEntity()) // acao val errors = assertThrows<StatusRuntimeException> { val response = grpcClient.registrar( RegistraChavePixRequest .newBuilder() .setClienteId(CLIENT_ID.toString()) .setTipoDeChave(TipoDeChaveGrpc.CPF) .setChave("02467781054") .setTipoDeConta(TipoDeContaGrpc.CONTA_CORRENTE) .build() ) } // validacao with(errors) { assertEquals(Status.FAILED_PRECONDITION.code, status.code) assertEquals("Erro ao registrar chave Pix no Banco Central do Brasil (BCB)", status.description) } } @Test fun `Nao deve registrar quando a chave pix ja existe`() { // cenario repository.save( ChavePix( clienteId = CLIENT_ID, tipoDeChave = TipoDeChave.EMAIL, chave = "<EMAIL>", tipoDeConta = TipoDeConta.CONTA_CORRENTE, conta = dadosDaContaResponse().toModel() ) ) // acao val errors = assertThrows<StatusRuntimeException> { grpcClient.registrar( RegistraChavePixRequest.newBuilder() .setClienteId(CLIENT_ID.toString()) .setTipoDeChave(TipoDeChaveGrpc.EMAIL) .setChave("<EMAIL>") .setTipoDeConta(TipoDeContaGrpc.CONTA_CORRENTE) .build() ) } // validacao with(errors) { assertEquals(Status.ALREADY_EXISTS.code, status.code) assertEquals("Chave Pix '<EMAIL>' existente", status.description) } } @Test fun `Nao deve registrar chave pix quando o cliente nao for encontrado`() { // cenario Mockito.`when`( itauClient.buscaContaPorTipo( clienteId = CLIENT_ID.toString(), tipo = TipoDeConta.CONTA_CORRENTE.name ) ).thenReturn(HttpResponse.notFound()) // acao val errors = assertThrows<StatusRuntimeException> { grpcClient.registrar( RegistraChavePixRequest.newBuilder() .setClienteId(CLIENT_ID.toString()) .setTipoDeChave(TipoDeChaveGrpc.EMAIL) .setChave("<EMAIL>") .setTipoDeConta(TipoDeContaGrpc.CONTA_CORRENTE) .build() ) } // validacao with(errors) { assertEquals(Status.FAILED_PRECONDITION.code, status.code) assertEquals("Cliente não encontrado no Itau", status.description) } } @Test fun `Nao deve registrar chave pix quando os parametros estiverem invalidos`() { // cenario // acao val erros = assertThrows<StatusRuntimeException> { grpcClient.registrar(RegistraChavePixRequest.newBuilder().build()) } // validacao with(erros) { assertEquals(Status.INVALID_ARGUMENT.code, status.code) assertEquals("Dados inválidos", status.description) } } // Mockando o itau client @MockBean(ContasDeClientesItauClient::class) fun itauClientMock(): ContasDeClientesItauClient { return Mockito.mock(ContasDeClientesItauClient::class.java) } // Mockando o bcb client @MockBean(BcbClient::class) fun bcbClient(): BcbClient? { return Mockito.mock(BcbClient::class.java) } // cria um client grpc pro endpoint de Registrar chave pix @Factory class Clients() { @Singleton fun blockingStub(@GrpcChannel(GrpcServerChannel.NAME) channel: ManagedChannel): KeyManagerRegistraGrpcServiceGrpc.KeyManagerRegistraGrpcServiceBlockingStub? { return KeyManagerRegistraGrpcServiceGrpc.newBlockingStub(channel) } } // response itau request private fun dadosDaContaResponse() = DadosDaContaResponse( tipo = TipoDeContaGrpc.CONTA_CORRENTE.name, instituicao = InstituicaoResponse(nome = "ITAÚ UNIBANCO S.A.", ispb = ContaAssociada.ITAU_UNIBANCO_ISPB), agencia = "0001", numero = "291900", titular = TitularResponse(nome = "<NAME>", cpf = "02467781054") ) private fun createPixKeyRequest(): CreatePixKeyRequest { return CreatePixKeyRequest( keyType = PixKeyType.CPF, key = "02467781054", bankAccount = bankAccount(), owner = owner() ) } private fun createPixKeyResponse(): CreatePixKeyResponse { return CreatePixKeyResponse( keyType = PixKeyType.CPF, key = "02467781054", bankAccount = bankAccount(), owner = owner(), createdAt = LocalDateTime.now() ) } private fun bankAccount(): BankAccount { return BankAccount( participant = ContaAssociada.ITAU_UNIBANCO_ISPB, branch = "0001", accountNumber = "291900", accountType = BankAccount.AccountType.CACC ) } private fun owner(): Owner { return Owner( type = Owner.OwnerType.NATURAL_PERSON, name = "<NAME>", taxIdNumber = "02467781054" ) } }
0
Kotlin
0
0
009a63ad017d62741e2a92d2e83e3c8cf537f94a
9,158
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
src/main/kotlin/com/thomas/needham/ftl/backend/EnumOpcodes.kt
FTL-Lang
71,374,301
false
null
/* The MIT License (MIT) FTL-Compiler Copyright (c) 2016 thoma 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.thomas.needham.ftl.backend /** * Container class for Opcodes Enum */ public class EnumOpcodes { /** * Enum containing a list of JVM 6 Opcodes */ enum class Opcodes(val value: Int) { nop(0x00), aconst_null(0x01), iconst_m1(0x02), iconst_0(0x03), iconst_1(0x04), iconst_2(0x05), iconst_3(0x06), iconst_4(0x07), iconst_5(0x08), lconst_0(0x09), lconst_1(0x0a), fconst_0(0x0b), fconst_1(0x0c), fconst_2(0x0d), dconst_0(0x0e), dconst_1(0x0f), bipush(0x10), sipush(0x11), ldc(0x12), ldc_w(0x13), ldc2_w(0x14), iload(0x15), lload(0x16), fload(0x17), dload(0x18), aload(0x19), iload_0(0x1a), iload_1(0x1b), iload_2(0x1c), iload_3(0x1d), lload_0(0x1e), lload_1(0x1f), lload_2(0x20), lload_3(0x21), fload_0(0x22), fload_1(0x23), fload_2(0x24), fload_3(0x25), dload_0(0x26), dload_1(0x27), dload_2(0x28), dload_3(0x29), aload_0(0x2a), aload_1(0x2b), aload_2(0x2c), aload_3(0x2d), iaload(0x2e), laload(0x2f), faload(0x30), daload(0x31), aaload(0x32), baload(0x33), caload(0x34), saload(0x35), istore(0x36), lstore(0x37), fstore(0x38), dstore(0x39), astore(0x3a), istore_0(0x3b), istore_1(0x3c), istore_2(0x3d), istore_3(0x3e), lstore_0(0x3f), lstore_1(0x40), lstore_2(0x41), lstore_3(0x42), fstore_0(0x43), fstore_1(0x44), fstore_2(0x45), fstore_3(0x46), dstore_0(0x47), dstore_1(0x48), dstore_2(0x49), dstore_3(0x4a), astore_0(0x4b), astore_1(0x4c), astore_2(0x4d), astore_3(0x4e), iastore(0x4f), lastore(0x50), fastore(0x51), dastore(0x52), aastore(0x53), bastore(0x54), castore(0x55), sastore(0x56), pop(0x57), pop2(0x58), dup(0x59), dup_x1(0x5a), dup_x2(0x5b), dup2(0x5c), dup2_x1(0x5d), dup2_x2(0x5e), swap(0x5f), iadd(0x60), ladd(0x61), fadd(0x62), dadd(0x63), isub(0x64), lsub(0x65), fsub(0x66), dsub(0x67), imul(0x68), lmul(0x69), fmul(0x6a), dmul(0x6b), idiv(0x6c), ldiv(0x6d), fdiv(0x6e), ddiv(0x6f), irem(0x70), lrem(0x71), frem(0x72), drem(0x73), ineg(0x74), lneg(0x75), fneg(0x76), dneg(0x77), ishl(0x78), lshl(0x79), ishr(0x7a), lshr(0x7b), iushr(0x7c), lushr(0x7d), iand(0x7e), land(0x7f), ior(0x80), lor(0x81), ixor(0x82), lxor(0x83), iinc(0x84), i2l(0x85), i2f(0x86), i2d(0x87), l2i(0x88), l2f(0x89), l2d(0x8a), f2i(0x8b), f2l(0x8c), f2d(0x8d), d2i(0x8e), d2l(0x8f), d2f(0x90), i2b(0x91), i2c(0x92), i2s(0x93), lcmp(0x94), fcmpl(0x95), fcmpg(0x96), dcmpl(0x97), dcmpg(0x98), ifeq(0x99), ifne(0x9a), iflt(0x9b), ifge(0x9c), ifgt(0x9d), ifle(0x9e), if_icmpeq(0x9f), if_icmpne(0xa0), if_icmplt(0xa1), if_icmpge(0xa2), if_icmpgt(0xa3), if_icmple(0xa4), if_acmpeq(0xa5), if_acmpne(0xa6), goto(0xa7), jsr(0xa8), ret(0xa9), tableswitch(0xaa), lookupswitch(0xab), ireturn(0xac), lreturn(0xad), freturn(0xae), dreturn(0xaf), areturn(0xb0), i_return(0xb1), getstatic(0xb2), putstatic(0xb3), getfield(0xb4), putfield(0xb5), invokevirtual(0xb6), invokespecial(0xb7), invokestatic(0xb8), invokeinterface(0xb9), xxxunusedxxx1(0xba), new(0xbb), newarray(0xbc), anewarray(0xbd), arraylength(0xbe), athrow(0xbf), checkcast(0xc0), instanceof(0xc1), monitorenter(0xc2), monitorexit(0xc3), wide(0xc4), multianewarray(0xc5), ifnull(0xc6), ifnonnull(0xc7), goto_w(0xc8), jsr_w(0xc9), breakpoint(0xca), impdep1(0xfe), impdep2(0xff) } }
0
Kotlin
0
3
0bb9b2624c062bf2fcc90b647dcb26513d9ce6cc
4,707
FTL-Compiler
MIT License
reaktive/src/commonMain/kotlin/com/badoo/reaktive/single/AsCompletable.kt
dmitryustimov
199,810,592
true
{"Kotlin": 621904, "Swift": 3221, "HTML": 1086}
package com.badoo.reaktive.single import com.badoo.reaktive.base.ErrorCallback import com.badoo.reaktive.base.Observer import com.badoo.reaktive.base.subscribeSafe import com.badoo.reaktive.completable.Completable import com.badoo.reaktive.completable.completableUnsafe fun Single<*>.asCompletable(): Completable = completableUnsafe { observer -> subscribeSafe( object : SingleObserver<Any?>, Observer by observer, ErrorCallback by observer { override fun onSuccess(value: Any?) { observer.onComplete() } } ) }
0
Kotlin
0
0
08a6ee6efb9e08feba276ba23769671e070452fc
612
Reaktive
Apache License 2.0
src/main/kotlin/icu/takeneko/nm/server/plugins/Routing.kt
NekoApplications
733,859,604
false
{"Kotlin": 42520}
package icu.takeneko.nm.server.plugins import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.encodeToString import kotlinx.serialization.json.decodeFromStream import icu.takeneko.nm.data.AgentUpstreamData import icu.takeneko.nm.data.QueryAllResult import icu.takeneko.nm.data.QueryResult import icu.takeneko.nm.data.Result import icu.takeneko.nm.server.Server import icu.takeneko.nm.server.auth import icu.takeneko.nm.server.fs.DataQueryParameters import icu.takeneko.nm.server.fs.FileStore import icu.takeneko.nm.util.* val keyMD5: String by lazy { Server.serverConfig.serverAccessKey.md5() } val userCredentials by lazy { buildMap { Server.serverConfig.agents.forEach { this += it.md5() to it } } } @OptIn(ExperimentalSerializationApi::class) fun Application.configureRouting() { routing { get("/") { call.respondText(getVersionInfoString("NekoMonitor::server")) } route("/status") { post("upload") { return@post auth { try { val content = call.receive<AgentUpstreamData>() [email protected](content.toString()) val pool = FileStore[content.agentName] val dataStream = json.encodeToString<AgentUpstreamData>(content).byteInputStream(Charsets.UTF_8) pool.addFile( generateAgentDataFileName(content.agentName), dataStream, true ) call.respond(QueryResult(Result.SUCCESS, "")) } catch (e: Exception) { call.respond(QueryResult(Result.FAILURE, "Exception: $e")) } } } } route("/query") { route("status") { get("{name?}") { return@get auth { val name = call.parameters["name"] ?: return@auth call.respondText( "Missing agent name", status = HttpStatusCode.BadRequest ) try { if (name !in Server.serverConfig.agents) { return@auth call.respond( status = HttpStatusCode.BadRequest, QueryResult(Result.FAILURE, "Agent $name not found.") ) } val param = try { getDataQueryParameters(call) } catch (e: Exception) { e.printStackTrace() return@auth call.respond( status = HttpStatusCode.BadRequest, QueryResult(Result.FAILURE, e.toString()) ) } val fileList = FileStore[name].select(param) val data = buildList { fileList.forEach { this += json.decodeFromStream<AgentUpstreamData>(FileStore[name].openInputStream(it)) } } call.respond(status = HttpStatusCode.OK, QueryResult(Result.SUCCESS, "", data)) } catch (e: Exception) { call.respond(status = HttpStatusCode.OK, QueryResult(Result.FAILURE, e.toString())) } } } } get("all") { auth { return@auth call.respond( status = HttpStatusCode.OK, QueryAllResult(Result.SUCCESS, data = buildMap { Server.serverConfig.agents.forEach { try { val data = FileStore[it].run { json.decodeFromStream<AgentUpstreamData>( openInputStream(reversedFileCache[fileCacheByIndex[indexCaches.last()]]!!) ) } this[it] = data } catch (e: Exception) { return@forEach } } }) ) } } } } } fun getDataQueryParameters(call: ApplicationCall): DataQueryParameters { val q = call.request.queryParameters val fromTime = (q["fromTime"] ?: throw RuntimeException("fromTime expected")).toLong() val toTime = q["toTime"].toString().toLongOrNull() val countLimit = q["countLimit"].toString().toLongOrNull() ?: 160 val compress = q["compress"].toString().toBooleanStrictOrNull() ?: false return DataQueryParameters(fromTime, toTime, countLimit, compress) }
0
Kotlin
0
0
f54f9778e7ed6cb37794d397d60d492dc4219e1c
5,465
NekoMonitor
MIT License
app/src/main/kotlin/com/xeladevmobile/medicalassistant/navigation/TopLevelDestination.kt
Alexminator99
702,145,143
false
{"Kotlin": 534097}
package com.xeladevmobile.medicalassistant.navigation import androidx.compose.ui.graphics.vector.ImageVector import com.xeladevmobile.medicalassistant.core.designsystem.icon.MedicalIcons import com.xeladevmobile.medicalassistant.feature.home.R as homeR import com.xeladevmobile.medicalassistant.feature.me.R as meR import com.xeladevmobile.medicalassistant.feature.records.R as recordsR /** * Type for the top level destinations in the application. Each of these destinations * can contain one or more screens (based on the window size). Navigation from one screen to the * next within a single destination will be handled directly in composables. */ enum class TopLevelDestination( val selectedIcon: ImageVector, val unselectedIcon: ImageVector, val iconTextId: Int, val titleTextId: Int, ) { HOME( selectedIcon = MedicalIcons.Upcoming, unselectedIcon = MedicalIcons.UpcomingBorder, iconTextId = homeR.string.home, titleTextId = homeR.string.home, ), RECORDS( selectedIcon = MedicalIcons.Bookmarks, unselectedIcon = MedicalIcons.BookmarksBorder, iconTextId = recordsR.string.records, titleTextId = recordsR.string.records, ), PROFILE( selectedIcon = MedicalIcons.Person, unselectedIcon = MedicalIcons.Person, iconTextId = meR.string.profile, titleTextId = meR.string.profile, ), }
0
Kotlin
0
0
37a35835a2562b0c6b4129e7b86cfca081a24783
1,424
Medical_Assistant
MIT License
app/src/main/java/uk/ac/aber/dcs/cs31620/faa/model/CatList.kt
chriswloftus
542,149,989
false
{"Kotlin": 37821}
/** * Hard-coded list of cat data * @author <NAME> */ package uk.ac.aber.dcs.cs31620.faa.model import uk.ac.aber.dcs.cs31620.faa.R import java.time.LocalDate val cats = listOf( Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ), Cat( "Tibs", Gender.MALE, "Short hair", "Lorem ipsum dolor sit amet, ...", R.drawable.cat1, LocalDate.now() ) )
0
Kotlin
1
0
d73bacc744d203e524685b610b544dcfe378e2fc
3,209
feline-adoption-agency-v6
MIT License
src/main/kotlin/just4fun/kotlinkit/async/AsyncTask.kt
just-4-fun
105,430,299
false
null
package just4fun.kotlinkit.async import java.util.concurrent.Executor import just4fun.kotlinkit.async.ResultTaskState.* import just4fun.kotlinkit.Result import just4fun.kotlinkit.lazyVar import just4fun.kotlinkit.Safely import java.util.concurrent.ScheduledThreadPoolExecutor import java.util.concurrent.TimeUnit import java.lang.System.currentTimeMillis as now /** [AsyncResult] of the [code] execution. * Can be delayed by [delayMs] milliseconds. * Can run in the [executor] thread if one is specified. Otherwise runs in the [AsyncTask.sharedContext]. */ open class AsyncTask<T>(val delayMs: Int = 0, val executor: Executor? = null, val code: TaskContext.() -> T): ResultTask<T>(), Runnable, Comparable<AsyncTask<*>> { companion object { var sharedContext: ThreadContext by lazyVar { DefaultThreadContext(1000) } private var SEQ = 0L private val nextSeqId get() = SEQ++ } val runTime: Long = delayMs + now() private var thread: Thread? = null private var runNow = executor == null internal var index = -1// optimizes task removal private val seqId = nextSeqId// helps compare tasks with equal runTime when order matters var wrapper: Runnable? = null// used to cancel the task scheduled by [ScheduledExecutorService] init { schedule() } private fun schedule() = executor.let { when (it) { is ThreadContext -> run { runNow = true; it.schedule(this) } is ScheduledThreadPoolExecutor -> run { runNow = true; it.schedule(this, delayMs.toLong(), TimeUnit.MILLISECONDS) } else -> sharedContext.schedule(this) } } override fun cancel(value: T, interrupt: Boolean): Unit = complete(Result(value), true, interrupt) override fun cancel(cause: Throwable, interrupt: Boolean) = complete(Result(cause), true, interrupt) override fun run() { if (runNow) run { runNow(); return } synchronized(lock) { if (state > CREATED) return else state = INITED } try { runNow = true executor?.execute(this) } catch (x: Throwable) { complete(Result<T>(x), false, false) } } private fun runNow() { synchronized(lock) { if (state > INITED) return else state = RUNNING } thread = Thread.currentThread() val res = try { Result(code(this)) } catch (x: Throwable) { Result<T>(x) } thread = null complete(res, false, false) Thread.interrupted()// clears interrupted status if any } override final fun complete(res: Result<T>, cancelled: Boolean, interrupt: Boolean): Unit { synchronized(lock) { if (state > RUNNING) return val remove = cancelled && state == CREATED state = if (cancelled) CANCELLED else EXECUTED result = res if (interrupt) thread?.interrupt() if (remove) onRemove() } reaction?.let { Safely { it.invoke(res) } } } fun onRemove() = executor.let { when (it) { is ThreadContext -> it.remove(this) is ScheduledThreadPoolExecutor -> it.remove(this) else -> sharedContext.remove(this) } } override fun onComplete(executor: Executor?, precede: Boolean, reaction: Reaction<T>): AsyncTask<T> { super.onComplete(executor, precede, reaction) return this } override fun compareTo(other: AsyncTask<*>): Int { if (this === other) return 0 val diff = runTime - other.runTime return if (diff < 0) -1 else if (diff > 0) 1 else if (seqId < other.seqId) -1 else 1 } fun runCopy(delay: Int = -1) = AsyncTask(if (delay < 0) delayMs else delay, executor, code).also { if (reaction != null) it.onComplete(null, false, reaction!!) } }
0
Kotlin
1
5
f99e8257837236fba7248cb999c0c0046848458d
3,463
kotlinkit
Apache License 2.0
ontrack-kdsl/src/main/java/net/nemerosa/ontrack/kdsl/spec/extension/av/AutoVersioningOntrackExtensions.kt
nemerosa
19,351,480
false
{"Kotlin": 8298680, "JavaScript": 2587834, "Java": 1129286, "HTML": 505573, "Groovy": 377453, "CSS": 137378, "Less": 35164, "Dockerfile": 6298, "Shell": 5086}
package net.nemerosa.ontrack.kdsl.spec.extension.av import net.nemerosa.ontrack.kdsl.spec.Ontrack /** * Management of auto versioning in Ontrack. */ val Ontrack.autoVersioning: AutoVersioningMgt get() = AutoVersioningMgt(connector)
39
Kotlin
26
94
c3cd484b681647bf68e43fa76a0bd4fccacf2972
236
ontrack
MIT License
app/src/main/java/com/kl3jvi/sysinfo/utils/Standard.kt
kl3jvi
348,700,775
false
null
package com.kl3jvi.sysinfo.utils import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract /** * Runs the given [block] after the execution of the last Unit method and returns the result as [Result]. * * @param block The block to be executed after the last Unit method. * @return The result of executing [block] as a [Result]. */ @OptIn(ExperimentalContracts::class) inline fun <T> T.thenCatching(block: T.() -> T): Result<T> { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return runCatching(block) } /** * Invokes a given function `fn` and returns its result. * * @param fn a function with no arguments that returns a `Long` value * @return the result of the function `fn` */ fun <T> invoke(fn: () -> T) = fn() fun Boolean.toAffirmative(): String { return if (this) "Yes" else "No" }
0
Kotlin
7
28
a2e7042237f4502155a58f6e5fae9247e6f18ca2
900
sysinfo_app
MIT License
mads-ns/src/main/kotlin/org/jetbrains/research/mads/ns/electrode/Electrode.kt
JetBrains-Research
435,540,085
false
{"Kotlin": 193384}
package org.jetbrains.research.mads.ns.electrode import org.jetbrains.research.mads.core.types.* import org.jetbrains.research.mads.ns.physiology.neurons.CurrentSignals import org.jetbrains.research.mads.ns.physiology.neurons.ProbabilisticSpikingSignals import java.util.* object ElectrodeConnection : ConnectionType class PeriodicPulsationSignals(cycleCounter: Int = 100, pulseValue: Double = 5.0) : Signals() { var cycle: Int by observable(cycleCounter) var iteration: Int by observable(1) var pulse: Double by observable(pulseValue) } class NoiseSignals(meanValue: Double = 0.0, std: Double = 1.0) : Signals() { val meanValue: Double by observable(meanValue) val std: Double by observable(std) } class Electrode(val rnd: Random, vararg signals: Signals) : ModelObject(ProbabilisticSpikingSignals(), *signals) class PulseConstants(val pulseValue: Double = 5.0) : MechanismConstants object ElectrodeMechanisms { val PeriodicPulseDynamic = Electrode::periodicPulseDynamic val PulseDynamic = Electrode::pulseDynamic val NoiseDynamic = Electrode::noiseDynamic } @Suppress("UNUSED_PARAMETER") fun Electrode.periodicPulseDynamic(params: MechanismParameters): List<Response> { val s = this.signals[CurrentSignals::class] as CurrentSignals val pps = this.signals[PeriodicPulsationSignals::class] as PeriodicPulsationSignals val iteration = pps.iteration val cycle = pps.cycle val delta = if (iteration % cycle == 0) { pps.pulse } else if (s.I_e > 0.0) { -pps.pulse } else { 0.0 } val result = updateCurrentInReceiver(this, delta) result.add( this.createResponse { pps.iteration++ } ) return result } fun Electrode.pulseDynamic(params: MechanismParameters): List<Response> { val currentSignals = this.signals[CurrentSignals::class] as CurrentSignals val spikeProbability = (this.signals[ProbabilisticSpikingSignals::class] as ProbabilisticSpikingSignals).spikeProbability var I = 0.0 if (currentSignals.I_e == 0.0 && rnd.nextDouble() < spikeProbability) { I = (params.constants as PulseConstants).pulseValue } val delta = I - currentSignals.I_e return updateCurrentInReceiver(electrode = this, delta) } @Suppress("UNUSED_PARAMETER") fun Electrode.noiseDynamic(params: MechanismParameters): List<Response> { val currentSignals = this.signals[CurrentSignals::class] as CurrentSignals val noiseSignals = this.signals[NoiseSignals::class] as NoiseSignals val newI = rnd.nextGaussian() * noiseSignals.std + noiseSignals.meanValue val delta = newI - currentSignals.I_e return updateCurrentInReceiver(electrode = this, delta) } fun updateCurrentInReceiver(electrode: Electrode, delta: Double): ArrayList<Response> { val result = arrayListOf<Response>() val currentSignals = electrode.signals[CurrentSignals::class] as CurrentSignals electrode.connections[ElectrodeConnection]?.forEach { val receiverCurrentSignals = it.signals[CurrentSignals::class] as CurrentSignals result.add( it.createResponse { receiverCurrentSignals.I_e += delta } ) } result.add( electrode.createResponse { currentSignals.I_e += delta } ) return result } fun Electrode.connectToCell(cell: ModelObject) { this.connections[ElectrodeConnection] = hashSetOf(cell) cell.connections[ElectrodeConnection] = hashSetOf(this) }
1
Kotlin
0
3
d2f4dadf77d9aa9946e6f5d646531a96bbd75097
3,512
mads
MIT License
app/src/main/java/com/noto/app/util/Constants.kt
alialbaali
245,781,254
false
{"Kotlin": 882792, "Ruby": 953}
package com.noto.app.util object Constants { const val Theme = "Theme" const val FolderId = "folder_id" const val FolderTitle = "folder_title" const val FilteredFolderIds = "filtered_folder_ids" const val SelectedFolderId = "selected_folder_id" const val NoteId = "note_id" const val Body = "body" const val IsDismissible = "is_dismissible" const val ClickListener = "click_listener" const val VaultTimeout = "VaultTimeout" const val IsNoneEnabled = "is_none_enabled" const val IsPasscodeValid = "IsPasscodeValid" const val WidgetRadius = "WidgetRadius" const val NoteTitle = "NoteTitle" const val NoteBody = "NoteBody" const val ScrollPosition = "ScrollPosition" const val IsTitleVisible = "IsTitleVisible" const val IsBodyVisible = "IsBodyVisible" const val Title = "title" const val Model = "model" const val EmailType = "mailto:" const val DisableSelection = "DisableSelection" const val FilteringType = "FilteringType" const val SortingType = "SortingType" const val SortingOrder = "SortingOrder" const val GroupingType = "GroupingType" const val GroupingOrder = "GroupingOrder" const val QuickNoteFolderId = "quick_note_interface_id" const val MainInterfaceId = "main_interface_id" const val QuickNote = "quick_note" object Intent { const val ActionCreateFolder = "com.noto.intent.action.CREATE_FOLDER" const val ActionCreateNote = "com.noto.intent.action.CREATE_NOTE" const val ActionQuickNote = "com.noto.intent.action.QUICK_NOTE" const val ActionOpenFolder = "com.noto.intent.action.OPEN_FOLDER" const val ActionOpenNote = "com.noto.intent.action.OPEN_NOTE" const val ActionOpenVault = "com.noto.intent.action.OPEN_VAULT" const val ActionSettings = "com.noto.intent.action.SETTINGS" } object Noto { const val Email = "<EMAIL>" const val DeveloperUrl = "https://www.alialbaali.com" const val LicenseUrl = "https://www.apache.org/licenses/LICENSE-2.0" const val PlayStoreUrl = "https://play.google.com/store/apps/details?id=com.noto" const val GithubUrl = "https://github.com/alialbaali/Noto" const val TelegramUrl = "https://t.me/notoapp" const val PrivacyPolicyUrl = "https://github.com/alialbaali/Noto/blob/master/PrivacyPolicy.md" const val GithubIssueUrl = "https://github.com/alialbaali/Noto/issues/new" const val ReportIssueEmailSubject = "Issue Regarding Noto" const val GitHubReleasesUrl = "https://github.com/alialbaali/Noto/releases" fun GitHubReleaseUrl(version: String) = "https://github.com/alialbaali/Noto/releases/tag/v$version" fun ReportIssueEmailBody(androidVersion: String, sdkVersion: String, appVersion: String) = """ Hi there, I'm having an issue with [ISSUE]. Android version: $androidVersion SDK version: $sdkVersion App version: $appVersion Regards, """.trimIndent() const val TranslationEmailSubject = "Translate Noto" val TranslationEmailBody = """ Hi there, I would like to translate Noto to [LANGUAGE]. I want to be credited as (optional): Name: [NAME] Link (optional): [LINK] Regards, """.trimIndent() } }
54
Kotlin
14
343
a1863c169f12d6852edc1c03d080a050647d3964
3,502
Noto
Apache License 2.0
buildSrc/build.gradle.kts
dandoh
213,273,434
true
{"Kotlin": 302332, "Lex": 25902, "Java": 10307, "HTML": 9727, "CSS": 7861, "Agda": 2356, "Perl": 239}
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet group = "org.ice1000.tt.gradle" version = "114514" plugins { kotlin("jvm") version "1.3.30" } sourceSets { main { withConvention(KotlinSourceSet::class) { kotlin.srcDirs("src") } } } repositories { jcenter() } dependencies { compile(kotlin("stdlib-jdk8")) }
0
Kotlin
0
0
47e013622f1761f4618fa13a391e335af4369b22
316
intellij-dtlc
Apache License 2.0
app/src/main/java/com/projects/melih/gistpub/view/BaseFragment.kt
melomg
110,280,973
false
null
package com.projects.melih.gistpub.view import android.Manifest import android.app.DownloadManager import android.app.ProgressDialog import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.Environment import android.support.annotation.CallSuper import android.support.annotation.MenuRes import android.support.design.widget.Snackbar import android.support.v4.app.DialogFragment import android.support.v4.app.Fragment import android.text.TextUtils import android.util.Log import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.View import android.view.ViewGroup import android.view.animation.Animation import android.webkit.MimeTypeMap import com.projects.melih.gistpub.Constants import com.projects.melih.gistpub.R import com.projects.melih.gistpub.model.File import com.projects.melih.gistpub.model.Gist import com.projects.melih.gistpub.network.service.GitHubApi import com.projects.melih.gistpub.view.gist.FileViewDialogFragment import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.util.ArrayList import okhttp3.ResponseBody import pub.devrel.easypermissions.AfterPermissionGranted import pub.devrel.easypermissions.AppSettingsDialog import pub.devrel.easypermissions.EasyPermissions import retrofit2.Call import retrofit2.Callback import retrofit2.Response /** * Created by melih on 23/12/2016 */ abstract class BaseFragment : Fragment(), EasyPermissions.PermissionCallbacks { protected var baseFragment: View? = null protected var gists: ArrayList<Gist>? = null protected lateinit var selectedFile: File protected var file: java.io.File? = null protected var navigationListener: NavigationListener? = null protected lateinit var responseBody: ResponseBody protected lateinit var fileName: String protected lateinit var username: String protected lateinit var rootView: View @get:MenuRes protected abstract val menuRes: Int private var progressDialog: ProgressDialog? = null override fun onAttach(context: Context?) { super.onAttach(context) this.navigationListener = context as NavigationListener? } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (menuRes != Constants.NO_RES) { setHasOptionsMenu(true) } } override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation? { var animation: Animation? = super.onCreateAnimation(transit, enter, nextAnim) if (disableFragmentAnimations) { if (animation == null) { animation = object : Animation() { } } animation.duration = 0 } return animation } @CallSuper override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { rootView = activity.findViewById(R.id.container) //TODO("move user data to a data manager like net manager") val sharedPref = context?.getSharedPreferences(context?.getString(R.string.preference_user_key), Context.MODE_PRIVATE) username = sharedPref?.getString(context?.getString(R.string.username_extra), "") ?: "" return rootView } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { super.onCreateOptionsMenu(menu, inflater) if (menuRes != Constants.NO_RES) { inflater?.inflate(menuRes, menu) } } override fun onDestroy() { super.onDestroy() navigationListener = null } protected fun showSnackBar(message: String) { Snackbar.make(rootView, message, Snackbar.LENGTH_LONG).show() } protected fun showSnackBar(message: String, actionMessage: String, listener: View.OnClickListener) { Snackbar.make(rootView, message, Snackbar.LENGTH_LONG).setAction(actionMessage, listener).show() } private fun openFolder(file: java.io.File?) { //TODO("clear download manager notification") if (file != null) { val intent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS) startActivity(intent) } } protected fun downloadFile(writeToDisk: Boolean) { val call = GitHubApi.getGitHubService(context).downloadFileWithDynamicUrlSync(selectedFile.rawUrl) call.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) { if (response.isSuccessful) { if (writeToDisk) { responseBody = response.body()!! fileName = selectedFile.filename writeResponseBodyToDisk() } else { openFile(response.body()?.byteStream()!!, selectedFile) } } else { showSnackBar(getString(R.string.unknown_error)) } } override fun onFailure(call: Call<ResponseBody>, t: Throwable) { showSnackBar(t.message ?: "") } }) } @AfterPermissionGranted(RC_WRITE_EXTERNAL_STORAGE) private fun writeResponseBodyToDisk() { var isSuccess = false if (EasyPermissions.hasPermissions(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { try { file = java.io.File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + java.io.File.separator + fileName.trim { it <= ' ' } + ".txt") var inputStream: InputStream? = null var outputStream: OutputStream? = null try { val fileReader = ByteArray(4096) val fileSize = responseBody.contentLength() var fileSizeDownloaded: Long = 0 inputStream = responseBody.byteStream() outputStream = FileOutputStream(file!!) while (true) { val read = inputStream?.read(fileReader) if (read == -1) { break } outputStream.write(fileReader, 0, read!!) fileSizeDownloaded += read.toLong() Log.d("melo", "file download: $fileSizeDownloaded of $fileSize") } outputStream.flush() isSuccess = true } catch (e: IOException) { isSuccess = false } finally { if (inputStream != null) { inputStream.close() } if (outputStream != null) { outputStream.close() } } } catch (e: IOException) { isSuccess = false } finally { val downloadManager = activity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager downloadManager.addCompletedDownload(file!!.name, file!!.name, true, getMimeType(Uri.fromFile(file).toString()), file!!.absolutePath, file!!.length(), true) showSnackBar(if (isSuccess) getString(R.string.success_file_download) else getString(R.string.error_file_download), getString(R.string.goToLocation), View.OnClickListener { openFolder(file) }) } } else { EasyPermissions.requestPermissions(this@BaseFragment, getString(R.string.permission_write_external_storage_rationale), RC_WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE) } } protected fun openFile(inputStream: InputStream, file: File) { showFragmentDialog(FileViewDialogFragment.newInstance(inputStream, file.filename), FileViewDialogFragment.TAG) } protected fun showLoading(message: String) { val activity = activity ?: return if (!isVisible && activity.isFinishing) { return } if (progressDialog == null) { progressDialog = ProgressDialog(context) progressDialog?.setCancelable(false) } if (!progressDialog!!.isShowing) { progressDialog?.setMessage(if (TextUtils.isEmpty(message)) getString(R.string.pleaseWait) else message) progressDialog?.show() } } protected fun dismissLoading() { val activity = activity ?: return if (!isVisible && activity.isFinishing || progressDialog == null) { return } progressDialog?.isShowing!!.let { progressDialog?.dismiss() } } protected fun showFragmentDialog(dialogFragment: DialogFragment, tag: String) { val activity = activity ?: return val fragmentManager = activity.supportFragmentManager val fragmentTransaction = fragmentManager.beginTransaction() val fragment = fragmentManager.findFragmentByTag(tag) if (fragment != null) { fragmentTransaction.remove(fragment) } fragmentTransaction.addToBackStack(null) dialogFragment.show(fragmentTransaction, tag) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this) } override fun onPermissionsGranted(requestCode: Int, perms: List<String>) { Log.d(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size) } override fun onPermissionsDenied(requestCode: Int, perms: List<String>) { if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) { AppSettingsDialog.Builder(this@BaseFragment).build().show() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) { downloadFile(true) } } companion object { var disableFragmentAnimations: Boolean = false public val TAG = "BaseFragment" const val RC_WRITE_EXTERNAL_STORAGE = 122 fun getMimeType(url: String): String { var type: String? = null val extension = MimeTypeMap.getFileExtensionFromUrl(url) if (extension != null) { type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) } return type ?: "" } } }
0
Kotlin
0
0
7a7353d342ce80a0883d173509b8070ac4f0aa08
10,883
gistpub
MIT License
data/src/main/java/com/thiennguyen/survey/data/interceptor/AuthenticationInterceptor.kt
thiennguyen0196
482,177,646
false
{"Kotlin": 148873}
package com.thiennguyen.survey.data.interceptor import com.thiennguyen.survey.data.Constants import com.thiennguyen.survey.data.local.PreferenceManager import javax.inject.Inject import okhttp3.Interceptor import okhttp3.Response class AuthenticationInterceptor @Inject constructor( private val preferenceManager: PreferenceManager ) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val tokenType = preferenceManager.getTokenType() val accessToken = preferenceManager.getAccessToken() return if (tokenType.isNullOrBlank() || accessToken.isNullOrBlank()) { chain.proceed(request) } else { val authenticationRequest = request.newBuilder() .header(Constants.Authorization.HEADER_AUTHORIZATION, "$tokenType $accessToken") .build() chain.proceed(authenticationRequest) } } }
6
Kotlin
0
0
25bed7de5aad8abfee37173ac28458d2a60c154d
959
survey
Apache License 2.0
gradle/plugins/convention/src/main/kotlin/AndroidLibraryPlugin.kt
battagliandrea
708,330,176
false
{"Kotlin": 92936, "Shell": 1093}
import com.android.build.gradle.LibraryExtension import it.battagliandrea.gradle.plugins.conventions.configureKotlinAndroid import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.kotlin.dsl.configure /** * Gradle plugin class for configuring an Android library project. * * This plugin extends the functionality of the Android Gradle Plugin to set up and configure * a project for Android library development. * * After applying the plugin, it configures the project for Android library development. */ class AndroidLibraryPlugin: Plugin<Project> { override fun apply(target: Project) = with(target) { with(pluginManager) { apply("com.android.library") apply("org.jetbrains.kotlin.android") apply("f1.spotless") } extensions.configure<LibraryExtension> { configureKotlinAndroid(this) } } }
4
Kotlin
0
0
38140064a89f11cccbbc6e1796bdca7d861ba5a9
908
Fomula1
Apache License 2.0
app/src/main/java/hive/com/paradiseoctopus/awareness/utils/SimpleDividerItemDecoration.kt
cliffroot
68,677,882
false
null
package hive.com.paradiseoctopus.awareness.utils import android.content.Context import android.graphics.Canvas import android.graphics.drawable.Drawable import android.support.v4.content.ContextCompat import android.support.v7.widget.RecyclerView import hive.com.paradiseoctopus.awareness.R /** * Created by edanylenko on 10/3/16. */ class SimpleDividerItemDecoration(val context : Context) : RecyclerView.ItemDecoration() { private var mDivider: Drawable = ContextCompat.getDrawable(context, R.drawable.line_divider) override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { val left = parent.paddingLeft val right = parent.width - parent.paddingRight val childCount = parent.childCount for (i in 0..childCount - 1) { val child = parent.getChildAt(i) val params = child.layoutParams as RecyclerView.LayoutParams val top = child.bottom + params.bottomMargin val bottom = top + mDivider.intrinsicHeight mDivider.setBounds(left, top, right, bottom) mDivider.draw(c) } } }
0
Kotlin
0
0
77bd018fd938ebebe804ecceca9315112564246b
1,132
awareness
Apache License 2.0
data/src/main/java/com/goms/data/datasource/admin/CouncilDataSource.kt
team-haribo
614,646,527
false
{"Kotlin": 195602}
package com.goms.data.datasource.admin import com.goms.data.model.council.request.ModifyRoleRequest import com.goms.data.model.council.response.MakeQrCodeResponse import com.goms.data.model.council.response.UserInfoResponse import kotlinx.coroutines.flow.Flow import retrofit2.Response import java.util.UUID interface CouncilDataSource { suspend fun getUserList(): Flow<List<UserInfoResponse>> suspend fun modifyRole(body: ModifyRoleRequest): Flow<Response<Unit>> suspend fun setBlackList(accountIdx: UUID): Flow<Response<Unit>> suspend fun cancelBlackList(accountIdx: UUID): Flow<Response<Unit>> suspend fun searchStudent( grade: Int?, classNum: Int?, name: String?, isBlackList: Boolean?, authority: String? ): Flow<List<UserInfoResponse>> suspend fun makeQrCode(): Flow<MakeQrCodeResponse> suspend fun deleteOuting(accountIdx: UUID): Flow<Response<Unit>> }
1
Kotlin
0
7
9d7a06d4c69abe6807c9f531403c3d48be0d6be8
939
GOMS-Android
MIT License
compose-score-keeper/app/src/main/java/dev/goobar/composescorekeeper/ui/theme/Theme.kt
goobar-dev
571,410,157
false
{"Kotlin": 54468}
package dev.goobar.composescorekeeper.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color private val DarkColorPalette = darkColors( primary = BlueGrey700Dark, primaryVariant = Grey900, secondary = BlueGrey700Dark, onPrimary = Color.White, onSecondary = Color.White, onBackground = Color.White, onSurface = Color.White, ) private val LightColorPalette = lightColors( primary = BlueGrey700, primaryVariant = BlueGrey700Dark, secondary = Blue700, background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, ) @Composable fun ComposeScoreKeeperTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
0
Kotlin
1
2
a6b1526799efb5258f61628dc3f8641e175c3b54
1,195
deprecated-android-402-advanced-android-kotlin
Apache License 2.0
agent/src/main/kotlin/ru/art/platform/agent/service/AgentKanikoService.kt
art-community
284,500,366
false
null
package ru.art.platform.agent.service import ru.art.core.constants.StringConstants.SLASH import ru.art.core.constants.SystemConstants.PROCESS_ERROR_CODE_OK import ru.art.platform.agent.constants.DockerConstants.DOCKER_CONFIG_ENVIRONMENT import ru.art.platform.common.service.ProcessOutputListener import ru.art.platform.common.service.process import java.nio.file.Path data class KanikoExecutorConfiguration(val contextPath: Path, val command: List<String>, val dockerConfigPath: String) object AgentKanikoService { fun executeKaniko(configuration: KanikoExecutorConfiguration, listener: ProcessOutputListener = ProcessOutputListener()): Process { with(configuration) { val process = process(command, contextPath) .environment(DOCKER_CONFIG_ENVIRONMENT, dockerConfigPath.substringBeforeLast(SLASH)) .onOutput(listener::produceEvent) .onError(listener::produceError) .execute() if (process.exitValue() != PROCESS_ERROR_CODE_OK) { listener.produceError("Kaniko failed with error code: ${process.exitValue()}") return process } listener.produceEvent("Kaniko finished with exit code: ${process.exitValue()}") return process } } }
1
TypeScript
0
1
80051409f70eec2abb66afb7d72359a975198a2b
1,327
art-platform
Apache License 2.0
dimens/src/test/java/dev/drewhamilton/inlinedimens/widget/TextViewTest.kt
drewhamilton
193,558,277
false
null
package dev.drewhamilton.inlinedimens.widget import android.graphics.Paint import android.text.TextPaint import android.util.TypedValue import android.widget.TextView import androidx.appcompat.widget.AppCompatTextView import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions import com.nhaarman.mockitokotlin2.whenever import dev.drewhamilton.inlinedimens.Dp import dev.drewhamilton.inlinedimens.Sp import dev.drewhamilton.inlinedimens.TestValues import dev.drewhamilton.inlinedimens.arrays.toDpIntArray import dev.drewhamilton.inlinedimens.arrays.toPxIntArray import dev.drewhamilton.inlinedimens.arrays.toSpIntArray import dev.drewhamilton.inlinedimens.dp import dev.drewhamilton.inlinedimens.px import dev.drewhamilton.inlinedimens.sp import dev.drewhamilton.inlinedimens.spoofSdkInt import org.junit.Assert.assertEquals import org.junit.Test class TextViewTest { private val mockTextView = mock<TextView>() private val mockResources = TestValues.mockResources //region Auto-size @Test fun `setAutoSizeTextTypeUniformWithPresetSizes with Px on API 27 sets px text sizes`() { spoofSdkInt(27) val pxArray = arrayOf(1.px, 2.px).toPxIntArray() mockTextView.setAutoSizeTextTypeUniformWithPresetSizes(pxArray) verify(mockTextView).setAutoSizeTextTypeUniformWithPresetSizes(pxArray.values, TypedValue.COMPLEX_UNIT_PX) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithPresetSizes with Px on API 26 AutoSizeableTextView sets px text sizes`() { spoofSdkInt(26) val pxArray = arrayOf(1.px, 2.px).toPxIntArray() val mockTextView: TextView = mock<AppCompatTextView>() mockTextView.setAutoSizeTextTypeUniformWithPresetSizes(pxArray) verify(mockTextView).setAutoSizeTextTypeUniformWithPresetSizes(pxArray.values, TypedValue.COMPLEX_UNIT_PX) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithPresetSizes with Px on API 26 TextView is no-op`() { spoofSdkInt(26) val pxArray = arrayOf(1.px, 2.px).toPxIntArray() mockTextView.setAutoSizeTextTypeUniformWithPresetSizes(pxArray) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithPresetSizes with Dp on API 27 sets dp text sizes`() { spoofSdkInt(27) val dpArray = arrayOf(1.dp, 2.dp).toDpIntArray() mockTextView.setAutoSizeTextTypeUniformWithPresetSizes(dpArray) verify(mockTextView).setAutoSizeTextTypeUniformWithPresetSizes(dpArray.values, TypedValue.COMPLEX_UNIT_DIP) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithPresetSizes with Dp on API 26 AutoSizeableTextView sets dp text sizes`() { spoofSdkInt(26) val dpArray = arrayOf(1.dp, 2.dp).toDpIntArray() val mockTextView: TextView = mock<AppCompatTextView>() mockTextView.setAutoSizeTextTypeUniformWithPresetSizes(dpArray) verify(mockTextView).setAutoSizeTextTypeUniformWithPresetSizes(dpArray.values, TypedValue.COMPLEX_UNIT_DIP) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithPresetSizes with Dp on API 26 TextView is no-op`() { spoofSdkInt(26) val dpArray = arrayOf(1.dp, 2.dp).toDpIntArray() mockTextView.setAutoSizeTextTypeUniformWithPresetSizes(dpArray) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithPresetSizes with Sp on API 27 sets sp text sizes`() { spoofSdkInt(27) val spArray = arrayOf(1.sp, 2.sp).toSpIntArray() mockTextView.setAutoSizeTextTypeUniformWithPresetSizes(spArray) verify(mockTextView).setAutoSizeTextTypeUniformWithPresetSizes(spArray.values, TypedValue.COMPLEX_UNIT_SP) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithPresetSizes with Sp on API 26 AutoSizeableTextView sets sp text sizes`() { spoofSdkInt(26) val spArray = arrayOf(1.sp, 2.sp).toSpIntArray() val mockTextView: TextView = mock<AppCompatTextView>() mockTextView.setAutoSizeTextTypeUniformWithPresetSizes(spArray) verify(mockTextView).setAutoSizeTextTypeUniformWithPresetSizes(spArray.values, TypedValue.COMPLEX_UNIT_SP) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithPresetSizes with Sp on API 26 TextView is no-op`() { spoofSdkInt(26) val spArray = arrayOf(1.sp, 2.sp).toSpIntArray() mockTextView.setAutoSizeTextTypeUniformWithPresetSizes(spArray) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithConfiguration with Px on API 27 sets px text size range`() { spoofSdkInt(27) val pxMin = 24.px val pxMax = 48.px val pxGranularity = 4.px mockTextView.setAutoSizeTextTypeUniformWithConfiguration(pxMin, pxMax, pxGranularity) verify(mockTextView).setAutoSizeTextTypeUniformWithConfiguration( pxMin.value, pxMax.value, pxGranularity.value, TypedValue.COMPLEX_UNIT_PX ) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithConfiguration with Px on API 26 AutoSizeableTextView sets px text size range`() { spoofSdkInt(26) val pxMin = 24.px val pxMax = 48.px val pxGranularity = 4.px val mockTextView: TextView = mock<AppCompatTextView>() mockTextView.setAutoSizeTextTypeUniformWithConfiguration(pxMin, pxMax, pxGranularity) verify(mockTextView).setAutoSizeTextTypeUniformWithConfiguration( pxMin.value, pxMax.value, pxGranularity.value, TypedValue.COMPLEX_UNIT_PX ) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithConfiguration with Px on API 26 TextView is no-op`() { spoofSdkInt(26) val pxMin = 24.px val pxMax = 48.px val pxGranularity = 4.px mockTextView.setAutoSizeTextTypeUniformWithConfiguration(pxMin, pxMax, pxGranularity) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithConfiguration with Dp on API 27 sets dp text size range`() { spoofSdkInt(27) val dpMin = 24.dp val dpMax = 48.dp val dpGranularity = 4.dp mockTextView.setAutoSizeTextTypeUniformWithConfiguration(dpMin, dpMax, dpGranularity) verify(mockTextView).setAutoSizeTextTypeUniformWithConfiguration( dpMin.value, dpMax.value, dpGranularity.value, TypedValue.COMPLEX_UNIT_DIP ) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithConfiguration with Dp on API 26 AutoSizeableTextView sets dp text size range`() { spoofSdkInt(26) val dpMin = 24.dp val dpMax = 48.dp val dpGranularity = 4.dp val mockTextView: TextView = mock<AppCompatTextView>() mockTextView.setAutoSizeTextTypeUniformWithConfiguration(dpMin, dpMax, dpGranularity) verify(mockTextView).setAutoSizeTextTypeUniformWithConfiguration( dpMin.value, dpMax.value, dpGranularity.value, TypedValue.COMPLEX_UNIT_DIP ) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithConfiguration with Dp on API 26 TextView is no-op`() { spoofSdkInt(26) val dpMin = 24.dp val dpMax = 48.dp val dpGranularity = 4.dp mockTextView.setAutoSizeTextTypeUniformWithConfiguration(dpMin, dpMax, dpGranularity) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithConfiguration with Sp on API 27 sets sp text size range`() { spoofSdkInt(27) val spMin = 24.sp val spMax = 48.sp val spGranularity = 4.sp mockTextView.setAutoSizeTextTypeUniformWithConfiguration(spMin, spMax, spGranularity) verify(mockTextView).setAutoSizeTextTypeUniformWithConfiguration( spMin.value, spMax.value, spGranularity.value, TypedValue.COMPLEX_UNIT_SP ) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithConfiguration with Sp on API 26 AutoSizeableTextView sets sp text size range`() { spoofSdkInt(26) val spMin = 24.sp val spMax = 48.sp val spGranularity = 4.sp val mockTextView: TextView = mock<AppCompatTextView>() mockTextView.setAutoSizeTextTypeUniformWithConfiguration(spMin, spMax, spGranularity) verify(mockTextView).setAutoSizeTextTypeUniformWithConfiguration( spMin.value, spMax.value, spGranularity.value, TypedValue.COMPLEX_UNIT_SP ) verifyNoMoreInteractions(mockTextView) } @Test fun `setAutoSizeTextTypeUniformWithConfiguration with Sp on API 26 TextView is no-op`() { spoofSdkInt(26) val spMin = 24.sp val spMax = 48.sp val spGranularity = 4.sp mockTextView.setAutoSizeTextTypeUniformWithConfiguration(spMin, spMax, spGranularity) verifyNoMoreInteractions(mockTextView) } //endregion //region Line and baseline heights @Test fun `lineHeightPx matches lineHeight as PxInt`() { whenever(mockTextView.lineHeight).thenReturn(34) assertThat(mockTextView.lineHeightPx).isEqualTo(34.px) } @Test fun `set lineHeightPx forwards to set lineHeight`() { val mockPaint = mock<TextPaint>() whenever(mockPaint.getFontMetricsInt(null)).thenReturn(30) whenever(mockTextView.paint).thenReturn(mockPaint) mockTextView.lineHeightPx = 35.px verify(mockTextView).paint verify(mockTextView).setLineSpacing(5f, 1f) verifyNoMoreInteractions(mockTextView) } @Test fun `firstBaselineToTopHeightPx matches firstBaselineToTopHeight as PxInt`() { val mockFontMetricInt = mock<Paint.FontMetricsInt>() mockFontMetricInt.top = 31 val mockPaint = mock<TextPaint>() whenever(mockPaint.fontMetricsInt).thenReturn(mockFontMetricInt) whenever(mockTextView.paint).thenReturn(mockPaint) whenever(mockTextView.paddingTop).thenReturn(42) assertThat(mockTextView.firstBaselineToTopHeightPx).isEqualTo(11.px) } @Test fun `set firstBaselineToTopHeightPx forwards to set firstBaselineToTopHeight`() { spoofSdkInt(28) mockTextView.firstBaselineToTopHeightPx = 65.px verify(mockTextView).firstBaselineToTopHeight = 65 verifyNoMoreInteractions(mockTextView) } @Test fun `lastBaselineToBottomHeightPx matches lastBaselineToBottomHeight as PxInt`() { val mockFontMetricInt = mock<Paint.FontMetricsInt>() mockFontMetricInt.bottom = 53 val mockPaint = mock<TextPaint>() whenever(mockPaint.fontMetricsInt).thenReturn(mockFontMetricInt) whenever(mockTextView.paint).thenReturn(mockPaint) whenever(mockTextView.paddingBottom).thenReturn(62) assertThat(mockTextView.lastBaselineToBottomHeightPx).isEqualTo(115.px) } @Test fun `set lastBaselineToBottomHeightPx forwards to set lastBaselineToBottomHeight`() { spoofSdkInt(16) val mockFontMetricInt = mock<Paint.FontMetricsInt>() mockFontMetricInt.bottom = 35 val mockPaint = mock<TextPaint>() whenever(mockPaint.fontMetricsInt).thenReturn(mockFontMetricInt) whenever(mockTextView.paint).thenReturn(mockPaint) whenever(mockTextView.includeFontPadding).thenReturn(true) mockTextView.lastBaselineToBottomHeightPx = 71.px verify(mockTextView).paint verify(mockTextView).includeFontPadding verify(mockTextView).paddingLeft verify(mockTextView).paddingTop verify(mockTextView).paddingRight verify(mockTextView).setPadding(0, 0, 0, 36) verifyNoMoreInteractions(mockTextView) } //endregion //region Text size @Test fun `textSizePx gets text size as Px`() { whenever(mockTextView.textSize).thenReturn(22f) assertEquals(22f.px, mockTextView.textSizePx) } @Test fun `set textSizePx sets px text size`() { val px = 234.5f.px mockTextView.textSizePx = px verify(mockTextView).setTextSize(TypedValue.COMPLEX_UNIT_PX, px.value) verifyNoMoreInteractions(mockTextView) } @Test fun `textSizeDp gets text size as Dp`() { whenever(mockTextView.resources).thenReturn(mockResources) whenever(mockTextView.textSize).thenReturn(23f) assertEquals(Dp(23f / TestValues.DENSITY), mockTextView.textSizeDp) } @Test fun `set textSizeDp sets dp text size`() { val dp = 234.5f.dp mockTextView.textSizeDp = dp verify(mockTextView).setTextSize(TypedValue.COMPLEX_UNIT_DIP, dp.value) verifyNoMoreInteractions(mockTextView) } @Test fun `textSizeSp gets text size as Sp`() { whenever(mockTextView.resources).thenReturn(mockResources) whenever(mockTextView.textSize).thenReturn(24f) assertEquals(Sp(24f / TestValues.SCALED_DENSITY), mockTextView.textSizeSp) } @Test fun `set textSizeSp sets sp text size`() { val sp = 234.5f.sp mockTextView.textSizeSp = sp verify(mockTextView).setTextSize(TypedValue.COMPLEX_UNIT_SP, sp.value) verifyNoMoreInteractions(mockTextView) } //endregion //region View size @Test fun `minHeightPx gets from View minHeight`() { whenever(mockTextView.minHeight).thenReturn(85) assertThat(mockTextView.minHeightPx).isEqualTo(85.px) } @Test fun `set minHeightPx sets View minHeight`() { mockTextView.minHeightPx = 58.px verify(mockTextView).minHeight = 58 verifyNoMoreInteractions(mockTextView) } @Test fun `maxHeightPx gets from View maxHeight`() { whenever(mockTextView.maxHeight).thenReturn(95) assertThat(mockTextView.maxHeightPx).isEqualTo(95.px) } @Test fun `set maxHeightPx sets View maxHeight`() { mockTextView.maxHeightPx = 59.px verify(mockTextView).maxHeight = 59 verifyNoMoreInteractions(mockTextView) } @Test fun `heightPx gets from View height`() { whenever(mockTextView.height).thenReturn(105) assertThat(mockTextView.heightPx).isEqualTo(105.px) } @Test fun `set heightPx sets View height`() { mockTextView.heightPx = 501.px verify(mockTextView).height = 501 verifyNoMoreInteractions(mockTextView) } @Test fun `minWidthPx gets from View minWidth`() { whenever(mockTextView.minWidth).thenReturn(115) assertThat(mockTextView.minWidthPx).isEqualTo(115.px) } @Test fun `set minWidthPx sets View minWidth`() { mockTextView.minWidthPx = 511.px verify(mockTextView).minWidth = 511 verifyNoMoreInteractions(mockTextView) } @Test fun `maxWidthPx gets from View maxWidth`() { whenever(mockTextView.maxWidth).thenReturn(125) assertThat(mockTextView.maxWidthPx).isEqualTo(125.px) } @Test fun `set maxWidthPx sets View maxWidth`() { mockTextView.maxWidthPx = 521.px verify(mockTextView).maxWidth = 521 verifyNoMoreInteractions(mockTextView) } @Test fun `widthPx gets from View width`() { whenever(mockTextView.width).thenReturn(135) assertThat(mockTextView.widthPx).isEqualTo(135.px) } @Test fun `set widthPx sets View width`() { mockTextView.widthPx = 531.px verify(mockTextView).width = 531 verifyNoMoreInteractions(mockTextView) } //endregion //region Line spacing @Test fun `setLineSpacing forwards to View function`() { mockTextView.setLineSpacing(83.2f.px, 2.3f) verify(mockTextView).setLineSpacing(83.2f, 2.3f) verifyNoMoreInteractions(mockTextView) } @Test fun `lineSpacingExtraPx wraps View lineSpacingExtra`() { whenever(mockTextView.lineSpacingExtra).thenReturn(808f) assertThat(mockTextView.lineSpacingExtraPx).isEqualTo(808f.px) } //endregion }
0
Kotlin
0
55
db8e4d68e9534e7d7f4e37530f533e246d28b99d
16,627
InlineDimens
Apache License 2.0
build.gradle.kts
acrylic-style
372,160,504
false
{"Java": 3878, "Kotlin": 1003}
plugins { java } group = "xyz.acrylicstyle" version = "1.0-SNAPSHOT" repositories { mavenLocal() mavenCentral() maven { url = uri("https://repo2.acrylicstyle.xyz") } } dependencies { implementation("xyz.acrylicstyle:api:0.8.1") compileOnly("org.spigotmc:spigot-api:1.12.2-R0.1-SNAPSHOT") } tasks { withType<JavaCompile>().configureEach { options.encoding = "utf-8" } withType<ProcessResources> { filteringCharset = "UTF-8" from(sourceSets.main.get().resources.srcDirs) { include("**") val tokenReplacementMap = mapOf("version" to project.version) filter<org.apache.tools.ant.filters.ReplaceTokens>("tokens" to tokenReplacementMap) } from(projectDir) { include("LICENSE") } } withType<Jar> { from(configurations.getByName("implementation").apply { isCanBeResolved = true }.map { if (it.isDirectory) it else zipTree(it) }) } }
0
Java
0
0
ba20eaae95ba1afed94fd701fd3ee8a6ef2a647c
964
NBSPlayerForever
Do What The F*ck You Want To Public License
modules/core/src/main/java/de/deutschebahn/bahnhoflive/backend/db/publictrainstation/model/Constants.kt
dbbahnhoflive
267,806,942
false
{"Kotlin": 1166808, "Java": 919061, "HTML": 43851}
/* * SPDX-FileCopyrightText: 2020 DB Station&Service AG <<EMAIL>> * * SPDX-License-Identifier: Apache-2.0 */ package de.deutschebahn.bahnhoflive.backend.db.publictrainstation.model object IdentifierType { const val EVA = "EVA" const val STADA = "STADA" } object LinkKey { const val SELF = "self" }
0
Kotlin
4
33
ae72e13b97a60ca942b63ff36f8b982ea0a7bb4f
349
dbbahnhoflive-android
Apache License 2.0
app/src/main/java/org/blitzortung/android/data/Parameters.kt
cheese1
389,361,833
true
{"Kotlin": 353710}
/* Copyright 2015 <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 org.blitzortung.android.data import org.blitzortung.android.data.provider.GLOBAL_REGION import org.blitzortung.android.data.provider.LOCAL_REGION data class Parameters( val region: Int = -1, val rasterBaselength: Int = 0, override val intervalDuration: Int = 0, override val intervalOffset: Int = 0, val countThreshold: Int = 0, val localReference: LocalReference? = null ) : TimeIntervalWithOffset { val isGlobal: Boolean = region == GLOBAL_REGION val isLocal: Boolean = region == LOCAL_REGION fun isRealtime(): Boolean = intervalOffset == 0 } data class LocalReference( val x: Int, val y: Int )
0
null
0
0
a795932a540362d7bb8f6f2bbba93e52ca36f672
1,280
bo-android
Apache License 2.0
src/main/kotlin/org/eclipse/tractusx/managedidentitywallets/routes/WalletRoutes.kt
eclipse-tractusx
531,494,665
false
{"Kotlin": 744116, "Smarty": 2971, "Dockerfile": 470, "Shell": 323}
/******************************************************************************** * Copyright (c) 2021,2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available 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. * * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ package org.eclipse.tractusx.managedidentitywallets.routes import io.bkbn.kompendium.auth.Notarized.notarizedAuthenticate import io.bkbn.kompendium.core.Notarized.notarizedDelete import io.bkbn.kompendium.core.Notarized.notarizedGet import io.bkbn.kompendium.core.Notarized.notarizedPost import io.bkbn.kompendium.core.metadata.ParameterExample import io.bkbn.kompendium.core.metadata.RequestInfo import io.bkbn.kompendium.core.metadata.ResponseInfo import io.bkbn.kompendium.core.metadata.method.DeleteInfo import io.bkbn.kompendium.core.metadata.method.GetInfo import io.bkbn.kompendium.core.metadata.method.PostInfo import io.ktor.application.* import io.ktor.http.* import io.ktor.request.* import io.ktor.response.* import io.ktor.routing.* import org.eclipse.tractusx.managedidentitywallets.models.BadRequestException import org.eclipse.tractusx.managedidentitywallets.models.ConflictException import org.eclipse.tractusx.managedidentitywallets.models.ExceptionResponse import org.eclipse.tractusx.managedidentitywallets.models.SelfManagedWalletCreateDto import org.eclipse.tractusx.managedidentitywallets.models.SelfManagedWalletResultDto import org.eclipse.tractusx.managedidentitywallets.models.StoreVerifiableCredentialParameter import org.eclipse.tractusx.managedidentitywallets.models.SuccessResponse import org.eclipse.tractusx.managedidentitywallets.models.UnprocessableEntityException import org.eclipse.tractusx.managedidentitywallets.models.WalletCreateDto import org.eclipse.tractusx.managedidentitywallets.models.WalletDto import org.eclipse.tractusx.managedidentitywallets.models.WalletDtoParameter import org.eclipse.tractusx.managedidentitywallets.models.conflictException import org.eclipse.tractusx.managedidentitywallets.models.forbiddenException import org.eclipse.tractusx.managedidentitywallets.models.notFoundException import org.eclipse.tractusx.managedidentitywallets.models.semanticallyInvalidInputException import org.eclipse.tractusx.managedidentitywallets.models.ssi.CredentialStatus import org.eclipse.tractusx.managedidentitywallets.models.ssi.InvitationRequestDto import org.eclipse.tractusx.managedidentitywallets.models.ssi.IssuedVerifiableCredentialRequestDto import org.eclipse.tractusx.managedidentitywallets.models.ssi.JsonLdContexts import org.eclipse.tractusx.managedidentitywallets.models.ssi.LdProofDto import org.eclipse.tractusx.managedidentitywallets.models.ssi.VerifiableCredentialDto import org.eclipse.tractusx.managedidentitywallets.models.syntacticallyInvalidInputException import org.eclipse.tractusx.managedidentitywallets.models.unauthorizedException import org.eclipse.tractusx.managedidentitywallets.services.IWalletService import org.jetbrains.exposed.exceptions.ExposedSQLException import java.time.LocalDateTime fun Route.walletRoutes(walletService: IWalletService) { route("/wallets") { notarizedAuthenticate(AuthorizationHandler.JWT_AUTH_TOKEN) { notarizedGet( GetInfo<Unit, List<WalletDto>>( summary = "List of wallets", description = "Permission: " + "**${AuthorizationHandler.getPermissionOfRole(AuthorizationHandler.ROLE_VIEW_WALLETS)}**\n" + "\nRetrieve list of registered wallets", responseInfo = ResponseInfo( status = HttpStatusCode.OK, description = "List of wallets", ), canThrow = setOf(forbiddenException, unauthorizedException), tags = setOf("Wallets") ) ) { AuthorizationHandler.checkHasRightsToViewWallet(call) call.respond(walletService.getAll()) } } notarizedAuthenticate(AuthorizationHandler.JWT_AUTH_TOKEN) { notarizedPost( PostInfo<Unit, WalletCreateDto, WalletDto>( summary = "Create wallet", description = "Permission: " + "**${AuthorizationHandler.getPermissionOfRole(AuthorizationHandler.ROLE_CREATE_WALLETS)}**\n" + "\nCreate a wallet and store it ", requestInfo = RequestInfo( description = "wallet to create", examples = walletCreateDtoExample ), responseInfo = ResponseInfo( status = HttpStatusCode.Created, description = "Wallet was successfully created", examples = walletDtoWithVerKeyExample ), canThrow = setOf(syntacticallyInvalidInputException, conflictException, forbiddenException, unauthorizedException), tags = setOf("Wallets") ) ) { AuthorizationHandler.checkHasRightToCreateWallets(call) try { val walletToCreate = call.receive<WalletCreateDto>() val createdWallet = walletService.createWallet(walletToCreate) call.respond(HttpStatusCode.Created, createdWallet) } catch (e: IllegalArgumentException) { throw BadRequestException(e.message) } catch (e: ExposedSQLException) { val isUniqueConstraintError = e.sqlState == "23505" if (isUniqueConstraintError) { throw ConflictException("Wallet with given BPN already exists!") } else { throw UnprocessableEntityException(e.message) } } } } route("/self-managed-wallets") { notarizedAuthenticate(AuthorizationHandler.JWT_AUTH_TOKEN) { notarizedPost( PostInfo<Unit, SelfManagedWalletCreateDto, SelfManagedWalletResultDto>( summary = "Register and Establish Initial Connection with Partners", description = "Permission: " + "**${AuthorizationHandler.getPermissionOfRole(AuthorizationHandler.ROLE_UPDATE_WALLETS)}**\n" + "\n Register self managed wallet and establish the initial connection with base wallet. " + "Also issue their membership and BPN credentials", requestInfo = RequestInfo( description = "Register self managed wallet, establish a connection and issue membership and BPN credentials", examples = selfManagedWalletCreateDtoExample ), responseInfo = ResponseInfo( status = HttpStatusCode.Created, description = "The request was able send a connection request to the DID", ), canThrow = setOf(notFoundException, syntacticallyInvalidInputException), ) ) { val selfManagedWalletCreateDto = call.receive<SelfManagedWalletCreateDto>() AuthorizationHandler.checkHasRightsToUpdateWallet(call, selfManagedWalletCreateDto.bpn) return@notarizedPost call.respond( HttpStatusCode.Created, walletService.registerSelfManagedWalletAndBuildConnection(selfManagedWalletCreateDto) ) } } } route("/{identifier}") { notarizedAuthenticate(AuthorizationHandler.JWT_AUTH_TOKEN) { notarizedGet( GetInfo<WalletDtoParameter, WalletDto>( summary = "Retrieve wallet by identifier", description = "Permission: " + "**${AuthorizationHandler.getPermissionOfRole(AuthorizationHandler.ROLE_VIEW_WALLETS)}** OR " + "**${AuthorizationHandler.getPermissionOfRole(AuthorizationHandler.ROLE_VIEW_WALLET)}** " + "(The BPN of Wallet to retrieve must equal the BPN of caller)\n" + "\nRetrieve single wallet by identifier, with or without its credentials", parameterExamples = setOf( ParameterExample("identifier", "did", "did:example:0123"), ParameterExample("identifier", "bpn", "bpn123"), ParameterExample("withCredentials", "withCredentials", "false") ), responseInfo = ResponseInfo( status = HttpStatusCode.OK, description = "The wallet", examples = walletDtoExample ), canThrow = setOf(syntacticallyInvalidInputException, notFoundException, forbiddenException, unauthorizedException), tags = setOf("Wallets") ) ) { val identifier = call.parameters["identifier"] ?: throw BadRequestException("Missing or malformed identifier") var withCredentials = false if (call.request.queryParameters["withCredentials"] != null) { withCredentials = call.request.queryParameters["withCredentials"].toBoolean() } AuthorizationHandler.checkHasRightsToViewWallet(call, identifier) val walletDto: WalletDto = walletService.getWallet(identifier, withCredentials) return@notarizedGet call.respond(HttpStatusCode.OK, walletDto) } } notarizedAuthenticate(AuthorizationHandler.JWT_AUTH_TOKEN) { notarizedDelete( DeleteInfo<Unit, SuccessResponse>( summary = "Remove wallet", description = "Permission: " + "**${AuthorizationHandler.getPermissionOfRole(AuthorizationHandler.ROLE_DELETE_WALLETS)}**\n" + "\nRemove hosted wallet", responseInfo = ResponseInfo( status = HttpStatusCode.OK, description = "Wallet successfully removed!", examples = mapOf("demo" to SuccessResponse("Wallet successfully removed!")) ), canThrow = setOf(notFoundException, syntacticallyInvalidInputException, forbiddenException, unauthorizedException), tags = setOf("Wallets") ) ) { val identifier = call.parameters["identifier"] ?: return@notarizedDelete call.respond(HttpStatusCode.BadRequest) AuthorizationHandler.checkHasRightToDeleteWallets(call) if (walletService.deleteWallet(identifier)) { return@notarizedDelete call.respond( HttpStatusCode.OK, SuccessResponse("Wallet successfully removed!") ) } call.respond(HttpStatusCode.BadRequest, ExceptionResponse("Delete wallet $identifier has failed!")) } } route("/credentials") { notarizedAuthenticate(AuthorizationHandler.JWT_AUTH_TOKEN) { notarizedPost( PostInfo<StoreVerifiableCredentialParameter, IssuedVerifiableCredentialRequestDto, SuccessResponse>( summary = "Store Verifiable Credential", description = "Permission: " + "**${AuthorizationHandler.getPermissionOfRole(AuthorizationHandler.ROLE_UPDATE_WALLETS)}** OR " + "**${AuthorizationHandler.getPermissionOfRole(AuthorizationHandler.ROLE_UPDATE_WALLET)}** " + "(The BPN of wallet to extract credentials from must equal BPN of caller)\n" + "\nStore a verifiable credential in the wallet of the given identifier", parameterExamples = setOf( ParameterExample("identifier", "did", "did:exp:123"), ParameterExample("identifier", "bpn", "BPN123"), ), requestInfo = RequestInfo( description = "The verifiable credential to be stored", examples = issuedVerifiableCredentialRequestDtoExample ), responseInfo = ResponseInfo( status = HttpStatusCode.Created, description = "Success message", examples = mapOf( "demo" to SuccessResponse( "Credential with id http://example.edu/credentials/3732" + "has been successfully stored" ) ) ), canThrow = setOf(semanticallyInvalidInputException, notFoundException, forbiddenException, unauthorizedException), tags = setOf("Wallets") ) ) { val identifier = call.parameters["identifier"] ?: throw BadRequestException("Missing or malformed identifier") AuthorizationHandler.checkHasRightsToUpdateWallet(call, identifier) try { val verifiableCredential = call.receive<IssuedVerifiableCredentialRequestDto>() walletService.storeCredential(identifier, verifiableCredential) call.respond( HttpStatusCode.Created, SuccessResponse("Credential has been successfully stored") ) } catch (e: ExposedSQLException) { val isUniqueConstraintError = e.sqlState == "23505" if (isUniqueConstraintError) { throw ConflictException("Credential already exists!") } else { throw UnprocessableEntityException(e.message) } } catch (e: Exception) { throw e } } } } route("/send-invitation") { notarizedAuthenticate(AuthorizationHandler.JWT_AUTH_TOKEN) { notarizedPost( PostInfo<Unit, InvitationRequestDto, Unit>( summary = "Send Connection Request", description = "Permission: " + "**${AuthorizationHandler.getPermissionOfRole(AuthorizationHandler.ROLE_UPDATE_WALLETS)}**\n" + "\n Send connection request to internal or external wallets.", requestInfo = RequestInfo( description = "The invitation request", examples = exampleInvitation ), responseInfo = ResponseInfo( status = HttpStatusCode.Accepted, description = "The connection request has been sent to the given DID", ), canThrow = setOf(notFoundException, syntacticallyInvalidInputException), ) ) { val identifier = call.parameters["identifier"] ?: throw BadRequestException("Missing or malformed identifier") AuthorizationHandler.checkHasRightsToUpdateWallet(call, identifier) val invitationRequestDto = call.receive<InvitationRequestDto>() walletService.sendInvitation(identifier, invitationRequestDto) return@notarizedPost call.respond(HttpStatusCode.Accepted) } } } } } } val exampleInvitation = mapOf( "demo" to InvitationRequestDto( theirPublicDid = "did:sov:example", alias = "alias", myLabel = "myLabel" ) ) val issuedVerifiableCredentialRequestDtoExample = mapOf( "demo" to IssuedVerifiableCredentialRequestDto( context = listOf( JsonLdContexts.JSONLD_CONTEXT_W3C_2018_CREDENTIALS_V1, JsonLdContexts.JSONLD_CONTEXT_W3C_2018_CREDENTIALS_EXAMPLES_V1 ), id = "http://example.edu/credentials/3732", type = listOf("University-Degree-Credential, VerifiableCredential"), issuer = "did:example:<KEY>", issuanceDate = "2019-06-16T18:56:59Z", expirationDate = "2019-06-17T18:56:59Z", credentialSubject = mapOf("college" to "Test-University"), credentialStatus = CredentialStatus( statusId = "http://example.edu/api/credentials/status/test#3", credentialType = "StatusList2021Entry", statusPurpose = "revocation", index= "3", listUrl= "http://example.edu/api/credentials/status/test" ), proof = LdProofDto( type = "Ed25519Signature2018", created = "2021-11-17T22:20:27Z", proofPurpose = "assertionMethod", verificationMethod = "did:example:<KEY>#key-1", jws = "<KEY>" ) ) ) val walletDtoWithVerKeyExample = mapOf( "demo" to WalletDto( "name", "bpn", "did", "verkey", LocalDateTime.now(), vcs = emptyList<VerifiableCredentialDto>().toMutableList(), pendingMembershipIssuance = false ) ) val walletDtoExample = mapOf( "demo" to WalletDto( "name", "bpn", "did", null, LocalDateTime.now(), vcs = emptyList<VerifiableCredentialDto>().toMutableList(), pendingMembershipIssuance = false ) ) val walletCreateDtoExample = mapOf( "demo" to WalletCreateDto( "name", "bpn" ) ) val selfManagedWalletCreateDtoExample = mapOf( "demo" to SelfManagedWalletCreateDto( name ="name", bpn = "bpn", did = "did", ) )
3
Kotlin
5
1
33537fdf039a771d551d175173d4c37d8dd17846
20,272
managed-identity-wallets-archived
Apache License 2.0
ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/properties/yaml/YamlNoContentException.kt
nemerosa
19,351,480
false
{"Kotlin": 8298680, "JavaScript": 2587834, "Java": 1129286, "HTML": 505573, "Groovy": 377453, "CSS": 137378, "Less": 35164, "Dockerfile": 6298, "Shell": 5086}
package net.nemerosa.ontrack.extension.av.properties.yaml import net.nemerosa.ontrack.common.BaseException class YamlNoContentException( expression: String, ) : BaseException( "Cannot evaluate expression because there is no content: $expression" )
39
Kotlin
26
94
c3cd484b681647bf68e43fa76a0bd4fccacf2972
257
ontrack
MIT License
src/test/kotlin/dev/storozhenko/familybot/infrastructure/TestSender.kt
AngryJKirk
114,262,178
false
{"Kotlin": 456535, "Shell": 2369, "Dockerfile": 1922}
package dev.storozhenko.familybot.infrastructure import dev.storozhenko.familybot.core.models.telegram.stickers.Sticker import org.mockito.invocation.InvocationOnMock import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatAdministrators import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMember import org.telegram.telegrambots.meta.api.methods.send.SendMessage import org.telegram.telegrambots.meta.api.methods.send.SendSticker import org.telegram.telegrambots.meta.api.methods.stickers.GetStickerSet import org.telegram.telegrambots.meta.api.objects.Message import org.telegram.telegrambots.meta.api.objects.User import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMember import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMemberAdministrator import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMemberMember import org.telegram.telegrambots.meta.api.objects.stickers.StickerSet import org.telegram.telegrambots.meta.bots.AbsSender import org.telegram.telegrambots.meta.api.objects.stickers.Sticker as TelegramSticker class TestSender { val sender = mock<AbsSender> { on { execute(any<SendMessage>()) } doReturn Message() on { execute(any<SendSticker>()) } doReturn Message() on { execute(any<GetStickerSet>()) } doReturn createStickers() on { execute(any<GetChatMember>()) } doAnswer requestedChatMember() on { execute(any<GetChatAdministrators>()) } doReturn requestedAdmins() } private fun requestedChatMember(): (InvocationOnMock) -> ChatMemberMember? = { val arg = it.arguments.first() as GetChatMember val userId = arg.userId ChatMemberMember().apply { user = User() user.id = userId user.userName = "user$userId" user.firstName = "Test user" user.lastName = "#$userId" } } private fun requestedAdmins(): ArrayList<ChatMember> { return ArrayList( (1L..3L).map { userId -> ChatMemberAdministrator().apply { user = User() user.id = userId user.userName = "user$userId" user.firstName = "Test user" user.lastName = "#$userId" } }, ) } private fun createStickers(): StickerSet { val stickers = Sticker.entries .map { sticker -> TelegramSticker().apply { emoji = sticker.stickerEmoji fileId = randomString() setName = sticker.pack.packName } } return StickerSet().apply { this.stickers = stickers } } }
0
Kotlin
5
110
17bd7aa36ef8963b8b673e2593c65e8cd4f06b83
2,965
familybot
MIT License
domain/src/main/java/com/roxana/recipeapp/domain/base/BaseSuspendableUseCase.kt
roxanapirlea
383,507,335
false
null
package com.roxana.recipeapp.domain.base abstract class BaseSuspendableUseCase<Input, Output> { suspend operator fun invoke(input: Input): Result<Output> { return try { val output = execute(input) Result.success(output) } catch (t: Throwable) { Result.failure(t) } } abstract suspend fun execute(input: Input): Output }
0
Kotlin
0
1
8dc3e7040d806893dddd4538e15dd3a40faa80a4
394
RecipeApp
Apache License 2.0
src/main/kotlin/org/portfolio/fileserver/service/GeneratorService.kt
K1rakishou
107,563,014
false
{"Kotlin": 33215, "HTML": 169}
package org.portfolio.fileserver.service interface GeneratorService { fun generateRandomString(len: Int, alphabet: String): String fun generateNewFileName(): String }
0
Kotlin
0
1
b4d7142572bf42f117d004b7a934cd4186be038b
175
fileserver
Do What The F*ck You Want To Public License
settings.gradle.kts
emmaboecker
412,768,830
true
{"Kotlin": 292593}
rootProject.name = "github-api-wrapper" enableFeaturePreview("VERSION_CATALOGS") enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") include( "core", "repositories", "repositories:branches", "bom", "full", "repositories:autolinks", "repositories:collaborators", "repositories:comments", "repositories:commits", "repositories:community" ) pluginManagement { repositories { gradlePluginPortal() mavenCentral() } } dependencyResolutionManagement { versionCatalogs { create("libs") { version("ktor", "1.6.3") alias("ktor-client-core").to("io.ktor", "ktor-client-core").versionRef("ktor") alias("ktor-client-okhttp").to("io.ktor", "ktor-client-okhttp").versionRef("ktor") alias("ktor-client-js").to("io.ktor", "ktor-client-js").versionRef("ktor") alias("ktor-client-auth").to("io.ktor", "ktor-client-auth").versionRef("ktor") alias("ktor-client-mock").to("io.ktor", "ktor-client-mock").versionRef("ktor") alias("ktor-client-serialization").to("io.ktor", "ktor-client-serialization").versionRef("ktor") alias("kotlinx-serialization-json").to("org.jetbrains.kotlinx", "kotlinx-serialization-json") .version("1.2.2") alias("kotlinx-datetime").to("org.jetbrains.kotlinx", "kotlinx-datetime").version("0.2.1") } create("test") { version("junit", "5.7.2") alias("junit5").to("org.junit.jupiter", "junit-jupiter-engine").versionRef("junit") } } } val isCi = System.getenv("GITHUB_ACTIONS") == "true" buildCache { remote<HttpBuildCache> { url = uri("https://gradle-cache.nycode.de/cache/") isPush = isCi credentials { username = System.getenv("GRADLE_CACHE_USER") password = System.getenv("GRADLE_CACHE_PASSWORD") } } }
0
null
0
0
2732723385084d165df38a62113f7ca318cd2e95
1,929
github-api-wrapper
Apache License 2.0
android-study-guide/app/src/main/java/dev/goobar/androidstudyguide/NavigationDestinations.kt
goobar-dev
571,410,157
false
{"Kotlin": 54468}
package dev.goobar.androidstudyguide /** * Defines routes to be used in conjunction with a [NavController] for navigating betetween * Composables */ object NavigationDestinations { val TOPICS = "/topics" val NOTES = "/notes" val ADD_NOTE = "/add-note" val TRENDING = "/trending" val HOME = "/home" }
0
Kotlin
1
2
a6b1526799efb5258f61628dc3f8641e175c3b54
323
deprecated-android-402-advanced-android-kotlin
Apache License 2.0
common-mvvm/src/androidMain/kotlin/com/link184/architecture/mvvm/KoinInitializer.kt
Link184
169,721,657
false
{"Kotlin": 63488}
package com.link184.architecture.mvvm import com.link184.architecture.mvvm.base.EmptyViewModel import org.koin.android.ext.koin.androidLogger import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.Koin import org.koin.core.context.startKoin import org.koin.core.context.stopKoin import org.koin.core.logger.Level import org.koin.core.module.Module import org.koin.dsl.KoinAppDeclaration import org.koin.dsl.module actual object KoinInitializer { actual fun startKoin(koinModules: List<Module>, logLevel: Level?, appDeclaration: KoinAppDeclaration) : Koin { return startKoin { appDeclaration() logLevel?.let { androidLogger(it) } modules(module { viewModel { EmptyViewModel() } }) modules(koinModules) }.koin } actual fun terminateKoin() { stopKoin() } }
0
Kotlin
0
0
c7d22da1b804b49aa1bf7572983c57c789cae7cd
861
ArchitectureMVVM
Apache License 2.0
app/src/main/java/com/koleff/kare_android/ui/compose/navigation/ExerciseDetailsToolbar.kt
MartinKoleff
741,013,199
false
{"Kotlin": 423021}
import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Settings import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import com.koleff.kare_android.R import com.koleff.kare_android.ui.MainScreen import com.koleff.kare_android.ui.compose.navigation.NavigationItem import com.koleff.kare_android.ui.compose.navigation.shapes.RoundedToolbarShape @Composable fun ExerciseDetailsToolbar( modifier: Modifier, navController: NavHostController, isNavigationInProgress: MutableState<Boolean>, exerciseImageId: Int ) { val primaryColor = MaterialTheme.colorScheme.primary val primaryContainerColor = MaterialTheme.colorScheme.primaryContainer val configuration = LocalConfiguration.current val screenHeight = configuration.screenHeightDp.dp val screenWidth = configuration.screenWidthDp.dp Box( modifier = modifier ) { //Exercise Muscle Group Image Image( painter = painterResource(id = exerciseImageId), contentDescription = "Image", contentScale = ContentScale.Crop, modifier = modifier.clip(RoundedToolbarShape()) ) //Navigation Row( Modifier .fillMaxWidth() .height(50.dp) .drawBehind { }, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { NavigationItem( // modifier = Modifier.drawBehind { // drawRect( // color = primaryContainerColor // ) // }, navController = navController, screen = null, //Backstack pop icon = Icons.Filled.ArrowBack, label = "Go back", isBlocked = isNavigationInProgress, tint = Color.White ) NavigationItem( // modifier = Modifier.drawBehind { // drawRect( // color = primaryContainerColor // ) // }, navController = navController, screen = MainScreen.Settings, icon = Icons.Filled.Settings, label = "Settings", isBlocked = isNavigationInProgress, tint = Color.White ) } } } @Preview @Composable fun PreviewExerciseDetailsToolbar() { val navController = rememberNavController() val configuration = LocalConfiguration.current val screenHeight = configuration.screenHeightDp.dp val screenWidth = configuration.screenWidthDp.dp ExerciseDetailsToolbar( modifier = Modifier .fillMaxWidth() .height(screenHeight / 2.5f) .background( // brush = Brush.verticalGradient( // colors = listOf( // MaterialTheme.colorScheme.primaryContainer, // MaterialTheme.colorScheme.primaryContainer, // MaterialTheme.colorScheme.primaryContainer, // MaterialTheme.colorScheme.primary, // MaterialTheme.colorScheme.primary // ) // ) color = MaterialTheme.colorScheme.primaryContainer ), isNavigationInProgress = mutableStateOf(false), navController = navController, exerciseImageId = R.drawable.ic_legs ) }
16
Kotlin
0
2
3402ad047fa4729c2ef3942f0bd718c0852b80c8
4,643
KareFitnessApp
MIT License
app/src/main/java/mustafaozhan/github/com/androcat/base/api/github/GitHubApiServices.kt
pahanchelo
198,120,459
true
{"Kotlin": 51177, "Java": 6772, "JavaScript": 4383}
package mustafaozhan.github.com.androcat.base.api.github import io.reactivex.Observable import mustafaozhan.github.com.androcat.model.Response import retrofit2.http.GET import retrofit2.http.Query interface GitHubApiServices { @GET("user") fun getUser(@Query("access_token") token: String?): Observable<Response> }
1
Kotlin
0
0
ebbaac02d9efaedc31c50b102070eb8a30da435c
324
AndroCat
Apache License 2.0
app/src/main/java/com/littlegnal/accounting/base/mvi/UiNotificationStatus.kt
qingmei2
144,553,525
true
{"Kotlin": 196307}
/* * Copyright (C) 2017 littlegnal * * 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.littlegnal.accounting.base.mvi /** * 像弹窗,toast或者动画等,很多时候我们只需要显示一次,所以通过该状态来控制 * * [SHOW] : 显示 * * [NONE] : 不显示 */ enum class UiNotificationStatus { SHOW, NONE }
0
Kotlin
1
1
591a8705bffebc79690f8bb716b35f81dc8d183c
857
Accounting
Apache License 2.0
kafka-core/src/main/kotlin/org/kishuomi/common/common.kt
Kishuomi
446,476,161
false
{"Kotlin": 18129}
package org.kishuomi.common import org.apache.kafka.clients.admin.AdminClient fun AdminClient.getTopicListNames(includeInternal: Boolean = false): List<String> = listTopics().namesToListings().get().values .filter { !it.isInternal || (includeInternal && it.isInternal) } .map { it.name() } .toList()
0
Kotlin
0
0
d56764abb4528e198d695aa47d242258ab858fc5
329
kafka-rest
Apache License 2.0
output/build.gradle.kts
aig787
320,055,206
true
{"Kotlin": 103776, "Dockerfile": 834}
group = "com.devo.feeds.output" plugins { id("feeds.library-conventions") } apply(plugin = Plugins.kotlinSerialization) dependencies { api(project(":data")) api(Libs.cloudbeesSyslog) api(Libs.kotlinCoroutinesCore) api(Libs.config4k) implementation(kotlin(Libs.kotlinStdLib)) implementation(Libs.kotlinLogging) implementation(Libs.kotlinSerializationJson) implementation(Libs.kafkaClient) testImplementation(project(":test-utils")) testImplementation(project(":storage")) Libs.logging.forEach { testImplementation(it) } testImplementation(Libs.hamkrest) testImplementation(Libs.awaitility) testImplementation(Libs.kafkaTestContainers) testImplementation(Libs.junitJupiterApi) testRuntimeOnly(Libs.junitJupiterEngine) }
3
Kotlin
0
0
9c8b4c18d7c83e839af863c75e59456079d1e1e2
791
feeds
MIT License
shared/qa/src/androidMain/kotlin/app/tivi/inject/AndroidActivityComponent.kt
chrisbanes
100,624,553
false
{"Kotlin": 906292, "Swift": 8717, "Shell": 3317, "Ruby": 3234, "Python": 1228}
// Copyright 2023, <NAME> and the Tivi project contributors // SPDX-License-Identifier: Apache-2.0 package app.tivi.inject import android.app.Activity import app.tivi.home.TiviContent import me.tatarka.inject.annotations.Component import me.tatarka.inject.annotations.Provides @ActivityScope @Component abstract class AndroidActivityComponent( @get:Provides override val activity: Activity, @Component val applicationComponent: AndroidApplicationComponent, ) : SharedActivityComponent, ProdUiComponent { abstract val tiviContent: TiviContent companion object }
21
Kotlin
856
6,308
247a024a7277ca6e9228b61dfb4b9eddd93d04aa
584
tivi
Apache License 2.0
px-services/src/main/java/com/mercadopago/android/px/model/internal/Button.kt
isabella232
465,809,447
true
{"Java": 1557816, "Kotlin": 778494, "Python": 4215}
package com.mercadopago.android.px.model.internal import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Button( val action: Action?, val target: String?, val type: Type?, val label: String ) : Parcelable { enum class Action { @SerializedName("continue") CONTINUE, @SerializedName("kyc") KYC, @SerializedName("change_pm") CHANGE_PM, @SerializedName("pay") PAY } enum class Type { @SerializedName("loud") LOUD, @SerializedName("quiet") QUIET, @SerializedName("transparent") TRANSPARENT } }
1
null
0
0
b8a3c2c45e66ee962e626edaed4f43c5a68359e9
666
px-android
MIT License
src/main/kotlin/com/abbisea/caves/systems/Wanderer.kt
lesbiangunshow
344,629,706
false
null
package com.abbisea.caves.systems import com.abbisea.caves.extensions.position import com.abbisea.caves.extensions.sameLevelNeighboursShuffled import com.abbisea.caves.messages.MoveTo import com.abbisea.caves.world.GameContext import org.hexworks.amethyst.api.base.BaseBehavior import org.hexworks.amethyst.api.entity.Entity import org.hexworks.amethyst.api.entity.EntityType object Wanderer : BaseBehavior<GameContext>() { override suspend fun update(entity: Entity<EntityType, GameContext>, context: GameContext): Boolean { val pos = entity.position if (pos.isUnknown.not()) { entity.receiveMessage( MoveTo( context = context, source = entity, position = pos.sameLevelNeighboursShuffled().first() ) ) return true } return false } }
0
Kotlin
0
0
9929ed7c8e07c6cf0ad9f25e4cb9093ba5dc70bb
904
caves-of-life-7drl
Apache License 2.0
src/jsBackendCommonMain/kotlin/de/robolab/common/externaljs/http/HTTP.kt
pixix4
243,975,894
false
null
@file:JsModule("http") @file:JsNonModule package de.robolab.common.externaljs.http import de.robolab.common.externaljs.JSArray import de.robolab.common.externaljs.stream.Readable import de.robolab.common.externaljs.stream.Writable external fun createServer(app: dynamic): dynamic external interface IncomingMessage : Readable { val aborted: Boolean val complete: Boolean fun destroy() fun destroy(error: Error) val headers: dynamic val httpVersion: String val rawHeaders: JSArray<String> val rawTrailers: JSArray<String> fun setTimeout(msecs: Int): IncomingMessage fun setTimeout(msecs: Int, callback: () -> Unit): IncomingMessage val trailers: dynamic } external interface IncomingServerMessage : IncomingMessage { val method: String val url: String } external interface ServerResponse : Writable { fun addTrailers(headers: dynamic) fun flushHeaders() fun getHeader(name: String): Any? fun getHeaderNames(): JSArray<String> fun getHeaders(): dynamic fun hasHeader(name: String): Boolean val headersSent: Boolean fun removeHeader(name: String) var sendDate: Boolean fun setHeader(name: String, value: dynamic) fun setTimeout(msecs: Int): ServerResponse fun setTimeout(msecs: Int, callback: () -> Unit): ServerResponse var statusCode: Int var statusMessage: String fun writeContinue() fun writeHead(statusCode: Int): ServerResponse fun writeHead(statusCode: Int, statusMessage: String): ServerResponse fun writeHead(statusCode: Int, headers: dynamic): ServerResponse fun writeHead(statusCode: Int, statusMessage: String, headers: dynamic): ServerResponse fun writeProcessing() }
4
Kotlin
1
2
1f20731971a9b02f971f01ab8ae8f4e506ff542b
1,737
robolab-renderer
MIT License
src/main/kotlin/no/nav/sbl/sosialhjelp_mock_alt/integrations/kodeverk/dto/KodeverkDto.kt
navikt
257,863,652
false
{"Kotlin": 218725, "Dockerfile": 427, "Shell": 217}
package no.nav.sbl.sosialhjelp_mock_alt.integrations.kodeverk.dto import com.fasterxml.jackson.annotation.JsonCreator class KodeverkDto @JsonCreator constructor(val betydninger: Map<String, List<BetydningDto>>)
1
Kotlin
0
0
f8253d72dc14d9fb5e5654d2c9289a8587e085fe
213
sosialhjelp-mock-alt-api
MIT License
buildSrc/src/main/kotlin/android.kt
NextFaze
90,596,780
false
null
@file:Suppress("RemoveRedundantBackticks", "NON_PUBLIC_CALL_FROM_PUBLIC_INLINE", "NOTHING_TO_INLINE") import com.android.build.gradle.BaseExtension import com.android.build.gradle.internal.dsl.BaseFlavor import org.gradle.api.Project import org.gradle.api.plugins.ExtensionAware object Android { const val compileSdkVersion = 28 const val minSdkVersion = 15 const val targetSdkVersion = 28 const val versionCode = 1 } @Suppress("unused") inline fun Project.configureAndroidLib() { androidExt { compileSdkVersion(Android.compileSdkVersion) defaultConfig { minSdkVersion(Android.minSdkVersion) targetSdkVersion(Android.targetSdkVersion) versionCode = Android.versionCode versionName = project.versionName consumerProguardFile("../proguard-rules-common.pro") testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" javaCompileOptions { annotationProcessorOptions { // We're using KAPT so ignore annotationProcessor configuration dependencies includeCompileClasspath = false if (project.isSnapshot) { argument("devfun.debug.verbose", "true") argument("devfun.logging.note.enabled", "true") } } } buildConfigField("VERSION_SNAPSHOT", project.isSnapshot) } resourcePrefix("df_${project.name.replace("devfun-", "")}_".replace('-', '_')) } } @Suppress("UnstableApiUsage") private inline fun Project.`androidExt`(noinline configure: BaseExtension.() -> Unit): Unit = (this as ExtensionAware).extensions.configure("android", configure) private inline fun <T : Any> BaseFlavor.buildConfigField(name: String, value: T) = when (value) { is Boolean -> buildConfigField("boolean", name, """Boolean.parseBoolean("$value")""") else -> throw RuntimeException("buildConfigField type ${value::class} not implemented.") }
5
Kotlin
4
49
cbf83014e478426750a2785b1e4e6a22d6964698
2,078
dev-fun
Apache License 2.0
lib-moshi/src/main/java/net/codefeet/lemmyandroidclient/gen/types/PrivateMessageReport.kt
Flex4Reddit
648,927,752
false
null
package net.codefeet.lemmyandroidclient.gen.types import android.os.Parcelable import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import kotlin.Boolean import kotlin.String import kotlinx.parcelize.Parcelize @Parcelize @JsonClass(generateAdapter = true) public data class PrivateMessageReport( public val id: PrivateMessageReportId, @Json(name = "creator_id") public val creatorId: PersonId, @Json(name = "private_message_id") public val privateMessageId: PrivateMessageId, @Json(name = "original_pm_text") public val originalPmText: String, public val reason: String, public val resolved: Boolean, @Json(name = "resolver_id") public val resolverId: PersonId?, public val published: String, public val updated: String?, ) : Parcelable
0
Kotlin
0
0
8028bbf4fc50d7c945d20c7034d6da2de4b7c0ac
779
lemmy-android-client
MIT License
app/src/main/java/com/june0122/wakplus/utils/diffcallbacks/ContentDiffCallback.kt
f-lab-edu
476,731,349
false
{"Kotlin": 116665}
package com.june0122.wakplus.utils.diffcallbacks import androidx.recyclerview.widget.DiffUtil import com.june0122.wakplus.data.entity.Content class ContentDiffCallback : DiffUtil.ItemCallback<Content>() { override fun areItemsTheSame(oldItem: Content, newItem: Content): Boolean { return oldItem.contentId == newItem.contentId } override fun areContentsTheSame(oldItem: Content, newItem: Content): Boolean { return oldItem == newItem } }
9
Kotlin
4
25
2b64c219ec20b8a3f1c09e6ba56942dae62e7875
472
wak-plus
Apache License 2.0
product-service/src/main/kotlin/br/com/maccommerce/productservice/domain/exception/EnvironmentVariableNotFoundException.kt
wellingtoncosta
251,454,379
false
null
package br.com.maccommerce.productservice.domain.exception import java.lang.RuntimeException class EnvironmentVariableNotFoundException(environmentVariableName: String) : RuntimeException( "Environment variable '$environmentVariableName' is not present. Check your system and try again." )
0
Kotlin
0
1
f25c2157e5ffe362e405a145e4889b4e9166897d
295
maccommerce
MIT License
app/src/main/java/com/developersancho/qnbmovie/movie/MovieAdapter.kt
developersancho
275,271,253
false
null
package com.developersancho.qnbmovie.movie import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import coil.api.load import com.developersancho.common.utils.CommonUtils import com.developersancho.qnbmovie.databinding.RowLoadMoreBinding import com.developersancho.qnbmovie.databinding.RowMovieBinding import com.developersancho.remote.model.Movie class MovieAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { var onMovieClick: ((Movie) -> Unit)? = null var onLoadMore: (() -> Unit)? = null private var items = listOf<Movie>() fun setData(movie: List<Movie>) { items = movie notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent.context) return if (viewType == ViewType.MOVIE_VIEW.value) { val itemBinding = RowMovieBinding.inflate(inflater, parent, false) MovieViewHolder(itemBinding) } else { val itemBinding = RowLoadMoreBinding.inflate(inflater, parent, false) LoadMoreViewHolder(itemBinding) } } override fun getItemCount(): Int = items.size + 1 override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder.itemViewType == ViewType.MOVIE_VIEW.value) { (holder as MovieViewHolder).bind(items[position]) } else { (holder as LoadMoreViewHolder).bind() } } override fun getItemViewType(position: Int): Int { return if (position == items.size) ViewType.LOAD_MORE_VIEW.value else ViewType.MOVIE_VIEW.value } inner class MovieViewHolder(private val binding: RowMovieBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(movie: Movie) { binding.ivPoster.load(CommonUtils.getPosterImage(movie.posterPath ?: "")) binding.tvTitle.text = movie.title binding.root.setOnClickListener { onMovieClick?.invoke(movie) } } } inner class LoadMoreViewHolder(private val binding: RowLoadMoreBinding) : RecyclerView.ViewHolder(binding.root) { fun bind() { binding.btnLoadMore.setOnClickListener { onLoadMore?.invoke() } } } } enum class ViewType(val value: Int) { LOAD_MORE_VIEW(0), MOVIE_VIEW(1) }
0
Kotlin
0
5
043b0f3a5763fa6998384c06821122ddf6a72e5e
2,483
qnbmovie
Apache License 2.0
komga/src/main/kotlin/org/gotson/komga/domain/service/SeriesCollectionLifecycle.kt
Kadantte
502,160,059
true
{"Kotlin": 1366049, "Vue": 575027, "TypeScript": 162380, "JavaScript": 3140, "Shell": 2891, "HTML": 1400, "Dockerfile": 427, "Sass": 309, "CSS": 304}
package org.gotson.komga.domain.service import mu.KotlinLogging import org.gotson.komga.application.events.EventPublisher import org.gotson.komga.domain.model.DomainEvent import org.gotson.komga.domain.model.DuplicateNameException import org.gotson.komga.domain.model.SeriesCollection import org.gotson.komga.domain.model.ThumbnailSeriesCollection import org.gotson.komga.domain.persistence.SeriesCollectionRepository import org.gotson.komga.domain.persistence.ThumbnailSeriesCollectionRepository import org.gotson.komga.infrastructure.image.MosaicGenerator import org.springframework.stereotype.Service import org.springframework.transaction.support.TransactionTemplate private val logger = KotlinLogging.logger {} @Service class SeriesCollectionLifecycle( private val collectionRepository: SeriesCollectionRepository, private val thumbnailSeriesCollectionRepository: ThumbnailSeriesCollectionRepository, private val seriesLifecycle: SeriesLifecycle, private val mosaicGenerator: MosaicGenerator, private val eventPublisher: EventPublisher, private val transactionTemplate: TransactionTemplate, ) { @Throws( DuplicateNameException::class, ) fun addCollection(collection: SeriesCollection): SeriesCollection { logger.info { "Adding new collection: $collection" } if (collectionRepository.existsByName(collection.name)) throw DuplicateNameException("Collection name already exists") collectionRepository.insert(collection) eventPublisher.publishEvent(DomainEvent.CollectionAdded(collection)) return collectionRepository.findByIdOrNull(collection.id)!! } fun updateCollection(toUpdate: SeriesCollection) { logger.info { "Update collection: $toUpdate" } val existing = collectionRepository.findByIdOrNull(toUpdate.id) ?: throw IllegalArgumentException("Cannot update collection that does not exist") if (existing.name != toUpdate.name && collectionRepository.existsByName(toUpdate.name)) throw DuplicateNameException("Collection name already exists") collectionRepository.update(toUpdate) eventPublisher.publishEvent(DomainEvent.CollectionUpdated(toUpdate)) } fun deleteCollection(collection: SeriesCollection) { transactionTemplate.executeWithoutResult { thumbnailSeriesCollectionRepository.deleteByCollectionId(collection.id) collectionRepository.delete(collection.id) } eventPublisher.publishEvent(DomainEvent.CollectionDeleted(collection)) } fun deleteEmptyCollections() { logger.info { "Deleting empty collections" } transactionTemplate.executeWithoutResult { val toDelete = collectionRepository.findAllEmpty() thumbnailSeriesCollectionRepository.deleteByCollectionIds(toDelete.map { it.id }) collectionRepository.delete(toDelete.map { it.id }) toDelete.forEach { eventPublisher.publishEvent(DomainEvent.CollectionDeleted(it)) } } } fun addThumbnail(thumbnail: ThumbnailSeriesCollection): ThumbnailSeriesCollection { when (thumbnail.type) { ThumbnailSeriesCollection.Type.USER_UPLOADED -> { thumbnailSeriesCollectionRepository.insert(thumbnail) if (thumbnail.selected) { thumbnailSeriesCollectionRepository.markSelected(thumbnail) } } } eventPublisher.publishEvent(DomainEvent.ThumbnailSeriesCollectionAdded(thumbnail)) return thumbnail } fun markSelectedThumbnail(thumbnail: ThumbnailSeriesCollection) { thumbnailSeriesCollectionRepository.markSelected(thumbnail) eventPublisher.publishEvent(DomainEvent.ThumbnailSeriesCollectionAdded(thumbnail.copy(selected = true))) } fun deleteThumbnail(thumbnail: ThumbnailSeriesCollection) { thumbnailSeriesCollectionRepository.delete(thumbnail.id) thumbnailsHouseKeeping(thumbnail.collectionId) eventPublisher.publishEvent(DomainEvent.ThumbnailSeriesCollectionDeleted(thumbnail)) } fun getThumbnailBytes(thumbnailId: String): ByteArray? = thumbnailSeriesCollectionRepository.findByIdOrNull(thumbnailId)?.thumbnail fun getThumbnailBytes(collection: SeriesCollection, userId: String): ByteArray { thumbnailSeriesCollectionRepository.findSelectedByCollectionIdOrNull(collection.id)?.let { return it.thumbnail } val ids = with(mutableListOf<String>()) { while (size < 4) { this += collection.seriesIds.take(4) } this.take(4) } val images = ids.mapNotNull { seriesLifecycle.getThumbnailBytes(it, userId) } return mosaicGenerator.createMosaic(images) } private fun thumbnailsHouseKeeping(collectionId: String) { logger.info { "House keeping thumbnails for collection: $collectionId" } val all = thumbnailSeriesCollectionRepository.findAllByCollectionId(collectionId) val selected = all.filter { it.selected } when { selected.size > 1 -> { logger.info { "More than one thumbnail is selected, removing extra ones" } thumbnailSeriesCollectionRepository.markSelected(selected[0]) } selected.isEmpty() && all.isNotEmpty() -> { logger.info { "Collection has no selected thumbnail, choosing one automatically" } thumbnailSeriesCollectionRepository.markSelected(all.first()) } } } }
1
null
0
1
a7e8d5f09d38ad6c8c1c41e8509517724f3e0205
5,232
komga
MIT License
app/src/main/java/com/example/feedbackprime/callprocess/api/models/Polarity.kt
aniketk13
417,912,751
true
{"Kotlin": 19235}
package com.example.feedbackprime.callprocess.api.models data class Polarity( val score: Float )
0
Kotlin
0
0
ac4ef864523293d2e45e4c80b6799e7d230bb5cc
102
Feedback-Prime
Apache License 2.0
sample/src/test/java/mohamedalaa/mautils/sample/AAAAAAAAA.kt
MohamedAlaaEldin636
178,618,838
false
null
/* * Copyright (c) 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 * * 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 mohamedalaa.mautils.sample import com.google.gson.reflect.TypeToken import org.junit.Test class AAAAAAAAA { inline fun <reified Q> f1(q: Q? = null) { f2(Q::class.java, object : TypeToken<Q>(){}.type.toString()) } fun f2(javaClass: Class<*>, s: String) { println() println("javaClass $s") println("javaClass == Set::class.java ${javaClass == Set::class.java}, ") println("javaClass == List::class.java ${javaClass == List::class.java}, ") println("javaClass == Array<Float>::class.java ${javaClass == Array<Float>::class.java}, ") println("javaClass.componentType == Float::class.java ${javaClass.componentType == Float::class.java}, ") println("javaClass == Array<String>::class.java ${javaClass == Array<String>::class.java}, ") // both true isa. println("javaClass == Array<String?>::class.java ${javaClass == Array<String?>::class.java}, ") } @Test fun f1() { f1<Set<Int>>() f1<List<Int>>() f1<Array<Int>>() f1(arrayOf(4f)) f1(listOf(3, 3).toTypedArray()) // this is Array<Int> not intArray isa. f1(floatArrayOf(5f)) f1(arrayOf("")) f1(arrayOf("", null, "s")) } }
0
Kotlin
0
0
16d6a8fdbf0d851c74485bdc1a609afaf3bb76f9
1,842
MAUtils
Apache License 2.0
app/src/main/java/com/example/weatherapp/ui/splashscreen/SplashActivity.kt
nicolasvc
366,546,731
false
null
package com.example.weatherapp.ui.splashscreen import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.viewpager2.widget.ViewPager2 import com.example.weatherapp.R import com.example.weatherapp.ui.informacionclima.InformacionClimaActivity import kotlinx.android.synthetic.main.activity_splash.* import kotlinx.android.synthetic.main.viewpager_weather.* import me.relex.circleindicator.CircleIndicator3 class SplashActivity : AppCompatActivity() { private var nombreCiudades = mutableListOf<String>() //region Sobrecarga override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportActionBar?.hide() setContentView(R.layout.activity_splash) //setContentView(R.layout.viewpager_weather) /*postList() viewPager2.adapter = ViewPageAdapter(nombreCiudades) viewPager2.orientation = ViewPager2.ORIENTATION_HORIZONTAL circleIndicator.setViewPager(viewPager2)*/ iniciarAplicacion() } //endregion private fun postList(){ for (i:Int in 1..5){ nombreCiudades.add("Ciudad $i") } } //region Propios private fun iniciarAplicacion() { imageViewSplash.alpha = 0f imageViewSplash.animate().setDuration(1500).alpha(1f).withEndAction { val intentInicio = Intent(this, InformacionClimaActivity::class.java) startActivity(intentInicio) overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) finish() } } //endregion }
0
Kotlin
0
0
b9ece609bedbd6096be54a3bad75b11ecd307cf0
1,633
WeatherApp
MIT License
app/src/main/java/com/nemscep/template_app/splash/SplashFragment.kt
nemscep
452,463,792
false
{"Kotlin": 23045}
package com.nemscep.template_app.splash import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.nemscep.template_app.MainGraphDirections import com.nemscep.template_app.R import com.nemscep.template_app.auth.ui.AuthFragment import com.nemscep.template_app.common.ui.viewBinding import com.nemscep.template_app.databinding.FragmentSplashBinding import org.koin.androidx.viewmodel.ext.android.viewModel class SplashFragment : Fragment(R.layout.fragment_splash) { private val binding by viewBinding(FragmentSplashBinding::bind) private val viewModel by viewModel<SplashViewModel>() private val deepLinkUrl get() = run { val args by navArgs<SplashFragmentArgs>() args.deepLinkUrl } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Setup live data. setupLiveData() // Setup result listeners. setupResultListeners() // Temp handleNavigation(deepLinkUrl = null) } private fun setupResultListeners() { val navController = findNavController() navController.currentBackStackEntry ?.savedStateHandle ?.getLiveData<AuthFragment.AuthResult>(AuthFragment.RESULT_KEY) ?.observe(viewLifecycleOwner) { authenticationResult -> when (authenticationResult) { AuthFragment.AuthResult.Cancelled -> navController.popBackStack() is AuthFragment.AuthResult.Success -> openDashboard(deepLinkUrl = deepLinkUrl) } } } private fun setupLiveData() { // TODO } private fun handleNavigation(deepLinkUrl: String?) { when (deepLinkUrl) { null -> openDashboard(deepLinkUrl) // TODO } arguments?.remove("deep_link_url") } private fun openDashboard(deepLinkUrl: String?) { findNavController().navigate(MainGraphDirections.actionGlobalDashboardFragment(deepLinkUrl = deepLinkUrl)) } }
0
Kotlin
0
1
bc4e0c5333d539f07af26f67c58ab4e19a0ebf75
2,217
template-app-android
Apache License 2.0
ziti/src/main/kotlin/org/openziti/net/dns/DNSResolver.kt
openziti
214,175,575
false
{"Kotlin": 347577, "Java": 43099}
/* * Copyright (c) 2018-2021 NetFoundry Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openziti.net.dns import java.io.Writer import java.net.InetAddress interface DNSResolver { fun resolve(hostname: String): InetAddress? fun lookup(addr: InetAddress): String? fun dump(writer: Writer) }
13
Kotlin
9
47
19aea125b658fffd573a77f8aa4fe66c4ce10d60
838
ziti-sdk-jvm
Apache License 2.0
src/Day02.kt
khongi
572,983,386
false
{"Kotlin": 24901}
sealed class HandGesture { abstract val score: Int abstract val defeats: HandGesture abstract val losesTo: HandGesture } object Rock : HandGesture() { override val score = 1 override val defeats = Scissors override val losesTo = Paper } object Paper : HandGesture() { override val score: Int = 2 override val defeats = Rock override val losesTo = Scissors } object Scissors : HandGesture() { override val score: Int = 3 override val defeats = Paper override val losesTo = Rock } fun main() { fun Char.getHandGesture(): HandGesture { return when (this) { 'A', 'X' -> Rock 'B', 'Y' -> Paper 'C', 'Z' -> Scissors else -> throw IllegalArgumentException("Input can't be $this") } } fun Char.getStrategyHandGesture(enemy: HandGesture): HandGesture { return when (this) { 'X' -> enemy.defeats 'Y' -> enemy 'Z' -> enemy.losesTo else -> throw IllegalArgumentException("Input can't be $this") } } fun HandGesture.calculateRound(enemy: HandGesture): Int { val combatScore = if (this.defeats == enemy) { 6 } else if (this.losesTo == enemy) { 0 } else { 3 } return combatScore + this.score } fun part1(input: List<String>): Int { var sum = 0 input.forEach { line -> val them = line[0].getHandGesture() val us = line[2].getHandGesture() sum += us.calculateRound(them) } return sum } fun part2(input: List<String>): Int { var sum = 0 input.forEach { line -> val them = line[0].getHandGesture() val us = line[2].getStrategyHandGesture(them) sum += us.calculateRound(them) } return sum } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9cc11bac157959f7934b031a941566d0daccdfbf
2,111
adventofcode2022
Apache License 2.0
app/src/main/java/id/my/fanslab/suitgamech5/ui/activity/LandingPageActivity.kt
meirusfandi
482,681,412
false
{"Kotlin": 19073}
package id.my.fanslab.suitgamech5.ui.activity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import id.my.fanslab.suitgamech5.R class LandingPageActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_landing_page) } }
0
Kotlin
0
0
f704ba37a55281533002e9edac2e7e22bdb08fbe
368
Chapter-5-Binar-Bootcamp-Code-Challenge
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsintegrationapi/models/hmpps/SentenceLength.kt
ministryofjustice
572,524,532
false
{"Kotlin": 583473, "Python": 32511, "Shell": 13474, "Dockerfile": 1154, "Makefile": 684}
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.models.hmpps data class SentenceLength( val duration: Int? = null, val units: String? = null, val terms: List<SentenceTerm> = emptyList(), )
1
Kotlin
1
2
b776c99457027adc73639de80ad5c8cea0a5ae9f
205
hmpps-integration-api
MIT License
common/src/mobileMain/kotlin/org/jetbrains/kotlinconf/ClientApi.kt
szymonnn
372,934,498
true
{"Kotlin": 138967, "Swift": 68709, "Ruby": 379}
package org.jetbrains.kotlinconf import io.ktor.client.* import io.ktor.client.features.* import io.ktor.client.features.json.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.util.date.* import kotlin.native.concurrent.* /** * Adapter to handle backend API and manage auth information. */ @ThreadLocal internal object ClientApi { val endpoint = "https://api.kotlinconf.com" private val client = HttpClient { install(JsonFeature) HttpResponseValidator { validateResponse { when (it.status) { COMEBACK_LATER_STATUS -> throw TooEarlyVote() TOO_LATE_STATUS -> throw TooLateVote() HttpStatusCode.Unauthorized -> throw Unauthorized() } if (!it.status.isSuccess()) { when (it.call.request.url.encodedPath) { "/favorites" -> throw CannotFavorite() else -> error("Bad status: ${it.status}") } } } } } /** * @return status of request. */ suspend fun sign(userId: String): Boolean { return client.post<HttpResponse> { apiUrl("users") body = userId }.status.isSuccess() } /** * Get [ConferenceData] info. * Load favorites and votes info if [userId] provided. */ suspend fun getAll(userId: String?): ConferenceData = client.get { apiUrl("all2019", userId) } /** * Update favorite information. */ suspend fun postFavorite(userId: String, sessionId: String): Unit = client.post { apiUrl("favorites", userId) body = sessionId } /** * Remove item from favorites list. */ suspend fun deleteFavorite(userId: String, sessionId: String): Unit = client.delete { apiUrl("favorites", userId) body = sessionId } /** * Vote for session. */ suspend fun postVote(userId: String, vote: VoteData): Unit = client.post { apiUrl("votes", userId) json() body = vote } /** * Remove vote. */ suspend fun deleteVote(userId: String, sessionId: String): Unit = client.delete { apiUrl("votes", userId) json() body = VoteData(sessionId) } /** * Get news feed. */ suspend fun getFeed(): FeedData = client.get { apiUrl("feed") } /** * Get server time. */ suspend fun getServerTime(): GMTDate = client.get<String> { apiUrl("time") }.let { response -> GMTDate(response.toLong()) } private fun HttpRequestBuilder.json() { contentType(ContentType.Application.Json) } private fun HttpRequestBuilder.apiUrl(path: String, userId: String? = null) { if (userId != null) { header(HttpHeaders.Authorization, "Bearer $userId") } header(HttpHeaders.CacheControl, "no-cache") url { takeFrom(endpoint) encodedPath = path } } }
0
Kotlin
0
0
f014d4a4d7aa3fede98fada6fdfcc2b28fca4784
3,140
kotlinconf-app
Apache License 2.0
src/main/kotlin/au/com/outware/cerberus/tasks/UpdateTicketTask.kt
outware
149,710,469
false
null
package au.com.outware.cerberus.tasks import au.com.outware.cerberus.CerberusPlugin import au.com.outware.cerberus.data.JiraClient import au.com.outware.cerberus.data.model.JiraCommentRequest import au.com.outware.cerberus.exceptions.GenericHttpException import au.com.outware.cerberus.exceptions.HttpAuthenticationException import au.com.outware.cerberus.util.getJiraTickets import au.com.outware.cerberus.util.makeComment open class UpdateTicketTask : NonEssentialTask() { override fun run() { val tickets = getJiraTickets() val ticketComment = makeComment(CerberusPlugin.properties?.buildNumber, CerberusPlugin.properties?.buildUrl, CerberusPlugin.properties?.hockeyAppShortVersion, CerberusPlugin.properties?.hockeyAppUploadUrl) tickets.forEach { commentOnJiraTicket(it.key, ticketComment) } } private fun commentOnJiraTicket(ticket: String, message: String) { val client = JiraClient("/rest/api/2/issue/$ticket/comment") val responseCode = client.post(JiraCommentRequest(message)) when (responseCode) { 201 -> println("Successfully commented on $ticket") in (400..499) -> { throw HttpAuthenticationException("Authentication failed. HTTP response code: $responseCode") } else -> { throw GenericHttpException("Comment on $ticket failed. HTTP response code: $responseCode") } } } }
0
Kotlin
2
3
6288c77f72f8ae53912d0b8d05001df2c860eb94
1,524
gradle-plugin-cerberus
MIT License
server/src/main/java/com/krillsson/sysapi/core/metrics/SystemMetrics.kt
Krillsson
40,235,586
false
{"Kotlin": 420391, "Java": 58934, "Dockerfile": 149}
package com.krillsson.sysapi.core.metrics import com.krillsson.sysapi.core.domain.processes.ProcessSort import com.krillsson.sysapi.core.domain.system.SystemInfo import com.krillsson.sysapi.core.domain.system.SystemLoad interface SystemMetrics { fun systemLoad( sort: ProcessSort = ProcessSort.MEMORY, limit: Int = -1 ): SystemLoad fun systemInfo(): SystemInfo }
9
Kotlin
2
83
4c06673a9563a0356d86c61c9592515c44ad1a68
393
sys-API
Apache License 2.0
powermanager-service/src/main/java/com/pyamsoft/powermanager/service/Manager.kt
pyamsoft
24,553,477
false
null
/* * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.powermanager.service import com.pyamsoft.pydroid.helper.SchedulerHelper import io.reactivex.Scheduler import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject import javax.inject.Named class Manager @Inject internal constructor(private val interactor: ManagerInteractor, @param:Named("io") private val scheduler: Scheduler) { private val compositeDisposable: CompositeDisposable = CompositeDisposable() init { SchedulerHelper.enforceBackgroundScheduler(scheduler) } fun enable(onEnabled: (() -> Unit)) { compositeDisposable.add( interactor.queueEnable().subscribeOn(scheduler).observeOn(scheduler).subscribe({ timber.log.Timber.d("%s: Queued up a new enable job", it) onEnabled.invoke() }) { throwable -> timber.log.Timber.e(throwable, "%s: onError enable") }) } fun disable(onDisabled: (() -> Unit)) { compositeDisposable.add( interactor.queueDisable().subscribeOn(scheduler).observeOn(scheduler).subscribe({ timber.log.Timber.d("%s: Queued up a new disable job", it) onDisabled.invoke() }) { throwable -> timber.log.Timber.e(throwable, "%s: onError disable") }) } fun cleanup() { compositeDisposable.clear() interactor.destroy() // Reset the device back to its original state when the Service is cleaned up enable { compositeDisposable.clear() } } }
0
Kotlin
0
0
bfc57e557e56a0503daae89a964a0ab447695b16
2,029
power-manager
Apache License 2.0
app/src/main/kotlin/batect/execution/model/rules/cleanup/RemoveContainerStepRule.kt
wyvern8
252,945,272
true
{"Kotlin": 2794589, "Python": 21919, "Shell": 19007, "Groovy": 11432, "PowerShell": 6532, "Dockerfile": 5578, "Batchfile": 3162, "Java": 1310, "HTML": 500}
/* Copyright 2017-2020 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.execution.model.rules.cleanup import batect.config.Container import batect.docker.DockerContainer import batect.execution.model.events.ContainerStoppedEvent import batect.execution.model.events.TaskEvent import batect.execution.model.rules.TaskStepRuleEvaluationResult import batect.execution.model.steps.RemoveContainerStep import batect.os.OperatingSystem data class RemoveContainerStepRule(val container: Container, val dockerContainer: DockerContainer, val containerWasStarted: Boolean) : CleanupTaskStepRule() { override fun evaluate(pastEvents: Set<TaskEvent>): TaskStepRuleEvaluationResult { if (containerWasStarted && !containerHasStopped(pastEvents)) { return TaskStepRuleEvaluationResult.NotReady } return TaskStepRuleEvaluationResult.Ready(RemoveContainerStep(container, dockerContainer)) } private fun containerHasStopped(pastEvents: Set<TaskEvent>): Boolean = pastEvents.contains(ContainerStoppedEvent(container)) override fun getManualCleanupInstructionForOperatingSystem(operatingSystem: OperatingSystem): String? = "docker rm --force --volumes ${dockerContainer.id}" override val manualCleanupSortOrder: ManualCleanupSortOrder = ManualCleanupSortOrder.RemoveContainers override fun toString() = "${this::class.simpleName}(container: '${container.name}', Docker container: '${dockerContainer.id}', container was started: $containerWasStarted)" }
4
Kotlin
0
0
ff441f765f1112385e0e2854206df375c12ddfcf
2,045
batect
Apache License 2.0