path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
FilesPicker/src/main/java/com/hashim/filespicker/gallerymodule/GalleryFilesFetcher.kt | hashimTahir | 451,656,161 | false | {"Kotlin": 83709} | package com.hashim.filespicker.gallerymodule
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.provider.MediaStore
import com.hashim.filespicker.gallerymodule.Constants.Companion.hDateMonthYearHrsMinFormat
import com.hashim.filespicker.gallerymodule.Constants.Companion.hHrsMinSecsFormat
import com.hashim.filespicker.gallerymodule.data.Folder
import timber.log.Timber
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
object GalleryFilesFetcher {
private val hVideosMap = mutableMapOf<Long, Folder>()
private val hImagesMap = mutableMapOf<Long, Folder>()
fun hFetchImages(hContext: Context): List<Folder.ImageFolder> {
try {
val hContentResolver = hContext.contentResolver
hContentResolver.query(
hGetMainUr(ProjectionType.Image),
hGetProjection(ProjectionType.Image),
"",
null,
""
).use { hCursor ->
hMapData(
hProjectionType = ProjectionType.Image,
hCursor = hCursor,
hContext = hContext,
)
hCursor?.close()
}
} catch (ex: Exception) {
Timber.d("Exception ${ex.message}")
}
return hImagesMap.values.filterIsInstance<Folder.ImageFolder>()
}
fun hFetchVideos(hContext: Context): List<Folder> {
try {
val hContentResolver = hContext.contentResolver
hContentResolver.query(
hGetMainUr(ProjectionType.Video),
hGetProjection(ProjectionType.Video),
"",
null,
""
).use { hCursor ->
hMapData(
ProjectionType.Video,
hCursor,
hContext,
)
hCursor?.close()
}
} catch (ex: Exception) {
Timber.d("Exception ${ex.message}")
}
return hVideosMap.values.filterIsInstance<Folder.VideoFolder>()
}
private fun hMapData(
hProjectionType: ProjectionType,
hCursor: Cursor?,
hContext: Context,
) {
when (hProjectionType) {
ProjectionType.Image -> hExtractImagesData(hCursor)
ProjectionType.Video -> hExtractVideosData(hCursor, hContext)
}
}
private fun hExtractVideosData(hCursor: Cursor?, hContext: Context) {
val hIdColumn = hCursor?.getColumnIndexOrThrow(MediaStore.Video.Media._ID)
val hBucketIdCol = hCursor?.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_ID)
val hBucketDisplayNameCol = hCursor?.getColumnIndexOrThrow(
MediaStore.Video.Media.BUCKET_DISPLAY_NAME
)
val hDisplayNameCol = hCursor?.getColumnIndexOrThrow(
MediaStore.Video.Media.DISPLAY_NAME
)
val hSizeCol = hCursor?.getColumnIndexOrThrow(
MediaStore.Video.Media.SIZE
)
val hDataCol = hCursor?.getColumnIndexOrThrow(
MediaStore.Video.Media.DATA
)
while (hCursor?.moveToNext() == true) {
val hId = hIdColumn?.let { hCursor.getLong(it) }
val hBucketDisplayName = hBucketDisplayNameCol?.let { hCursor.getString(it) }
val hBucketId = hBucketIdCol?.let { hCursor.getLong(it) }
val hDisplayName = hDisplayNameCol?.let { hCursor.getString(it) }
val hSize = hSizeCol?.let { hCursor.getString(it) }
val hPath = hDataCol?.let { hCursor.getString(it) }
val hContentUri: Uri? = hId?.let {
ContentUris.withAppendedId(
hGetMainUr(ProjectionType.Video),
it
)
}
hPath?.let {
File(it).apply {
val hFileDuration = hGetDuration(hContentUri, hContext)
val hLastModifiedData = hFormatDate(this.lastModified())
val hFolder = Folder.VideoFolder()
hFolder.hFolderName = hBucketDisplayName
hFolder.hFolderId = hBucketId
hCreateVideoItem(
hPath,
hDisplayName,
hSize,
hFileDuration,
this,
hLastModifiedData.toString(),
hContentUri
).also { hVideoItem ->
val hCheckMapFolder = hVideosMap[hFolder.hFolderId!!]
if (hCheckMapFolder != null) {
(hCheckMapFolder as Folder.VideoFolder).hVideoItemsList.add(hVideoItem)
} else {
hFolder.hVideoItemsList.add(hVideoItem)
hVideosMap[hFolder.hFolderId!!] = hFolder
}
}
}
}
}
}
private fun hExtractImagesData(hCursor: Cursor?) {
val hIdColumn = hCursor?.getColumnIndexOrThrow(
MediaStore.Images.Media._ID
)
val hBucketIdCol = hCursor?.getColumnIndexOrThrow(
MediaStore.Images.Media.BUCKET_ID
)
val hBucketDisplayNameCol = hCursor?.getColumnIndexOrThrow(
MediaStore.Images.Media.BUCKET_DISPLAY_NAME
)
val hDisplayNameCol = hCursor?.getColumnIndexOrThrow(
MediaStore.Images.Media.DISPLAY_NAME
)
val hSizeCol = hCursor?.getColumnIndexOrThrow(
MediaStore.Images.Media.SIZE
)
val hDataCol = hCursor?.getColumnIndexOrThrow(
MediaStore.Images.Media.DATA
)
while (hCursor?.moveToNext() == true) {
val hId = hIdColumn?.let { hCursor.getLong(it) }
val hBucketDisplayName = hBucketDisplayNameCol?.let { hCursor.getString(it) }
val hBucketId = hBucketIdCol?.let { hCursor.getLong(it) }
val hDisplayName = hDisplayNameCol?.let { hCursor.getString(it) }
val hSize = hSizeCol?.let { hCursor.getString(it) }
val hPath = hDataCol?.let { hCursor.getString(it) }
val hContentUri: Uri? = hId?.let {
ContentUris.withAppendedId(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
it
)
}
val hImageFolder = Folder.ImageFolder()
hImageFolder.hFolderId = hBucketId
hImageFolder.hFolderName = hBucketDisplayName
hCreateImageItem(
hPath,
hDisplayName,
hSize,
hContentUri
).also { hFolderItem->
val hCheckFolderMap = hImagesMap[hImageFolder.hFolderId!!]
if (hCheckFolderMap != null) {
(hCheckFolderMap as Folder.ImageFolder).hImageItemsList.add(hFolderItem)
} else {
hImageFolder.hImageItemsList.add(hFolderItem)
hImagesMap[hImageFolder.hFolderId!!] = hImageFolder
}
}
}
}
private fun hCreateImageItem(
hPath: String?,
hDisplayName: String?,
hSize: String?,
hContentUri: Uri?
): Folder.ImageItem {
return Folder.ImageItem(
hItemName = hDisplayName,
hSize = hSize,
hImagePath = hPath,
hImageUri = hContentUri.toString()
)
}
private fun hCreateVideoItem(
hPath: String?,
hDisplayName: String?,
hSize: String?,
hFileDuration: String?,
hFile: File,
hLastModifiedData: String,
hContentUri: Uri?
): Folder.VideoItem {
return Folder.VideoItem(
hFilePath = hPath,
hFileName = hDisplayName,
hFileSize = hSize,
hFileDuaration = hFileDuration,
hModifiedDate = hFile.lastModified(),
hFileSizeForOrder = hFile.length().toString(),
hFileDateTime = hLastModifiedData,
hUri = hContentUri.toString()
)
}
private fun hFormatDate(hLastModified: Long?): String? {
if (hLastModified != null) {
return SimpleDateFormat(hDateMonthYearHrsMinFormat, Locale.getDefault()).format(hLastModified)
}
return null
}
private fun hGetDuration(hPath: Uri?, context: Context): String? {
hPath?.let {
context.contentResolver.openFileDescriptor(it, "r")?.use {
MediaMetadataRetriever().apply {
setDataSource(it.fileDescriptor)
val hDurationLong = extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLong()
return SimpleDateFormat(hHrsMinSecsFormat, Locale.getDefault()).format(hDurationLong)
}
}
}
return null
}
}
private fun hGetMainUr(hProjectionType: ProjectionType): Uri {
return when (hProjectionType) {
is ProjectionType.Image -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
is ProjectionType.Video -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
}
}
private fun hGetProjection(hProjectionType: ProjectionType): Array<String> {
return when (hProjectionType) {
is ProjectionType.Video -> arrayOf(
MediaStore.Video.Media._ID,
MediaStore.Video.Media.BUCKET_ID,
MediaStore.Video.Media.BUCKET_DISPLAY_NAME,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DATA,
)
is ProjectionType.Image -> arrayOf(
MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.SIZE,
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.DATA,
)
}
}
sealed class ProjectionType {
object Image : ProjectionType()
object Video : ProjectionType()
}
| 0 | Kotlin | 2 | 14 | 934e634b05657ce937556a17493ab700c2b31c25 | 10,308 | Facebook-Styled-Image-Picker | Apache License 2.0 |
src/main/kotlin/dev/realmkit/game/domain/enemy/enums/EnemyTypeEnum.kt | RealmKit | 590,912,533 | false | null | /*
* Copyright (c) 2023 RealmKit
*
* 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 dev.realmkit.game.domain.enemy.enums
import dev.realmkit.game.domain.ship.enums.ShipTypeEnum
import dev.realmkit.game.domain.ship.enums.ShipTypeEnum.ALIEN_CRUISER
import dev.realmkit.game.domain.ship.enums.ShipTypeEnum.ROGUE_DRONE
private const val SOLO = 1
private const val VERY_TINY_FLEET = 3
private const val TINY_FLEET = 5
/**
* # [EnemyTypeEnum]
* the ship type enum
* @property enemies
*/
enum class EnemyTypeEnum(
vararg val enemies: Pair<Int, ShipTypeEnum>,
) {
ONE_ALIEN_CRUISER(
SOLO to ALIEN_CRUISER,
),
FLEET_OF_ALIEN_CRUISERS_WITH_DRONES(
VERY_TINY_FLEET to ALIEN_CRUISER,
TINY_FLEET to ROGUE_DRONE,
),
;
}
| 28 | Kotlin | 0 | 0 | c444ea63b415bd76fbb394b2a8f6a986c321f75c | 1,793 | game | MIT License |
app/src/main/java/dev/robert/spacexgo/features/rockets/presentation/RocketsScreet.kt | robert-muriithi | 586,537,208 | false | {"Kotlin": 219684} | package dev.robert.spacexgo.features.rockets.presentation
import android.annotation.SuppressLint
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImagePainter
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.coil.CoilImage
import dev.robert.spacexgo.R
import dev.robert.spacexgo.core.utils.UiEvents
import dev.robert.spacexgo.features.rockets.domain.model.Rocket
import dev.robert.spacexgo.core.presentation.theme.darkGrey
import dev.robert.spacexgo.features.destinations.RocketDetailsScreenDestination
import kotlinx.coroutines.flow.collectLatest
@Composable
@Destination
fun RocketsScreen(
navigator: DestinationsNavigator,
viewModel: RocketsViewModel = hiltViewModel(),
) {
val scaffoldState = rememberScaffoldState()
LaunchedEffect(key1 = true, block = {
viewModel.events.collectLatest { UiEvents ->
when (UiEvents) {
is UiEvents.ErrorEvent -> {
scaffoldState.snackbarHostState.showSnackbar(message = UiEvents.message)
}
is UiEvents.NavigationEvent -> {
//
}
}
}
})
val state = viewModel.rocketsState.value
RocketScreenContent(scaffoldState = scaffoldState, state = state, navigator = navigator)
}
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
private fun RocketScreenContent(
scaffoldState: ScaffoldState,
state: RocketsState,
navigator: DestinationsNavigator
) {
Scaffold(
scaffoldState = scaffoldState,
topBar = {
TopAppBar(
title = {
Text(text = "Rockets", fontFamily = FontFamily.Serif)
},
elevation = 1.dp
)
}
) {
Box(modifier = Modifier.fillMaxSize()) {
RocketLoadingStateComponent(state)
RocketsErrorStateComponent(state)
RocketsEmptyStateComponent(state)
ShipSuccessStateComponent(state, navigator = navigator)
}
}
}
@Composable
private fun ShipSuccessStateComponent(state: RocketsState, navigator: DestinationsNavigator) {
if (!state.isLoading && state.error == null && state.rockets.isNotEmpty()) {
LazyColumn() {
items(state.rockets) { item ->
RocketItem(item, navigator = navigator)
}
}
}
}
@Composable
private fun BoxScope.RocketsErrorStateComponent(state: RocketsState) {
if (!state.isLoading && state.error != null) {
Text(
text = state.error,
modifier = Modifier.align(Alignment.Center)
)
}
}
@Composable
private fun BoxScope.RocketsEmptyStateComponent(state: RocketsState) {
if (!state.isLoading && state.error != null && state.rockets.isEmpty()) {
Text(
text = "No rockets found",
modifier = Modifier.align(Alignment.Center)
)
}
}
@Composable
private fun BoxScope.RocketLoadingStateComponent(state: RocketsState) {
if (state.isLoading) {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center)
)
}
}
@Composable
fun RocketItem(
rocket: Rocket,
navigator: DestinationsNavigator
) {
Card(
elevation = 1.dp,
modifier = Modifier
.fillMaxWidth()
.height(80.dp)
.padding(8.dp)
.clickable {
navigator.navigate(RocketDetailsScreenDestination(rocket = rocket))
}
) {
RocketCardContent(rocket)
}
}
@Composable
private fun RocketCardContent(
rocket: Rocket
) {
Row(
modifier = Modifier.fillMaxSize(),
) {
Box(
modifier = Modifier
.fillMaxHeight()
.width(70.dp)
) {
CoilImage(
imageModel = {
rocket.flickrImages[0]
},
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
contentDescription = null,
),
modifier = Modifier.fillMaxSize(),
loading = {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center)
)
},
)
}
Column(
modifier = Modifier.padding(horizontal = 5.dp),
verticalArrangement = Arrangement.Center
) {
Text(
text = rocket.name,
style = TextStyle(
fontSize = 13.sp,
fontFamily = FontFamily.Serif,
fontWeight = FontWeight.Bold
),
)
Spacer(modifier = Modifier.height(5.dp))
Text(
text = rocket.type,
style = TextStyle(fontSize = 11.sp, fontFamily = FontFamily.Serif)
)
Text(
text = "Stages: ${rocket.stages}",
style = TextStyle(fontSize = 11.sp, fontFamily = FontFamily.Serif)
)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(vertical = 3.dp)
) {
Box(
modifier = Modifier
.clip(CircleShape)
.size(8.dp)
.background(
if (rocket.active) Color.Green else Color.Red
)
)
Text(
text = if (rocket.active) "Active" else "Inactive",
modifier = Modifier.padding(horizontal = 3.dp),
style = TextStyle(fontSize = 11.sp, fontFamily = FontFamily.Serif)
)
}
}
Column(
modifier = Modifier
.weight(1f)
.fillMaxHeight(),
horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.Center
) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Image(
modifier = Modifier
.size(16.dp)
.align(Alignment.CenterEnd),
painter = painterResource(id = R.drawable.arrow_forward),
contentDescription = null
)
}
}
}
} | 3 | Kotlin | 0 | 7 | e33d59efc00fa315f4380253bebbb90ab27d7cab | 7,975 | SpaceXGo | Apache License 2.0 |
jvm/src/test/kotlin/com/project/starter/quality/KotlinQualityPluginTest.kt | usefulness | 211,367,914 | false | {"Kotlin": 141179} | package com.project.starter.quality
import com.project.starter.WithGradleProjectTest
import com.project.starter.javaClass
import com.project.starter.kotlinClass
import org.assertj.core.api.Assertions.assertThat
import org.gradle.testkit.runner.TaskOutcome
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class KotlinQualityPluginTest : WithGradleProjectTest() {
@BeforeEach
fun setUp() {
rootDirectory.apply {
resolve("build.gradle") {
writeText(
// language=groovy
"""
plugins {
id('com.starter.library.kotlin')
}
""".trimIndent(),
)
}
resolve("src/main/kotlin/com/example/ValidKotlinFile1.kt") {
writeText(kotlinClass("ValidKotlinFile1"))
}
resolve("src/test/kotlin/com/example/ValidKotlinTest1.kt") {
writeText(kotlinClass("ValidKotlinTest1"))
}
resolve("src/test/java/com/example/ValidJavaTest1.java") {
writeText(javaClass("ValidJavaTest1"))
}
}
}
@Test
fun `projectCodeStyle runs Detekt`() {
val result = runTask("projectCodeStyle")
assertThat(result.task(":detekt")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
}
@Test
fun `projectCodeStyle runs ktlint`() {
val result = runTask("projectCodeStyle")
assertThat(result.task(":lintKotlinMain")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(result.task(":lintKotlinTest")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
}
}
| 1 | Kotlin | 5 | 26 | e4dbe95d369ba10962ae2f59aead36c2f612d11b | 1,727 | project-starter | MIT License |
app/src/main/java/io/github/takusan23/tatimidroid/nicovideo/compose/screen/NicoVideoListMenuScreen.kt | ugokitakunai | 420,580,612 | false | null | package io.github.takusan23.tatimidroid.nicovideo.compose.screen
import android.app.Application
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ComponentName
import android.content.Context
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.session.MediaControllerCompat
import android.widget.Toast
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import io.github.takusan23.tatimidroid.R
import io.github.takusan23.tatimidroid.compose.FillIconTextButton
import io.github.takusan23.tatimidroid.nicoad.compose.NicoAdScreen
import io.github.takusan23.tatimidroid.nicoad.viewmodel.NicoAdViewModelFactory
import io.github.takusan23.tatimidroid.nicoapi.NicoVideoCache
import io.github.takusan23.tatimidroid.nicovideo.viewmodel.factory.NicoVideoMyListViewModelFactory
import io.github.takusan23.tatimidroid.service.BackgroundPlaylistCachePlayService
import io.github.takusan23.tatimidroid.service.startCacheService
import io.github.takusan23.tatimidroid.service.startVideoPlayService
/**
* ニコ動一覧で使うメニュー。Composeでできている
*
* @param initRoute 最初に表示するメニュー
* @param navController rememberNavController
* @param onPlaylistClick 連続再生押したとき
* @param onUseInternetPlayClick インターネット経由で視聴を押したときに呼ばれる
* */
@Composable
fun NicoVideoListMenuScreen(
initRoute: String = "video_menu/{id}?title={title}?is_mylist={is_mylist}?is_cache={is_cache}",
navController: NavHostController = rememberNavController(),
onPlaylistClick: () -> Unit,
onUseInternetPlayClick: (String) -> Unit,
) {
val context = LocalContext.current
val application = context.applicationContext as Application
/** 引数を取得する */
fun NavBackStackEntry.getVideoId(): String = arguments!!.getString("id")!!
NavHost(navController = navController, startDestination = initRoute) {
composable("mylist/{id}") {
val videoId = it.getVideoId()
NicoVideoAddMylistScreen(
viewModel = viewModel(factory = NicoVideoMyListViewModelFactory(application, null)),
videoId = videoId
)
}
composable("nicoad/{id}") {
val videoId = it.getVideoId()
NicoAdScreen(viewModel = viewModel(factory = NicoAdViewModelFactory(application, videoId)))
}
composable("cache_delete/{id}") {
val videoId = it.getVideoId()
val nicoVideoCache = NicoVideoCache(context)
NicoVideoListMenuScreenCacheDeleteScreen(
onCancel = { navController.popBackStack() },
onDelete = { nicoVideoCache.deleteCache(videoId) }
)
}
composable("video_menu/{id}?title={title}?is_mylist={is_mylist}?is_cache={is_cache}") {
val videoTitle = it.arguments?.getString("title")
if (videoTitle != null) {
val videoId = it.getVideoId()
val isMylist = it.arguments!!.getString("is_mylist").toBoolean()
val isCache = it.arguments!!.getString("is_cache").toBoolean()
Column {
NicoVideoListMenuScreenInfo(videoId, videoTitle)
Divider()
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
NicoVideoListMenuScreenCopyButton(videoId)
if (isMylist) {
NicoVideoListMenuScreenMylistDeleteButton()
} else {
NicoVideoListMenuScreenMylistAddButton(onAddMylistClick = { navController.navigate("mylist/$videoId") })
}
NicoVideoListMenuScreenShowCommentListButton(onClick = {})
if (isCache) {
NicoVideoListMenuScreenCacheMusicModeButton(videoId = videoId)
}
NicoVideoListMenuScreenPlaylistButton(onClick = onPlaylistClick)
NicoVideoListMenuScreenPlayUseInternet(onClick = { onUseInternetPlayClick(videoId) })
NicoVideoListMenuScreenNicoAdButton(onClick = { navController.navigate("nicoad/$videoId") })
NicoVideoListMenuScreenPopupPlayButton(onClick = { startVideoPlayService(context, "popup", videoId, isCache) })
NicoVideoListMenuScreenBackgroundPlayButton(onClick = { startVideoPlayService(context, "backgournd", videoId, isCache) })
if (isCache) {
NicoVideoListMenuScreenCacheMenu(onDeleteClick = { navController.navigate("cache_delete/$videoId") })
} else {
NicoVideoListMenuScreenCacheGetMenu(videoId = videoId)
}
}
}
}
}
}
}
/**
* キャッシュ削除画面
*
* @param onCancel キャンセル押したら呼ばれる
* @param onDelete 削除押したら呼ばれる
* */
@Composable
private fun NicoVideoListMenuScreenCacheDeleteScreen(
onCancel: () -> Unit,
onDelete: () -> Unit
) {
Column {
NicoVideoListMenuScreenCacheDeleteScreenTitle()
FillIconTextButton(
text = stringResource(id = R.string.delete_cache),
icon = painterResource(id = R.drawable.ic_outline_delete_24px),
onClick = onDelete
)
FillIconTextButton(
text = stringResource(id = R.string.cancel),
icon = painterResource(id = R.drawable.ic_arrow_back_black_24dp),
onClick = onCancel
)
}
}
/** キャッシュ削除画面のタイトル部分 */
@Composable
private fun NicoVideoListMenuScreenCacheDeleteScreenTitle() {
Column {
Icon(
painter = painterResource(id = R.drawable.ic_outline_delete_24px),
contentDescription = null,
modifier = Modifier
.size(50.dp)
.padding(start = 10.dp, end = 10.dp)
)
Text(
text = stringResource(id = R.string.cache_delete_message),
fontSize = 20.sp,
modifier = Modifier
.padding(start = 10.dp, end = 10.dp, bottom = 10.dp)
)
}
}
/**
* キャッシュ取得メニュー
* */
@Composable
private fun NicoVideoListMenuScreenCacheGetMenu(videoId: String) {
val context = LocalContext.current
FillIconTextButton(
text = stringResource(id = R.string.get_cache),
icon = painterResource(id = R.drawable.ic_cache_progress_icon),
onClick = { startCacheService(context, videoId, false) }
)
FillIconTextButton(
text = stringResource(id = R.string.get_cache_eco),
icon = painterResource(id = R.drawable.ic_cache_progress_icon),
onClick = { startCacheService(context, videoId, true) }
)
}
/**
* キャッシュ再取得、削除ボタン
* @param onDeleteClick 削除押したら呼ばれる
* */
@Composable
private fun NicoVideoListMenuScreenCacheMenu(onDeleteClick: () -> Unit) {
FillIconTextButton(
text = stringResource(id = R.string.get_cache_re_get),
icon = painterResource(id = R.drawable.ic_refresh_black_24dp),
onClick = {
}
)
FillIconTextButton(
text = stringResource(id = R.string.cache_delete),
icon = painterResource(id = R.drawable.ic_outline_delete_24px),
onClick = onDeleteClick
)
}
/**
* バッググラウンド再生ボタン
* @param onClick 押したときに呼ばれる
* */
@Composable
private fun NicoVideoListMenuScreenBackgroundPlayButton(onClick: () -> Unit) {
FillIconTextButton(
text = stringResource(id = R.string.background_play),
icon = painterResource(id = R.drawable.ic_background_icon_black),
onClick = onClick
)
}
/**
* ポップアップ再生ボタン
* @param onClick 押したとき呼ばれる
* */
@Composable
private fun NicoVideoListMenuScreenPopupPlayButton(onClick: () -> Unit) {
FillIconTextButton(
text = stringResource(id = R.string.popup_player),
icon = painterResource(id = R.drawable.ic_popup_icon_black),
onClick = onClick
)
}
/**
* ニコニ広告ボタン
* @param onClick 押したとき呼ばれる
* */
@Composable
private fun NicoVideoListMenuScreenNicoAdButton(onClick: () -> Unit) {
FillIconTextButton(
text = stringResource(id = R.string.nicoads),
icon = painterResource(id = R.drawable.ic_outline_money_24px),
onClick = onClick
)
}
/**
* インターネットを利用して再生するボタン
* @param onClick 押したとき
* */
@Composable
private fun NicoVideoListMenuScreenPlayUseInternet(onClick: () -> Unit) {
FillIconTextButton(
text = stringResource(id = R.string.internet_play),
icon = painterResource(id = R.drawable.ic_play_arrow_24px),
onClick = onClick
)
}
/**
* 連続再生ボタン
* @param onClick 押したら呼ばれる
* */
@Composable
private fun NicoVideoListMenuScreenPlaylistButton(onClick: () -> Unit) {
FillIconTextButton(
text = stringResource(id = R.string.playlist_button),
icon = painterResource(id = R.drawable.ic_tatimidroid_list_icon_black),
onClick = onClick
)
}
/**
* キャッシュ用音楽モード起動ボタン
* @param nicoVideoData 動画情報
* */
@Composable
private fun NicoVideoListMenuScreenCacheMusicModeButton(videoId: String) {
val context = LocalContext.current
// MediaBrowserServiceに接続
val mediaBrowserCompat = remember {
val mediaBrowserCompat: MediaBrowserCompat?
mediaBrowserCompat = MediaBrowserCompat(
context,
ComponentName(context, BackgroundPlaylistCachePlayService::class.java),
object : MediaBrowserCompat.ConnectionCallback() {},
null
)
mediaBrowserCompat.connect()
return@remember mediaBrowserCompat
}
DisposableEffect(Unit) {
onDispose {
mediaBrowserCompat.disconnect()
}
}
FillIconTextButton(
text = stringResource(id = R.string.nicovideo_cache_music_mode),
icon = painterResource(id = R.drawable.ic_tatimidroid_playlist_play_black),
onClick = {
if (mediaBrowserCompat.isConnected) {
MediaControllerCompat(context, mediaBrowserCompat.sessionToken).transportControls?.playFromMediaId(videoId, null)
}
}
)
}
/** コメントのみ表示ボタン */
@Composable
private fun NicoVideoListMenuScreenShowCommentListButton(onClick: () -> Unit) {
FillIconTextButton(
text = stringResource(id = R.string.comment_list_only),
icon = painterResource(id = R.drawable.ic_outline_comment_24px),
onClick = onClick
)
}
/**
* マイリスト追加ボタン
* @param onAddMylistClick マイリスト追加押したら呼ばれる
* */
@Composable
private fun NicoVideoListMenuScreenMylistAddButton(
onAddMylistClick: () -> Unit
) {
FillIconTextButton(
text = stringResource(id = R.string.add_mylist),
icon = painterResource(id = R.drawable.ic_folder_open_black_24dp),
onClick = onAddMylistClick
)
}
/**
* マイリスト削除ボタン
* @param nicoVideoData 動画情報
* */
@Composable
private fun NicoVideoListMenuScreenMylistDeleteButton() {
FillIconTextButton(
text = stringResource(id = R.string.mylist_delete),
icon = painterResource(id = R.drawable.ic_outline_delete_24px),
onClick = { }
)
}
/**
* コピーボタン
* @param nicoVideoData 動画情報
* */
@Composable
private fun NicoVideoListMenuScreenCopyButton(videoId: String) {
val context = LocalContext.current
val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
FillIconTextButton(
text = stringResource(id = R.string.video_id_copy),
icon = painterResource(id = R.drawable.ic_content_paste_black_24dp),
onClick = {
clipboardManager.setPrimaryClip(ClipData.newPlainText("videoId", videoId))
Toast.makeText(context, "${context.getString(R.string.video_id_copy_ok)}:$videoId", Toast.LENGTH_SHORT).show()
}
)
}
/** 動画情報表示部分 */
@Composable
private fun NicoVideoListMenuScreenInfo(videoId: String, videoTitle: String) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier.weight(1f)) {
// タイトル
Text(
text = videoTitle,
modifier = Modifier.padding(5.dp),
style = TextStyle(fontSize = 18.sp),
)
// 動画ID
Text(
text = videoId,
modifier = Modifier.padding(5.dp),
style = TextStyle(fontSize = 12.sp),
)
}
}
}
/**
* 文字をコピーする関数
* @param text コピーする文字列
* */
private fun copyText(context: Context, text: String) {
val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboardManager.setPrimaryClip(ClipData.newPlainText(text, text))
}
| 0 | null | 0 | 0 | 745d6a4f0a00349c31e48403fa25488fe6bc346b | 13,593 | TatimiDroid | Apache License 2.0 |
app/src/main/java/org/itstep/liannoi/fractioncalculator/application/common/interfaces/RequestHandler.kt | liannoi | 292,411,983 | false | null | package org.itstep.liannoi.fractioncalculator.application.common.interfaces
interface BaseRequestHandler<in TRequest, TResponse>
where TRequest : Request<TResponse> {
fun handle(request: TRequest): TResponse
}
interface RequestHandler<in TRequest> : BaseRequestHandler<TRequest, Unit>
where TRequest : Request<Unit>
| 0 | Kotlin | 0 | 0 | 2c88f2f13c669d6d32c63b841622397dfa2f5764 | 339 | fraction-calculator | Apache License 2.0 |
remote/src/main/kotlin/com/cinema/entract/remote/CinemaService.kt | StephaneBg | 147,789,207 | false | null | /*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.cinema.entract.remote
import com.cinema.entract.remote.model.MovieRemote
import com.cinema.entract.remote.model.ParametersRemote
import com.cinema.entract.remote.model.PromotionalRemote
import com.cinema.entract.remote.model.WeekRemote
import retrofit2.http.GET
import retrofit2.http.PUT
import retrofit2.http.Query
interface CinemaService {
@GET("getFilmsJour.php")
suspend fun getMovies(@Query("jour") day: String): List<MovieRemote>
@GET("getProgramme.php")
suspend fun getSchedule(): List<WeekRemote>
@GET("getParametres.php")
suspend fun getParameters(): ParametersRemote
@GET("getLiensEvenement.php")
suspend fun getPromotional(): PromotionalRemote
@PUT("registerPushNotifications")
suspend fun registerNotifications(
@Query("type") type: String = "android",
@Query("deviceToken") token: String
)
@PUT("updateStatistiques.php")
suspend fun tagSchedule(@Query("page") type: String = "page_programme")
@PUT("updateStatistiques.php")
suspend fun tagPromotional(@Query("page") type: String = "page_evt")
@PUT("updateStatistiques.php")
suspend fun tagDetails(
@Query("page") type: String = "page_detail",
@Query("seance") sessionId: String
)
@PUT("updateStatistiques.php")
suspend fun tagCalendar(
@Query("page") type: String = "ajout_cal",
@Query("seance") sessionId: String
)
}
| 0 | Kotlin | 0 | 6 | 4453e5f02a0b2c6683cbbab4f8a8c551258930d6 | 2,023 | entract-cinema-android | Apache License 2.0 |
jvm/src/test/kotlin/com/jetbrains/infra/pgpVerifier/TestPgpSignaturesVerifierLogger.kt | JetBrains | 383,109,473 | false | {"Kotlin": 28690, "C#": 22144} | package com.jetbrains.infra.pgpVerifier
object TestPgpSignaturesVerifierLogger : PgpSignaturesVerifierLogger {
override fun info(message: String) {
println(message)
}
} | 0 | Kotlin | 3 | 3 | 836a4fe09957e81e9e66383e4ba3e2e3144b8124 | 185 | download-pgp-verifier | Apache License 2.0 |
bot/connector-web-model/src/main/kotlin/ai/tock/bot/connector/web/send/UrlButton.kt | theopenconversationkit | 84,538,053 | false | {"Kotlin": 6173880, "TypeScript": 1286450, "HTML": 532576, "Python": 376720, "SCSS": 79512, "CSS": 66318, "Shell": 12085, "JavaScript": 1849} | /*
* Copyright (C) 2017/2021 e-voyageurs technologies
*
* 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 ai.tock.bot.connector.web.send
import ai.tock.bot.connector.web.HrefTargetType
import com.fasterxml.jackson.annotation.JsonTypeName
@JsonTypeName("url_button")
data class UrlButton(
val title: String,
val url: String,
val imageUrl: String? = null,
val target: String? = HrefTargetType._blank.name,
val style: String? = ButtonStyle.primary.name
) : Button(ButtonType.web_url)
| 163 | Kotlin | 127 | 475 | 890f69960997ae9146747d082d808d92ee407fcb | 1,019 | tock | Apache License 2.0 |
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/messages/TLMessagesSlice.kt | Miha-x64 | 436,587,061 | true | {"Kotlin": 3919807, "Java": 75352} | package com.github.badoualy.telegram.tl.api.messages
import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID
import com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32
import com.github.badoualy.telegram.tl.api.TLAbsChat
import com.github.badoualy.telegram.tl.api.TLAbsMessage
import com.github.badoualy.telegram.tl.api.TLAbsUser
import com.github.badoualy.telegram.tl.core.TLObjectVector
import com.github.badoualy.telegram.tl.serialization.TLDeserializer
import com.github.badoualy.telegram.tl.serialization.TLSerializer
import java.io.IOException
/**
* messages.messagesSlice#3a54685e
*
* @author <NAME> <EMAIL>
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
class TLMessagesSlice() : TLAbsMessages() {
@Transient
var inexact: Boolean = false
var count: Int = 0
var nextRate: Int? = null
var offsetIdOffset: Int? = null
var messages: TLObjectVector<TLAbsMessage> = TLObjectVector()
var chats: TLObjectVector<TLAbsChat> = TLObjectVector()
var users: TLObjectVector<TLAbsUser> = TLObjectVector()
private val _constructor: String = "messages.messagesSlice#3a54685e"
override val constructorId: Int = CONSTRUCTOR_ID
constructor(
inexact: Boolean,
count: Int,
nextRate: Int?,
offsetIdOffset: Int?,
messages: TLObjectVector<TLAbsMessage>,
chats: TLObjectVector<TLAbsChat>,
users: TLObjectVector<TLAbsUser>
) : this() {
this.inexact = inexact
this.count = count
this.nextRate = nextRate
this.offsetIdOffset = offsetIdOffset
this.messages = messages
this.chats = chats
this.users = users
}
override fun computeFlags() {
_flags = 0
updateFlags(inexact, 2)
updateFlags(nextRate, 1)
updateFlags(offsetIdOffset, 4)
}
@Throws(IOException::class)
override fun serializeBody(tlSerializer: TLSerializer) = with (tlSerializer) {
computeFlags()
writeInt(_flags)
writeInt(count)
doIfMask(nextRate, 1) { writeInt(it) }
doIfMask(offsetIdOffset, 4) { writeInt(it) }
writeTLVector(messages)
writeTLVector(chats)
writeTLVector(users)
}
@Throws(IOException::class)
override fun deserializeBody(tlDeserializer: TLDeserializer) = with (tlDeserializer) {
_flags = readInt()
inexact = isMask(2)
count = readInt()
nextRate = readIfMask(1) { readInt() }
offsetIdOffset = readIfMask(4) { readInt() }
messages = readTLVector<TLAbsMessage>()
chats = readTLVector<TLAbsChat>()
users = readTLVector<TLAbsUser>()
}
override fun computeSerializedSize(): Int {
computeFlags()
var size = SIZE_CONSTRUCTOR_ID
size += SIZE_INT32
size += SIZE_INT32
size += getIntIfMask(nextRate, 1) { SIZE_INT32 }
size += getIntIfMask(offsetIdOffset, 4) { SIZE_INT32 }
size += messages.computeSerializedSize()
size += chats.computeSerializedSize()
size += users.computeSerializedSize()
return size
}
override fun toString() = _constructor
override fun equals(other: Any?): Boolean {
if (other !is TLMessagesSlice) return false
if (other === this) return true
return _flags == other._flags
&& inexact == other.inexact
&& count == other.count
&& nextRate == other.nextRate
&& offsetIdOffset == other.offsetIdOffset
&& messages == other.messages
&& chats == other.chats
&& users == other.users
}
companion object {
const val CONSTRUCTOR_ID: Int = 0x3a54685e
}
}
| 1 | Kotlin | 2 | 3 | 1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b | 3,840 | kotlogram-resurrected | MIT License |
app/src/main/java/com/xeniac/chillclub/feature_music_player/domain/use_cases/ObserveMusicVolumeChangesUseCase.kt | WilliamGates99 | 840,710,908 | false | {"Kotlin": 380219} | package com.xeniac.chillclub.feature_music_player.domain.use_cases
import com.xeniac.chillclub.feature_music_player.domain.repositories.MusicPlayerRepository
import com.xeniac.chillclub.feature_music_player.domain.repositories.MusicVolumePercentage
import kotlinx.coroutines.flow.Flow
class ObserveMusicVolumeChangesUseCase(
private val musicPlayerRepository: MusicPlayerRepository
) {
operator fun invoke(): Flow<MusicVolumePercentage> =
musicPlayerRepository.observeMusicVolumeChanges()
} | 0 | Kotlin | 0 | 2 | 4740cc0fca1dc7445c0a28793aefc35fbbf780e6 | 508 | ChillClub | Apache License 2.0 |
data/src/main/java/com/oguzdogdu/data/repository/UnsplashUserRepositoryImpl.kt | oguzsout | 616,912,430 | false | null | package com.oguzdogdu.data.repository
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.map
import com.oguzdogdu.data.common.Constants
import com.oguzdogdu.data.common.safeApiCall
import com.oguzdogdu.data.di.Dispatcher
import com.oguzdogdu.data.di.WalliesDispatchers
import com.oguzdogdu.data.source.paging.SearchPagingSource
import com.oguzdogdu.data.source.paging.SearchUsersPagingSource
import com.oguzdogdu.domain.model.search.searchuser.SearchUser
import com.oguzdogdu.domain.model.userdetail.UserCollections
import com.oguzdogdu.domain.model.userdetail.UserDetails
import com.oguzdogdu.domain.model.userdetail.UsersPhotos
import com.oguzdogdu.domain.repository.UnsplashUserRepository
import com.oguzdogdu.domain.wrapper.Resource
import com.oguzdogdu.network.model.collection.toUserCollection
import com.oguzdogdu.network.model.maindto.toDomainUsersPhotos
import com.oguzdogdu.network.model.searchdto.searchuser.SearchUsersResponse
import com.oguzdogdu.network.model.searchdto.searchuser.toSearchUser
import com.oguzdogdu.network.model.searchdto.toDomainSearch
import com.oguzdogdu.network.model.userdetail.toDomain
import com.oguzdogdu.network.service.UnsplashUserService
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.mapNotNull
import javax.inject.Inject
class UnsplashUserRepositoryImpl @Inject constructor(private val service: UnsplashUserService,@Dispatcher(
WalliesDispatchers.IO) private val ioDispatcher: CoroutineDispatcher
) :
UnsplashUserRepository {
override suspend fun getUserDetails(username: String?): Flow<Resource<UserDetails?>> {
return safeApiCall(ioDispatcher) {
service.getUserDetailInfos(username = username).body()?.toDomain()
}
}
override suspend fun getUsersPhotos(username: String?): Flow<Resource<List<UsersPhotos>?>>{
return safeApiCall(ioDispatcher) {
service.getUserPhotos(username = username).body().orEmpty().map {
it.toDomainUsersPhotos()
}
}
}
override suspend fun getUsersCollections(username: String?): Flow<Resource<List<UserCollections>?>> {
return safeApiCall(dispatcher = ioDispatcher) {
service.getUserCollections(username = username).body().orEmpty().map {
it.toUserCollection()
}
}
}
override suspend fun getSearchFromUsers(query: String?): Flow<PagingData<SearchUser>> {
val pagingConfig = PagingConfig(pageSize = Constants.PAGE_ITEM_LIMIT)
return Pager(
config = pagingConfig,
initialKey = 1,
pagingSourceFactory = { SearchUsersPagingSource(service = service, query = query ?: "") }
).flow.mapNotNull {
it.map { search ->
search.toSearchUser()
}
}
}
} | 0 | null | 6 | 61 | ddd410404ffd346e221fcd183226496411d8aa43 | 2,935 | Wallies | MIT License |
app/src/main/java/xyz/teamgravity/offlinecaching/arch/repository/MainRepositoryImpl.kt | raheemadamboev | 361,400,376 | false | null | package xyz.teamgravity.offlinecaching.arch.repository
import androidx.room.withTransaction
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import xyz.teamgravity.offlinecaching.arch.api.RandomDataApi
import xyz.teamgravity.offlinecaching.arch.database.RestaurantDatabase
import xyz.teamgravity.offlinecaching.helper.util.Resource
import xyz.teamgravity.offlinecaching.helper.util.networkBoundResource
import xyz.teamgravity.offlinecaching.model.RestaurantModel
class MainRepositoryImpl(
private val api: RandomDataApi,
private val db: RestaurantDatabase
) : MainRepository {
private val dao = db.restaurantDao()
override fun getRestaurants(): Flow<Resource<List<RestaurantModel>>> = networkBoundResource(
query = {
dao.getRestaurants()
},
fetch = {
delay(2000)
api.retrieveRestaurants()
},
saveFetchResult = { restaurants ->
db.withTransaction {
dao.deleteAll()
dao.insertAll(restaurants)
}
}
)
} | 0 | Kotlin | 2 | 8 | afcad8f414501c87cabba66be3e884aafd93c235 | 1,081 | simple-offline-caching-app | Apache License 2.0 |
MyBookLibrary/app/src/main/java/com/h10000b84/android/mybooklibrary/ui/scene/historyscene/HistoryPresenter.kt | kangkkang | 178,814,163 | false | null | package com.h10000b84.android.mybooklibrary.ui.scene.historyscene
import com.h10000b84.android.mybooklibrary.model.Book
import com.h10000b84.android.mybooklibrary.model.historyList
import com.h10000b84.android.mybooklibrary.util.androidThread
import com.h10000b84.android.mybooklibrary.util.ioThread
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
class HistoryPresenter : HistoryContract.Presenter {
private val subscriptions: CompositeDisposable by lazy { CompositeDisposable() }
private lateinit var view: HistoryContract.View
override fun subscribe() {
}
override fun unsubscribe() {
subscriptions.clear()
}
override fun attach(view: HistoryContract.View) {
this.view = view
}
override fun loadData() {
val subscribe = Single.just(historyList)
.subscribeOn(ioThread())
.observeOn(androidThread())
.doOnSuccess {
view.showProgress(false)
}
.doOnError {
view.showProgress(false)
}
.subscribe({ list: List<Book>? ->
view.loadDataSuccess(list!!)
}, { error ->
view.showErrorMessage(error.localizedMessage)
})
subscriptions.add(subscribe)
}
override fun deleteItem(book: Book) {
historyList.any { b -> b.isbn13.equals(book.isbn13) }.let {
if (it) historyList.remove(book)
}
}
} | 0 | Kotlin | 0 | 0 | 1743c97fe1428933d8e6350ab492a25bebdf822d | 1,555 | kotlin-mvp-rx-retrofit-di | Apache License 2.0 |
presentation/src/main/java/com/yapp/growth/presentation/component/PlanzModalBottomSheet.kt | YAPP-Github | 475,724,938 | false | {"Kotlin": 517158} | package com.yapp.growth.presentation.component
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetDefaults
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun PlanzModalBottomSheetLayout(
sheetState: ModalBottomSheetState,
sheetContent: @Composable () -> Unit,
scrimColor: Color = ModalBottomSheetDefaults.scrimColor,
content: @Composable () -> Unit,
) {
ModalBottomSheetLayout(
sheetBackgroundColor = Color.Transparent,
sheetState = sheetState,
sheetContent = {
Column(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
) {
PlanzModalBottomSheet {
sheetContent()
}
}
},
scrimColor = scrimColor,
content = content,
)
}
@Composable
fun PlanzModalBottomSheet(
sheetContent: @Composable () -> Unit,
) {
Spacer(
modifier = Modifier
.fillMaxWidth()
.height(24.dp)
.clip(RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp))
.background(color = Color.White)
)
sheetContent()
Spacer(
modifier = Modifier
.fillMaxWidth()
.height(20.dp)
.background(color = Color.White)
)
}
| 6 | Kotlin | 0 | 43 | 1dfc20bd4631567ea35def8d2fcb8414139c490d | 1,829 | 20th-Android-Team-1-FE | Apache License 2.0 |
matugr/src/main/java/com/matugr/authorization_request/external/AuthorizationOAuthErrorCode.kt | judegpinto | 453,862,040 | false | null | /*
* Copyright 2022 The Matugr Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.matugr.authorization_request.external
import com.matugr.common.oauth.AuthorizationErrorCodeBody
enum class AuthorizationOAuthErrorCode {
InvalidRequest,
UnAuthorizedClient,
AccessDenied,
UnSupportedResponseType,
InvalidScope,
ServerError,
TemporarilyUnavailable;
}
fun convertFromAuthorizationOAuthNetworkingError(
authorizationOAuthErrorCodeBody: AuthorizationErrorCodeBody
): AuthorizationOAuthErrorCode {
return when(authorizationOAuthErrorCodeBody) {
AuthorizationErrorCodeBody.InvalidRequest -> AuthorizationOAuthErrorCode.InvalidRequest
AuthorizationErrorCodeBody.UnauthorizedClient -> AuthorizationOAuthErrorCode.UnAuthorizedClient
AuthorizationErrorCodeBody.AccessDenied -> AuthorizationOAuthErrorCode.AccessDenied
AuthorizationErrorCodeBody.UnsupportedResponseType -> AuthorizationOAuthErrorCode.UnSupportedResponseType
AuthorizationErrorCodeBody.InvalidScope -> AuthorizationOAuthErrorCode.InvalidScope
AuthorizationErrorCodeBody.ServerError -> AuthorizationOAuthErrorCode.ServerError
AuthorizationErrorCodeBody.TemporarilyUnavailable -> AuthorizationOAuthErrorCode.TemporarilyUnavailable
}
} | 0 | Kotlin | 0 | 3 | adceecaa88c0f5b603fceb9b3607a57e2c217749 | 1,811 | matugr | Apache License 2.0 |
src/main/kotlin/br/ufrn/imd/obama/usuario/infrastructure/resource/AuthenticationResourceImpl.kt | obama-imd | 491,996,208 | false | {"Kotlin": 230849, "Dockerfile": 248} | package br.ufrn.imd.obama.usuario.infrastructure.resource
import br.ufrn.imd.obama.usuario.domain.usecase.UsuarioUseCase
import br.ufrn.imd.obama.usuario.infrastructure.configuration.TokenService
import br.ufrn.imd.obama.usuario.infrastructure.entity.UsuarioEntity
import br.ufrn.imd.obama.usuario.infrastructure.resource.exchange.LoginRequest
import br.ufrn.imd.obama.usuario.infrastructure.resource.exchange.LoginResponse
import io.swagger.v3.oas.annotations.tags.Tag
import jakarta.validation.Valid
import org.springframework.http.ResponseEntity
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping(
"/v1/auth"
)
@Tag(
name = "AuthenticationResource",
description = "Recurso que lida com a autenticação do usuário"
)
class AuthenticationResourceImpl(
private val authenticationManager: AuthenticationManager,
private val tokenService: TokenService,
private val usuarioUseCase: UsuarioUseCase
) {
@PostMapping("/login")
fun login(
@RequestBody @Valid request: LoginRequest
): ResponseEntity<LoginResponse> {
//TODO: Remover esse método no futuro, porque fluxo está assumindo mais de uma resposabilidade.
usuarioUseCase.alterarCriptografiaSenha(email = request.login, senha = request.senha)
val usernamePassword = UsernamePasswordAuthenticationToken(request.login, request.senha)
val auth = authenticationManager.authenticate(usernamePassword)
val token = tokenService.gerarToken( auth.principal as UsuarioEntity)
return ResponseEntity.ok().body(
LoginResponse(token)
)
}
}
| 13 | Kotlin | 0 | 3 | 83aa89efc5beb7314f1b47ca3ce81c43285a3170 | 1,982 | obama | Creative Commons Attribution 4.0 International |
kotlin-validators/src/main/kotlin/com/cleveroad/bootstrap/kotlin_validators/InviteCodeValidator.kt | Cleveroad | 114,619,348 | false | null | package com.cleveroad.bootstrap.kotlin_validators
import android.content.Context
import java.util.regex.Pattern
open class InviteCodeValidator private constructor(private val minLength: Int,
private val maxLength: Int,
private val emptyError: String,
private val invalidError: String,
private val additionalRegex: Regex?) : Validator {
companion object {
inline fun build(context: Context, block: InviteCodeValidator.Builder.() -> Unit) = InviteCodeValidator.Builder(context).apply(block).build()
fun builder(context: Context) = InviteCodeValidator.Builder(context)
fun getDefaultValidator(context: Context) = builder(context).build()
}
override fun validate(code: String?): ValidationResponse {
val error = if (code.isNullOrEmpty()) emptyError else if (!isCodeValid(code)) invalidError else ""
return ValidationResponseImpl(error.isEmpty(), error)
}
private fun isCodeValid(code: String) = !code.isEmpty()
&& code.length >= minLength && code.length <= maxLength
&& checkPatternAndValidate(code)
private fun checkPatternAndValidate(code: String) = additionalRegex?.matches(code) ?: true
class Builder constructor(aContext: Context) {
private val context = aContext.applicationContext
var minLength: Int = context.resources.getInteger(R.integer.min_code_length)
var maxLength: Int = context.resources.getInteger(R.integer.max_code_length)
var emptyError: String = context.getString(R.string.code_is_empty)
var invalidError: String = context.getString(R.string.code_is_invalid)
var additionalRegex: Regex? = null
fun minLength(length: Int) = apply { if (length > 0) minLength = length }
fun maxLength(length: Int) = apply { if (length > 0) maxLength = length }
fun emptyError(error: String?) = apply {
emptyError = error ?: ""
}
fun invalidError(error: String?) = apply {
invalidError = error ?: ""
}
fun additionalRegex(additionalRegex: Regex?) = apply { this.additionalRegex = additionalRegex }
fun additionalRegex(additionalRegex: String?) = apply { this.additionalRegex = additionalRegex?.toRegex() }
fun additionalRegex(additionalRegex: Pattern?) = apply { this.additionalRegex = additionalRegex?.toRegex() }
fun build(): Validator {
maxLength = Math.max(maxLength, minLength)
return InviteCodeValidator(minLength, maxLength, emptyError, invalidError, additionalRegex)
}
}
}
| 3 | Kotlin | 6 | 38 | 7bc51f35e26b1f0ca600422a57fc37b2231b726a | 2,782 | Bootstrap | The Unlicense |
mvp-dialog-sample/src/main/java/ru/surfstudio/android/mvp/dialog/sample/ui/screen/dialogs/simple/bottom/SimpleBottomSheetDialogRoute.kt | llOldmenll | 153,600,669 | true | {"Kotlin": 965498, "Java": 812179, "FreeMarker": 79263, "Groovy": 8783} | package ru.surfstudio.android.mvp.dialog.sample.ui.screen.dialogs.simple.bottom
import android.support.v4.app.DialogFragment
import ru.surfstudio.android.mvp.dialog.navigation.route.DialogRoute
class SimpleBottomSheetDialogRoute : DialogRoute() {
override fun getFragmentClass(): Class<out DialogFragment> = SimpleBottomSheetDialogFragment::class.java
} | 0 | Kotlin | 0 | 0 | 039e659bea18fae9e7254b5c2a341b59d0442cc0 | 359 | SurfAndroidStandard | Apache License 2.0 |
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/pm/conversation/ConversationView.kt | saletrak | 102,412,247 | true | {"Kotlin": 211185} | package io.github.feelfreelinux.wykopmobilny.ui.modules.pm.conversation
import io.github.feelfreelinux.wykopmobilny.base.BaseView
import io.github.feelfreelinux.wykopmobilny.models.dataclass.FullConversation
import io.github.feelfreelinux.wykopmobilny.models.dataclass.PMMessage
interface ConversationView : BaseView {
fun showConversation(conversation : FullConversation)
fun hideInputToolbar()
fun resetInputbarState()
fun hideInputbarProgress()
} | 0 | Kotlin | 0 | 0 | 0f2b65a46888e193134e8b94dacf5653ce5bb0ea | 467 | WykopMobilny | MIT License |
drawbox/src/main/java/com/t8rin/drawbox/domain/DrawController.kt | T8RIN | 478,710,402 | false | null | package com.t8rin.drawbox.domain
import android.graphics.Bitmap
import android.graphics.Paint
import androidx.compose.ui.graphics.Color
import com.t8rin.drawbox.presentation.model.DrawPath
import com.t8rin.drawbox.presentation.model.PaintOptions
interface DrawController {
val paths: Map<DrawPath, PaintOptions>
val lastPaths: Map<DrawPath, PaintOptions>
val undonePaths: Map<DrawPath, PaintOptions>
var paint: Paint
var drawPath: DrawPath
var paintOptions: PaintOptions
val backgroundColor: Color
var curX: Float
var curY: Float
var startX: Float
var startY: Float
var isStrokeWidthBarEnabled: Boolean
var isEraserOn: Boolean
fun undo()
fun redo()
fun setColor(newColor: Int)
fun setDrawBackground(color: Color)
fun setAlpha(newAlpha: Int)
fun setStrokeWidth(newStrokeWidth: Float)
suspend fun getBitmap(): Bitmap?
fun addPath(path: DrawPath, options: PaintOptions)
fun changePaint(paintOptions: PaintOptions)
fun toggleEraser()
fun clearPaths()
fun clearDrawing()
}
@Suppress("UNUSED_PARAMETER")
abstract class AbstractDrawController : DrawController {
override val paths: Map<DrawPath, PaintOptions>
get() = emptyMap()
override val lastPaths: Map<DrawPath, PaintOptions>
get() = emptyMap()
override val undonePaths: Map<DrawPath, PaintOptions>
get() = emptyMap()
override var paint: Paint
get() = Paint()
set(value) {}
override var drawPath: DrawPath
get() = DrawPath()
set(value) {}
override var paintOptions: PaintOptions
get() = PaintOptions()
set(value) {}
override val backgroundColor: Color
get() = Color.Transparent
override var curX: Float
get() = 0f
set(value) {}
override var curY: Float
get() = 0f
set(value) {}
override var startX: Float
get() = 0f
set(value) {}
override var startY: Float
get() = 0f
set(value) {}
override var isStrokeWidthBarEnabled: Boolean
get() = false
set(value) {}
override var isEraserOn: Boolean
get() = false
set(value) {}
override fun undo() {}
override fun redo() {}
override fun setColor(newColor: Int) {}
override fun setDrawBackground(color: Color) {}
override fun setAlpha(newAlpha: Int) {}
override fun setStrokeWidth(newStrokeWidth: Float) {}
override suspend fun getBitmap(): Bitmap? = null
override fun addPath(path: DrawPath, options: PaintOptions) {}
override fun changePaint(paintOptions: PaintOptions) {}
override fun toggleEraser() {}
override fun clearPaths() {}
override fun clearDrawing() {}
} | 15 | Kotlin | 47 | 514 | c039548b804f7d716972bd5f3648fac26a17e806 | 2,761 | ImageToolbox | Apache License 2.0 |
src/main/kotlin/org/mathematics/common/functions/Map.kt | aamct2 | 169,865,807 | false | null | package org.mathematics.common.functions
interface Map<T : Any, G : Any> {
fun applyMap(input: T): G
}
| 0 | Kotlin | 0 | 0 | b5b78952e12d7c566f9dc044b4a530be9f8a1436 | 108 | mathematics-kotlin | MIT License |
src/main/kotlin/org/webscene/client/notification_permission.kt | webscene | 84,691,058 | false | null | package org.webscene.client
/**
* Has all notification permission types that are used with the W3C Permission API.
*/
enum class NotificationPermission {
/** Permission hasn't been requested from the user yet. No notification will be displayed. **/
DEFAULT,
/** User has granted permission to display notifications. Notifications will be displayed. **/
GRANTED,
/** User has denied permission to display notifications. Notifications will *NOT* be displayed. **/
DENIED
}
val NotificationPermission.txt
get() = name.toLowerCase() | 0 | Kotlin | 0 | 0 | 0b68d69ae6b4a18885c5862eab84075a5d4eb734 | 560 | webscene-client | Apache License 2.0 |
database-test/src/commonMain/kotlin/com/alexvanyo/composelife/database/di/TestDatabaseComponent.kt | alexvanyo | 375,146,193 | false | {"Kotlin": 1943779} | /*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alexvanyo.composelife.database.di
import app.cash.sqldelight.db.SqlDriver
import com.alexvanyo.composelife.database.CellState
import com.alexvanyo.composelife.database.ComposeLifeDatabase
import com.alexvanyo.composelife.scopes.Singleton
import me.tatarka.inject.annotations.Provides
interface TestDatabaseComponent : DatabaseModule, TestDriverComponent, QueriesComponent, AdapterComponent {
@Provides
@Singleton
fun providesDatabase(
driver: SqlDriver,
cellStateAdapter: CellState.Adapter,
): ComposeLifeDatabase =
ComposeLifeDatabase(
driver = driver,
cellStateAdapter = cellStateAdapter,
)
}
| 36 | Kotlin | 10 | 99 | 64595b8d36c559a70ca52d578069fe4df8d170c7 | 1,300 | composelife | Apache License 2.0 |
core/src/main/java/com/ifmvo/togetherad/core/listener/RewardListener.kt | zhangbi18 | 311,344,968 | true | {"Kotlin": 152863} | package com.ifmvo.togetherad.core.listener
import org.jetbrains.annotations.NotNull
/**
* Created by <NAME> on 2020-04-22.
*/
interface RewardListener : BaseListener {
fun onAdLoaded(@NotNull providerType: String) {}
fun onAdClicked(@NotNull providerType: String) {}
fun onAdShow(@NotNull providerType: String) {}
fun onAdExpose(@NotNull providerType: String) {}
fun onAdVideoComplete(@NotNull providerType: String) {}
fun onAdVideoCached(@NotNull providerType: String) {}
fun onAdRewardVerify(@NotNull providerType: String) {}
fun onAdClose(@NotNull providerType: String) {}
} | 0 | null | 0 | 0 | 695a92fe32500f9a830130f282efdcaa9479cea6 | 623 | TogetherAd | MIT License |
kutil-unit-impl/src/main/java/net/kigawa/kutil/unitimpl/extension/store/LateInitStore.kt | kigawa01 | 534,968,547 | false | null | package net.kigawa.kutil.unitimpl.extension.store
import net.kigawa.kutil.unitapi.UnitIdentify
import net.kigawa.kutil.unitapi.annotation.getter.AlwaysInit
import net.kigawa.kutil.unitapi.component.*
import net.kigawa.kutil.unitapi.extention.UnitStore
import net.kigawa.kutil.unitapi.options.RegisterOptionEnum
import net.kigawa.kutil.unitapi.options.RegisterOptions
@Suppress("unused")
@AlwaysInit
class LateInitStore(
private val factoryComponent: UnitFactoryComponent,
): UnitStore {
private var obj: Any? = null
private var registered = false
override fun <T: Any> get(identify: UnitIdentify<T>): T {
synchronized(this) {
@Suppress("UNCHECKED_CAST")
if (obj != null) return obj as T
val obj = factoryComponent.init(identify, InitStack())
this.obj = obj
return obj
}
}
override fun <T: Any> initOrGet(identify: UnitIdentify<T>, initStack: InitStack): T {
return get(identify)
}
override fun initGetter(identify: UnitIdentify<out Any>, initStack: InitStack) {
}
override fun register(identify: UnitIdentify<out Any>, options: RegisterOptions): Boolean {
if (obj != null) return false
if (registered) return false
registered = true
return options.contain(RegisterOptionEnum.LATE_INIT)
}
} | 8 | Kotlin | 0 | 0 | d755464ff6490aa72155ccdd2100cdf4d9298b00 | 1,283 | kutil-unit | MIT License |
feature/museum/src/main/java/com/hanbikan/nook/feature/museum/CollectibleScreenUiState.kt | hanbikan | 737,877,468 | false | {"Kotlin": 361408} | package com.hanbikan.nook.feature.museum
import com.hanbikan.nook.core.common.getCurrentHour
import com.hanbikan.nook.core.domain.model.common.Collectible
import com.hanbikan.nook.core.domain.model.common.MonthToTimes.Companion.ALL_DAY
import com.hanbikan.nook.core.domain.model.common.Monthly
import com.hanbikan.nook.core.domain.model.common.parseTimeRange
import kotlin.math.ceil
enum class CollectibleScreenViewType {
LOADING, OVERALL, MONTHLY_GENERAL, MONTHLY_HOUR,
}
sealed class CollectibleScreenUiState(val chipIndex: Int?) {
object Loading : CollectibleScreenUiState(chipIndex = null)
class OverallView(val collectibleList: List<Collectible>) : CollectibleScreenUiState(chipIndex = 0)
sealed class MonthlyView(
val month: Int,
val isNorth: Boolean,
) : CollectibleScreenUiState(chipIndex = 1) {
class GeneralView(collectibleList: List<Collectible>, month: Int, isNorth: Boolean) : MonthlyView(month, isNorth) {
val collectibleListForMonth: List<Collectible> =
getCollectibleListForMonth(collectibleList, month)
private fun getCollectibleListForMonth(
collectibleList: List<Collectible>,
month: Int
): List<Collectible> {
return collectibleList.filter {
it is Monthly && it.belongsToMonth(month, isNorth)
}
}
}
class HourView(
collectibleList: List<Collectible>,
month: Int,
isNorth: Boolean,
private val minuteOffset: Int
) : MonthlyView(month, isNorth) {
val startHourToCollectibleListForMonth: Map<Int, List<Collectible>> =
getStartHourToCollectibleListForMonth(collectibleList, month)
/**
* startHour에 대응하는 endHour를 반환합니다.
*/
fun getEndHourByStartHour(startHour: Int): Int {
val hours = startHourToCollectibleListForMonth.keys.sorted()
val nextHourIndex = hours.indexOfFirst { it == startHour } + 1
return hours.getOrElse(nextHourIndex) { 24 }
}
fun isStartHourCurrentHourRange(startHour: Int): Boolean {
val endHour = getEndHourByStartHour(startHour)
val currentHour = getCurrentHour(minuteOffset)
return currentHour in startHour until endHour
}
/**
* 현재 시간에 해당하는 startHour key를 반환합니다.
*/
fun getCurrentHourKey(): Int {
val hours = startHourToCollectibleListForMonth.keys.sorted()
hours.forEach { startHour ->
if (isStartHourCurrentHourRange(startHour)) {
return startHour
}
}
return ALL_DAY_KEY
}
fun getScrollIndexForKey(
hourKey: Int,
itemsPerRow: Int
): Int {
var scrollIndex = 1
startHourToCollectibleListForMonth.forEach { (startHour, collectibleList) ->
if (startHour < hourKey) {
scrollIndex += 2 + ceil(
(collectibleList.count().toFloat() / itemsPerRow)
).toInt()
}
}
return scrollIndex
}
/**
* Returns {0: <Collectible List 1>, 4: <Collectible List 2>, ..., 21: <Collectible List 3>}
* which is merged by time range for same lists.
*/
private fun getStartHourToCollectibleListForMonth(
collectibleList: List<Collectible>,
month: Int
): Map<Int, List<Collectible>> {
val startHourToCollectibleListForMonth: MutableMap<Int, List<Collectible>> =
mutableMapOf()
val hourToCollectibleListForMonth =
getHourToCollectibleListForMonth(collectibleList, month)
hourToCollectibleListForMonth.forEach { (hour, collectibleListForHour) ->
// Skip if current collectible list is the same as the previous list.
if (hour - 1 >= 0 && collectibleListForHour == hourToCollectibleListForMonth[hour - 1]) {
return@forEach
}
startHourToCollectibleListForMonth[hour] = collectibleListForHour
}
return startHourToCollectibleListForMonth.toMap()
}
/**
* Returns {0: <Collectible List>, 1: <Collectible List>, ..., 23: <Collectible List>}
*/
private fun getHourToCollectibleListForMonth(
collectibleList: List<Collectible>,
month: Int
): Map<Int, List<Collectible>> {
val hourToCollectibleListForMonth = buildMap<Int, MutableList<Collectible>> {
put(-1, mutableListOf()) // for always available
repeat(24) { hour ->
put(hour, mutableListOf())
}
}
collectibleList.forEach { item ->
if (item is Monthly && item.belongsToMonth(month, isNorth)) {
val times = item.getCurrentMonthToTimes(isNorth).getTimesOrNull(month)
// 항상 잡을 수 있는 생물은 ALL_DAY_KEY에 추가합니다.
if (times == ALL_DAY) {
hourToCollectibleListForMonth[ALL_DAY_KEY]?.add(item)
} else {
val hours = times?.parseTimeRange() ?: listOf()
hours.forEach { hour ->
hourToCollectibleListForMonth[hour]?.add(item)
}
}
}
}
return hourToCollectibleListForMonth
.mapValues { it.value.toList() } // MutableList to List
.toMap()
}
companion object {
const val ALL_DAY_KEY = -1
}
}
}
} | 0 | Kotlin | 0 | 0 | a11874424d5923fb4f1ce32ccf0e83ae6d6dc9f9 | 6,261 | Nook | Apache License 2.0 |
src/Day15.kt | thpz2210 | 575,577,457 | false | {"Kotlin": 50995} | import kotlin.math.abs
private class Solution15(input: List<String>) {
val sensors = input.map { getSensorFrom(it) }
private fun getSensorFrom(line: String): Sensor {
val split = line.split("x=", "y=", ",", ":")
val position = Coordinate(split[1].toInt(), split[3].toInt())
val beacon = Coordinate(split[5].toInt(), split[7].toInt())
return Sensor(position, beacon)
}
fun part1(y: Int) = lineCover(y).sumOf { it.to - it.from + 1 } - beaconsInLine(y)
private fun beaconsInLine(y: Int) = sensors.map { it.beacon }.filter { it.y == y }.toSet().size
fun part2(max: Int): Long {
for (y in (0..max)) {
val lineCover = lineCover(y).singleOrNull() { it.from in 1..max }
if (lineCover != null) return (lineCover.from - 1) * 4000000L + y
}
throw IllegalStateException()
}
private fun lineCover(y: Int): List<LineCover> = sensors.mapNotNull { it.lineCover(y) }.sortedBy { it.from }
.fold<LineCover, List<LineCover>>(listOf()) { acc, fromTo -> reduceLineCovers(acc, fromTo) }
.fold(listOf()) { acc, fromTo -> reduceLineCovers(acc, fromTo) } // here happens magic
private fun reduceLineCovers(acc: List<LineCover>, rightCover: LineCover): List<LineCover> {
if (acc.isEmpty())
return listOf(rightCover)
val newAcc = mutableSetOf<LineCover>()
acc.forEach { leftCover ->
if (leftCover.from == rightCover.from && leftCover.to <= rightCover.to)
newAcc.add(rightCover)
else if (rightCover.to <= leftCover.to)
newAcc.add(leftCover)
else if (leftCover.to + 1 >= rightCover.from)
newAcc.add(LineCover(leftCover.from, rightCover.to))
else {
newAcc.add(leftCover)
newAcc.add(rightCover)
}
}
return newAcc.sortedBy { it.from }
}
data class Sensor(val position: Coordinate, val beacon: Coordinate) {
val distance = abs(position.x - beacon.x) + abs(position.y - beacon.y)
fun lineCover(y: Int): LineCover? {
val dx = distance - abs(y - position.y)
return if (dx >= 0) LineCover(position.x - dx, position.x + dx) else null
}
}
data class LineCover(var from: Int, var to: Int)
}
fun main() {
val testSolution = Solution15(readInput("Day15_test"))
check(testSolution.part1(10) == 26)
check(testSolution.part2(20) == 56000011L)
val solution = Solution15(readInput("Day15"))
println(solution.part1(2000000))
println(solution.part2(4000000))
}
| 0 | Kotlin | 0 | 0 | 69ed62889ed90692de2f40b42634b74245398633 | 2,650 | aoc-2022 | Apache License 2.0 |
api/src/main/kotlin/org/kryptonmc/api/block/meta/RedstoneSide.kt | KryptonMC | 255,582,002 | false | null | /*
* This file is part of the Krypton project, licensed under the Apache License v2.0
*
* Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.kryptonmc.api.block.meta
/**
* Indicates the way in which a redstone wire (placed redstone dust) block
* this property is applied to connects to an adjacent block on a specific
* face.
*/
public enum class RedstoneSide {
/**
* The wire travels vertically up the side of the adjacent block.
*
* This is always the case when there is another wire placed on the
* adjacent block's upper face.
*/
UP,
/**
* The wire travels horizontally along the floor, connecting in to the
* side of the adjacent block.
*/
SIDE,
/**
* The wire has no connection to the adjacent block.
*/
NONE;
/**
* Gets whether this side of the redstone wire is connected in some way, to
* either another wire or another block, rather than being not connected,
* or appearing as a single dot, meaning no connections on any faces.
*
* @return true if connected, false otherwise
*/
public fun isConnected(): Boolean = this != NONE
}
| 27 | Kotlin | 11 | 233 | a9eff5463328f34072cdaf37aae3e77b14fcac93 | 1,763 | Krypton | Apache License 2.0 |
src/main/kotlin/software/amazon/smithy/intellij/psi/SmithyAstTarget.kt | iancaffey | 455,381,865 | false | {"Kotlin": 286598, "Lex": 5063, "Smithy": 2929} | package software.amazon.smithy.intellij.psi
import software.amazon.smithy.intellij.SmithyShapeResolver.getDefinitions
/**
* A [shape member](https://awslabs.github.io/smithy/1.0/spec/core/model.html#member) target in the [Smithy](https://awslabs.github.io/smithy) [AST](https://awslabs.github.io/smithy/1.0/spec/core/json-ast.html).
*
* @author <NAME>
* @since 1.0
*/
data class SmithyAstTarget(
val enclosing: SmithyDefinition, val shapeId: String
) : SmithySyntheticElement(), SmithyShapeTarget {
private val parts = shapeId.split('#', limit = 2)
override val shapeName = parts[1]
override val declaredNamespace = parts[0]
override val resolvedNamespace = parts[0]
override fun getName() = shapeName
override fun getParent() = enclosing
override fun resolve() = getDefinitions(this, declaredNamespace, shapeName).firstOrNull()
} | 2 | Kotlin | 2 | 24 | 286adf8f042e9ebeeb28bbd99aa3ac320ed95f23 | 869 | smithy-intellij-plugin | MIT License |
korge-core/src/korlibs/image/style/DOM.kt | korlibs | 80,095,683 | false | {"WebAssembly": 14293935, "Kotlin": 9728800, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41} | package korlibs.image.style
import korlibs.datastructure.iterators.*
import korlibs.image.annotation.*
import korlibs.math.geom.*
import korlibs.math.interpolation.*
import kotlin.jvm.*
import kotlin.reflect.*
@KorimExperimental
open class DOM(val css: CSS) {
val elementsById = HashMap<String, DomElement>()
val elementsByClassName = HashMap<String, MutableSet<DomElement>>()
fun getSetForClassName(className: String) = elementsByClassName.getOrPut(className) { mutableSetOf() }
private val internalListener: DomListener = object : DomListener {
override fun removedId(element: DomElement, id: String) {
elementsById.remove(id)
}
override fun addedId(element: DomElement, id: String) {
elementsById[id] = element
}
override fun removedClass(element: DomElement, className: String) {
getSetForClassName(className).remove(element)
}
override fun addedClass(element: DomElement, className: String) {
getSetForClassName(className).add(element)
}
}
val listeners = arrayListOf(internalListener)
private val listener = ComposedDomListener(listeners)
class DomPropertyMapping() {
interface Mapping<T> {
val name: String
val property: KMutableProperty1<DomElement, T>
fun set(element: DomElement, prop: String, value: Any?)
}
class RatioMapping(
override val name: String,
override val property: KMutableProperty1<DomElement, Double?>
) : Mapping<Double?> {
override fun set(element: DomElement, prop: String, value: Any?) {
property.set(element, getRatio(prop, value).toDouble())
}
}
class MatrixMapping(
override val name: String,
override val property: KMutableProperty1<DomElement, Matrix>
) : Mapping<Matrix> {
override fun set(element: DomElement, prop: String, value: Any?) {
property.set(element, getMatrix(prop, value))
}
}
val mappings = HashMap<String, Mapping<*>>()
@JvmName("addRatio")
fun add(name: String, property: KMutableProperty1<out DomElement, out Double?>): DomPropertyMapping = this.apply { mappings[name] = RatioMapping(name,
property as KMutableProperty1<DomElement, Double?>
) }
@JvmName("addMatrix")
fun add(name: String, property: KMutableProperty1<out DomElement, out Matrix>): DomPropertyMapping = this.apply { mappings[name] = MatrixMapping(name,
property as KMutableProperty1<DomElement, Matrix>
) }
}
open class DomElement(val dom: DOM, val mappings: DomPropertyMapping? = null) {
private val listener get() = dom.listener
var id: String? = null
set(value) {
if (field != null) {
listener.removedId(this, field!!)
}
field = value
if (field != null) {
listener.addedId(this, field!!)
}
}
private val _classNames = mutableSetOf<String>()
val classNames: Set<String> get() = _classNames
fun addClassNames(vararg names: String) = names.fastForEach { addClassName(it) }
fun removeClassNames(vararg names: String) = names.fastForEach { removeClassName(it) }
fun addClassName(name: String) {
if (name in _classNames) return
_classNames.add(name)
listener.addedClass(this, name)
}
fun removeClassName(name: String) {
if (name !in _classNames) return
_classNames.remove(name)
listener.removedClass(this, name)
}
// @TODO: Maybe we can create a map like: "transform" to SvgElement::transform to Matrix::class
open fun setProperty(prop: String, value: Any?) {
mappings?.mappings?.get(prop)?.let { map ->
map.set(this, prop, value)
}
}
fun setPropertyInterpolated(result: CSS.InterpolationResult) {
val properties = result.properties
for (prop in properties) {
setProperty(prop, result)
}
}
}
interface DomListener {
fun removedId(element: DomElement, id: String) = updatedElement(element)
fun addedId(element: DomElement, id: String) = updatedElement(element)
fun removedClass(element: DomElement, className: String) = updatedElement(element)
fun addedClass(element: DomElement, className: String) = updatedElement(element)
fun updatedElement(element: DomElement) = Unit
}
class ComposedDomListener(val list: List<DomListener>) : DomListener {
override fun removedId(element: DomElement, id: String) = list.fastForEachReverse { it.removedId(element, id) }
override fun addedId(element: DomElement, id: String) = list.fastForEachReverse { it.addedId(element, id) }
override fun removedClass(element: DomElement, className: String) = list.fastForEachReverse { it.removedClass(element, className) }
override fun addedClass(element: DomElement, className: String) = list.fastForEachReverse { it.addedClass(element, className) }
override fun updatedElement(element: DomElement) = list.fastForEachReverse { it.updatedElement(element) }
}
companion object {
fun getTransform(prop: String, value: Any?): MatrixTransform = when (value) {
is MatrixTransform -> value
is CSS.InterpolationResult -> value.getTransform(prop)
is CSS.Expression -> value.transform
else -> MatrixTransform.IDENTITY
}
fun getMatrix(prop: String, value: Any?): Matrix = when (value) {
is Matrix -> value
is CSS.InterpolationResult -> value.getMatrix(prop)
is CSS.Expression -> value.matrix
else -> Matrix.IDENTITY
}
fun getRatio(prop: String, value: Any?): Ratio = when (value) {
is Float -> value.toRatio()
is Double -> value.toRatio()
is CSS.InterpolationResult -> value.getRatio(prop)
is CSS.Expression -> value.ratio
else -> Ratio.ZERO
}
}
}
| 444 | WebAssembly | 121 | 2,207 | dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a | 6,342 | korge | Apache License 2.0 |
app/src/main/java/net/hwyz/iov/ui/page/login/LoginState.kt | hwyzleo | 649,753,962 | false | null | package net.hwyz.iov.ui.page.login
import net.hwyz.iov.base.MviState
data class LoginState(
var countryRegionCode: String = "",
val mobile: String = "",
val verifyCode: String = "",
val isAgree: Boolean = false,
val isSendVerifyCode: Boolean = false,
val isLogged: Boolean = false
) : MviState {
companion object {
fun initialState(): LoginState = LoginState()
}
} | 0 | Kotlin | 0 | 0 | 7f67e8e7bb747a0e1f807ea7251fd30b54634775 | 406 | iov-android-app | Apache License 2.0 |
amalia-core/src/main/java/com/vicidroid/amalia/ext/ViewDelegateProvider.kt | vicidroiddev | 171,361,804 | false | null | package com.vicidroid.amalia.ext
import androidx.appcompat.app.AppCompatActivity
import com.vicidroid.amalia.core.ViewEvent
import com.vicidroid.amalia.core.ViewState
import com.vicidroid.amalia.ui.BaseViewDelegate
/**
* Used to conveniently inject parameters from the activity into the view delegate.
* Note: this `lazy` approach cannot be used by fragments due to the attach/detach lifecycle which will destroy the view but not the fragment instance.
*/
inline fun AppCompatActivity.viewDelegateProvider(crossinline viewDelegateCreator: () -> BaseViewDelegate) =
lazy {
viewDelegateCreator().also { delegate ->
delegate.setHostActivity(this)
}
}
/**
* Used for child view delegates. Allows injection of important fields such as [BaseViewDelegate.parent]
*/
inline fun BaseViewDelegate.viewDelegateProvider(crossinline viewDelegateCreator: () -> BaseViewDelegate) =
lazy {
viewDelegateCreator().also { delegate ->
delegate.parent = this
}
} | 7 | Kotlin | 0 | 9 | 0a4facc243feefe3f982f7f2915ccc5541dc321b | 1,021 | amalia | Apache License 2.0 |
src/main/kotlin/br/com/zupacademy/registra/controller/RegistraChaveEndpoint.kt | CharlesRodrigues-01 | 393,033,826 | true | {"Kotlin": 72390, "Smarty": 1872, "Dockerfile": 184} | package br.com.zupacademy.registra.controller
import br.com.zupacademy.KeyManagerRegistraGrpcServiceGrpc
import br.com.zupacademy.RegistraChavePixRequest
import br.com.zupacademy.RegistraChavePixResponse
import br.com.zupacademy.shared.exception.interceptor.ErrorHandler
import br.com.zupacademy.registra.request.toModel
import io.grpc.stub.StreamObserver
import org.slf4j.LoggerFactory
import javax.inject.Inject
import javax.inject.Singleton
@ErrorHandler
@Singleton
class RegistraChaveEndpoint(@Inject val service: NovaChavePixService) :
KeyManagerRegistraGrpcServiceGrpc.KeyManagerRegistraGrpcServiceImplBase() {
private val logger = LoggerFactory.getLogger(RegistraChaveEndpoint::class.java)
override fun registra(
request: RegistraChavePixRequest,
responseObserver: StreamObserver<RegistraChavePixResponse>
) {
val novaChave = request.toModel()
val chaveCriada = service.registra(novaChave)
logger.info("Montando resposta")
responseObserver.onNext(
RegistraChavePixResponse.newBuilder()
.setClientId(chaveCriada.clientId.toString())
.setPixId(chaveCriada.id.toString())
.build())
responseObserver.onCompleted()
}
} | 0 | Kotlin | 0 | 0 | 3e482e6eb1798501329ae0148326f398dc9e6318 | 1,249 | orange-talents-06-template-pix-keymanager-grpc | Apache License 2.0 |
src/main/kotlin/dreipc/plugins/development/modul/Lombok.kt | 3pc-Berlin | 641,448,549 | false | {"Kotlin": 24639, "Shell": 1108} | package dreipc.plugins.development.modul
import io.freefair.gradle.plugins.lombok.tasks.LombokConfig
import io.freefair.gradle.plugins.lombok.tasks.LombokTask
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.io.File
/**
* Java Code Generation plugin for reduction of boilerplate code for pojo's
* @see [Lombok Gradle](https://plugins.gradle.org/plugin/io.freefair.lombok)
* @see [Official Lombok](https://projectlombok.org/)
*
* Author: <NAME>
*/
class Lombok : Plugin<Project> {
override fun apply(project: Project) {
project.plugins.apply("io.freefair.lombok")
project.changeLombokGroupName("code generation")
addLombokConfig()
}
private fun Project.changeLombokGroupName(name: String) = afterEvaluate {
project.tasks.withType(LombokTask::class.java) {
group = name
}
this.tasks.withType(LombokConfig::class.java) {
group = name
}
}
private fun addLombokConfig() {
val lombokConfigFile = File("lombok.config")
if (lombokConfigFile.exists()) return
val lombokConfigContent = this::class.java.classLoader.getResourceAsStream("lombok.config")
?.bufferedReader()
?.readText()
?: ""
lombokConfigFile.writeText(lombokConfigContent, Charsets.UTF_8)
}
}
| 0 | Kotlin | 1 | 2 | d8b6ad61a323a2a439f727c7a5ac490e4bf55b7e | 1,270 | gradle-development-plugin | MIT License |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/AirTemperatureData.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: AirTemperatureData
*
* Full name: System`AirTemperatureData
*
* AirTemperatureData[] gives the most recent measurement for air temperature near the current location.
* AirTemperatureData[datespec] gives the air temperature value for the specified time near the current location.
* AirTemperatureData[locationspec] gives the most recent measurement for air temperature near the specified location.
* AirTemperatureData[locationspec, datespec] gives the value or values for the specified date and location.
* AirTemperatureData[{{location , date }, {location , date }, …}] gives values for all specified locations on the specified dates.
* Usage: 1 1 2 2
*
* Options: UnitSystem :> $UnitSystem
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/AirTemperatureData
* Documentation: web: http://reference.wolfram.com/language/ref/AirTemperatureData.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun airTemperatureData(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("AirTemperatureData", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,713 | mathemagika | Apache License 2.0 |
taxiql-query-engine/src/test/java/com/orbitalhq/models/JsonPathTest.kt | orbitalapi | 541,496,668 | false | {"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337} | package com.orbitalhq.models
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.winterbe.expekt.should
import com.orbitalhq.schemas.taxi.TaxiSchema
import org.junit.Test
import kotlin.test.assertFailsWith
class JsonPathTest {
val traderJson = """
{
"username" : "EUR_Trader",
"jurisdiction" : "EUR",
"limit" : {
"currency" : "USD",
"value" : 100
}
}
""".trimIndent()
@Test
fun canReadValueFromJsonPath() {
val taxi = TaxiSchema.from("""
type Foo {
limitValue : Decimal by jsonPath("$.limit.value")
}
""".trimIndent())
val instance = TypedInstance.from(taxi.type("Foo"), traderJson, schema = taxi, source = Provided) as TypedObject
instance["limitValue"].value.should.equal(100.toBigDecimal())
}
@Test
fun `can parse json string from to a schema that mixes jsonpath and plain mappings`() {
val taxi = TaxiSchema.from("""
model Trade {
username : String
country : String by jsonPath("$.jurisdiction")
limit : Int by jsonPath("$.limit.value")
}
""".trimIndent())
val instance = TypedInstance.from(taxi.type("Trade"), traderJson, schema = taxi, source = Provided) as TypedObject
instance["username"].value.should.equal("EUR_Trader")
instance["country"].value.should.equal("EUR")
instance["limit"].value.should.equal(100)
}
@Test
fun `can parse json node from to a schema that mixes jsonpath and plain mappings`() {
// Note that Casks pre-parse json from string to jackson jsonNode, so this needs to pass
val taxi = TaxiSchema.from("""
model Trade {
username : String
country : String by jsonPath("$.jurisdiction")
limit : Int by jsonPath("$.limit.value")
}
""".trimIndent())
val jsonNode = jacksonObjectMapper().readTree(traderJson)
val instance = TypedInstance.from(taxi.type("Trade"), jsonNode, schema = taxi, source = Provided) as TypedObject
instance["username"].value.should.equal("EUR_Trader")
instance["country"].value.should.equal("EUR")
instance["limit"].value.should.equal(100)
}
@Test
fun `can parse json string from a schema that uses legacy xpath style jsonPath mappings`() {
val taxi = TaxiSchema.from("""
model Trade {
username : String
country : String by jsonPath("/jurisdiction")
limit : Int by jsonPath("$.limit.value")
}
""".trimIndent())
val instance = TypedInstance.from(taxi.type("Trade"), traderJson, schema = taxi, source = Provided) as TypedObject
instance["username"].value.should.equal("EUR_Trader")
instance["country"].value.should.equal("EUR")
instance["limit"].value.should.equal(100)
}
@Test
fun `when using an indefinite json path but expecting a single response then it is returned if only one item matches`() {
// Usecase here is finding a specific array element.
// Jsonpath doesn't support parent access, but Jayway's JsonPath issues page
// suggests this approach.
// See : https://github.com/json-path/JsonPath/issues/287#issuecomment-265479196
// This stems from a client trying to parse a Json FIX message
val json = """{
"noSecurityAltID": [
6,
{
"securityAltID": "GEZ0",
"securityAltIDSource": [
"98",
"NAME"
]
},
{
"securityAltID": "GE Dec20",
"securityAltIDSource": [
"97",
"ALIAS"
]
},
{
"securityAltID": "1EDZ0",
"securityAltIDSource": [
"5",
"RIC_CODE"
]
},
{
"securityAltID": "870833",
"securityAltIDSource": [
"8",
"EXCHANGE_SECURITY_ID"
]
},
{
"securityAltID": "EDZ0 Comdty",
"securityAltIDSource": [
"A",
"BLOOMBERG_CODE"
],
"bloombergSecurityExchange": "CME"
},
{
"securityAltID": "BBG001BH7R55",
"securityAltIDSource": [
"S",
"OPENFIGI_ID"
],
"bloombergSecurityExchange": "CME"
}
]
}"""
val taxi = TaxiSchema.from("""
type RicCode inherits String
model FixMessage {
ricCode : RicCode by jsonPath("$.noSecurityAltID[?(@.securityAltIDSource[1]=='RIC_CODE')].securityAltID")
}
""".trimIndent())
val instance = TypedInstance.from(taxi.type("FixMessage"), json, taxi, source = Provided) as TypedObject
instance["ricCode"].value.should.equal("1EDZ0")
}
@Test
fun jsonPathToUndefinedValueReturnsNull() {
val taxi = TaxiSchema.from("""
type Foo {
limitValue : Decimal by jsonPath("$.something.that.doesnt.exist")
}
""".trimIndent())
val instance = TypedInstance.from(taxi.type("Foo"), traderJson, schema = taxi, source = Provided) as TypedObject
instance["limitValue"].value.should.be.`null`
}
@Test
fun `when the jsonPath contains a syntax error then a helpful error is thrown`() {
val taxi = TaxiSchema.from("""
type Oscar inherits String
model Actor {
name : ActorName inherits String
awards : {
oscars: Oscar by jsonPath("oscars[0") // Intentoionally invlalid jsonPath
}
}
""".trimIndent())
val json = """[
{
"name" : "<NAME>",
"awards" : {
"oscars" : [ "Best Movie" ]
}
},
{
"name" : "<NAME>",
"awards" : {
"oscars" : [ "Best Song" ]
}
}
]
"""
assertFailsWith<RuntimeException>("Could not evaluate path: oscars[0 -- the path is invalid: Could not parse token starting at position 8. Expected ?, ', 0-9, *") {
TypedInstance.from(taxi.type("Actor[]"), json, schema = taxi) as TypedCollection
}
}
@Test
fun `can use relative json path`() {
val taxi = TaxiSchema.from("""
type Oscar inherits String
model Actor {
name : ActorName inherits String
awards : {
oscars: Oscar by jsonPath("oscars[0]")
}
}
""".trimIndent())
val json = """[
{
"name" : "<NAME>",
"awards" : {
"oscars" : [ "Best Movie" ]
}
},
{
"name" : "<NAME>",
"awards" : {
"oscars" : [ "Best Song" ]
}
}
]
"""
val collection = TypedInstance.from(taxi.type("Actor[]"), json, schema = taxi) as TypedCollection
collection.toRawObject().should.equal(listOf(
mapOf("name" to "<NAME>", "awards" to mapOf("oscars" to "Best Movie")),
mapOf("name" to "<NAME>", "awards" to mapOf("oscars" to "Best Song")),
))
}
}
| 9 | TypeScript | 10 | 292 | 2be59abde0bd93578f12fc1e2ecf1f458a0212ec | 7,025 | orbital | Apache License 2.0 |
cryptography-providers/jdk/src/jvmMain/kotlin/operations/JdkMacSignature.kt | whyoleg | 492,907,371 | false | {"Kotlin": 989467, "JavaScript": 318} | /*
* Copyright (c) 2023-2024 <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.whyoleg.cryptography.providers.jdk.operations
import dev.whyoleg.cryptography.functions.*
import dev.whyoleg.cryptography.operations.*
import dev.whyoleg.cryptography.providers.jdk.*
import dev.whyoleg.cryptography.providers.jdk.internal.*
internal class JdkMacSignature(
state: JdkCryptographyState,
private val key: JSecretKey,
algorithm: String,
) : SignatureGenerator, SignatureVerifier {
private val mac = state.mac(algorithm)
private fun createFunction() = JdkMacFunction(mac.borrowResource().also {
it.access().init(key)
})
override fun createSignFunction(): SignFunction = createFunction()
override fun createVerifyFunction(): VerifyFunction = createFunction()
}
private class JdkMacFunction(private val mac: Pooled.Resource<JMac>) : SignFunction, VerifyFunction {
override fun update(source: ByteArray, startIndex: Int, endIndex: Int) {
checkBounds(source.size, startIndex, endIndex)
val mac = mac.access()
mac.update(source, startIndex, endIndex - startIndex)
}
override fun signIntoByteArray(destination: ByteArray, destinationOffset: Int): Int {
val mac = mac.access()
checkBounds(destination.size, destinationOffset, destinationOffset + mac.macLength)
mac.doFinal(destination, destinationOffset).also { close() }
return mac.macLength
}
override fun signToByteArray(): ByteArray {
val mac = mac.access()
return mac.doFinal().also { close() }
}
override fun tryVerify(signature: ByteArray, startIndex: Int, endIndex: Int): Boolean {
checkBounds(signature.size, startIndex, endIndex)
return signToByteArray().contentEquals(signature.copyOfRange(startIndex, endIndex))
}
override fun verify(signature: ByteArray, startIndex: Int, endIndex: Int) {
check(tryVerify(signature, startIndex, endIndex)) { "Invalid signature" }
}
override fun close() {
mac.close()
}
}
| 19 | Kotlin | 18 | 287 | fa49703c4e9dd40c4aae741eb28a5a932f07e49c | 2,094 | cryptography-kotlin | Apache License 2.0 |
server/src/main/kotlin/com/wo1f/domain/models/Conversation.kt | adwardwolf | 494,332,246 | false | {"Kotlin": 238756, "JavaScript": 3319, "Python": 3159} | /**
* @author Adwardwo1f
* @created May 27, 2022
*/
package com.wo1f.domain.models
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import org.bson.codecs.pojo.annotations.BsonId
import org.bson.types.ObjectId
import java.time.Instant
import java.util.Date
/**
* Data class represents conversation response
*/
@Serializable
data class ConversationRes(
@BsonId
val id: String,
val question: String,
val answer: String,
val category: String,
val isTrained: Boolean,
val createdAt: String
)
/**
* Data class represents conversation in database
*/
@Serializable
data class ConversationDb(
@Contextual
@BsonId
val id: ObjectId,
val question: String,
val answer: String,
val category: String,
val isTrained: Boolean,
@Contextual
val createdAt: Date
)
/**
* Data class represents conversation request
*/
@Serializable
data class ConversationRq(
var question: String,
var answer: String,
val category: String
)
@Serializable
data class GetConversationRes(
val category: CategoryRes,
val conversations: List<ConversationRes>
)
fun ConversationRq.toDbObject(): ConversationDb {
return ConversationDb(
id = ObjectId.get(),
question = this.question,
answer = this.answer,
category = this.category,
isTrained = false,
createdAt = Date.from(Instant.now())
)
}
| 0 | Kotlin | 0 | 0 | 9d1ceff9fda21e2c3c1f4a12d39669845bea11f6 | 1,435 | yilong-ma-bot | Apache License 2.0 |
src/main/kotlin/com/theapache64/ghmm/templates/drake/DrakeData.kt | theapache64 | 330,988,608 | false | null | package com.theapache64.ghmm.templates.drake
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
class DrakeData(
@SerialName("drake_hates")
var drakeHates: String, // Dagger2
@SerialName("drake_loves")
val drakeLoves: String, // Hilt
@SerialName("font_size")
val fontSize: Float = 80f,
)
| 25 | Kotlin | 3 | 52 | 439e52157669365a7431d30c1b6383a602c3f060 | 359 | gh-meme-maker | Apache License 2.0 |
app/src/main/java/divyansh/tech/kotnewreader/models/MLModels/communicationAnalysis.kt | justdvnsh | 272,389,822 | false | null | package divyansh.tech.kotnewreader.models.MLModels
data class Emotion(
val prediction: String,
val probability: Double
)
data class communicationAnalysis(
val predictions: MutableList<Emotion>
)
| 0 | Kotlin | 1 | 3 | cd39b3f8f9b50e2ca33289083528bb099c8cc0bf | 209 | Samachaar | MIT License |
app/flutter_medx_app/android/app/src/main/kotlin/com/example/hopeitworks/MainActivity.kt | Tani21 | 343,033,048 | true | {"Dart": 70785, "HTML": 1511, "Swift": 404, "Kotlin": 128, "Objective-C": 38} | package com.example.hopeitworks
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 0 | 19c480d49df31e0895f2899c6d325b7b07da0bab | 128 | MedX | MIT License |
app/src/main/java/com/example/appplantery/login/Login.kt | JhonatanNeves | 658,355,572 | false | {"Kotlin": 67876} | package com.example.appplantery.login
import androidx.annotation.StringRes
import com.example.appplantery.common.base.BasePresenter
import com.example.appplantery.common.base.BaseView
interface Login {
interface Presenter : BasePresenter {
fun login(email: String, senha: String)
}
interface View : BaseView<Presenter> {
fun showProgress(enabled: Boolean)
fun displayEmailFailure(@StringRes emailError: Int?)
fun displayPasswordFailure(@StringRes passwordError: Int?)
fun onUserAuthenticated()
fun onUserUnauthorized(message: String)
}
} | 0 | Kotlin | 0 | 1 | 75f4225f50d39dce7ab7cfadfa016305ca940443 | 606 | appPlantery | MIT License |
haze/src/androidMain/kotlin/dev/chrisbanes/haze/HazeEffect.android.kt | chrisbanes | 710,434,447 | false | {"Kotlin": 74125, "Shell": 1077} | // Copyright 2024, <NAME> and the Haze project contributors
// SPDX-License-Identifier: Apache-2.0
package dev.chrisbanes.haze
internal actual fun HazeEffectNode.observeInvalidationTick() {
// No need to do anything on Android
}
| 8 | Kotlin | 26 | 997 | 31b8085a887c4fd8ab3a67e40be2a70d85c9f4c4 | 233 | haze | Apache License 2.0 |
app/src/main/java/com/example/whats_eat/viewModel/DetailPlaceViewModel.kt | KanuKim97 | 428,755,782 | false | null | package com.example.whats_eat.viewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.whats_eat.BuildConfig
import com.example.whats_eat.data.common.Constant
import com.example.whats_eat.data.di.dispatcherQualifier.IoDispatcher
import com.example.whats_eat.data.flow.producer.FirebaseDBProducer
import com.example.whats_eat.data.flow.producer.PlaceApiProducer
import com.example.whats_eat.view.dataViewClass.DetailPlace
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class DetailPlaceViewModel @Inject constructor(
private val placeApiProducer: PlaceApiProducer,
private val fireDBProducer: FirebaseDBProducer,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
): ViewModel() {
private val _detailPlaceResult = MutableLiveData<DetailPlace>()
val detailPlaceResult: LiveData<DetailPlace> get() = _detailPlaceResult
fun getPlaceDetailData(placeID: String): Job = viewModelScope.launch(ioDispatcher) {
placeApiProducer.detailedPlace(placeID).collect { result ->
_detailPlaceResult.postValue(
DetailPlace(
name = result.name,
formattedAddress = result.formatted_address,
isOpenNow = result.openingHours?.open_now,
rating = result.rating,
lat = result.geometry?.location?.lat,
lng = result.geometry?.location?.lng,
photoRef = getPhotoUrl(result.photos?.get(0)?.photo_reference.toString())
)
)
}
}
fun saveUserCollection(place: DetailPlace): Job = viewModelScope.launch(ioDispatcher) {
fireDBProducer.saveUserCollection(place)
}
private fun getPhotoUrl(photoReference: String): String =
StringBuilder(Constant.PLACE_PHOTO_API_URI)
.append("?maxwidth=1000")
.append("&photo_reference=$photoReference")
.append("&key=${BuildConfig.PLACE_API_KEY}")
.toString()
override fun onCleared() {
super.onCleared()
viewModelScope.cancel()
}
} | 0 | Kotlin | 0 | 2 | d01a732ec329b6d32ba7b1d87855e3ecf6e1a6bb | 2,395 | whats_eat | Apache License 2.0 |
app/src/main/java/com/imminentmeals/imminenttime/ui/views/ClickActors.kt | imminent | 105,390,341 | false | null | /**
* MIT License
*
* Copyright (c) 2017 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.imminentmeals.imminenttime.ui.views
import android.content.DialogInterface
import android.support.annotation.StringRes
import android.support.v7.app.AlertDialog
import android.view.View
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.channels.Channel
import kotlinx.coroutines.experimental.channels.actor
// https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#using-actors-within-ui-context
const val CAPACITY_SINGLE = 0
const val CAPACITY_SINGLE_MOST_RECENT = Channel.CONFLATED
const val CAPACITY_UNLIMITED = Channel.UNLIMITED
/**
* @receiver click events of this [View] will be observed
* @param capacity optional of values [CAPACITY_SINGLE], [CAPACITY_SINGLE_MOST_RECENT],
* [CAPACITY_UNLIMITED], or any positive [Int]
* @param action executed when receiver [View] is clicked
* @see [Channel]
*/
fun View.onClick(capacity: Int = CAPACITY_SINGLE, action: suspend () -> Unit) {
// launch one actor
val eventActor = actor<Unit>(UI, capacity) {
for (event in channel) action()
}
// install a listener to activate this actor
setOnClickListener {
eventActor.offer(Unit)
}
}
/**
* @receiver long-click events of this [View] will be observed
* @param capacity optional of values [CAPACITY_SINGLE], [CAPACITY_SINGLE_MOST_RECENT],
* [CAPACITY_UNLIMITED], or any positive [Int]
* @param action executed when receiver [View] is long-clicked
* @see [Channel]
*/
fun View.onLongClick(capacity: Int = CAPACITY_SINGLE, action: suspend () -> Unit) {
// launch one actor
val eventActor = actor<Unit>(UI, capacity) {
for (event in channel) action()
}
// install a listener to activate this actor
setOnLongClickListener {
eventActor.offer(Unit)
}
}
private typealias AlertDialogEvent = Pair<DialogInterface, Int>
private val AlertDialogEvent.dialogInterface get() = first
private val AlertDialogEvent.button get() = second
/**
* @receiver positive button click events of this [AlertDialog] will be observed
* @param capacity optional of values [CAPACITY_SINGLE], [CAPACITY_SINGLE_MOST_RECENT],
* [CAPACITY_UNLIMITED], or any positive [Int]
* @param action executed when receiver [AlertDialog] positive button is clicked
* @see [Channel]
*/
fun AlertDialog.Builder.onPositiveButtonClick(
@StringRes textId: Int,
capacity: Int = CAPACITY_SINGLE,
action: suspend (DialogInterface, Int) -> Unit
) = apply {
// launch one actor
val eventActor = actor<AlertDialogEvent>(UI, capacity) {
for (event in channel) action(event.dialogInterface, event.button)
}
// install a listener to activate this actor
setPositiveButton(textId) { dialogInterface, button ->
eventActor.offer(AlertDialogEvent(dialogInterface, button))
}
}
/**
* @receiver negative button click events of this [AlertDialog] will be observed
* @param capacity optional of values [CAPACITY_SINGLE], [CAPACITY_SINGLE_MOST_RECENT],
* [CAPACITY_UNLIMITED], or any positive [Int]
* @param action executed when receiver [AlertDialog] negative button is clicked
* @see [Channel]
*/
fun AlertDialog.Builder.onNegativeButtonClick(
@StringRes textId: Int,
capacity: Int = CAPACITY_SINGLE,
action: suspend (DialogInterface, Int) -> Unit
) = apply {
// launch one actor
val eventActor = actor<AlertDialogEvent>(UI, capacity) {
for (event in channel) action(event.dialogInterface, event.button)
}
// install a listener to activate this actor
setNegativeButton(textId) { dialogInterface, button ->
eventActor.offer(AlertDialogEvent(dialogInterface, button))
}
}
/**
* @receiver neutral button click events of this [AlertDialog] will be observed
* @param capacity optional of values [CAPACITY_SINGLE], [CAPACITY_SINGLE_MOST_RECENT],
* [CAPACITY_UNLIMITED], or any positive [Int]
* @param action executed when receiver [AlertDialog] neutral button is clicked
* @see [Channel]
*/
fun AlertDialog.Builder.onNeutralButtonClick(
@StringRes textId: Int,
capacity: Int = CAPACITY_SINGLE,
action: suspend (DialogInterface, Int) -> Unit
) = apply {
// launch one actor
val eventActor = actor<AlertDialogEvent>(UI, capacity) {
for (event in channel) action(event.dialogInterface, event.button)
}
// install a listener to activate this actor
setNeutralButton(textId) { dialogInterface, button ->
eventActor.offer(AlertDialogEvent(dialogInterface, button))
}
} | 8 | Kotlin | 0 | 0 | c6891eac3f47aa186abc1c0d22f05781fdfdbbac | 5,696 | Imminent-Time | Apache License 2.0 |
ContactsTest/app/src/main/java/com/example/contactstest/MyProvider.kt | Chiu-xaH | 860,949,434 | false | {"Kotlin": 556183, "C++": 23070, "CMake": 18778, "HTML": 5262, "Dart": 3816, "Swift": 2070, "C": 1425, "Java": 1162, "Objective-C": 38} | package com.example.contactstest
import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
abstract class MyProvider : ContentProvider() {
private val data0 = 0
private val data1 = 1
private val data2 = 2
private val data3 = 3
private val uri = UriMatcher(UriMatcher.NO_MATCH)
init {
uri.addURI("com.example.contactstest.provider","table1",data0)
uri.addURI("com.example.contactstest.provider","table1/#",data1)
uri.addURI("com.example.contactstest.provider","table2",data2)
uri.addURI("com.example.contactstest.provider","table2/#",data3)
}
override fun onCreate(): Boolean {
return false
}
override fun query( uri: Uri,projection : Array<out String>?, selection : String?, selectionArgs: Array<out String>?, sortOrder : String?): Cursor? {
data0 -> {
//
}
data1 -> {
}
data2 -> {
}
data3 -> {
}
}
override fun delete(p0: Uri, p1: String?, p2: Array<out String>?): Int {
return 0
}
override fun insert(p0: Uri, p1: ContentValues?): Uri? {
return null
}
override fun update(p0: Uri, p1: ContentValues?, p2: String?, p3: Array<out String>?): Int {
return 0
}
override fun getType(p0: Uri): String? = when (uri.match(uri)){
data0 -> "vnd.android"
data1 ->
data2 ->
data3 ->
return null
}
} | 0 | Kotlin | 0 | 0 | 961ff7cd1d3b6c4b6e2cf2687cb5b01e643cd832 | 1,572 | Android-Practice | Apache License 2.0 |
app/src/main/kotlin/com/tans/tfiletranserdesktop/utils/SerilizationUtils.kt | Tans5 | 341,413,863 | false | {"Kotlin": 387306} | package com.tans.tlocalvideochat.ui
import com.squareup.moshi.Moshi
val defaultMoshi: Moshi by lazy {
Moshi.Builder().build()
}
inline fun <reified T : Any> T.toJson(): String? {
return try {
defaultMoshi.adapter(T::class.java).toJson(this)
} catch (e: Throwable) {
e.printStackTrace()
null
}
}
inline fun <reified T : Any> String.fromJson(): T? {
return try {
defaultMoshi.adapter(T::class.java).fromJson(this)
} catch (e: Throwable) {
e.printStackTrace()
null
}
}
| 1 | Kotlin | 2 | 35 | 0478156da948e4ea9816444d5ba1a10ce83ea1c7 | 550 | tFileTransfer_desktop | Apache License 2.0 |
app/src/test/java/com/google/samples/apps/sunflower/test/CalendarMatcher.kt | android | 134,505,361 | false | {"Kotlin": 170699} | /*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.sunflower.test
import org.hamcrest.Description
import org.hamcrest.Factory
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeDiagnosingMatcher
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Calendar.DAY_OF_MONTH
import java.util.Calendar.MONTH
import java.util.Calendar.YEAR
/**
* Calendar matcher.
* Only Year/Month/Day precision is needed for comparing GardenPlanting Calendar entries
*/
internal class CalendarMatcher(
private val expected: Calendar
) : TypeSafeDiagnosingMatcher<Calendar>() {
private val formatter = SimpleDateFormat("dd.MM.yyyy")
override fun describeTo(description: Description?) {
description?.appendText(formatter.format(expected.time))
}
override fun matchesSafely(actual: Calendar?, mismatchDescription: Description?): Boolean {
if (actual == null) {
mismatchDescription?.appendText("was null")
return false
}
if (actual.get(YEAR) == expected.get(YEAR) &&
actual.get(MONTH) == expected.get(MONTH) &&
actual.get(DAY_OF_MONTH) == expected.get(DAY_OF_MONTH)
)
return true
mismatchDescription?.appendText("was ")?.appendText(formatter.format(actual.time))
return false
}
companion object {
/**
* Creates a matcher for [Calendar]s that only matches when year, month and day of
* actual calendar are equal to year, month and day of expected calendar.
*
* For example:
* <code>assertThat(someDate, hasSameDateWith(Calendar.getInstance()))</code>
*
* @param expected calendar that has expected year, month and day [Calendar]
*/
@Factory
fun equalTo(expected: Calendar): Matcher<Calendar> = CalendarMatcher(expected)
}
}
| 76 | Kotlin | 4687 | 17,613 | 2a357a31551bb53f3fe80382a9ce6d30bcc8b960 | 2,455 | sunflower | Apache License 2.0 |
src/main/kotlin/com/salesforce/revoman/output/report/failure/ExeFailure.kt | salesforce-misc | 677,000,343 | false | {"Kotlin": 117081, "Java": 41850, "HTML": 772, "Starlark": 283} | /**
* ************************************************************************************************
* Copyright (c) 2023, Salesforce, Inc. All rights reserved. SPDX-License-Identifier: Apache License
* Version 2.0 For full license text, see the LICENSE file in the repo root or
* http://www.apache.org/licenses/LICENSE-2.0
* ************************************************************************************************
*/
package com.salesforce.revoman.output.report.failure
import com.salesforce.revoman.output.report.ExeType
sealed class ExeFailure {
abstract val exeType: ExeType
abstract val failure: Any
}
| 9 | Kotlin | 3 | 6 | 1c4aa93c77a28d1d1482da14a4afbdabf3991f14 | 629 | ReVoman | Apache License 2.0 |
aws-examples/lambdas/src/main/kotlin/uy/kohesive/iac/examples/aws/lambdas/TriggeredEventRunAthena.kt | kohesive | 81,814,921 | false | null | package uy.kohesive.iac.examples.aws.lambdas
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider
import com.amazonaws.auth.profile.ProfileCredentialsProvider
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.LambdaLogger
import com.amazonaws.services.lambda.runtime.RequestHandler
import com.fasterxml.jackson.annotation.JsonProperty
import java.sql.DriverManager
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.util.*
class TriggeredEventRunAthena(val overrideCredentialsProviderWithProfile: String? = null,
val overrideS3OutputBucketEnvValue: String? = null,
val overrideOutputFilePrefixEnvValue: String? = null,
val overrideS3InputBucketEnvValue: String? = null,
val overrideInputBucketPrefix: String? = null,
val overrideAthenaRegion: String? = null) : RequestHandler<ScheduledEvent, AthenaDatasetResponse> {
companion object {
val ENV_SETTING_OUTPUT_S3_BUCKET = "OUTPUT_S3_BUCKET"
val ENV_SETTING_OUTPUT_PREFIX = "OUTPUT_FILE_PREFIX"
val ENV_SETTING_INPUT_S3_BUCKET = "INPUT_S3_BUCKET"
val ENV_SETTING_INPUT_PREFIX = "INTPUT_FILE_PREFIX"
val ENV_SETTING_ATHENA_REGION = "ATHENA_AWS_REGION"
}
val athenaS3OutputBucket = overrideS3OutputBucketEnvValue
?: System.getenv(ENV_SETTING_OUTPUT_S3_BUCKET)
?: throw IllegalStateException("Missing environment variable ${ENV_SETTING_OUTPUT_S3_BUCKET} defining the S3 bucket for output")
val athenaOutputFilePrefix = overrideOutputFilePrefixEnvValue
?: System.getenv(ENV_SETTING_OUTPUT_PREFIX)
?: throw IllegalStateException("Missing environment variable ${ENV_SETTING_OUTPUT_PREFIX} defining the file prefix for output")
val athenaS3InputBucket = overrideS3InputBucketEnvValue
?: System.getenv(ENV_SETTING_INPUT_S3_BUCKET)
?: throw IllegalStateException("Missing environment variable ${ENV_SETTING_INPUT_S3_BUCKET} defining the S3 bucket for input")
val athenaInputFilePrefix = overrideInputBucketPrefix
?: System.getenv(ENV_SETTING_INPUT_PREFIX)
?: throw IllegalStateException("Missing environment variable ${ENV_SETTING_INPUT_PREFIX} defining the file prefix for input")
val athenaRegion = overrideAthenaRegion
?: System.getenv(ENV_SETTING_ATHENA_REGION)
?: throw IllegalStateException("Missing environment variable ${ENV_SETTING_ATHENA_REGION} defining the Athena AWS region")
val athenaUrl = "jdbc:awsathena://athena.${athenaRegion}.amazonaws.com:443/"
val defaultJdbcProps = Properties().apply {
if (overrideCredentialsProviderWithProfile != null) {
put("aws_credentials_provider_class", ProfileCredentialsProvider::class.java.name)
put("aws_credentials_provider_arguments", overrideCredentialsProviderWithProfile)
} else {
put("aws_credentials_provider_class", EnvironmentVariableCredentialsProvider::class.java.name)
}
}
override fun handleRequest(input: ScheduledEvent, context: Context): AthenaDatasetResponse {
// TODO: make time a range, and go back to last processed (DynamoDB state) in case we had an outage/delay for data feed
val parsedTime = Instant.from(DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC).parse(input.time))
return processForEventTime(parsedTime, context.logger)
}
fun processForEventTime(time: Instant, logger: LambdaLogger?): AthenaDatasetResponse {
val execTime = Instant.now()
val execReversedNumericTime = "%020d".format(Long.MAX_VALUE - execTime.toEpochMilli())
val execTimeAsString = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss").format(execTime.atZone(ZoneOffset.UTC))
val execUniqueness = UUID.randomUUID().toString()
val execIdentifier = "$execReversedNumericTime-$execTimeAsString-$execUniqueness"
// our output bucket will always sort the newest data to the top of the list when scanning the S3 prefix
val outputLocation = "s3://${athenaS3OutputBucket}/${athenaOutputFilePrefix.trimStart('/').trimEnd('/')}/$execIdentifier/"
val connectProps = Properties(defaultJdbcProps)
connectProps.put("s3_staging_dir", outputLocation)
val tempTableName = "notification_email_digest_temp_${execUniqueness.replace('-', '_')}"
val targetHour = time.atOffset(ZoneOffset.UTC).truncatedTo(ChronoUnit.HOURS).minusHours(1)
fun Int.twoDigits() = "%02d".format(this)
val targetHourPrefix = "${targetHour.year}/${targetHour.month.value.twoDigits()}/${targetHour.dayOfMonth.twoDigits()}/${targetHour.hour.twoDigits()}"
logger?.log("Processing target hour: ${targetHour} at prefix ${targetHourPrefix} to $outputLocation")
// TODO: move to freemarker template?
val createTempTableSql = """
CREATE EXTERNAL TABLE `$tempTableName`(
`email` string COMMENT 'from deserializer',
`name` string COMMENT 'from deserializer',
`message` string COMMENT 'from deserializer',
`timestamp` string COMMENT 'from deserializer')
ROW FORMAT SERDE
'org.openx.data.jsonserde.JsonSerDe'
LOCATION
's3://${athenaS3InputBucket}/${athenaInputFilePrefix.trimStart('/').trimEnd('/')}/$targetHourPrefix/'
"""
// TODO: move to freemarker template?
val dropTempTableSql = """
DROP TABLE `$tempTableName`
"""
// TODO: range the query to only be the involved time frame
// TODO: move to freemarker template?
val querySql = """
WITH base AS (
SELECT email, name, message, timestamp, parse_datetime(timestamp, 'yyyy-MM-dd''T''HH:mm:ss') as eventTime
FROM $tempTableName
ORDER BY eventTime
), hourBucketed AS (
SELECT *, date_trunc('hour', eventTime) as eventHour
FROM base
), mapped AS (
SELECT eventHour, eventTime, email, name, map(ARRAY['eventTime', 'message'], ARRAY[timestamp, message]) as event
FROM hourBucketed
ORDER BY eventTime
), rolledUp AS (
SELECT email, arbitrary(name) as name, count(*) as eventCount, array_agg(event) as events
FROM mapped
GROUP BY email
)
SELECT email, name, eventCount, cast(events AS JSON) as events FROM rolledUp
ORDER BY email
"""
Class.forName("com.amazonaws.athena.jdbc.AthenaDriver")
DriverManager.getConnection(athenaUrl, connectProps).use { db ->
// let exceptions fall through for Lambda logging of errors
db.createStatement().executeQuery(createTempTableSql)
db.createStatement().executeQuery(querySql)
db.createStatement().executeQuery(dropTempTableSql)
}
return AthenaDatasetResponse(outputLocation)
}
}
data class AthenaDatasetResponse(val outputS3Location: String)
// TODO: the lambda events JAR is missing one for cloudwatch scheduled events, or I missed it. Look for it again, this is a odd class just to get the time of the event.
class ScheduledEvent() {
var version: String? = null
var id: String? = null
@get:JsonProperty("detail-type") var detailType: String? = null
var source: String? = null
var account: String? = null
lateinit var time: String
var region: String? = null
var resources: List<String> = emptyList()
var detail: Map<String, Any> = emptyMap()
} | 0 | Kotlin | 1 | 3 | c52427c99384396ea60f436750932ed12aad4e6d | 7,974 | kohesive-iac | MIT License |
community/src/main/java/com/kotlin/android/community/ui/home/adapter/JoinFamilyItemBinder.kt | R-Gang-H | 538,443,254 | false | null | package com.kotlin.android.community.ui.home.adapter
import com.kotlin.android.community.R
import com.kotlin.android.community.databinding.ItemCommunityJoinFamilyBinding
import com.kotlin.android.app.router.path.RouterProviderPath
import com.kotlin.android.app.router.provider.community_family.ICommunityFamilyProvider
import com.kotlin.android.router.ext.getProvider
import com.kotlin.android.widget.adapter.multitype.adapter.binder.MultiTypeBinder
/**
* @author ZhouSuQiang
* @email [email protected]
* @date 2020/7/17
*
* 我的家族ItemBinder
*/
class JoinFamilyItemBinder : MultiTypeBinder<ItemCommunityJoinFamilyBinding>() {
val mFamilyProvider = getProvider(ICommunityFamilyProvider::class.java)
override fun layoutId(): Int {
return R.layout.item_community_join_family
}
override fun areContentsTheSame(other: MultiTypeBinder<*>): Boolean {
return other is JoinFamilyItemBinder
}
} | 0 | Kotlin | 0 | 1 | e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28 | 932 | Mtime | Apache License 2.0 |
detekt-api/src/test/kotlin/io/gitlab/arturbosch/detekt/api/EntitySpec.kt | niraj8 | 272,693,530 | true | {"Kotlin": 1852830, "HTML": 4183, "Groovy": 2423} | package io.gitlab.arturbosch.detekt.api
import io.github.detekt.test.utils.compileContentForTest
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class EntitySpec : Spek({
describe("entity signatures") {
val code = compileContentForTest("""
package test
class C : Any() {
private fun memberFun(): Int = 5
}
fun topLevelFun(number: Int) = Unit
""".trimIndent())
describe("functions") {
val functions = code.collectDescendantsOfType<KtNamedFunction>()
it("includes full function header, class name and filename") {
val memberFunction = functions.first { it.name == "memberFun" }
assertThat(Entity.atName(memberFunction).signature)
.isEqualTo("Test.kt\$C\$private fun memberFun(): Int")
}
it("includes full function header and filename for a top level function") {
val topLevelFunction = functions.first { it.name == "topLevelFun" }
assertThat(Entity.atName(topLevelFunction).signature)
.isEqualTo("Test.kt\$fun topLevelFun(number: Int)")
}
}
describe("classes") {
it("includes full class signature") {
val clazz = requireNotNull(code.findDescendantOfType<KtClass>())
assertThat(Entity.atName(clazz).signature).isEqualTo("Test.kt\$C : Any")
}
}
describe("files") {
it("includes package and file name") {
assertThat(Entity.atPackageOrFirstDecl(code).signature).isEqualTo("Test.kt\$test.Test.kt")
}
}
}
})
| 0 | Kotlin | 0 | 1 | 8536e848ec2d4470c970442a8ea4579937b4b2d8 | 2,026 | detekt | Apache License 2.0 |
plam/src/main/kotlin/com/pwssv67/plam/DependencyFunctions.kt | pwssv67 | 649,458,619 | false | null | @file:Suppress("unused")
package com.pwssv67.plam
//region basics
/**
* This function is used to wrap dependency notation and add some modifiers to it.
*
* @param prefix modifier to add to dependency notation
* @return DependencyWrapper - wrapper for dependency notation
* @see DependencyWrapper
* @see [debug]
*/
fun prefixDep(prefix: String, dependencyNotation: Any): DependencyWrapper = DependencyWrapper(prefix, dependencyNotation)
/**
* This function is used to wrap dependency notation and add "implementation" modifier to it.
*
* Analogue for basic Gradle KTS `dependencies { implementation("...") }`
*
* @return DependencyWrapper - wrapper for dependency notation
* @see DependencyWrapper
*/
fun impl(dependencyNotation: Any): DependencyWrapper = DependencyWrapper(DepTypes.impl, dependencyNotation)
/**
* This function is used to wrap dependency notation and add "api" modifier to it.
*
* Analogue for basic Gradle KTS `dependencies { api("...") }`
*
* @return DependencyWrapper - wrapper for dependency notation
* @see DependencyWrapper
*/
fun api(dependencyNotation: Any): DependencyWrapper = DependencyWrapper(DepTypes.api, dependencyNotation)
/**
* This function is used to wrap dependency notation and add "compileOnly" modifier to it.
*
* Analogue for basic Gradle KTS `dependencies { compileOnly("...") }`
*
* @return DependencyWrapper - wrapper for dependency notation
* @see DependencyWrapper
*/
fun compileOnly(dependencyNotation: Any): DependencyWrapper = DependencyWrapper(DepTypes.compileOnly, dependencyNotation)
/**
* This function is used to wrap dependency notation and add "kapt" modifier to it.
*
* Analogue for basic Gradle KTS `dependencies { annotationProcessor("...") }`
*
* @return DependencyWrapper - wrapper for dependency notation
* @see DependencyWrapper
*/
fun annotationProcessor(dependencyNotation: Any): DependencyWrapper = DependencyWrapper(DepTypes.annotationProcessor, dependencyNotation)
/**
* This function is used to wrap dependency notation and add "test" modifier to it.
*
* Analogue for basic Gradle KTS `dependencies { test("...") }`
*
* @return DependencyWrapper - wrapper for dependency notation
* @see DependencyWrapper
*/
fun test(dependency: DependencyWrapper) = DependencyWrapper(DepTypes.test, dependency)
//endregion
//region flavors
/**
* This function is used to wrap dependency notation and add flavor modifier to it.
*
* Analogue for basic Gradle KTS
* ```kotlin
* dependencies { flavor1Implementation("...") }
* ```
* would be
* ```kotlin
* flavor("flavor1", impl("..."))
* ```
*/
fun flavor(flavor: String, dependency: DependencyWrapper): DependencyWrapper = prefixDep(flavor, dependency)
/**
* This function is used to use [flavor] function with multiple flavors.
*
* You can use it like this:
* ```kotlin
* flavors(listOf("flavor1", "flavor2"), impl("..."))
* ```
* and get similar result to
* ```kotlin
* dependencies {
* flavor1Impl("...")
* flavor2Impl("...")
* }
* ```
*
* @see flavor
*/
fun flavors(flavors: List<String>, dependency: DependencyWrapper): List<DependencyWrapper> = flavors.map { flavor(it, dependency) }
//endregion
//region utilities
/**
* This function is used to wrap dependency notation and add "testImplementation" modifier to it.
*
* Analogue for basic Gradle KTS `dependencies { testImplementation("...") }`
*
* @return DependencyWrapper - wrapper for dependency notation
* @see DependencyWrapper
*/
fun testImpl(dependencyNotation: Any): DependencyWrapper = test(impl(dependencyNotation))
/**
* This function is used to wrap dependency notation and add "androidTest" modifier to it.
*
* Analogue for basic Gradle KTS
* ```kotlin
* dependencies { androidTestImplementation("...") }
* ```
* would be:
* ```kotlin
* androidTest(impl("..."))
* ```
*/
fun androidTest(dependency: DependencyWrapper): DependencyWrapper = prefixDep(DepTypes.android, test(dependency))
/**
* This function is used to wrap dependency notation and add "androidTestImplementation" modifier to it.
*
* Analogue for basic Gradle KTS `dependencies { androidTestImplementation("...") }`
*/
fun androidTestImpl(dependencyNotation: Any): DependencyWrapper = androidTest(impl(dependencyNotation))
/**
* This function is used to wrap dependency notation and add "debug" modifier to it.
*
* Analogue for basic Gradle KTS
* ```kotlin
* dependencies { debugImplementation("...") }
* ```
* would be:
* ```kotlin
* debug(impl("..."))
* ```
*/
fun debug(dependency: DependencyWrapper): DependencyWrapper = prefixDep(DepTypes.debug, dependency)
/**
* This function is used to wrap dependency notation and add "release" modifier to it.
*
* Analogue for basic Gradle KTS
* ```kotlin
* dependencies { releaseImplementation("...") }
* ```
* would be:
* ```kotlin
* release(impl("..."))
* ```
*/
fun release(dependency: DependencyWrapper): DependencyWrapper = prefixDep(DepTypes.release, dependency)
/**
* This function is used to wrap dependency notation and add "debugImplementation" modifier to it.
*
* Analogue for basic Gradle KTS `dependencies { debugImplementation("...") }`
*/
fun debugImpl(dependencyNotation: Any): DependencyWrapper = debug(impl(dependencyNotation))
/**
* This function is used to wrap dependency notation and add "releaseImplementation" modifier to it.
*
* Analogue for basic Gradle KTS `dependencies { releaseImplementation("...") }`
*/
fun releaseImpl(dependencyNotation: Any): DependencyWrapper = release(impl(dependencyNotation))
//endregion
/**
* This function is used to wrap dependency notation and register it as a *platform* dependency.
*
* Don't use it with other functions inside! It will not work, and build will fail. Instead, wrap it with other functions.
*
* Analogue for basic Gradle KTS `dependencies { platform("...") }`
*/
fun platform(dependencyNotation: Any): DependencyWrapper = DependencyWrapper("", dependencyNotation, true)
@Suppress("DeprecatedCallableAddReplaceWith", "unused") //can't be properly replaced because we have no access to inner function argument. If you know how to specify replacement of a(b(arg)) to b(a(arg)) - please create an issue.
@Deprecated(message = "Don't wrap other custom dependencies with platform. Instead wrap platform() with other functions.", level = DeprecationLevel.ERROR)
fun platform(dependencyNotation: DependencyWrapper): DependencyWrapper = throw IllegalArgumentException("Don't wrap another dependencies with platform()! This isn't supported neither by Gradle nor by plam")
| 1 | Kotlin | 0 | 2 | 27ecbdb93a5aa5d0ce2657e3984219d0abd364fb | 6,580 | PLAM | MIT License |
matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/crypto/verification/VerificationInfoKey.kt | t0mmar | 191,595,408 | true | {"Kotlin": 5394333, "Java": 113304, "HTML": 23969, "Shell": 22642, "Python": 5234} | /*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.matrix.android.internal.crypto.verification
/**
* Sent by both devices to send their ephemeral Curve25519 public key to the other device.
*/
internal interface VerificationInfoKey : VerificationInfo {
/**
* The device’s ephemeral public key, as an unpadded base64 string
*/
val key: String?
}
internal interface VerificationInfoKeyFactory {
fun create(tid: String, pubKey: String): VerificationInfoKey
}
| 0 | Kotlin | 0 | 0 | 5ff670b184d991d43aef8568419ff71aed8208c0 | 1,046 | riotX-android | Apache License 2.0 |
app/src/main/java/com/devstromo/advancedtictactoe/presentation/bluetooth/BluetoothGameScreen.kt | devstromo | 792,098,527 | false | {"Kotlin": 130653} | package com.devstromo.advancedtictactoe.presentation.bluetooth
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.DialogProperties
import androidx.navigation.NavController
import com.devstromo.advancedtictactoe.R
import com.devstromo.advancedtictactoe.navigation.Screen
import com.devstromo.advancedtictactoe.presentation.GameViewModel
import com.devstromo.advancedtictactoe.presentation.components.CustomButton
import com.devstromo.advancedtictactoe.presentation.components.QrCodeImage
import com.devstromo.advancedtictactoe.presentation.permissions.RequestBluetoothPermissions
import com.devstromo.advancedtictactoe.presentation.permissions.hasBluetoothPermissions
@SuppressLint("MissingPermission", "HardwareIds")
@Composable
fun BluetoothGameScreen(
navController: NavController,
modifier: Modifier = Modifier,
viewModel: GameViewModel,
) {
val typo = MaterialTheme.typography
val context = LocalContext.current
val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
var permissionsGranted by remember { mutableStateOf(hasBluetoothPermissions(context)) }
var isBluetoothEnabled by remember { mutableStateOf(isBluetoothEnabled(bluetoothManager)) }
var showEnableBluetoothDialog by remember { mutableStateOf(false) }
var startServer by remember { mutableStateOf(false) }
val joinGameServer by remember { mutableStateOf(false) }
val enableBluetoothLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
isBluetoothEnabled = isBluetoothEnabled(bluetoothManager)
}
if (!permissionsGranted) {
RequestBluetoothPermissions { granted ->
permissionsGranted = granted
}
}
val isServerStarted by viewModel.isServerStarted.collectAsState()
val isConnected by viewModel.isConnected.collectAsState()
if (showEnableBluetoothDialog) {
AlertDialog(
onDismissRequest = { showEnableBluetoothDialog = false },
title = { Text("Enable Bluetooth") },
text = { Text("Bluetooth is required to proceed. Please enable Bluetooth.") },
confirmButton = {
Button(modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(25),
onClick = {
showEnableBluetoothDialog = false
enableBluetoothLauncher.launch(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE))
}) {
Text(
modifier = Modifier
.align(Alignment.CenterVertically)
.padding(top = 10.dp),
text = stringResource(R.string.bluetooth_connection_enable_request),
textAlign = TextAlign.Center,
style = typo.bodyLarge.copy(color = Color.White)
)
}
},
dismissButton = {
Button(modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(25),
onClick = {
showEnableBluetoothDialog = false
}) {
Text(
modifier = Modifier
.align(Alignment.CenterVertically)
.padding(top = 10.dp),
text = stringResource(R.string.bluetooth_connection_cancel_request),
textAlign = TextAlign.Center,
style = typo.bodyLarge.copy(color = Color.White)
)
}
},
properties = DialogProperties(dismissOnClickOutside = false)
)
}
Box(
modifier = Modifier.fillMaxSize()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
.align(Alignment.TopStart)
) {
IconButton(
modifier = Modifier
.height(45.dp)
.width(45.dp)
.background(
color = Color.Transparent,
shape = RoundedCornerShape(25)
),
onClick = { navController.popBackStack() },
) {
Icon(
Icons.Rounded.ArrowBack,
contentDescription = "Favorite",
tint = Color.White,
modifier = Modifier
.size(40.dp)
)
}
}
Column(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 45.dp, vertical = 20.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.weight(1f))
if (isServerStarted) {
Text("Server started, waiting for connection...")
} else {
if (!permissionsGranted) {
Text("Bluetooth permissions are required to proceed.")
} else if (!isBluetoothEnabled) {
Text("Need to turn on your bluetooth connection.")
} else if (startServer) {
val deviceName = bluetoothManager.adapter?.name ?: "Unknown"
val deviceAddress = bluetoothManager.adapter?.address ?: "00:00:00:00:00:00"
val qrCodeContent = "DeviceName:$deviceName;DeviceAddress:$deviceAddress"
QrCodeImage(
content = qrCodeContent,
size = 200.dp
)
} else if (joinGameServer) {
Text("Join Game")
} else {
Text("Create or Join to a new Game")
}
}
if (isConnected) {
Text("Connected to a device!")
}
Spacer(modifier = Modifier.weight(1f))
CustomButton(
text = stringResource(R.string.bluetooth_game_create_title),
onClick = {
if (permissionsGranted && !isBluetoothEnabled) {
showEnableBluetoothDialog = true
} else {
startServer = true
}
},
isEnable = permissionsGranted && isBluetoothEnabled
)
Spacer(modifier = Modifier.height(10.dp))
CustomButton(
text = stringResource(R.string.bluetooth_game_join_title),
onClick = {
navController.navigate(Screen.QRScanner.route)
},
isEnable = permissionsGranted && isBluetoothEnabled
)
}
}
}
fun isBluetoothEnabled(bluetoothManager: BluetoothManager): Boolean {
return bluetoothManager.adapter?.isEnabled == true
}
| 0 | Kotlin | 0 | 0 | e32a72f0981bc98f6526675ab7582551e9f061e4 | 8,956 | tic_tac_toe_jetpack_compose | MIT License |
app/src/test/java/com/nullist/finbox/domain/FinboxServiceTest.kt | nullist0 | 758,528,383 | false | {"Kotlin": 10061} | package com.nullist.finbox.domain
import org.junit.Before
import org.junit.Test
internal class FinboxServiceTest {
lateinit var finboxService: FinboxService
lateinit var finboxRepository: FakeFinboxRepository
@Before
fun setup() {
finboxRepository = FakeFinboxRepository()
finboxService = FinboxService(finboxRepository)
}
@Test
fun `test get all inbox files with files`() {
// given
val expectedInboxFiles = listOf(
PermanentInboxFile("file1"),
TemporaryInboxFile("file2"),
)
val directory = InboxDirectory(
"/path/to/dir1",
expectedInboxFiles
)
finboxRepository.addDirectory(directory)
// when
val inboxFiles = finboxService.allInboxFiles
// then
assert(inboxFiles == expectedInboxFiles)
}
@Test
fun `test get all inbox files with empty files`() {
// given
val expectedInboxFiles = listOf<InboxFile>()
// when
val inboxFiles = finboxService.allInboxFiles
// then
assert(inboxFiles == expectedInboxFiles)
}
}
| 0 | Kotlin | 0 | 0 | 65ccf4bad8331c89de0f6dc8a7e63e14e756eb1a | 1,155 | finbox | Apache License 2.0 |
src/jsMain/kotlin/com/jeffpdavidson/kotwords/web/TwoToneForm.kt | jpd236 | 143,651,464 | false | null | package com.jeffpdavidson.kotwords.web
import com.jeffpdavidson.kotwords.KotwordsInternal
import com.jeffpdavidson.kotwords.model.Puzzle
import com.jeffpdavidson.kotwords.model.TwoTone
import com.jeffpdavidson.kotwords.util.trimmedLines
import com.jeffpdavidson.kotwords.web.html.FormFields
import com.jeffpdavidson.kotwords.web.html.Html
import kotlinx.html.InputType
import kotlinx.html.div
@JsExport
@KotwordsInternal
class TwoToneForm {
private val jpzForm = PuzzleFileForm("two-tone", ::createPuzzle)
private val title: FormFields.InputField = FormFields.InputField("title")
private val creator: FormFields.InputField = FormFields.InputField("creator")
private val copyright: FormFields.InputField = FormFields.InputField("copyright")
private val description: FormFields.TextBoxField = FormFields.TextBoxField("description")
private val allSquaresAnswers: FormFields.TextBoxField = FormFields.TextBoxField("all-squares-answers")
private val allSquaresClues: FormFields.TextBoxField = FormFields.TextBoxField("all-squares-clues")
private val oddSquaresAnswers: FormFields.TextBoxField = FormFields.TextBoxField("odd-squares-answers")
private val oddSquaresClues: FormFields.TextBoxField = FormFields.TextBoxField("odd-squares-clues")
private val oddSquaresColor: FormFields.InputField = FormFields.InputField("odd-squares-color")
private val evenSquaresAnswers: FormFields.TextBoxField = FormFields.TextBoxField("even-squares-answers")
private val evenSquaresClues: FormFields.TextBoxField = FormFields.TextBoxField("even-squares-clues")
private val evenSquaresColor: FormFields.InputField = FormFields.InputField("even-squares-color")
init {
Html.renderPage {
jpzForm.render(this, bodyBlock = {
[email protected](this, "Title")
creator.render(this, "Creator (optional)")
copyright.render(this, "Copyright (optional)")
description.render(this, "Description (optional)") {
rows = "5"
}
allSquaresAnswers.render(this, "All squares answers") {
placeholder = "In sequential order, separated by whitespace. " +
"Non-alphabetical characters are ignored."
rows = "5"
}
allSquaresClues.render(this, "All squares clues") {
placeholder = "One clue per row. Omit clue numbers."
rows = "10"
}
oddSquaresAnswers.render(this, "Odd squares answers (first, third, etc.)") {
placeholder = "In sequential order, separated by whitespace. " +
"Non-alphabetical characters are ignored."
rows = "5"
}
oddSquaresClues.render(this, "Odd squares clues") {
placeholder = "One clue per row. Omit clue numbers."
rows = "10"
}
evenSquaresAnswers.render(this, "Even squares answers (second, fourth, etc.)") {
placeholder = "In sequential order, separated by whitespace. " +
"Non-alphabetical characters are ignored."
rows = "5"
}
evenSquaresClues.render(this, "Even squares clues") {
placeholder = "One clue per row. Omit clue numbers."
rows = "10"
}
}, advancedOptionsBlock = {
div(classes = "form-row") {
oddSquaresColor.render(this, "Odd squares color", flexCols = 6) {
type = InputType.color
value = "#C0C0C0"
}
evenSquaresColor.render(this, "Even squares color", flexCols = 6) {
type = InputType.color
value = "#FFFFFF"
}
}
})
}
}
private suspend fun createPuzzle(): Puzzle {
val twoTone = TwoTone(
title = title.getValue(),
creator = creator.getValue(),
copyright = copyright.getValue(),
description = description.getValue(),
allSquaresAnswers = allSquaresAnswers.getValue().uppercase().split("\\s+".toRegex()),
allSquaresClues = allSquaresClues.getValue().trimmedLines(),
oddSquaresAnswers = oddSquaresAnswers.getValue().uppercase().split("\\s+".toRegex()),
oddSquaresClues = oddSquaresClues.getValue().trimmedLines(),
evenSquaresAnswers = evenSquaresAnswers.getValue().uppercase().split("\\s+".toRegex()),
evenSquaresClues = evenSquaresClues.getValue().trimmedLines(),
oddSquareBackgroundColor = oddSquaresColor.getValue(),
evenSquareBackgroundColor = evenSquaresColor.getValue(),
)
return twoTone.asPuzzle()
}
} | 8 | null | 2 | 10 | a934756f63e898b4e061fbceadab5414e90dd16c | 5,022 | kotwords | Apache License 2.0 |
http-client/test/no/nav/tilleggsstonader/libs/http/client/AbstractRestClientTest.kt | navikt | 682,534,919 | false | {"Kotlin": 74472} | package no.nav.tilleggsstonader.libs.http.client
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.client.WireMock.aResponse
import com.github.tomakehurst.wiremock.client.WireMock.anyUrl
import com.github.tomakehurst.wiremock.client.WireMock.created
import com.github.tomakehurst.wiremock.client.WireMock.okJson
import com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo
import com.github.tomakehurst.wiremock.common.ConsoleNotifier
import com.github.tomakehurst.wiremock.core.WireMockConfiguration
import no.nav.tilleggsstonader.kontrakter.felles.ObjectMapperProvider.objectMapper
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.assertj.core.api.Assertions.catchThrowable
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertDoesNotThrow
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.http.HttpStatus
import org.springframework.http.ProblemDetail
import org.springframework.web.client.HttpClientErrorException.NotFound
import org.springframework.web.client.HttpServerErrorException
import org.springframework.web.client.RestTemplate
import org.springframework.web.util.UriComponentsBuilder
import java.net.URI
internal class AbstractRestClientTest {
class TestClient(val uri: URI) : AbstractRestClient(RestTemplate()) {
fun test() {
getForEntity<Any>(uri.toString())
}
fun testMedUriVariables() {
getForEntity<Any>("$uri/api/test/{id}/data", uriVariables = mapOf("id" to "123"))
}
fun testMedUriComponentsBuilder() {
val uri = UriComponentsBuilder.fromUri(uri)
.pathSegment("api", "test", "{id}", "data")
.queryParam("userId", "{userId}")
.encode()
.toUriString()
getForEntity<Any>(uri, uriVariables = mapOf("id" to "123", "userId" to "id"))
}
fun postUtenResponseBody(): String? {
return postForEntityNullable<String>(uri.toString(), emptyMap<String, String>())
}
}
companion object {
private lateinit var wireMockServer: WireMockServer
private lateinit var client: TestClient
@BeforeAll
@JvmStatic
fun initClass() {
val notifier = ConsoleNotifier(false) // enabler logging ved feil
wireMockServer = WireMockServer(WireMockConfiguration.wireMockConfig().dynamicPort().notifier(notifier))
wireMockServer.start()
}
@AfterAll
@JvmStatic
fun tearDown() {
wireMockServer.stop()
}
}
@AfterEach
fun tearDownEachTest() {
wireMockServer.resetAll()
}
@BeforeEach
fun setupEachTest() {
client = TestClient(URI.create("http://localhost:${wireMockServer.port()}"))
}
@Test
fun `skal kunne kalle på tjeneste med uriVariables`() {
wireMockServer.stubFor(
WireMock.get(urlEqualTo("/api/test/123/data"))
.willReturn(okJson(objectMapper.writeValueAsString(mapOf("test" to "ok")))),
)
assertDoesNotThrow {
client.testMedUriVariables()
}
}
@Test
fun `skal kunne kalle på tjeneste med uriVariables med UriComponentsBuilder`() {
wireMockServer.stubFor(
WireMock.get(urlEqualTo("/api/test/123/data?userId=id"))
.willReturn(okJson(objectMapper.writeValueAsString(mapOf("test" to "ok")))),
)
assertDoesNotThrow {
client.testMedUriComponentsBuilder()
}
}
@Test
fun `skal kunne kalle på endepunkt og forvente svar uten body`() {
wireMockServer.stubFor(
WireMock.post(anyUrl())
.willReturn(created()),
)
assertThat(client.postUtenResponseBody()).isNull()
}
@Test
fun `query param request skal feile hvis query params ikke mer med`() {
wireMockServer.stubFor(
WireMock.get(urlEqualTo("/api/test/123/data"))
.willReturn(okJson(objectMapper.writeValueAsString(mapOf("test" to "ok")))),
)
assertThatThrownBy {
client.testMedUriComponentsBuilder()
}.isInstanceOf(NotFound::class.java)
}
@Test
internal fun `feil med problemDetail kaster ProblemDetailException`() {
val problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "Feil")
val body = objectMapper.writeValueAsString(problemDetail)
wireMockServer.stubFor(
WireMock.get(anyUrl())
.willReturn(aResponse().withStatus(500).withBody(body)),
)
val catchThrowable = catchThrowable { client.test() }
assertThat(catchThrowable).isInstanceOfAny(ProblemDetailException::class.java)
assertThat(catchThrowable).hasCauseInstanceOf(HttpServerErrorException::class.java)
val ressursException = catchThrowable as ProblemDetailException
assertThat(ressursException.httpStatus).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR)
assertThat(ressursException.detail.detail).isEqualTo(problemDetail.detail)
}
@Test
internal fun `feil med body som inneholder feltet status men ikke er en ressurs`() {
val body = objectMapper.writeValueAsString(mapOf("status" to "nei"))
wireMockServer.stubFor(
WireMock.get(anyUrl())
.willReturn(aResponse().withStatus(500).withBody(body)),
)
val catchThrowable = catchThrowable { client.test() }
assertThat(catchThrowable).isInstanceOfAny(HttpServerErrorException::class.java)
assertThat((catchThrowable as HttpServerErrorException).statusCode).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR)
}
@Test
internal fun `feil uten ressurs kaster videre spring exception`() {
wireMockServer.stubFor(
WireMock.get(anyUrl())
.willReturn(aResponse().withStatus(500)),
)
val catchThrowable = catchThrowable { client.test() }
assertThat(catchThrowable).isInstanceOfAny(HttpServerErrorException::class.java)
assertThat((catchThrowable as HttpServerErrorException).statusCode).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR)
}
}
| 3 | Kotlin | 0 | 0 | 65cb9a56f6dfbb453fee0f562830ec079abecd82 | 6,505 | tilleggsstonader-libs | MIT License |
src/main/kotlin/io/battlerune/net/packet/out/PlaySongPacketEncoder.kt | Adams94 | 106,645,065 | true | {"Kotlin": 94442} | package io.battlerune.net.packet.out
import io.battlerune.game.world.actor.Player
import io.battlerune.net.codec.game.ByteModification
import io.battlerune.net.codec.game.RSByteBufWriter
import io.battlerune.net.packet.Packet
import io.battlerune.net.packet.PacketEncoder
import io.battlerune.net.packet.PacketType
class PlaySongPacketEncoder(val songId: Int) : PacketEncoder {
override fun encode(player: Player): Packet {
val writer = RSByteBufWriter.alloc()
writer.writeShort(songId, ByteModification.ADD)
return writer.toPacket(90, PacketType.FIXED)
}
} | 0 | Kotlin | 0 | 0 | 12f33d5add8a95757274f1082449680402798916 | 593 | battlerune-server | MIT License |
plugin-build/plugin/src/test/java/com/javax0/jamal/gradle/plugin/JamalPluginTest.kt | verhas | 697,728,019 | false | {"Kotlin": 3640} | package com.javax0.jamal.gradle.plugin
import org.gradle.testfixtures.ProjectBuilder
import org.junit.Assert.assertNotNull
import org.junit.Test
import java.io.File
class JamalPluginTest {
@Test
fun `plugin is applied correctly to the project`() {
val project = ProjectBuilder.builder().build()
project.pluginManager.apply("jamal-gradle-plugin")
assert(project.tasks.getByName("JamalConvertFile") is JamalFileConverterTask)
}
@Test
fun `extension templateExampleConfig is created correctly`() {
val project = ProjectBuilder.builder().build()
project.pluginManager.apply("jamal-gradle-plugin")
assertNotNull(project.extensions.getByName("JamalConvertFile"))
}
@Test
fun `parameters are passed correctly from extension to task`() {
val project = ProjectBuilder.builder().build()
project.pluginManager.apply("jamal-gradle-plugin")
val aFile = File(project.projectDir, ".tmp")
(project.extensions.getByName("JamalConvertFile") as JamalExtension).apply {
inputFile.set(File("a-sample-input.adoc.jam"))
}
val task = project.tasks.getByName("JamalConvertFile") as JamalFileConverterTask
}
}
| 0 | Kotlin | 0 | 0 | 78b9c537cbaab8e795a62ed5b5e272be020e99ac | 1,237 | jamal-gradle-plugin | MIT License |
DADMApp/app/src/main/java/com/example/dadmapp/ui/home/HomePage.kt | UTN-FRBA-Mobile | 697,567,152 | false | {"Kotlin": 129135, "TypeScript": 17069, "JavaScript": 663} | package com.example.dadmapp.ui.home
import android.annotation.SuppressLint
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.ExitToApp
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.dadmapp.R
import com.example.dadmapp.model.note.Note
import com.example.dadmapp.model.tag.Tag
import com.example.dadmapp.ui.components.NotePreview
import com.example.dadmapp.ui.home.components.FloatingButton
import com.example.dadmapp.ui.home.components.TopBar
import com.example.dadmapp.ui.theme.AccentRed1
import com.example.dadmapp.ui.theme.BgDark
import com.example.dadmapp.ui.theme.LightRed
import kotlinx.coroutines.launch
fun shouldDisplayNote(
note: Note,
filterByTags: List<Tag>,
searchTerm: String?
): Boolean {
if (
filterByTags.isNotEmpty() &&
note.tags.none { t -> filterByTags.contains(t) }
) {
return false
}
if (
searchTerm != null &&
(
note.title == null ||
!note.title.lowercase().contains(searchTerm.lowercase())
)
) {
return false
}
return true
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun HomePage(
onNoteClick: (noteId: String) -> Unit,
homePageViewModel: HomePageViewModel = viewModel(factory = HomePageViewModel.Factory),
onRecordAudio: () -> Unit,
onLogOut: () -> Unit,
onTagsColoursClick: () -> Unit
) {
val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
val scope = rememberCoroutineScope()
val tagIconSize = 14.dp
ModalNavigationDrawer(
drawerState = drawerState,
drawerContent = {
Column(
modifier = Modifier
.width(200.dp)
.background(BgDark)
.fillMaxHeight()
) {
Row(
modifier = Modifier
.padding(vertical = 16.dp)
.padding(start = 10.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(Icons.Filled.AccountCircle, contentDescription = null, tint = Color.White)
Column(modifier = Modifier.padding(start = 12.dp)) {
Text(
text = homePageViewModel.username ?: "",
color = Color.White,
fontWeight = FontWeight.SemiBold,
fontSize = 20.sp
)
}
}
Divider(
color = LightRed,
thickness = 1.dp,
modifier = Modifier.fillMaxWidth()
)
Row(
modifier = Modifier
.padding(start = 10.dp)
.padding(vertical = 12.dp)
.fillMaxWidth()
.clickable { onTagsColoursClick() },
verticalAlignment = Alignment.CenterVertically
) {
Icon(
painterResource(id = R.drawable.tag),
contentDescription = null,
tint = Color.White,
modifier = Modifier.width(tagIconSize).height(tagIconSize)
)
Text(
text = "Customize tags",
color = Color.White,
modifier = Modifier.padding(start = 8.dp),
textAlign = TextAlign.Left
)
}
Row(
modifier = Modifier
.padding(start = 10.dp)
.padding(vertical = 12.dp)
.fillMaxWidth()
.clickable { homePageViewModel.onLogOut(onLogOut) },
verticalAlignment = Alignment.CenterVertically
) {
Icon(
Icons.Filled.ExitToApp,
contentDescription = null,
tint = Color.White,
modifier = Modifier.width(tagIconSize).height(tagIconSize)
)
Text(
text = "Log out",
color = Color.White,
modifier = Modifier.padding(start = 8.dp),
textAlign = TextAlign.Left
)
}
}
}
) {
PageContent(
onNoteClick,
homePageViewModel,
onRecordAudio,
onDrawerStateChange = {
scope.launch {
drawerState.apply {
if (isClosed) {
open()
} else {
close()
}
}
}
}
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PageContent(
onNoteClick: (noteId: String) -> Unit,
homePageViewModel: HomePageViewModel = viewModel(factory = HomePageViewModel.Factory),
onRecordAudio: () -> Unit,
onDrawerStateChange: () -> Unit,
) {
if (homePageViewModel.selectedNoteId != null) {
LaunchedEffect(Unit) {
onNoteClick(homePageViewModel.selectedNoteId!!)
}
}
val notesState = homePageViewModel.notes?.collectAsState()
Scaffold(
topBar = {
TopAppBar(
title = { Text(text = "") },
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.requiredHeight(45.dp)
.clip(RoundedCornerShape(50.dp)),
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = AccentRed1,
titleContentColor = BgDark
),
actions = {
TopBar(
homePageViewModel = homePageViewModel,
onDrawerStateChange = onDrawerStateChange
)
}
)
},
containerColor = BgDark,
floatingActionButton = {
FloatingButton(
homePageViewModel,
onRecordAudio
)
}
) { paddingValues ->
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(
top = paddingValues.calculateTopPadding(),
bottom = paddingValues.calculateBottomPadding(),
start = 10.dp,
end = 10.dp,
)
) {
items(notesState?.value?.size ?: 0) { idx ->
val note = notesState?.value?.get(idx)
if (
note != null &&
shouldDisplayNote(
note,
homePageViewModel.filterByTags,
homePageViewModel.searchTerm
)
) {
Row(modifier = Modifier.padding(bottom = 20.dp)) {
NotePreview(
title = note.title,
content = note.content ?: "",
date = note.createdAt,
imageName = note.imageName,
audioName = note.audioName,
tags = note.tags,
onNoteClick = { onNoteClick(note.id.toString()) }
)
}
}
}
}
}
} | 1 | Kotlin | 0 | 0 | d98cd9463842be965b2dc57ea5a1551817a578ee | 10,347 | Capture | MIT License |
android/app/src/main/kotlin/com/fptu/swd391/cvideo_mobile/Question.kt | IAmRealPoca | 295,609,700 | false | {"Dart": 580270, "Kotlin": 28175, "Ruby": 1354, "Swift": 417, "Shell": 83, "Objective-C": 39} | package com.fptu.swd391.cvideo_mobile
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class Question(
var questionId: Int,
var questionContent: String,
var questionTime: Int) {
} | 0 | Dart | 0 | 0 | 8d6628053428499cb0b97c825604749b7a6dcbc3 | 239 | cvideo-employee-mobile | MIT License |
intellij-plugin-verifier/verifier-repository/src/main/java/com/jetbrains/pluginverifier/plugin/DefaultPluginDetailsProvider.kt | JetBrains | 3,686,654 | false | {"Kotlin": 2524497, "Java": 253600, "CSS": 1454, "JavaScript": 692} | package com.jetbrains.pluginverifier.plugin
import com.jetbrains.plugin.structure.base.plugin.PluginCreationResult
import com.jetbrains.plugin.structure.intellij.classes.locator.CompileServerExtensionKey
import com.jetbrains.plugin.structure.intellij.classes.plugin.BundledPluginClassesFinder
import com.jetbrains.plugin.structure.intellij.classes.plugin.IdePluginClassesLocations
import com.jetbrains.plugin.structure.intellij.plugin.IdePlugin
import com.jetbrains.plugin.structure.intellij.problems.IntelliJPluginCreationResultResolver
import com.jetbrains.plugin.structure.intellij.problems.JetBrainsPluginCreationResultResolver
import com.jetbrains.plugin.structure.intellij.problems.PluginCreationResultResolver
import com.jetbrains.pluginverifier.repository.PluginInfo
import com.jetbrains.pluginverifier.repository.files.FileLock
import com.jetbrains.pluginverifier.repository.repositories.bundled.BundledPluginInfo
import com.jetbrains.pluginverifier.repository.repositories.dependency.DependencyPluginInfo
import java.nio.file.Path
/**
* Provides plugin details with explicit support for bundled plugins that are provided by the Platform.
*
* Non-bundled plugins are handled by the delegate [PluginDetailsProviderImpl].
*/
class DefaultPluginDetailsProvider(extractDirectory: Path) : AbstractPluginDetailsProvider(extractDirectory) {
private val nonBundledPluginDetailsProvider: PluginDetailsProviderImpl = PluginDetailsProviderImpl(extractDirectory)
private val dependencyProblemResolver: PluginCreationResultResolver =
JetBrainsPluginCreationResultResolver.fromClassPathJson(IntelliJPluginCreationResultResolver())
override fun readPluginClasses(pluginInfo: PluginInfo, idePlugin: IdePlugin): IdePluginClassesLocations {
return if (pluginInfo is BundledPluginInfo) {
BundledPluginClassesFinder.findPluginClasses(idePlugin, additionalKeys = listOf(CompileServerExtensionKey))
} else {
nonBundledPluginDetailsProvider.readPluginClasses(pluginInfo, idePlugin)
}
}
override fun createPlugin(pluginInfo: PluginInfo, pluginFileLock: FileLock): PluginCreationResult<IdePlugin> {
return if (pluginInfo is DependencyPluginInfo) {
idePluginManager.createPlugin(pluginFileLock.file, validateDescriptor = false, problemResolver = dependencyProblemResolver)
} else {
super.createPlugin(pluginInfo, pluginFileLock)
}
}
} | 6 | Kotlin | 38 | 178 | 4deec2e4e08c9ee4ce087697ef80b8b327703548 | 2,390 | intellij-plugin-verifier | Apache License 2.0 |
src/main/kotlin/com/goldenberg/data/structure/tree/heap/Heap.kt | AlexGoldenbergDev | 264,484,811 | false | null | package com.goldenberg.data.structure.tree.heap
interface Heap<T : Comparable<T>> {
fun add(element: T): Boolean
fun addAll(elements: Collection<T>): Boolean
fun poll(): T
fun isEmpty(): Boolean
fun isNotEmpty(): Boolean = !isEmpty()
fun clear()
}
| 0 | Kotlin | 0 | 0 | c8dd486c79df36d1eb3101a003d4b2947de88f92 | 278 | eazy-data-kotlin | Apache License 2.0 |
src/main/kotlin/network/xyo/sdkcorekotlin/crypto/signing/XyoPublicKey.kt | ReconCatLord | 179,439,094 | true | {"Kotlin": 150281} | package network.xyo.sdkcorekotlin.crypto.signing
import network.xyo.sdkobjectmodelkotlin.buffer.XyoBuff
import java.security.PublicKey
abstract class XyoPublicKey : PublicKey, XyoBuff() | 0 | Kotlin | 0 | 0 | a8d35cb1290ccbb1345df501f4ecf4eb97c92b19 | 187 | sdk-core-kotlin | MIT License |
plugins/kotlin/fir/testData/quickDoc/AtConstantWithUnderscore.kt | ingokegel | 72,937,917 | false | null | class C {
/** Use [SOME_REFERENCED_VAL] to do something */
fun fo<caret>o() {
}
companion object {
val SOME_REFERENCED_VAL = 1
}
}
//INFO: <div class='definition'><pre>fun foo(): Unit</pre></div><div class='content'><p style='margin-top:0;padding-top:0;'>Use <a href="psi_element://SOME_REFERENCED_VAL"><code style='font-size:96%;'><span style="color:#660e7a;font-weight:bold;">SOME_REFERENCED_VAL</span></code></a> to do something</p></div><table class='sections'></table><div class='bottom'><icon src="class"/> <a href="psi_element://C"><code><span style="color:#000000;">C</span></code></a><br/></div>
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 641 | intellij-community | Apache License 2.0 |
app/src/main/java/id/co/woiapp/data/entities/ResponseQuote.kt | bintangeditya | 340,482,979 | false | null | package id.co.woiapp.data.entities
import com.google.gson.annotations.SerializedName
data class ResponseQuote(
@field:SerializedName("copyright")
val copyright: Copyright? = null,
@field:SerializedName("baseurl")
val baseurl: String? = null,
@field:SerializedName("contents")
val contents: Contents? = null,
@field:SerializedName("success")
val success: Success? = null
)
data class Copyright(
@field:SerializedName("year")
val year: Int? = null,
@field:SerializedName("url")
val url: String? = null
)
data class QuotesItem(
@field:SerializedName("date")
val date: String? = null,
@field:SerializedName("quote")
val quote: String? = null,
@field:SerializedName("author")
val author: String? = null,
@field:SerializedName("background")
val background: String? = null,
@field:SerializedName("length")
val length: String? = null,
@field:SerializedName("language")
val language: String? = null,
@field:SerializedName("id")
val id: String? = null,
@field:SerializedName("category")
val category: String? = null,
@field:SerializedName("permalink")
val permalink: String? = null,
@field:SerializedName("title")
val title: String? = null,
@field:SerializedName("tags")
val tags: List<String?>? = null
)
data class Contents(
@field:SerializedName("quotes")
val quotes: List<QuotesItem?>? = null
)
data class Success(
@field:SerializedName("total")
val total: Int? = null
)
| 0 | Kotlin | 0 | 0 | a88ef6c24baa270b03c3637d4f95beb335316e5b | 1,427 | WorkOnItApp | Apache License 2.0 |
frames/src/main/java/com/checkout/frames/di/component/CvvViewModelSubComponent.kt | checkout | 140,300,675 | false | null | package com.checkout.frames.di.component
import com.checkout.frames.component.cvv.CvvViewModel
import com.checkout.frames.style.component.CvvComponentStyle
import dagger.BindsInstance
import dagger.Subcomponent
@Subcomponent
internal interface CvvViewModelSubComponent {
val cvvViewModel: CvvViewModel
@Subcomponent.Builder
interface Builder {
@BindsInstance
fun style(style: CvvComponentStyle): Builder
fun build(): CvvViewModelSubComponent
}
}
| 14 | null | 34 | 51 | e1d99bff49067403a22f56bcb241cd4d014b269d | 490 | frames-android | MIT License |
MGSectionAdapterKtDemo/mg-section-adapter-kt/src/main/java/org/magicalwater/mgkotlin/mgsectionadapterkt/model/MGSection.kt | MagicalWater | 132,988,375 | false | {"Kotlin": 44281, "CMake": 1715, "Java": 1216, "C++": 295} | package org.magicalwater.mgkotlin.mgsectionadapterkt.model
import org.magicalwater.mgkotlin.mgsectionadapterkt.adapter.MGBaseAdapter
/**
* Created by magicalwater on 2017/12/19.
*/
class MGSection(holderType: Int = MGBaseAdapter.TYPE_BODY) {
constructor() : this(0)
var father: MGSection? = null
var child: MutableList<MGSection> = mutableListOf()
//此father底下的第幾個
var row: Int = 0
//依賴的 viewHolder type
var holderType: Int = holderType
//絕對位置(平鋪後的位置)
//需要注意的是, 當outerHeader開啟後, 此項都會加1, 因此需要有另外一個位置紀錄扣掉 outerHeader的
var absolatePos: Int = 0
var absolatePosNoOuterHeader: Int = 0
/**
* 當child size
* = 0 -> 是 leaf
* > 0 -> 是 node
*/
var isLeaf: Boolean = false
get() = child.size == 0
//深度
var depth: Int = 0
get() = (father?.depth ?: -1) + 1
//長度與深度相對應, 從頭到尾第幾個位置進入
var position: MGSectionPos = mutableListOf()
get() {
val p = father?.position ?: mutableListOf()
p.add(row)
return p
}
//搜尋所有層次的child數量
var totalChildCount: Int = 0
get() {
var count: Int = 0
for (c in child) count += c.totalChildCount
return count
}
//下層的child數量
var childCount: Int = 0
get() = child.size
//是否為展開狀態 - 默認展開狀態
var isExpand: Boolean = true
fun addChild(section: MGSection) {
child.add(section)
section.row = childCount - 1
section.father = this
}
fun removeChild(index: Int) {
child.removeAt(index)
//在 index 之後的 child 的 row 全部都要減去1
if (childCount >= index) {
for (i in index until childCount) child[i].row -= 1
}
}
fun resortChild() {
child.forEachIndexed { index, st ->
st.row = index
st.resortChild()
}
}
//將所有的 child 照順序取出(包含自己, 但若是狀態是縮起, 則不計算)
fun getAllSection(): MutableList<MGSection> {
var list = mutableListOf<MGSection>()
list.add(this)
if (isExpand) child.forEach { list.addAll(it.getAllSection()) }
return list
}
//得到所有擴展狀態與參數相同的MGSectionPos
fun getExpandStatusList(status: Boolean): MutableList<MGSectionPos> {
var list = mutableListOf<MGSectionPos>()
if (isExpand == status) list.add(position)
child.forEach {
list.addAll(it.getExpandStatusList(status))
}
return list
}
//一路往下傳下去, 直至找到正確位置
fun setExpandStatus(pos: MGSectionPos, status: Boolean): Int {
//先檢查深度是否正確
if (depth == pos.size-1) {
//正確, 就是自己
//只有當狀態不一樣時, 才回傳改變的數量
if (isExpand != status) {
isExpand = status
return if (isExpand) childCount
else -childCount
} else {
return 0
}
} else {
//不正確, 往child傳
//下個child的排序是第幾個
val childSort = pos[depth+1]
return child[childSort].setExpandStatus(pos, status)
}
}
//得到section的組成結構
fun getSectionStruct(): MGSectionStructInfo {
// var info = MGSectionStructInfo()
var list: MutableList<Any> = mutableListOf()
child.forEach {
list.add(it.getSectionStruct())
}
var info = MGSectionStructInfo(row, holderType, list)
return info
}
data class MGSectionStructInfo(val row: Int, val type: Int, val child: List<Any>)
} | 0 | Kotlin | 0 | 1 | 75e604dced2ac037dbbdee307322f3793fb03ced | 3,510 | MGSectionAdapterKt | MIT License |
app/src/main/java/com/webaddicted/newhiltproject/view/splash/SplashFragment.kt | webaddicted | 434,853,888 | false | {"Kotlin": 403122, "Java": 83} | package com.webaddicted.newhiltproject.view.splash
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.DrawableImageViewTarget
import com.webaddicted.newhiltproject.R
import com.webaddicted.newhiltproject.data.model.UserModel
import com.webaddicted.newhiltproject.databinding.FrmSplashBinding
import com.webaddicted.newhiltproject.utils.constant.AppConstant
import com.webaddicted.newhiltproject.view.base.BaseFragment
import com.webaddicted.newhiltproject.view.home.HomeActivity
import com.webaddicted.newhiltproject.viewmodel.HomeViewModel
import dagger.hilt.android.AndroidEntryPoint
class SplashFragment : BaseFragment(R.layout.frm_splash) {
private lateinit var userInfo: UserModel
private lateinit var mBinding: FrmSplashBinding
val homeVM: HomeViewModel by viewModels()
companion object {
val TAG = SplashFragment::class.qualifiedName
fun getInstance(bundle: Bundle): SplashFragment {
val fragment = SplashFragment()
fragment.arguments = bundle
return fragment
}
}
override fun onBindTo(binding: ViewDataBinding) {
mBinding = binding as FrmSplashBinding
init()
}
private fun init() {
Glide.with(this).load(R.raw.loader).into(DrawableImageViewTarget(mBinding.loadingTyreIv))
userInfo = homeVM.getPrefUserInfo()
Handler(Looper.getMainLooper()).postDelayed({
Log.d(TAG, "Test : ${userInfo.Email}")
if (userInfo.Email != null && userInfo.Email?.isNotEmpty()!!)
HomeActivity.newClearLogin(mActivity)
else navigateScreen(UserTypeFragment.TAG)
}, AppConstant.SPLASH_DELAY)
}
private fun navigateScreen(tag: String?) {
var frm: Fragment? = null
when (tag) {
UserTypeFragment.TAG -> frm = UserTypeFragment.getInstance(Bundle())
}
if (frm != null) navigateFragment(R.id.container, frm, false)
}
} | 0 | Kotlin | 0 | 1 | 3dcf906deec23c672cfb3a1212411395fa319edf | 2,340 | HiltDemo | Apache License 2.0 |
AOC2022/src/main/kotlin/AOC3.kt | bsautner | 575,496,785 | false | {"Kotlin": 16189, "Assembly": 496} | import java.io.File
fun main(args: Array<String>) {
val input = File("/home/ben/aoc/input-3.txt")
var sum = 0
//Part 1
input.forEachLine {
val a = deDup(it.subSequence(0, it.length / 2))
val b = deDup(it.subSequence(it.length / 2, it.length))
a.forEach {c ->
if (b.contains(c)) {
sum += getPriority(c)
}
}
}
println("part 1 $sum")
//part 2
val list = mutableListOf<String>()
var badgeSum = 0
input.forEachLine {
list.add(it)
}
var idx = -1
while (idx++ < list.size -1) {
val a = list[idx]
val b = list[++idx]
val c = list[++idx]
val badge = getBadge(a, b, c)
val priority = getPriority(badge)
badgeSum += priority
}
println(badgeSum)
}
fun getBadge(vararg s: String) : Char {
s[0].toCharArray().forEach {
if (s[1].contains(it) && s[2].contains(it)) {
println(it)
return it
}
}
throw IllegalStateException()
}
fun getPriority(c : Char) : Int {
return if (c.code > 96) {
c.code - 96
} else {
c.code - 65 + 27
}
}
fun deDup(s : CharSequence) : String {
val sb = StringBuilder()
s.forEach {
if (! sb.contains(it)) {
sb.append(it)
}
}
return sb.toString()
}
| 0 | Kotlin | 0 | 0 | 5f53cb1c4214c960f693c4f6a2b432b983b9cb53 | 1,609 | Advent-of-Code-2022 | The Unlicense |
app/src/main/java/com/example/pharmacymanagement/screens/AddMedicineFragment.kt | theKeval | 335,750,803 | false | null | package com.example.pharmacymanagement.screens
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import com.example.pharmacymanagement.R
import com.example.pharmacymanagement.databinding.FragmentAddMedicineBinding
import com.example.pharmacymanagement.handler.DatabaseHandler
class AddMedicineFragment : Fragment() {
private lateinit var binding: FragmentAddMedicineBinding
private lateinit var db: DatabaseHandler
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding =
DataBindingUtil.inflate(inflater, R.layout.fragment_add_medicine, container, false)
db = DatabaseHandler(context)
binding.btnProductDetailSave.setOnClickListener {
saveManufacturer()
saveMrIfAny()
saveMedicine()
saveMedicineIngredients()
saveMedicineStock()
it.findNavController().navigateUp()
}
binding.btnProductDetailCancel.setOnClickListener {
it.findNavController().navigateUp()
}
return binding.root
}
private fun saveMedicineStock() {
db.addMedicineStock(
binding.etMedicineName.text.toString(),
(binding.etQuantity.text.toString()).toInt(),
binding.etDescription.text.toString()
)
}
private fun saveMedicineIngredients() {
val ingredients = binding.etIngredients.text.toString()
if (!ingredients.isEmpty()) {
val lastMedId = db.lastMedId()
db.addMedicineIngredients(lastMedId, binding.etIngredients.text.toString())
}
}
private fun saveMedicine() {
var mr_id: Int = 0
var manufId = db.lastManufacturerId()
if (!binding.etMrName.text.toString().isEmpty()) {
mr_id = db.lastMrId()
}
db.addMedicine(
binding.etMedicineName.text.toString(),
(binding.etPrice.text.toString()).toInt(),
binding.etManufDate.text.toString(),
binding.etExpiryDate.text.toString(),
mr_id,
manufId
)
}
private fun saveMrIfAny() {
if (!binding.etMrName.text.toString().isEmpty()) {
var manufId = db.lastManufacturerId()
db.addMR(
binding.etMrName.text.toString(),
binding.etMrContact.text.toString(),
manufId
)
}
}
private fun saveManufacturer() {
db.addManufacturer(
binding.etManufacturerName.text.toString(),
binding.etManufAddresss.text.toString()
)
}
} | 1 | null | 1 | 1 | 285ac4befe2b6780a9ac03fb5940f67d570be966 | 2,891 | PharmacyManagement | Apache License 2.0 |
src/algorithm/boj/Boj2775.kt | yh-kim | 92,353,795 | false | null | package algorithm.boj
import java.io.BufferedReader
import java.io.InputStreamReader
/**
* Created by yonghoon on 2019-01-08
* Blog : http://blog.pickth.com
* Github : https://github.com/yh-kim
* Mail : <EMAIL>
*
* site : https://www.acmicpc.net/problem/2775
*/
fun main(args: Array<String>) {
val br = BufferedReader(InputStreamReader(System.`in`))
val T = Integer.parseInt(br.readLine())
for(i in 0 until T) {
val k = Integer.parseInt(br.readLine())
val n = Integer.parseInt(br.readLine())
// println(solve(k+2,n))
println(solve2(k+2,n))
}
br.close()
}
// 재귀2 -> 메모리 13232, 시간 1172
fun solve2(k: Int, n: Int): Int {
if(k == 0 || n == 0) {
return 0
}
if(k == 1 && n ==1) {
return 1
}
return solve(k-1,n)+solve(k,n-1)
}
// 재귀 -> 메모리 13236, 시간 832
fun solve(k: Int, n: Int): Int {
if(k == 1 && n ==1) {
return 1
} else if(k == 1) {
return solve(k,n-1)
} else if(n == 1) {
return solve(k-1,n)
}
return solve(k-1,n)+solve(k,n-1)
} | 0 | Kotlin | 0 | 0 | a1c51dd2cb7d3a5a6885f4d912fb4364c6630c9c | 1,108 | kotlin-study | Apache License 2.0 |
app/src/main/java/com/buffersolve/news/ui/fragments/SavedNewsFragment.kt | Buffersolve | 574,678,238 | false | null | package com.buffersolve.news.ui.fragments
import android.os.Bundle
import android.view.*
import androidx.core.view.MenuProvider
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.buffersolve.news.R
import com.buffersolve.news.adapters.NewsAdapter
import com.buffersolve.news.databinding.FragmentSavedNewsBinding
import com.buffersolve.news.ui.NewsActivity
import com.buffersolve.news.ui.NewsViewModel
import com.google.android.material.elevation.SurfaceColors
import com.google.android.material.snackbar.Snackbar
class SavedNewsFragment : Fragment(R.layout.fragment_saved_news) {
lateinit var viewModel: NewsViewModel
lateinit var newsAdapter: NewsAdapter
private var _binding: FragmentSavedNewsBinding? = null
private val binding get() = _binding!!
// Fragment onCreateView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentSavedNewsBinding.inflate(inflater, container, false)
return binding.root
}
// Fragment onViewCreated
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = (activity as NewsActivity).viewModel
setupRecycleView()
// Open Article
newsAdapter.setOnItemClickListener {
val bundle = Bundle().apply {
putParcelable("article", it)
}
findNavController().navigate(
R.id.action_savedNewsFragment_to_articleFragment,
bundle
)
}
// Monkey
if (newsAdapter.differ.currentList.isEmpty()) {
binding.monkey.visibility = View.VISIBLE
}
// Swipe Delete
val itemTouchHelperCallBack = object : ItemTouchHelper.SimpleCallback(
ItemTouchHelper.UP or ItemTouchHelper.DOWN,
ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
val article = newsAdapter.differ.currentList[position]
// Delete
viewModel.deleteArticle(article.url)
// Monkey
if (newsAdapter.differ.currentList.size > 0) {
binding.monkey.visibility = View.VISIBLE
}
Snackbar.make(view, "Article Deleted", Snackbar.LENGTH_SHORT)
.setAnchorView(R.id.bottomNavigationView).apply {
setAction("Undo") {
viewModel.saveArticle(article)
}
show()
}
}
}
ItemTouchHelper(itemTouchHelperCallBack).apply {
attachToRecyclerView(binding.rvSavedNews)
}
// Update RV Live Data
viewModel.getSavedNews().observe(viewLifecycleOwner) {
newsAdapter.differ.submitList(it)
if (it.isNotEmpty()) {
binding.monkey.visibility = View.INVISIBLE
}
}
// New Tool Bar Api
(activity as NewsActivity).setSupportActionBar(binding.toolBar)
setToolBar()
binding.appBar.setBackgroundColor(SurfaceColors.SURFACE_2.getColor(requireContext()))
}
// RV Setup
private fun setupRecycleView() {
newsAdapter = NewsAdapter()
binding.rvSavedNews.apply {
adapter = newsAdapter
layoutManager = LinearLayoutManager(activity)
}
}
private fun setToolBar() {
requireActivity().addMenuProvider(object : MenuProvider {
override fun onPrepareMenu(menu: Menu) {
super.onPrepareMenu(menu)
menu.findItem(R.id.app_bar_search).isVisible = false
menu.findItem(R.id.app_bar_save).isVisible = false
}
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.tool_bar_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return true
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
}
// Fragment onDestroyView
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
} | 0 | Kotlin | 0 | 2 | 7ab5d3893b1bbcb703df29089517cf294971bb1a | 4,962 | News | MIT License |
piped/src/main/kotlin/com/peecock/piped/utils/Serializers.kt | geekeie | 852,991,746 | false | {"Kotlin": 3810622, "Batchfile": 445} | package com.peecock.lrclib.utils
import io.ktor.http.Url
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import java.time.LocalDateTime
object UrlSerializer : KSerializer<Url> {
override val descriptor = PrimitiveSerialDescriptor("Url", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder) = Url(decoder.decodeString())
override fun serialize(encoder: Encoder, value: Url) = encoder.encodeString(value.toString())
}
typealias SerializableUrl = @Serializable(with = UrlSerializer::class) Url
object Iso8601DateSerializer : KSerializer<LocalDateTime> {
override val descriptor = PrimitiveSerialDescriptor("Iso8601LocalDateTime", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder) = LocalDateTime.parse(decoder.decodeString().removeSuffix("Z"))
override fun serialize(encoder: Encoder, value: LocalDateTime) = encoder.encodeString(value.toString())
}
typealias SerializableIso8601Date = @Serializable(with = Iso8601DateSerializer::class) LocalDateTime
| 0 | Kotlin | 0 | 0 | bcc8e691579ea2c6f04e9287e45056e9fb85c532 | 1,253 | YMusic | Apache License 2.0 |
commonext/src/main/java/com/spielberg/commonext/EncodeExt.kt | SpielbergGao | 332,424,338 | false | null | package com.spielberg.commonext
import android.os.Build
import android.text.Html
import android.util.Base64
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
import java.net.URLEncoder
/**
* @author: long
* @email <EMAIL>
* @describe Return the urlencoded string.
*/
fun String?.urlEncodeExt(): String? {
return this.urlEncodeExt("UTF-8")
}
/**
* @author: long
* @email <EMAIL>
* @describe Return the urlencoded string.
*/
fun String?.urlEncodeExt(charsetName: String?): String? {
return if (this.isEmptyOrBlankExt()) "" else try {
URLEncoder.encode(this, charsetName)
} catch (e: UnsupportedEncodingException) {
throw AssertionError(e)
}
}
/**
* @author: long
* @email <EMAIL>
* @describe Return the string of decode urlencoded string.
*/
fun String?.urlDecodeExt(): String? {
return this.urlDecodeExt("UTF-8")
}
/**
* @author: long
* @email <EMAIL>
* @describe Return the string of decode urlencoded string.
*/
fun String?.urlDecodeExt(charsetName: String?): String? {
return if (this.isEmptyOrBlankExt()) "" else try {
val safeInput =
this!!.replace("%(?![0-9a-fA-F]{2})".toRegex(), "%25").replace("\\+".toRegex(), "%2B")
URLDecoder.decode(safeInput, charsetName)
} catch (e: UnsupportedEncodingException) {
throw AssertionError(e)
}
}
/**
* @author: long
* @email <EMAIL>
* @describe Return Base64-encode bytes.
*/
fun String.base64EncodeExt(): ByteArray? {
return this.toByteArray().base64EncodeExt()
}
/**
* @author: long
* @email <EMAIL>
* @describe Return Base64-encode bytes.
*/
fun ByteArray?.base64EncodeExt(): ByteArray? {
return if (this == null || this.isEmpty()) ByteArray(0) else Base64.encode(
this,
Base64.NO_WRAP
)
}
/**
* @author: long
* @email <EMAIL>
* @describe Return Base64-encode string.
*/
fun ByteArray?.base64Encode2StringExt(): String? {
return if (this == null || this.isEmpty()) "" else Base64.encodeToString(
this,
Base64.NO_WRAP
)
}
/**
* @author: long
* @email <EMAIL>
* @describe Return the bytes of decode Base64-encode string.
*/
fun String?.base64DecodeExt(): ByteArray? {
return if (this == null || this.isEmpty()) ByteArray(0) else Base64.decode(
this,
Base64.NO_WRAP
)
}
/**
* @author: long
* @email <EMAIL>
* @describe Return the bytes of decode Base64-encode bytes.
*/
fun ByteArray?.base64DecodeExt(): ByteArray? {
return if (this == null || this.isEmpty()) ByteArray(0) else Base64.decode(
this,
Base64.NO_WRAP
)
}
/**
* @author: long
* @email <EMAIL>
* @describe Return html-encode string.
*/
fun CharSequence?.htmlEncodeExt(): String? {
if (this == null || this.isEmpty()) return ""
val sb = StringBuffer()
var c: Char
var i = 0
val len = this.length
while (i < len) {
c = this[i]
when (c) {
'<' -> sb.append("<") //$NON-NLS-1$
'>' -> sb.append(">") //$NON-NLS-1$
'&' -> sb.append("&") //$NON-NLS-1$
'\'' -> //http://www.w3.org/TR/xhtml1
// The named character reference ' (the apostrophe, U+0027) was
// introduced in XML 1.0 but does not appear in HTML. Authors should
// therefore use ' instead of ' to work as expected in HTML 4
// user agents.
sb.append("'") //$NON-NLS-1$
'"' -> sb.append(""") //$NON-NLS-1$
else -> sb.append(c)
}
i++
}
return sb.toString()
}
/**
* @author: long
* @email <EMAIL>
* @describe Return the string of decode html-encode string.
*/
fun String?.htmlDecodeExt(): CharSequence? {
if (this.isEmptyOrBlankExt()) return ""
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(this)
}
}
/**
* @author: long
* @email <EMAIL>
* @describe Return the binary encoded string padded with one space
*/
fun String?.binaryEncodeExt(): String? {
if (this.isEmptyOrBlankExt()) return ""
val sb = StringBuffer()
for (i in this!!.toCharArray()) {
sb.append(Integer.toBinaryString(i.toInt())).append(" ")
}
return sb.deleteCharAt(sb.length - 1).toString()
}
/**
* @author: long
* @email <EMAIL>
* @describe Return UTF-8 String from binary
*/
fun String?.binaryDecodeExt(): String? {
if (this.isEmptyOrBlankExt()) return ""
val splits = this!!.split(" ".toRegex()).toTypedArray()
val sb = StringBuffer()
for (split in splits) {
sb.append(split.toInt(2).toChar())
}
return sb.toString()
} | 0 | Kotlin | 0 | 0 | 85f113fb0471d34652982da8bfa97e99a288f523 | 4,797 | CommonEx | Apache License 2.0 |
app/src/main/java/pl/kamilszustak/justfit/common/moshi/adapter/LocalDateTimeFieldAdapter.kt | swistak7171 | 248,487,099 | false | null | package pl.kamilszustak.justfit.common.moshi.adapter
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
import pl.kamilszustak.justfit.common.moshi.annotation.LocalDateTimeField
import java.text.SimpleDateFormat
import java.util.Date
class LocalDateTimeFieldAdapter {
private val dateFormat: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd'T'h:m")
@FromJson
@LocalDateTimeField
fun fromJson(dateText: String?): Date? {
return if (dateText != null) {
dateFormat.parse(dateText)
} else {
null
}
}
@ToJson
fun toJson(@LocalDateTimeField date: Date?): String? {
return if (date != null) {
dateFormat.format(date)
} else {
null
}
}
} | 0 | Kotlin | 0 | 1 | e1b584010dd7edeaa41c7d432fb398f05a2f5dea | 777 | JustFit | Apache License 2.0 |
app/src/main/java/br/com/renancsdev/avenuecodeeventos/viewmodel/detalhe/DetalheViewModel.kt | RenanCostaSilva | 775,714,533 | false | {"Kotlin": 27190} | package br.com.renancsdev.avenuecodeeventos.viewmodel.detalhe
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import br.com.renancsdev.avenuecodeeventos.api.call.CallEvento
import br.com.renancsdev.avenuecodeeventos.api.sealed.Resultado
import br.com.renancsdev.avenuecodeeventos.model.Evento
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
class DetalheViewModel(private val api: CallEvento): ViewModel() {
private val _eventoID = MutableLiveData<LiveData<Resultado<Evento?>>>()
private val _checkIn = MutableLiveData<LiveData<Resultado<Evento?>>>()
val id = 0
private val nome = ""
private val email = ""
init {
viewModelScope.launch(IO) {
_eventoID.postValue(api.buscarEventosPorID(id))
_checkIn.postValue(api.fazerCheckIn(nome , email , id))
}
}
fun buscarEventosPorID(id: Int): LiveData<Resultado<Evento?>> =
api.buscarEventosPorID(id)
fun fazerCheckIN(nome: String , email: String , id: Int): LiveData<Resultado<Evento?>> =
api.fazerCheckIn(nome , email ,id)
} | 1 | Kotlin | 0 | 0 | fd9c60d148485dc4385ce35e81cab3b9881abe10 | 1,197 | AvenueCodeEventos | Apache License 2.0 |
app/src/main/java/com/example/movieshowstracker/data/model/FavoriteMovie.kt | danielmaman | 260,897,974 | false | null | package com.example.movieshowstracker.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "favorite_movie")
data class FavoriteMovie(
@PrimaryKey val imdbID: String
) | 0 | Kotlin | 0 | 0 | 27074ed8d51b5b9a022b4e6a3c3bea3f2fe6617f | 211 | MovieTracker | MIT License |
domain/src/main/kotlin/studio/lunabee/onesafe/domain/usecase/autolock/AutoLockInactivityUseCase.kt | LunabeeStudio | 624,544,471 | false | {"Kotlin": 2791660, "Java": 11977, "Python": 3979} | /*
* Copyright (c) 2023 Lunabee Studio
*
* 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.
*
* Created by Lunabee Studio / Date - 4/11/2023 - for the oneSafe6 SDK.
* Last modified 4/11/23, 10:45 AM
*/
package studio.lunabee.onesafe.domain.usecase.autolock
import co.touchlab.kermit.Logger
import com.lunabee.lbcore.model.LBResult
import com.lunabee.lblogger.LBLogger
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import studio.lunabee.onesafe.domain.repository.SafeRepository
import studio.lunabee.onesafe.domain.repository.SecuritySettingsRepository
import studio.lunabee.onesafe.domain.usecase.authentication.IsSafeReadyUseCase
import studio.lunabee.onesafe.error.OSError
import javax.inject.Inject
import kotlin.time.Duration
private val logger: Logger = LBLogger.get<AutoLockInactivityUseCase>()
class AutoLockInactivityUseCase @Inject constructor(
private val securitySettingsRepository: SecuritySettingsRepository,
private val autoLockInactivityGetRemainingTimeUseCase: AutoLockInactivityGetRemainingTimeUseCase,
private val lockAppUseCase: LockAppUseCase,
private val isSafeReadyUseCase: IsSafeReadyUseCase,
private val safeRepository: SafeRepository,
) {
suspend fun app(): LBResult<Unit> = OSError.runCatching(logger) {
val safeId = safeRepository.currentSafeId()
doAutoLock(
inactivityDelayFlow = securitySettingsRepository.autoLockInactivityDelayFlow(safeId),
remainingDelay = { autoLockInactivityGetRemainingTimeUseCase.app(safeId) },
clearClipboard = true,
)
}
suspend fun osk(): LBResult<Unit> = OSError.runCatching(logger) {
val safeId = safeRepository.currentSafeId()
doAutoLock(
inactivityDelayFlow = securitySettingsRepository.autoLockOSKInactivityDelayFlow(safeId),
remainingDelay = { autoLockInactivityGetRemainingTimeUseCase.osk(safeId) },
clearClipboard = false,
)
}
private suspend fun doAutoLock(
inactivityDelayFlow: Flow<Duration>,
remainingDelay: suspend () -> Duration,
clearClipboard: Boolean,
) {
combine(
inactivityDelayFlow,
isSafeReadyUseCase.flow(),
) { inactivityDelay, isCryptoDataReady ->
inactivityDelay to isCryptoDataReady
}.collectLatest { (inactivityDelay, isCryptoDataReady) ->
if (isCryptoDataReady && inactivityDelay != Duration.INFINITE) {
var currentDelay = inactivityDelay
while (currentDelay > Duration.ZERO) {
delay(currentDelay)
currentDelay = remainingDelay()
}
lockAppUseCase(clearClipboard)
}
}
}
}
| 1 | Kotlin | 1 | 2 | 4d6199939c91e0d6d31aa5328549a3ac442d046a | 3,363 | oneSafe6_SDK_Android | Apache License 2.0 |
domain/src/main/kotlin/studio/lunabee/onesafe/domain/usecase/autolock/AutoLockInactivityUseCase.kt | LunabeeStudio | 624,544,471 | false | {"Kotlin": 2791660, "Java": 11977, "Python": 3979} | /*
* Copyright (c) 2023 Lunabee Studio
*
* 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.
*
* Created by Lunabee Studio / Date - 4/11/2023 - for the oneSafe6 SDK.
* Last modified 4/11/23, 10:45 AM
*/
package studio.lunabee.onesafe.domain.usecase.autolock
import co.touchlab.kermit.Logger
import com.lunabee.lbcore.model.LBResult
import com.lunabee.lblogger.LBLogger
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import studio.lunabee.onesafe.domain.repository.SafeRepository
import studio.lunabee.onesafe.domain.repository.SecuritySettingsRepository
import studio.lunabee.onesafe.domain.usecase.authentication.IsSafeReadyUseCase
import studio.lunabee.onesafe.error.OSError
import javax.inject.Inject
import kotlin.time.Duration
private val logger: Logger = LBLogger.get<AutoLockInactivityUseCase>()
class AutoLockInactivityUseCase @Inject constructor(
private val securitySettingsRepository: SecuritySettingsRepository,
private val autoLockInactivityGetRemainingTimeUseCase: AutoLockInactivityGetRemainingTimeUseCase,
private val lockAppUseCase: LockAppUseCase,
private val isSafeReadyUseCase: IsSafeReadyUseCase,
private val safeRepository: SafeRepository,
) {
suspend fun app(): LBResult<Unit> = OSError.runCatching(logger) {
val safeId = safeRepository.currentSafeId()
doAutoLock(
inactivityDelayFlow = securitySettingsRepository.autoLockInactivityDelayFlow(safeId),
remainingDelay = { autoLockInactivityGetRemainingTimeUseCase.app(safeId) },
clearClipboard = true,
)
}
suspend fun osk(): LBResult<Unit> = OSError.runCatching(logger) {
val safeId = safeRepository.currentSafeId()
doAutoLock(
inactivityDelayFlow = securitySettingsRepository.autoLockOSKInactivityDelayFlow(safeId),
remainingDelay = { autoLockInactivityGetRemainingTimeUseCase.osk(safeId) },
clearClipboard = false,
)
}
private suspend fun doAutoLock(
inactivityDelayFlow: Flow<Duration>,
remainingDelay: suspend () -> Duration,
clearClipboard: Boolean,
) {
combine(
inactivityDelayFlow,
isSafeReadyUseCase.flow(),
) { inactivityDelay, isCryptoDataReady ->
inactivityDelay to isCryptoDataReady
}.collectLatest { (inactivityDelay, isCryptoDataReady) ->
if (isCryptoDataReady && inactivityDelay != Duration.INFINITE) {
var currentDelay = inactivityDelay
while (currentDelay > Duration.ZERO) {
delay(currentDelay)
currentDelay = remainingDelay()
}
lockAppUseCase(clearClipboard)
}
}
}
}
| 1 | Kotlin | 1 | 2 | 4d6199939c91e0d6d31aa5328549a3ac442d046a | 3,363 | oneSafe6_SDK_Android | Apache License 2.0 |
src/jvmMain/kotlin/maryk/rocksdb/WalFileType.kt | webnah | 195,759,908 | true | {"Kotlin": 707302} | package maryk.rocksdb
import org.rocksdb.WalFileType as RDBWalFileType
actual typealias WalFileType = RDBWalFileType
| 0 | Kotlin | 0 | 0 | 92ec1677df1646d817abfd434929d27d430ec319 | 119 | rocksdb | Apache License 2.0 |
lib/src/main/kotlin/online/ecm/youtrack/model/TimeTrackingUserProfile.kt | ecmonline | 429,371,464 | false | null | /**
* YouTrack REST API
*
* YouTrack issue tracking and project management system
*
* The version of the OpenAPI document: 2021.3
*
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package online.ecm.youtrack.model
import online.ecm.youtrack.model.PeriodFieldFormat
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
/**
* Represents time tracking settings in the user's profile.
*
* @param periodFormat
* @param id
* @param dollarType
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "\$type", visible = true)
@JsonSubTypes(
)
open class TimeTrackingUserProfile (
@get:JsonProperty("periodFormat")
val periodFormat: PeriodFieldFormat? = null,
@get:JsonProperty("id")
val id: kotlin.String? = null,
@get:JsonProperty("\$type")
val dollarType: kotlin.String? = null,
)
| 0 | Kotlin | 2 | 3 | ccbbeea848cddc13beecfb9c3a91195735c0f19b | 1,180 | youtrack-rest-api | Apache License 2.0 |
filesystem/src/androidTest/java/com/google/modernstorage/filesystem/AndroidPathsTests.kt | google | 365,054,118 | false | null | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.modernstorage.filesystem
import android.content.Context
import android.net.Uri
import androidx.test.core.app.ApplicationProvider
import org.junit.Before
import org.junit.Test
import java.io.File
import java.net.URI
import java.nio.file.FileSystems
/**
* Unit tests for [AndroidPaths] that depend on Android specific methods.
*/
class AndroidPathsTests {
private val context = ApplicationProvider.getApplicationContext<Context>()
@Before
fun setup() {
AndroidFileSystems.initialize(context)
}
@Test
fun constructPath_UriMatchesURI() {
val mediaUriString = "content://media/external/files/media/1"
val mediaPathFromUri = AndroidPaths.get(Uri.parse(mediaUriString))
val mediaPathFromURI = AndroidPaths.get(URI(mediaUriString))
assert(mediaPathFromUri.toUri() == mediaPathFromURI.toUri())
}
@Test
fun constructPath_FileScheme() {
val filePath = AndroidPaths.get(File(context.filesDir, "Test.txt").toURI())
assert(filePath.fileSystem == FileSystems.getDefault())
}
}
| 8 | Kotlin | 24 | 859 | 05a8ee7ad4e680c1507415cd0f0c9cd052d4dc16 | 1,681 | modernstorage | Apache License 2.0 |
kronos/src/test/java/com/hananrh/kronos/constraint/MinValueConstraintTest.kt | hananrh | 288,522,556 | false | {"Kotlin": 106265} | package com.hananrh.kronos.constraint
import com.hananrh.kronos.common.kronosTest
import com.hananrh.kronos.common.mapConfig
import com.hananrh.kronos.common.withRemoteMap
import com.hananrh.kronos.config.FeatureRemoteConfig
import com.hananrh.kronos.config.constraint.FallbackPolicy
import com.hananrh.kronos.config.constraint.minValue
import com.hananrh.kronos.config.type.adaptedLongConfig
import com.hananrh.kronos.config.type.floatConfig
import com.hananrh.kronos.config.type.intConfig
import com.hananrh.kronos.config.type.longConfig
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertEquals
object MinValueConstraintTest : Spek(kronosTest {
class DefaultFallbackConfig : FeatureRemoteConfig by mapConfig() {
val someInt by intConfig {
default = 3
minValue = 2
}
val someLong by longConfig {
default = 3
minValue = 2
}
val someFloat by floatConfig {
default = 3f
minValue = 2f
}
val someAdapted by adaptedLongConfig {
default = ""
minValue = 0
adapt {
get { it.toString() }
}
}
}
val defaultFallbackConfig = DefaultFallbackConfig()
describe("Remote value smaller than minValue should fallback to default") {
beforeGroup {
withRemoteMap(
"someInt" to 1,
"someLong" to 1L,
"someFloat" to 1f,
"someAdapted" to -1L
)
}
it("Should return default - intConfig") {
assertEquals(3, defaultFallbackConfig.someInt)
}
it("Should return default - longConfig") {
assertEquals(3L, defaultFallbackConfig.someLong)
}
it("Should return default - floatConfig") {
assertEquals(3f, defaultFallbackConfig.someFloat)
}
it("Should return default - adaptedConfig") {
assertEquals("", defaultFallbackConfig.someAdapted)
}
}
describe("Remote value equal or greater than minValue should be used") {
beforeGroup {
withRemoteMap(
"someInt" to 5,
"someLong" to 5L,
"someFloat" to 5f
)
}
it("Should return remote value - intConfig") {
assertEquals(5, defaultFallbackConfig.someInt)
}
it("Should return remote value - longConfig") {
assertEquals(5L, defaultFallbackConfig.someLong)
}
it("Should return remote value - floatConfig") {
assertEquals(5f, defaultFallbackConfig.someFloat)
}
}
describe("Remote value smaller than minValue with range fallback should fall to it") {
class RangeFallbackConfig : FeatureRemoteConfig by mapConfig() {
val someInt by intConfig {
default = 3
minValue {
value = 2
fallbackPolicy = FallbackPolicy.RANGE
}
}
val someLong by longConfig {
default = 3
minValue {
value = 2L
fallbackPolicy = FallbackPolicy.RANGE
}
}
val someFloat by floatConfig {
default = 3f
minValue {
value = 2f
fallbackPolicy = FallbackPolicy.RANGE
}
}
}
val rangeFallbackConfig = RangeFallbackConfig()
beforeGroup {
withRemoteMap(
"someInt" to 1,
"someLong" to 1L,
"someFloat" to 1f
)
}
it("Should return minValue - intConfig") {
assertEquals(2, rangeFallbackConfig.someInt)
}
it("Should return minValue - longConfig") {
assertEquals(2L, rangeFallbackConfig.someLong)
}
it("Should return minValue - floatConfig") {
assertEquals(2f, rangeFallbackConfig.someFloat)
}
}
}) | 0 | Kotlin | 0 | 0 | b8757b4affcecae66613256f5ae3d32e12e7b773 | 3,316 | kronos | MIT License |
library_api/src/main/java/com/crow/ksp/api/handler/OutgoingHandler.kt | crowforkotlin | 798,153,843 | false | {"Kotlin": 27881} | package com.crow.ksp.api.handler
import com.crow.ksp.api.RouteHandler
import com.crow.ksp.api.RouteRequest
import com.crow.ksp.api.Router
class OutgoingHandler(private val domains: Set<String> = setOf(), private val schemes: Set<String> = setOf()) : RouteHandler {
override fun handle(request: RouteRequest): Boolean {
val uri = request.uri
if (setOf("http", "https").contains(uri.scheme) && (domains.isEmpty() || domains.contains(uri.host))) {
return Router.browse(request.context, uri)
}
if (uri.scheme.isNullOrEmpty()) {
return false
}
if (schemes.isEmpty() || schemes.contains(uri.scheme)) {
return Router.browse(request.context, uri)
}
return false
}
} | 0 | Kotlin | 0 | 0 | 5a89525b8254cf84f9da450714e8df631cbe2a76 | 767 | Ksp-Template | Apache License 2.0 |
src/main/java/org/radarbase/management/service/mapper/SubjectMapper.kt | RADAR-base | 90,646,368 | false | {"Kotlin": 1000491, "TypeScript": 476028, "HTML": 280734, "Java": 24215, "SCSS": 20166, "Scala": 16198, "JavaScript": 3395, "Dockerfile": 2950, "Shell": 734, "CSS": 425} | package org.radarbase.management.service.mapper
import org.mapstruct.DecoratedWith
import org.mapstruct.IterableMapping
import org.mapstruct.Mapper
import org.mapstruct.Mapping
import org.mapstruct.MappingTarget
import org.mapstruct.Named
import org.radarbase.management.domain.Subject
import org.radarbase.management.service.dto.SubjectDTO
import org.radarbase.management.service.mapper.decorator.SubjectMapperDecorator
/**
* Mapper for the entity Subject and its DTO SubjectDTO.
*/
@Mapper(
componentModel = "spring",
uses = [UserMapper::class, ProjectMapper::class, SourceMapper::class, RoleMapper::class]
)
@DecoratedWith(
SubjectMapperDecorator::class
)
interface SubjectMapper {
@Mapping(source = "user.login", target = "login")
@Mapping(target = "status", ignore = true)
@Mapping(target = "project", ignore = true)
@Mapping(source = "group.name", target = "group")
@Mapping(target = "createdBy", ignore = true)
@Mapping(target = "createdDate", ignore = true)
@Mapping(target = "lastModifiedBy", ignore = true)
@Mapping(target = "lastModifiedDate", ignore = true)
@Mapping(source = "user.roles", target = "roles")
fun subjectToSubjectDTO(subject: Subject?): SubjectDTO?
@Mapping(source = "user.login", target = "login")
@Mapping(source = "group.name", target = "group")
@Mapping(target = "status", ignore = true)
@Mapping(target = "project", ignore = true)
@Mapping(target = "createdBy", ignore = true)
@Mapping(target = "createdDate", ignore = true)
@Mapping(target = "lastModifiedBy", ignore = true)
@Mapping(target = "lastModifiedDate", ignore = true)
@Mapping(source = "user.roles", target = "roles")
fun subjectToSubjectReducedProjectDTO(subject: Subject?): SubjectDTO?
@Named(value = "subjectReducedProjectDTO")
@Mapping(source = "user.login", target = "login")
@Mapping(source = "group.name", target = "group")
@Mapping(target = "status", ignore = true)
@Mapping(target = "project", ignore = true)
@Mapping(target = "createdBy", ignore = true)
@Mapping(target = "createdDate", ignore = true)
@Mapping(target = "lastModifiedBy", ignore = true)
@Mapping(target = "lastModifiedDate", ignore = true)
@Mapping(source = "user.roles", target = "roles")
fun subjectToSubjectWithoutProjectDTO(subject: Subject?): SubjectDTO?
@IterableMapping(qualifiedByName = ["subjectReducedProjectDTO"])
fun subjectsToSubjectReducedProjectDTOs(subjects: List<Subject?>?): List<SubjectDTO?>?
@Mapping(source = "login", target = "user.login")
@Mapping(target = "group", ignore = true)
@Mapping(target = "user.email", ignore = true)
@Mapping(target = "user.activated", ignore = true)
@Mapping(target = "removed", ignore = true)
@Mapping(source = "roles", target = "user.roles")
@Mapping(target = "metaTokens", ignore = true)
fun subjectDTOToSubject(subjectDto: SubjectDTO?): Subject?
@Mapping(target = "user", ignore = true)
@Mapping(target = "removed", ignore = true)
@Mapping(target = "metaTokens", ignore = true)
@Mapping(target = "group", ignore = true)
fun safeUpdateSubjectFromDTO(subjectDto: SubjectDTO?, @MappingTarget subject: Subject?): Subject?
/**
* Generating the fromId for all mappers if the databaseType is sql, as the class has
* relationship to it might need it, instead of creating a new attribute to know if the entity
* has any relationship from some other entity.
*
* @param id id of the entity
* @return the entity instance
*/
fun subjectFromId(id: Long?): Subject? {
if (id == null) {
return null
}
val subject = Subject()
subject.id = id
return subject
}
}
| 85 | Kotlin | 16 | 21 | 7d5d527beaf6e9d20f7f8bb95dfc110eb46fe300 | 3,774 | ManagementPortal | Apache License 2.0 |
src/test/kotlin/info/benjaminhill/utils/SimplePrefKtTest.kt | salamanders | 277,926,542 | false | null | package info.benjaminhill.utils
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class SimplePrefKtTest {
private val mySetting1: Int by preference(
enclosingClass = this::class.java,
key = "MY_SETTING_1",
defaultValue = -1
)
private var mySetting2: Int by preference(
enclosingClass = this::class.java,
key = "MY_SETTING_2",
defaultValue = -1
)
@Test
fun testPrefs() {
mySetting2 = 5
assertEquals(-1, mySetting1)
assertEquals(5, mySetting2)
mySetting2 = 7
assertEquals(7, mySetting2)
}
} | 0 | Kotlin | 0 | 0 | a9b1fd396a83db15044c7a6cff77fe4ec6f20044 | 656 | utils | MIT License |
features/content/explore/explore-api/src/main/java/com/odogwudev/example/explore_api/ExploreService.kt | odogwudev | 592,877,753 | false | null | package com.odogwudev.example.explore_api
import com.odogwudev.example.pagination_api.PagerItem
import com.odogwudev.example.pagination_api.RefreshType
import kotlinx.coroutines.flow.Flow
interface ExploreService {
val discoverMovies: Flow<List<PagerItem>>
val searchMovies: Flow<List<PagerItem>>
val discoverTvSeries: Flow<List<PagerItem>>
val searchTvSeries: Flow<List<PagerItem>>
suspend fun getMovies(region: List<String>, withGenres: List<Int>, sortBy: List<String>, refreshType: RefreshType) : List<PagerItem>
suspend fun getTvSeries(region: List<String>, withGenres: List<Int>, sortBy: List<String>, refreshType: RefreshType) : List<PagerItem>
suspend fun searchMovies(query: String, refreshType: RefreshType) : List<PagerItem>
suspend fun searchTvSeries(query: String, refreshType: RefreshType) : List<PagerItem>
fun clearSearchMovies()
fun clearSearchTvSeries()
} | 0 | Kotlin | 0 | 4 | 82791abdcf1554d2a2cd498a19cd93952f90e53e | 924 | CinephilesCompanion | MIT License |
main/src/main/kotlin/dev/younesgouyd/apps/spotifyclient/desktop/main/ui/components/playlist/details/PlaylistDetails.kt | younesgouyd | 771,762,928 | false | {"Kotlin": 229749} | package dev.younesgouyd.apps.spotifyclient.desktop.main.ui.components.playlist.details
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.PlaylistAdd
import androidx.compose.material.icons.filled.PlayCircle
import androidx.compose.material.icons.filled.PlaylistRemove
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import dev.younesgouyd.apps.spotifyclient.desktop.main.TrackId
import dev.younesgouyd.apps.spotifyclient.desktop.main.UserId
import dev.younesgouyd.apps.spotifyclient.desktop.main.ui.Image
import dev.younesgouyd.apps.spotifyclient.desktop.main.ui.Item
import dev.younesgouyd.apps.spotifyclient.desktop.main.ui.ScrollToTopFloatingActionButton
import dev.younesgouyd.apps.spotifyclient.desktop.main.ui.VerticalScrollbar
import dev.younesgouyd.apps.spotifyclient.desktop.main.ui.models.Playlist
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
@Composable
fun PlaylistDetails(state: PlaylistDetailsState) {
when (state) {
is PlaylistDetailsState.Loading -> Text("Loading...")
is PlaylistDetailsState.State -> PlaylistDetails(state)
}
}
@Composable
private fun PlaylistDetails(state: PlaylistDetailsState.State) {
PlaylistDetails(
playlist = state.playlist,
followButtonEnabledState = state.followButtonEnabledState,
tracks = state.tracks,
loadingTracks = state.loadingTracks,
onOwnerClick = state.onOwnerClick,
onPlaylistFollowStateChange = state.onPlaylistFollowStateChange,
onLoadTracks = state.onLoadTracks,
onPlayClick = state.onPlayClick,
onTrackClick = state.onTrackClick
)
}
@Composable
private fun PlaylistDetails(
playlist: StateFlow<Playlist>,
followButtonEnabledState: StateFlow<Boolean>,
tracks: StateFlow<List<Playlist.Track>>,
loadingTracks: StateFlow<Boolean>,
onOwnerClick: (UserId) -> Unit,
onPlaylistFollowStateChange: (state: Boolean) -> Unit,
onLoadTracks: () -> Unit,
onPlayClick: () -> Unit,
onTrackClick: (TrackId) -> Unit
) {
val playlist by playlist.collectAsState()
val followButtonEnabledState by followButtonEnabledState.collectAsState()
val tracks by tracks.collectAsState()
val loadingTracks by loadingTracks.collectAsState()
val lazyColumnState = rememberLazyListState()
Scaffold(
modifier = Modifier.fillMaxSize(),
content = { it ->
Box(modifier = Modifier.fillMaxSize().padding(it)) {
VerticalScrollbar(lazyColumnState)
LazyColumn (
modifier = Modifier.fillMaxSize().padding(end = 16.dp),
state = lazyColumnState,
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
item {
PlaylistInfo(
modifier = Modifier.fillMaxWidth(),
playlist = playlist,
followButtonEnabledState = followButtonEnabledState,
onOwnerClick = onOwnerClick,
onPlaylistFollowStateChange = onPlaylistFollowStateChange,
onPlayClick = onPlayClick
)
}
items(
items = tracks,
key = { it.id }
) { item ->
TrackItem(
modifier = Modifier.fillMaxWidth(),
track = item,
onTrackClick = onTrackClick
)
}
if (loadingTracks) {
item {
Box(modifier = Modifier.fillMaxWidth().padding(10.dp), contentAlignment = Alignment.Center) {
CircularProgressIndicator(modifier = Modifier.size(50.dp), strokeWidth = 2.dp)
}
}
}
}
}
},
floatingActionButton = { ScrollToTopFloatingActionButton(lazyColumnState) }
)
LaunchedEffect(lazyColumnState) {
snapshotFlow {
lazyColumnState.layoutInfo.visibleItemsInfo.lastOrNull()?.index
}.map { it == null || it >= (tracks.size + 1) - 5 }
.filter { it }
.collect { onLoadTracks() }
}
}
@Composable
private fun PlaylistInfo(
modifier: Modifier,
playlist: Playlist,
followButtonEnabledState: Boolean,
onOwnerClick: (UserId) -> Unit,
onPlaylistFollowStateChange: (state: Boolean) -> Unit,
onPlayClick: () -> Unit
) {
Row(
modifier = modifier.height(300.dp),
horizontalArrangement = Arrangement.spacedBy(space = 12.dp, alignment = Alignment.Start),
verticalAlignment = Alignment.CenterVertically
) {
Image(
modifier = Modifier.fillMaxHeight(),
url = playlist.images.preferablyMedium(),
contentScale = ContentScale.FillHeight
)
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(space = 12.dp, alignment = Alignment.CenterVertically)
) {
Text(
text = playlist.name ?: "",
style = MaterialTheme.typography.displayMedium
)
Text(
text = playlist.description ?: "",
style = MaterialTheme.typography.bodyMedium
)
if (playlist.owner != null) {
TextButton(
content = { Text(text = playlist.owner.name ?: "", style = MaterialTheme.typography.labelMedium) },
onClick = { onOwnerClick(playlist.owner.id) }
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(space = 12.dp, alignment = Alignment.CenterHorizontally),
verticalAlignment = Alignment.CenterVertically
) {
Button(
content = {
Row(
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(Icons.Default.PlayCircle, null)
Text(text = "Play", style = MaterialTheme.typography.labelMedium)
}
},
onClick = onPlayClick
)
Button(
content = {
Row(
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically
) {
if (!playlist.followed) {
Icon(Icons.AutoMirrored.Default.PlaylistAdd, null)
Text(text = "Follow", style = MaterialTheme.typography.labelMedium)
} else {
Icon(Icons.Default.PlaylistRemove, null)
Text(text = "Unfollow", style = MaterialTheme.typography.labelMedium)
}
}
},
onClick = { if (playlist.canUnfollow) onPlaylistFollowStateChange(!playlist.followed) },
enabled = followButtonEnabledState && playlist.canUnfollow
)
}
}
}
}
@Composable
private fun TrackItem(
modifier: Modifier = Modifier,
track: Playlist.Track,
onTrackClick: (TrackId) -> Unit
) {
Item(
modifier = modifier,
onClick = { onTrackClick(track.id) },
contentAlignment = Alignment.CenterStart
) {
Row(
horizontalArrangement = Arrangement.spacedBy(
space = 12.dp,
alignment = Alignment.Start
),
verticalAlignment = Alignment.CenterVertically
) {
Image(
modifier = Modifier.size(64.dp),
url = track.images.preferablySmall()
)
Text(
text = track.name ?: "",
style = MaterialTheme.typography.titleMedium
)
}
}
}
| 0 | Kotlin | 0 | 0 | 7da66f2b292503507ed1c7c897cbd8925799849f | 9,067 | spotify-client-desktop | Apache License 2.0 |
studio/src/main/java/com/seanghay/studio/gles/graphics/attribute/VertexAttribute.kt | seanghay | 200,696,080 | false | {"Gradle": 8, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Kotlin": 184, "YAML": 1, "Proguard": 2, "XML": 40, "Java": 8, "Text": 15} | /**
* Designed and developed by Seanghay Yath (@seanghay)
*
* 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.seanghay.studio.gles.graphics.attribute
import android.opengl.GLES20
import com.seanghay.studio.utils.GlUtils.FLOAT_SIZE_BYTES
import com.seanghay.studio.utils.toByteBuffer
import com.seanghay.studio.utils.toFloatBuffer
import java.nio.ByteBuffer
import java.nio.FloatBuffer
class VertexAttribute(name: String, var vertices: FloatArray, var coordinatesPerVertex: Int) :
Attribute<FloatArray>(name) {
var buffer: FloatBuffer = vertices.toFloatBuffer()
protected set
private var lastIndices: ByteArray? = null
private var lastIndicesBuffer: ByteBuffer? = null
override fun setValue(value: FloatArray) {
cachedValue = value
buffer = value.toFloatBuffer()
}
fun enable() {
GLES20.glEnableVertexAttribArray(getLocation())
GLES20.glVertexAttribPointer(
getLocation(), coordinatesPerVertex, GLES20.GL_FLOAT,
false, coordinatesPerVertex * FLOAT_SIZE_BYTES, buffer
)
}
fun drawArrays(mode: Int = DRAW_MODE) {
GLES20.glDrawArrays(mode, 0, vertices.size / coordinatesPerVertex)
}
fun drawElements(mode: Int = DRAW_MODE, count: Int, indices: ByteBuffer) {
if (count <= 0) throw RuntimeException("Vertices count cannot be lower than 0")
GLES20.glDrawElements(mode, count, GLES20.GL_UNSIGNED_BYTE, indices)
}
fun drawElements(mode: Int = DRAW_MODE, indices: ByteArray) {
val buffer: ByteBuffer =
(if (lastIndices?.contentEquals(indices) == true) lastIndicesBuffer
else null) ?: indices.toByteBuffer()
drawElements(mode, indices.size, buffer)
}
fun drawTriangleElements(vararg indices: Byte) {
drawElements(indices = indices)
}
fun disable() {
GLES20.glDisableVertexAttribArray(getLocation())
}
inline fun use(block: VertexAttribute.() -> Unit) {
enable()
block(this)
disable()
}
override fun getValue(): FloatArray {
return vertices
}
companion object {
const val DRAW_MODE = GLES20.GL_TRIANGLES
}
}
| 5 | Kotlin | 12 | 25 | 40344013111ecd72c508b75775123b7daddc7fab | 2,721 | studio | Apache License 2.0 |
wow-spring-boot-starter/src/test/kotlin/me/ahoo/wow/spring/boot/starter/eventsourcing/state/StateAutoConfigurationTest.kt | Ahoo-Wang | 628,167,080 | false | {"Kotlin": 1902621, "Java": 34050, "TypeScript": 31834, "HTML": 11619, "Lua": 3978, "JavaScript": 2288, "Dockerfile": 820, "SCSS": 500, "Less": 342} | package me.ahoo.wow.spring.boot.starter.eventsourcing.state
import io.mockk.mockk
import me.ahoo.wow.event.compensation.StateEventCompensator
import me.ahoo.wow.eventsourcing.EventStore
import me.ahoo.wow.eventsourcing.InMemoryEventStore
import me.ahoo.wow.eventsourcing.state.DistributedStateEventBus
import me.ahoo.wow.eventsourcing.state.InMemoryStateEventBus
import me.ahoo.wow.eventsourcing.state.LocalFirstStateEventBus
import me.ahoo.wow.eventsourcing.state.LocalStateEventBus
import me.ahoo.wow.eventsourcing.state.SendStateEventFilter
import me.ahoo.wow.modeling.state.ConstructorStateAggregateFactory
import me.ahoo.wow.modeling.state.StateAggregateFactory
import me.ahoo.wow.spring.boot.starter.BusProperties
import me.ahoo.wow.spring.boot.starter.enableWow
import org.assertj.core.api.AssertionsForInterfaceTypes
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.assertj.AssertableApplicationContext
import org.springframework.boot.test.context.runner.ApplicationContextRunner
class StateAutoConfigurationTest {
private val contextRunner = ApplicationContextRunner()
@Test
fun contextLoads() {
contextRunner
.enableWow()
.withPropertyValues(
"${StateProperties.BUS_TYPE}=${BusProperties.Type.IN_MEMORY_NAME}",
)
.withBean(EventStore::class.java, { InMemoryEventStore() })
.withBean(StateAggregateFactory::class.java, { ConstructorStateAggregateFactory })
.withUserConfiguration(
StateAutoConfiguration::class.java,
)
.run { context: AssertableApplicationContext ->
AssertionsForInterfaceTypes.assertThat(context)
.hasSingleBean(InMemoryStateEventBus::class.java)
.hasSingleBean(StateEventCompensator::class.java)
.hasSingleBean(SendStateEventFilter::class.java)
.hasSingleBean(StateEventCompensator::class.java)
}
}
@Test
fun contextLoadsIfLocalFirst() {
contextRunner
.enableWow()
.withBean(DistributedStateEventBus::class.java, { mockk() })
.withBean(EventStore::class.java, { InMemoryEventStore() })
.withBean(StateAggregateFactory::class.java, { ConstructorStateAggregateFactory })
.withUserConfiguration(
StateAutoConfiguration::class.java,
)
.withUserConfiguration(
StateAutoConfiguration::class.java,
)
.run { context: AssertableApplicationContext ->
AssertionsForInterfaceTypes.assertThat(context)
.hasSingleBean(LocalStateEventBus::class.java)
.hasSingleBean(LocalFirstStateEventBus::class.java)
}
}
}
| 6 | Kotlin | 4 | 98 | eed438bab2ae009edf3a1db03396de402885c681 | 2,845 | Wow | Apache License 2.0 |
src/main/kotlin/org/geepawhill/yz/Main.kt | geertguldentops | 360,274,296 | true | {"Kotlin": 8967} | package org.geepawhill.yz
import tornadofx.*
class Main : App(YzView::class) {
}
| 0 | null | 0 | 0 | 02cd25b0141bd2256774f30a42673a84dbffa4ef | 84 | yz | MIT License |
SolAppduino/SolArduino/app/src/main/kotlin/com/abbyberkers/solarduino/communication/HttpResponse.kt | PHPirates | 71,649,988 | false | {"C++": 600545, "Mathematica": 393627, "PHP": 109835, "Java": 92171, "Processing": 67920, "Haskell": 30026, "Python": 29344, "Kotlin": 23451, "C": 22148, "HTML": 7677, "CSS": 1880, "Shell": 160} | package com.abbyberkers.solarduino.communication
/**
* Response from the webserver.
*/
data class HttpResponse(
val emergency: Boolean,
val angle: Float,
val auto_mode: Boolean,
val message: String,
val min_angle: Float,
val max_angle: Float
) | 16 | C++ | 1 | 3 | d7fee339dd4af896cee267306127a13b160e032b | 294 | SolArduino | ISC License |
baselibrary/src/main/kotlin/com/huawen/baselibrary/views/SwipeProgressView.kt | cc17236 | 297,074,446 | false | null | package com.huawen.baselibrary.views
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.os.Build
import androidx.annotation.RequiresApi
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
/**
* @作者: #Administrator #
*@日期: #2018/9/12 #
*@时间: #2018年09月12日 11:27 #
*@File:Kotlin Class
*/
class SwipeProgressView : View {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
private var paint: Paint
private var touchSlop = 0
private var clickSlop = 0
init {
paint = Paint()
paint.isAntiAlias = true
paint.style = Paint.Style.FILL
touchSlop = ViewConfiguration.get(context).scaledTouchSlop
clickSlop = ViewConfiguration.getTapTimeout()
}
private var cursor: Float = 0f
var leftColor: Int = Color.parseColor("#D6ECFF")
var rightColor: Int = Color.WHITE
fun setProgress(progress: Float) {
cursor = progress
invalidate()
}
private val leftRectF = RectF()
private val rightRectF = RectF()
private var mWidth = 0
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
leftRectF.left = 0f
rightRectF.right = 0f
leftRectF.top = top.toFloat()
leftRectF.bottom = bottom.toFloat()
rightRectF.top = top.toFloat()
rightRectF.bottom = bottom.toFloat()
mWidth = width
}
companion object {
interface SwipeListener {
fun onSwipe(progress: Float)
fun onSwipeBegin()
fun onSwipeEnd(pos: Float)
}
}
private var lis: SwipeListener? = null
fun setOnSwipeListener(lis: SwipeListener) {
this.lis = lis
}
private var isEnable = true
fun setEnable(enable: Boolean) {
isEnable = enable
}
private var downX = 0f
private var downTime = 0.toLong()
private var swipeBegin = false
override fun onTouchEvent(event: MotionEvent?): Boolean {
when (event?.action) {
MotionEvent.ACTION_DOWN -> {
swipeBegin = false
downX = event.x
downTime = System.currentTimeMillis()
}
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
(parent as? ViewGroup)?.requestDisallowInterceptTouchEvent(false)
if (swipeBegin) {
val progress = ((event.x) / (mWidth.toFloat())) * 100.toFloat()
if (progress >= 0 && progress <= 100) {
if (x > downX) {//向右滑
lis?.onSwipeEnd(progress)
} else {//向左滑
lis?.onSwipeEnd(progress)
}
}
} else {
if (clickSlop < System.currentTimeMillis() - downTime) {
val progress = ((event.x) / (mWidth.toFloat())) * 100.toFloat()
if (progress >= 0 && progress <= 100) {
lis?.onSwipeBegin()
lis?.onSwipe(progress)
lis?.onSwipeEnd(progress)
}
}
}
downX = 0f
}
MotionEvent.ACTION_MOVE -> {
val x = event.x
if (isEnable) {
if (Math.abs(x - downX) > touchSlop) {
(parent as? ViewGroup)?.requestDisallowInterceptTouchEvent(true)
if (!swipeBegin) {
lis?.onSwipeBegin()
}
swipeBegin = true
val progress = ((event.x) / (mWidth.toFloat())) * 100.toFloat()
if (progress >= 0 && progress <= 100) {
if (x > downX) {//向右滑
setProgress(progress)
lis?.onSwipe(progress)
} else {//向左滑
setProgress(progress)
lis?.onSwipe(progress)
}
}
}
}
}
}
return true
}
private fun isTouchPointInView(view: View?, x: Int, y: Int): Boolean {
if (view == null) {
return false
}
val location = IntArray(2)
view.getLocationOnScreen(location)
val left = location[0]
val top = location[1]
val right = left + view.measuredWidth
val bottom = top + view.measuredHeight
//view.isClickable() &&
return if (y >= top && y <= bottom && x >= left
&& x <= right) {
true
} else false
}
override fun onDraw(canvas: Canvas?) {
val center = ((cursor / 100f) * mWidth.toFloat()).toInt()
leftRectF.right = leftRectF.left + center
rightRectF.left = rightRectF.right - center
if (center > 0f) {
paint.color = leftColor
canvas?.drawRect(leftRectF, paint)
}
paint.color = rightColor
canvas?.drawRect(rightRectF, paint)
}
} | 0 | Kotlin | 0 | 0 | 219c6d63fee41a9f28e9f935a3d222159d12d5e3 | 5,880 | AnroidKotlinSample | Apache License 2.0 |
sourceamazing-schema/src/test/kotlin/org/codeblessing/sourceamazing/schema/schemacreator/query/SchemaQueryValidatorTest.kt | code-blessing | 695,574,460 | false | {"Kotlin": 323825} | package org.codeblessing.sourceamazing.schema.schemacreator.query
import org.codeblessing.sourceamazing.schema.api.annotations.Concept
import org.codeblessing.sourceamazing.schema.api.annotations.QueryConcepts
import org.codeblessing.sourceamazing.schema.api.annotations.Schema
import org.codeblessing.sourceamazing.schema.schemacreator.exceptions.MalformedSchemaException
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
class SchemaQueryValidatorTest {
private interface CommonConceptInterface
@Concept(facets = [])
private interface OneConceptClass: CommonConceptInterface
@Concept(facets = [])
private interface OtherConceptClass: CommonConceptInterface
@Concept(facets = [])
private interface UnsupportedConceptClass
@Schema(concepts = [ OneConceptClass::class, OtherConceptClass::class ])
private interface SchemaWithoutAccessorMethods
@Test
fun `test schema without accessor method should return without exception`() {
SchemaQueryValidator.validateAccessorMethodsOfSchemaDefinitionClass(SchemaWithoutAccessorMethods::class)
}
@Schema(concepts = [ OneConceptClass::class, OtherConceptClass::class ])
private interface SchemaWithUnannotatedAccessorMethods {
fun getMyConcepts(): List<Any>
}
@Test
fun `test schema with a unannotated method should throw an exception`() {
assertThrows(MalformedSchemaException::class.java) {
SchemaQueryValidator.validateAccessorMethodsOfSchemaDefinitionClass(SchemaWithUnannotatedAccessorMethods::class)
}
}
@Schema(concepts = [ OneConceptClass::class, OtherConceptClass::class ])
private interface SchemaWithUnsupportedConceptClass {
@QueryConcepts(conceptClasses = [OtherConceptClass::class, UnsupportedConceptClass::class])
fun getMyConcepts(): List<Any>
}
@Test
fun `test schema with a unsupported concept class should throw an exception`() {
assertThrows(MalformedSchemaException::class.java) {
SchemaQueryValidator.validateAccessorMethodsOfSchemaDefinitionClass(SchemaWithUnsupportedConceptClass::class)
}
}
@Schema(concepts = [ OneConceptClass::class, OtherConceptClass::class ])
private interface SchemaWithEmptyConceptClass {
@QueryConcepts(conceptClasses = [])
fun getMyConcepts(): List<Any>
}
@Test
fun `test schema with a empty concept class list should throw an exception`() {
assertThrows(MalformedSchemaException::class.java) {
SchemaQueryValidator.validateAccessorMethodsOfSchemaDefinitionClass(SchemaWithEmptyConceptClass::class)
}
}
@Schema(concepts = [ OneConceptClass::class, OtherConceptClass::class ])
private interface SchemaWithValidReturnTypes {
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsAsListOfAny(): List<Any>
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsOfListOfConcreteConceptClass(): List<OneConceptClass>
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsOfListWithACommonBaseInterface(): List<CommonConceptInterface>
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsAsSetOfAny(): Set<Any>
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsOfSetOfConcreteConceptClass(): Set<OneConceptClass>
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsOfSetWithACommonBaseInterface(): Set<CommonConceptInterface>
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsAsAny(): Any
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsConcreteConceptClass(): OneConceptClass
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsWithACommonBaseInterface(): CommonConceptInterface
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsAsAnyNullable(): Any?
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsConcreteConceptClassNullable(): OneConceptClass?
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsWithACommonBaseInterfaceNullable(): CommonConceptInterface?
}
@Test
fun `test schema with valid return types should return without exception`() {
SchemaQueryValidator.validateAccessorMethodsOfSchemaDefinitionClass(SchemaWithValidReturnTypes::class)
}
@Schema(concepts = [ OneConceptClass::class, OtherConceptClass::class ])
private interface SchemaWithMethodHavingParameter {
@QueryConcepts(conceptClasses = [OneConceptClass::class])
fun getMyConceptsAsListOfAny(myParam: Int): List<Any>
}
@Test
fun `test schema with method having parameters should throw an exception`() {
assertThrows(MalformedSchemaException::class.java) {
SchemaQueryValidator.validateAccessorMethodsOfSchemaDefinitionClass(SchemaWithMethodHavingParameter::class)
}
}
} | 2 | Kotlin | 0 | 0 | de6462727ad25d107cd1ef93089acd5dc7fc0bac | 5,214 | sourceamazing | MIT License |
baselibrary/src/main/kotlin/com/huawen/baselibrary/schedule/navi2/internal/NaviEmitter.kt | cc17236 | 297,074,446 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 412, "XML": 48, "Java": 91} | /*
* 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.huawen.baselibrary.schedule.navi2.internal
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.os.PersistableBundle
import android.view.View
import com.huawen.baselibrary.schedule.navi2.Event
import com.huawen.baselibrary.schedule.navi2.Listener
import com.huawen.baselibrary.schedule.navi2.NaviComponent
import com.huawen.baselibrary.schedule.navi2.internal.Constants.Companion.SIGNAL
import com.huawen.baselibrary.schedule.navi2.model.ActivityResult
import com.huawen.baselibrary.schedule.navi2.model.BundleBundle
import com.huawen.baselibrary.schedule.navi2.model.RequestPermissionsResult
import com.huawen.baselibrary.schedule.navi2.model.ViewCreated
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
/**
* Emitter of Navi events which contains all the actual logic
*
* This makes it easier to port [NaviComponent] to Activities and Fragments
* without duplicating quite as much code.
*/
class NaviEmitter(handledEvents: Collection<Event<*>>) : NaviComponent {
private val handledEvents: Set<Event<*>>
private val listenerMap: ConcurrentHashMap<Event<*>, CopyOnWriteArrayList<Listener<Any>>>
// Only used for fast removal of listeners
private val eventMap: MutableMap<Listener<*>, Event<*>>
init {
this.handledEvents = Collections.unmodifiableSet(HashSet(handledEvents))
this.listenerMap = ConcurrentHashMap()
this.eventMap = ConcurrentHashMap()
}
override fun handlesEvents(vararg events: Event<*>): Boolean {
for (a in events.indices) {
val event = events[a]
if (event !== Event.ALL && !handledEvents.contains(event)) {
return false
}
}
return true
}
override fun <T> addListener(event: Event<T>, listener: Listener<T>) {
if (!handlesEvents(event)) {
throw IllegalArgumentException("This component cannot handle event $event")
}
// Check that we're not adding the same listener in multiple places
// For the same event, it's idempotent; for different events, it's an error
if (eventMap.containsKey(listener)) {
val otherEvent = eventMap[listener]
if (event != otherEvent) {
throw IllegalStateException(
"Cannot use the same listener for two events! e1: $event e2: $otherEvent"
)
}
return
}
eventMap[listener] = event
if (!listenerMap.containsKey(event)) {
listenerMap[event] = CopyOnWriteArrayList()
}
val listeners = listenerMap[event]
listeners!!.add(listener as Listener<Any>)
}
override fun <T> removeListener(listener: Listener<T>) {
val event = eventMap.remove(listener)
if (event != null && listenerMap.containsKey(event)) {
listenerMap[event]!!.remove(listener as Listener<Any>)
}
}
private fun emitEvent(event: Event<Any>) {
emitEvent(event, SIGNAL)
}
private fun <T> emitEvent(event: Event<T>, data: T) {
// We gather listener iterators all at once so adding/removing listeners during emission
// doesn't change the listener list.
val listeners = listenerMap[event]
val listenersIterator = listeners?.listIterator()
val allListeners = listenerMap[Event.ALL]
val allListenersIterator = allListeners?.iterator()
if (allListenersIterator != null) {
val type = event.type()
while (allListenersIterator.hasNext()) {
allListenersIterator.next().call(type)
}
}
if (listeners != null) {
while (listenersIterator!!.hasNext()) {
listenersIterator.next().call(data!!)
}
}
}
////////////////////////////////////////////////////////////////////////////
// Events
fun onActivityCreated(savedInstanceState: Bundle?) {
emitEvent(
Event.ACTIVITY_CREATED,
savedInstanceState ?: Bundle()
)
}
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
emitEvent(Event.ACTIVITY_RESULT, ActivityResult.create(requestCode, resultCode, data))
}
fun onAttach(activity: Activity) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
emitEvent(Event.ATTACH, activity)
}
}
fun onAttach(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
emitEvent(Event.ATTACH, context)
}
}
fun onAttachedToWindow() {
emitEvent(Event.ATTACHED_TO_WINDOW)
}
fun onBackPressed() {
emitEvent(Event.BACK_PRESSED)
}
fun onConfigurationChanged(newConfig: Configuration) {
emitEvent(Event.CONFIGURATION_CHANGED, newConfig)
}
fun onCreate(savedInstanceState: Bundle?) {
emitEvent(Event.CREATE, savedInstanceState ?: Bundle())
}
fun onCreate(
savedInstanceState: Bundle?,
persistentState: PersistableBundle?
) {
emitEvent(Event.CREATE_PERSISTABLE, BundleBundle.create(savedInstanceState, persistentState))
}
fun onCreateView(savedInstanceState: Bundle?) {
emitEvent(Event.CREATE_VIEW, savedInstanceState ?: Bundle())
}
fun onViewCreated(view: View, bundle: Bundle?) {
emitEvent(Event.VIEW_CREATED, ViewCreated.create(view, bundle))
}
fun onDestroy() {
emitEvent(Event.DESTROY)
}
fun onDestroyView() {
emitEvent(Event.DESTROY_VIEW)
}
fun onDetach() {
emitEvent(Event.DETACH)
}
fun onDetachedFromWindow() {
emitEvent(Event.DETACHED_FROM_WINDOW)
}
fun onNewIntent(intent: Intent) {
emitEvent(Event.NEW_INTENT, intent)
}
fun onPause() {
emitEvent(Event.PAUSE)
}
fun onPostCreate(savedInstanceState: Bundle?) {
emitEvent(Event.POST_CREATE, savedInstanceState ?: Bundle())
}
fun onPostCreate(
savedInstanceState: Bundle?,
persistentState: PersistableBundle?
) {
emitEvent(
Event.POST_CREATE_PERSISTABLE,
BundleBundle.create(savedInstanceState, persistentState)
)
}
fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>,
grantResults: IntArray
) {
emitEvent(
Event.REQUEST_PERMISSIONS_RESULT,
RequestPermissionsResult.create(requestCode, permissions, grantResults)
)
}
fun onRestart() {
emitEvent(Event.RESTART)
}
fun onRestoreInstanceState(savedInstanceState: Bundle?) {
emitEvent(
Event.RESTORE_INSTANCE_STATE,
savedInstanceState ?: Bundle()
)
}
fun onRestoreInstanceState(
savedInstanceState: Bundle?,
persistentState: PersistableBundle?
) {
emitEvent(
Event.RESTORE_INSTANCE_STATE_PERSISTABLE,
BundleBundle.create(savedInstanceState, persistentState)
)
}
fun onResume() {
emitEvent(Event.RESUME)
}
fun onSaveInstanceState(outState: Bundle) {
emitEvent(Event.SAVE_INSTANCE_STATE, outState)
}
fun onSaveInstanceState(
outState: Bundle,
outPersistentState: PersistableBundle
) {
emitEvent(
Event.SAVE_INSTANCE_STATE_PERSISTABLE,
BundleBundle.create(outState, outPersistentState)
)
}
fun onStart() {
emitEvent(Event.START)
}
fun onStop() {
emitEvent(Event.STOP)
}
fun onViewStateRestored(savedInstanceState: Bundle?) {
emitEvent(
Event.VIEW_STATE_RESTORED,
savedInstanceState ?: Bundle()
)
}
companion object {
fun createActivityEmitter(): NaviEmitter {
return NaviEmitter(HandledEvents.ACTIVITY_EVENTS)
}
fun createFragmentEmitter(): NaviEmitter {
return NaviEmitter(HandledEvents.FRAGMENT_EVENTS)
}
}
}
| 0 | Kotlin | 0 | 0 | 219c6d63fee41a9f28e9f935a3d222159d12d5e3 | 8,849 | AnroidKotlinSample | Apache License 2.0 |
src/main/kotlin/com/netflix/rewrite/ast/visitor/RetrieveCursorVisitor.kt | neven7 | 77,039,844 | false | null | package com.netflix.rewrite.ast.visitor
import com.netflix.rewrite.ast.Cursor
import com.netflix.rewrite.ast.Tree
class RetrieveCursorVisitor(val treeId: Long?) : AstVisitor<Cursor?>(null) {
constructor(t: Tree?) : this(t?.id)
override fun visitTree(t: Tree): Cursor? =
if (treeId == t.id) cursor() else super.visitTree(t)
} | 1 | null | 1 | 1 | 198ff9f21f80c313e9c94eca1f3ec65d62f17442 | 347 | rewrite | Apache License 2.0 |
androidApp/src/androidMain/kotlin/com/pstep/kmp/health/MainActivity.kt | Maximum21 | 772,105,852 | false | {"Kotlin": 50334, "Swift": 815, "Shell": 228, "Ruby": 190} | package com.pstep.kmp.health
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import com.pstep.kmp.health.sample.SampleApp
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
SampleApp()
}
}
} | 0 | Kotlin | 0 | 0 | 5874d610c7472f7be2e90a54fb45319282b7101c | 399 | HealthKMP | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.