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
src/main/kotlin/dev/emortal/immortal/game/GameManager.kt
EmortalMC
387,273,202
false
null
package dev.emortal.immortal.game import dev.emortal.immortal.inventory.GameSelectorGUI import net.kyori.adventure.sound.Sound import net.kyori.adventure.text.Component import net.kyori.adventure.text.format.NamedTextColor import net.minestom.server.entity.Player import net.minestom.server.event.Event import net.minestom.server.event.EventNode import net.minestom.server.sound.SoundEvent import net.minestom.server.tag.Tag import org.slf4j.Logger import org.slf4j.LoggerFactory import world.cepi.kstom.Manager import java.time.Duration import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import kotlin.reflect.KClass import kotlin.reflect.full.primaryConstructor object GameManager { val logger: Logger = LoggerFactory.getLogger("GameManager") val doNotUnregisterTag = Tag.Byte("doNotUnregister") val gameNameTag = Tag.String("gameName") val gameIdTag = Tag.Integer("gameId") val joiningGameTag = Tag.Byte("joiningGame") val playerGameMap = ConcurrentHashMap<Player, Game>() val gameNameToClassMap = ConcurrentHashMap<String, KClass<out Game>>() val registeredGameMap = ConcurrentHashMap<KClass<out Game>, GameTypeInfo>() val gameMap = ConcurrentHashMap<String, MutableSet<Game>>() @Volatile internal var nextGameID = 0 val Player.game get() = playerGameMap[this] fun Player.joinGameOrSpectate(game: Game): CompletableFuture<Void>? = joinGame(game) ?: spectateGame(game) fun Player.spectateGame(game: Game): CompletableFuture<Void>? { if (!game.gameTypeInfo.spectatable) return null if (game.spectators.contains(this)) { sendMessage(Component.text("Already spectating this game", NamedTextColor.RED)) return null } val lastGame = this.game if (hasTag(joiningGameTag)) { sendMessage(Component.text("Already trying to spectating a game", NamedTextColor.RED)) return null } setTag(joiningGameTag, 1) val future = game.addSpectator(this) if (future != null) { lastGame?.removePlayer(this) lastGame?.removeSpectator(this) playerGameMap[this] = game Manager.scheduler.buildTask { removeTag(joiningGameTag) }.delay(Duration.ofSeconds(3)).schedule() } else { sendMessage(Component.text("Something went wrong while spectating ${game.gameTypeInfo.gameName}", NamedTextColor.RED)) playSound(Sound.sound(SoundEvent.ENTITY_VILLAGER_NO, Sound.Source.MASTER, 1f, 1f), Sound.Emitter.self()) removeTag(joiningGameTag) } return future } fun Player.joinGame(game: Game): CompletableFuture<Void>? { if (!game.canBeJoined(this)) return null logger.info("Joining game ${game.gameTypeInfo.gameName}") val lastGame = this.game if (hasTag(joiningGameTag)) { sendMessage(Component.text("You are joining games too quickly", NamedTextColor.RED)) return null } setTag(joiningGameTag, 1) val future = game.addPlayer(this) if (future != null) { future.thenRun { lastGame?.removePlayer(this) lastGame?.removeSpectator(this) playerGameMap[this] = game Manager.scheduler.buildTask { removeTag(joiningGameTag) }.delay(Duration.ofSeconds(3)).schedule() } } else { sendMessage(Component.text("Something went wrong while joining ${game.gameTypeInfo.gameName}", NamedTextColor.RED)) playSound(Sound.sound(SoundEvent.ENTITY_VILLAGER_NO, Sound.Source.MASTER, 1f, 1f), Sound.Emitter.self()) removeTag(joiningGameTag) } return future } fun Player.joinGameOrNew( gameTypeName: String, options: GameOptions = registeredGameMap[gameNameToClassMap[gameTypeName]]!!.gameOptions ): CompletableFuture<Void>? = this.joinGame(findOrCreateGame(this, gameTypeName, options)) fun findOrCreateGame( player: Player, gameTypeName: String, options: GameOptions = registeredGameMap[gameNameToClassMap[gameTypeName]]!!.gameOptions ): Game { val game = gameMap[gameTypeName]?.firstOrNull { it.canBeJoined(player) && it.gameOptions == options } ?: createGame(gameTypeName, options, player) return game } fun createGame(gameTypeName: String, options: GameOptions, creator: Player? = null): Game { nextGameID++ //options.private = creator?.party?.privateGames ?: false val gameClass = gameNameToClassMap[gameTypeName] val game = gameClass?.primaryConstructor?.call(options) ?: throw IllegalArgumentException("Primary constructor not found.") game.gameCreator = creator gameMap.putIfAbsent(gameTypeName, mutableSetOf()) gameMap[gameTypeName]!!.add(game) return game } inline fun <reified T : Game> registerGame( eventNode: EventNode<Event>, gameName: String, sidebarTitle: Component, showsInSlashPlay: Boolean = true, canSpectate: Boolean = true, whenToRegisterEvents: WhenToRegisterEvents = WhenToRegisterEvents.GAME_START, gameOptions: GameOptions ) { gameNameToClassMap[gameName] = T::class registeredGameMap[T::class] = GameTypeInfo( eventNode, gameName, sidebarTitle, showsInSlashPlay, canSpectate, whenToRegisterEvents, gameOptions ) gameMap[gameName] = mutableSetOf() GameSelectorGUI.refresh() logger.info("Registered game type '${gameName}'") } inline fun <reified T : Game> unregisterGame() { val gameName = registeredGameMap[T::class]!!.gameName gameMap[gameName]?.forEach { it.destroy() } gameMap.remove(gameName) gameNameToClassMap.remove(gameName) registeredGameMap.remove(T::class) logger.info("Unregistered game type '${gameName}'") } }
4
Kotlin
0
5
81dfdace2b64f98a1c3433afd9f330dbe9d1cf4a
6,229
Immortal
MIT License
src/main/kotlin/com/wutsi/flutter/sdui/Positioned.kt
wutsi
415,658,640
false
null
package com.wutsi.flutter.sdui import com.wutsi.flutter.sdui.enums.WidgetType class Positioned( val top: Double? = null, val bottom: Double? = null, val left: Double? = null, val right: Double? = null, val width: Double? = null, val height: Double? = null, val child: WidgetAware, ) : WidgetAware { override fun toWidget() = Widget( type = WidgetType.Positioned, attributes = mapOf( "top" to top, "bottom" to bottom, "left" to left, "right" to right, "width" to width, "height" to height, ), children = listOf(child.toWidget()), ) }
1
Kotlin
1
2
0e39b6120b9cb6e8acf35c5d4d86cf95e75ebfae
675
sdui-kotlin
MIT License
lib/src/apiTest/kotlin/com/lemonappdev/konsist/architecture/assertarchitecture/architecture5/project/presentation/sample/PresentationSecondClass.kt
LemonAppDev
621,181,534
false
{"Kotlin": 4854719, "Python": 17926}
package com.lemonappdev.konsist.architecture.assertarchitecture.architecture5.project.presentation.sample import com.lemonappdev.konsist.architecture.assertarchitecture.architecture5.project.presentation.PresentationFirstClass class PresentationSecondClass(val sampleParameter: PresentationFirstClass)
5
Kotlin
26
995
603d19e179f59445c5f4707c1528a438e4595136
304
konsist
Apache License 2.0
thirdparty/ktfx-controlsfx-commons/src/main/kotlin/ktfx/controlsfx/controls/Notifications.kt
hanggrian
102,934,147
false
{"Kotlin": 1146536, "CSS": 1653}
@file:OptIn(ExperimentalContracts::class) package ktfx.controlsfx.controls import javafx.event.ActionEvent import javafx.geometry.Pos import javafx.scene.Node import javafx.util.Duration import ktfx.internal.KtfxInternals.NO_GETTER import ktfx.internal.KtfxInternals.noGetter import org.controlsfx.control.Notifications import org.controlsfx.control.action.Action import kotlin.DeprecationLevel.ERROR import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract /** Build notifications with Kotlin DSL. */ public inline fun buildNotifications( builderAction: NotificationsBuilder.() -> Unit, ): Notifications { contract { callsInPlace(builderAction, InvocationKind.EXACTLY_ONCE) } return NotificationsBuilder().apply(builderAction).notifications } /** Supporting class to use [Notifications] with DSL. */ public class NotificationsBuilder { public val notifications: Notifications = Notifications.create() /** Specify the text to show in the notification. */ public var text: String @Deprecated(NO_GETTER, level = ERROR) get() = noGetter() set(value) { notifications.text(value) } /** Specify the title to show in the notification. */ public var title: String @Deprecated(NO_GETTER, level = ERROR) get() = noGetter() set(value) { notifications.title(value) } /** Specify the graphic to show in the notification. */ public var graphic: Node @Deprecated(NO_GETTER, level = ERROR) get() = noGetter() set(value) { notifications.graphic(value) } /** Specify the position of the notification on screen, by default it is [Pos.BOTTOM_RIGHT]. */ public var position: Pos @Deprecated(NO_GETTER, level = ERROR) get() = noGetter() set(value) { notifications.position(value) } /** * The dialog window owner - which can be [javafx.stage.Screen], [javafx.stage.Window], * or [javafx.scene.Node]. */ public var owner: Any @Deprecated(NO_GETTER, level = ERROR) get() = noGetter() set(value) { notifications.owner(value) } /** Specify the duration that the notification should show, after which it will be hidden. */ public var hideAfter: Duration @Deprecated(NO_GETTER, level = ERROR) get() = noGetter() set(value) { notifications.hideAfter(value) } /** Specify what to do when the user clicks on the notification. */ public fun onAction(action: (ActionEvent) -> Unit) { notifications.onAction(action) } /** * Specify that the notification should use the built-in dark styling, rather than the default * 'modena' notification style. */ public fun darkStyle() { notifications.darkStyle() } /** * Specify that the close button in the top-right corner of the notification should not be * shown. */ public fun hideCloseButton() { notifications.hideCloseButton() } /** Specify the actions that should be shown in the notification as buttons. */ public fun actions(vararg actions: Action) { notifications.action(*actions) } /** * Collapses all the current notifications into a single notification when the number of * notifications exceed the threshold limit. A value of zero will disable the threshold * behavior. */ public fun threshold(threshold: Int, thresholdNotifications: Notifications) { notifications.threshold(threshold, thresholdNotifications) } /** Alias of [NotificationsBuilder.threshold] with builder DSL. */ public fun threshold( threshold: Int, thresholdNotificationsBuilder: NotificationsBuilder.() -> Unit, ) { notifications.threshold(threshold, buildNotifications(thresholdNotificationsBuilder)) } }
1
Kotlin
2
19
6e5ec9fedf8359423c31a2ba64cd175bc9864cd2
4,003
ktfx
Apache License 2.0
app/src/main/java/com/example/jetpack_compose_all_in_one/features/quotes_using_rx_java/QuoteAPI/APIService.kt
myofficework000
626,474,700
false
{"Kotlin": 1392414}
package com.example.jetpack_compose_all_in_one.features.quotes_using_rx_java.QuoteAPI import com.example.jetpack_compose_all_in_one.utils.Constants.RANDOM_ENDPOINT import io.reactivex.Single import retrofit2.http.GET interface APIService { @GET(RANDOM_ENDPOINT) fun getRandomQuote(): Single<QuoteResponse> }
21
Kotlin
22
222
4de5418608d6917b5c97fac7d868454c424daa26
318
Jetpack-Compose-All-in-one-Guide
MIT License
app/src/main/java/com/hoc/comicapp/ui/chapter_detail/ChapterDetailInteractorImpl.kt
hoang06kx1
216,228,666
true
{"Kotlin": 353295}
package com.hoc.comicapp.ui.chapter_detail import com.hoc.comicapp.domain.repository.ComicRepository import com.hoc.comicapp.domain.repository.DownloadComicsRepository import com.hoc.comicapp.domain.thread.CoroutinesDispatcherProvider import com.hoc.comicapp.ui.chapter_detail.ChapterDetailPartialChange.InitialRetryLoadChapterPartialChange import com.hoc.comicapp.ui.chapter_detail.ChapterDetailPartialChange.RefreshPartialChange import com.hoc.comicapp.ui.chapter_detail.ChapterDetailViewState.Chapter import com.hoc.comicapp.ui.chapter_detail.ChapterDetailViewState.Detail import com.hoc.comicapp.ui.chapter_detail.ChapterDetailViewState.Detail.Companion.fromDomain import com.hoc.comicapp.utils.fold import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.rx2.asObservable import timber.log.Timber @ExperimentalCoroutinesApi class ChapterDetailInteractorImpl( private val comicRepository: ComicRepository, private val dispatcherProvider: CoroutinesDispatcherProvider, private val downloadComicsRepository: DownloadComicsRepository ) : ChapterDetailInteractor { override fun getChapterDetail(chapter: Chapter, isDownloaded: Boolean) = flow<InitialRetryLoadChapterPartialChange> { Timber.tag("LoadChapter###").d("getChapterDetail ${chapter.debug}") val initial = Detail.Initial(chapter) emit(InitialRetryLoadChapterPartialChange.InitialData(initial)) emit(InitialRetryLoadChapterPartialChange.Loading) if (isDownloaded) { downloadComicsRepository .getDownloadedChapter(chapter.link) .map { it.fold( left = { InitialRetryLoadChapterPartialChange.Error(it, initial) }, right = { InitialRetryLoadChapterPartialChange.Data(fromDomain(it)) } ) } .let { emitAll(it) } } else { comicRepository .getChapterDetail(chapter.link) .fold( left = { InitialRetryLoadChapterPartialChange.Error( it, initial ) }, right = { InitialRetryLoadChapterPartialChange.Data(fromDomain(it)) } ) .let { emit(it) } } }.flowOn(dispatcherProvider.ui).asObservable() override fun refresh(chapter: Chapter, isDownloaded: Boolean) = flow<ChapterDetailPartialChange> { Timber.tag("LoadChapter###").d("refresh ${chapter.debug}") emit(RefreshPartialChange.Loading) if (isDownloaded) { var isFirstEvent = true downloadComicsRepository .getDownloadedChapter(chapter.link) .map { if (isFirstEvent) { it.fold( left = { RefreshPartialChange.Error(it) }, right = { RefreshPartialChange.Success(fromDomain(it)) } ).also { isFirstEvent = false } } else { val initial = Detail.Initial(chapter) it.fold( left = { InitialRetryLoadChapterPartialChange.Error(it, initial) }, right = { InitialRetryLoadChapterPartialChange.Data(fromDomain(it)) } ) } } .let { emitAll(it) } } else { comicRepository .getChapterDetail(chapter.link) .fold( left = { RefreshPartialChange.Error(it) }, right = { RefreshPartialChange.Success(fromDomain(it)) } ) .let { emit(it) } } }.flowOn(dispatcherProvider.ui).asObservable() }
0
null
0
0
8ff2ea495d56c2d73bfd5cfc4c6244d2b7c8faaa
3,548
ComicReaderApp_MVI_Coroutine_RxKotlin_Jetpack
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/emr/AutoTerminationPolicyPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.emr import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.emr.CfnCluster @Generated public fun buildAutoTerminationPolicyProperty(initializer: @AwsCdkDsl CfnCluster.AutoTerminationPolicyProperty.Builder.() -> Unit): CfnCluster.AutoTerminationPolicyProperty = CfnCluster.AutoTerminationPolicyProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
e08d201715c6bd4914fdc443682badc2ccc74bea
477
aws-cdk-kt
Apache License 2.0
app/src/main/java/com/baptistecarlier/echo/ui/component/videodetail/VideoDetailScreen.kt
BapNesS
533,918,653
false
{"Kotlin": 111871}
package com.baptistecarlier.echo.ui.component.videodetail import android.content.share import android.content.shareOnTwitter import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.platform.LocalContext import androidx.hilt.navigation.compose.hiltViewModel import com.baptistecarlier.echo.domain.model.YoutubeVideo import com.baptistecarlier.echo.ui.model.PostOn @Composable fun VideoDetailScreen( viewModel: VideoDetailVM = hiltViewModel(), onBack: () -> Unit ) { val state = viewModel.state.collectAsState().value val context = LocalContext.current val onPost: (postOn: PostOn, previewComment: String, youtubeVideo: YoutubeVideo) -> Unit = { postOn, previewComment, youtubeVideo -> when (postOn) { PostOn.LinkedIn -> viewModel.postOnLinkedIn(previewComment, youtubeVideo) PostOn.Twitter -> context.shareOnTwitter(previewComment) PostOn.JustText -> context.share(previewComment) } } VideoDetailView(state, onBack, onPost) }
0
Kotlin
0
1
26c09e5da4735f25ee066a3c5216b2cfc6ff95ac
1,102
EchoApp
Apache License 2.0
flare/src/iosMain/kotlin/enchant/flare/FirebaseStorage.kt
TeraThought
442,684,893
false
null
package enchant.flare import cocoapods.FirebaseStorage.* import kotlinx.cinterop.* import kotlinx.coroutines.suspendCancellableCoroutine import platform.Foundation.* import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException class FirebaseStorageImpl(private val storage: FIRStorage) : FirebaseStorage { override suspend fun deleteFile(path: String): Unit = suspendCancellableCoroutine { c -> storage.referenceWithPath(path).deleteWithCompletion { error -> if (error == null) c.resume(Unit) else c.resumeWithException(toStorageException(error)) } } override suspend fun getBytes( path: String, maxDownloadSize: Long ): ByteArray = suspendCancellableCoroutine { c -> storage.referenceWithPath(path).dataWithMaxSize(maxDownloadSize) { data, error -> if (data != null) memScoped { val p = StableRef.create(ByteArray(data.length.toInt())) data.getBytes(p.asCPointer()) c.resume(p.get()) } else c.resumeWithException(toStorageException(error!!)) } } override suspend fun getDownloadUrl(path: String): String = suspendCancellableCoroutine { c -> storage.referenceWithPath(path).downloadURLWithCompletion { data, error -> if (data != null) c.resume(data.toString()) else c.resumeWithException(toStorageException(error!!)) } } override suspend fun getFile( path: String, filePath: String, onProgress: ((bytesDownloaded: Long, totalBytes: Long) -> Unit)? ): Unit = suspendCancellableCoroutine { c -> val task = storage.referenceWithPath(path) .writeToFile(NSURL(fileURLWithPath = filePath)) { data, error -> if (data != null) c.resume(Unit) else if (error!!.code == FIRStorageErrorCodeCancelled) return@writeToFile else c.resumeWithException(toStorageException(error)) } if (onProgress != null) task.observeStatus(FIRStorageTaskStatus.FIRStorageTaskStatusProgress) { snapshot -> onProgress(snapshot!!.progress!!.completedUnitCount, snapshot.progress!!.totalUnitCount) } c.invokeOnCancellation { task.cancel() } } override suspend fun getMetadata(path: String): StorageMetadata = suspendCancellableCoroutine { c -> storage.referenceWithPath(path).metadataWithCompletion { data, error -> if (data != null) c.resume(toStorageMetadata(data)) else c.resumeWithException(toStorageException(error!!)) } } override suspend fun list(path: String, maxResults: Int?, pageToken: String?): ListResult { return suspendCancellableCoroutine { c -> val completion: (FIRStorageListResult?, NSError?) -> Unit = { data, error -> if (data != null) c.resume( ListResult( data.items.map { (it as FIRStorageReference).fullPath }, data.pageToken ) ) else c.resumeWithException(toStorageException(error!!)) } when { maxResults == null -> storage.referenceWithPath(path) .listAllWithCompletion(completion) pageToken == null -> storage.referenceWithPath(path) .listWithMaxResults(maxResults.toLong(), completion) else -> storage.referenceWithPath(path) .listWithMaxResults(maxResults.toLong(), pageToken, completion) } } } override suspend fun putBytes( path: String, bytes: ByteArray, metadata: FileMetadata?, onProgress: ((bytesUploaded: Long, totalBytes: Long) -> Unit)? ): StorageMetadata = suspendCancellableCoroutine { c -> var d: NSData? = null memScoped { d = NSData.dataWithBytesNoCopy( StableRef.create(bytes).asCPointer(), bytes.size.toULong() ) } val task = storage.referenceWithPath(path).putData(d!!, metadata?.let { toFIRMetadata(it) }) { data, error -> if (data != null) c.resume(toStorageMetadata(data)) else if (error!!.code == FIRStorageErrorCodeCancelled) return@putData else c.resumeWithException(toStorageException(error)) } if (onProgress != null) task.observeStatus(FIRStorageTaskStatus.FIRStorageTaskStatusProgress) { snapshot -> onProgress(snapshot!!.progress!!.completedUnitCount, snapshot.progress!!.totalUnitCount) } c.invokeOnCancellation { task.cancel() } } override suspend fun putFile( path: String, filePath: String, metadata: FileMetadata?, onProgress: ((bytesUploaded: Long, totalBytes: Long) -> Unit)? ): StorageMetadata = suspendCancellableCoroutine { c -> val task = storage.referenceWithPath(path).putFile(NSURL(fileURLWithPath = filePath), metadata?.let { toFIRMetadata(it) }) { data, error -> if (data != null) c.resume(toStorageMetadata(data)) else if (error!!.code == FIRStorageErrorCodeCancelled) return@putFile else c.resumeWithException(toStorageException(error)) } if (onProgress != null) task.observeStatus(FIRStorageTaskStatus.FIRStorageTaskStatusProgress) { snapshot -> onProgress(snapshot!!.progress!!.completedUnitCount, snapshot.progress!!.totalUnitCount) } c.invokeOnCancellation { task.cancel() } } override suspend fun updateMetadata(path: String, metadata: FileMetadata): StorageMetadata = suspendCancellableCoroutine { c -> storage.referenceWithPath(path).updateMetadata(toFIRMetadata(metadata)) { data, error -> if (data != null) c.resume(toStorageMetadata(data)) else c.resumeWithException(toStorageException(error!!)) } } override val config: FirebaseStorage.Config get() = object : FirebaseStorage.Config { override var maxDownloadRetryTime: Long get() = storage.maxDownloadRetryTime.toLong() set(value) { storage.setMaxDownloadRetryTime(value.toDouble()) } override var maxOperationRetryTime: Long get() = storage.maxOperationRetryTime.toLong() set(value) { storage.setMaxOperationRetryTime(value.toDouble()) } override var maxUploadRetryTime: Long get() = storage.maxUploadRetryTime.toLong() set(value) { storage.setMaxUploadRetryTime(value.toDouble()) } override val bucket: String get() = storage.reference().bucket override fun useEmulator(host: String, port: Int) = storage.useEmulatorWithHost(host, port.toLong()) } private fun toFIRMetadata(metadata: FileMetadata): FIRStorageMetadata = FIRStorageMetadata().apply { cacheControl = metadata.cacheControl contentDisposition = metadata.contentDisposition contentEncoding = metadata.contentEncoding contentLanguage = metadata.contentLanguage contentType = metadata.contentType setCustomMetadata(metadata.customMetadata as Map<Any?, *>) } private fun toStorageMetadata(metadata: FIRStorageMetadata?): StorageMetadata = StorageMetadata( bucket = metadata!!.bucket, cacheControl = metadata.cacheControl, contentDisposition = metadata.contentDisposition, contentEncoding = metadata.contentEncoding, contentLanguage = metadata.contentLanguage, contentType = metadata.contentType, creationTime = metadata.timeCreated!!.timeIntervalSince1970.toLong(), generation = metadata.generation, md5Hash = metadata.md5Hash, metadataGeneration = metadata.metageneration, name = metadata.name, path = metadata.path!!, size = metadata.size, updatedTime = metadata.updated!!.timeIntervalSince1970.toLong(), customMetadata = metadata.customMetadata as Map<String, String> ) } private fun toStorageException(error: NSError): StorageException { val code = when (error.code) { FIRStorageErrorCodeBucketNotFound -> StorageException.Code.BucketNotFound FIRStorageErrorCodeNonMatchingChecksum -> StorageException.Code.InvalidChecksum FIRStorageErrorCodeUnauthenticated -> StorageException.Code.NotAuthenticated FIRStorageErrorCodeUnauthorized -> StorageException.Code.NotAuthorized FIRStorageErrorCodeProjectNotFound -> StorageException.Code.ProjectNotFound FIRStorageErrorCodeQuotaExceeded -> StorageException.Code.QuotaExceeded FIRStorageErrorCodeRetryLimitExceeded -> StorageException.Code.RetryLimitExceeded FIRStorageErrorCodeObjectNotFound -> StorageException.Code.ObjectNotFound else -> StorageException.Code.Unknown } return StorageException(code, error.description) } internal actual val firebaseStorageInstance: FirebaseStorage by lazy { FirebaseStorageImpl(FIRStorage.storage()) } @Suppress("TYPE_MISMATCH") internal actual fun getStorageInstance(app: FirebaseApp): FirebaseStorage = FirebaseStorageImpl(FIRStorage.storageForApp(app.app))
1
Kotlin
3
0
8874d6ad0791b7d2dc6f2fd72d156d21d0c7eb7b
9,556
flare
Apache License 2.0
src/main/kotlin/com/fileee/oihAdapter/Constants.kt
openintegrationhub
159,690,721
false
null
package com.fileee.oihAdapter const val API_BASE_URL = "https://api.fileee.com/v2" const val PERSONS_API_URL = "$API_BASE_URL/persons" const val USER_INFO = "$API_BASE_URL/authorization/user-info" const val REFRESH_TOKEN_URL = "$API_BASE_URL/authorization/token" // json configuration constants const val OAUTH_KEY = "oauth" const val ACCESS_TOKEN = "access_token" const val REFRESH_TOKEN = "refresh_token" const val MODIFIED_AFTER_KEY = "modified_after" const val CONTACT_TYPE = "contacts" const val DELETED_CONTACT_TYPE = "deleted_contacts" const val DELETED_KEY = "deleted"
0
Kotlin
0
0
0bef6ec18c38c34f55b3ede68f7b68a3b7baf743
581
fileee-adapter
Apache License 2.0
music/commands/src/main/kotlin/dev/schlaubi/mikmusic/commands/NowPlayingCommand.kt
DRSchlaubi
409,332,765
false
{"Kotlin": 343748, "Java": 5154, "Dockerfile": 201, "Shell": 197, "PowerShell": 96}
package dev.schlaubi.mikmusic.commands import com.kotlindiscord.kord.extensions.commands.Arguments import com.kotlindiscord.kord.extensions.commands.converters.impl.optionalInt import com.kotlindiscord.kord.extensions.extensions.publicSlashCommand import dev.kord.rest.builder.message.embed import dev.schlaubi.mikmusic.checks.anyMusicPlaying import dev.schlaubi.mikmusic.checks.musicQuizAntiCheat import dev.schlaubi.mikmusic.core.MusicModule import dev.schlaubi.mikmusic.core.musicControlContexts import dev.schlaubi.mikmusic.util.addSong import kotlin.time.DurationUnit import kotlin.time.toDuration class NowPlayingArguments : Arguments() { val index by optionalInt { name = "position" description = "commands.now_playing.arguments.position.description" } } private val regex = """\.[0-9]*""".toRegex() suspend fun MusicModule.nowPlayingCommand() = publicSlashCommand(::NowPlayingArguments) { name = "now-playing" description = "commands.now_playing.description" musicControlContexts() check { anyMusicPlaying(this@nowPlayingCommand) musicQuizAntiCheat(this@nowPlayingCommand) } action { val index = arguments.index val (playingTrack) = if (index != null) { musicPlayer.queuedTracks.getOrNull(index) ?: run { respond { translate("commands.now_playing.invalid_index") } return@action } } else musicPlayer.playingTrack ?: return@action respond { embed { addSong(this@action, playingTrack) field { name = translate("commands.now_playing.serving_node.discord") value = "`${java.net.InetAddress.getLocalHost().hostName}`" } field { name = translate("commands.now_playing.serving_node.music") value = "`${link.node.host}`" } field { name = translate("commands.now_playing.progress") value = "${player.positionDuration.toString().replace(regex, "")}/${ playingTrack.info.length.toDuration( DurationUnit.MILLISECONDS ) }" } } } } }
16
Kotlin
12
36
7023a740f1019eba14ae667ba63b049743e7f502
2,394
mikbot
MIT License
base/src/main/kotlin/github/hua0512/plugins/base/Extractor.kt
hua0512
756,063,189
false
{"Kotlin": 530228, "Dockerfile": 614}
/* * MIT License * * Stream-rec https://github.com/hua0512/stream-rec * * Copyright (c) 2024 hua0512 (https://github.com/hua0512) * * 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 github.hua0512.plugins.base import github.hua0512.data.media.MediaInfo import github.hua0512.utils.withIOContext import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import kotlinx.serialization.json.Json import org.slf4j.Logger import org.slf4j.LoggerFactory /** * The base class for all the extractors. * * An extractor is a class that is used to extract the media info from an input stream. * * @property http the http client * @property json the json serializer * @author hua0512 * @date : 2024/3/15 19:47 */ abstract class Extractor(protected open val http: HttpClient, protected open val json: Json) { companion object { val commonHeaders = arrayOf( HttpHeaders.Accept to "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", HttpHeaders.AcceptLanguage to "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", HttpHeaders.UserAgent to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.3029.110 Safari/537.36" ) @JvmStatic protected val logger: Logger = LoggerFactory.getLogger(this::class.java) /** * Parses the cookies from the input string * @param cookies the input string * @return a map of cookies */ @JvmStatic protected fun parseCookies(cookies: String): Map<String, String> { return parseClientCookiesHeader(cookies) } } /** * The cookies to be used to download the stream */ var cookies: String = "" /** * The platform headers to be used to download the stream * @return a map of platform headers */ protected val platformHeaders = mutableMapOf<String, String>() /** * The platform params to be used to download the stream * @return a map of platform params */ protected val platformParams = mutableMapOf<String, String>() /** * The regex pattern to match the url * @return a regex pattern * @see Regex */ abstract val regexPattern: Regex /** * The url of the stream * @return a string of the url */ abstract val url: String /** * Initialize the extractor */ open suspend fun prepare() { if (!match()) { throw IllegalArgumentException("The url $url does not match the pattern") } } /** * Function to match the url with the regex pattern * @return a boolean value */ open fun match(): Boolean { return regexPattern.matches(url) } /** * Function to check if the stream is live * @return a boolean value */ protected abstract suspend fun isLive(): Boolean /** * Function to extract the media info from the stream * @return a [MediaInfo] object * @see MediaInfo */ abstract suspend fun extract(): MediaInfo /** * get the response from the input url * * request uses predefined headers and params: * [commonHeaders], [platformHeaders], [platformParams] * * @param url the input url * @param request the request builder * @return a [HttpResponse] object */ suspend fun getResponse(url: String, request: HttpRequestBuilder.() -> Unit = {}): HttpResponse = withIOContext { http.get(url) { populateCommons() request() } } /** * post the response from the input url * request uses predefined headers and params: * [commonHeaders], [platformHeaders], [platformParams] * @param url the input url * @param request the request builder * @return a [HttpResponse] object */ suspend fun postResponse(url: String, request: HttpRequestBuilder.() -> Unit = {}): HttpResponse = withIOContext { http.post(url) { populateCommons() request() } } /** * populate the common headers and params * @receiver the request builder * @see HttpRequestBuilder */ private fun HttpRequestBuilder.populateCommons() { headers { commonHeaders.forEach { append(it.first, it.second) } platformHeaders.forEach { append(it.key, it.value) } if (cookies.isNotEmpty()) { append(HttpHeaders.Cookie, cookies) } } platformParams.forEach { (t, u) -> parameter(t, u) } } }
5
Kotlin
1
7
cebff4def8190f642a73f4f0863b7e91059fce41
5,382
stream-rec
MIT License
app/src/main/java/com/pperrin54/happy_plants/home_activity/PlantModal.kt
protoxvga
570,509,351
false
{"Kotlin": 57661}
package com.pperrin54.happy_plants.home_activity class PlantModal( val plantID: Int, var plantName: String, var plantImage: Int, var plantCategory: String, var plantLuminosity: Float, var plantTemperature: Float, var plantHumidity: Float, var plantLastWatering: String, var plantWateringFreq: Int, var plantHappiness: Float ) { var id = 0 } class PlantGraphData( val plantID: Int, var date: String, var newPlantLuminosity: Float, var newPlantTemperature: Float, var newPlantHumidity: Float, var newPlantHappiness: Float ) { var id = 0 }
0
Kotlin
0
0
fbfd0d52c4f00917693733826da5a373ba32e07e
610
happy_plants
MIT License
src/main/kotlin/no/nav/tjenestepensjon/simulering/v1/soap/marshalling/domain/XMLSimulertPensjon.kt
navikt
184,583,998
false
null
package no.nav.tjenestepensjon.simulering.v1.soap.marshalling.domain import jakarta.xml.bind.annotation.XmlAccessType.* import jakarta.xml.bind.annotation.XmlAccessorType import jakarta.xml.bind.annotation.XmlElement import jakarta.xml.bind.annotation.XmlType import no.nav.tjenestepensjon.simulering.model.domain.FNR import no.nav.tjenestepensjon.simulering.v1.models.response.SimulertPensjon import no.nav.tjenestepensjon.simulering.v1.soap.marshalling.Utvidelse.SimulertPensjonUtvidelse1 @XmlAccessorType(FIELD) @XmlType(propOrder = [ "tpnr", "navnOrdning", "inkludertOrdningListe", "leverandorUrl", "utbetalingsperiodeListe", "utvidelse" ]) class XMLSimulertPensjon { @XmlElement(required = true) lateinit var tpnr: String @XmlElement(required = true) lateinit var navnOrdning: String @XmlElement(required = true) lateinit var inkludertOrdningListe: List<String> @XmlElement(required = true) lateinit var leverandorUrl: String @XmlElement(required = true, nillable = true) lateinit var utbetalingsperiodeListe: List<XMLUtbetalingsperiode?> lateinit var utvidelse: SimulertPensjonUtvidelse1 fun toSimulertPensjon(fnr: FNR) = SimulertPensjon( tpnr = tpnr, navnOrdning = navnOrdning, inkluderteOrdninger = inkludertOrdningListe, leverandorUrl = leverandorUrl, utbetalingsperioder = utbetalingsperiodeListe.map { it?.toUtbetalingsperiode(fnr) } ) }
10
Kotlin
0
0
4e8543b8c263fad378b2f2f75441f03d78762bf3
1,487
tjenestepensjon-simulering
MIT License
app/src/main/java/com/robert/android/lostpets/network/MessagingServiceGenerator.kt
robertene1994
303,119,114
false
null
package com.robert.android.lostpets.network import android.content.Context import com.robert.android.lostpets.BuildConfig import com.robert.android.lostpets.storage.SessionRepositoryImpl import ua.naiksoftware.stomp.Stomp import ua.naiksoftware.stomp.StompClient import ua.naiksoftware.stomp.dto.StompHeader /** * Clase que genera los servicios de mensajería basados en la comunicación mediante el protocolo * STOMP. * * @author <NAME> */ class MessagingServiceGenerator { companion object { private const val MESSAGING_SERVICE_BASE_URL = BuildConfig.LOST_PETS_MESSAGING private const val CLIENT_HEARTBEAT_MS = 1000 private const val SERVER_HEARTBEAT_MS = 1000 /** * Método que crea el servicio STOMP. * * @param context el contexto de la aplicación. * @return el servicio STOMP creado. */ fun createStompClient(context: Context): StompClient { return setUp(context) } private fun setUp(context: Context): StompClient { val mStompClient = Stomp.over(Stomp.ConnectionProvider.OKHTTP, MESSAGING_SERVICE_BASE_URL) .withClientHeartbeat(CLIENT_HEARTBEAT_MS) .withServerHeartbeat(SERVER_HEARTBEAT_MS) val token = SessionRepositoryImpl(context).getToken() val headers = ArrayList<StompHeader>() if (token != null) headers.add(StompHeader("Authorization", token)) mStompClient.connect(headers) return mStompClient } } }
0
Kotlin
0
0
a7af7de031d3ab4e2d14851a117d3729330cd875
1,601
lostpets-android
MIT License
src/commonMain/kotlin/com.comcast.vrex.sdk/message/send/WakeUpWord.kt
rdkcentral
493,187,704
false
null
/* * Copyright 2021 Comcast Cable Communications Management, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ package com.comcast.vrex.sdk.message.send import kotlinx.serialization.Serializable @Serializable data class WakeUpWord( val sowuw: Int, val eowuw: Int, val unit: Unit?, val detector: Detector? ) { private fun getByMs(time: Int): Int { return if (null == unit || Unit.SAMPLE == unit) { getTimeByMs(time) } else time } fun getSowuwByMs(): Int { return getByMs(sowuw) } fun getEowuwByMs(): Int { return getByMs(eowuw) } private fun getTimeByMs(sampleTime: Int): Int { return sampleTime ushr 4 // Our audio rate is 16K. } }
0
Kotlin
0
0
8cade4bea0976afe422c909a664477701222421a
1,292
xvcs-speech-sdk-core
Apache License 2.0
src/main/kotlin/io/cutebot/markonimagemanage/bot/blocks/managebot/tools/MarkBuilder.kt
asundukov
275,147,772
false
null
package io.cutebot.markonimagemanage.bot.blocks.managebot.tools import io.cutebot.markonimagemanage.botclient.model.MarkPosition data class MarkBuilder( var filePath: String, var title: String = "", var description: String = "", var sizePercent: Int = 50, var opacity: Int = 100, var position: MarkPosition = MarkPosition.LB )
2
Kotlin
0
0
cf165269d0053c5060ddf24ae1a943c339701259
377
mark-on-image-manage-bot
Apache License 2.0
ach/src/main/java/com/adyen/checkout/ach/internal/ui/ACHDirectDebitDelegate.kt
Adyen
91,104,663
false
null
/* * Copyright (c) 2023 <NAME>. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by onurk on 16/2/2023. */ package com.adyen.checkout.ach.internal.ui import com.adyen.checkout.ach.ACHDirectDebitComponentState import com.adyen.checkout.ach.internal.ui.model.ACHDirectDebitInputData import com.adyen.checkout.ach.internal.ui.model.ACHDirectDebitOutputData import com.adyen.checkout.components.core.internal.ui.PaymentComponentDelegate import com.adyen.checkout.core.exception.CheckoutException import com.adyen.checkout.ui.core.internal.ui.AddressDelegate import com.adyen.checkout.ui.core.internal.ui.ViewProvidingDelegate import kotlinx.coroutines.flow.Flow internal interface ACHDirectDebitDelegate : PaymentComponentDelegate<ACHDirectDebitComponentState>, ViewProvidingDelegate, AddressDelegate { val outputData: ACHDirectDebitOutputData val outputDataFlow: Flow<ACHDirectDebitOutputData> val componentStateFlow: Flow<ACHDirectDebitComponentState> val exceptionFlow: Flow<CheckoutException> fun updateInputData(update: ACHDirectDebitInputData.() -> Unit) }
28
Kotlin
59
96
1f000e27e07467f3a30bb3a786a43de62be003b2
1,169
adyen-android
MIT License
app/src/main/java/playground/develop/socialnote/di/AppModules.kt
mars-amn
197,773,483
false
{"Kotlin": 252056, "JavaScript": 2212}
package playground.develop.socialnote.di import androidx.room.Room import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.storage.FirebaseStorage import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module import playground.develop.socialnote.database.local.AppDatabase import playground.develop.socialnote.repository.AuthenticationRepository import playground.develop.socialnote.repository.NoteRepository import playground.develop.socialnote.repository.PostRepository import playground.develop.socialnote.viewmodel.AuthenticationViewModel import playground.develop.socialnote.viewmodel.NoteViewModel import playground.develop.socialnote.viewmodel.PostViewModel /** * Created by AbdullahAtta on 7/23/2019. */ val appModules = module { single { Room.databaseBuilder(androidContext(), AppDatabase::class.java, "notes.db").build() } single { get<AppDatabase>().notesDao() } } val repositoriesModules = module { single { NoteRepository() } single { AuthenticationRepository() } single { PostRepository() } } val viewModelsModules = module { viewModel { NoteViewModel() } viewModel { AuthenticationViewModel() } viewModel { PostViewModel() } } val firebaseModules = module { single { FirebaseAuth.getInstance() } single { FirebaseFirestore.getInstance() } single { FirebaseStorage.getInstance() } }
0
Kotlin
10
58
811a30081d7cf3555419a618ead5cebc0e28a6d7
1,491
Social-Note
MIT License
src/main/kotlin/com/google/androidstudiopoet/input/ModuleConfig.kt
Soros1223
118,137,013
true
{"Kotlin": 154933}
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.androidstudiopoet.input open class ModuleConfig(val moduleName: String, val javaPackageCount: Int, val javaClassCount: Int, val javaMethodsPerClass:Int, val kotlinPackageCount : Int, val kotlinClassCount: Int, val kotlinMethodsPerClass: Int, val useKotlin: Boolean, val extraLines: List<String>?, val dependencies: List<String>, val generateTests: Boolean)
0
Kotlin
0
0
594742e98a042e565806a98b25f5162fc6a19b33
1,011
android-studio-poet
Apache License 2.0
app/src/main/java/com/example/uasAPI/ui/penerbit/ListPenerbitFragment.kt
alkusr
501,196,460
false
null
package com.example.uasAPI.ui.penerbit import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import com.example.uasAPI.R import com.example.uasAPI.databinding.FragmentListPenerbitBinding import com.example.uasAPI.ui.MyViewModel class ListPenerbitFragment: Fragment() { private val myViewModel: MyViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = FragmentListPenerbitBinding.inflate(inflater) myViewModel.getPenerbitList() binding.lifecycleOwner = this binding.viewModel = myViewModel binding.recyclerView.adapter = PenerbitListAdapter(PenerbitListener { penerbit -> myViewModel.onPenerbitCLicked(penerbit) findNavController() .navigate(R.id.action_listPenerbitFragment_to_detailPenerbitFragment) }) return binding.root } }
0
Kotlin
0
1
d1d5f35149853d4a3d8534143fa5b2010fc79e19
1,177
UAS-Pemrograman-Mobile
MIT License
app/src/main/java/com/udacity/loadapp/view/ButtonState.kt
jploz
343,891,618
false
null
package com.udacity.loadapp.view sealed class ButtonState { object Clicked : ButtonState() object Loading : ButtonState() object Completed : ButtonState() }
0
Kotlin
0
0
7259636d163ce979cc7eed61f16444b381ccd274
171
android-nd-load-app
Apache License 2.0
helper/src/main/kotlin/io/kaxis/extension/DefaultKaxisBcJcaGenerator.kt
barudisshu
806,368,620
false
{"Kotlin": 1248420, "Java": 451145, "Shell": 28440, "Dockerfile": 956}
/* * Copyright (c) 2024. <EMAIL> * * All rights reserved. */ package io.kaxis.extension import io.kaxis.BCProvider import io.kaxis.extension.generator.KaxisBcFabric import io.kaxis.extension.param.AlgEnum import org.bouncycastle.asn1.x500.X500Name import org.slf4j.Logger import org.slf4j.LoggerFactory import java.security.KeyPair import java.security.KeyPairGenerator /** * Almost the same with [org.bouncycastle.jcajce.util.DefaultJcaJceHelper] * * @author galudisu */ class DefaultKaxisBcJcaGenerator : AbstractKaxisBcJcaGenerator() { companion object { private val LOGGER: Logger = LoggerFactory.getLogger(DefaultKaxisBcJcaGenerator::class.java) } /** * Also NOTE that there are good quality domain parameters available for both DSA and Diffie-Hellman and thus there is no need to genrate your own. A common performance issued with DSA and Diffie-Hellman keys are due to users generating their own parameters when there is no need to; parameter generation for both these algorithms is quite expensive. */ override fun spawn(algParameter: AlgParameter): JcaMiscPemGroove { fun getInstance( algorithm: String, provider: String, ): KeyPair { val keyPairGenerator = KeyPairGenerator.getInstance(algorithm, provider) if (algParameter.type == AlgEnum.DSA) { keyPairGenerator.initialize(generateDsaParameters(algParameter)) } else { keyPairGenerator.initialize(algParameter.keySize) } return keyPairGenerator.generateKeyPair() } val timeSlot = KaxisBcFabric.generateTimeSlot(algParameter.aliveYears) // ROOT val rootKeyPair = getInstance(algParameter.type.name, BCProvider.PROVIDER_NAME) val rootCertIssuer = X500Name(algParameter.caIssuer) val rootJcaKeyPair = KaxisBcFabric.generateX509CaChain(rootKeyPair, timeSlot, rootCertIssuer, algParameter.sigAlgName) LOGGER.info("Spawning ASN.1 {}", algParameter.sigAlgOid.id) val rootCert = rootJcaKeyPair.x509Certificate val generateFunc: (String, String, String, String, String, KeyPair) -> KaxisBcFabric.JcaKeyPair = { algorithm, provider, issuer, dnsName, ipAddress, keyPair -> val certKeyPair = getInstance(algorithm, provider) val certSubject = X500Name(issuer) KaxisBcFabric.generateX509CertificateAndKey( keyPair, certKeyPair, rootCert, rootCertIssuer, certSubject, timeSlot, dnsName, ipAddress, algParameter.sigAlgName, ) } // SERVER val serverJcaKeyPair = generateFunc( algParameter.type.name, BCProvider.PROVIDER_NAME, algParameter.serverIssuer, algParameter.serverDnsName, algParameter.serverIpAddress, rootKeyPair, ) // CLIENT val clientJcaKeyPair = generateFunc( algParameter.type.name, BCProvider.PROVIDER_NAME, algParameter.clientIssuer, algParameter.clientDnsName, algParameter.clientIpAddress, rootKeyPair, ) return JcaMiscPemGroove(rootJcaKeyPair, serverJcaKeyPair, clientJcaKeyPair) } }
0
Kotlin
0
0
e5cfba9c1f3db08eba55201a6fa128cfebb00006
3,171
kaxis
MIT License
src/test/kotlin/chapter6/solutions/ex10/listing.kt
DavidGomesh
680,857,367
false
{"Kotlin": 204685}
package chapter6.solutions.ex10 import chapter3.Cons import chapter3.List import chapter3.foldRight import chapter6.RNG import chapter6.rng1 import io.kotest.matchers.shouldBe import io.kotest.core.spec.style.WordSpec //tag::init[] data class State<S, out A>(val run: (S) -> Pair<A, S>) { companion object { fun <S, A> unit(a: A): State<S, A> = State { s: S -> a to s } //tag::ignore[] fun <S, A, B, C> map2( ra: State<S, A>, rb: State<S, B>, f: (A, B) -> C ): State<S, C> = ra.flatMap { a -> rb.map { b -> f(a, b) } } fun <S, A> sequence(fs: List<State<S, A>>): State<S, List<A>> = foldRight(fs, unit(List.empty<A>()), { f, acc -> map2(f, acc) { h, t -> Cons(h, t) } } ) //end::ignore[] } fun <B> map(f: (A) -> B): State<S, B> = flatMap { a -> unit<S, B>(f(a)) } fun <B> flatMap(f: (A) -> State<S, B>): State<S, B> = State { s: S -> val (a: A, s2: S) = this.run(s) f(a).run(s2) } } //end::init[] class Solution10 : WordSpec({ "unit" should { "compose a new state of pure a" { State.unit<RNG, Int>(1).run(rng1) shouldBe (1 to rng1) } } "map" should { "transform a state" { State.unit<RNG, Int>(1).map { it.toString() } .run(rng1) shouldBe ("1" to rng1) } } "flatMap" should { "transform a state" { State.unit<RNG, Int>(1) .flatMap { i -> State.unit<RNG, String>(i.toString()) }.run(rng1) shouldBe ("1" to rng1) } } "map2" should { "combine the results of two actions" { val combined: State<RNG, String> = State.map2( State.unit(1.0), State.unit(1) ) { d: Double, i: Int -> ">>> $d double; $i int" } combined.run(rng1).first shouldBe ">>> 1.0 double; 1 int" } } "sequence" should { "combine the results of many actions" { val combined: State<RNG, List<Int>> = State.sequence( List.of( State.unit(1), State.unit(2), State.unit(3), State.unit(4) ) ) combined.run(rng1).first shouldBe List.of(1, 2, 3, 4) } } })
0
Kotlin
0
0
41fd131cd5049cbafce8efff044bc00d8acddebd
2,680
fp-kotlin
MIT License
db/src/main/kotlin/org/jaram/jubaky/db/repository/JobRepositoryImpl.kt
jubaky
195,964,455
false
null
package org.jaram.jubaky.db.repository import org.jaram.jubaky.db.dao.JobDao import org.jaram.jubaky.protocol.JobInfo import org.jaram.jubaky.repository.JobRepository class JobRepositoryImpl( private val jobDao: JobDao ) : JobRepository { override suspend fun getJobInfo(applicationId: Int, branch: String): JobInfo { println("$applicationId, $branch") return jobDao.getJobInfo(applicationId, branch) } override suspend fun createJob(branch: String, applicationId: Int, tag: String) { jobDao.createJob(branch, applicationId, tag) } override suspend fun updateJob(applicationId: Int, branch: String, lastBuildNumber: Int) { jobDao.updateJob(applicationId, branch, lastBuildNumber) } }
1
Kotlin
1
0
834790726cc2d9be82eded60fc2449cf7e22591a
748
api_server
Apache License 2.0
src/main/kotlin/io/battlerune/game/world/actor/pawn/player/block/PlayerHitUpdateBlock.kt
scape-tools
105,257,050
false
null
package io.battlerune.game.world.actor.pawn.player.block import io.battlerune.game.world.actor.pawn.player.Player import io.battlerune.game.world.actor.pawn.update.UpdateBlock import io.battlerune.game.world.actor.pawn.update.BlockType import io.battlerune.net.codec.game.RSByteBufWriter class PlayerHitUpdateBlock : UpdateBlock<Player>(0x20, BlockType.HIT) { override fun encode(pawn: Player, buffer: RSByteBufWriter) { // TODO } }
0
Kotlin
12
9
dd711cf4c61cd0af99e8e2d51afee5f5c02bdbad
452
kotlin-osrs
MIT License
persistance/src/main/java/com/linhtetko/persistance/entities/WeatherEntity.kt
lin-htet-ko
726,358,254
false
{"Kotlin": 95925, "CMake": 1249, "C++": 502}
package com.linhtetko.persistance.entities import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import com.linhtetko.persistance.databases.Schema @Entity(tableName = Schema.Table.TB_WEATHER, indices = [Index("type")]) data class WeatherEntity( @PrimaryKey(autoGenerate = true) val id: Int = 0, val day: String, val date: String, val time: String, val tempC: Double, val tempF: Double, val status: String, val statusIcon: String, val windySpeedKph: Double, val windySpeedMph: Double, val uv: Double, val cloud: Int, val location: String, val type: Int ) { companion object { const val TYPE_CURRENT = 0 const val TYPE_FORECAST = 1 } }
0
Kotlin
0
0
dea33ddf60850d8e3ec8fc6d121cb161ea65bd1a
757
efficient_weather_app
Apache License 2.0
Server/src/main/kotlin/server/PythonInitialization.kt
MikeDepies
325,124,905
false
{"CSS": 7942948, "Kotlin": 700526, "Python": 545415, "TypeScript": 76204, "Svelte": 50830, "JavaScript": 6857, "HTML": 2446, "Dockerfile": 772}
package server import kotlinx.serialization.Serializable @Serializable data class EvaluatorSettings(val attackTime: Int, val maxTime: Int, val actionLimit: Int) @Serializable enum class MeleeStage { FinalDestination, BattleField, PokemonStadium, Dreamland, FountainOfDreams } @Serializable data class ControllerConfiguration(val character: Character, val cpuLevel: Int) @Serializable data class PythonConfiguration( val evaluatorSettings: EvaluatorSettings, val player1: ControllerConfiguration, val player2: ControllerConfiguration, val stage: MeleeStage, val frameDelay : Int )
0
CSS
0
3
215f13fd4140e32b882e3a8c68900b174d388d9f
608
NeatKotlin
Apache License 2.0
airin-core/src/jvmMain/kotlin/io/morfly/airin/SharedPropertiesHolder.kt
Morfly
368,910,388
false
{"Kotlin": 84682}
package io.morfly.airin import io.morfly.airin.label.MavenCoordinates interface SharedPropertiesHolder { val sharedProperties: MutableMap<String, Any> } @Suppress("UNCHECKED_CAST") val SharedPropertiesHolder.allMavenArtifacts: MutableSet<MavenCoordinates> get() = sharedProperties.getOrPut("allMavenArtifacts") { mutableSetOf<MavenCoordinates>() } as MutableSet<MavenCoordinates>
1
Kotlin
3
31
0891ce67c744e9b49ddf0714247ae1b7131df03e
404
airin
Apache License 2.0
app/src/androidTest/java/com/kylecorry/trail_sense/astronomy/domain/moon/MoonPhaseCalculatorTest.kt
TrendingTechnology
268,941,914
true
{"Kotlin": 217677}
package com.kylecorry.trail_sense.astronomy.domain.moon import org.junit.Test import org.junit.Assert.* import java.time.LocalDateTime import java.time.Month import java.time.ZoneId import java.time.ZonedDateTime class MoonPhaseCalculatorTest { @Test fun getPhase() { val calculator = MoonPhaseCalculator() val tolerance = 0.5f // Main phases assertMoonPhases(MoonPhase(MoonTruePhase.FirstQuarter, 50f), calculator.getPhase(getDate(LocalDateTime.of(2020, Month.MARCH, 2, 14, 58))), tolerance) assertMoonPhases(MoonPhase(MoonTruePhase.Full, 100f), calculator.getPhase(getDate(LocalDateTime.of(2020, Month.MARCH, 9, 13, 48))), tolerance) assertMoonPhases(MoonPhase(MoonTruePhase.ThirdQuarter, 50f), calculator.getPhase(getDate(LocalDateTime.of(2020, Month.MARCH, 16, 5, 35))), tolerance) assertMoonPhases(MoonPhase(MoonTruePhase.New, 0f), calculator.getPhase(getDate(LocalDateTime.of(2020, Month.MARCH, 24, 5, 29))), tolerance) // Intermediate phases assertMoonPhases(MoonPhase(MoonTruePhase.WaxingCrescent, 23f), calculator.getPhase(getDate(LocalDateTime.of(2020, Month.MARCH, 29, 12, 0))), tolerance) assertMoonPhases(MoonPhase(MoonTruePhase.WaxingGibbous, 79f), calculator.getPhase(getDate(LocalDateTime.of(2020, Month.MARCH, 5, 12, 0))), tolerance) assertMoonPhases(MoonPhase(MoonTruePhase.WaningGibbous, 79f), calculator.getPhase(getDate(LocalDateTime.of(2020, Month.MARCH, 13, 12, 0))), tolerance) assertMoonPhases(MoonPhase(MoonTruePhase.WaningCrescent, 28f), calculator.getPhase(getDate(LocalDateTime.of(2020, Month.MARCH, 18, 12, 0))), tolerance) } private fun getDate(time: LocalDateTime): ZonedDateTime { return time.atZone(ZoneId.of("America/New_York")) } private fun assertMoonPhases(expected: MoonPhase, actual: MoonPhase, tolerance: Float){ assertEquals(expected.phase, actual.phase) assertEquals(expected.illumination, actual.illumination, tolerance) } }
0
null
0
0
ba8786be4ac8deb02f3f0cbc71f4b11420cd09fa
2,027
Trail-Sense
MIT License
app/src/main/java/com/uphar/bussiness/domain/Utils/BasePreferences.kt
uphargaur
790,430,007
false
{"Kotlin": 44522, "Java": 2198}
package com.jhalakXCorp.vent.bussinesss.domain.Utils import android.content.Context val PREFERENCE_NAME = "language_preference" val FIREBASE_REFRESH_TOKEN = "firebase_refresh_token" val MULTIPLE_LOGIN = "multiple_login" val LOG_OUT_REASON = "login_out_reason" val LOG_IN_STATUS = "login_status" val APP_TOKEN = "application_token" val APP_REFRESH_TOKEN = "application_refresh_token" class BasePreferences(context: Context?) { private val preferences = context?.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE) fun setFirebaseRefreshedToken(token: String) { val editor = preferences?.edit() editor?.putString(FIREBASE_REFRESH_TOKEN, token) editor?.apply() } fun getFirebaseRefreshedToken() = preferences?.getString(FIREBASE_REFRESH_TOKEN, "") fun setTokens(token: String, refreshToken: String) { val editor = preferences?.edit() editor?.putString(APP_TOKEN, token) editor?.putString(APP_REFRESH_TOKEN, refreshToken) editor?.apply() } fun getToken() = preferences?.getString(APP_TOKEN, "") fun getRefreshToken() = preferences?.getString(APP_REFRESH_TOKEN, "") fun setMultipleLogin(status: Boolean, reason: String) { val editor = preferences?.edit() editor?.putBoolean(MULTIPLE_LOGIN, status) editor?.putString(LOG_OUT_REASON, reason) editor?.apply() } fun isMultipleLogin() = preferences?.getBoolean(MULTIPLE_LOGIN, false) fun getLogOutReason() = preferences?.getString(LOG_OUT_REASON, "") fun setLoginStatus(status: Boolean) { val editor = preferences?.edit() editor?.putBoolean(LOG_IN_STATUS, status) editor?.apply() } }
0
Kotlin
0
0
0d3b021399a1eb384f13a374fe79c66d65422948
1,720
PicSprint
MIT License
src/main/kotlin/dev/architectury/plugin/TransformingTask.kt
architectury
300,942,019
false
null
package dev.architectury.plugin import dev.architectury.plugin.utils.GradleSupport import dev.architectury.transformer.Transform import dev.architectury.transformer.Transformer import dev.architectury.transformer.shadowed.impl.com.google.gson.Gson import dev.architectury.transformer.transformers.BuiltinProperties import dev.architectury.transformer.util.Logger import dev.architectury.transformer.util.TransformerPair import org.gradle.api.Project import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction import org.gradle.jvm.tasks.Jar import java.io.File import java.nio.file.Path import java.util.* import java.util.function.BiConsumer import kotlin.properties.Delegates import kotlin.time.ExperimentalTime open class TransformingTask : Jar() { @InputFile val input: RegularFileProperty = GradleSupport.getFileProperty(project) @Internal val transformers: ListProperty<Transformer> = project.objects.listProperty(Transformer::class.java) @Internal var platform: String? = null @ExperimentalTime @TaskAction fun doTask() { val input: Path = this.input.asFile.get().toPath() val output: Path = this.archiveFile.get().asFile.toPath() val extension = project.extensions.getByType(ArchitectPluginExtension::class.java) extension.properties(platform ?: throw NullPointerException("No Platform specified")).forEach { (key, value) -> System.setProperty(key, value) } System.setProperty(BuiltinProperties.LOCATION, project.file(".gradle").absolutePath) Logger.debug("") Logger.debug("============================") Logger.debug("Transforming from $input to $output") Logger.debug("============================") Logger.debug("") Transform.runTransformers(input, output, transformers.get()) } operator fun invoke(transformer: Transformer) { transformers.add(transformer) } operator fun plusAssign(transformer: Transformer) { transformers.add(transformer) } fun add(transformer: Transformer, config: BiConsumer<Path, MutableMap<String, Any>>) { transformers.add(project.provider { val properties = mutableMapOf<String, Any>() config.accept(input.asFile.get().toPath(), properties) transformer.supplyProperties(Gson().toJsonTree(properties).asJsonObject) transformer }) } fun add(transformer: Transformer, config: MutableMap<String, Any>.(file: Path) -> Unit) { add(transformer, BiConsumer { file, map -> config(map, file) }) } } fun Project.projectUniqueIdentifier(): String { val cache = File(project.file(".gradle"), "architectury-cache") cache.mkdirs() val uniqueIdFile = File(cache, "projectID") var id by Delegates.notNull<String>() if (uniqueIdFile.exists()) { id = uniqueIdFile.readText() } else { id = UUID.randomUUID().toString().filterNot { it == '-' } uniqueIdFile.writeText(id) } var name = project.name if (project.rootProject != project) name = project.rootProject.name + "_" + name return "architectury_inject_${name}_$id".filter { Character.isJavaIdentifierPart(it) } } class Epic : RuntimeException()
4
Kotlin
7
48
0a37a6b6ed26600d0eea26d45281e50eb29233a2
3,424
architectury-plugin
MIT License
koarl-backend/src/main/java/dev/moetz/koarl/backend/obfuscation/ObfuscationManager.kt
FlowMo7
317,061,970
false
null
package dev.moetz.koarl.backend.obfuscation import dev.moetz.koarl.api.model.CrashUploadRequestBody import dev.moetz.koarl.backend.persistence.CrashStorage import dev.moetz.koarl.backend.persistence.ObfuscationMappingStorage import proguard.retrace.ReTrace import java.io.File import java.io.LineNumberReader import java.io.PrintWriter import java.io.StringWriter class ObfuscationManager( private val obfuscationMappingStorage: ObfuscationMappingStorage, private val stackTraceStringifier: StackTraceStringifier, private val crashStorage: CrashStorage, private val tempFileDirectory: File = File("/tmp/obfuscation") ) { private fun createMappingFile(mappingText: String): File { tempFileDirectory.mkdirs() return File.createTempFile("mapping", ".tmp", tempFileDirectory).apply { writeText(mappingText) } } suspend fun addMappingFile( packageName: String, appVersionCode: Long, mappingFileContents: String ) { obfuscationMappingStorage.insertMapping( packageName = packageName, appVersionCode = appVersionCode, mappingFileContents = mappingFileContents ) //TODO apply deobfuscation automatically to all crashes present in the crash store yet? val crashes = crashStorage.getCrashes( packageName = packageName, versionCode = appVersionCode ) crashes.forEach { crashData -> crashStorage.updateThrowable( crashUUID = crashData.crash.uuid, packageName = packageName, throwable = deObfuscate( mappingText = mappingFileContents, throwable = crashData.crash.throwable ) ) } //TODO regenerate groups! } suspend fun getObfuscationMapping(packageName: String, appVersionCode: Long): String? { return obfuscationMappingStorage.getMapping( packageName = packageName, appVersionCode = appVersionCode ) } suspend fun getObfuscationMappingVersionCodes(packageName: String): List<Long> { return obfuscationMappingStorage.getStoredMappingsForPackageName(packageName = packageName) } suspend fun deObfuscate( packageName: String, appVersionCode: Long, throwables: Iterable<CrashUploadRequestBody.ApiCrash.ApiThrowable> ): Iterable<CrashUploadRequestBody.ApiCrash.ApiThrowable> { val mappingText = getObfuscationMapping( packageName = packageName, appVersionCode = appVersionCode ) return if (mappingText != null) { val mappingFile = createMappingFile(mappingText) val reTrace = ReTrace( ReTrace.STACK_TRACE_EXPRESSION, false, mappingFile ) try { throwables.map { throwable -> deobFullStackTraceWithCause( reTrace = reTrace, obfuscated = throwable ) } } finally { mappingFile.delete() } } else { throw NoSuchElementException("No obfuscation mapping for packageName '$packageName' and appVersionCode '$appVersionCode' found.") } } fun deObfuscate( mappingText: String, throwable: CrashUploadRequestBody.ApiCrash.ApiThrowable ): CrashUploadRequestBody.ApiCrash.ApiThrowable { val mappingFile = createMappingFile(mappingText) val reTrace = ReTrace( ReTrace.STACK_TRACE_EXPRESSION, false, mappingFile ) return try { deobFullStackTraceWithCause( reTrace = reTrace, obfuscated = throwable ) } finally { mappingFile.delete() } } private fun deobFullStackTraceWithCause( reTrace: ReTrace, obfuscated: CrashUploadRequestBody.ApiCrash.ApiThrowable ): CrashUploadRequestBody.ApiCrash.ApiThrowable { var subject: CrashUploadRequestBody.ApiCrash.ApiThrowable? = obfuscated val stack = mutableListOf<CrashUploadRequestBody.ApiCrash.ApiThrowable>() while (subject != null) { stack.add(deobSingleStackTraceWithoutCause(reTrace, subject)) subject = subject.cause } val deobfuscated = stack.reversed() .fold<CrashUploadRequestBody.ApiCrash.ApiThrowable, CrashUploadRequestBody.ApiCrash.ApiThrowable?>( null ) { acc, item -> item.copy(cause = acc) }!! return deobfuscated } private fun deobSingleStackTraceWithoutCause( reTrace: ReTrace, obfuscated: CrashUploadRequestBody.ApiCrash.ApiThrowable ): CrashUploadRequestBody.ApiCrash.ApiThrowable { val stringWriter = StringWriter() reTrace.retrace( LineNumberReader( stackTraceStringifier.getStackTraceString( apiThrowable = obfuscated, includeCause = false ).reader() ), PrintWriter(stringWriter) ) val deobString = stringWriter.toString() val deobfuscatedApiThrowable = stackTraceStringifier.stackTraceToApiThrowable( stackTraceString = deobString, originalApiThrowable = obfuscated, cause = null ) return deobfuscatedApiThrowable } }
0
Kotlin
0
6
48bec5de7c1fdb9eaa67795f3313f0b3d690af15
5,603
Koarl
Apache License 2.0
src/main/kotlin/br/com/manieri/mikoshi/repository/RepositoryData.kt
JoaoManieri
798,898,226
false
{"Kotlin": 9453}
package br.com.manieri.mikoshi.repository import br.com.manieri.mikoshi.model.SaveData import br.com.manieri.mikoshi.model.Validation import br.com.manieri.mikoshi.util.getHash import org.springframework.stereotype.Repository import java.io.File @Repository class RepositoryData { fun setData(data : SaveData){ File("dados.csv").appendText(data.getCsv()) } fun validate(validade : Validation) : Boolean { val hashes = mutableListOf<String>() val csvLeitura = File("dados.csv") csvLeitura.forEachLine { linha -> val colunas = linha.split(",") if (colunas.size >= 2) { hashes.add(colunas[3].trim()) } } val senhaHash = getHash(validade.senha) println(senhaHash) return senhaHash in hashes } }
0
Kotlin
0
0
f00b8c8d548f6f36eadcfebed5ebcc62429c618a
829
mikoshi
Apache License 2.0
app/src/main/java/com/bulletapps/candypricer/domain/usecase/product/DeleteProductUseCase.kt
jvsena42
485,055,339
false
{"Kotlin": 265086}
package com.bulletapps.candypricer.domain.usecase.product import com.bulletapps.candypricer.data.repository.CandyPricerRepository import javax.inject.Inject class DeleteProductUseCase @Inject constructor( private val repository: CandyPricerRepository ) { // TODO VALIDATE NEGATIVE VALUE suspend operator fun invoke(supplyId: Int) = repository.deleteProduct(supplyId) }
18
Kotlin
0
2
c89da3d248d32f976ad7f0d918815822787ae33a
382
baking_calculator
MIT License
PhoneClient/app/src/main/java/ru/niatomi/phoneclient/Entrypoint.kt
Niatomi
705,881,258
false
{"Kotlin": 14000, "C": 1499, "C++": 1217, "Makefile": 95}
package ru.niatomi.phoneclient import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.currentRecomposeScope import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import com.hoho.android.usbserial.driver.UsbSerialPort import kotlinx.coroutines.delay import ru.niatomi.phoneclient.components.DevBar import ru.niatomi.phoneclient.screens.Oscilloscope import ru.niatomi.phoneclient.utils.FrameParser import ru.niatomi.phoneclient.utils.RingBuffer import java.time.Instant @RequiresApi(Build.VERSION_CODES.O) @Composable fun Entrypoint( port: UsbSerialPort, ) { val recentInstantTimeTake = remember { mutableStateOf(Instant.now()) } val rf = remember { mutableStateOf(RingBuffer<Pair<Instant, Double>>(bufferSize = 30)) } val currentFrame = remember { mutableStateOf(ByteArray(size = 8)) } LaunchedEffect(key1 = currentFrame) { while (true) { delay(20) val buffer = ByteArray(size = 8) port.read(buffer, 1); Log.d("SERIAL", buffer.contentToString()) Log.d("SERIAL-PARSE", FrameParser.parse(buffer).toString()) var value = FrameParser.parse(buffer) if (value == 0.0) { recentInstantTimeTake.value = Instant.now() val clone = rf.value.clone() clone.add(Pair(recentInstantTimeTake.value, FrameParser.parse(currentFrame.value))) rf.value = clone } else { currentFrame.value = buffer recentInstantTimeTake.value = Instant.now() val clone = rf.value.clone() clone.add(Pair(recentInstantTimeTake.value, FrameParser.parse(buffer))) rf.value = clone } } } Column { Oscilloscope(ringBuffer = rf) DevBar( instantTime = recentInstantTimeTake, byteFrame = currentFrame ) } }
0
Kotlin
0
0
69e31dd7e50aa3789daab2dba9f4e17f8aded122
2,228
portable-phone-osciloscope
Apache License 2.0
core/src/main/kotlin/io/zeebe/bpmnspec/verifications/ElementInstanceStateVerification.kt
strogo
359,518,634
true
{"Kotlin": 73169, "Shell": 987}
package io.zeebe.bpmnspec.verifications import io.zeebe.bpmnspec.api.Verification import io.zeebe.bpmnspec.api.VerificationResult import io.zeebe.bpmnspec.api.WorkflowInstanceContext import io.zeebe.bpmnspec.api.runner.ElementInstanceState import io.zeebe.bpmnspec.api.runner.TestRunner class ElementInstanceStateVerification( val state: ElementInstanceState, val elementId: String?, val elementName: String?, val workflowInstance: String? ) : Verification { override fun verify(runner: TestRunner, contexts: Map<String, WorkflowInstanceContext>): VerificationResult { val context = workflowInstance?.let { contexts[workflowInstance] } ?: contexts.values.first() val actualState = runner.getElementInstances(context) .filter { elementInstance -> elementId?.let { it == elementInstance.elementId } ?: true } .filter { elementInstance -> elementName?.let { it == elementInstance.elementName } ?: true } .firstOrNull() ?.state val wfAlias = workflowInstance?.let { "of the workflow instance '$it'" } ?: "" val element = elementId?.let { "with id '$it'" } ?: elementName?.let { "with name '$it'" } ?: "" return actualState?.let { if (it == state) { VerificationResult(isFulfilled = true) } else { VerificationResult( isFulfilled = false, failureMessage = "Expected the element $element $wfAlias to be in state '$state' but was '$actualState'." ) } } ?: VerificationResult( isFulfilled = false, failureMessage = "Expected the element $element $wfAlias to be in state '$state' but no element instance found." ) } }
0
null
0
0
b86b23d5abb7951b9f8eeaf2ce7a48a4c2627c96
2,039
bpmn-spec
Apache License 2.0
demo/src/main/java/nl/joery/demo/animatedbottombar/MainActivity.kt
rushabh13
245,955,972
true
{"Kotlin": 48258}
package nl.joery.demo.animatedbottombar import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import nl.joery.animatedbottombar.AnimatedBottomBar class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val bottomBars = arrayOf(bottom_bar, bottom_bar2, bottom_bar3, bottom_bar4) bottom_bar.setOnTabSelectListener(object : AnimatedBottomBar.OnTabSelectListener { override fun onTabSelected( lastIndex: Int, lastTab: AnimatedBottomBar.Tab?, newIndex: Int, newTab: AnimatedBottomBar.Tab ) { Log.d("TAB_SELECTED", "Selected index: $newIndex, title: ${newTab.title}") } }) select.setOnClickListener { for (bottomBar in bottomBars) { bottomBar.addTabAt( 0, bottom_bar.createTab(R.drawable.alarm, R.string.app_name) ) } } deselect.setOnClickListener { for (bottomBar in bottomBars) { if (bottomBar.tabCount > 0) { val tab = bottomBar.tabs.last() bottomBar.removeTab(tab) } } } select_first.setOnClickListener { for (bottomBar in bottomBars) { bottomBar.selectTabAt(0) } } select_last.setOnClickListener { for (bottomBar in bottomBars) { bottomBar.selectTabAt(bottom_bar.tabCount - 1) } } } }
0
null
2
5
7043ba5a14a873d2389df95e042b5d96f9c6bd25
1,803
AnimatedBottomBar
MIT License
retroravelry/src/test/java/com/caseykulm/retroravelry/MockClient.kt
caseykulm
106,941,886
false
null
package com.caseykulm.retroravelry import com.caseykulm.retroravelry.auth.AuthenticationHeaderProvider import com.caseykulm.retroravelry.auth.OAuth2Authenticator import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.logging.HttpLoggingInterceptor import okhttp3.mockwebserver.MockWebServer val MOCK_USER_NAME = "rumpletestuser" val MOCK_ACCESS_TOKEN = "mockAccessToken" val MOCK_ACCESS_TOKEN_SECRET = "mockAccessTokenSecret" val MOCK_CONSUMER_KEY = "mockConsumerKey" val MOCK_CONSUMER_SECRET = "mockConsumerSecret" val MOCK_CALLBACK_URL = "https://example.com/oauth" class MockClient { var server: MockWebServer = MockWebServer() val ravelryClient: RavelryClient by lazy { RavelryClient(oAuth2Authenticator, okhttpClient, server.url("/")) } private val okhttpClient by lazy { val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY OkHttpClient.Builder() .addInterceptor(logging) .build() } private val authenticationHeaderProvider: AuthenticationHeaderProvider by lazy { object : AuthenticationHeaderProvider { override fun getAuthorizationHeaderValue(request: Request): String { return "Bearer $MOCK_ACCESS_TOKEN" } } } private val oAuth2Authenticator: OAuth2Authenticator by lazy { object : OAuth2Authenticator { override val authHeaderProvider: AuthenticationHeaderProvider get() = authenticationHeaderProvider override fun isExpired(): Boolean { return false } override fun refresh(): Boolean { return true } override fun onRefreshFailed() { /* no-op */ } } } }
1
Kotlin
0
2
177f20c4a84bd0a6f7a4da2ac7b942fd01699e06
1,818
retroravelry
Apache License 2.0
lcc-content/src/main/kotlin/com/joshmanisdabomb/lcc/block/entity/ClassicChestBlockEntity.kt
joshmanisdabomb
537,458,013
false
{"Kotlin": 2724329, "Java": 138822}
package com.joshmanisdabomb.lcc.block.entity import com.joshmanisdabomb.lcc.directory.LCCBlockEntities import com.joshmanisdabomb.lcc.directory.LCCBlocks import com.joshmanisdabomb.lcc.extensions.NBT_STRING import com.joshmanisdabomb.lcc.lib.inventory.LCCInventory import net.minecraft.block.BlockState import net.minecraft.block.entity.BlockEntity import net.minecraft.block.enums.ChestType import net.minecraft.entity.player.PlayerEntity import net.minecraft.entity.player.PlayerInventory import net.minecraft.inventory.DoubleInventory import net.minecraft.inventory.Inventories import net.minecraft.inventory.SidedInventory import net.minecraft.item.ItemStack import net.minecraft.nbt.NbtCompound import net.minecraft.screen.GenericContainerScreenHandler import net.minecraft.screen.NamedScreenHandlerFactory import net.minecraft.state.property.Properties.CHEST_TYPE import net.minecraft.text.Text import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Direction class ClassicChestBlockEntity(pos: BlockPos, state: BlockState) : BlockEntity(LCCBlockEntities.classic_chest, pos, state), NamedScreenHandlerFactory, SidedInventory { val other: ClassicChestBlockEntity? get() { if (cachedState[CHEST_TYPE] != ChestType.SINGLE) { return world?.getBlockEntity(pos.offset(LCCBlocks.classic_chest.getDirectionToAttached(cachedState))) as? ClassicChestBlockEntity } else { return null } } val double get() = other != null val inventory = LCCInventory(27).apply { addListener { this@ClassicChestBlockEntity.markDirty() } } val otherInventory get() = other?.inventory val leftInventory get() = when (cachedState[CHEST_TYPE]) { ChestType.LEFT -> otherInventory else -> inventory } val rightInventory get() = when (cachedState[CHEST_TYPE]) { ChestType.LEFT -> inventory else -> otherInventory } val doubleInventory get() = DoubleInventory(leftInventory, rightInventory) var customName: Text? = null val otherName get() = other?.customName val doubleName get() = when (cachedState[CHEST_TYPE]) { ChestType.LEFT -> otherName ?: customName else -> customName ?: otherName } override fun createMenu(syncId: Int, inv: PlayerInventory, player: PlayerEntity): GenericContainerScreenHandler? { if (double) { return GenericContainerScreenHandler.createGeneric9x6(syncId, inv, doubleInventory) } return GenericContainerScreenHandler.createGeneric9x3(syncId, inv, inventory) } override fun getDisplayName(): Text { if (double) { return doubleName ?: Text.translatable("container.chest") } return customName ?: Text.translatable("container.chest") } override fun readNbt(tag: NbtCompound) { super.readNbt(tag) if (tag.contains("CustomName", NBT_STRING)) customName = Text.Serializer.fromJson(tag.getString("CustomName")) inventory.apply { clear(); Inventories.readNbt(tag, list) } } override fun writeNbt(tag: NbtCompound) { super.writeNbt(tag) if (customName != null) tag.putString("CustomName", Text.Serializer.toJson(customName)) Inventories.writeNbt(tag, inventory.list) } override fun clear() = if (double) doubleInventory.clear() else inventory.clear() override fun size() = if (double) doubleInventory.size() else inventory.size() override fun isEmpty() = if (double) doubleInventory.isEmpty else inventory.isEmpty override fun getStack(slot: Int) = if (double) doubleInventory.getStack(slot) else inventory.getStack(slot) override fun removeStack(slot: Int, amount: Int) = if (double) doubleInventory.removeStack(slot, amount) else inventory.removeStack(slot, amount) override fun removeStack(slot: Int) = if (double) doubleInventory.removeStack(slot) else inventory.removeStack(slot) override fun setStack(slot: Int, stack: ItemStack) = if (double) doubleInventory.setStack(slot, stack) else inventory.setStack(slot, stack) override fun canPlayerUse(player: PlayerEntity) = if (double) doubleInventory.canPlayerUse(player) else inventory.canPlayerUse(player) override fun getAvailableSlots(side: Direction) = (0 until size()).toList().toIntArray() override fun canInsert(slot: Int, stack: ItemStack, dir: Direction?) = true override fun canExtract(slot: Int, stack: ItemStack, dir: Direction) = true }
0
Kotlin
0
0
a836162eaf64a75ca97daffa02c1f9e66bdde1b4
4,468
loosely-connected-concepts
Creative Commons Zero v1.0 Universal
thelema-kx/src/commonMain/kotlin/org/ksdfv/thelema/fs/FS.kt
cybernetics
365,452,918
true
{"Kotlin": 3356187, "C": 552354, "Java": 355550, "HTML": 6211, "Makefile": 260}
/* * Copyright 2020 Anton Trushkov * * 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.ksdfv.thelema.fs import org.ksdfv.thelema.kx.ThreadLocal /** File system abstraction layer. It is singleton and you can use it anywhere after initialization. * If you want multiple APIs, you may switch between them by setting. * By default used JVM file system implementation. * @author zeganstyl */ @ThreadLocal object FS: IFileSystem { const val ReadAccessFlag = 1 const val WriteAccessFlag = 2 lateinit var proxy: IFileSystem override val externalStoragePath: String get() = proxy.externalStoragePath override val isExternalStorageAvailable: Boolean get() = proxy.isExternalStorageAvailable override val localStoragePath: String get() = proxy.localStoragePath override val isLocalStorageAvailable: Boolean get() = proxy.isLocalStorageAvailable override fun file(path: String, location: Int): IFile = proxy.file(path, location) }
0
null
0
0
c274a903f0a4d17e5ef14773efa144ee8c8809dd
1,515
thelema-engine
Apache License 2.0
Android/app/src/test/java/uk/ac/lshtm/keppel/android/scanning/ScanActivityTest.kt
LSHTM-ORK
240,033,125
false
{"Kotlin": 93320, "Java": 4400, "Shell": 1742}
package uk.ac.lshtm.keppel.android.scanning import android.content.Context import android.content.Intent import androidx.test.core.app.ApplicationProvider import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.android.controller.ActivityController import org.robolectric.annotation.LooperMode import uk.ac.lshtm.keppel.android.External import uk.ac.lshtm.keppel.android.Keppel import uk.ac.lshtm.keppel.core.Scanner @RunWith(RobolectricTestRunner::class) @LooperMode(LooperMode.Mode.PAUSED) class ScanActivityTest { private val fakeScanner = mock<Scanner>() private lateinit var activity: ScanActivity private lateinit var activityController: ActivityController<ScanActivity> @Before fun setup() { ApplicationProvider.getApplicationContext<Keppel>() .setDependencies(availableScanners = listOf(FakeScannerFactory(fakeScanner))) ApplicationProvider.getApplicationContext<Keppel>().configureDefaultScanner(override = true) activityController = Robolectric.buildActivity( ScanActivity::class.java, Intent().also { it.action = External.ACTION_SCAN } ) activity = activityController.setup().get() } @Test fun pausing_stopsCapture() { activityController.pause() verify(fakeScanner).stopCapture() } } class FakeScannerFactory(private val scanner: Scanner) : ScannerFactory { override val name: String = "Fake" override val isAvailable: Boolean = true override fun create(context: Context): Scanner = scanner }
4
Kotlin
2
7
d9e5f8bc99c068751004085351bd0a5ff8d8c49f
1,744
ODK_Biometrics
MIT License
kotest-examples/kotest-examples-jvm/src/jvmMain/kotlin/com/sksamuel/kotest/examples/jvm/ssn.kt
niraj8
268,596,932
true
{"Kotlin": 2246160, "HTML": 423, "Java": 145}
package com.sksamuel.kotest.examples.jvm val socialRegex = "^\\d{3}-\\d{3}-\\d{4}$".toRegex() fun validateSocial(ssn: String): Boolean = socialRegex.matches(ssn)
0
null
0
1
53daa30e3fb889935e8de419d233454dda2e385f
164
kotest
Apache License 2.0
vk-api-generated/src/main/kotlin/name/anton3/vkapi/generated/photos/methods/PhotosReportComment.kt
Anton3
159,801,334
true
{"Kotlin": 1382186}
@file:Suppress("unused", "MemberVisibilityCanBePrivate", "SpellCheckingInspection") package name.anton3.vkapi.generated.photos.methods import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import name.anton3.vkapi.generated.common.objects.ReportReason import name.anton3.vkapi.method.UserMethod import name.anton3.vkapi.method.VkMethod import name.anton3.vkapi.vktypes.OkResponse /** * [https://vk.com/dev/photos.reportComment] * * Reports (submits a complaint about) a comment on a photo. * * @property ownerId ID of the user or community that owns the photo. * @property commentId ID of the comment being reported. * @property reason Reason for the complaint: '0' - spam, '1' - child pornography, '2' - extremism, '3' - violence, '4' - drug propaganda, '5' - adult material, '6' - insult, abuse */ data class PhotosReportComment( var ownerId: Long, var commentId: Long, var reason: ReportReason? = null ) : VkMethod<OkResponse, UserMethod>("photos.reportComment", jacksonTypeRef())
2
Kotlin
0
8
773c89751c4382a42f556b6d3c247f83aabec625
1,011
kotlin-vk-api
MIT License
starter/slack-spring-boot/src/main/kotlin/io/hndrs/slack/broker/util/SlackApiTextResponseExt.kt
hndrs
168,710,332
false
null
package io.hndrs.slack.broker.util import com.slack.api.methods.SlackApiTextResponse fun <T : SlackApiTextResponse, R> T.on(onSuccess: (response: T) -> R, onFailure: (response: T) -> R): R { return if (this.isOk) { onSuccess(this) } else { onFailure(this) } }
56
Kotlin
13
17
1691baf43c8d842e087e684aa14597909e80d310
290
slack-spring-boot-starter
MIT License
audioengine/src/main/java/io/github/gaomjun/audioengine/AudioEngine.kt
GaoMjun
261,919,677
false
{"C++": 5298889, "Java": 1356277, "C": 826238, "Kotlin": 143998, "GLSL": 17726, "Objective-C": 7774, "CMake": 4632, "Makefile": 2264}
package io.github.gaomjun.audioengine import android.media.AudioFormat import android.media.AudioRecord import android.media.MediaRecorder import android.os.Handler import android.os.HandlerThread import io.github.gaomjun.live.aacEncoder.AACEncoder import io.github.gaomjun.live.encodeConfiguration.AudioConfiguration import java.nio.ByteOrder.LITTLE_ENDIAN import android.R.attr.order import android.os.Environment import java.io.BufferedOutputStream import java.io.File import java.io.FileOutputStream import java.io.RandomAccessFile import java.nio.ByteBuffer import java.nio.ByteOrder /** * Created by qq on 25/1/2017. */ class AudioEngine { private var audioRecord: AudioRecord? = null private var audioRecordThread: AudioRecordThread? = AudioRecordThread() private var bufferSizeInBytes: Int? = null private var audioData: ByteArray? = null private val aacEncoder = AACEncoder(AudioConfiguration.instance()) private var saveToFile = false private var bufferedOutputStream: BufferedOutputStream? = null init { initAudioRecord() } fun start() { audioRecord?.startRecording() if (audioRecord?.state == AudioRecord.STATE_INITIALIZED) { audioRecordThread?.start() } } fun stop() { if (saveToFile) { saveToFile = false bufferedOutputStream?.flush() bufferedOutputStream?.close() val f = File(Environment.getExternalStorageDirectory(), "Download/audio.wav") if (f.exists()) { val filePath = f.absolutePath val fileSize = f.length() prepareWAVSize(filePath, fileSize.toInt()) println("saveToFile") } } } private fun initAudioRecord() { val audioSource = MediaRecorder.AudioSource.DEFAULT val sampleRateInHz = 44100 val channelConfig = AudioFormat.CHANNEL_IN_MONO val audioFormat = AudioFormat.ENCODING_PCM_16BIT bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat) * 1 audioRecord = AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes!!) } private inner class AudioRecordThread : Thread() { override fun run() { super.run() while (!isInterrupted) { if (audioData == null) { audioData = ByteArray(bufferSizeInBytes!!) } val len = audioRecord?.read(audioData, 0, bufferSizeInBytes!!) if (len!! > 0) { // println("audioRecord $len") aacEncoder.encoding(audioData!!, System.currentTimeMillis()) audioDataCallback?.onAudioData(audioData!!, len) if (saveToFile) { if (bufferedOutputStream == null) { val f = File(Environment.getExternalStorageDirectory(), "Download/audio.wav") if (f.exists()) { f.delete() println("rm " + f.absolutePath) } bufferedOutputStream = BufferedOutputStream(FileOutputStream(f)) bufferedOutputStream?.write(wavHeader()) bufferedOutputStream?.write(audioData) } else { bufferedOutputStream?.write(audioData) } } } Thread.sleep(10) } } } interface AudioDataCallback { fun onAudioData(data: ByteArray, size: Int) } var audioDataCallback: AudioDataCallback? = null private fun wavHeader(): ByteArray { val byteBuffer = ByteBuffer.allocate(44) byteBuffer.order(ByteOrder.LITTLE_ENDIAN) byteBuffer.putInt(0x46464952) byteBuffer.putInt(0) byteBuffer.putInt(0x45564157) byteBuffer.putInt(0x20746d66) byteBuffer.putInt(16) byteBuffer.putShort(1.toShort()) byteBuffer.putShort(1.toShort()) byteBuffer.putInt(44100) byteBuffer.putInt(44100 * 1 * 2) byteBuffer.putShort((1 * 2).toShort()) byteBuffer.putShort(16.toShort()) byteBuffer.putInt(0x61746164) byteBuffer.putInt(0) return byteBuffer.array() } private fun prepareWAVSize(mFilePath: String, mFileSize: Int) { val ras = RandomAccessFile(mFilePath, "rw") ras.seek(4) val byteBuffer = ByteBuffer.allocate(4) byteBuffer.order(ByteOrder.LITTLE_ENDIAN) byteBuffer.putInt(mFileSize - 8) ras.write(byteBuffer.array()) byteBuffer.rewind() byteBuffer.putInt(mFileSize - 42) ras.seek(40) ras.write(byteBuffer.array()) } }
0
C++
3
6
70e6d8f075521fd14012ee9a0687f19046a97f19
4,939
Ringo-Android
MIT License
app/src/main/java/com/better/alarm/background/AlertService.kt
csshine
252,324,328
true
{"Kotlin": 216111, "Java": 195933}
package com.better.alarm.background import com.better.alarm.interfaces.IAlarmsManager import com.better.alarm.interfaces.Intents import com.better.alarm.logger.Logger import com.better.alarm.model.Alarmtone import com.better.alarm.wakelock.Wakelocks import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.functions.BiFunction import io.reactivex.subjects.BehaviorSubject interface AlertPlugin { fun go(alarm: PluginAlarmData, prealarm: Boolean, targetVolume: Observable<TargetVolume>): Disposable } data class PluginAlarmData(val id: Int, val alarmtone: Alarmtone, val label: String) enum class TargetVolume { MUTED, FADED_IN, FADED_IN_FAST } sealed class Event { data class NullEvent(val actions: String = "null") : Event() data class AlarmEvent(val id: Int, val actions: String = Intents.ALARM_ALERT_ACTION) : Event() data class PrealarmEvent(val id: Int, val actions: String = Intents.ALARM_PREALARM_ACTION) : Event() data class DismissEvent(val id: Int, val actions: String = Intents.ALARM_DISMISS_ACTION) : Event() data class SnoozedEvent(val id: Int, val actions: String = Intents.ALARM_SNOOZE_ACTION) : Event() data class CancelSnoozedEvent(val id: Int, val actions: String = Intents.ACTION_CANCEL_SNOOZE) : Event() data class Autosilenced(val id: Int, val actions: String = Intents.ACTION_SOUND_EXPIRED) : Event() data class MuteEvent(val actions: String = Intents.ACTION_MUTE) : Event() data class DemuteEvent(val actions: String = Intents.ACTION_DEMUTE) : Event() } /** * Listens to all kinds of events, vibrates, shows notifications and so on. */ class AlertService( private val log: Logger, private val wakelocks: Wakelocks, private val alarms: IAlarmsManager, private val inCall: Observable<Boolean>, private val plugins: Array<AlertPlugin>, private val handleUnwantedEvent: () -> Unit, private val stopSelf: () -> Unit ) { private val wantedVolume: BehaviorSubject<TargetVolume> = BehaviorSubject.createDefault(TargetVolume.MUTED) private enum class Type { NORMAL, PREALARM } private data class CallState(val initial: Boolean, val inCall: Boolean) private var soundAlarmDisposable: CompositeDisposable = CompositeDisposable() init { wakelocks.acquireServiceLock() } private var playingAlarm = false fun onStartCommand(event: Event) { log.d("[AlertService] onStartCommand $event") if (!playingAlarm) { when (event) { // we will start playing now is Event.AlarmEvent, is Event.PrealarmEvent -> { } else -> { log.w("[AlertService] not playingAlarm, ignore $event") handleUnwantedEvent() } } } when (event) { is Event.AlarmEvent -> soundAlarm(event.id, Type.NORMAL) is Event.PrealarmEvent -> soundAlarm(event.id, Type.PREALARM) is Event.MuteEvent -> wantedVolume.onNext(TargetVolume.MUTED) is Event.DemuteEvent -> wantedVolume.onNext(TargetVolume.FADED_IN_FAST) is Event.DismissEvent, is Event.SnoozedEvent, is Event.Autosilenced -> { if (playingAlarm) { log.d("[AlertService] Cleaning up after $event") playingAlarm = false wantedVolume.onNext(TargetVolume.MUTED) soundAlarmDisposable.dispose() wakelocks.releaseServiceLock() stopSelf() } } } } private fun soundAlarm(id: Int, type: Type) { // new alarm - dispose all current signals soundAlarmDisposable.dispose() playingAlarm = true wantedVolume.onNext(TargetVolume.FADED_IN) val targetVolumeAccountingForInCallState: Observable<TargetVolume> = Observable.combineLatest<TargetVolume, CallState, TargetVolume>( wantedVolume, inCall.zipWithIndex { callActive, index -> CallState(index == 0, callActive) }, BiFunction { volume, callState -> when { !callState.initial && callState.inCall -> TargetVolume.MUTED !callState.initial && !callState.inCall -> TargetVolume.FADED_IN_FAST else -> volume } }) val alarm = alarms.getAlarm(id) val alarmtone = alarm?.alarmtone ?: Alarmtone.Default() val label = alarm?.labelOrDefault ?: "" soundAlarmDisposable = CompositeDisposable( plugins.map { it.go(PluginAlarmData(id, alarmtone, label), prealarm = type == Type.PREALARM, targetVolume = targetVolumeAccountingForInCallState) } ) } private fun <U, D> Observable<U>.zipWithIndex(function: (U, Int) -> D): Observable<D> { return zipWith(generateSequence(0) { it + 1 }.asIterable()) { next, index -> function.invoke(next, index) } } }
0
null
0
0
3f0686d6e7e7ccc3d24c1433b4d3273bb1655cb1
5,143
AlarmClock
Apache License 2.0
app/src/main/java/com/stocksexchange/android/ui/views/MarkableImageView.kt
libertaria-project
183,030,087
true
{"Kotlin": 2210140}
package com.stocksexchange.android.ui.views import android.content.Context import android.graphics.* import androidx.annotation.ColorInt import android.util.AttributeSet import android.widget.ImageView import androidx.appcompat.widget.AppCompatImageView import com.stocksexchange.android.ui.utils.extensions.spToPx /** * A wrapper around [ImageView] with marking functionality. */ class MarkableImageView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : AppCompatImageView(context, attrs, defStyleAttr) { companion object { private const val DEFAULT_TEXT_SIZE = 18f private const val DEFAULT_TEXT_COLOR = Color.WHITE } private var mOuterBackgroundPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) private var mInnerBackgroundPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) private var mTextPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) private var mOuterBackgroundBounds: RectF = RectF() private var mInnerBackgroundBounds: RectF = RectF() private var mTextBounds: Rect = Rect() private var mViewSize: IntArray = IntArray(2) /** * A boolean flag indicating whether to draw backgrounds on this * image view or not. */ var shouldDrawBackground: Boolean = false set(value) { field = value invalidate() } /** * A type of shape to draw on this image view. */ var backgroundShape: Shape = Shape.RECTANGULARISH set(value) { field = value invalidate() } /** * A mark (letter) to draw on this image view. */ var mark: String = "" set(value) { field = value invalidate() } init { mTextPaint.typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL) mTextPaint.textSize = spToPx(DEFAULT_TEXT_SIZE) mTextPaint.color = DEFAULT_TEXT_COLOR mTextPaint.textAlign = Paint.Align.CENTER } /** * Sets a color of the outer background of this image view. * * @param color The color to set */ fun setOuterBackgroundColor(@ColorInt color: Int) { mOuterBackgroundPaint.color = color invalidate() } /** * Sets a color of the inner background of this image view. */ fun setInnerBackgroundColor(@ColorInt color: Int) { mInnerBackgroundPaint.color = color invalidate() } /** * Sets a text size of the text paint. * * @param textSize The text size to set (in pixels). */ fun setTextSize(textSize: Int) { mTextPaint.textSize = textSize.toFloat() invalidate() } /** * Gets the text size of the text paint. * * @return The text size (in pixels) */ fun getTextSize(): Int { return mTextPaint.textSize.toInt() } /** * Sets a text color of the text paint. * * @param textColor The text color to set */ fun setTextColor(@ColorInt textColor: Int) { mTextPaint.color = textColor invalidate() } /** * Gets the text color of the text paint. * * @return The text color */ fun getTextColor(): Int { return mTextPaint.color } /** * Checks whether this image is marked. * * @return true if marked; false otherwise */ fun isMarked(): Boolean { return mark.isNotBlank() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) mViewSize[0] = measuredWidth mViewSize[1] = measuredHeight mOuterBackgroundBounds.set( 0f, 0f, mViewSize[0].toFloat(), mViewSize[1].toFloat() ) mInnerBackgroundBounds.set( paddingLeft.toFloat(), paddingTop.toFloat(), (mViewSize[0] - paddingRight).toFloat(), (mViewSize[1] - paddingBottom).toFloat() ) } override fun onDraw(canvas: Canvas) { if(shouldDrawBackground) { if(backgroundShape == Shape.RECTANGULARISH) { canvas.drawRect(mOuterBackgroundBounds, mOuterBackgroundPaint) canvas.drawRect(mInnerBackgroundBounds, mInnerBackgroundPaint) } else if(backgroundShape == Shape.OVALISH) { canvas.drawOval(mOuterBackgroundBounds, mOuterBackgroundPaint) canvas.drawOval(mInnerBackgroundBounds, mInnerBackgroundPaint) } } super.onDraw(canvas) if(isMarked()) { mTextPaint.getTextBounds(mark, 0, mark.length, mTextBounds) canvas.drawText( mark, (mViewSize[0] / 2).toFloat(), ((mViewSize[1] + mTextBounds.height()) / 2).toFloat(), mTextPaint ) } } enum class Shape { RECTANGULARISH, OVALISH } }
0
Kotlin
0
0
35a7f9a61f52f68ab3267da24da3c1d77d84e9c3
5,049
Android-app
MIT License
components/external-messaging-services/src/test/kotlin/net/corda/external/messaging/services/ExternalMessagingRoutingServiceImplTest.kt
corda
346,070,752
false
{"Kotlin": 20585419, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.external.messaging.services import com.typesafe.config.ConfigFactory import net.corda.external.messaging.entities.VirtualNodeRouteKey import net.corda.external.messaging.services.impl.ExternalMessagingRoutingServiceImpl import net.corda.libs.configuration.SmartConfig import net.corda.libs.configuration.SmartConfigFactory import net.corda.libs.external.messaging.entities.InactiveResponseType import net.corda.libs.external.messaging.entities.Route import net.corda.messagebus.api.admin.Admin import net.corda.messagebus.api.admin.builder.AdminBuilder import net.corda.messagebus.api.configuration.AdminConfig import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.SoftAssertions.assertSoftly import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.whenever class ExternalMessagingRoutingServiceImplTest { private val route1 = Route("c1", "t1", true, InactiveResponseType.IGNORE) private val route2 = Route("c2", "t2", true, InactiveResponseType.IGNORE) private val route3 = Route("c3", "t3", true, InactiveResponseType.IGNORE) private val listenerCaptor = argumentCaptor<VirtualNodeRouteConfigInfoListener>() private val listenerRegistration = mock<AutoCloseable>() private val configurations = mapOf<String, SmartConfig>() private val messagingConfig = SmartConfigFactory.createWithoutSecurityServices().create(ConfigFactory.empty()) private val busAdmin1 = mock<Admin>() private val busAdmin2 = mock<Admin>() private val adminBuilder = mock<AdminBuilder>() private val virtualNodeRouteConfigInfoService = mock<VirtualNodeRouteConfigInfoService>().apply { whenever(this.registerCallback(listenerCaptor.capture())).thenReturn(listenerRegistration) } // Validate we are passing the configurations to the helper function private val toMessagingConfig: (Map<String, SmartConfig>) -> SmartConfig = { configs -> assertThat(configs).isEqualTo(configurations) messagingConfig } private val target = ExternalMessagingRoutingServiceImpl( adminBuilder, virtualNodeRouteConfigInfoService, toMessagingConfig ) @BeforeEach fun setup() { // Bus Admin configuration and initialisation whenever(adminBuilder.createAdmin(AdminConfig("Messaging Routing Service"), messagingConfig)) .thenReturn(busAdmin1, busAdmin2) // Setup different topic specs for the two example buses whenever(busAdmin1.getTopics()).thenReturn(setOf("t1")) whenever(busAdmin2.getTopics()).thenReturn(setOf("t1", "t2", "t3")) } @Test fun `onConfigChange multiple calls, closes previous instance of bus admin`() { target.onConfigChange(configurations) verify(busAdmin1, never()).close() verify(busAdmin2, never()).close() target.onConfigChange(configurations) verify(busAdmin1).close() verify(busAdmin2, never()).close() } @Test fun `onConfigChange with not virtual node data does nothing`() { target.onConfigChange(configurations) } @Test fun `virtual change with no call to onConfigChange does nothing`() { listenerCaptor.firstValue.onUpdate(getExampleRoutes()) } @Test fun `get routes for configured routing service`() { target.onConfigChange(configurations) // using busAdmin1 so only topic t1 available listenerCaptor.firstValue.onUpdate(getExampleRoutes()) assertSoftly { var result = target.getRoute("h1", "c1") it.assertThat(result).isNotNull it.assertThat(result!!.route).isEqualTo(route1) it.assertThat(result.externalReceiveTopicNameExists).isEqualTo(true) result = target.getRoute("h1", "c2") it.assertThat(result).isNotNull it.assertThat(result!!.route).isEqualTo(route2) it.assertThat(result.externalReceiveTopicNameExists).isEqualTo(false) result = target.getRoute("h2", "c3") it.assertThat(result).isNotNull it.assertThat(result!!.route).isEqualTo(route3) it.assertThat(result.externalReceiveTopicNameExists).isEqualTo(false) } } @Test fun `get routes for configured routing service after config change`() { listenerCaptor.firstValue.onUpdate(getExampleRoutes()) target.onConfigChange(configurations) target.onConfigChange(configurations) // using busAdmin2 so all topics available assertSoftly { var result = target.getRoute("h1", "c1") it.assertThat(result).isNotNull it.assertThat(result!!.route).isEqualTo(route1) it.assertThat(result.externalReceiveTopicNameExists).isEqualTo(true) result = target.getRoute("h1", "c2") it.assertThat(result).isNotNull it.assertThat(result!!.route).isEqualTo(route2) it.assertThat(result.externalReceiveTopicNameExists).isEqualTo(true) result = target.getRoute("h2", "c3") it.assertThat(result).isNotNull it.assertThat(result!!.route).isEqualTo(route3) it.assertThat(result.externalReceiveTopicNameExists).isEqualTo(true) } } @Test fun `get route for missing topic queries the message bus`() { target.onConfigChange(configurations) // using busAdmin1 so only topic t1 available listenerCaptor.firstValue.onUpdate(getExampleRoutes()) var result = target.getRoute("h2", "c3") assertThat(result).isNotNull assertThat(result!!.route).isEqualTo(route3) assertThat(result.externalReceiveTopicNameExists).isEqualTo(false) whenever(busAdmin1.getTopics()).thenReturn(setOf("t3")) result = target.getRoute("h2", "c3") assertThat(result).isNotNull assertThat(result!!.route).isEqualTo(route3) assertThat(result.externalReceiveTopicNameExists).isEqualTo(true) } @Test fun `get routes that don't exist returns null`() { target.onConfigChange(configurations) listenerCaptor.firstValue.onUpdate(getExampleRoutes()) assertSoftly { var result = target.getRoute("h1", "cX") assertThat(result).isNull() result = target.getRoute("hX", "c1") assertThat(result).isNull() } } private fun getExampleRoutes(): Map<VirtualNodeRouteKey, Route> { return mapOf( VirtualNodeRouteKey("h1", "c1") to route1, VirtualNodeRouteKey("h1", "c2") to route2, VirtualNodeRouteKey("h2", "c3") to route3, ) } }
11
Kotlin
27
69
d478e119ab288af663910f9a2df42a7a7b9f5bce
6,843
corda-runtime-os
Apache License 2.0
model/src/main/java/com/gentalhacode/github/model/Response.kt
thgMatajs
239,887,486
false
null
package com.gentalhacode.github.model /** * .:.:.:. Created by @thgMatajs on 11/02/20 .:.:.:. */ interface Response { val totalRepositories: Int val repositories: List<Repository> }
0
Kotlin
0
5
f3e8465cdbc92c9375f32c20085afdeac69dd04d
192
GitHubSearch
The Unlicense
inputs/core/src/commonMain/kotlin/symphony/Serializable.kt
aSoft-Ltd
632,021,007
false
null
package symphony import kotlinx.serialization.KSerializer interface Serializable<T> { val serializer: KSerializer<T> }
0
Kotlin
0
0
53ebc57b18457ef0417812a21d4b73caa10c10f0
124
symphony
MIT License
archive/533/solve.kt
daniellionel01
435,306,139
false
null
/* === #533 Minimum values of the Carmichael function - Project Euler === The Carmichael function λ(n) is defined as the smallest positive integer m such that am = 1 modulo n for all integers a coprime with n. For example λ(8) = 2 and λ(240) = 4. Define L(n) as the smallest positive integer m such that λ(k) ≥ n for all k ≥ m. For example, L(6) = 241 and L(100) = 20 174 525 281. Find L(20 000 000). Give the last 9 digits of your answer. Difficulty rating: 50% */ fun solve(x: Int): Int { return x*2; } fun main() { val a = solve(10); println("solution: $a"); }
0
Kotlin
0
1
1ad6a549a0a420ac04906cfa86d99d8c612056f6
573
euler
MIT License
app/src/main/java/com/koleff/kare_android/ui/state/WorkoutDetailsListState.kt
MartinKoleff
741,013,199
false
{"Kotlin": 655085}
package com.koleff.kare_android.ui.state import com.koleff.kare_android.data.model.dto.ExerciseDetailsDto import com.koleff.kare_android.data.model.dto.WorkoutDetailsDto import com.koleff.kare_android.data.model.response.base_response.KareError data class WorkoutDetailsListState ( val workoutDetailsList: List<WorkoutDetailsDto> = emptyList(), val isSuccessful: Boolean = false, val isLoading: Boolean = false, val isError: Boolean = false, val error : KareError = KareError.GENERIC )
15
Kotlin
0
4
e31db6fb293ae0b00fd9c4526b1f8d5c2be64b67
507
KareFitnessApp
MIT License
app/src/main/java/com/loan/golden/cash/money/loan/app/util/CacheUtil.kt
williamXw
693,063,899
false
{"Java": 2423785, "Kotlin": 747998}
package com.loan.golden.cash.money.loan.app.util import android.text.TextUtils import com.google.gson.Gson import com.loan.golden.cash.money.loan.data.response.LoginResponse import com.tencent.mmkv.MMKV object CacheUtil { /** * 获取保存的账户信息 */ fun getUser(): LoginResponse? { val kv = MMKV.mmkvWithID("app") val userStr = kv.decodeString("user") return if (TextUtils.isEmpty(userStr)) { null } else { Gson().fromJson(userStr, LoginResponse::class.java) } } /** * 设置账户信息 */ fun setUser(userResponse: LoginResponse?) { val kv = MMKV.mmkvWithID("app") if (userResponse == null) { kv.encode("user", "") setIsLogin(false) } else { kv.encode("user", Gson().toJson(userResponse)) setIsLogin(true) } } /** * 是否已经登录 */ fun isLogin(): Boolean { val kv = MMKV.mmkvWithID("app") return kv.decodeBool("login", false) } /** * 设置是否已经登录 */ fun setIsLogin(isLogin: Boolean) { val kv = MMKV.mmkvWithID("app") kv.encode("login", isLogin) } }
1
null
1
1
2ba6be236ce6de634dda7d02f78d87b4a6f9c7f6
1,189
goldenMoney
Apache License 2.0
common/sdk/settings/api/external/src/commonMain/kotlin/io/chefbook/sdk/settings/api/external/domain/usecases/SetCommunityRecipesLanguagesUseCase.kt
mephistolie
379,951,682
false
{"Kotlin": 1334117, "Ruby": 16819, "Swift": 352}
package io.chefbook.sdk.settings.api.external.domain.usecases import io.chefbook.libs.models.language.Language interface SetCommunityRecipesLanguagesUseCase { suspend operator fun invoke(languages: List<Language>) }
0
Kotlin
0
12
ddaf82ee3142f30aee8920d226a8f07873cdcffe
220
chefbook-mobile
Apache License 2.0
examples/kotless/shortener/src/main/kotlin/io/kotless/examples/page/Shortener.kt
JetBrains
192,359,205
false
null
package io.kotless.examples.page import io.kotless.dsl.lang.http.* import io.kotless.dsl.model.HttpResponse import io.kotless.examples.storage.URLStorage import org.apache.commons.validator.routines.UrlValidator import org.slf4j.LoggerFactory @Get("/r") fun redirectUrl(k: String): HttpResponse { val url = URLStorage.getByCode(k) return if (url == null) { notFound("Unknown short URL") } else { redirect(url) } } private val logger = LoggerFactory.getLogger("ShortenerKt") @Get("/shorten") fun shorten(value: String): String { logger.info("URL for shortening $value") val url = if (value.contains("://").not()) "https://$value" else value if (UrlValidator.getInstance().isValid(url).not()) { return "Non valid URL" } val code = URLStorage.getByUrl(url) ?: URLStorage.createCode(url) return "https://short.kotless.io${::redirectUrl.href(code)}" }
51
Kotlin
56
975
596c77f41410409207647dfd195e34f4562728ed
920
kotless
Apache License 2.0
poko-compiler-plugin/src/main/kotlin/dev/drewhamilton/poko/ir/PokoIrGenerationExtension.kt
drewhamilton
243,601,035
false
null
package dev.drewhamilton.poko.ir import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageUtil import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.name.FqName internal class PokoIrGenerationExtension( private val pokoAnnotationName: FqName, private val messageCollector: MessageCollector ) : IrGenerationExtension { override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) { val pokoAnnotationClass = pluginContext.referenceClass(pokoAnnotationName) if (pokoAnnotationClass == null) { moduleFragment.reportError("Could not find class <$pokoAnnotationName>") return } val pokoMembersTransformer = PokoMembersTransformer(pokoAnnotationClass, pluginContext, messageCollector) moduleFragment.transform(pokoMembersTransformer, null) } private fun IrModuleFragment.reportError(message: String) { val psi = descriptor.findPsi() val location = MessageUtil.psiElementToMessageLocation(psi) messageCollector.report(CompilerMessageSeverity.ERROR, message, location) } }
6
Kotlin
3
99
3d433f1851085076efc88ce8e9cfcbce8d8ba841
1,484
Poko
Apache License 2.0
app/src/main/java/com/nyinyihtunlwin/prj_getgo/search/Car.kt
nyinyihtunlwin-codigo
368,795,690
false
{"Kotlin": 13808}
package com.nyinyihtunlwin.prj_getgo.search class Car { }
0
Kotlin
0
0
11f1d203ca128b54444b7f5f5333fc485c4e622d
58
prj-getgo
Apache License 2.0
app/src/main/java/com/udacity/shoestore/models/Shoe.kt
PaoloCaldera
607,771,342
false
{"Kotlin": 17867}
package com.udacity.shoestore.models import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class Shoe(var name: String, var size: Double, var company: String, var description: String, val images: List<String> = mutableListOf()) : Parcelable
0
Kotlin
0
0
3db9315d032e0e3d5977d5c747d7bbebe78bcb10
338
shoeStore
MIT License
day7/src/main/kotlin/BagRuleParser.kt
ascheja
317,918,055
false
null
package net.sinceat.aoc2020.day7 class BagRuleParser(private val rules: Map<String, List<Pair<Int, String>>>) { fun unpackShinyGoldBags(): Sequence<String> { return unpackBag("shiny gold") } private fun unpackBag(toUnpack: String): Sequence<String> = sequence { rules[toUnpack]?.forEach { (count, content) -> repeat(count) { yield(content) yieldAll(unpackBag(content)) } } } fun findShinyGoldBags(): Sequence<String> { return findBags("shiny gold") } private fun findBags(toFind: String): Sequence<String> = sequence { rules.filter { (_, contents) -> toFind in contents.map(Pair<Int, String>::second) }.forEach { (container, _) -> yield(container) yieldAll(findBags(container)) } } companion object { private val bagRuleRegex = Regex("(?<target>.*) bags contain (?<contents>.*)") private val contentRegex = Regex("(?<count>\\d+) (?<bag>\\w+ \\w+) bag[s]?[.]?") fun parse(file: String): BagRuleParser { val result = ClassLoader.getSystemResourceAsStream(file)!!.bufferedReader().use { reader -> reader.lineSequence().mapNotNull(bagRuleRegex::find).map { matchResult -> val (target, contentsString) = matchResult.destructured val contents = when (contentsString) { "no other bags." -> emptyList() else -> contentsString.split(", ").mapNotNull(contentRegex::find).map { contentMatch -> contentMatch.groupValues[1].toInt() to contentMatch.groupValues[2] } } target to contents }.toMap() } return BagRuleParser(result) } } }
0
Kotlin
0
0
f115063875d4d79da32cbdd44ff688f9b418d25e
1,893
aoc2020
MIT License
Java_part/AssignmentD/src/Q2.kt
enihsyou
58,862,788
false
null
import java.util.* class MazeGenerator(private val x: Int, private val y: Int) { private val maze = Array(x) { IntArray(y) } fun generate(cx: Int, cy: Int) { Direction.values().shuffle().forEach { val nx = cx + it.dx val ny = cy + it.dy if (between(nx, x) && between(ny, y) && maze[nx][ny] == 0) { // 未填充 maze[cx][cy] = maze[cx][cy] or it.bit maze[nx][ny] = maze[nx][ny] or it.opposite.bit generate(nx, ny) } } } fun display() { for (i in 0 until y) { // 上面的线 (0 until x) .joinToString("+", "+", "+") { if (maze[it][i] and 1 == 0) "---" else " " }.also { println(it) } // 左右的线 (0 until x) .joinToString("", postfix = "|") { if (maze[it][i] and 8 == 0) "| " else " " }.also { println(it) } } // 画底边框 println((0..x).joinToString("---") { "+" }) } fun search(startX: Int, startY: Int, goalX: Int, goalY: Int): Boolean { fun display2(visited: Queue<Pair<Int, Int>>) { fun has(i: Int, j: Int): String = if (Pair(i, j) in visited) "×" else " " for (i in 0 until y) { // 上面的线 (0 until x) .joinToString("+", "+", "+") { if (maze[it][i] and 1 == 0) "---" else " " }.also { println(it) } // 左右的线 (0 until x) .joinToString("", postfix = "|") { if (maze[it][i] and 8 == 0) "| ${has(it, i)} " else " ${has(it, i)} " }.also { println(it) } } // 画底边框 println((0..x).joinToString("---") { "+" }) } val visited: Deque<Pair<Int, Int>> = LinkedList<Pair<Int, Int>>() fun search_(startX: Int, startY: Int, goalX: Int, goalY: Int, comeFrom: Direction?): Boolean { visited += Pair(startX, startY) println() println("访问:${Pair(startX, startY)}") display2(visited) /*抵达目标 退出*/ if (startX == goalX && startY == goalY) { println("抵达目标:${Pair(startX, startY)}") return true } Direction.values() /*过滤掉来的方向,防止搜索走回头路*/ .filterNot { it == comeFrom?.opposite } /*过滤出有效的前进方向*/ .filter { maze[startX][startY] and it.bit == it.bit } .forEach { val nx = startX + it.dx val ny = startY + it.dy if (search_(nx, ny, goalX, goalY, it)) return true else { visited.pollLast() println() println("退回:${Pair(startX, startY)}") display2(visited) } } return false } println("从${Pair(startX, startY)}开始寻找目标${Pair(goalX, goalY)}") return search_(startX, startY, goalX, goalY, null) } inline private fun <reified T> Array<T>.shuffle(): Array<T> { val list = toMutableList() Collections.shuffle(list) return list.toTypedArray() } private enum class Direction(val bit: Int, val dx: Int, val dy: Int) { N(1, 0, -1), S(2, 0, 1), E(4, 1, 0), W(8, -1, 0); lateinit var opposite: Direction companion object { init { N.opposite = S S.opposite = N E.opposite = W W.opposite = E } } } private fun between(v: Int, upper: Int) = v in 0 until upper } fun main(args: Array<String>) { var x = 8 var y = 8 if (args.size == 2) { x = args[0].toInt() y = args[1].toInt() } else { val s = Scanner(System.`in`) with(s) { println("输入迷宫的长和宽") x = nextInt() y = nextInt() } } with(MazeGenerator(x, y)) { generate(0, 0) display() search(0, 0, x - 1, y - 1) } }
1
null
1
1
09a109bb26e0d8d165a4d1bbe18ec7b4e538b364
4,222
Sorting-algorithm
MIT License
core/src/test/kotlin/org/tty/dioc/core/test/services/circle/HelloServiceToPrintImpl.kt
h1542462994
374,315,892
false
null
package org.tty.dioc.core.test.services.circle import org.tty.dioc.annotation.Inject import org.tty.dioc.annotation.Component @Component class HelloServiceToPrintImpl: HelloServiceToPrint { @Inject lateinit var printService: PrintService override fun hello(): String { return "hello" } override fun print(): String { return printService.print() } }
0
Kotlin
0
1
f24ce47a59936ee21a7d705ef19b5c2e17208868
392
dioc
MIT License
shared/src/commonMain/kotlin/com/mbta/tid/mbta_app/repositories/TripRepository.kt
mbta
718,216,969
false
{"Kotlin": 1077869, "Swift": 529057, "Ruby": 4666, "Shell": 4134}
package com.mbta.tid.mbta_app.repositories import com.mbta.tid.mbta_app.json import com.mbta.tid.mbta_app.model.TripShape import com.mbta.tid.mbta_app.model.response.ApiResult import com.mbta.tid.mbta_app.model.response.ErrorDetails import com.mbta.tid.mbta_app.model.response.TripResponse import com.mbta.tid.mbta_app.model.response.TripSchedulesResponse import com.mbta.tid.mbta_app.network.MobileBackendClient import io.ktor.client.call.body import io.ktor.client.plugins.HttpRequestTimeoutException import io.ktor.client.plugins.ResponseException import io.ktor.client.request.parameter import io.ktor.http.HttpStatusCode import io.ktor.http.path import io.ktor.serialization.JsonConvertException import io.ktor.utils.io.errors.IOException import kotlinx.coroutines.suspendCancellableCoroutine import org.koin.core.component.KoinComponent import org.koin.core.component.inject interface ITripRepository { @Throws( IOException::class, kotlin.coroutines.cancellation.CancellationException::class, JsonConvertException::class, ResponseException::class, HttpRequestTimeoutException::class ) suspend fun getTripSchedules(tripId: String): TripSchedulesResponse suspend fun getTrip(tripId: String): ApiResult<TripResponse> suspend fun getTripShape(tripId: String): ApiResult<TripShape> } class TripRepository : ITripRepository, KoinComponent { private val mobileBackendClient: MobileBackendClient by inject() override suspend fun getTripSchedules(tripId: String): TripSchedulesResponse = mobileBackendClient .get { url { path("api/schedules") parameter("trip_id", tripId) } } .body() override suspend fun getTrip(tripId: String): ApiResult<TripResponse> { try { val response = mobileBackendClient.get { url { path("api/trip") parameter("trip_id", tripId) } } if (response.status === HttpStatusCode.OK) { return ApiResult.Ok(data = json.decodeFromString(response.body())) } else { return ApiResult.Error(json.decodeFromString<ErrorDetails>(response.body())) } } catch (e: Exception) { return ApiResult.Error(ErrorDetails(message = e.message ?: e.toString())) } } override suspend fun getTripShape(tripId: String): ApiResult<TripShape> { try { val response = mobileBackendClient.get { url { path("api/trip/map") parameter("trip_id", tripId) } } if (response.status === HttpStatusCode.OK) { return ApiResult.Ok(data = json.decodeFromString(response.body())) } else { return ApiResult.Error(json.decodeFromString<ErrorDetails>(response.body())) } } catch (e: Exception) { return ApiResult.Error(ErrorDetails(message = e.message ?: e.toString())) } } } open class IdleTripRepository : ITripRepository { override suspend fun getTripSchedules(tripId: String): TripSchedulesResponse { return suspendCancellableCoroutine {} } override suspend fun getTrip(tripId: String): ApiResult<TripResponse> { return suspendCancellableCoroutine {} } override suspend fun getTripShape(tripId: String): ApiResult<TripShape> { return suspendCancellableCoroutine {} } }
10
Kotlin
0
0
d9d9e2129e532125f2d46b37bc3b9eba44517728
3,675
mobile_app
MIT License
app/src/main/java/ir/roohi/farshid/reminderpro/repository/LocationRepository.kt
FarshidRoohi
156,371,913
false
null
package ir.roohi.farshid.reminderpro.repository import android.content.Context import androidx.lifecycle.LiveData import ir.roohi.farshid.reminderpro.database.AppDatabase import ir.roohi.farshid.reminderpro.model.LocationEntity import java.util.concurrent.Executors /** * Created by <NAME>. * ReminderPro | Copyrights 1/4/19. */ class LocationRepository constructor(context: Context) { private var database: AppDatabase? = null var locationList: LiveData<List<LocationEntity>>? = null private val executors = Executors.newSingleThreadExecutor() init { database = AppDatabase.getInstance(context) this.locationList = getLocations() } companion object { private var repository: LocationRepository? = null fun instance(context: Context): LocationRepository { if (repository == null) { repository = LocationRepository(context) } return repository!! } } fun getLocations(): LiveData<List<LocationEntity>> { return database!!.locationDao().all } fun add(item: LocationEntity) { executors.execute { database!!.locationDao().insert(item) } } fun remove(item: LocationEntity) { executors.execute { database!!.locationDao().delete(item) } } fun update(item: LocationEntity) { executors.execute { database!!.locationDao().update(item) } } }
9
Kotlin
8
32
ca8057f117442ae1ff292179723d0f779efbde7a
1,490
ReminderPro
Apache License 2.0
app/src/main/java/pl/sienczykm/templbn/ui/list/weather/WeatherListViewModel.kt
mat-sienczyk
193,071,707
false
null
package pl.sienczykm.templbn.ui.list.weather import android.app.Application import pl.sienczykm.templbn.db.AppDb import pl.sienczykm.templbn.db.model.BaseStationModel import pl.sienczykm.templbn.db.model.WeatherStationModel import pl.sienczykm.templbn.ui.list.common.BaseStationListViewModel import pl.sienczykm.templbn.utils.UpdateHandler class WeatherListViewModel(application: Application) : BaseStationListViewModel<WeatherStationModel>(application) { override fun refresh() { UpdateHandler.syncNowWeatherStations(getApplication(), receiver) } override val stationsLiveData = AppDb.getDatabase(getApplication()).weatherStationDao().getAllStationsLiveData() init { stations.addSource(stationsLiveData) { result: List<WeatherStationModel>? -> result?.let { stations.value = sortStations(it) if (!isRefreshedOnInit) refreshIfNeeded(it) } } } override fun refreshIfNeeded(stations: List<WeatherStationModel>) { if (WeatherStationModel.getAllStations().minus(stations).isNotEmpty()) refresh() else { stations.filter { it.isDateObsoleteOrNull() } .let { stationsToUpdate -> UpdateHandler.syncNowWeatherStations( getApplication(), receiver, stationsToUpdate ) } } isRefreshedOnInit = true } override suspend fun updateFavourite(station: BaseStationModel): Int = AppDb.getDatabase(getApplication()).weatherStationDao().updateFavoriteSuspend( station.stationId, !station.favorite ) }
0
Kotlin
1
2
9c87e40d685d62a4e523708428c2f8ec44494948
1,725
LubelskieStacjePogodowe
Apache License 2.0
app/src/main/java/com/yveschiong/macrofit/activities/AddNutritionFactActivity.kt
yveschiong
135,364,946
false
{"Kotlin": 130902}
package com.yveschiong.macrofit.activities import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.design.widget.TextInputLayout import android.widget.ArrayAdapter import com.yveschiong.macrofit.App import com.yveschiong.macrofit.R import com.yveschiong.macrofit.constants.Constants import com.yveschiong.macrofit.constants.ResponseCode import com.yveschiong.macrofit.contracts.AddNutritionFactViewContract import com.yveschiong.macrofit.models.NutritionFact import com.yveschiong.macrofit.models.Weight import kotlinx.android.synthetic.main.activity_add_nutrition_fact.* import javax.inject.Inject class AddNutritionFactActivity : BaseActivity(), AddNutritionFactViewContract.View { @Inject lateinit var presenter: AddNutritionFactViewContract.Presenter<AddNutritionFactViewContract.View> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_nutrition_fact) App.graph.inject(this) presenter.onAttach(this) val adapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Weight.UNITS) // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) // Apply the adapter to the spinner unitsSpinner.adapter = adapter add_button.setOnClickListener { _ -> val nameText = name.text.toString() val weightText = weight.text.toString() val unitText = unitsSpinner.selectedItem.toString() val caloriesText = calories.text.toString() val proteinText = protein.text.toString() val carbText = carb.text.toString() val fatText = fat.text.toString() // We want to validate all the fields at once so we can show // all the error messages at once val isWeightValid = presenter.validateWeight(weightText) val isCaloriesValid = presenter.validateCalories(caloriesText) val isProteinValid = presenter.validateProtein(proteinText) val isCarbValid = presenter.validateCarb(carbText) val isFatValid = presenter.validateFat(fatText) // We need to validate for the food name's uniqueness presenter.validateFoodName(nameText) { if (isWeightValid && isCaloriesValid && isProteinValid && isCarbValid && isFatValid) { // Validated the fields so we can create a nutrition fact val result = Intent() result.putExtra(Constants.RESULT_KEY, NutritionFact(nameText, weightText.toFloat(), unitText, caloriesText.toFloat(), proteinText.toFloat(), carbText.toFloat(), fatText.toFloat())) setResult(Activity.RESULT_OK, result) finish() } } } } override fun onDestroy() { presenter.onDetach() super.onDestroy() } private fun tryShowError(layout: TextInputLayout, code: Int) { when (code) { ResponseCode.FIELD_IS_REQUIRED -> { layout.error = getString(R.string.field_required_error_text) } ResponseCode.FIELD_IS_INVALID -> { layout.error = getString(R.string.field_invalid_error_text) } ResponseCode.FIELD_VALUE_ALREADY_EXISTS -> { layout.error = getString(R.string.field_value_already_exists_error_text) } ResponseCode.OK -> { layout.error = null } } } override fun tryShowFoodNameErrorMessage(code: Int) { tryShowError(nameLayout, code) } override fun tryShowWeightErrorMessage(code: Int) { tryShowError(weightLayout, code) } override fun tryShowCaloriesErrorMessage(code: Int) { tryShowError(caloriesLayout, code) } override fun tryShowProteinErrorMessage(code: Int) { tryShowError(proteinLayout, code) } override fun tryShowCarbErrorMessage(code: Int) { tryShowError(carbLayout, code) } override fun tryShowFatErrorMessage(code: Int) { tryShowError(fatLayout, code) } }
0
Kotlin
0
0
57a923fe85f7a69d3da87d4835cd453522f3d009
4,385
macro-fit
MIT License
app/src/main/java/com/example/bitfit_pt1/Navigation.kt
irania0201
555,544,995
false
null
package com.example.bitfit_pt1 import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.launch import kotlin.math.max import kotlin.math.min class Navigation : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_navigation, container, false) val avgText: TextView = view.findViewById(R.id.avgText) val minText: TextView = view.findViewById(R.id.minText) val maxText: TextView = view.findViewById(R.id.maxText) val entryList: MutableList<DisplayEntry> = listOf<DisplayEntry>().toMutableList() var total = 0.0 var count = 0.0 var min = 0 var max = 0 lifecycleScope.launch { (activity?.application as Application).db.entryDao().getAllByDateDesc().collect { databaseList -> databaseList.map { entity -> DisplayEntry( entity.id, entity.title, entity.date, entity.entry ) }.also { mappedList -> entryList.clear() entryList.addAll(mappedList) } if(entryList.size > 0) { val words = entryList[0].entry?.split(" ") if (words != null) { min = words.size max = words.size } } entryList.forEach { displayDiary: DisplayEntry -> count++ val words = displayDiary.entry?.split(" ") if(words != null) { total += words.size min = min(min, words.size) max = max(max, words.size) } } ("Average words per entry: " + (total/count).toInt()).also { avgText.text = it } ("Minimum words per entry: $min").also { minText.text = it } ("Maximum words per entry: $max").also { maxText.text = it } } } return view } companion object { fun newInstance(): Navigation{ return Navigation() } } }
2
Kotlin
0
0
2505fc6e1ec385375670db9b6c6bccbb6ef65c6c
2,614
BitFitPt2
Apache License 2.0
teamcity-vsix-gallery-server/src/main/teamcity/vsix/index/VsixMetadataProvider.kt
hhariri
34,997,181
true
{"Kotlin": 15178, "Java": 8061, "JavaScript": 2032, "CSS": 244}
package teamcity.vsix.index import com.google.common.collect.Lists import com.intellij.openapi.diagnostic.Logger import jetbrains.buildServer.log.Loggers import jetbrains.buildServer.serverSide.SBuild import jetbrains.buildServer.serverSide.artifacts.BuildArtifact import jetbrains.buildServer.serverSide.artifacts.BuildArtifacts import jetbrains.buildServer.serverSide.artifacts.BuildArtifactsViewMode import jetbrains.buildServer.serverSide.dependency.Dependency import jetbrains.buildServer.serverSide.impl.LogUtil import jetbrains.buildServer.serverSide.metadata.BuildMetadataProvider import jetbrains.buildServer.serverSide.metadata.MetadataStorageWriter import jetbrains.buildServer.util.StringUtil import org.joda.time.DateTime import org.joda.time.DateTimeZone import java.util.* import jetbrains.buildServer.serverSide.artifacts.BuildArtifacts.BuildArtifactsProcessor.Continuation.* import teamcity.vsix.feed.VSIX_EXTENSION import teamcity.vsix.feed.VSIX_PROVIDER_ID class VsixMetadataProvider() : BuildMetadataProvider { val log = Logger.getInstance("teamcity.vsix"); init { log.info("Metadata provider initialized.") } override fun getProviderId(): String = VSIX_PROVIDER_ID override fun generateMedatadata(build: SBuild, store: MetadataStorageWriter) { log.info("Looking for VSIX packages in " + LogUtil.describe(build)) val packages = ArrayList<BuildArtifact>() visitArtifacts(build.getArtifacts(BuildArtifactsViewMode.VIEW_ALL).getRootArtifact(), packages) // todo: consider enabling all arficats, maybe an option // build.getArtifacts(BuildArtifactsViewMode.VIEW_ALL).iterateArtifacts({ artifact -> // LOG.info("Processing artifact: " + artifact) // visitArtifacts(artifact, packages) // CONTINUE // }) for (aPackage in packages) { log.info("Indexing VSIX package from artifact " + aPackage.getRelativePath() + " of build " + LogUtil.describe(build)) try { val metadata = generateMetadataForPackage(build, aPackage) //myReset.resetCache() store.addParameters(metadata.get("Id"), metadata) } catch(ex: Exception) { log.warn("An error occurred during generating VSIX metadata: " + ex.toString()) } } } val TEAMCITY_ARTIFACT_RELPATH: String = "teamcity.artifactPath" val TEAMCITY_BUILD_TYPE_ID: String = "teamcity.buildTypeId" public fun generateMetadataForPackage(build: SBuild, aPackage: BuildArtifact): Map<String, String> { val analyzer = VsixPackageStructureAnalyser(DateTime(build.getFinishDate(), DateTimeZone.UTC)) val visitor = VsixPackageStructureVisitor(Arrays.asList(analyzer)) visitor.visit(aPackage) val metadata = analyzer.getItems() metadata.put(TEAMCITY_ARTIFACT_RELPATH, aPackage.getRelativePath()) metadata.put(TEAMCITY_BUILD_TYPE_ID, build.getBuildTypeId()) log.debug("Metadata: " + metadata) return metadata } // todo make this a lambda expression (Kotlin surely supports those!) fun visitArtifacts(artifact: BuildArtifact, packages: MutableList<BuildArtifact>) { if (!artifact.isDirectory()) { val name = artifact.getName().toLowerCase() if (name.endsWith(VSIX_EXTENSION)) packages.add(artifact) } for (children in artifact.getChildren()) { visitArtifacts(children, packages) } } }
0
Kotlin
0
0
2e92cac2fe231138246e36951c0948530f1f1af9
3,545
teamcity-vsix-gallery
MIT License
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/combat/strategy/ranged/weapon/Bows.kt
2011Scape
578,880,245
false
{"Kotlin": 8359518, "Dockerfile": 1354}
package gg.rsmod.plugins.content.combat.strategy.ranged.weapon import gg.rsmod.plugins.api.cfg.Items /** * @author Tom <<EMAIL>> */ object Bows { val CRYSTAL_BOWS = arrayOf( Items.NEW_CRYSTAL_BOW, Items.CRYSTAL_BOW_FULL, Items.CRYSTAL_BOW_110, Items.CRYSTAL_BOW_210, Items.CRYSTAL_BOW_310, Items.CRYSTAL_BOW_410, Items.CRYSTAL_BOW_510, Items.CRYSTAL_BOW_610, Items.CRYSTAL_BOW_710, Items.CRYSTAL_BOW_810, Items.CRYSTAL_BOW_910) val LONG_BOWS = arrayOf( Items.LONGBOW, Items.OAK_LONGBOW, Items.MAPLE_LONGBOW, Items.WILLOW_LONGBOW, Items.YEW_LONGBOW, Items.MAGIC_LONGBOW, Items.DARK_BOW) }
36
Kotlin
14
32
da66bb6d68ebae531ee325b909a6536e798b1144
757
game
Apache License 2.0
NativeMobileCaseStudy/app/src/main/java/com/example/nativemobilecasestudy/presentation/screens/cart_screen/components/CartProductCard.kt
ekineskin
849,029,080
false
{"Kotlin": 63538}
package com.example.nativemobilecasestudy.presentation.screens.cart_screen.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.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.filled.Delete import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import com.example.nativemobilecasestudy.data.local.CartEntity import com.example.nativemobilecasestudy.presentation.ui.theme.lightGrayColor import com.example.nativemobilecasestudy.presentation.ui.theme.orangeColor @Composable fun CartProductCard( product: CartEntity, onQuantityChange: (Int) -> Unit, onRemove: () -> Unit ) { Card( modifier = Modifier .fillMaxWidth() .padding(8.dp), shape = RoundedCornerShape(8.dp), colors = CardDefaults.cardColors(containerColor = lightGrayColor) ) { Box( modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Row { AsyncImage( model = product.image, contentDescription = product.name, modifier = Modifier .size(120.dp) .clip(RoundedCornerShape(8.dp)), contentScale = ContentScale.Crop ) Spacer(modifier = Modifier.width(16.dp)) Column( modifier = Modifier .fillMaxHeight() .padding(end = 40.dp) ) { Text(text = product.name, fontWeight = FontWeight.Bold) Spacer(modifier = Modifier.height(4.dp)) Text(text = "Price: ${product.price}") Spacer(modifier = Modifier.height(8.dp)) QuantitySelector( quantity = product.quantity, onQuantityChange = { quantity -> if (quantity > 0) onQuantityChange(quantity) } ) } } IconButton( onClick = onRemove, modifier = Modifier .align(Alignment.TopEnd) ) { Icon(imageVector = Icons.Default.Delete, contentDescription = "Remove from cart", tint = orangeColor) } } } }
0
Kotlin
0
0
0ebd59e58dd1d00bfd41154a709a121f14f019d9
3,389
NativeMobileCaseStudy
MIT License
app/web3proxy/src/main/kotlin/io/hamal/app/web3proxy/arbitrum/repository/Block.kt
hamal-io
622,870,037
false
{"Kotlin": 3316689, "C": 1401511, "TypeScript": 450023, "Lua": 193995, "C++": 40651, "Makefile": 11728, "Java": 7564, "JavaScript": 5832, "SCSS": 5191, "CMake": 2838, "CSS": 1626, "HTML": 1245, "Shell": 993}
package io.hamal.app.web3proxy.arbitrum.repository import io.hamal.lib.common.compress.BzipCompressor import io.hamal.lib.common.hot.HotObjectModule import io.hamal.lib.common.serialization.JsonFactoryBuilder import io.hamal.lib.domain.Json import io.hamal.lib.domain.vo.ValueObjectJsonModule import io.hamal.lib.sqlite.Connection import io.hamal.lib.sqlite.SqliteBaseRepository import io.hamal.lib.web3.evm.EvmHotModule import io.hamal.lib.web3.evm.abi.type.EvmAddress import io.hamal.lib.web3.evm.abi.type.EvmUint64 import io.hamal.lib.web3.evm.chain.arbitrum.domain.ArbitrumBlockData import io.hamal.lib.web3.evm.chain.arbitrum.domain.ArbitrumGetBlockResponse import io.hamal.lib.web3.evm.chain.arbitrum.http.ArbitrumBatchService import java.nio.file.Path internal interface ArbitrumBlockRepository { fun list(blockNumbers: List<EvmUint64>): List<BlockEntity?> fun clear() } internal class ArbitrumBlockRepositoryImpl( path: Path, private val batchService: ArbitrumBatchService<*>, private val addressRepository: ArbitrumAddressRepository, private val indexRepository: ArbitrumIndexRepository ) : SqliteBaseRepository( path = path, filename = "block.db" ), ArbitrumBlockRepository { override fun list(blockNumbers: List<EvmUint64>): List<BlockEntity?> { val foundBlocks = blockNumbers.mapNotNull { number -> findBlock(number) } val foundBlockNumbers = foundBlocks.map { it.number }.toSet() val blockNumbersToDownload = blockNumbers.filterNot { it in foundBlockNumbers } if (blockNumbersToDownload.isEmpty()) { return foundBlocks } log.info("Download blocks [${blockNumbersToDownload.map { it.toPrefixedHexString() }.joinToString(" ")}]") blockNumbersToDownload.forEach(batchService::getBlock) val blocks = batchService .execute() .filterIsInstance<ArbitrumGetBlockResponse>() .mapNotNull { it.result } val addresses = addressRepository.resolve(collectArbitrumAddresses(blocks)) val entities = blocks.map { it.toEntity(addresses) }.also { insertBlocks(it) } val result = entities.plus(foundBlocks).associateBy { it.number } return blockNumbers.map { number -> result[number] } } private fun findBlock(blockNumber: EvmUint64): BlockEntity? { return connection.tx { executeQueryOne("SELECT data FROM block WHERE number = :number") { query { set("number", blockNumber.value) } map { rs -> json.decompressAndDeserialize(BlockEntity::class, rs.getBytes("data")) } } } } private fun insertBlocks(blocks: List<BlockEntity>) { connection.tx { blocks.forEach { block -> execute("INSERT OR REPLACE INTO block(number, hash, data) VALUES( :number, :hash, :data )") { set("number", block.number.value) set("hash", block.hash.toPrefixedHexString().value) set("data", json.serializeAndCompress(block)) } } } blocks.forEach { block -> indexRepository.index(block) } } override fun setupConnection(connection: Connection) { connection.execute("""PRAGMA journal_mode = wal;""") connection.execute("""PRAGMA locking_mode = exclusive;""") connection.execute("""PRAGMA temp_store = memory;""") connection.execute("""PRAGMA synchronous = off;""") } override fun setupSchema(connection: Connection) { connection.execute( """ CREATE TABLE IF NOT EXISTS block ( number INTEGER PRIMARY KEY, hash VARCHAR(64) NOT NULL, data BLOB NOT NULL, UNIQUE (hash) ); """.trimIndent() ) } override fun clear() { connection.execute("DELETE FROM block") } private val json = Json( factory = JsonFactoryBuilder() .register(EvmHotModule) .register(HotObjectModule) .register(ValueObjectJsonModule), compressor = BzipCompressor ) } private fun collectArbitrumAddresses(blocks: List<ArbitrumBlockData>): Set<EvmAddress> { return blocks.flatMap { block -> listOf(block.miner) .plus(block.transactions.flatMap { transaction -> listOfNotNull(transaction.from, transaction.to) }) }.toSet() } private fun ArbitrumBlockData.toEntity(addresses: Map<EvmAddress, ArbitrumAddressId>) = BlockEntity( baseFeePerGas = baseFeePerGas, extraData = extraData, gasLimit = gasLimit, gasUsed = gasUsed, hash = hash, l1BlockNumber = l1BlockNumber, logsBloom = logsBloom, miner = addresses[miner]!!, mixHash = mixHash, number = number, sendCount = sendCount, sendRoot = sendRoot, parentHash = parentHash, receiptsRoot = receiptsRoot, sha3Uncles = sha3Uncles, size = size, stateRoot = stateRoot, timestamp = timestamp, totalDifficulty = totalDifficulty, transactions = transactions.map { tx -> TransactionEntity( from = tx.from.let { addresses[it]!! }, gas = tx.gas, gasPrice = tx.gasPrice, hash = tx.hash, input = tx.input, nonce = tx.nonce, to = tx.to?.let { addresses[it] }, value = tx.value, type = tx.type, requestId = tx.requestId ) }, transactionsRoot = transactionsRoot, )
44
Kotlin
0
0
1c9b1ad3368823ad9c339b6a56532a602cef7c63
5,662
hamal
Creative Commons Zero v1.0 Universal
src/app/src/main/java/com/huawei/touchmenot/kotlin/main/common/PermissionManager.kt
huaweicodelabs
400,165,704
false
null
/** * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.huawei.touchmenot.kotlin.main.common import android.Manifest import android.app.Activity import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import java.util.* object PermissionManager { private const val REQUEST_CODE_ASK_PERMISSIONS = 1 private val PERMISSIONS_ARRAYS = arrayOf(Manifest.permission.CAMERA) // List of permissions to be applied for. private val permissionsList: MutableList<String> = ArrayList() /** * Check whether the current app has the necessary permissions (by default, the camera permission is required). * If not, apply for the permission. This method should be called in the onResume method of the main activity. * * @param activity Activity */ @JvmStatic fun onResume(activity: Activity?) { var isHasPermission = true for (permission in PERMISSIONS_ARRAYS) { if (ContextCompat.checkSelfPermission(activity!!, permission) != PackageManager.PERMISSION_GRANTED) { isHasPermission = false break } } if (!isHasPermission) { for (permission in PERMISSIONS_ARRAYS) { if (ContextCompat.checkSelfPermission(activity!!, permission) != PackageManager.PERMISSION_GRANTED) { permissionsList.add(permission) } } ActivityCompat.requestPermissions(activity!!, permissionsList.toTypedArray(), REQUEST_CODE_ASK_PERMISSIONS) } } /** * Check whether the current app has the required permissions. * This method will be called when [com.huawei.touchmenot.main.HomeActivity.onRequestPermissionsResult]. * * @param activity Activity. * @return Has permission or not. */ fun hasPermission(activity: Activity): Boolean { for (permission in PERMISSIONS_ARRAYS) { if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) { return false } } return true } }
1
null
1
1
46ff26e6627395e16f7bd5a6ba904e89f7e6ba34
2,790
TouchMeNot
Apache License 2.0
interpreter/src/main/kotlin/org/actorlang/interpreter/InterpreterImpl.kt
422404
371,440,848
false
null
package org.actorlang.interpreter import org.actorlang.actorsystem.ActorSystem import org.actorlang.actorsystem.ServerLikeState import org.actorlang.interpreter.eval.RootEvaluator import org.actorlang.interpreter.synchronization.InterpreterExitReason import org.actorlang.interpreter.synchronization.InterpreterSynchronization import org.actorlang.parser.ParserFactory import java.io.PrintStream import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock class InterpreterImpl( private val actorSystem: ActorSystem, stdout: PrintStream, private val parserFactory: ParserFactory, private val interpreterSynchronization: InterpreterSynchronization ) : Interpreter { private val context = Context.of(stdout) private val stateLock = ReentrantLock() private var state = ServerLikeState.CREATED override fun run(source: String, sourceName: String): InterpreterExitReason { // Parse and evaluate the code val parser = parserFactory.createParser() val rootNode = parser.parse(source, sourceName) RootEvaluator(context, actorSystem).evaluateRoot(rootNode) // Wait for an exit condition (normal or erroneous) interpreterSynchronization.waitForExitCondition() return interpreterSynchronization.exitReason!! } override fun start() { stateLock.withLock { if (state == ServerLikeState.CREATED) { state = ServerLikeState.STARTED actorSystem.start() } } } override fun shutdown(timeoutMillis: Long) { stateLock.withLock { if (state == ServerLikeState.STARTED) { state = ServerLikeState.STOPPED actorSystem.shutdown(timeoutMillis) } } } }
23
null
1
3
bccf9c554e2dc2ad9c946cf8f38cacdd7002b555
1,804
ActorLang
MIT License
app/src/main/java/com/example/contactconnect/Contactlist/contactinfo_activity.kt
uphargaur
654,267,647
false
null
package com.example.contactconnect.Contactlist import android.content.Context import android.icu.text.SimpleDateFormat import android.os.Bundle import android.util.Base64 import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.room.Room import com.example.contactconnect.History.AppDatabase import com.example.contactconnect.Message.SendMessage.Messagedata import com.example.contactconnect.Message.SendMessage.createTwilioApiService import com.example.contactconnect.R import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import retrofit2.Call import java.util.* class contactinfo_activity : AppCompatActivity() { val ACCOUNT_SID = "AC389ec42f42ee2e630c1d72ec9fe9990d" val AUTH_TOKEN = "25511ae88f290fd6421c3c2aaa37c833" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_contactinfo_fragment) val firstname:TextView = findViewById(R.id.textViewFirstName) val lastname :TextView= findViewById(R.id.textViewLastName) val Mobileno :TextView= findViewById(R.id.textViewMobileNumber) val messagesend :EditText=findViewById(R.id.message1) val sendbutton:Button=findViewById(R.id.sendbutton) //reterving all the text from bundle val firstnametext: String = intent.getStringExtra("firstName").toString() val lastnametext: String = intent.getStringExtra("lastname").toString() val Mobilenotext: String = intent.getStringExtra("mobileNumber").toString() val otp:String=generateOTP() //setting up text to ui firstname.text=firstnametext lastname.text=lastnametext Mobileno.text=Mobilenotext //setting up other stuff val messagestring ="Hi ${intent.getStringExtra("firstName")} ! \n Your OTP is:- $otp \n For your Mobile No $Mobilenotext" messagesend.setText(messagestring) println("checking in otp activity $Mobilenotext $firstnametext") val savedMessage= Messagedata(phoneNumber=Mobilenotext ,message=messagestring,F_name=firstnametext,L_name=lastnametext,Otp=otp,timestamp= SimpleDateFormat("HH:mm dd.MM.yyyy").format(Date()) ) sendbutton.setOnClickListener() { sendSMS(Mobileno.toString(),messagestring,savedMessage) } } fun sendSMS(phoneNumber: String, message: String, Savedmessage :Messagedata) { val twilioService = createTwilioApiService() val accountSid = "AC389ec42f42ee2e630c1d72ec9fe9990d" val twilioPhoneNumber = "+14026966904" val call = twilioService.sendSMS(accountSid,"+917988204539",twilioPhoneNumber,message) call.enqueue(object : retrofit2.Callback<Void> { override fun onResponse(call: Call<Void>, response: retrofit2.Response<Void>) { if (response.isSuccessful) { println("SMS sent successfully!") // nowletssavethisintoadatabase Toast.makeText(this@contactinfo_activity,"Successfully sent otp",Toast.LENGTH_SHORT).show() val context = this@contactinfo_activity // Store the activity context in a variable GlobalScope.launch { val database = Room.databaseBuilder(context, AppDatabase::class.java, "app_database").build() database.sentMessageDao().insertSentMessage(Savedmessage) } finish() } else { println(phoneNumber) println("Failed to send SMS: ${response.code()}") } } override fun onFailure(call: Call<Void>, t: Throwable) { println("Failed to send SMS: ${t.message}") println(phoneNumber) } }) } private fun generateOTP(): String { // Generate a random 6-digit number for OTP val otp = (100000..999999).random() return otp.toString() } }
0
Kotlin
0
1
39ab833d685f55e6e62474a4381fc1f8c336b2e5
4,168
Contactapp
MIT License
solidblocks-test/src/test/kotlin/de/solidblocks/infra/test/snippets/CommandSnippets.kt
pellepelster
427,474,970
false
{"Kotlin": 327110, "Shell": 145200, "HCL": 94738, "Python": 9981, "Dockerfile": 7516, "HTML": 4972}
package de.solidblocks.infra.test.snippets import de.solidblocks.infra.test.SolidblocksTest import de.solidblocks.infra.test.SolidblocksTestContext import de.solidblocks.infra.test.command.runtimeShouldBeLessThan import de.solidblocks.infra.test.command.shouldHaveExitCode import de.solidblocks.infra.test.docker.DockerTestImage import de.solidblocks.infra.test.files.file import de.solidblocks.infra.test.output.outputShouldMatch import de.solidblocks.infra.test.output.stderrShouldBeEmpty import de.solidblocks.infra.test.output.stdoutShouldMatch import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(SolidblocksTest::class) public class CommandSnippets { @Test fun longRunningCommandSnippet(testContext: SolidblocksTestContext) { val longRunningCommand = """ #!/usr/bin/env bash set -eu -o pipefail sleep 2 echo "something has happened" sleep 2 echo "something else has happened" sleep 2 echo "everything worked" """ .trimIndent() val tempDir = testContext.createTempDir() val command = tempDir.file("long-running-script.sh").content(longRunningCommand).executable().create() val result = testContext .local() .command(command) .assert { it.waitForOutput(".*something has happened.*") } .assert { it.waitForOutput(".*something else has happened.*") } .runResult() result shouldHaveExitCode 0 result stdoutShouldMatch ".*everything worked.*" result.stderrShouldBeEmpty() result runtimeShouldBeLessThan 8.seconds } @Test fun respondToCommandSnippet(testContext: SolidblocksTestContext) { val respondToCommand = """ #!/usr/bin/env bash set -eu -o pipefail echo "please enter name" read echo "name was entered" """ .trimIndent() val tempDir = testContext.createTempDir() val command = tempDir.file("respond-to-command.sh").content(respondToCommand).executable().create() val result = testContext .local() .command(command) .assert { it.waitForOutput(".*please enter name.*") { "<NAME>" } } .assert { it.waitForOutput(".*name was entered.*") } .runResult() result shouldHaveExitCode 0 } @Test fun linearAssertionsSnippet(testContext: SolidblocksTestContext) { val longRunningCommand = """ #!/usr/bin/env bash set -eu -o pipefail sleep 2 echo "something has happened" sleep 2 echo "something else has happened" sleep 2 echo "everything worked" """ .trimIndent() val tempDir = testContext.createTempDir() val command = tempDir.file("long-running-script.sh").content(longRunningCommand).executable().create() runBlocking { val run = testContext.local().command(command).run() run.waitForOutput(".*something has happened.*") run.waitForOutput(".*something else has happened.*") val result = run.result() result shouldHaveExitCode 0 result stdoutShouldMatch ".*everything worked.*" result.stderrShouldBeEmpty() result runtimeShouldBeLessThan 8.seconds } } @Test fun localCommandSnippet(testContext: SolidblocksTestContext) { val currentUserName = System.getProperty("user.name") val result = testContext.local().command("whoami").runResult() result shouldHaveExitCode 0 result outputShouldMatch (".*$currentUserName.*") result.stderrShouldBeEmpty() } @Test fun dockerCommandSnippet(testContext: SolidblocksTestContext) { val result = testContext.docker(DockerTestImage.UBUNTU_22).command("whoami").runResult() result shouldHaveExitCode 0 result outputShouldMatch (".*root.*") result.stderrShouldBeEmpty() } @Test fun dockerCommandsSnippet(testContext: SolidblocksTestContext) { listOf( DockerTestImage.UBUNTU_20, DockerTestImage.UBUNTU_22, DockerTestImage.UBUNTU_24, DockerTestImage.DEBIAN_11, DockerTestImage.DEBIAN_11, DockerTestImage.DEBIAN_12, ) .forEach { val result = testContext.docker(it).command("whoami").runResult() result shouldHaveExitCode 0 result outputShouldMatch (".*root.*") result.stderrShouldBeEmpty() } } }
4
Kotlin
5
25
e63a6f13522e32ae2343fd75791f47e5777fd702
4,645
solidblocks
MIT License
src/main/kotlin/implementation/TagShort.kt
luizrcs
259,787,951
false
null
package io.github.mrpng.nbt.implementation import io.github.mrpng.nbt.* import io.github.mrpng.nbt.TagType.* import java.nio.* class TagShort private constructor(name: String? = null): Tag<Short>(TAG_SHORT, name) { override val sizeInBytes = Short.SIZE_BYTES constructor(value: Short, name: String? = null): this(name) { _value = value } constructor(byteBuffer: ByteBuffer, name: String? = null): this(name) { read(byteBuffer) } override fun read(byteBuffer: ByteBuffer) { _value = byteBuffer.short } override fun write(byteBuffer: ByteBuffer) { byteBuffer.putShort(_value) } override fun clone(name: String?) = TagShort(value, name) }
1
Kotlin
3
9
9f110ecf41bac6f9e9986ec5ff5c20157be5adfc
668
KotlinNBT
MIT License
cli_kt/app/src/main/kotlin/net/nanai10a/twomeat/cli/usecases/user/get/UserGetOutputData.kt
Nanai10a
330,746,827
false
null
package net.nanai10a.twomeat.cli.usecases.user.get import net.nanai10a.twomeat.cli.entities.User import net.nanai10a.twomeat.cli.usecases.SessionData data class UserGetOutputData(val sessionData: SessionData, val user: User?)
1
Kotlin
0
1
d28a4e3997958e703af79a8896655d96f06b043e
228
2Meat-4.5th
MIT License
app/src/main/java/pl/polciuta/qrscanner/utils/BitmapUtils.kt
nikt0r
311,046,064
false
null
package pl.polciuta.qrscanner.utils import android.content.Context import android.graphics.* import android.util.TypedValue import pl.polciuta.qrscanner.analyzer.RelativeCornerPoints import kotlin.math.max import kotlin.math.min object BitmapUtils { // forSize - if bitmap size differs from forSize, rescale corners and border accordingly fun getRoundedCornerBitmap(bitmap: Bitmap, color: Int, cornerSizePx: Int, borderSizePx: Int, forSize: Int): Bitmap { val scale = 1.0f * bitmap.height / forSize val corner = cornerSizePx * scale val border = borderSizePx * scale val output = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888) val canvas = Canvas(output) val paint = Paint() val rect = Rect(0, 0, bitmap.width, bitmap.height) val rectF = RectF(rect) // prepare canvas for transfer paint.isAntiAlias = true paint.color = -0x1 paint.style = Paint.Style.FILL canvas.drawARGB(0, 0, 0, 0) canvas.drawRoundRect(rectF, corner, corner, paint) // draw bitmap paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) canvas.drawBitmap(bitmap, rect, rect, paint) // draw border paint.color = color paint.alpha = 0x90 paint.style = Paint.Style.STROKE paint.strokeWidth = border canvas.drawRoundRect(rectF, corner, corner, paint) return output } // Return square or horizontal rectangle (w >= h) fun getBitmapSquareAtLeast(bitmap: Bitmap, cornerPoints: RelativeCornerPoints, padding: Int = 0): Bitmap? { return bitmap.let { // val it = stretchBitmap(cornerPoints, bitmap) var left = (1f * cornerPoints.xMin * it.width - padding).toInt() var right = (1f * cornerPoints.xMax * it.width + padding).toInt() var top = (1f * cornerPoints.yMin * it.height - padding).toInt() var bottom = (1f * cornerPoints.yMax * it.height + padding).toInt() val w = right - left val h = bottom - top when { // w > h -> { // top -= (w - h) / 2 // bottom += (w - h) / 2 // } h > w -> { left -= (h - w) / 2 right += (h - w) / 2 } } if (left < 0) { // right -= left // left is negative hence subtraction right = min(right - left, it.width) // left is negative hence subtraction left = 0 } if (right > it.width) { // left -= right - it.width left = max(0, left - (right - it.width)) right = it.width } if (top < 0) { // bottom -= top // top is negative hence subtraction bottom = min(bottom - top, it.height) // top is negative hence subtraction top = 0 } if (bottom > it.height) { // top -= bottom - it.height top = max(0, top - (bottom - it.height)) bottom = it.height } val width = right - left val height = bottom - top Bitmap.createBitmap(it, left, top, width, min(width, height)) // stretchBitmap(cornerPoints, Bitmap.createBitmap(it, left, top, width, min(width, height))) } } fun convertDpToPx(cornerDips: Float, context: Context): Float { return TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, cornerDips, context.resources.displayMetrics ) } }
0
Kotlin
0
0
dda9cf235db27ccc6474a308b39c13e1eb4ad838
3,725
QRScanner
MIT License
src/main/kotlin/icons/FlutterDevToolsIcons.kt
wanggaowan
599,862,484
false
{"Kotlin": 693357}
package icons import com.intellij.openapi.util.IconLoader import javax.swing.Icon /** * 图片ICON资源加载 * * @author Created by wanggaowan on 2022/5/1 21:44 */ object FlutterDevToolsIcons { // IconLoader.getIcon,只要在同一个路径下放置同名,后缀为_dark的图片,则自动在暗色主题时加载dart图片 // 比如:/icons/ic_search.svg /icons/ic_search_dark.svg /** * 搜索Icon */ @JvmField val search: Icon = IconLoader.getIcon("/icons/ic_search.svg", FlutterDevToolsIcons::class.java) /** * 图片预览方式为列表的Icon */ @JvmField val list: Icon = IconLoader.getIcon("/icons/ic_list.svg", FlutterDevToolsIcons::class.java) /** * 图片预览方式为网格的Icon */ @JvmField val grid: Icon = IconLoader.getIcon("/icons/ic_grid.svg", FlutterDevToolsIcons::class.java) /** * 刷新Icon */ @JvmField val refresh: Icon = IconLoader.getIcon("/icons/ic_refresh.svg", FlutterDevToolsIcons::class.java) /** * 关闭Icon */ @JvmField val close: Icon = IconLoader.getIcon("/icons/ic_close.svg", FlutterDevToolsIcons::class.java) /** * 关闭获取到焦点时的Icon */ @JvmField val closeFocus: Icon = IconLoader.getIcon("/icons/ic_close_focus.svg", FlutterDevToolsIcons::class.java) @JvmField val add: Icon = IconLoader.getIcon("/icons/add.svg", FlutterDevToolsIcons::class.java) @JvmField val delete: Icon = IconLoader.getIcon("/icons/delete.svg", FlutterDevToolsIcons::class.java) @JvmField val arbFile: Icon = IconLoader.getIcon("/icons/arb_file.svg", FlutterDevToolsIcons::class.java) @JvmField val fileTemplate: Icon = IconLoader.getIcon("/icons/file_template.svg", FlutterIcons::class.java) }
0
Kotlin
0
0
fd49bb62d901b289644475ccee66df2ae549492b
1,665
FlutterDevTools
Apache License 2.0
core-media/src/main/java/com/thoughtworks/ark/media/video/player/VideoPlayer.kt
TW-Smart-CoE
548,729,881
false
null
@file:Suppress("TooManyFunctions") package com.thoughtworks.ark.media.video.player interface VideoPlayer { fun addListener(videoPlayerListener: VideoPlayerListener) fun removeListener(videoPlayerListener: VideoPlayerListener) fun play(videoDataSource: VideoDataSource) fun replay() fun pause() fun resume() fun stop() fun volumeOff() fun volumeOn() fun release() fun getPlayState(): Int fun isPlaying(): Boolean }
16
Kotlin
2
16
35d0c4fe5e9ffc1c0cbd6318e46a2ad6f34f4e63
474
ARK-Android
Apache License 2.0
src/main/java/com/impact/addon/gt/api/multis/ISwitchRecipeMap.kt
GT-IMPACT
272,411,733
false
{"Java": 2070057, "Kotlin": 191017}
package com.impact.addon.gt.api.multis import gregtech.api.util.GT_Recipe.GT_Recipe_Map import net.minecraft.entity.player.EntityPlayer interface ISwitchRecipeMap { fun getRecipesMap(): List<GT_Recipe_Map> fun onChangeRecipeMap(map: GT_Recipe_Map, player: EntityPlayer) fun hasSwitchMap(): Boolean fun getMapName(): String }
0
Java
4
3
1320d520b6a96e18d609fd8ac3520b2a3f1f2f0c
342
Impact-Core
MIT License
app/src/main/kotlin/net/ketc/numeri/presentation/view/activity/MainActivity.kt
KetcKtsD
75,272,615
false
null
package net.ketc.numeri.presentation.view.activity import android.content.Context import android.content.Intent import android.content.res.Configuration import android.graphics.drawable.Drawable import android.os.Bundle import android.support.design.widget.BottomSheetDialog import android.support.design.widget.NavigationView import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.view.* import net.ketc.numeri.R import net.ketc.numeri.domain.entity.TweetsDisplayGroup import net.ketc.numeri.domain.model.TwitterUser import net.ketc.numeri.presentation.presenter.activity.MainPresenter import net.ketc.numeri.presentation.view.activity.ui.IMainActivityUI import net.ketc.numeri.presentation.view.activity.ui.MainActivityUI import net.ketc.numeri.presentation.view.component.ui.AccountViewUI import net.ketc.numeri.presentation.view.component.ui.menu.createIconMenu import net.ketc.numeri.presentation.view.component.ui.dialog.BottomSheetDialogUI import net.ketc.numeri.presentation.view.component.ui.dialog.addMenu import net.ketc.numeri.presentation.view.component.ui.dialog.messageText import net.ketc.numeri.presentation.view.fragment.TimeLinesFragment import net.ketc.numeri.util.android.* import net.ketc.numeri.util.log.v import net.ketc.numeri.util.rx.AutoDisposable import net.ketc.numeri.util.toImmutableList import org.jetbrains.anko.* import java.util.* class MainActivity : ApplicationActivity<MainPresenter>(), NavigationView.OnNavigationItemSelectedListener, MainActivityInterface, IMainActivityUI by MainActivityUI() { override val ctx: Context get() = this override val presenter: MainPresenter = MainPresenter(this) private val drawerToggle: ActionBarDrawerToggle by lazy { ActionBarDrawerToggle(this, drawer, 0, 0) } override var showingGroupId = -1 private set private val accountItemViewHolderList = ArrayList<AccountItemViewHolder>() private val groups = ArrayList<TweetsDisplayGroup>() private val dialogOwner = DialogOwner() override var addAccountButtonEnabled: Boolean get() = addAccountButton.isEnabled set(value) { addAccountButton.isEnabled = value } override val accounts: List<TwitterUser> get() = mAccounts.toImmutableList() private val mAccounts = ArrayList<TwitterUser>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(this) initialize() restoreGroupViews(savedInstanceState) presenter.initialize(savedInstanceState) } private fun initialize() { setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) drawer.addDrawerListener(drawerToggle) drawerToggle.isDrawerIndicatorEnabled = true navigation.setNavigationItemSelectedListener(this) showAccountRelative.setOnClickListener { toggleNavigationState() } tweetButton.setOnClickListener { TweetActivity.start(this) } addAccountButton.setOnClickListener { presenter.newAuthenticate() } } private fun restoreGroupViews(savedInstanceState: Bundle?) { savedInstanceState?.let { (it.getSerializable(EXTRA_GROUP) as Array<*>).forEach { (it as? TweetsDisplayGroup)?.let { addGroup(it) } ?: throw IllegalStateException("EXTRA_GROUP contains non TweetsDisplayGroup") } val id = it.getInt(EXTRA_CURRENT_SHOW_GROUP_ID, -1) if (groups.isEmpty()) return id.takeIf { it != -1 }?.let { val group = groups.firstOrNull { it.id == id } ?: return showGroup(group) } ?: showGroup(groups.first()) } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) val oauthIntent = intent.getParcelableExtra<Intent>(INTENT_OAUTH) ?: return presenter.onNewIntent(oauthIntent) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (drawerToggle.onOptionsItemSelected(item)) return true return super.onOptionsItemSelected(item) } override fun onNavigationItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.column_manage -> TweetsDisplayGroupManageActivity.start(this) R.id.changing_column_group -> showChangeColumnGroupDialog() else -> return super.onOptionsItemSelected(item) } drawer.closeDrawer(navigation) return true } override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { when (keyCode) { KeyEvent.KEYCODE_BACK -> { if (drawer.isDrawerOpen(navigation)) { drawer.closeDrawer(navigation) } else { moveTaskToBack(true) } } else -> return super.onKeyDown(keyCode, event) } return true } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) drawerToggle.syncState() } override fun onConfigurationChanged(newConfig: Configuration?) { super.onConfigurationChanged(newConfig) drawerToggle.onConfigurationChanged(newConfig) } override fun onPause() { super.onPause() dialogOwner.onPause() } override fun onSaveInstanceState(outState: Bundle) { outState.putSerializable(EXTRA_GROUP, groups.toTypedArray()) outState.putInt(EXTRA_CURRENT_SHOW_GROUP_ID, showingGroupId) super.onSaveInstanceState(outState) } override fun onResume() { super.onResume() dialogOwner.onResume() } override fun onDestroy() { super.onDestroy() dialogOwner.onDestroy() } private fun toggleNavigationState() { val drawable: Drawable if (navigationContent.visibility == View.GONE) { navigation.menu.setGroupVisible(R.id.main_menu, false) drawable = getDrawable(R.drawable.ic_expand_less_white_24dp) showAccountIndicator.image = drawable navigationContent.fadeIn().end { visibility = View.VISIBLE }.execute() } else { drawable = getDrawable(R.drawable.ic_expand_more_white_24dp) showAccountIndicator.image = drawable navigationContent.visibility = View.GONE navigationContent.fadeOut().end { navigation.menu.setGroupVisible(R.id.main_menu, true) }.execute() } } fun addGroupView(id: Int) { if (columnGroupWrapper.toList().any { it.id == id }) return columnGroupWrapper.addView(ctx.frameLayout { this.id = id tag = id.toString() visibility = View.GONE lparams(matchParent, matchParent) }) } override fun addAccount(twitterUser: TwitterUser, autoDisposable: AutoDisposable) { val holder = AccountItemViewHolder(ctx, twitterUser, autoDisposable) accountItemViewHolderList.add(holder) mAccounts.add(twitterUser) accountsLinear.addView(holder.view) holder.view.fadeIn().execute() } override fun updateAccount(user: TwitterUser) { val clientHolder = accountItemViewHolderList.find { it.twitterUser == user } ?: throw IllegalArgumentException("nonexistent user was passed") clientHolder.update() } override fun addGroup(group: TweetsDisplayGroup) { if (!groups.contains(group)) { val id = group.id addGroupView(id) groups.add(group) } } override fun removeGroup(group: TweetsDisplayGroup) { if (!groups.contains(group)) return val removed = (0..columnGroupWrapper.childCount) .map { columnGroupWrapper.getChildAt(it) } .find { it.id == group.id } ?: throw IllegalStateException() val removedFragment = supportFragmentManager.fragments .filter { it is TimeLinesFragment } .map { it as TimeLinesFragment } .find { it.group.id == group.id } supportFragmentManager.beginTransaction() .remove(removedFragment) .commit() columnGroupWrapper.removeView(removed) if (removed.id == showingGroupId) { columnGroupWrapper.getChildAt(0)?.let { it.visibility = View.VISIBLE showingGroupId = it.id } } groups.remove(group) } override fun showGroup(group: TweetsDisplayGroup) { columnGroupWrapper.forEachChild { if (it.id == group.id) { showingGroupId = group.id it.visibility = View.VISIBLE if (supportFragmentManager.findFragmentByTag(group.id.toString()) == null) { v(javaClass.simpleName, "replace:$group") supportFragmentManager.beginTransaction() .replace(group.id, TimeLinesFragment.create(group), group.id.toString()) .commit() } } else { it.visibility = View.GONE } } supportActionBar!!.subtitle = group.name columnGroupWrapper.fadeIn().execute() } override fun showAddAccountDialog() { var ok = false val dialog = AlertDialog.Builder(ctx) .setPositiveButton(getString(R.string.yes), { _, _ -> drawer.openDrawer(navigation) toggleNavigationState() ok = true }) .setOnDismissListener { if (!ok) showAddAccountDialog() } .setMessage("アカウントの認証する必要があります。") .create() dialogOwner.showDialog(dialog) } fun showChangeColumnGroupDialog() { val dialog = BottomSheetDialog(this) dialog.apply { setContentView(BottomSheetDialogUI(ctx).createView()) groups.forEach { group -> addMenu(createIconMenu(ctx, R.drawable.ic_view_carousel_white_24dp, group.name, { showGroup(group) dialog.dismiss() })) messageText.text = getString(R.string.select_column_group) } } dialogOwner.showDialog(dialog) } class AccountItemViewHolder(ctx: Context, val twitterUser: TwitterUser, val autoDisposable: AutoDisposable) { private val ui = AccountViewUI(ctx) val view: View = ui.createView() init { update() } fun update() { ui.screenNameText.text = twitterUser.screenName ui.userNameText.text = twitterUser.name ui.iconImage.download(twitterUser.iconUrl, autoDisposable) } } companion object { val INTENT_OAUTH = "INTENT_OAUTH" val EXTRA_GROUP = "EXTRA_GROUPS" val EXTRA_CURRENT_SHOW_GROUP_ID = "EXTRA_CURRENT_SHOW_GROUP_ID" } } interface MainActivityInterface : ActivityInterface { var addAccountButtonEnabled: Boolean val accounts: List<TwitterUser> val showingGroupId: Int fun addAccount(twitterUser: TwitterUser, autoDisposable: AutoDisposable) fun updateAccount(user: TwitterUser) fun addGroup(group: TweetsDisplayGroup) fun removeGroup(group: TweetsDisplayGroup) fun showGroup(group: TweetsDisplayGroup) fun showAddAccountDialog() } class OauthActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) startActivity<MainActivity>(MainActivity.INTENT_OAUTH to intent) finish() } }
0
Kotlin
0
0
ea3b007ab7875ea6d1bc1c5c1cec871eee2685a5
11,960
numeri3
MIT License
src/main/kotlin/g1801_1900/s1878_get_biggest_three_rhombus_sums_in_a_grid/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4901773, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1878_get_biggest_three_rhombus_sums_in_a_grid // #Medium #Array #Math #Sorting #Matrix #Heap_Priority_Queue #Prefix_Sum // #2023_06_22_Time_326_ms_(100.00%)_Space_43.8_MB_(100.00%) import java.util.PriorityQueue class Solution { fun getBiggestThree(grid: Array<IntArray>): IntArray { val capicity = 3 val minHeap = PriorityQueue<Int>() val m = grid.size val n = grid[0].size val preSum = Array(m) { Array(n) { IntArray(2) } } val maxLen = Math.min(m, n) / 2 for (r in 0 until m) { for (c in 0 until n) { addToMinHeap(minHeap, grid[r][c], capicity) preSum[r][c][0] += if (valid(m, n, r - 1, c - 1)) grid[r][c] + preSum[r - 1][c - 1][0] else grid[r][c] preSum[r][c][1] += if (valid(m, n, r - 1, c + 1)) grid[r][c] + preSum[r - 1][c + 1][1] else grid[r][c] } } for (r in 0 until m) { for (c in 0 until n) { for (l in 1..maxLen) { if (!valid(m, n, r - l, c - l) || !valid(m, n, r - l, c + l) || !valid(m, n, r - 2 * l, c) ) { break } var rhombus = preSum[r][c][0] - preSum[r - l][c - l][0] rhombus += preSum[r][c][1] - preSum[r - l][c + l][1] rhombus += preSum[r - l][c - l][1] - preSum[r - 2 * l][c][1] rhombus += preSum[r - l][c + l][0] - preSum[r - 2 * l][c][0] rhombus += -grid[r][c] + grid[r - 2 * l][c] addToMinHeap(minHeap, rhombus, capicity) } } } val size = minHeap.size val res = IntArray(size) for (i in size - 1 downTo 0) { res[i] = minHeap.poll() } return res } private fun addToMinHeap(minHeap: PriorityQueue<Int>, num: Int, capicity: Int) { if (minHeap.isEmpty() || minHeap.size < capicity && !minHeap.contains(num)) { minHeap.offer(num) } else { if (num > minHeap.peek() && !minHeap.contains(num)) { minHeap.poll() minHeap.offer(num) } } } private fun valid(m: Int, n: Int, r: Int, c: Int): Boolean { return 0 <= r && r < m && 0 <= c && c < n } }
0
Kotlin
20
43
471d45c60f669ea1a2e103e6b4d8d54da55711df
2,420
LeetCode-in-Kotlin
MIT License
compose_material3/src/main/java/dev/vengateshm/compose_material3/apps/landmark_recognition/LandmarkRecognitionSample.kt
vengateshm
670,054,614
false
{"Kotlin": 1918870, "Java": 46008}
package dev.vengateshm.compose_material3.apps.landmark_recognition import androidx.camera.view.CameraController import androidx.camera.view.LifecycleCameraController import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat @Composable fun LandmarkRecognitionSample(modifier: Modifier = Modifier) { var classification by remember { mutableStateOf(emptyList<Classification>()) } val context = LocalContext.current val landmarkImageAnalyzer = remember { LandmarkImageAnalyzer( landmarkClassifier = TFLiteLandmarkClassifier( context = context.applicationContext, ), onResult = { classification = it } ) } val controller = remember { LifecycleCameraController(context.applicationContext).apply { setEnabledUseCases(CameraController.IMAGE_ANALYSIS) setImageAnalysisAnalyzer( ContextCompat.getMainExecutor(context.applicationContext), landmarkImageAnalyzer ) } } Box(modifier = Modifier.fillMaxSize()) { LandmarkCameraPreview( controller = controller, modifier = Modifier.fillMaxSize() ) Column( modifier = Modifier.fillMaxWidth() .align(Alignment.TopCenter) ) { classification.forEach { Text( text = it.name, modifier = Modifier .fillMaxWidth() .background(color = MaterialTheme.colorScheme.primaryContainer) .padding(8.dp), color = MaterialTheme.colorScheme.primary, fontSize = 20.sp, textAlign = TextAlign.Center ) } } } }
0
Kotlin
0
1
50b5792dc73c2f4c7da625f6c3a0771813089c83
2,671
Android-Kotlin-Jetpack-Compose-Practice
Apache License 2.0
features/auth/src/main/java/com/shekharhandigol/auth/LoginUserUiState.kt
iamShekharGH
861,279,529
false
{"Kotlin": 188994}
package com.shekharhandigol.auth import com.shekharhandigol.models.UserInformation sealed class LoginUserUiState { data object FirstBoot : LoginUserUiState() sealed class Response : LoginUserUiState() { data class Error(val errorMessage: String) : Response() data class Success(val userInformation: UserInformation) : Response() data object Loading : Response() } sealed class UserState : LoginUserUiState() { data object UserIsLoggedIn : UserState() data object UserIsLoggedOut : UserState() data object UserIsNew : UserState() } }
0
Kotlin
0
1
0e57f3f0ddb6b6b2f6ce78fb1be34dbce8641929
604
Employee_crm
MIT License
src/commonMain/kotlin/matt/file/numbered/common/common.kt
mgroth0
513,680,528
false
{"Kotlin": 152887}
package matt.file.numbered.common import matt.file.construct.common.mFile import matt.file.expects.file.toIoFile import matt.lang.anno.MergeWith import matt.lang.model.file.AnyFsFile import matt.lang.model.file.fName @MergeWith(id = 34206385) fun AnyFsFile.next(): AnyFsFile { var ii = 0 while (true) { val f = mFile(path + ii.toString(), myFileSystem) if (!f.toIoFile().exists()) return f ii += 1 } } @MergeWith(id = 34206385) fun AnyFsFile.withNumber(num: Int): AnyFsFile = if ("." !in fName) mFile( "$path ($num)", myFileSystem ) else mFile( path.substringBeforeLast(".") + " ($num)." + path.substringAfterLast( "." ), myFileSystem ) @MergeWith(id = 34206385) fun AnyFsFile.numberedSequence() = sequence { yield(this@numberedSequence) var i = 2 while (true) { yield(this@numberedSequence.withNumber(i++)) } } @MergeWith(id = 34206385) fun AnyFsFile.firstNonExistingFromNumberedSequence() = numberedSequence() .first { it.toIoFile().doesNotExist }
0
Kotlin
0
0
7af07174145d7c5cf16410f6f38ce8c6162ba6cf
1,165
file
MIT License
src/main/kotlin/org/hukehrs/appmessenger/AppMessenger.kt
HukehrsEngineering
226,487,788
false
null
package org.hukehrs.appmessenger import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.hukehrs.extensions.printableStacktrace import org.slf4j.LoggerFactory import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write @Suppress("MemberVisibilityCanBePrivate") open class AppMessenger<T: IAppMessage>(val name: String, private val sendScope: CoroutineScope = SendScope(name), private val receiveScope: CoroutineScope = ReceiveScope(name)) { companion object { val log = LoggerFactory.getLogger(AppMessenger::class.java)!! } private val subscribers = mutableMapOf<Class<*>, MutableList<ISubscriber>>() private val lock = ReentrantReadWriteLock() var debug = false var throwErrors = true fun subscribe(subscriber: ISubscriber, cls: Class<T>) { lock.write { if(!subscribers.containsKey(cls)) { subscribers[cls] = mutableListOf() } subscribers[cls]!!.add(subscriber) } } inline fun <reified TT: T>subscribe(subscriber: ISubscriber) { @Suppress("UNCHECKED_CAST") subscribe(subscriber, TT::class.java as Class<T>) } fun publishAsync(message: T) { publish(message, true) } fun publishSync(message: T) { publish(message, false) } private fun publish(message: IAppMessage, async: Boolean) { val stacktrace = if(debug) { val trace = Thread.currentThread().stackTrace.drop(1) log.trace("[{}AppMessenger]: publishing text {} from {}", name, message, trace[2]) trace } else { null } val currentSubscribers = getSubscribers(message.javaClass) if (currentSubscribers.isEmpty()) { log.warn("[{}AppMessenger]: no subscribers for message of type {}", name, message::class.java.name) } else { if (async) { sendScope.launch { publishToSubscribers(currentSubscribers, message, true, stacktrace) } } else { runBlocking { publishToSubscribers(currentSubscribers, message, false, stacktrace) } } } } fun <T> getSubscribers(messageClass: Class<T>): List<ISubscriber> { return lock.read { subscribers.filter { it.key.isAssignableFrom(messageClass) }.values.flatten() } } private suspend fun publishToSubscribers( currentSubscribers: List<ISubscriber>, message: IAppMessage, async: Boolean, stacktrace: List<StackTraceElement>? ) { currentSubscribers.forEach { if(async) { receiveScope.launch { publishToSubscriber(it, message, stacktrace) } } else { runBlocking { publishToSubscriber(it, message, stacktrace) } } } } private suspend fun publishToSubscriber(it: ISubscriber, message: IAppMessage, stacktrace: List<StackTraceElement>?) { try { it.receive(message) } catch (e: Exception) { if (throwErrors) { throw e } else { log.debug("[{}AppMessenger]: suppressed exception while publishing event: {} {}\n{}\nreceived from\n{}", name, e::class.java.simpleName, e.message, e.stackTrace.printableStacktrace(1), stacktrace?.printableStacktrace()) } } } fun deleteSubscriptions(subscriber: ISubscriber) { lock.write { subscribers.values.forEach { it.remove(subscriber) } } } }
0
Kotlin
0
0
f711d8540985217b0c98f74ea0295a433529fe3a
3,901
AppMessenger
MIT License
buildSrc/src/main/kotlin/Dependencies.kt
faogustavo
304,986,591
false
null
object Kached { val core = ":core" object Serializer { const val gson = ":serializer:gson-serializer" } object Storage { const val simpleMemory = ":storage:simple-memory-storage" } } object Kotlin { const val version = "1.4.10" const val testJUnit = "test-junit" const val testJS = "test-js" const val testCommon = "test-common" const val testAnnotationCommon = "test-annotations-common" object Coroutines { const val version = "1.4.0-M1" const val core = "org.jetbrains.kotlinx:kotlinx-coroutines-core:$version" const val test = "org.jetbrains.kotlinx:kotlinx-coroutines-test:$version" } } object Test { object MockK { const val core = "io.mockk:mockk:1.10.2" const val common = "io.mockk:mockk-common:1.10.2" } } object Serializers { const val gson = "com.google.code.gson:gson:2.8.6" const val kotlinxJson = "org.jetbrains.kotlinx:kotlinx-serialization-json:1.0.1" private const val jacksonVersion = "2.11.3" const val jackson = "com.fasterxml.jackson.core:jackson-databind:$jacksonVersion" const val jacksonKotlinModule = "com.fasterxml.jackson.module:jackson-module-kotlin:$jacksonVersion" } object Loggers { const val sl4j = "org.slf4j:slf4j-api:1.7.30" } object Android { const val coreKtx = "androidx.core:core-ktx:1.3.2" } object Storages { const val awsS3 = "software.amazon.awssdk:s3:2.5.18" }
9
Kotlin
1
5
f5124a6e295e9328669cb2d8a744321fac57b5c2
1,461
kached
Apache License 2.0
recycler/delegate/RecyclerDelegateDispatcher.kt
nikitamasloff
847,614,511
false
{"Kotlin": 34937}
import androidx.recyclerview.widget.DiffUtil interface RecyclerDelegateDispatcher { fun addDelegate(delegate: RecyclerDelegate<*, *>) fun <T : Any> getDelegateViewTypeForItem(item: T): Int? fun findDelegateByViewType(viewType: Int): RecyclerDelegate<*, *>? fun <T : Any> findDelegateForItem(item: T): RecyclerDelegate<T, *>? fun <T : Any> findItemDiffCallbackFor( oldItem: T, newItem: T ): DiffUtil.ItemCallback<in T>? } operator fun RecyclerDelegateDispatcher.plusAssign(delegate: RecyclerDelegate<*, *>) = addDelegate(delegate) fun recyclerDelegateDispatcher( vararg delegates: RecyclerDelegate<*, *> ): RecyclerDelegateDispatcher = DefaultRecyclerDelegateDispatcher(delegates.toList()) fun recyclerDelegateDispatcher( delegates: Collection<RecyclerDelegate<*, *>> = emptyList() ): RecyclerDelegateDispatcher = DefaultRecyclerDelegateDispatcher(delegates)
0
Kotlin
0
0
3b4c56fda00616dee0a17cd7049eede4a93511d4
927
block-delegate-adapterr
MIT License
app/src/main/java/com/parish/register/model/FilterType.kt
valerybodak
554,869,752
false
{"Kotlin": 90023}
package com.parish.register.model enum class FilterType(val id: Int) { ALL(0), BORN(1), MARRIAGES(2), DIED(3); companion object { fun getById(id: Int?): FilterType { if (id == null) { return ALL } return values() .find { it.id == id } ?: ALL } } }
0
Kotlin
0
3
e1d528dd35c3938bca44d3b2eb0f075629919f4f
357
ParishRegister
Apache License 2.0
solana-kotlin/src/commonMain/kotlin/net/avianlabs/solana/methods/sendTransaction.kt
avianlabs
653,085,616
false
{"Kotlin": 89848}
package net.avianlabs.solana.methods import io.ktor.util.* import kotlinx.serialization.json.add import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import net.avianlabs.solana.SolanaClient import net.avianlabs.solana.domain.core.Commitment import net.avianlabs.solana.domain.core.Transaction /** * Send a signed transaction to the cluster * @param transaction The signed transaction to send * @param skipPreflight If true, skip the preflight check * @param preflightCommitment The commitment level to use for the preflight check * @param maxRetries The maximum number of retries to send the transaction * @param minContextSlot The minimum slot to send the transaction * @return The transaction signature */ public suspend fun SolanaClient.sendTransaction( transaction: Transaction, skipPreflight: Boolean = false, preflightCommitment: Commitment = Commitment.Finalized, maxRetries: Int? = null, minContextSlot: Long? = null, ): String { val result = invoke<String>( method = "sendTransaction", params = buildJsonArray { add(transaction.serialize().encodeBase64()) add(buildJsonObject { put("encoding", "base64") put("skipPreflight", skipPreflight) put("preflightCommitment", preflightCommitment.value) maxRetries?.let { put("maxRetries", it) } minContextSlot?.let { put("minContextSlot", it) } }) } ) return result!! }
8
Kotlin
0
2
6afbe1c50dcc4fff66db557a49925f4efcd63316
1,501
solana-kotlin
MIT License
solana-kotlin/src/commonMain/kotlin/net/avianlabs/solana/methods/sendTransaction.kt
avianlabs
653,085,616
false
{"Kotlin": 89848}
package net.avianlabs.solana.methods import io.ktor.util.* import kotlinx.serialization.json.add import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import net.avianlabs.solana.SolanaClient import net.avianlabs.solana.domain.core.Commitment import net.avianlabs.solana.domain.core.Transaction /** * Send a signed transaction to the cluster * @param transaction The signed transaction to send * @param skipPreflight If true, skip the preflight check * @param preflightCommitment The commitment level to use for the preflight check * @param maxRetries The maximum number of retries to send the transaction * @param minContextSlot The minimum slot to send the transaction * @return The transaction signature */ public suspend fun SolanaClient.sendTransaction( transaction: Transaction, skipPreflight: Boolean = false, preflightCommitment: Commitment = Commitment.Finalized, maxRetries: Int? = null, minContextSlot: Long? = null, ): String { val result = invoke<String>( method = "sendTransaction", params = buildJsonArray { add(transaction.serialize().encodeBase64()) add(buildJsonObject { put("encoding", "base64") put("skipPreflight", skipPreflight) put("preflightCommitment", preflightCommitment.value) maxRetries?.let { put("maxRetries", it) } minContextSlot?.let { put("minContextSlot", it) } }) } ) return result!! }
8
Kotlin
0
2
6afbe1c50dcc4fff66db557a49925f4efcd63316
1,501
solana-kotlin
MIT License
rtsp/src/main/java/com/pedro/rtsp/rtp/packets/BasePacket.kt
pedroSG94
79,667,969
false
{"Kotlin": 1116814, "Java": 618860, "GLSL": 34672}
/* * Copyright (C) 2024 pedroSG94. * * 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.pedro.rtsp.rtp.packets import com.pedro.common.frame.MediaFrame import com.pedro.rtsp.rtsp.RtpFrame import com.pedro.rtsp.utils.RtpConstants import com.pedro.rtsp.utils.setLong import kotlin.experimental.and import kotlin.experimental.or /** * Created by pedro on 27/11/18. */ abstract class BasePacket(private var clock: Long, private val payloadType: Int) { protected var channelIdentifier: Int = 0 private var seq = 0L private var ssrc = 0L protected val maxPacketSize = RtpConstants.MTU - 28 protected val TAG = "BasePacket" abstract suspend fun createAndSendPacket( mediaFrame: MediaFrame, callback: suspend (List<RtpFrame>) -> Unit ) open fun reset() { seq = 0 ssrc = 0 } fun setSSRC(ssrc: Long) { this.ssrc = ssrc } protected fun setClock(clock: Long) { this.clock = clock } protected fun getBuffer(size: Int): ByteArray { val buffer = ByteArray(size) buffer[0] = 0x80.toByte() buffer[1] = payloadType.toByte() setLongSSRC(buffer, ssrc) requestBuffer(buffer) return buffer } protected fun updateTimeStamp(buffer: ByteArray, timestamp: Long): Long { val ts = timestamp * clock / 1000000000L buffer.setLong(ts, 4, 8) return ts } protected fun updateSeq(buffer: ByteArray) { buffer.setLong(++seq, 2, 4) } protected fun markPacket(buffer: ByteArray) { buffer[1] = buffer[1] or 0x80.toByte() } private fun setLongSSRC(buffer: ByteArray, ssrc: Long) { buffer.setLong(ssrc, 8, 12) } private fun requestBuffer(buffer: ByteArray) { buffer[1] = buffer[1] and 0x7F } }
87
Kotlin
772
2,545
eca59948009d5a7b564f9a838c149b850898d089
2,212
RootEncoder
Apache License 2.0
app/src/main/java/com/udacity/geofence/basics/model/LandmarkModel.kt
RicardoBravoA
317,751,620
false
null
package com.udacity.geofence.basics.model import com.google.android.gms.maps.model.LatLng /** * Stores latitude and longitude information along with a hint to help user find the location. */ data class LandmarkModel(val id: String, val hint: Int, val name: Int, val latLong: LatLng)
0
Kotlin
0
0
1f7aa5b5d3fd01432215e32bcd39a20571c0b96d
286
GeofenceBasics
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/uievents/TouchList.kt
karakum-team
393,199,102
false
null
// Automatically generated - do not modify! package web.uievents import js.core.ArrayLike import js.core.JsIterable sealed external class TouchList : ArrayLike<Touch>, JsIterable<Touch> { fun item(index: Int): Touch? }
0
Kotlin
6
22
340fa5d93f874ebf14810ab797a9808af574e058
234
types-kotlin
Apache License 2.0
app/src/main/kotlin/com/josealfonsomora/jetpackgithubtrends/ui/reposlist/GithubReposListFragment.kt
josealfonsomora
294,715,074
false
null
package com.josealfonsomora.jetpackgithubtrends.ui.reposlist import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.josealfonsomora.jetpackgithubtrends.R import com.josealfonsomora.jetpackgithubtrends.databinding.GithubReposListFragmentBinding import com.josealfonsomora.jetpackgithubtrends.ui.repodetails.GithubRepoDetailFragment import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class GithubReposListFragment : Fragment(R.layout.github_repos_list_fragment) { private val viewModel: GitHubReposListViewModel by viewModels() private val adapter by lazy { GithubReposListAdapter { val action = GithubReposListFragmentDirections.actionReposListtToDetailDest(it) findNavController().navigate(action) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = GithubReposListFragmentBinding.bind(view) val toolbar = view.findViewById<Toolbar>(R.id.toolbar) toolbar.title = getString(R.string.single_fetch_list) binding.lifecycleOwner = this binding.model = viewModel binding.reposList.adapter = adapter viewModel.githubRepos.observe(viewLifecycleOwner, { list -> adapter.updateList(list) }) binding.swipeRefresh.setOnRefreshListener { viewModel.loadData() } viewModel.stateEvent.observe(viewLifecycleOwner, { it?.getContentIfNotHandled()?.let { state -> when (state) { GitHubReposListViewModel.State.ErrorLoadingReposEvent -> showErrorLoadingReposMessage() } } }) viewModel.loadData() } private fun showErrorLoadingReposMessage() { Toast.makeText(requireContext(), R.string.error_loading_repos, Toast.LENGTH_SHORT).show() } }
0
Kotlin
0
0
f6dfb4fc9d27fa521ab94fbb13359a85dc4ce567
2,134
jetpack-github-trends
MIT License
feature/room_list/src/main/java/fr/boitakub/room_list/RoomListViewModel.kt
jforatier
388,597,382
false
null
package fr.boitakub.room_list import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import fr.boitakub.common.jeedom_client.ListObjectRequest import fr.boitakub.common.jeedom_client.Object import fr.boitakub.common.jeedom_client.Parameters import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class RoomListViewModel @Inject constructor( private val savedStateHandle: SavedStateHandle, private val repository: RoomRepository, private val apiKey: String ) : ViewModel() { val errorMessage = MutableLiveData<String>() val roomList = MutableLiveData<List<Object>>() var job: Job? = null val exceptionHandler = CoroutineExceptionHandler() { _, throwable -> onError("Exception handled: ${throwable.localizedMessage}") } val loading = MutableLiveData<Boolean>() fun retrieveRooms() { job = CoroutineScope(Dispatchers.IO + exceptionHandler).launch { val response = repository.getAllRooms(ListObjectRequest(Parameters(apiKey))) withContext(Dispatchers.Main) { if (response?.result != null) { roomList.postValue(response.result) loading.value = false } else { onError("Error : ${response?.firstErrorMessage} ") } } } } private fun onError(message: String) { errorMessage.value = message loading.value = false } override fun onCleared() { super.onCleared() job?.cancel() } }
1
Kotlin
2
2
7c15e1844a53601648bd46eac282d8be1b6e25ce
1,890
Tuxedo
MIT License
src/main/kotlin/io/curity/identityserver/plugin/dynamodb/helpers/DatabaseClientAttributesHelper.kt
curityio
319,927,873
false
{"Kotlin": 385688}
/* * Copyright 2023 Curity AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.curity.identityserver.plugin.dynamodb.helpers import io.curity.identityserver.plugin.dynamodb.helpers.AttributesHelper.withMetaIfEnumerated import se.curity.identityserver.sdk.attribute.Attribute import se.curity.identityserver.sdk.attribute.AttributeCollector import se.curity.identityserver.sdk.attribute.Attributes import se.curity.identityserver.sdk.attribute.MapAttributeValue import se.curity.identityserver.sdk.attribute.client.database.DatabaseClientAttributes import se.curity.identityserver.sdk.attribute.client.database.DatabaseClientAttributes.DatabaseClientAttributeKeys import se.curity.identityserver.sdk.attribute.scim.v2.ResourceAttributes import se.curity.identityserver.sdk.data.query.ResourceQuery.AttributesEnumeration import se.curity.identityserver.sdk.service.Json import java.util.Objects object DatabaseClientAttributesHelper { const val CLIENT_NAME_COLUMN = "client_name" private const val CREATED_DATE_COLUMN = "created" private const val UPDATED_COLUMN = "updated" const val ID_TOKEN_JWE_ENCRYPTION_KEY_ID = "id_token_jwe_encryption_key_id" const val REQUEST_OBJECT_BY_REFERENCE_HTTP_CLIENT_ID = "request_object_by_reference_http_client_id" const val SECONDARY_CLIENT_AUTHENTICATION = "secondary_client_authentication" const val SECONDARY_CREDENTIAL_MANAGER_ID = "secondary_credential_manager_id" const val SECONDARY_ASYMMETRIC_KEY_ID = "secondary_asymmetric_key_id" const val SECONDARY_MUTUAL_TLS_CLIENT_CERTIFICATE_ID = "secondary_mutual_tls_client_certificate_id" const val PRIMARY_CLIENT_AUTHENTICATION = "primary_client_authentication" const val PRIMARY_CREDENTIAL_MANAGER_ID = "primary_credential_manager_id" const val PRIMARY_ASYMMETRIC_KEY_ID = "primary_asymmetric_key_id" const val PRIMARY_MUTUAL_TLS_CLIENT_CERTIFICATE_ID = "primary_mutual_tls_client_certificate_id" const val HAAPI_POLICY_ID = "haapi_policy_id" const val JWT_ASSERTION_JWKS_URI_CLIENT_ID = "jwt_assertion_jwks_uri_http_client_id" const val JWT_ASSERTION_ASYMMETRIC_KEY_ID = "jwt_assertion_asymmetric_key_id" const val ROPC_CREDENTIAL_MANAGER_ID = "resource_owner_password_credentials_credential_manager_id" const val BACKCHANNEL_LOGOUT_HTTP_CLIENT_ID = "backchannel_logout_http_client_id" const val CONFIGURATION_REFERENCES = "configuration_references" private const val TAGS = "tags" const val ATTRIBUTES = "attributes" const val PROFILE_ID = "profile_id" /** * When persisting to the database, collection of attributes which should not be persisted into the ATTRIBUTES json * blob. */ val DATABASE_CLIENT_SEEDING_ATTRIBUTES = setOf( DatabaseClientAttributeKeys.CLIENT_ID, PROFILE_ID, DatabaseClientAttributeKeys.NAME, ATTRIBUTES, DatabaseClientAttributeKeys.STATUS, TAGS, DatabaseClientAttributeKeys.META, ResourceAttributes.SCHEMAS ) /** * When fetching from the database, collection of attributes that are used to fully populate a DatabaseClientAttributes. * They must be discarded from the Attributes source given to the DatabaseClient constructor. */ val DATABASE_CLIENT_INTERNAL_ATTRIBUTES = setOf( PROFILE_ID, ATTRIBUTES, CREATED_DATE_COLUMN, UPDATED_COLUMN ) fun toResource( attributes: Attributes, attributesEnumeration: AttributesEnumeration, json: Json ): DatabaseClientAttributes { val multiValuedAttributes: Collection<String> = emptySet<String>() // All persistable attributes, are stored into the ATTRIBUTES attribute, non persistable attributes // are stored in dedicated columns and are not duplicated in ATTRIBUTES. The non persistable attributes are // the source attributes to inflate a DatabaseClient: // 1. Discard all attributes duplicated in ATTRIBUTES attribute. val parsedAttributes = toResource(attributes, multiValuedAttributes, json, ATTRIBUTES) // 2. Promote all attributes nested in ATTRIBUTES property at top level. val nestedAttributes = parsedAttributes[ATTRIBUTES] // The ATTRIBUTES attribute is known to be a MapAttributeValue and was parsed by the toResource(...) call above. var allAttributes = if (nestedAttributes == null) { parsedAttributes } else { assert(nestedAttributes.attributeValue is Iterable<*>) parsedAttributes.with(nestedAttributes.attributeValue as Iterable<Attribute>) } // 3. Add the "meta" attribute if it is enumerated. allAttributes = withMetaIfEnumerated(allAttributes, attributesEnumeration, DatabaseClientAttributes.RESOURCE_TYPE) // 4. Remove all persistence related attributes which are not needed anymore. allAttributes = allAttributes.removeAttributes(DATABASE_CLIENT_INTERNAL_ATTRIBUTES) return DatabaseClientAttributes.of(allAttributes) } private fun toResource( attributes: Attributes, multiValuedAttributes: Collection<String>, json: Json, vararg extraAttributesHolderName: String ): Attributes { var extendedAttributes = attributes for (attributeName in extraAttributesHolderName) { val extraAttributesHolder: Attribute? = attributes[attributeName] if (extraAttributesHolder != null) { val extraAttributes = json.toAttributes(extraAttributesHolder.getValueOfType(String::class.java)) extendedAttributes = extendedAttributes.with(Attribute.of(attributeName, MapAttributeValue.of(extraAttributes))) } } return extendedAttributes.append(multiValuedAttributes.stream() .map { name: String -> extendedAttributes[name] } .filter { obj: Attribute -> Objects.nonNull(obj) } .map { obj: Attribute -> AttributesHelper.spaceSeparatedValuesToListAttributeValue(obj) } .collect(AttributeCollector.toAttributes()) ) } }
0
Kotlin
2
0
82aae9ffb45f6e4ed9e633eab469bb3a3dae648f
6,673
dynamodb-data-access-provider
Apache License 2.0
app/src/main/java/com/example/newsapp/fragments/WebViewFragment.kt
atiQkhalid
383,113,868
false
null
package com.example.newsapp.fragments import android.graphics.Bitmap import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebChromeClient import android.webkit.WebView import android.webkit.WebViewClient import com.example.newsapp.R import com.example.newsapp.base.BaseFragment import kotlinx.android.synthetic.main.fragment_web_view.* /** * The PrivacyPolicesFragment.kt */ class WebViewFragment(private val url: String) : BaseFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.fragment_web_view, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { mainActivity.updateNavigationViewVisibility(false) startWebView(url) } private fun startWebView(url: String) { webView.webViewClient = object : WebViewClient() { override fun onPageStarted( view: WebView?, url: String?, favicon: Bitmap? ) { progressDialog.show() } override fun onPageFinished(view: WebView?, url: String?) { progressDialog.dismiss() } } webView.webChromeClient = object : WebChromeClient() { override fun onProgressChanged(view: WebView?, newProgress: Int) { progressDialog.dismiss() } } // Enable the javascript webView.settings.javaScriptEnabled = true // Render the web page webView.loadUrl(url) } }
0
Kotlin
0
0
3a77284efcab0bf700a833a60f1b4f02fe65ee39
1,722
newsApp
MIT License
src/test/kotlin/eu/luminis/workshops/kdd/testutil/FirstFromList.kt
nkrijnen
500,971,652
false
{"Kotlin": 69360}
package eu.luminis.workshops.kdd.testutil import org.assertj.core.api.Assertions internal inline fun <reified T> List<*>.firstAndOnlyItemAs(): T { Assertions.assertThat(this.size).isEqualTo(1) return this[0] as T }
0
Kotlin
0
7
05b896ac01651f05eacbf7880743321a97cc8d79
224
event-sourcing-in-code
MIT License