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/com/adamcalculator/rpdeletebutton/ModMenuIntegration.kt | AdamCalculator | 830,981,434 | false | {"Kotlin": 9468} | package com.adamcalculator.rpdeletebutton
import com.terraformersmc.modmenu.api.ConfigScreenFactory
import com.terraformersmc.modmenu.api.ModMenuApi
import me.shedaniel.clothconfig2.api.ConfigBuilder
import me.shedaniel.clothconfig2.api.ConfigEntryBuilder
import net.fabricmc.loader.api.FabricLoader
import net.minecraft.ChatFormatting
import net.minecraft.Util
import net.minecraft.client.gui.screens.Screen
import net.minecraft.network.chat.Component
class ModMenuIntegration : ModMenuApi {
override fun getModConfigScreenFactory(): ConfigScreenFactory<*> {
return ConfigScreenFactory { parent ->
return@ConfigScreenFactory if (FabricLoader.getInstance().isModLoaded("cloth-config")) {
createClothConfigScreen(parent)
} else {
println("[${DeleteButtonWidget.LOG}] cloth-config is missing :(")
null
}
}
}
private fun createClothConfigScreen(parent: Screen): Screen? {
val config = Config.getConfig()
val defConfig = Config() // if u save it, config restored to defaults
val builder = ConfigBuilder.create()
.setParentScreen(parent)
.setTitle(Component.translatable("rpdeletebutton.modname.full"))
.setSavingRunnable(Config.Companion::save)
val entryBuilder: ConfigEntryBuilder = builder.entryBuilder()
val general = builder.getOrCreateCategory(Component.literal(""))
general.addEntry(
entryBuilder.startBooleanToggle(Component.translatable("rpdeletebutton.config.always_show_button"), config.alwaysShowButton)
.setTooltip(Component.translatable("rpdeletebutton.config.always_show_button.tooltip"))
.setDefaultValue(defConfig.alwaysShowButton)
.setSaveConsumer { newValue ->
config.alwaysShowButton = newValue
}
.build()
)
general.addEntry(
entryBuilder.startBooleanToggle(Component.translatable("rpdeletebutton.config.use_trash_folder"), config.isUseTrashFolder)
.setTooltip(Component.translatable(if (Util.getPlatform() == Util.OS.WINDOWS) "rpdeletebutton.config.use_trash_folder.tooltip.windows" else "rpdeletebutton.config.use_trash_folder.tooltip", config.trashPath.replace("%GAME_DIR%", ".minecraft")))
.setDefaultValue(defConfig.isUseTrashFolder)
.setSaveConsumer { newValue ->
config.isUseTrashFolder = newValue
}
.build()
)
general.addEntry(
entryBuilder.startBooleanToggle(Component.translatable("rpdeletebutton.config.delete_without_confirming").withStyle(ChatFormatting.RED), config.noConfirmationDelete)
.setTooltip(Component.translatable("rpdeletebutton.config.delete_without_confirming.tooltip"))
.setDefaultValue(defConfig.noConfirmationDelete)
.setSaveConsumer { newValue ->
config.noConfirmationDelete = newValue
}
.build()
)
return builder.build()
}
} | 0 | Kotlin | 0 | 1 | a02883c59e4dc2c8104690c435f6b80969a04476 | 3,163 | RPDeleteButton | MIT License |
wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/WireGrpcExperimental.kt | square | 12,274,147 | false | null | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.squareup.wire
import kotlinx.coroutines.ExperimentalCoroutinesApi
/**
* Marker annotation for experimental Wire gRPC features.
*/
@ExperimentalCoroutinesApi
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class WireGrpcExperimental
| 148 | null | 570 | 4,244 | 74715088d7d2ee1fdd6d3e070c8b413eefc7e5bd | 911 | wire | Apache License 2.0 |
bbfgradle/tmp/results/diffABI/classified/64/xxranzp_FILE.kt | DaniilStepanov | 346,008,310 | false | {"Markdown": 122, "Gradle": 762, "Gradle Kotlin DSL": 649, "Java Properties": 23, "Shell": 49, "Ignore List": 20, "Batchfile": 26, "Git Attributes": 8, "Kotlin": 82508, "Protocol Buffer": 12, "Java": 6674, "Proguard": 12, "XML": 1698, "Text": 13298, "INI": 221, "JavaScript": 294, "JAR Manifest": 2, "Roff": 217, "Roff Manpage": 38, "JSON": 199, "HTML": 2429, "AsciiDoc": 1, "YAML": 21, "EditorConfig": 1, "OpenStep Property List": 19, "C": 79, "Objective-C": 68, "C++": 169, "Swift": 68, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 12, "Groovy": 45, "Dockerfile": 3, "Diff": 1, "EJS": 1, "CSS": 6, "Ruby": 6, "SVG": 50, "JFlex": 3, "Maven POM": 107, "JSON with Comments": 9, "Ant Build System": 53, "Graphviz (DOT)": 78, "Scala": 1} | // Bug happens on JVM , JVM -Xuse-ir
// WITH_RUNTIME
// FILE: tmp0.kt
import kotlin.properties.Delegates.notNull
fun box(): String {
var bunny by notNull<String>()
val obj = object {
val getBunny = { bunny }
}
bunny = "OK"
return obj.getBunny()
}
| 1 | null | 1 | 1 | e772ef1f8f951873ebe7d8f6d73cf19aead480fa | 279 | kotlinWithFuzzer | Apache License 2.0 |
skrapers/src/main/kotlin/ru/sokomishalov/skraper/client/okhttp3/OkHttp3SkraperClient.kt | edwinRNDR | 262,866,888 | true | {"Kotlin": 201997, "Shell": 41, "Batchfile": 33} | /**
* Copyright (c) 2019-present <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.sokomishalov.skraper.client.okhttp3
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okio.BufferedSink
import ru.sokomishalov.skraper.SkraperClient
import ru.sokomishalov.skraper.client.HttpMethodType
import ru.sokomishalov.skraper.model.URLString
import java.io.IOException
import kotlin.coroutines.resumeWithException
/**
* Huge appreciation to my russian colleague
* @see <a href="https://github.com/gildor/kotlin-coroutines-okhttp/blob/master/src/main/kotlin/ru/gildor/coroutines/okhttp/CallAwait.kt">link</a>
*
* @author sokomishalov
*/
class OkHttp3SkraperClient(
private val client: OkHttpClient = DEFAULT_CLIENT
) : SkraperClient {
@Suppress("BlockingMethodInNonBlockingContext")
override suspend fun request(
url: URLString,
method: HttpMethodType,
headers: Map<String, String>,
body: ByteArray?
): ByteArray? {
val request = Request
.Builder()
.url(url)
.headers(Headers.headersOf(*(headers.flatMap { listOf(it.key, it.value) }.toTypedArray())))
.method(method = method.name, body = body?.createRequest(contentType = headers["Content-Type"]))
.build()
return client
.newCall(request)
.await()
.body
?.bytes()
}
@OptIn(ExperimentalCoroutinesApi::class)
private suspend fun Call.await(): Response {
return suspendCancellableCoroutine { continuation ->
enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) = continuation.resume(response) { Unit }
override fun onFailure(call: Call, e: IOException) = if (continuation.isCancelled.not()) continuation.resumeWithException(e) else Unit
})
continuation.invokeOnCancellation {
runCatching { cancel() }.getOrNull()
}
}
}
private fun ByteArray.createRequest(contentType: String?): RequestBody? {
return object : RequestBody() {
override fun contentType(): MediaType? = contentType?.toMediaType()
override fun contentLength(): Long = [email protected]()
override fun writeTo(sink: BufferedSink) = sink.write(this@createRequest).run { Unit }
}
}
companion object {
@JvmStatic
val DEFAULT_CLIENT: OkHttpClient = OkHttpClient
.Builder()
.followRedirects(true)
.followSslRedirects(true)
.build()
}
} | 0 | Kotlin | 0 | 0 | 2dee3affe988db6d1de568bea97e9c43074c3d72 | 3,348 | skraper | Apache License 2.0 |
app/src/main/java/com/prime/media/core/playback/Playback.kt | iZakirSheikh | 506,656,610 | false | null | package com.prime.media.core.playback
import android.annotation.SuppressLint
import android.app.*
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Intent
import android.os.Build
import android.widget.Toast
import androidx.media3.common.*
import androidx.media3.common.C.AUDIO_CONTENT_TYPE_MUSIC
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.ShuffleOrder.DefaultShuffleOrder
import androidx.media3.session.*
import androidx.media3.session.MediaLibraryService.MediaLibrarySession.Callback
import androidx.media3.session.MediaSession.ControllerInfo
import com.google.common.collect.ImmutableList
import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
import com.prime.media.MainActivity
import com.prime.media.R
import com.prime.media.console.Widget
import com.prime.media.core.db.Playlist
import com.prime.media.core.db.Playlists
import com.prime.media.core.util.Member
import com.primex.preferences.*
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.*
import org.json.JSONArray
import javax.inject.Inject
import kotlin.random.Random
private const val TAG = "Playback"
/**
* The name of Global [Playlists]
*/
private val PLAYLIST_FAVOURITE = Playlists.PRIVATE_PLAYLIST_PREFIX + "favourite"
/**
* The name of Global [Playlists]
*/
private val PLAYLIST_RECENT = Playlists.PRIVATE_PLAYLIST_PREFIX + "recent"
/**
* The name of Global [Playlists]
*/
private val PLAYLIST_QUEUE = Playlists.PRIVATE_PLAYLIST_PREFIX + "queue"
/**
* Different roots served by this service.
*/
private const val ROOT_QUEUE = "com.prime.player.queue"
/**
* A MediaItem impl of [ROOT_QUEUE]
*/
private val BROWSER_ROOT_QUEUE =
MediaItem.Builder()
.setMediaId(ROOT_QUEUE)
.setMediaMetadata(
MediaMetadata.Builder().setIsBrowsable(true)
.setIsPlayable(false)
.build()
)
.build()
/*Different keys for saving the state*/
private val PREF_KEY_SHUFFLE_MODE = booleanPreferenceKey("_shuffle", false)
private val PREF_KEY_REPEAT_MODE = intPreferenceKey("_repeat_mode", Player.REPEAT_MODE_OFF)
private val PREF_KEY_INDEX = intPreferenceKey("_index", C.INDEX_UNSET)
private val PREF_KEY_BOOKMARK = longPreferenceKey("_bookmark", C.TIME_UNSET)
private val PREF_KEY_ORDERS = stringPreferenceKey(
"_orders",
IntArray(0),
object : StringSaver<IntArray> {
override fun restore(value: String): IntArray {
val arr = JSONArray(value)
return IntArray(arr.length()) {
arr.getInt(it)
}
}
override fun save(value: IntArray): String {
val arr = JSONArray(value)
return arr.toString()
}
}
)
private val PREF_KEY_RECENT_PLAYLIST_LIMIT =
intPreferenceKey( "_max_recent_size", defaultValue = 50)
/**
* A simple extension fun that adds items to recent.
*/
private suspend fun Playlists.addToRecent(item: MediaItem, limit: Long) {
val playlistId =
get(PLAYLIST_RECENT)?.id ?: insert(Playlist(name = PLAYLIST_RECENT))
// here two cases arise
// case 1 the member already exists:
// in this case we just have to update the order and nothing else
// case 2 the member needs to be inserted.
// In both cases the playlist's dateModified needs to be updated.
val playlist = get(playlistId)!!
update(playlist = playlist.copy(dateModified = System.currentTimeMillis()))
val member = get(playlistId, item.requestMetadata.mediaUri.toString())
when (member != null) {
// exists
true -> {
//localDb.members.update(member.copy(order = 0))
// updating the member doesn't work as expected.
// localDb.members.delete(member)
update(member = member.copy(order = 0))
}
else -> {
// delete above member
delete(playlistId, limit)
insert(Member(item, playlistId, 0))
}
}
}
/**
* An extension fun that saves [items] to queue replacing the old ones.
*/
private suspend fun Playlists.save(items: List<MediaItem>) {
val id = get(PLAYLIST_QUEUE)?.id ?: insert(
Playlist(name = PLAYLIST_QUEUE)
)
// delete all old
delete(id, 0)
var order = 0
val members = items.map { Member(it, id, order++) }
insert(members)
}
/**
* The Playback Service class using media3.
*/
@AndroidEntryPoint
class Playback : MediaLibraryService(), Callback, Player.Listener {
companion object {
/**
* The name of Global [Playlists]
*/
@JvmField
val PLAYLIST_FAVOURITE = com.prime.media.core.playback.PLAYLIST_FAVOURITE
/**
* The name of Global [Playlists]
*/
@JvmField
val PLAYLIST_RECENT = com.prime.media.core.playback.PLAYLIST_RECENT
/**
* The name of Global [Playlists]
*/
@JvmField
val PLAYLIST_QUEUE = com.prime.media.core.playback.PLAYLIST_QUEUE
/**
* The root of the playing queue
*/
const val ROOT_QUEUE = com.prime.media.core.playback.ROOT_QUEUE
@JvmField
val PREF_KEY_RECENT_PLAYLIST_LIMIT = com.prime.media.core.playback.PREF_KEY_RECENT_PLAYLIST_LIMIT
}
/**
* The pending intent for the underlying activity.
*/
private val activity by lazy {
// create the activity intent and set with session
TaskStackBuilder.create(this).run {
addNextIntent(Intent(this@Playback, MainActivity::class.java))
val immutableFlag = if (Build.VERSION.SDK_INT >= 23) FLAG_IMMUTABLE else 0
getPendingIntent(0, immutableFlag or FLAG_UPDATE_CURRENT)
}
}
private val player: Player by lazy {
ExoPlayer.Builder(this).setAudioAttributes(
// set audio attributes to it
AudioAttributes.Builder().setContentType(AUDIO_CONTENT_TYPE_MUSIC)
.setUsage(C.USAGE_MEDIA).build(), true
).setHandleAudioBecomingNoisy(true).build()
}
private val session: MediaLibrarySession by lazy {
runBlocking { onRestoreSavedState() }
player.addListener(this)
MediaLibrarySession.Builder(this, player, this).setSessionActivity(activity).build()
}
// This helps in implement the state of this service using persistent storage .
@Inject
lateinit var preferences: Preferences
@Inject
lateinit var playlists: Playlists
/**
* Restore the saved state of this service.
*/
@SuppressLint("UnsafeOptInUsageError")
private suspend fun onRestoreSavedState() {
with(player) {
shuffleModeEnabled = preferences.value(PREF_KEY_SHUFFLE_MODE)
repeatMode = preferences.value(PREF_KEY_REPEAT_MODE)
setMediaItems(playlists.getMembers(PLAYLIST_QUEUE).map(Playlist.Member::toMediaSource))
// set saved shuffled.
(this as ExoPlayer).setShuffleOrder(
DefaultShuffleOrder(preferences.value(PREF_KEY_ORDERS), Random.nextLong())
)
// seek to current position
val index = preferences.value(PREF_KEY_INDEX)
if (index != C.INDEX_UNSET) seekTo(index, preferences.value(PREF_KEY_BOOKMARK))
}
}
// here return the session
override fun onGetSession(controllerInfo: ControllerInfo) = session
// return the items to add to player
override fun onAddMediaItems(
mediaSession: MediaSession, controller: ControllerInfo, mediaItems: MutableList<MediaItem>
): ListenableFuture<List<MediaItem>> =
Futures.immediateFuture(mediaItems.map(MediaItem::toMediaSource))
// FixMe: Don't currently know how this affects.
@SuppressLint("UnsafeOptInUsageError")
override fun onGetLibraryRoot(
session: MediaLibrarySession, browser: ControllerInfo, params: LibraryParams?
): ListenableFuture<LibraryResult<MediaItem>> =
Futures.immediateFuture(LibraryResult.ofItem(BROWSER_ROOT_QUEUE, params))
// return the individual media item pointed out by the [mediaId]
override fun onGetItem(
session: MediaLibrarySession, browser: ControllerInfo, mediaId: String
): ListenableFuture<LibraryResult<MediaItem>> {
val item = player.mediaItems.find { it.mediaId == mediaId }
val result = if (item == null) LibraryResult.ofError(LibraryResult.RESULT_ERROR_BAD_VALUE)
else LibraryResult.ofItem(item, /* params = */ null)
return Futures.immediateFuture(result)
}
//TODO: Find how can i return he playing queue with upcoming items only.
override fun onSubscribe(
session: MediaLibrarySession,
browser: ControllerInfo,
parentId: String,
params: LibraryParams?
): ListenableFuture<LibraryResult<Void>> {
val children = when (parentId) {
ROOT_QUEUE -> player.queue
else -> return Futures.immediateFuture(
LibraryResult.ofError(LibraryResult.RESULT_ERROR_BAD_VALUE)
)
}
session.notifyChildrenChanged(browser, parentId, children.size, params)
return Futures.immediateFuture(LibraryResult.ofVoid())
}
override fun onGetChildren(
session: MediaLibrarySession,
browser: ControllerInfo,
parentId: String,
page: Int,
pageSize: Int,
params: LibraryParams?
): ListenableFuture<LibraryResult<ImmutableList<MediaItem>>> {
//TODO(Maybe add support for paging.)
val children = when (parentId) {
ROOT_QUEUE -> player.queue
else -> return Futures.immediateFuture(
LibraryResult.ofError(LibraryResult.RESULT_ERROR_BAD_VALUE)
)
}
return Futures.immediateFuture(LibraryResult.ofItemList(children, params))
}
// release resources
// cancel scope etc.
override fun onDestroy() {
player.release()
session.release()
super.onDestroy()
}
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
// save current index in preference
preferences[PREF_KEY_INDEX] = player.currentMediaItemIndex
if (mediaItem != null) {
val limit = preferences.value(PREF_KEY_RECENT_PLAYLIST_LIMIT)
GlobalScope.launch { playlists.addToRecent(mediaItem, limit.toLong()) }
session.notifyChildrenChanged(ROOT_QUEUE, 0, null)
}
}
override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) {
preferences[PREF_KEY_SHUFFLE_MODE] = shuffleModeEnabled
session.notifyChildrenChanged(ROOT_QUEUE, 0, null)
}
override fun onRepeatModeChanged(repeatMode: Int) {
preferences[PREF_KEY_REPEAT_MODE] = repeatMode
}
override fun onTimelineChanged(timeline: Timeline, reason: Int) {
// construct list and update.
if (reason == Player.TIMELINE_CHANGE_REASON_PLAYLIST_CHANGED) {
GlobalScope.launch(Dispatchers.Main) { playlists.save(player.mediaItems) }
preferences[PREF_KEY_ORDERS] = player.orders
session.notifyChildrenChanged(ROOT_QUEUE, 0, null)
}
}
override fun onUpdateNotification(session: MediaSession, startInForegroundRequired: Boolean) {
super.onUpdateNotification(session, startInForegroundRequired)
// send intent for updating the widget also,
val intent = Intent(this, Widget::class.java)
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
val ids = AppWidgetManager.getInstance(application)
.getAppWidgetIds(ComponentName(application, Widget::class.java))
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
sendBroadcast(intent)
}
override fun onPlayerError(error: PlaybackException) {
// make a simple toast
Toast.makeText(this, getString(R.string.unplayable_file), Toast.LENGTH_SHORT).show()
//player.seekToNextMediaItem()
}
} | 12 | Kotlin | 1 | 36 | 69819f03e335c8b93ddc792dcbe8c22cefd63f95 | 12,207 | Audiofy | Apache License 2.0 |
rpgJavaInterpreter-core/src/main/kotlin/com/smeup/rpgparser/interpreter/InterpreterCore.kt | eprparadocs | 263,168,951 | true | {"Kotlin": 805492, "ANTLR": 158813, "Ruby": 1899, "PowerShell": 861, "Dockerfile": 551, "Batchfile": 395} | package com.smeup.rpgparser.interpreter
import com.smeup.rpgparser.parsing.ast.*
/**
* Expose interpreter core method that could be useful in statements logic implementation
**/
interface InterpreterCore {
val status: InterpreterStatus
val interpretationContext: InterpretationContext
val systemInterface: SystemInterface
val predefinedIndicators: HashMap<IndicatorKey, BooleanValue>
val klists: HashMap<String, List<String>>
val globalSymbolTable: SymbolTable
val localizationContext: LocalizationContext
fun log(logEntry: () -> LogEntry)
fun assign(target: AssignableExpression, value: Value): Value
fun assign(dataDefinition: AbstractDataDefinition, value: Value): Value
fun assign(target: AssignableExpression, value: Expression, operator: AssignmentOperator = AssignmentOperator.NORMAL_ASSIGNMENT): Value
fun assignEachElement(target: AssignableExpression, value: Value): Value
fun assignEachElement(target: AssignableExpression, value: Expression, operator: AssignmentOperator = AssignmentOperator.NORMAL_ASSIGNMENT): Value
operator fun get(data: AbstractDataDefinition): Value
operator fun get(dataName: String): Value
fun setPredefinedIndicators(statement: WithRightIndicators, hi: BooleanValue, lo: BooleanValue, eq: BooleanValue)
fun eval(expression: Expression): Value
fun execute(statements: List<Statement>)
fun dbFile(name: String, statement: Statement): DBFile
fun toSearchValues(searchArgExpression: Expression): List<RecordField>
fun fillDataFrom(record: Record)
fun exists(dataName: String): Boolean
fun dataDefinitionByName(name: String): AbstractDataDefinition?
fun mult(statement: MultStmt): Value
fun div(statement: DivStmt): Value
fun add(statement: AddStmt): Value
fun sub(statement: SubStmt): Value
fun rawRender(values: List<Value>): String
fun optimizedIntExpression(expression: Expression): () -> Long
fun enterCondition(index: Value, end: Value, downward: Boolean): Boolean
fun increment(dataDefinition: AbstractDataDefinition, amount: Long): Value
}
| 0 | null | 0 | 0 | a52bb6034582a03325b179c79b2c9a8ecd783a79 | 2,108 | jariko | Apache License 2.0 |
src/main/kotlin/net/sorenon/kevlar/CollectRigidBodiesAABBCallback.kt | Sorenon | 328,740,116 | false | {"Gradle": 2, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "INI": 1, "Java": 5, "JSON": 7, "Wavefront Object": 2, "Wavefront Material": 2, "Kotlin": 24} | package net.sorenon.kevlar
import com.badlogic.gdx.physics.bullet.collision.btBroadphaseAabbCallback
import com.badlogic.gdx.physics.bullet.collision.btBroadphaseProxy
import com.badlogic.gdx.physics.bullet.collision.btCollisionObject
import com.badlogic.gdx.physics.bullet.dynamics.btRigidBody
class CollectRigidBodiesAABBCallback: btBroadphaseAabbCallback() {
val rigidBodies = arrayListOf<btRigidBody>()
override fun process(proxy: btBroadphaseProxy): Boolean {
val obj = btCollisionObject.getInstance(proxy.clientObject)
if (obj is btRigidBody) {
rigidBodies.add(obj)
}
return true
}
} | 1 | null | 1 | 1 | 7f1c2710a1beb7bb90f06c3f63090c03e6f84ffb | 649 | Kevlar | Creative Commons Zero v1.0 Universal |
LeetCode/0455. Assign Cookies/Solution.kt | InnoFang | 86,413,001 | false | null | /**
* Created by <NAME> on 2018/1/31.
*/
/**
* 21 / 21 test cases passed.
* Status: Accepted
* Runtime: 623 ms
*/
class Solution {
fun findContentChildren(g: IntArray, s: IntArray): Int {
g.sortDescending()
s.sortDescending()
var gi = 0
var si = 0
var res = 0
while (gi < g.size && si < s.size) {
if (s[si] >= g[gi]) {
gi++
si++
res++
} else gi++
}
return res
}
}
fun main(args: Array<String>) {
Solution().findContentChildren(intArrayOf(1, 2, 3), intArrayOf(2, 3)).let(::println)
Solution().findContentChildren(intArrayOf(1, 2, 3), intArrayOf(1, 1)).let(::println)
} | 1 | C++ | 6 | 21 | 9c797b435fcff440f998027c471c2caf26258fa7 | 728 | algo-set | Apache License 2.0 |
app/src/main/java/com/az/pokedex/ui/Pokedex.kt | pranay999000 | 389,523,050 | true | {"Kotlin": 82038} | package com.az.pokedex.ui
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navArgument
import androidx.navigation.compose.rememberNavController
import com.az.pokedex.ui.view.pokemondetail.PokemonDetailView
import com.az.pokedex.ui.view.pokemonlist.PokemonListView
import com.google.accompanist.pager.ExperimentalPagerApi
@ExperimentalPagerApi
@Composable
fun Pokedex() {
val navController: NavHostController = rememberNavController()
NavHost(
navController = navController,
startDestination = "/pokemon_list"
) {
composable(
route = "/pokemon_list"
) {
PokemonListView(navController)
}
composable(
route = "/pokemon_detail/{pokemonId}/{dominantColor}/{dominantOnColor}",
arguments = listOf(
navArgument("pokemonId") { type = NavType.LongType },
navArgument("dominantColor") { type = NavType.IntType },
navArgument("dominantOnColor") { type = NavType.IntType },
)
) {
val pokemonId: Long = it.arguments?.getLong("pokemonId") ?: 1
val dominantColor: Int = it.arguments?.getInt("dominantColor") ?: 0
val dominantOnColor: Int = it.arguments?.getInt("dominantOnColor") ?: 0
PokemonDetailView(pokemonId, dominantColor, dominantOnColor)
}
}
} | 0 | null | 0 | 1 | ddce67d80c913223cb47e4227a81f81c93187f5f | 1,573 | Pokedex-V2 | MIT License |
src/main/java/top/zbeboy/isy/service/data/CollegeRoleServiceImpl.kt | zbeboy | 71,459,176 | false | null | package top.zbeboy.isy.service.data
import org.jooq.DSLContext
import org.jooq.Record
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import top.zbeboy.isy.domain.tables.daos.CollegeRoleDao
import javax.annotation.Resource
import top.zbeboy.isy.domain.Tables.COLLEGE_ROLE
import top.zbeboy.isy.domain.tables.pojos.CollegeRole
import top.zbeboy.isy.domain.tables.records.CollegeRoleRecord
import java.util.*
/**
* Created by zbeboy 2017-12-02 .
**/
@Service("collegeRoleService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
open class CollegeRoleServiceImpl @Autowired constructor(dslContext: DSLContext) : CollegeRoleService{
private val create: DSLContext = dslContext
@Resource
open lateinit var collegeRoleDao: CollegeRoleDao
override fun findByCollegeId(collegeId: Int): List<CollegeRoleRecord> {
return create.selectFrom(COLLEGE_ROLE)
.where(COLLEGE_ROLE.COLLEGE_ID.eq(collegeId))
.fetch()
}
override fun findByCollegeIdAndAllowAgent(collegeId: Int, allowAgent: Byte?): List<CollegeRoleRecord> {
return create.selectFrom(COLLEGE_ROLE)
.where(COLLEGE_ROLE.COLLEGE_ID.eq(collegeId).and(COLLEGE_ROLE.ALLOW_AGENT.eq(allowAgent)))
.fetch()
}
override fun findByRoleId(roleId: String): Optional<Record> {
return create.select()
.from(COLLEGE_ROLE)
.where(COLLEGE_ROLE.ROLE_ID.eq(roleId))
.fetchOptional()
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
override fun save(collegeRole: CollegeRole) {
collegeRoleDao.insert(collegeRole)
}
override fun update(collegeRole: CollegeRole) {
collegeRoleDao.update(collegeRole)
}
override fun deleteByRoleId(roleId: String) {
create.deleteFrom(COLLEGE_ROLE)
.where(COLLEGE_ROLE.ROLE_ID.eq(roleId))
.execute()
}
} | 7 | JavaScript | 2 | 7 | 9634602adba558dbdb945c114692019accdb50a9 | 2,155 | ISY | MIT License |
app/src/main/java/com/olshevchenko/currencyconverter/core/presentation/ViewState.kt | olshevchenko | 359,572,358 | false | null | package com.olshevchenko.currencyconverter.core.presentation
import com.olshevchenko.currencyconverter.features.converter.domain.model.CurrencyCodes
import com.olshevchenko.currencyconverter.features.converter.domain.model.CurrencyRate
typealias CodesViewState = ViewState<CurrencyCodes>
typealias RateViewState = ViewState<CurrencyRate>
typealias RefreshViewState = ViewState<String>
data class ViewState<T> private constructor(
val stateType: StateType,
val data: T? = null,
// val error: Exception? = null,
val errorDesc: String? = null
) {
companion object {
fun <T> init(): ViewState<T> =
ViewState(StateType.INIT)
fun <T> inProgress(): ViewState<T> =
ViewState(StateType.IN_PROGRESS)
fun <T> ready(): ViewState<T> =
ViewState(StateType.READY)
fun <T> success(data: T?): ViewState<T> =
ViewState(StateType.SUCCESS, data)
fun <T> error(data: T? = null, errorDesc: String?): ViewState<T> =
ViewState(StateType.ERROR, data, errorDesc = errorDesc)
}
enum class StateType {
INIT,
IN_PROGRESS,
READY,
SUCCESS,
ERROR,
}
}
| 0 | Kotlin | 0 | 0 | f73f70cb2b57989ed1e5d3dcaddfc1da36adc563 | 1,201 | CurrencyConverter-Kotlin | Apache License 2.0 |
samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Tooltips.kt | JetBrains | 440,164,967 | false | {"Kotlin": 1615027, "Java": 22778, "Shell": 361} | package org.jetbrains.jewel.samples.standalone.view.component
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.unit.dp
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.delay
import org.jetbrains.jewel.ui.component.CheckboxRow
import org.jetbrains.jewel.ui.component.DefaultButton
import org.jetbrains.jewel.ui.component.Text
import org.jetbrains.jewel.ui.component.Tooltip
@Composable
fun Tooltips() {
var toggleEnabled by remember { mutableStateOf(true) }
var enabled by remember { mutableStateOf(true) }
LaunchedEffect(toggleEnabled) {
if (!toggleEnabled) return@LaunchedEffect
while (true) {
delay(1.seconds)
enabled = !enabled
}
}
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp)) {
Tooltip(tooltip = { Text("This is a tooltip") }, enabled = enabled) {
// Any content works — this is a button just because it's focusable
DefaultButton({}) { Text("Hover me!") }
}
CheckboxRow("Enabled", enabled, { enabled = it })
CheckboxRow("Toggle enabled every 1s", toggleEnabled, { toggleEnabled = it })
}
}
| 94 | Kotlin | 39 | 722 | e0e6f1b4a46ca1c27ce1c13524ff11f75a2bed54 | 1,586 | jewel | Apache License 2.0 |
storage/src/test/kotlin/uk/tvidal/kraft/storage/StorageTest.kt | tvidal-net | 99,751,401 | false | null | package uk.tvidal.kraft.storage
import uk.tvidal.kraft.FIRST_INDEX
import uk.tvidal.kraft.codec.binary.BinaryCodec.IndexEntry
import uk.tvidal.kraft.codec.binary.computeSerialisedSize
import uk.tvidal.kraft.codec.binary.toProto
import uk.tvidal.kraft.storage.data.KRaftData
import uk.tvidal.kraft.storage.index.IndexEntryRange
import java.util.UUID
const val TEST_SIZE = 11
val testEntry = entryOf("12345678901", 11L)
val testEntryBytes = computeSerialisedSize(testEntry.toProto())
val testFileLength = INITIAL_OFFSET + TEST_SIZE * testEntryBytes
val testEntries = entries()
val testRange = testEntries.toIndex()
fun entries(size: Int = TEST_SIZE) = KRaftEntries(
(0 until size)
.map { testEntry }
)
fun rangeOf(vararg entries: IndexEntry) = rangeOf(entries.toList())
fun rangeOf(entries: Iterable<IndexEntry>) = IndexEntryRange(entries)
fun indexRange(
count: Int,
firstIndex: Long = FIRST_INDEX,
initialOffset: Int = INITIAL_OFFSET,
bytes: Int = TEST_SIZE
) =
IndexEntryRange(
(0 until count).map {
val index = firstIndex + it
val offset = initialOffset + (bytes * it)
indexEntry(index, offset, bytes)
}
)
fun indexEntry(
index: Long = 1L,
offset: Int = INITIAL_OFFSET,
bytes: Int = TEST_SIZE
): IndexEntry = IndexEntry.newBuilder()
.setId(UUID.randomUUID().toProto())
.setIndex(index)
.setOffset(offset)
.setBytes(bytes)
.build()
fun KRaftData.write(count: Int) = append(entries(count))
fun KRaftFile.write(count: Int) = append(entries(count))
fun KRaftFileStorage.writeAt(fromIndex: Long, count: Int) = append(entries(count), fromIndex)
fun KRaftEntries.toIndex(
fromIndex: Long = FIRST_INDEX,
initialOffset: Int = INITIAL_OFFSET
) = IndexEntryRange(
mapIndexed { i, it ->
IndexEntry.newBuilder()
.setId(it.id.toProto())
.setIndex(fromIndex + i)
.setOffset(initialOffset + i * testEntryBytes)
.setBytes(testEntryBytes)
.build()
}
)
| 1 | Kotlin | 0 | 0 | 9cfca67330b27c1f2f834dc430d3a369d2538255 | 2,050 | kraft | MIT License |
chargeback/validation/src/main/kotlin/com/amazon/paymentsfiles/ChargebackContextChecks.kt | amzn | 285,929,660 | false | null | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazon.paymentsfiles
import java.util.Currency
/**
* Context validation function to ensure that a record's Disputed Amount has the proper number of decimal places
* expected for the corresponding Currency
* @param record a CSVEntry object being examined
* @return a FieldError object if the check fails and null otherwise
*/
fun checkCurrencyFields(record: CSVEntry): FieldError? = try {
val currency = Currency.getInstance(record.get(ChargebackField.Currency))
val amount = record.get(ChargebackField.DisputedAmount).toBigDecimal()
if (amount.scale() == currency.defaultFractionDigits) null
else StandardChargebackError.DisputedAmountContext.error
} catch (e: IllegalArgumentException) {
null
}
val contextChecks = listOf(::checkCurrencyFields)
/**
* CSVEntry extension function that performs additional validation checks across multiple fields of a chargeback entry
*/
fun CSVEntry.validateContext(): List<FieldError> = contextChecks.mapNotNull { check -> check(this) }
| 0 | Kotlin | 5 | 7 | 8b02668cba3dcc266fdd49e76ed38d452bad7492 | 1,125 | amazon-payment-files-tools | Apache License 2.0 |
app/src/main/java/com/example/helloworld/crypto/hash/HashHelper.kt | buddingleader | 198,601,451 | false | null | package com.example.helloworld.crypto.hash
import com.example.helloworld.utils.HexUtil
import java.security.MessageDigest
object HashHelper {
fun sha256(str: ByteArray): String {
val digest = MessageDigest.getInstance("SHA-256")
val result = digest.digest(str)
return HexUtil.bytesToHex(result)
}
} | 0 | Kotlin | 0 | 0 | 415a820b9564febed4d116f6c1e2347a4078a70c | 333 | AndroidTEE | MIT License |
data/src/main/java/com/quangnguyen/data/mapper/ImageMapperImpl.kt | quangctkm9207 | 126,580,618 | false | {"Kotlin": 56258} | package com.quangnguyen.data.mapper
import com.quangnguyen.data.model.ImageModel
import com.quangnguyen.hoga.domain.entity.Image
class ImageMapperImpl: ImageMapper {
override fun dataToDomain(imageModel: ImageModel): Image {
return Image(imageModel.id, imageModel.urls.small, imageModel.urls.full, imageModel.user.name, imageModel.downloadedFilePath)
}
} | 0 | Kotlin | 6 | 12 | 88dcf301cda74c939de1ccc97ba7e5100ede7be5 | 365 | android-clean-architecture-hoga | MIT License |
app/src/main/java/com/merxury/blocker/ui/component/ComponentFragment.kt | lihenggui | 115,417,337 | false | null | package com.merxury.blocker.ui.component
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.*
import android.widget.PopupMenu
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.SearchView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.elvishew.xlog.XLog
import com.merxury.blocker.R
import com.merxury.blocker.baseview.ContextMenuRecyclerView
import com.merxury.blocker.core.root.EControllerMethod
import com.merxury.blocker.ui.Constants
import com.merxury.blocker.util.PreferenceUtil
import com.merxury.blocker.util.ToastUtil
import kotlinx.android.synthetic.main.component_item.view.*
import kotlinx.android.synthetic.main.fragment_component.*
import kotlinx.android.synthetic.main.fragment_component.view.*
import moe.shizuku.api.ShizukuApiConstants
class ComponentFragment : Fragment(), ComponentContract.View, ComponentContract.ComponentItemListener {
override lateinit var presenter: ComponentContract.Presenter
private lateinit var componentAdapter: ComponentsRecyclerViewAdapter
private lateinit var packageName: String
private lateinit var type: EComponentType
private val logger = XLog.tag("ComponentFragment").build()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
type = arguments?.getSerializable(Constants.CATEGORY) as EComponentType
packageName = arguments?.getString(Constants.PACKAGE_NAME) ?: ""
presenter = ComponentPresenter(requireContext(), this, packageName)
initShizuku()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val root = inflater.inflate(R.layout.fragment_component, container, false)
with(root) {
componentListSwipeLayout.apply {
setColorSchemeColors(
ContextCompat.getColor(context, R.color.colorPrimary),
ContextCompat.getColor(context, R.color.colorAccent),
ContextCompat.getColor(context, R.color.colorPrimaryDark)
)
setOnRefreshListener {
presenter.loadComponents(packageName, type)
}
}
componentListFragmentRecyclerView.apply {
val layoutManager = LinearLayoutManager(context)
this.layoutManager = layoutManager
componentAdapter = ComponentsRecyclerViewAdapter()
componentAdapter.setOnClickListener(this@ComponentFragment)
this.adapter = componentAdapter
this.itemAnimator = DefaultItemAnimator()
addItemDecoration(DividerItemDecoration(context, layoutManager.orientation))
registerForContextMenu(this)
}
}
setHasOptionsMenu(true)
return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
presenter.loadComponents(packageName, type)
}
override fun onDestroy() {
presenter.destroy()
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.list_fragment_menu, menu)
val searchItem = menu.findItem(R.id.menu_search)
val searchView = searchItem?.actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(newText: String): Boolean {
searchForComponent(newText)
return true
}
override fun onQueryTextSubmit(query: String): Boolean {
searchForComponent(query)
return true
}
})
searchView.setOnSearchClickListener {
setItemsVisibility(menu, searchItem, false)
}
searchView.setOnCloseListener {
setItemsVisibility(menu, searchItem, true)
false
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_filter -> showFilteringPopUpMenu()
R.id.menu_refresh -> presenter.loadComponents(packageName, type)
R.id.menu_block_all -> showDisableAllAlert()
R.id.menu_enable_all -> {
Toast.makeText(context, R.string.enabling_hint, Toast.LENGTH_SHORT).show()
presenter.enableAllComponents(packageName, type)
}
R.id.menu_export_rule -> presenter.exportRule(packageName)
R.id.menu_import_rule -> {
presenter.importRule(packageName)
}
}
return true
}
override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
activity?.menuInflater?.inflate(R.menu.component_list_long_click_menu, menu)
if (type != EComponentType.ACTIVITY) {
menu.removeItem(R.id.launch_activity)
}
context?.let {
if (PreferenceUtil.getControllerType(it) == EControllerMethod.IFW) {
menu.removeItem(R.id.block_by_ifw)
menu.removeItem(R.id.enable_by_ifw)
}
}
}
override fun onContextItemSelected(item: MenuItem): Boolean {
if (!userVisibleHint) {
return false
}
val position = (item.menuInfo as ContextMenuRecyclerView.RecyclerContextMenuInfo).position
val component = componentAdapter.getDataAt(position)
when (item.itemId) {
R.id.block_by_ifw -> presenter.addToIFW(component.packageName, component.name, type)
R.id.enable_by_ifw -> presenter.removeFromIFW(component.packageName, component.name, type)
R.id.launch_activity -> presenter.launchActivity(component.packageName, component.name)
R.id.copy_component_name -> copyToClipboard(component.simpleName)
R.id.copy_full_name -> copyToClipboard(component.name)
}
return true
}
override fun setLoadingIndicator(active: Boolean) {
componentListSwipeLayout?.run {
post { isRefreshing = active }
}
}
override fun showNoComponent() {
componentListFragmentRecyclerView?.visibility = View.GONE
noComponentContainer?.visibility = View.VISIBLE
}
override fun searchForComponent(name: String) {
componentAdapter.filter(name)
}
override fun showFilteringPopUpMenu() {
PopupMenu(activity, activity?.findViewById(R.id.menu_filter)).apply {
menuInflater.inflate(R.menu.filter_component, menu)
setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.name_asc -> presenter.currentComparator = EComponentComparatorType.SIMPLE_NAME_ASCENDING
R.id.name_des -> presenter.currentComparator = EComponentComparatorType.SIMPLE_NAME_DESCENDING
R.id.package_name_asc -> presenter.currentComparator = EComponentComparatorType.NAME_ASCENDING
R.id.package_name_des -> presenter.currentComparator = EComponentComparatorType.NAME_DESCENDING
}
presenter.loadComponents(packageName, type)
true
}
show()
}
}
override fun refreshComponentState(componentName: String) {
val viewModel = presenter.getComponentViewModel(packageName, componentName)
componentAdapter.updateViewModel(viewModel)
}
override fun showAlertDialog(message: String?) {
context?.apply {
AlertDialog.Builder(this)
.setTitle(resources.getString(R.string.oops))
.setMessage(getString(R.string.no_root_error_message, message))
.setPositiveButton(R.string.close) { dialog: DialogInterface, _: Int -> dialog.dismiss() }
.show()
}
}
override fun showComponentList(components: MutableList<ComponentItemViewModel>) {
noComponentContainer?.visibility = View.GONE
componentListFragmentRecyclerView?.visibility = View.VISIBLE
componentAdapter.updateData(components)
}
override fun onComponentClick(name: String) {
}
override fun onComponentLongClick(name: String) {
}
override fun onSwitchClick(name: String, isChecked: Boolean) {
if (isChecked) {
presenter.enable(packageName, name)
} else {
presenter.disable(packageName, name)
}
}
override fun showDisableAllAlert() {
AlertDialog.Builder(requireContext())
.setTitle(R.string.warning)
.setMessage(R.string.warning_disable_all_component)
.setCancelable(true)
.setNegativeButton(R.string.cancel) { dialog, _ -> dialog.dismiss() }
.setPositiveButton(R.string.ok) { _, _ ->
Toast.makeText(requireContext(), R.string.disabling_hint, Toast.LENGTH_SHORT).show()
presenter.disableAllComponents(packageName, type)
}
.create()
.show()
}
override fun showActionDone() {
Toast.makeText(context, R.string.done, Toast.LENGTH_SHORT).show()
}
override fun showActionFail() {
Toast.makeText(context, R.string.fail, Toast.LENGTH_SHORT).show()
}
override fun showImportFail() {
Toast.makeText(context, R.string.import_fail_message, Toast.LENGTH_SHORT).show()
}
override fun showToastMessage(message: String?, length: Int) {
ToastUtil.showToast(message ?: "null", length)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
logger.d("Request permission back, $requestCode, $permissions, $grantResults")
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED && requestCode == REQUEST_CODE_PERMISSION) {
logger.d("Shizuku permission granted")
}
}
private fun initShizuku() {
val context = requireContext()
if (PreferenceUtil.getControllerType(context) != EControllerMethod.SHIZUKU) {
return
}
logger.d("Request shizuku permission")
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
logger.e("Shizuku does not support Android 5.1 or below")
return
}
if (ContextCompat.checkSelfPermission(context, ShizukuApiConstants.PERMISSION) == PackageManager.PERMISSION_GRANTED) {
return
} else if (ActivityCompat.shouldShowRequestPermissionRationale(requireActivity(), ShizukuApiConstants.PERMISSION)) {
logger.e("User denied Shizuku permission")
return
} else {
ActivityCompat.requestPermissions(requireActivity(), arrayOf(SHIZUKU_PERMISSION_V23), REQUEST_CODE_PERMISSION)
}
}
private fun setItemsVisibility(menu: Menu, exception: MenuItem, visible: Boolean) {
for (i in 0 until menu.size()) {
val item = menu.getItem(i)
if (item !== exception)
item.isVisible = visible
}
}
private fun copyToClipboard(content: String) {
val clipboard = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
?: return
val clip = ClipData.newPlainText(getString(R.string.component_name), content)
clipboard.setPrimaryClip(clip)
Toast.makeText(requireContext(), R.string.copied, Toast.LENGTH_SHORT).show()
}
companion object {
private const val SHIZUKU_PERMISSION_V23 = "moe.shizuku.manager.permission.API_V23"
private const val REQUEST_CODE_PERMISSION = 101
fun newInstance(packageName: String, type: EComponentType): Fragment {
val fragment = ComponentFragment()
val bundle = Bundle()
bundle.putSerializable(Constants.CATEGORY, type)
bundle.putString(Constants.PACKAGE_NAME, packageName)
fragment.arguments = bundle
return fragment
}
}
inner class ComponentsRecyclerViewAdapter(
private var components: MutableList<ComponentItemViewModel> = mutableListOf())
: RecyclerView.Adapter<ComponentsRecyclerViewAdapter.ViewHolder>() {
private lateinit var pm: PackageManager
private var listCopy = ArrayList<ComponentItemViewModel>()
private lateinit var listener: ComponentContract.ComponentItemListener
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.component_item, parent, false)
pm = parent.context.packageManager
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindComponent(this.components[position])
holder.itemView.isLongClickable = true
}
override fun getItemCount(): Int {
return this.components.size
}
fun updateData(components: MutableList<ComponentItemViewModel>) {
this.components = components
this.listCopy = ArrayList(components)
notifyDataSetChanged()
}
fun getDataAt(index: Int): ComponentItemViewModel {
return components[index]
}
fun updateViewModel(viewModel: ComponentItemViewModel) {
components.forEachIndexed { i, model ->
if (model.name == viewModel.name) {
components[i] = viewModel
notifyItemChanged(i)
}
}
listCopy.forEachIndexed { i, model ->
if (model.name == viewModel.name) {
listCopy[i] = viewModel
}
}
}
fun filter(keyword: String) {
components = if (keyword.isEmpty()) {
listCopy
} else {
listCopy.asSequence().filter { it.name.contains(keyword, true) }.toMutableList()
}
notifyDataSetChanged()
}
fun setOnClickListener(listener: ComponentContract.ComponentItemListener) {
this.listener = listener
}
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindComponent(component: ComponentItemViewModel) {
with(itemView) {
component_name.text = component.simpleName
component_package_name.text = component.name
component_switch.isChecked = component.state && component.ifwState
setOnClickListener {
listener.onSwitchClick(component.name, !it.component_switch.isChecked)
it.component_switch.isChecked = !it.component_switch.isChecked
}
component_switch.setOnClickListener {
listener.onSwitchClick(component.name, it.component_switch.isChecked)
}
if (component.isRunning) {
itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.md_light_blue_50))
} else {
itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.md_white_1000))
}
}
}
}
}
} | 11 | null | 28 | 237 | a51b75c16303b9837bed72181ab7007cf8a59625 | 16,337 | blocker | Apache License 2.0 |
src/main/kotlin/com/onegravity/sudoku/model/region/ExtraRegion.kt | 1gravity | 407,597,760 | false | {"Kotlin": 148326} | package com.onegravity.sudoku.model.region
import com.onegravity.sudoku.model.Cell
import com.onegravity.sudoku.model.Puzzle
import com.onegravity.sudoku.model.mapCodes2Indices
/**
* ExtraRegion defines an extra region in the puzzle (beyond the regular Regions Block, Row and Column).
*
* @param puzzle We need the Puzzle to retrieve the Cells that are part of this ExtraRegion.
* @param regionType The type of ExtraRegion (X, Hyper, Color etc.)
* @param regionCode The regionCode defines which ExtraRegion this is. It's the equivalent to the blockCode for Blocks.
* @param regionCodes The regionCodes defines which Cells are part of which region. Together with the regionCode this
* ExtraRegion can determine which cells are part of this region.
*/
abstract class ExtraRegion(
private val puzzle: Puzzle,
regionType: RegionType,
regionCode: Int,
private vararg val regionCodes: IntArray
) : Region(regionType, regionCode) {
init {
assert(regionType.isExtraRegion)
}
open val nrOfRegions: Int = 1
@Suppress("UNCHECKED_CAST")
override val cells by lazy {
val cells = ArrayList<Cell>()
val cellIndices = mapCodes2Indices(regionCodes[0])[regionCode]
cellIndices?.forEach { index ->
cells.add(puzzle.getCell(index))
}
cells
}
override fun toString() = "${regionType.name} $regionCode/$nrOfRegions"
override fun compareTo(other: Region) =
when (other is ExtraRegion) {
true -> if (
regionType == other.regionType &&
regionCode == other.regionCode &&
cells.containsAll(other.cells)
) 0 else -1
else -> -1
}
}
| 0 | Kotlin | 0 | 1 | 4e8bfb119a57a101db4d873bf86cd5722105ebb3 | 1,727 | Dancing-Links-Kotlin | Apache License 2.0 |
buildSrc/src/main/java/ConfigData.kt | Ahabdelhak | 535,852,545 | false | {"Kotlin": 134308} | /*
* Copyright 2022 AHMED ABDELHAK. 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.
*/
object ConfigData {
const val compileSdkVersion = 32
const val buildToolsVersion = "30.0.3"
const val minSdkVersion = 21
const val targetSdkVersion = 32
const val versionCode = 1
const val versionName = "1.0"
}
| 0 | Kotlin | 1 | 4 | 46a82e6c0c86b700f996a912547bf4f1fae70d82 | 843 | InstaCrypto | Apache License 2.0 |
app/src/main/java/com/jumpingphantom/flow/features/dialog/ui/UiEvent.kt | JumpingPhantom | 811,400,534 | false | {"Kotlin": 109236} | package com.jumpingphantom.flow.features.dialog.ui
import com.jumpingphantom.flow.core.data.common.PaymentMethod
import com.jumpingphantom.flow.core.data.common.TransactionType
import com.jumpingphantom.flow.core.data.entity.Subcategory
sealed interface UiEvent {
data class SetAmount(val amount: String) : UiEvent
data class SetDate(val date: Long) : UiEvent
data class SetType(val type: TransactionType) : UiEvent
data class SetMethod(val method: PaymentMethod) : UiEvent
data class SetSubcategory(val subcategory: Subcategory) : UiEvent
data class SetInputError(val errorState: Boolean) : UiEvent
data class SetCategoryError(val errorState: Boolean) : UiEvent
data object AddTransaction: UiEvent
} | 0 | Kotlin | 0 | 0 | 7c82814773d647043401c8e67781af0cae0947a9 | 734 | Flow | MIT License |
correlation/core/domain/src/main/kotlin/org/sollecitom/chassis/correlation/core/domain/toggles/ToggleValue.kt | sollecitom | 669,483,842 | false | {"Kotlin": 831362, "Java": 30834} | package org.sollecitom.chassis.correlation.core.domain.toggles
import org.sollecitom.chassis.core.domain.traits.Identifiable
sealed interface ToggleValue<out VALUE : Any> : Identifiable {
val value: VALUE
companion object
} | 0 | Kotlin | 0 | 2 | e4e3403e46f7358a03c8ee3520b3b94be679792b | 235 | chassis | MIT License |
RetenoSdkCore/src/main/java/com/reteno/core/data/remote/model/iam/displayrules/targeting/InAppWithTime.kt | reteno-com | 545,381,514 | false | {"Kotlin": 1371838, "Java": 161863, "HTML": 17807, "Shell": 379} | package com.reteno.core.data.remote.model.iam.displayrules.targeting
import com.reteno.core.data.remote.model.iam.message.InAppMessage
data class InAppWithTime(
val inApp: InAppMessage,
val time: Long
) | 1 | Kotlin | 2 | 1 | 2c859bd78f495efbfa69ad7d70edd9d547252df2 | 212 | reteno-mobile-android-sdk | MIT License |
jsfring-webservice/src/main/kotlin/fr/pinguet62/jsfring/webservice/controller/UserController.kt | pinguet62 | 20,840,724 | false | {"Java": 489593, "HTML": 76385, "Rich Text Format": 32564, "TypeScript": 31995, "Kotlin": 23485, "JavaScript": 21937, "CSS": 2295, "Dockerfile": 1199, "Python": 593, "TSQL": 35} | package fr.pinguet62.jsfring.webservice.controller
import fr.pinguet62.jsfring.model.sql.User
import fr.pinguet62.jsfring.service.UserService
import fr.pinguet62.jsfring.webservice.controller.UserController.Companion.PATH
import fr.pinguet62.jsfring.webservice.converter.UserMapper
import fr.pinguet62.jsfring.webservice.dto.UserDto
import org.springframework.web.bind.annotation.*
import reactor.core.publisher.Flux
@RestController
@RequestMapping(PATH)
class UserController(
val userService: UserService,
val converter: UserMapper
) {
companion object {
const val PATH = "/user"
}
@PutMapping
fun create(@RequestBody userDto: UserDto) {
var user: User = converter.fromDto(userDto)
userService.create(user)
}
@GetMapping("/{email:.+}")
fun get(@PathVariable email: String) =
userService
.get(email)
.map { converter.toDto(it) }
@GetMapping
fun list(): Flux<UserDto> =
userService
.getAll()
.map { converter.toDto(it) }
@PostMapping
fun update(@RequestBody userDto: UserDto) {
userService
.get(userDto.email)
.doOnNext { converter.updateFromDto(it, userDto) }
.doOnNext { userService.update(it) }
}
} | 1 | null | 1 | 1 | ee8ff590113f2f0a992259f4044a0497f84b207e | 1,356 | JSFring | Apache License 2.0 |
app/src/main/java/com/kickstarter/services/LakeService.kt | garcias082 | 231,163,796 | true | {"Java Properties": 2, "Gradle": 4, "Shell": 4, "Markdown": 3, "Batchfile": 1, "Ruby": 20, "Gemfile.lock": 1, "Ignore List": 3, "Makefile": 1, "Git Config": 1, "SVG": 4, "YAML": 2, "XML": 397, "Text": 4, "Java": 483, "Kotlin": 206, "INI": 1, "JSON": 8, "GraphQL": 5} | package com.kickstarter.services
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Headers
import retrofit2.http.PUT
import rx.Observable
interface LakeService {
@Headers("Content-Type: application/json")
@PUT("record")
fun track(@Body body: RequestBody) : Observable<Response<ResponseBody>>
}
| 0 | null | 0 | 0 | 494a34f551b895473c826e04104c49acd93b7395 | 389 | android-oss | Apache License 2.0 |
src/main/kotlin/com/koresframework/kores/bytecode/processor/processors/InstanceOfProcessor.kt | JonathanxD | 77,163,846 | false | {"Git Config": 1, "Gradle": 4, "YAML": 4, "Markdown": 4, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Java": 63, "Kotlin": 108} | /*
* Kores-BytecodeWriter - Translates Kores Structure to JVM Bytecode <https://github.com/JonathanxD/CodeAPI-BytecodeWriter>
*
* The MIT License (MIT)
*
* Copyright (c) 2021 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <<EMAIL>>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.koresframework.kores.bytecode.processor.processors
import com.koresframework.kores.base.InstanceOfCheck
import com.koresframework.kores.bytecode.processor.IN_EXPRESSION
import com.koresframework.kores.bytecode.processor.METHOD_VISITOR
import com.koresframework.kores.bytecode.processor.incrementInContext
import com.koresframework.kores.processor.Processor
import com.koresframework.kores.processor.ProcessorManager
import com.koresframework.kores.type.internalName
import com.github.jonathanxd.iutils.data.TypedData
import com.github.jonathanxd.iutils.kt.require
import org.objectweb.asm.Opcodes
object InstanceOfProcessor : Processor<InstanceOfCheck> {
override fun process(
part: InstanceOfCheck,
data: TypedData,
processorManager: ProcessorManager<*>
) {
val visitor = METHOD_VISITOR.require(data).methodVisitor
val checkPart = part.part
val codeType = part.checkType
IN_EXPRESSION.incrementInContext(data) {
processorManager.process(checkPart::class.java, checkPart, data)
}
visitor.visitTypeInsn(Opcodes.INSTANCEOF, codeType.internalName)
}
} | 7 | Kotlin | 0 | 1 | 8324bd03a52ddf5f12dd54c8d7459f83a000ed9a | 2,620 | CodeAPI-BytecodeWriter | MIT License |
code/JL_OTA_V1.7.3_SDK_V1.9.2/otasdk/src/main/java/com/jieli/otasdk_autotest/tool/auto/OnTaskListener.kt | Jieli-Tech | 274,283,026 | false | {"Text": 2, "Markdown": 3, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 1, "Kotlin": 76, "Java": 57, "XML": 88, "INI": 1} | package com.jieli.otasdk_autotest.tool.auto
/**
* @author zqjasonZhong
* @since 2022/9/14
* @email <EMAIL>
* @desc 任务事件监听器
*/
interface OnTaskListener {
fun onStart(message: String?)
fun onLogcat(log: String?)
fun onFinish(code: Int, message: String?)
} | 1 | Java | 12 | 16 | 041e6aa3e18421585a179eace4fd8b56d5f631ee | 275 | Android-JL_OTA | Apache License 2.0 |
app/src/main/java/com/rmakiyama/cap/ui/extension/LazyDsl.kt | rmakiyama | 548,899,765 | false | null | package com.rmakiyama.cap.ui.extension
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
fun LazyListScope.sampleItem(
modifier: Modifier = Modifier,
backgroundColor: Color? = null,
content: @Composable () -> Unit,
) {
item {
Box(
modifier = modifier
.fillMaxWidth()
.background(backgroundColor ?: MaterialTheme.colorScheme.primaryContainer)
.padding(horizontal = 16.dp, vertical = 24.dp)
) {
content()
}
}
}
| 0 | Kotlin | 0 | 0 | 1bb7b4afe46f33dd6a8f51dce483993da59101ec | 932 | compose-animation-playground | MIT License |
backend/data/src/main/kotlin/io/tolgee/model/views/TranslationMemoryItemView.kt | tolgee | 303,766,501 | false | null | package io.tolgee.model.views
interface TranslationMemoryItemView {
val baseTranslationText: String
val targetTranslationText: String
val keyName: String
val similarity: Float
}
| 100 | Kotlin | 40 | 666 | 38c1064783f3ec5d60d0502ec0420698395af539 | 187 | tolgee-platform | Apache License 2.0 |
src/test/kotlin/com/jackchapman/adventofcode/Day04Test.kt | crepppy | 317,691,375 | false | null | package com.jackchapman.adventofcode
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
internal class Day04Test {
@Test
fun `test passport has fields`() {
val pass1 = """
ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm
""".trimIndent()
assertTrue(isValidPassport(pass1, false))
val pass2 = """
iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929
""".trimIndent()
assertFalse(isValidPassport(pass2, false))
val pass3 = """
hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm
""".trimIndent()
assertTrue(isValidPassport(pass3, false))
val pass4 = """
hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in
""".trimIndent()
assertFalse(isValidPassport(pass4, false))
}
@Test
fun `test passport has valid fields`() {
val batch = """
eyr:1972 cid:100
hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926
iyr:2019
hcl:#602927 eyr:1967 hgt:170cm
ecl:grn pid:012533040 byr:1946
hcl:dab227 iyr:2012
ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277
hgt:59cm ecl:zzz
eyr:2038 hcl:74454a iyr:2023
pid:3556412378 byr:2007
pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980
hcl:#623a2f
eyr:2029 ecl:blu cid:129 byr:1989
iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm
hcl:#888785
hgt:164cm byr:2001 iyr:2015 cid:88
pid:545766238 ecl:hzl
eyr:2022
iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719
""".trimIndent().split("\n\n")
assertFalse(isValidPassport(batch[0]))
assertFalse(isValidPassport(batch[1]))
assertFalse(isValidPassport(batch[2]))
assertFalse(isValidPassport(batch[3]))
assertTrue(isValidPassport(batch[4]))
assertTrue(isValidPassport(batch[5]))
assertTrue(isValidPassport(batch[6]))
assertTrue(isValidPassport(batch[7]))
}
} | 0 | Kotlin | 0 | 0 | b49bb8f62b4542791626950846ca07d1eff4f2d1 | 2,384 | aoc2020 | The Unlicense |
src/test/kotlin/aoc2022/Day16Test.kt | w8mr | 572,700,604 | false | {"Kotlin": 140954} | package aoc2022
import kotlin.test.Test
import aoc.*
internal class Day16Test {
private val subject = Day16()
private val year = 2022
private val day = 16
private val testInput = readFile(year, day, 1).readText()
private val input = readFile(year, day).readText()
@Test
fun testPart1TestInput() {
subject.testSafe(year, day, 1, false, 1651) { part1(testInput) }
}
@Test
fun testPart1RealInput() {
subject.testSafe(year, day, 1, true, 1991) { part1(input) }
}
@Test
fun testPart2TestInput() {
subject.testSafe(year, day, 2, false, 1707) { part2(testInput) }
}
@Test
fun testPart2RealInput() {
subject.testSafe(year, day, 2, true, 2705) { part2(input) }
}
} | 0 | Kotlin | 0 | 0 | e9bd07770ccf8949f718a02db8d09daf5804273d | 764 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/com/mastrodaro/earthquakes/Application.kt | mastrodaro | 248,083,006 | false | null | package com.mastrodaro.earthquakes
import com.google.gson.Gson
import com.mastrodaro.earthquakes.io.ConsolePrinter
import com.mastrodaro.earthquakes.io.ConsoleReader
import com.mastrodaro.earthquakes.io.InputReader
import com.mastrodaro.earthquakes.provider.EarthquakesProvider
import com.mastrodaro.earthquakes.provider.HttpClient
import com.mastrodaro.earthquakes.utils.DistanceCalculator
import kotlinx.coroutines.runBlocking
import org.koin.core.KoinComponent
import org.koin.core.context.startKoin
import org.koin.core.inject
import org.koin.dsl.module
val gson = Gson()
val appModule = module {
single { ConsoleReader(get()) }
single { ConsolePrinter() }
single { InputReader() }
single { EarthquakesProvider(get(), gson) }
single { HttpClient() }
single { DistanceCalculator() }
single { EarthquakesReporter(get(), get(), get(), get()) }
}
class Application : KoinComponent {
private val reporter by inject<EarthquakesReporter>()
fun run() = runBlocking {
reporter.start()
}
}
fun main() {
startKoin {
modules(appModule)
}
Application().run()
}
| 0 | Kotlin | 0 | 0 | dcbb257f3f920c90b836a4b5be19f57da1333566 | 1,126 | nearby-earthquakes | MIT License |
src/test/kotlin/br/com/webbudget/services/registration/FinancialPeriodServiceITest.kt | web-budget | 354,665,828 | false | null | package br.com.webbudget.services.registration
import br.com.webbudget.BaseIntegrationTest
import br.com.webbudget.domain.entities.registration.FinancialPeriod
import br.com.webbudget.domain.exceptions.BusinessException
import br.com.webbudget.domain.exceptions.ConflictingPropertyException
import br.com.webbudget.domain.services.registration.FinancialPeriodService
import br.com.webbudget.infrastructure.repository.registration.FinancialPeriodRepository
import br.com.webbudget.utilities.fixture.createFinancialPeriod
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.fail
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.jdbc.Sql
import java.math.BigDecimal
import java.time.LocalDate
import java.util.UUID
class FinancialPeriodServiceITest : BaseIntegrationTest() {
@Autowired
private lateinit var financialPeriodRepository: FinancialPeriodRepository
@Autowired
private lateinit var financialPeriodService: FinancialPeriodService
@Test
@Sql("/sql/registration/clear-tables.sql")
fun `should create`() {
val financialPeriod = createFinancialPeriod()
val externalId = financialPeriodService.create(financialPeriod)
val saved = financialPeriodRepository.findByExternalId(externalId) ?: fail { OBJECT_NOT_FOUND_ERROR }
assertThat(saved).satisfies({
assertThat(it.id).isNotNull()
assertThat(it.externalId).isEqualTo(externalId)
assertThat(it.version).isZero()
assertThat(it.createdOn).isNotNull()
assertThat(it.lastUpdate).isNotNull()
assertThat(it.status).isEqualTo(financialPeriod.status)
assertThat(it.name).isEqualTo(financialPeriod.name)
assertThat(it.startingAt).isEqualTo(financialPeriod.startingAt)
assertThat(it.endingAt).isEqualTo(financialPeriod.endingAt)
})
}
@Test
@Sql(
"/sql/registration/clear-tables.sql",
"/sql/registration/create-financial-period.sql"
)
fun `should fail to create if name is duplicated`() {
val financialPeriod = createFinancialPeriod(
name = "08/2024",
startingAt = LocalDate.of(2024, 7, 1),
endingAt = LocalDate.of(2024, 7, 31)
)
assertThatThrownBy { financialPeriodService.create(financialPeriod) }
.isInstanceOf(ConflictingPropertyException::class.java)
}
@Test
@Sql(
"/sql/registration/clear-tables.sql",
"/sql/registration/create-financial-period.sql"
)
fun `should fail to create if periods overlap`() {
val start = LocalDate.of(2024, 8, 1)
val end = start.plusDays(15)
val financialPeriod = createFinancialPeriod(name = "Agosto", startingAt = start, endingAt = end)
assertThatThrownBy { financialPeriodService.create(financialPeriod) }
.isInstanceOf(BusinessException::class.java)
.hasMessage("Period start and end dates are overlap with other open periods")
}
@Test
@Sql("/sql/registration/clear-tables.sql")
fun `should fail to create if start date is after end date`() {
val financialPeriod = createFinancialPeriod(
name = "09/2024",
startingAt = LocalDate.of(2024, 9, 30),
endingAt = LocalDate.of(2024, 9, 1)
)
assertThatThrownBy { financialPeriodService.create(financialPeriod) }
.isInstanceOf(BusinessException::class.java)
.hasMessage("Start date must be before end date")
}
@Test
@Sql(
"/sql/registration/clear-tables.sql",
"/sql/registration/create-financial-period.sql"
)
fun `should update`() {
val externalId = UUID.fromString("27881a12-5e61-43cd-a6d0-fdb32eaa75c0")
val toUpdate = financialPeriodRepository.findByExternalId(externalId) ?: fail { OBJECT_NOT_FOUND_ERROR }
toUpdate.apply {
this.name = "09/2024"
this.startingAt = LocalDate.of(2024, 9, 1)
this.endingAt = LocalDate.of(2024, 9, 30)
this.revenuesGoal = BigDecimal.TWO
this.expensesGoal = BigDecimal.TEN
}
financialPeriodService.update(toUpdate)
val updated = financialPeriodRepository.findByExternalId(externalId) ?: fail { OBJECT_NOT_FOUND_ERROR }
assertThat(updated).satisfies({
assertThat(it.id).isNotNull()
assertThat(it.externalId).isEqualTo(externalId)
assertThat(it.version).isGreaterThan(toUpdate.version)
assertThat(it.createdOn).isEqualTo(toUpdate.createdOn)
assertThat(it.lastUpdate).isAfter(toUpdate.lastUpdate)
assertThat(it.status).isEqualTo(toUpdate.status)
assertThat(it.name).isEqualTo(toUpdate.name)
assertThat(it.startingAt).isEqualTo(toUpdate.startingAt)
assertThat(it.endingAt).isEqualTo(toUpdate.endingAt)
})
}
@Test
@Sql(
"/sql/registration/clear-tables.sql",
"/sql/registration/create-financial-period.sql"
)
fun `should fail to update if name is duplicated`() {
val financialPeriod = createFinancialPeriod(
name = "10/2024",
startingAt = LocalDate.of(2024, 10, 1),
endingAt = LocalDate.of(2024, 10, 31)
)
val externalId = financialPeriodService.create(financialPeriod)
val toUpdate = financialPeriodRepository.findByExternalId(externalId) ?: fail { OBJECT_NOT_FOUND_ERROR }
toUpdate.apply {
this.name = "08/2024"
}
assertThatThrownBy { financialPeriodService.update(toUpdate) }
.isInstanceOf(ConflictingPropertyException::class.java)
}
@Test
@Sql(
"/sql/registration/clear-tables.sql",
"/sql/registration/create-financial-period.sql"
)
fun `should fail to update if periods overlap`() {
val financialPeriod = createFinancialPeriod(
name = "10/2024",
startingAt = LocalDate.of(2024, 10, 1),
endingAt = LocalDate.of(2024, 10, 31)
)
val externalId = financialPeriodService.create(financialPeriod)
val toUpdate = financialPeriodRepository.findByExternalId(externalId) ?: fail { OBJECT_NOT_FOUND_ERROR }
toUpdate.apply {
this.startingAt = LocalDate.of(2024, 8, 1)
this.endingAt = LocalDate.of(2024, 8, 31)
}
assertThatThrownBy { financialPeriodService.update(toUpdate) }
.isInstanceOf(BusinessException::class.java)
.hasMessage("Period start and end dates are overlap with other open periods")
}
@Test
fun `should fail to update if start date is after end date`() {
val financialPeriod = createFinancialPeriod(
name = "10/2024",
startingAt = LocalDate.of(2024, 10, 1),
endingAt = LocalDate.of(2024, 10, 31)
)
val externalId = financialPeriodService.create(financialPeriod)
val toUpdate = financialPeriodRepository.findByExternalId(externalId) ?: fail { OBJECT_NOT_FOUND_ERROR }
toUpdate.apply {
this.endingAt = LocalDate.of(2024, 10, 5)
this.startingAt = LocalDate.of(2024, 10, 10)
}
assertThatThrownBy { financialPeriodService.update(toUpdate) }
.isInstanceOf(BusinessException::class.java)
.hasMessage("Start date must be before end date")
}
@Test
fun `should fail to update if period is not active`() {
val financialPeriod = createFinancialPeriod(
name = "10/2024",
startingAt = LocalDate.of(2024, 10, 1),
endingAt = LocalDate.of(2024, 10, 31),
status = FinancialPeriod.Status.ACCOUNTED
)
val externalId = financialPeriodService.create(financialPeriod)
val toUpdate = financialPeriodRepository.findByExternalId(externalId) ?: fail { OBJECT_NOT_FOUND_ERROR }
assertThatThrownBy { financialPeriodService.update(toUpdate) }
.isInstanceOf(BusinessException::class.java)
.hasMessage("You can't delete or update non active periods")
}
@Test
@Sql(
"/sql/registration/clear-tables.sql",
"/sql/registration/create-financial-period.sql"
)
fun `should delete`() {
val externalId = UUID.fromString("27881a12-5e61-43cd-a6d0-fdb32eaa75c0")
val toDelete = financialPeriodRepository.findByExternalId(externalId) ?: fail { OBJECT_NOT_FOUND_ERROR }
financialPeriodService.delete(toDelete)
val deleted = financialPeriodRepository.findByExternalId(externalId)
assertThat(deleted).isNull()
}
@Test
@Sql(
"/sql/registration/clear-tables.sql",
"/sql/registration/create-financial-period.sql"
)
fun `should fail to delete if period is not active`() {
val externalId = UUID.fromString("27881a12-5e61-43cd-a6d0-fdb32eaa75c0")
val toUpdate = financialPeriodRepository.findByExternalId(externalId) ?: fail { OBJECT_NOT_FOUND_ERROR }
toUpdate.apply {
this.status = FinancialPeriod.Status.ACCOUNTED
}
financialPeriodService.update(toUpdate)
val toDelete = financialPeriodRepository.findByExternalId(externalId) ?: fail { OBJECT_NOT_FOUND_ERROR }
assertThatThrownBy { financialPeriodService.delete(toDelete) }
.isInstanceOf(BusinessException::class.java)
.hasMessage("You can't delete or update non active periods")
}
@Test
@Disabled
fun `should fail to delete if period has movements`() {
// TODO this should be done after the movement feature is created
}
} | 3 | null | 5 | 7 | 2e4985121985c6dcf1de83b9044ca1c5927c20fb | 9,915 | back-end | Apache License 2.0 |
backend/src/main/kotlin/com/ynixt/sharedfinances/repository/UserRepository.kt | ynixt | 369,952,878 | false | {"TypeScript": 236801, "Kotlin": 168282, "HTML": 94035, "SCSS": 14812, "JavaScript": 2009, "Dockerfile": 850} | package com.ynixt.sharedfinances.repository
import com.ynixt.sharedfinances.entity.User
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.CrudRepository
interface UserRepository : CrudRepository<User, Long> {
@Query(
"""
from User u
left join fetch u.bankAccounts ub
where u.id = :id
"""
)
fun findCurrentUserOneById(id: Long): User?
fun findByUid(uid: String): User?
fun findByEmail(uid: String): User?
@Modifying
fun save(user: User): User
@Query(
"""
from User u
left join fetch u.bankAccounts ub
left join fetch u.creditCards cc
where u.id in :ids
"""
)
fun findAllIncludeCreditCardAndBankAccount(ids: List<Long>): List<User>
}
| 5 | TypeScript | 0 | 1 | 6abf9d076698e0d8526919152dc534f41c1d29e0 | 859 | shared-finances | MIT License |
sirius-chainconnector/src/test/kotlin/org/starcoin/sirius/protocol/ethereum/InMemoryChainTest.kt | westarlabs | 174,323,114 | false | null | package org.starcoin.sirius.protocol.ethereum
import kotlinx.coroutines.runBlocking
import org.ethereum.util.blockchain.EtherUtil
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import kotlin.properties.Delegates
class InMemoryChainTest {
var chain: InMemoryChain by Delegates.notNull()
@Before
fun before() {
chain = InMemoryChain(true)
}
@Test
fun testMineAndTransfer() {
val account1 = EthereumAccount()
val account2 = EthereumAccount()
val oneEther = EtherUtil.convert(1, EtherUtil.Unit.ETHER)
chain.tryMiningCoin(account1, oneEther * 1000.toBigInteger())
Assert.assertEquals(chain.getBalance(account1.address), oneEther * 1000.toBigInteger())
chain.tryMiningCoin(account2, oneEther * 1000.toBigInteger())
Assert.assertEquals(chain.getBalance(account2.address), oneEther * 1000.toBigInteger())
runBlocking {
chain.submitTransaction(
account1,
chain.newTransaction(account1, account2.address, oneEther * 500.toBigInteger())
).awaitTimoutOrNull()
}
Assert.assertTrue(chain.getBalance(account1.address) > oneEther * 499.toBigInteger())
Assert.assertEquals(oneEther * 1500.toBigInteger(), chain.getBalance(account2.address))
chain.tryMiningCoin(account1, oneEther * 10000.toBigInteger())
Assert.assertTrue(chain.getBalance(account1.address) > oneEther * 10499.toBigInteger())
Assert.assertEquals(1, account1.getNonce())
Assert.assertEquals(0, account2.getNonce())
Assert.assertEquals(account1.getNonce(), chain.getNonce(account1.address).longValueExact())
Assert.assertEquals(account2.getNonce(), chain.getNonce(account2.address).longValueExact())
}
}
| 4 | Kotlin | 6 | 15 | 27ccb840a5d8d3787fcef3c9914d0afd8a59ed1f | 1,811 | sirius | MIT License |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Flag.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.BoldGroup
public val BoldGroup.Flag: ImageVector
get() {
if (_flag != null) {
return _flag!!
}
_flag = Builder(name = "Flag", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.0204f, 12.33f)
lineTo(16.8004f, 11.11f)
curveTo(16.5104f, 10.86f, 16.3404f, 10.49f, 16.3304f, 10.08f)
curveTo(16.3104f, 9.63f, 16.4904f, 9.18f, 16.8204f, 8.85f)
lineTo(18.0204f, 7.65f)
curveTo(19.0604f, 6.61f, 19.4504f, 5.61f, 19.1204f, 4.82f)
curveTo(18.8004f, 4.04f, 17.8104f, 3.61f, 16.3504f, 3.61f)
horizontalLineTo(5.9004f)
verticalLineTo(2.75f)
curveTo(5.9004f, 2.34f, 5.5604f, 2.0f, 5.1504f, 2.0f)
curveTo(4.7404f, 2.0f, 4.4004f, 2.34f, 4.4004f, 2.75f)
verticalLineTo(21.25f)
curveTo(4.4004f, 21.66f, 4.7404f, 22.0f, 5.1504f, 22.0f)
curveTo(5.5604f, 22.0f, 5.9004f, 21.66f, 5.9004f, 21.25f)
verticalLineTo(16.37f)
horizontalLineTo(16.3504f)
curveTo(17.7904f, 16.37f, 18.7604f, 15.93f, 19.0904f, 15.14f)
curveTo(19.4204f, 14.35f, 19.0404f, 13.36f, 18.0204f, 12.33f)
close()
}
}
.build()
return _flag!!
}
private var _flag: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 2,297 | VuesaxIcons | MIT License |
app/src/main/java/com/gzaber/forexviewer/data/repository/forexdata/model/ModelMappingExt.kt | gzaber | 734,830,877 | false | {"Kotlin": 70722} | package com.gzaber.forexviewer.data.repository.forexdata.model
import com.gzaber.forexviewer.data.source.network.model.NetworkExchangeRate
import com.gzaber.forexviewer.data.source.network.model.NetworkForexPair
import com.gzaber.forexviewer.data.source.network.model.NetworkQuote
import com.gzaber.forexviewer.data.source.network.model.NetworkTimeSeriesValue
fun NetworkForexPair.toModel() = ForexPair(symbol, group, base, quote)
fun NetworkExchangeRate.toModel() = ExchangeRate(symbol, rate)
fun NetworkQuote.toModel() = Quote(symbol, name, change, percentChange)
fun NetworkTimeSeriesValue.toModel() = TimeSeriesValue(datetime, open, high, low, close) | 0 | Kotlin | 0 | 0 | 1d19ad610dd1029bb8836dcf59858adfbe05bced | 659 | ForexViewer | MIT License |
app/src/test/java/net/marksheehan/githubsearch/GithubRestApiTests.kt | mcsheehan | 220,323,764 | true | {"Kotlin": 16478} | package net.marksheehan.githubsearch
import net.marksheehan.githubsearch.github.GithubApi
import net.marksheehan.githubsearch.github.GithubServiceInterface
import net.marksheehan.githubsearch.github.appendLanguageToQuery
import org.junit.Assert
import org.junit.Test
class GithubRestApiTests{
var api : GithubServiceInterface = GithubApi.buildGithubRestApi()
@Test
fun ensureMoreThan1ResultReturned(){
val observable = api.searchForRepository("tetris")
val response = observable.blockingGet()
val result = response.body()
Assert.assertTrue(response.isSuccessful)
Assert.assertNotNull(result)
Assert.assertTrue(result!!.total_count > 0)
}
@Test
fun emptyQueryProducesNotSuccessful(){
val query = ""
val observable = api.searchForRepository(query)
val response = observable.blockingGet()
Assert.assertFalse(response.isSuccessful)
}
@Test
fun searchingMultipleLanguagesProducesResults(){
val queryWithLanguage = appendLanguageToQuery("test", "kotlin")
val observable = api.searchForRepository(queryWithLanguage)
val response = observable.blockingGet()
val result = response.body()
Assert.assertTrue(response.isSuccessful)
Assert.assertTrue(result!!.total_count > 0)
}
@Test
fun searchingTargetLanguageProducesResultsWithTargetLanguage(){
val targetLanguage = "Kotlin"
val queryWithLanguage = appendLanguageToQuery("test", targetLanguage)
val observable = api.searchForRepository(queryWithLanguage)
val response = observable.blockingGet()
val result = response.body()
Assert.assertTrue(response.isSuccessful)
for (item in result!!.items){
Assert.assertTrue(item.language != targetLanguage )
}
}
@Test
fun searchingWithEmptyLanguageStringProducesMoreResults(){
val queryWithNoLanguage = appendLanguageToQuery("farm", "")
val queryWithLanguage = appendLanguageToQuery("farm", "Kotlin")
val observableWithNoLanguage = api.searchForRepository(queryWithNoLanguage)
val responseWithNoLanguage = observableWithNoLanguage.blockingGet()
val resultWithNoLanguage = responseWithNoLanguage.body()
val observableWithLanguage = api.searchForRepository(queryWithLanguage)
val responseWithLanguage = observableWithLanguage.blockingGet()
val resultWithLanguage = responseWithLanguage.body()
Assert.assertTrue(responseWithLanguage.isSuccessful)
Assert.assertTrue(responseWithNoLanguage.isSuccessful)
Assert.assertTrue( resultWithNoLanguage!!.total_count > resultWithLanguage!!.total_count)
}
@Test
fun queryWithoutSortingByStarsIsSuccessful(){
val queryWithLanguage = appendLanguageToQuery("test", "kotlin")
val observable = api.searchForRepository(queryWithLanguage, "")
val response = observable.blockingGet()
val result = response.body()
Assert.assertTrue(response.isSuccessful)
Assert.assertTrue(result!!.total_count > 0)
}
} | 1 | Kotlin | 1 | 0 | 661e3c3dd44e349fbd43c04ceb37f78cd9d741a6 | 3,163 | github-search | MIT License |
app/src/main/java/com/laotoua/dawnislandk/screens/profile/DisplaySettingFragment.kt | mnixry | 288,540,733 | true | {"Kotlin": 675495, "HTML": 16531} | /*
* Copyright 2020 Fishballzzz
* *
* * 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.laotoua.dawnislandk.screens.profile
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.checkbox.checkBoxPrompt
import com.afollestad.materialdialogs.checkbox.isCheckPromptChecked
import com.afollestad.materialdialogs.list.listItemsSingleChoice
import com.laotoua.dawnislandk.DawnApp.Companion.applicationDataStore
import com.laotoua.dawnislandk.R
import com.laotoua.dawnislandk.databinding.FragmentDisplaySettingBinding
import com.laotoua.dawnislandk.screens.util.Layout.toast
import com.laotoua.dawnislandk.screens.util.Layout.updateSwitchSummary
import com.laotoua.dawnislandk.util.IntentUtil
class DisplaySettingFragment : Fragment() {
private var binding: FragmentDisplaySettingBinding? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDisplaySettingBinding.inflate(inflater,container, false)
binding?.animationSwitch?.apply {
key.setText(R.string.animation_settings)
val options = resources.getStringArray(R.array.adapter_animation_options)
summary.text = options[applicationDataStore.animationOption]
root.setOnClickListener {
if (activity == null || !isAdded) return@setOnClickListener
MaterialDialog(requireContext()).show {
title(res = R.string.animation_settings)
checkBoxPrompt(res = R.string.animation_first_only) {}
listItemsSingleChoice(items = options.toList()) { _, index, _ ->
applicationDataStore.setAnimationOption(index)
applicationDataStore.setAnimationFirstOnly(isCheckPromptChecked())
toast(R.string.restart_to_apply_setting)
summary.text = options[index]
}
positiveButton(R.string.submit)
negativeButton(R.string.cancel)
}
}
}
return binding!!.root
}
override fun onResume() {
super.onResume()
binding?.layoutCustomization?.apply {
key.setText(R.string.layout_customization)
preferenceSwitch.visibility = View.VISIBLE
preferenceSwitch.isClickable = true
preferenceSwitch.isChecked = applicationDataStore.getLayoutCustomizationStatus()
updateSwitchSummary(R.string.layout_customization_on, R.string.layout_customization_off)
preferenceSwitch.setOnCheckedChangeListener { _, isChecked ->
applicationDataStore.setLayoutCustomizationStatus(isChecked)
updateSwitchSummary(
R.string.layout_customization_on,
R.string.layout_customization_off
)
toast(R.string.restart_to_apply_setting)
}
root.setOnClickListener {
if (activity == null || !isAdded) return@setOnClickListener
val action = DisplaySettingFragmentDirections.actionDisplaySettingFragmentToSizeCustomizationFragment()
findNavController().navigate(action)
}
}
binding?.toolbarCustomization?.apply {
key.setText(R.string.toolbar_customization)
preferenceSwitch.visibility = View.VISIBLE
preferenceSwitch.isClickable = true
preferenceSwitch.isChecked = applicationDataStore.getCustomToolbarImageStatus()
updateSwitchSummary(R.string.toolbar_customization_on, R.string.toolbar_customization_off)
preferenceSwitch.setOnCheckedChangeListener { _, isChecked ->
applicationDataStore.setCustomToolbarImageStatus(isChecked)
updateSwitchSummary(
R.string.toolbar_customization_on,
R.string.toolbar_customization_off
)
toast(R.string.restart_to_apply_setting)
}
root.setOnClickListener {
if (activity == null || !isAdded) return@setOnClickListener
IntentUtil.setToolbarBackgroundImage(requireActivity()){ uri: Uri? ->
if (uri != null) {
applicationDataStore.setCustomToolbarImagePath(uri.toString())
toast(R.string.restart_to_apply_setting)
} else {
toast(R.string.cannot_load_image_file)
}
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
} | 0 | Kotlin | 0 | 0 | 7d0a3645b8ce09eb732556eacc398ca0128857f9 | 5,565 | DawnIslandK | Apache License 2.0 |
kalah-game-service/src/main/kotlin/org/jesperancinha/kalah/controller/KalaExceptionHandlingController.kt | jesperancinha | 55,727,989 | false | {"Kotlin": 60899, "TypeScript": 27317, "HTML": 4679, "Shell": 2663, "CSS": 2239, "Makefile": 1936, "JavaScript": 1711, "Dockerfile": 815, "SCSS": 121} | package org.jesperancinha.kalah.controller;
import jakarta.servlet.http.HttpServletRequest
import org.jesperancinha.kalah.exception.*
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
@ControllerAdvice
class KalaExceptionHandlingController {
/**
* The game is over and that means that there is a winner already
*
* @param req
* @param ex
* @return
*/
@ExceptionHandler(GameOverException::class)
fun handleErrorGameOver(req: HttpServletRequest?, ex: Exception?): ResponseEntity<String> {
return ResponseEntity.badRequest().body(KalahErrorCode.GAME_OVER.toString())
}
/**
* We cannot pick Kalah pits to start from
*
* @param req
* @param ex
* @return
*/
@ExceptionHandler(InvalidPitException::class)
fun handleErrorInvalidPit(req: HttpServletRequest?, ex: Exception?): ResponseEntity<String> {
return ResponseEntity.badRequest().body(KalahErrorCode.INVALID_PIT.toString())
}
/**
* The player does not own the pit
*
* @param req
* @param ex
* @return
*/
@ExceptionHandler(NotOwnedPitException::class)
fun handleErrorNotOwned(req: HttpServletRequest?, ex: Exception?): ResponseEntity<String> {
return ResponseEntity.badRequest().body(KalahErrorCode.NOT_OWNED.toString())
}
/**
* The player tried to make a move when it wasn't their turn
*
* @param req
* @param ex
* @return
*/
@ExceptionHandler(WrongTurnException::class)
fun handleErrorWrongTurn(req: HttpServletRequest?, ex: Exception?): ResponseEntity<String> {
return ResponseEntity.badRequest().body(KalahErrorCode.WRONG_TURN.toString())
}
/**
* The game cannot start until player two joins in
*
* @param req
* @param ex
* @return
*/
@ExceptionHandler(PlayerNotJoinedYetException::class)
fun handleErrorPlayerNotJoined(req: HttpServletRequest?, ex: Exception?): ResponseEntity<String> {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(KalahErrorCode.NOT_JOINED.toString())
}
/**
* The Board does not exist
*
* @param req
* @param ex
* @return
*/
@ExceptionHandler(BoardDoesNotExistException::class)
fun handleErrorBoardDoesNotExist(req: HttpServletRequest?, ex: Exception?): ResponseEntity<String> {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(KalahErrorCode.BOARD_NOT_FOUND.toString())
}
/**
* The Pit does not exist
*
* @param req
* @param ex
* @return
*/
@ExceptionHandler(PitDoesNotExistException::class)
fun handleErrorPitDoesNotExist(req: HttpServletRequest?, ex: Exception?): ResponseEntity<String> {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(KalahErrorCode.PIT_NOT_FOUND.toString())
}
/**
* No Stones to move
*
* @param req
* @param ex
* @return
*/
@ExceptionHandler(ZeroStonesToMoveException::class)
fun handleErrorZeroStonesToMove(req: HttpServletRequest?, ex: Exception?): ResponseEntity<String> {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(KalahErrorCode.ZERO_STONES.toString())
}
} | 0 | Kotlin | 1 | 2 | fabf3ccd21d4033d4f5185be2e8470e739cb7433 | 3,402 | mancalaje | Apache License 2.0 |
client/client-hci/src/commonMain/kotlin/de/jlnstrk/transit/api/hci/method/tripsearch/HciTripSearchRequest.kt | jlnstrk | 229,599,180 | false | {"Kotlin": 729374} | @file:UseSerializers(
HciLocalDateSerializer::class,
HciLocalTimeSerializer::class,
HciDurationSerializer::class
)
package de.jlnstrk.transit.api.hci.method.tripsearch
import de.jlnstrk.transit.api.hafas.HciModel
import de.jlnstrk.transit.api.hci.method.HciServiceMethod
import de.jlnstrk.transit.api.hci.model.location.HciLocation
import de.jlnstrk.transit.api.hci.model.HciRoutingPreselection
import de.jlnstrk.transit.api.hci.model.eco.HciEcoParams
import de.jlnstrk.transit.api.hci.model.gis.HciGisLocation
import de.jlnstrk.transit.api.hci.model.gis.HciGisPreferredLocation
import de.jlnstrk.transit.api.hci.model.recon.HciReconstruction
import de.jlnstrk.transit.api.hci.model.tariff.HciTariffRequest
import de.jlnstrk.transit.api.hci.request.HciServiceRequest
import de.jlnstrk.transit.api.hci.request.filter.HciGisFilter
import de.jlnstrk.transit.api.hci.request.filter.HciJourneyFilter
import de.jlnstrk.transit.api.hci.serializer.time.HciDurationSerializer
import de.jlnstrk.transit.api.hci.serializer.time.HciLocalDateSerializer
import de.jlnstrk.transit.api.hci.serializer.time.HciLocalTimeSerializer
import de.jlnstrk.transit.api.hci.serializer.time.HciMinutesSerializer
import de.jlnstrk.transit.util.Duration
import de.jlnstrk.transit.util.LocalDate
import de.jlnstrk.transit.util.LocalTime
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers
@HciModel("1.39")
@Serializable
public class HciTripSearchRequest(
/** The possible departure locations for trips */
public var depLocL: List<HciLocation> = emptyList(),
/** The possible arrival locations for trips */
public var arrLocL: List<HciLocation> = emptyList(),
/** The via locations for trips to be routed over */
public var viaLocL: List<Via> = emptyList(),
/** The anti via locations for trips to avoid */
public var antiViaLocL: List<Via> = emptyList(),
// TODO: Purpose?
public var prefLocL: List<HciLocation> = emptyList(),
/** The number of trips to be returned that run before the specified datetime */
public var numB: Int? = null,
/** The number of trips to be returned that run after the specified datetime */
public var numF: Int? = null,
/** A trip request context to scroll upon */
public var ctxScr: String? = null,
/** The date of the outgoing connection */
public var outDate: LocalDate? = null,
/** The time of the outgoing connection */
public var outTime: LocalTime? = null,
/** Whether [outTime] refers to the departure time (as opposed to arrival time) */
public var outFrwd: Boolean? = null,
// TODO: Purpose?
public var outPeriod: Int? = null,
/** Reconstructions for the outgoing connections */
public var outReconL: List<String> = emptyList(),
/** The date of the returning connection */
public var retDate: LocalDate? = null,
/** The time of the returning connection */
public var retTime: LocalTime? = null,
/** Whether [retTime] refers to the respective departure time (as opposed to arrival time) */
public var retFrwd: Boolean? = null,
// TODO: Purpose?
public var retPeriod: Int? = null,
/** Reconstructions for the returning connections */
public var retReconL: List<HciReconstruction> = emptyList(),
// TODO: Purpose?
public var period: Duration? = null,
// TODO: Purpose?
public var periodCombineDep: Boolean? = null,
// TODO: Purpose?
public var periodMaxCons: Int? = null,
/** The minimum duration for changes */
public var minChgTime: Duration? = null,
/** The maximum duration for changes */
public var maxChgTime: Duration? = null,
// TODO: Purpose?
public var supplChgTime: Int? = null,
// TODO: Purpose?
public var extChgTime: Duration? = null,
/** The maximum number of changes */
public var maxChg: Int? = null,
// TODO: Purpose?
public var getLastPass: Boolean? = null,
/** Whether traffic messages shall be returned */
public var getTrafficMsg: Boolean? = null,
/** Whether simple train compositions shall be returned */
public var getSimpleTrainComposition: Boolean? = null,
/** Whether full train compositions shall be returned */
public var getTrainComposition: Boolean? = null,
// TODO: Purpose?
public var getAltCoordinates: Boolean? = null,
// TODO: Purpose?
public var getAnnotations: Boolean? = null,
/** Whether connections shall be put in scoring groups */
public var getConGroups: Boolean? = null,
// TODO: Purpose?
public var getIST: Boolean? = null,
/** Whether individual transport shall be returned */
public var getIV: Boolean? = null,
/** Whether public transport options should be considered fro trips */
public var getPT: Boolean? = null,
/** Whether passed stops shall be returned */
public var getPasslist: Boolean? = null,
/** Whether tariff data shall be returned */
public var getTariff: Boolean? = null,
/** Tariff request to specify ticket interest */
public var trfReq: HciTariffRequest? = null,
/** Whether route polylines shall be returned */
public var getPolyline: Boolean? = null,
// TODO: Purpose?
public var polySplitting: Boolean? = null,
/** Whether eco information shall be returned */
public var getEco: Boolean? = null,
// TODO: Purpose?
public var getEcoCmp: Boolean? = null,
/** The params for eco considerations */
public var ecoParams: HciEcoParams? = null,
// TODO: Purpose?
public var backPreselectionL: List<HciRoutingPreselection> = emptyList(),
// TODO: Purpose?
public var frontPreselectionL: List<HciRoutingPreselection> = emptyList(),
// TODO: Purpose?
public var baim: Boolean? = null,
// TODO: Purpose?
public var disableDurOpt: Boolean? = null,
// TODO: Purpose?
public var freq: Int? = null,
/** Whether trips should be computed based on economic criteria */
public var economic: Boolean? = null,
/** Whether stops nearby the specified departure and arrival locations can be considered */
public var ushrp: Boolean? = null,
// TODO: Purpose?
public var program: String? = null,
// TODO: Purpose?
public var pt: PtSearchMode? = null,
// TODO: Purpose?
public var searchContext: HciReconstruction? = null,
// TODO: Purpose?
public var indoor: Boolean? = null,
// TODO: Purpose?
public var liveSearch: Boolean? = null,
// TODO: Purpose?
public var withICTAlternatives: Boolean? = null,
public var jnyFltrL: List<HciJourneyFilter> = emptyList(),
public var gisFltrL: List<HciGisFilter> = emptyList(),
public var gisLocL: List<HciGisLocation> = emptyList(),
public var gisPrefLocL: List<HciGisPreferredLocation> = emptyList(),
// TODO: Purpose?
public var bfAndroidEnd: String? = null,
// TODO: Purpose?
public var bfAndroidStart: String? = null,
// TODO: Purpose?
public var bfIOSEnd: String? = null,
// TODO: Purpose?
public var bfIOSStart: String? = null,
// TODO: Purpose?
public var cFGZ: Int? = null,
// TODO: Purpose?
public var cFLZ: Int? = null,
// TODO: Purpose?
public var cMZE: Int? = null,
// TODO: Purpose?
public var cNRA: Int? = null,
// TODO: Purpose?
public var cNUH: Int? = null,
// TODO: Purpose?
public var cNUMH: Int? = null,
// TODO: Purpose?
public var cNVOR: Int? = null,
// TODO: Purpose?
public var cOFFERR: Int? = null,
// TODO: Purpose?
public var cRFRA: Int? = null,
// TODO: Purpose?
public var cTFS: Int? = null,
// TODO: Purpose?
public var cVLKURZ: Int? = null,
// TODO: Purpose?
public var cVLMITTEL: Int? = null,
) : HciServiceRequest<HciTripSearchResult>() {
override val method: HciServiceMethod get() = HciServiceMethod.TRIP_SEARCH
@Serializable
public class Via(
public val loc: HciLocation,
@Serializable(with = HciMinutesSerializer::class)
public val min: Duration? = null
)
@Serializable
public enum class PtSearchMode {
FIRST,
LAST,
OFF,
STD,
}
public companion object {
public inline operator fun invoke(init: HciTripSearchRequest.() -> Unit): HciTripSearchRequest =
HciTripSearchRequest().apply(init)
}
} | 0 | Kotlin | 0 | 0 | 9f700364f78ebc70b015876c34a37b36377f0d9c | 8,391 | transit | Apache License 2.0 |
sample/dapp/src/main/kotlin/com/walletconnect/sample/dapp/DappSampleApp.kt | WalletConnect | 435,951,419 | false | null | package com.walletconnect.sample.dapp
import android.app.Application
import com.google.firebase.appdistribution.FirebaseAppDistribution
import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.ktx.Firebase
import com.walletconnect.android.Core
import com.walletconnect.android.CoreClient
import com.walletconnect.sample.common.BuildConfig
import com.walletconnect.sample.common.tag
import com.walletconnect.wcmodal.client.Modal
import com.walletconnect.wcmodal.client.WalletConnectModal
import timber.log.Timber
class DappSampleApp : Application() {
override fun onCreate() {
super.onCreate()
val appMetaData = Core.Model.AppMetaData(
name = "Kotlin Dapp",
description = "Kotlin Dapp Implementation",
url = "https://web3modal-laboratory-git-chore-kotlin-assetlinks-walletconnect1.vercel.app",
icons = listOf("https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media"),
redirect = "kotlin-dapp-wc://request",
appLink = "https://web3modal-laboratory-git-chore-kotlin-assetlinks-walletconnect1.vercel.app/dapp",
linkMode = true
)
CoreClient.initialize(
application = this,
projectId = BuildConfig.PROJECT_ID,
metaData = appMetaData,
) {
Firebase.crashlytics.recordException(it.throwable)
}
WalletConnectModal.initialize(
Modal.Params.Init(core = CoreClient)
) { error ->
Timber.e(tag(this), error.throwable.stackTraceToString())
}
FirebaseAppDistribution.getInstance().updateIfNewReleaseAvailable()
}
}
| 78 | null | 72 | 199 | e373c535d7cefb2f932368c79622ac05763b411a | 1,702 | WalletConnectKotlinV2 | Apache License 2.0 |
core/src/main/java/com/kevinmost/koolbelt/extension/DateTimeUtil.kt | kevinmost | 57,383,899 | false | null | package com.kevinmost.koolbelt.extension
import org.threeten.bp.Instant
import org.threeten.bp.LocalDateTime
import org.threeten.bp.ZoneId
fun Instant.localDateTime(): LocalDateTime {
return LocalDateTime.ofInstant(this, ZoneId.systemDefault())
}
| 0 | Kotlin | 2 | 3 | 2a35ac39f57810f7fbc044e780b9a838562e4554 | 251 | koolbelt | Apache License 2.0 |
src/main/kotlin/com/ecwid/apiclient/v3/dto/product/result/ProductFileUploadResult.kt | alf-ecwid | 267,801,795 | true | {"Kotlin": 412279} | package com.ecwid.apiclient.v3.dto.product.result
data class ProductFileUploadResult(
val id: Int = 0
) | 0 | null | 0 | 0 | 1eb037cdc7504b10cc3a417e4799d0ad977214af | 106 | ecwid-java-api-client | Apache License 2.0 |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/globalaccelerator/PortRangeDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.globalaccelerator
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Number
import software.amazon.awscdk.services.globalaccelerator.PortRange
/**
* The list of port ranges for the connections from clients to the accelerator.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.globalaccelerator.*;
* PortRange portRange = PortRange.builder()
* .fromPort(123)
* // the properties below are optional
* .toPort(123)
* .build();
* ```
*/
@CdkDslMarker
public class PortRangeDsl {
private val cdkBuilder: PortRange.Builder = PortRange.builder()
/**
* @param fromPort The first port in the range of ports, inclusive.
*/
public fun fromPort(fromPort: Number) {
cdkBuilder.fromPort(fromPort)
}
/**
* @param toPort The last port in the range of ports, inclusive.
*/
public fun toPort(toPort: Number) {
cdkBuilder.toPort(toPort)
}
public fun build(): PortRange = cdkBuilder.build()
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 1,288 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/java/com/github/pakka_papad/collection/CollectionViewModel.kt | pakka-papad | 539,192,838 | false | null | package com.github.pakka_papad.collection
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.github.pakka_papad.Constants
import com.github.pakka_papad.R
import com.github.pakka_papad.components.SortOptions
import com.github.pakka_papad.data.music.Song
import com.github.pakka_papad.data.services.PlayerService
import com.github.pakka_papad.data.services.PlaylistService
import com.github.pakka_papad.data.services.QueueService
import com.github.pakka_papad.data.services.SongService
import com.github.pakka_papad.util.MessageStore
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
@HiltViewModel
class CollectionViewModel @Inject constructor(
private val messageStore: MessageStore,
private val playlistService: PlaylistService,
private val songService: SongService,
private val playerService: PlayerService,
private val queueService: QueueService,
) : ViewModel() {
val currentSong = queueService.currentSong
private val queue = queueService.queue
private val _collectionType = MutableStateFlow<CollectionType?>(null)
private val _chosenSortOrder = MutableStateFlow(SortOptions.Default.ordinal)
val chosenSortOrder = _chosenSortOrder.asStateFlow()
private val _message = MutableStateFlow("")
val message = _message.asStateFlow()
@OptIn(ExperimentalCoroutinesApi::class)
val collectionUi = _collectionType
.flatMapLatest { type ->
when (type?.type) {
CollectionType.AlbumType -> {
songService.getAlbumWithSongsByName(type.id).map {
if (it == null) CollectionUi()
else {
CollectionUi(
songs = it.songs,
topBarTitle = it.album.name,
topBarBackgroundImageUri = it.album.albumArtUri ?: ""
)
}
}
}
CollectionType.ArtistType -> {
songService.getArtistWithSongsByName(type.id).map {
if (it == null) CollectionUi()
else {
CollectionUi(
songs = it.songs,
topBarTitle = it.artist.name,
topBarBackgroundImageUri = it.songs.randomOrNull()?.artUri ?: ""
)
}
}
}
CollectionType.PlaylistType -> {
playlistService.getPlaylistWithSongsById(type.id.toLong()).map {
if (it == null) CollectionUi()
else {
CollectionUi(
songs = it.songs,
topBarTitle = it.playlist.playlistName,
topBarBackgroundImageUri = it.playlist.artUri ?:
it.songs.randomOrNull()?.artUri ?: ""
)
}
}
}
CollectionType.AlbumArtistType -> {
songService.getAlbumArtistWithSongsByName(type.id).map {
if (it == null) CollectionUi()
else {
CollectionUi(
songs = it.songs,
topBarTitle = it.albumArtist.name,
topBarBackgroundImageUri = it.songs.randomOrNull()?.artUri ?: ""
)
}
}
}
CollectionType.ComposerType -> {
songService.getComposerWithSongsByName(type.id).map {
if (it == null) CollectionUi()
else {
CollectionUi(
songs = it.songs,
topBarTitle = it.composer.name,
topBarBackgroundImageUri = it.songs.randomOrNull()?.artUri ?: ""
)
}
}
}
CollectionType.LyricistType -> {
songService.getLyricistWithSongsByName(type.id).map {
if (it == null) CollectionUi()
else {
CollectionUi(
songs = it.songs,
topBarTitle = it.lyricist.name,
topBarBackgroundImageUri = it.songs.randomOrNull()?.artUri ?: ""
)
}
}
}
CollectionType.GenreType -> {
songService.getGenreWithSongsByName(type.id).map {
if (it == null) CollectionUi()
else {
CollectionUi(
songs = it.songs,
topBarTitle = it.genre.genre,
topBarBackgroundImageUri = it.songs.randomOrNull()?.artUri ?: ""
)
}
}
}
CollectionType.FavouritesType -> {
songService.getFavouriteSongs().map {
CollectionUi(
songs = it,
topBarTitle = "Favourites",
topBarBackgroundImageUri = it.randomOrNull()?.artUri ?: ""
)
}
}
else -> flow { }
}
}.combine(_chosenSortOrder) { ui, sortOrder ->
when(sortOrder){
SortOptions.TitleASC.ordinal -> {
ui.copy(songs = ui.songs.sortedBy { it.title })
}
SortOptions.TitleDSC.ordinal -> {
ui.copy(songs = ui.songs.sortedByDescending { it.title })
}
SortOptions.YearASC.ordinal -> {
ui.copy(songs = ui.songs.sortedBy { it.year })
}
SortOptions.YearDSC.ordinal -> {
ui.copy(songs = ui.songs.sortedByDescending { it.year })
}
SortOptions.DurationASC.ordinal -> {
ui.copy(songs = ui.songs.sortedBy { it.durationMillis })
}
SortOptions.DurationDSC.ordinal -> {
ui.copy(songs = ui.songs.sortedByDescending { it.durationMillis })
}
else -> ui
}
}.catch { exception ->
Timber.e(exception)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(100),
initialValue = null
)
fun loadCollection(type: CollectionType?) {
_collectionType.update { type }
}
fun shufflePlay(songs: List<Song>?) = setQueue(songs?.shuffled(), 0)
fun setQueue(songs: List<Song>?, startPlayingFromIndex: Int = 0) {
if (songs == null) return
queueService.setQueue(songs, startPlayingFromIndex)
playerService.startServiceIfNotRunning(songs, startPlayingFromIndex)
showMessage(messageStore.getString(R.string.playing))
}
fun addToQueue(song: Song) {
if (queue.isEmpty()) {
queueService.setQueue(listOf(song), 0)
playerService.startServiceIfNotRunning(listOf(song), 0)
} else {
val result = queueService.append(song)
showMessage(
if (result) messageStore.getString(R.string.added_to_queue, song.title)
else messageStore.getString(R.string.song_already_in_queue)
)
}
}
fun addToQueue(songs: List<Song>) {
if (queue.isEmpty()) {
queueService.setQueue(songs, 0)
playerService.startServiceIfNotRunning(songs, 0)
} else {
val result = queueService.append(songs)
showMessage(messageStore.getString(if (result) R.string.done else R.string.song_already_in_queue))
}
}
fun changeFavouriteValue(song: Song? = currentSong.value) {
if (song == null) return
val updatedSong = song.copy(favourite = !song.favourite)
viewModelScope.launch(Dispatchers.IO) {
queueService.update(updatedSong)
songService.updateSong(updatedSong)
}
}
fun removeFromPlaylist(song: Song){
viewModelScope.launch {
try {
val playlistId = _collectionType.value?.id?.toLong() ?: throw IllegalArgumentException()
playlistService.removeSongsFromPlaylist(listOf(song.location), playlistId)
showMessage(messageStore.getString(R.string.done))
} catch (e: Exception){
Timber.e(e)
showMessage(messageStore.getString(R.string.some_error_occurred))
}
}
}
fun updateSortOrder(order: Int){
_chosenSortOrder.update { order }
}
private fun showMessage(message: String){
viewModelScope.launch {
_message.update { message }
delay(Constants.MESSAGE_DURATION)
_message.update { "" }
}
}
} | 8 | null | 19 | 222 | 5235163fcb575bd14ccfb03343e2b995739dade6 | 9,801 | Zen | MIT License |
app/src/main/java/com/breezefieldsalesayshfacade/features/myprofile/model/citylist/CityListApiResponse.kt | DebashisINT | 849,339,890 | false | {"Kotlin": 15796449, "Java": 1028706} | package com.breezefieldsalesayshfacade.features.myprofile.model.citylist
import com.breezefieldsalesayshfacade.base.BaseResponse
/**
* Created by Pratishruti on 19-02-2018.
*/
class CityListApiResponse:BaseResponse() {
var city_list:List<CityListData>? = null
} | 0 | Kotlin | 0 | 0 | 1a7295943ae51c2feff787bed4219be9c8399217 | 269 | AyshFacade | Apache License 2.0 |
intellij.tools.ide.starter.bus/src/com/intellij/tools/ide/starter/bus/EventsReceiver.kt | JetBrains | 499,194,001 | false | {"Kotlin": 464953, "C++": 3610, "Makefile": 713} | package com.intellij.tools.ide.starter.bus
import com.intellij.tools.ide.starter.bus.events.Event
import com.intellij.tools.ide.util.common.logError
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.filterNotNull
import java.io.PrintWriter
import java.io.StringWriter
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
open class EventsReceiver(private val producer: EventsProducer) {
private val parentJob = Job()
private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
throw throwable
}
// Using IO(has more threads) to avoid coroutine's threads lock by producers.
private val coroutineScope = CoroutineScope(Dispatchers.IO + parentJob + exceptionHandler)
private val subscribers = HashMap<String, Any>()
private val subscribersLock = ReentrantLock()
fun <EventType : Event, SubscriberType : Any> subscribeTo(event: Class<EventType>,
subscriber: SubscriberType,
callback: suspend (event: EventType) -> Unit) {
subscribersLock.withLock {
// To avoid double subscriptions
val jobHash = subscriber.hashCode().toString() + event.simpleName
if (subscribers.contains(jobHash) && subscribers[jobHash] == subscriber) return
subscribers.put(jobHash, subscriber)
}
val flow = producer.getOrCreateFlowForEvent(event)
//Subscription to the bus must occur before execution proceeds further, so CoroutineStart.UNDISPATCHED is used
coroutineScope.launch(start = CoroutineStart.UNDISPATCHED) {
flow
.filterNotNull()
.collect { event ->
launch {
try {
callback(event)
}
catch (e: Exception) {
if (e !is CancellationException) {
logError("Suppressed error: ${e.message}")
logError(StringWriter().let {
e.printStackTrace(PrintWriter(it))
it.buffer.toString()
})
}
}
finally {
// SharedFlow.emit only waits for the event to be delivered, not for the event to be processed.
producer.processedEvent(event)
}
}
}
}
}
fun unsubscribeAll() {
subscribersLock.withLock {
parentJob.children.forEach { runBlocking { it.cancelAndJoin() } }
subscribers.clear()
producer.clear()
}
}
}
| 0 | Kotlin | 2 | 12 | a97f38f5ff8b60a10d85491aaa74acec5300ac03 | 2,518 | intellij-ide-starter | Apache License 2.0 |
bootstrap-icons-compose/src/main/java/com/wiryadev/bootstrapiconscompose/bootstrapicons/normal/Fullscreen.kt | wiryadev | 380,639,096 | false | null | package com.wiryadev.bootstrapiconscompose.bootstrapicons.normal
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.wiryadev.bootstrapiconscompose.bootstrapicons.NormalGroup
public val NormalGroup.Fullscreen: ImageVector
get() {
if (_fullscreen != null) {
return _fullscreen!!
}
_fullscreen = Builder(name = "Fullscreen", defaultWidth = 16.0.dp, defaultHeight = 16.0.dp,
viewportWidth = 16.0f, viewportHeight = 16.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(1.5f, 1.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.5f, 0.5f)
verticalLineToRelative(4.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, -1.0f, 0.0f)
verticalLineToRelative(-4.0f)
arcTo(1.5f, 1.5f, 0.0f, false, true, 1.5f, 0.0f)
horizontalLineToRelative(4.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.0f, 1.0f)
horizontalLineToRelative(-4.0f)
close()
moveTo(10.0f, 0.5f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, -0.5f)
horizontalLineToRelative(4.0f)
arcTo(1.5f, 1.5f, 0.0f, false, true, 16.0f, 1.5f)
verticalLineToRelative(4.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, -1.0f, 0.0f)
verticalLineToRelative(-4.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.5f, -0.5f)
horizontalLineToRelative(-4.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, -0.5f, -0.5f)
close()
moveTo(0.5f, 10.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, 0.5f)
verticalLineToRelative(4.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.5f, 0.5f)
horizontalLineToRelative(4.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.0f, 1.0f)
horizontalLineToRelative(-4.0f)
arcTo(1.5f, 1.5f, 0.0f, false, true, 0.0f, 14.5f)
verticalLineToRelative(-4.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, -0.5f)
close()
moveTo(15.5f, 10.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, 0.5f)
verticalLineToRelative(4.0f)
arcToRelative(1.5f, 1.5f, 0.0f, false, true, -1.5f, 1.5f)
horizontalLineToRelative(-4.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.0f, -1.0f)
horizontalLineToRelative(4.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.5f, -0.5f)
verticalLineToRelative(-4.0f)
arcToRelative(0.5f, 0.5f, 0.0f, false, true, 0.5f, -0.5f)
close()
}
}
.build()
return _fullscreen!!
}
private var _fullscreen: ImageVector? = null
| 0 | Kotlin | 0 | 2 | 1c199d953dc96b261aab16ac230dc7f01fb14a53 | 3,643 | bootstrap-icons-compose | MIT License |
app/src/main/java/com/moo/frogs/MainActivity.kt | jsnwang | 645,538,906 | false | null | package com.moo.frogs
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.moo.frogs.ui.theme.FrogsTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
FrogsTheme {
Frogs()
}
}
}
}
| 0 | Kotlin | 0 | 0 | 23d9b674d4680afebf995dbe9d2f79fce5b0e404 | 486 | frogs | MIT License |
src/main/kotlin/com/cuupa/mailprocessor/process/CallActivityConstants.kt | Cuupa | 281,472,343 | false | null | package com.cuupa.mailprocessor.process
object CallActivityConstants {
const val PREPROCESSING_CALL = "preprocessing"
const val SCAN_PREPROCESSING = "scan_preprocessing"
const val EMAIL_PREPROCESSING = "email_preprocessing"
const val CONVERTING_CALL = "converting"
const val CONVERTING = "converting"
const val OCR_CALL = "OCR"
const val OCR = "OCR"
const val CLASSIFICATION_CALL = "classificaton"
const val CLASSIFICATION = "classificaton"
const val QA_CALL = "qa"
const val QA = "qa"
const val ARCHIVING_CALL = "archiving"
const val ARCHIVING = "archiving"
} | 13 | Kotlin | 0 | 0 | d9221e33487d30d3fb9449e2bd840cbad000b156 | 614 | mailprocessor | MIT License |
weather-database/src/main/java/com/github/mukiva/weatherdatabase/models/LocationDbo.kt | MUKIVA | 715,584,869 | false | {"Kotlin": 323153} | package com.github.mukiva.weatherdatabase.models
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.datetime.LocalDateTime
@Entity
public data class LocationDbo(
@PrimaryKey
val id: Long,
@ColumnInfo("name")
val name: String,
@ColumnInfo("region")
val region: String,
@ColumnInfo("country")
val country: String,
@ColumnInfo("lat")
val lat: Double,
@ColumnInfo("lon")
val lon: Double,
@ColumnInfo("tz_id")
val tzId: String,
@ColumnInfo("localtime_epoch")
val localtimeEpoch: LocalDateTime,
@ColumnInfo("priority")
val priority: Int
)
| 0 | Kotlin | 0 | 5 | c616fcc30cbea2fa079fac76c4eb16ec6922705d | 663 | open-weather | Apache License 2.0 |
android/app/src/main/java/com/algorand/android/deviceregistration/domain/mapper/DeviceUpdateDTOMapper.kt | perawallet | 364,359,642 | false | {"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596} | /*
* Copyright 2022 <NAME>, LDA
* 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.algorand.android.deviceregistration.domain.mapper
import com.algorand.android.deviceregistration.domain.model.DeviceUpdateDTO
import javax.inject.Inject
class DeviceUpdateDTOMapper @Inject constructor() {
fun mapToDeviceUpdateDTO(
deviceId: String,
token: String?,
accountPublicKeyList: List<String>,
application: String,
platform: String,
locale: String
): DeviceUpdateDTO {
return DeviceUpdateDTO(
deviceId = deviceId,
pushToken = token,
accountPublicKeys = accountPublicKeyList,
application = application,
platform = platform,
locale = locale
)
}
}
| 22 | Swift | 62 | 181 | 92fc77f73fa4105de82d5e87b03c1e67600a57c0 | 1,294 | pera-wallet | Apache License 2.0 |
app/src/main/java/com/loki/ripoti/util/extensions/NavController.kt | lokified | 539,420,367 | false | null | package com.plcoding.streamchatapp.util
import android.os.Bundle
import androidx.annotation.IdRes
import androidx.navigation.NavController
import androidx.navigation.NavOptions
import androidx.navigation.Navigator
fun NavController.navigateSafely(
@IdRes resId: Int,
args: Bundle? = null,
navOptions: NavOptions? = null,
navExtras: Navigator.Extras? = null
) {
val action = currentDestination?.getAction(resId) ?: graph.getAction(resId)
if(action != null && currentDestination?.id != action.destinationId) {
navigate(resId, args, navOptions, navExtras)
}
} | 0 | null | 0 | 2 | 9269a53bb7f7d07d4a8d6e414e7bc7592869704d | 603 | Ripoti | Apache License 2.0 |
permission-manager/src/main/java/com/mohsents/permissionmanager/PermissionManager.kt | Mohsents | 618,562,566 | false | null | /*
* Copyright (C) 2023 Mohsents
*
* 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.mohsents.permissionmanager
import android.os.Build
import androidx.activity.ComponentActivity
import androidx.annotation.RequiresApi
import java.lang.ref.WeakReference
@ExperimentalPermissionManagerApi
class PermissionManager private constructor(
activity: WeakReference<ComponentActivity>
) {
private val singlePermissionRequest = SinglePermissionRequest(activity.get()!!)
private val multiplePermissionRequest = MultipleRequestPermission(activity.get()!!)
companion object {
@JvmStatic
fun from(activity: ComponentActivity): PermissionManager =
PermissionManager(WeakReference(activity))
}
/**
* Requests a single permission from user.
*
* @param permission permission to request
* @param onGrant Called when the user grants permission
* @param onDenied Called when the user denied the permission
* @param onNeedRationale if an permission denied and and asked later, this will be called.
* means the permission needs rationale and the user needs more information about why you asked this.
* @param onNeverAskAgain if permission denied and the user does not want to ask it again, will be called
*/
fun requestPermission(
permission: String,
onGrant: () -> Unit,
onDenied: () -> Unit,
onNeedRationale: (SinglePermissionWrapper) -> Unit,
onNeverAskAgain: () -> Unit
) {
singlePermissionRequest.request(
permission,
onGrant,
onDenied,
onNeedRationale,
onNeverAskAgain
)
}
/**
* Requests multiple permission from user.
*
* @param permissions permissions to request
* @param onResult Called when the result of asked permission backed from user
* @param onNeedRationale if an permission denied and and asked later, this will be called.
* means the permission needs rationale and the user needs more information about why you asked this.
* @param onNeverAskAgain when the result of asked permission returns, will be called.
* It contains both granted permissions and denied permissions result.
*/
fun requestMultiplePermissions(
permissions: Array<String>,
onResult: (PermissionResult) -> Unit,
onNeedRationale: (MultiplePermissionWrapper, Array<String>) -> Unit,
onNeverAskAgain: (Array<String>) -> Unit
) {
multiplePermissionRequest.request(
permissions,
onResult,
onNeedRationale,
onNeverAskAgain
)
}
}
| 0 | Kotlin | 0 | 1 | db542244b8768787cf0cd6fdba3a5b7a0db9726e | 3,197 | android-permission-manager | Apache License 2.0 |
desktop_device_connection/src/main/java/com/kaspersky/test_server/DesktopDeviceSocketConnectionFactory.kt | eakurnikov | 208,156,480 | true | {"Kotlin": 41009} | package com.kaspersky.test_server
import com.kaspresky.test_server.log.Logger
object DesktopDeviceSocketConnectionFactory {
fun getSockets(
desktopDeviceSocketConnectionType: DesktopDeviceSocketConnectionType,
logger: Logger
): DesktopDeviceSocketConnection {
return when (desktopDeviceSocketConnectionType) {
DesktopDeviceSocketConnectionType.FORWARD -> DesktopDeviceSocketConnectionForwardImpl(logger)
DesktopDeviceSocketConnectionType.REVERSE -> throw UnsupportedOperationException("Please implement REVERSE DesktopDeviceSocketConnection")
}
}
} | 0 | null | 0 | 1 | d899bfc0f0399e4e25da2a21551e88c2b3d953aa | 619 | AdbServer | Apache License 2.0 |
shared/src/commonMain/kotlin/link/socket/kore/model/agent/KoreAgent.kt | socket-link | 724,331,833 | false | {"Kotlin": 94725, "Swift": 580, "Shell": 228} | @file:Suppress("MemberVisibilityCanBePrivate")
package link.socket.kore.model.agent
import com.aallam.openai.api.chat.ChatCompletionRequest
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import link.socket.kore.model.conversation.ChatHistory
import link.socket.kore.model.tool.FunctionProvider
import link.socket.kore.ui.conversation.selector.AgentInput
sealed interface KoreAgent : LLMAgent, AgentCapabilities {
val name: String
val neededInputs: List<AgentInput>
fun parseNeededInputs(inputs: Map<String, AgentInput>)
interface HumanAssisted : KoreAgent {
suspend fun executeHumanAssistance(): String
override val availableFunctions: Map<String, FunctionProvider>
get() = agentFunctions.plus(
FunctionProvider.provide(
"executeHumanAssisted",
"Prompts the user through a CLI to either enter text, or to confirm text that you have generated",
::callHumanAssistance,
),
)
fun callHumanAssistance(): String {
var response = ""
scope.launch {
response = executeHumanAssistance()
}
return response
}
}
abstract class HumanAndLLMAssisted(
override val scope: CoroutineScope,
) : KoreAgent, HumanAssisted {
override var chatHistory: ChatHistory = ChatHistory.Threaded.Uninitialized
set(value) {
field = value
updateCompletionRequest()
}
override var completionRequest: ChatCompletionRequest? = null
}
}
| 1 | Kotlin | 0 | 1 | 750ba432de2b36db3f9bc447cd73faaa42616017 | 1,662 | kore-ai | Apache License 2.0 |
compiler/testData/codegen/box/inlineClasses/jvm8DefaultInterfaceMethods/jvmDefaultSafeCall.kt | JetBrains | 3,432,266 | false | null | // !JVM_DEFAULT_MODE: all
// TARGET_BACKEND: JVM
// WITH_STDLIB
// JVM_TARGET: 1.8
interface IOk {
fun ok(): String = "OK"
}
@Suppress("OPTIONAL_DECLARATION_USAGE_IN_NON_COMMON_SOURCE")
@kotlin.jvm.JvmInline
value class InlineClass(val s: String) : IOk
fun test(x: InlineClass?) = x?.ok() ?: "Failed"
fun box() = test(InlineClass(""))
| 125 | Kotlin | 4813 | 39,375 | 83d2d2cfcfc3d9903c902ca348f331f89bed1076 | 343 | kotlin | Apache License 2.0 |
app/src/main/kotlin/eu/ezytarget/processingtemplate/realms/tesseract/TesseractRealm.kt | easytarget2000 | 266,631,921 | false | {"Kotlin": 125275} | package eu.ezytarget.processingtemplate.realms.tesseract
import eu.ezytarget.processingtemplate.nextFloatInRange
import eu.ezytarget.processingtemplate.realms.Realm
import processing.core.PApplet
import processing.core.PConstants
import processing.core.PGraphics
import processing.core.PVector
class TesseractRealm(
private val minNumberOfShapes: Int = 1,
private val maxNumberOfShapes: Int = 5,
maxColorValue: Float = 1f
) : Realm() {
var numberOfIterations = 1
var strokeWeightGrowthVelocity = 0.01f
var minStrokeWeight = 4f
var maxStrokeWeight = 16f
var strokeWeight = minStrokeWeight
var hue = 0.5f
var hueVelocity = 0.01f
var minHue = 0f
var maxHue = maxColorValue
var saturation = 0.7f
var brightness = 1f
var alpha = 0.5f
var xRotation = 1f
var zRotation = 1f
var xRotationVelocity = 0.021f
var zRotationVelocity = 0.002f
var angleVelocity = random.nextFloatInRange(from = 0.001f, until = 0.005f)
var logTesseractInits = false
private var angle = 0f
private lateinit var tesseracts: List<Tesseract>
override fun setup(pApplet: PApplet, pGraphics: PGraphics) {
super.setup(pApplet, pGraphics)
val numberOfShapes = if (minNumberOfShapes >= maxNumberOfShapes) {
minNumberOfShapes
} else {
random.nextInt(from = minNumberOfShapes, until = maxNumberOfShapes)
}
tesseracts = (0 until numberOfShapes).map {
val scale = random.nextFloatInRange(from = 0.1f, until = 0.5f)
Tesseract(scale)
}
if (logTesseractInits) {
tesseracts.forEach {
println("TesseractRealm: setup(): scale: ${it.scale} ")
}
}
}
override fun update(pApplet: PApplet) {
super.update(pApplet)
updateColorValues()
updateStrokeWeight()
angle += angleVelocity
}
override fun drawIn(pGraphics: PGraphics) {
super.drawIn(pGraphics)
pGraphics.beginDraw()
pGraphics.push()
pGraphics.translate(pGraphics.width / 2f, pGraphics.height / 2f)
updateRotations(pGraphics)
pGraphics.rotateX(-PConstants.PI / 2f)
pGraphics.strokeWeight(strokeWeight)
pGraphics.stroke(hue, saturation, brightness, alpha)
repeat(numberOfIterations) {
pGraphics.pushMatrix()
pGraphics.rotateZ((it / numberOfIterations.toFloat()) * PConstants.TWO_PI)
tesseracts.forEach { tesseract ->
draw(tesseract, pGraphics)
}
pGraphics.popMatrix()
}
pGraphics.pop()
pGraphics.endDraw()
}
private fun draw(tesseract: Tesseract, pGraphics: PGraphics) {
val projectedVerticesIn3D = tesseract.vertices.map { vertex4D ->
val rotationXY = arrayOf(
floatArrayOf(PApplet.cos(angle), -PApplet.sin(angle), 0f, 0f),
floatArrayOf(PApplet.sin(angle), PApplet.cos(angle), 0f, 0f),
floatArrayOf(0f, 0f, 1f, 0f),
floatArrayOf(0f, 0f, 0f, 1f)
)
val rotationZW = arrayOf(
floatArrayOf(1f, 0f, 0f, 0f),
floatArrayOf(0f, 1f, 0f, 0f),
floatArrayOf(0f, 0f, PApplet.cos(angle), -PApplet.sin(angle)),
floatArrayOf(0f, 0f, PApplet.sin(angle), PApplet.cos(angle))
)
val xyRotatedVertex = MatrixCalculator.matmul4(rotationXY, vertex4D)
val fullyRotatedVertex =
MatrixCalculator.matmul4(rotationZW, xyRotatedVertex)
val distance = 2f
val w = 1 / (distance - fullyRotatedVertex.w)
val projection = arrayOf(
floatArrayOf(w, 0f, 0f, 0f),
floatArrayOf(0f, w, 0f, 0f),
floatArrayOf(0f, 0f, w, 0f)
)
val projected =
MatrixCalculator.matmul(projection, fullyRotatedVertex)
projected.mult(pGraphics.width * tesseract.scale)
projected
}
(0..3).forEach { vertexIndex ->
connectVertices(
0,
vertexIndex,
(vertexIndex + 1) % 4,
projectedVerticesIn3D,
pGraphics
)
connectVertices(
0,
vertexIndex + 4,
(vertexIndex + 1) % 4 + 4,
projectedVerticesIn3D,
pGraphics
)
connectVertices(
0,
vertexIndex,
vertexIndex + 4,
projectedVerticesIn3D,
pGraphics
)
}
(0..3).forEach { vertexIndex ->
connectVertices(
8,
vertexIndex,
(vertexIndex + 1) % 4,
projectedVerticesIn3D,
pGraphics
)
connectVertices(
8,
vertexIndex + 4,
(vertexIndex + 1) % 4 + 4,
projectedVerticesIn3D,
pGraphics
)
connectVertices(
8,
vertexIndex,
vertexIndex + 4,
projectedVerticesIn3D,
pGraphics
)
}
(0..7).forEach { vertexIndex ->
connectVertices(
0,
vertexIndex,
vertexIndex + 8,
projectedVerticesIn3D,
pGraphics
)
}
}
private fun updateColorValues() {
hue += hueVelocity
if (hue > maxHue) {
hue = minHue
}
}
private fun updateStrokeWeight() {
strokeWeight += strokeWeightGrowthVelocity
if (strokeWeight > maxStrokeWeight) {
strokeWeight = minStrokeWeight
}
}
private fun updateRotations(pGraphics: PGraphics) {
zRotation += zRotationVelocity
pGraphics.rotateZ(zRotation)
xRotation += xRotationVelocity
pGraphics.rotateX(xRotation)
}
private fun connectVertices(
offset: Int = 0,
index1: Int,
index2: Int,
vertices: List<PVector>,
pGraphics: PGraphics
) {
val vertex1 = vertices[index1 + offset]
val vertex2 = vertices[index2 + offset]
pGraphics.line(
vertex1.x,
vertex1.y,
vertex1.z,
vertex2.x,
vertex2.y,
vertex2.z
)
}
}
| 0 | Kotlin | 0 | 0 | 78f5aa56882a8cb16017781bd0060ba36ba1793b | 6,604 | kotlin-processing-template | ANTLR Software Rights Notice |
src/boj_25314/Kotlin.kt | devetude | 70,114,524 | false | {"Java": 563470, "Kotlin": 54466} | package boj_25314
fun main() {
val n = readln().toInt()
val times = n / 4
val result = buildString {
repeat(times) { append("long ") }
appendLine(value = "int")
}
System.out.bufferedWriter().use {
it.write(result)
it.flush()
}
}
| 0 | Java | 7 | 20 | 1a42ce0351c5fbf71b14ba053978b5bb3b98e855 | 288 | BOJ-PSJ | Apache License 2.0 |
core/src/commonMain/kotlin/org/kobjects/greenspun/core/type/FuncType.kt | kobjects | 340,712,554 | false | {"Kotlin": 151490, "Ruby": 1673} | package org.kobjects.greenspun.core.type
import org.kobjects.greenspun.core.binary.WasmTypeCode
import org.kobjects.greenspun.core.binary.WasmWriter
import org.kobjects.greenspun.core.expr.Expr
data class FuncType(
val index: Int,
val returnType: List<org.kobjects.greenspun.core.type.WasmType>,
val parameterTypes: List<org.kobjects.greenspun.core.type.WasmType>,
) : org.kobjects.greenspun.core.type.WasmType {
override fun createConstant(value: Any): Expr {
throw UnsupportedOperationException("TODO: Re-Implement when FuncInterface is a node")
}
override fun toWasm(writer: WasmWriter) {
writer.writeTypeCode(WasmTypeCode.FUNC)
writer.writeU32(parameterTypes.size)
for (t in parameterTypes) {
t.toWasm(writer)
}
writer.writeU32(returnType.size)
for (t in returnType) {
t.toWasm(writer)
}
}
fun matches(returnType: List<org.kobjects.greenspun.core.type.WasmType>, parameterTypes: List<org.kobjects.greenspun.core.type.WasmType>) =
this.returnType == returnType && this.parameterTypes == parameterTypes
} | 0 | Kotlin | 0 | 0 | b7799357b809138cb6e3744723d7ca87e524e18b | 1,140 | greenspun | Apache License 2.0 |
app/src/main/java/com/oajstudios/pocketshop/models/CountryModel.kt | AYOMITIDE-OAJ | 617,064,177 | false | null | package com.oajstudios.pocketshop.models
import java.io.Serializable
data class CountryModel(
val code : String,
val name : String,
val states : ArrayList<State>,
val _links: Links
): Serializable
data class State(
val code : String,
val name : String
) : Serializable | 1 | Kotlin | 0 | 10 | 48cf66963987da31392350a9afec1125b9cfa4fa | 299 | pocketshop | Apache License 2.0 |
app/src/main/java/studio/mandysa/music/logic/bean/PlaylistBean.kt | ZXHHYJ | 575,649,635 | false | null | package studio.mandysa.music.logic.bean
import mandysax.anna2.annotation.Value
class PlaylistBean {
@Value("id")
lateinit var id: String
@Value("name")
lateinit var name: String
/*@Value("copywriter")
public String info;*/
@Value("picUrl")
lateinit var picUrl: String
} | 0 | Kotlin | 0 | 2 | db3678f535f249ee16aeceedb7a7eb9331cfdf71 | 305 | MandySa-Music | Apache License 2.0 |
core/ui/src/main/kotlin/ru/tech/imageresizershrinker/core/ui/widget/preferences/ScreenPreference.kt | T8RIN | 478,710,402 | false | null | /*
* ImageToolbox is an image editor for android
* Copyright (c) 2024 T8RIN (<NAME>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.
*
* You should have received a copy of the Apache License
* along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package ru.tech.imageresizershrinker.core.ui.widget.preferences
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import ru.tech.imageresizershrinker.core.ui.utils.navigation.Screen
@Composable
internal fun ScreenPreference(
screen: Screen,
navigate: (Screen) -> Unit
) {
val basePreference = @Composable {
PreferenceItem(
onClick = { navigate(screen) },
startIcon = screen.icon,
title = stringResource(screen.title),
subtitle = stringResource(screen.subtitle),
modifier = Modifier.fillMaxWidth()
)
}
when (screen) {
is Screen.GifTools -> {
if (screen.type != null) {
PreferenceItem(
onClick = { navigate(screen) },
startIcon = screen.type.icon,
title = stringResource(screen.type.title),
subtitle = stringResource(screen.type.subtitle),
modifier = Modifier.fillMaxWidth()
)
} else basePreference()
}
is Screen.PdfTools -> {
if (screen.type != null) {
PreferenceItem(
onClick = { navigate(screen) },
startIcon = screen.type.icon,
title = stringResource(screen.type.title),
subtitle = stringResource(screen.type.subtitle),
modifier = Modifier.fillMaxWidth()
)
} else basePreference()
}
is Screen.Filter -> {
if (screen.type != null) {
PreferenceItem(
onClick = { navigate(screen) },
startIcon = screen.type.icon,
title = stringResource(screen.type.title),
subtitle = stringResource(screen.type.subtitle),
modifier = Modifier.fillMaxWidth()
)
} else basePreference()
}
is Screen.ApngTools -> {
if (screen.type != null) {
PreferenceItem(
onClick = { navigate(screen) },
startIcon = screen.type.icon,
title = stringResource(screen.type.title),
subtitle = stringResource(screen.type.subtitle),
modifier = Modifier.fillMaxWidth()
)
} else basePreference()
}
is Screen.JxlTools -> {
if (screen.type != null) {
PreferenceItem(
onClick = { navigate(screen) },
startIcon = screen.type.icon,
title = stringResource(screen.type.title),
subtitle = stringResource(screen.type.subtitle),
modifier = Modifier.fillMaxWidth()
)
} else basePreference()
}
else -> basePreference()
}
} | 24 | null | 90 | 3,817 | 486410d4a9ea3c832fc5aa63eb5bdc7b1fab871d | 3,770 | ImageToolbox | Apache License 2.0 |
AcornUiLwjglBackend/src/com/acornui/jvm/LwjglApplication.kt | konsoletyper | 105,533,124 | false | null | /*
* Copyright 2015 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.jvm
import com.acornui.assertionsEnabled
import com.acornui.browser.decodeUriComponent2
import com.acornui.browser.encodeUriComponent2
import com.acornui.component.*
import com.acornui.component.scroll.ScrollArea
import com.acornui.component.scroll.ScrollRect
import com.acornui.component.text.EditableTextField
import com.acornui.component.text.TextArea
import com.acornui.component.text.TextField
import com.acornui.component.text.TextInput
import com.acornui.core.AppConfig
import com.acornui.core.UserInfo
import com.acornui.core.assets.AssetManager
import com.acornui.core.assets.AssetManagerImpl
import com.acornui.core.assets.AssetTypes
import com.acornui.core.audio.AudioManager
import com.acornui.core.cursor.CursorManager
import com.acornui.core.di.*
import com.acornui.core.focus.FocusManager
import com.acornui.core.focus.FocusManagerImpl
import com.acornui.core.focus.fakeFocusMouse
import com.acornui.core.graphics.Camera
import com.acornui.core.graphics.OrthographicCamera
import com.acornui.core.graphics.Window
import com.acornui.core.graphics.autoCenterCamera
import com.acornui.core.i18n.Locale
import com.acornui.core.input.InteractivityManager
import com.acornui.core.input.InteractivityManagerImpl
import com.acornui.core.input.KeyInput
import com.acornui.core.input.MouseInput
import com.acornui.core.input.interaction.clickDispatcher
import com.acornui.core.io.BufferFactory
import com.acornui.core.io.JSON_KEY
import com.acornui.core.io.file.Files
import com.acornui.core.io.file.FilesImpl
import com.acornui.core.lineSeparator
import com.acornui.core.persistance.Persistence
import com.acornui.core.popup.PopUpManager
import com.acornui.core.popup.PopUpManagerImpl
import com.acornui.core.request.RestServiceFactory
import com.acornui.core.selection.SelectionManager
import com.acornui.core.selection.SelectionManagerImpl
import com.acornui.core.text.DateTimeFormatter
import com.acornui.core.text.NumberFormatter
import com.acornui.core.time.TimeDriver
import com.acornui.core.time.TimeDriverImpl
import com.acornui.core.time.time
import com.acornui.gl.component.*
import com.acornui.gl.component.text.*
import com.acornui.gl.core.Gl20
import com.acornui.gl.core.GlState
import com.acornui.io.file.FilesManifestSerializer
import com.acornui.jvm.io.JvmHttpRequest
import com.acornui.jvm.audio.NoAudioException
import com.acornui.jvm.audio.OpenAlAudioManager
import com.acornui.jvm.audio.OpenAlMusicLoader
import com.acornui.jvm.audio.OpenAlSoundLoader
import com.acornui.jvm.cursor.JvmCursorManager
import com.acornui.jvm.graphics.GlfwWindowImpl
import com.acornui.jvm.graphics.JvmGl20Debug
import com.acornui.jvm.graphics.JvmTextureLoader
import com.acornui.jvm.graphics.LwjglGl20
import com.acornui.jvm.input.JvmMouseInput
import com.acornui.jvm.input.LwjglKeyInput
import com.acornui.jvm.io.JvmBufferFactory
import com.acornui.jvm.loader.JvmTextLoader
import com.acornui.jvm.persistance.LwjglPersistence
import com.acornui.jvm.text.DateTimeFormatterImpl
import com.acornui.jvm.text.NumberFormatterImpl
import com.acornui.jvm.time.TimeProviderImpl
import com.acornui.logging.ILogger
import com.acornui.logging.Log
import com.acornui.serialization.JsonSerializer
import org.lwjgl.Version
import org.lwjgl.glfw.GLFW
import org.lwjgl.glfw.GLFWWindowRefreshCallback
import java.io.File
import java.io.FileNotFoundException
import java.io.FileReader
import java.net.URLDecoder
import java.net.URLEncoder
import java.util.Locale as LocaleJvm
/**
* @author nbilyk
*/
open class LwjglApplication(
private val config: AppConfig = AppConfig(),
onReady: Owned.(stage: Stage) -> Unit
) {
val bootstrap = Bootstrap()
// If accessing the window id, use bootstrap.on(Window) { }
protected var windowId: Long = -1
init {
initializeUserInfo()
initializeConfig()
initializeLwjglNative()
bootstrap.on(AppConfig) {
initializeBootstrap()
bootstrap.then {
bootstrap.lock()
val stage = bootstrap[Stage]
stage.onReady(stage)
stage.addElement(bootstrap[PopUpManager].view)
bootstrap.run()
}
}
}
protected open fun initializeUserInfo() {
UserInfo.isDesktop = true
UserInfo.isOpenGl = true
UserInfo.isTouchDevice = false
UserInfo.languages = listOf(Locale(LocaleJvm.getDefault().toLanguageTag()))
println("UserInfo: $UserInfo")
}
protected open fun initializeConfig() {
val buildVersion = File("assets/build.txt")
if (buildVersion.exists()) {
config.version.build = buildVersion.readText().toInt()
}
Log.info("Build ${config.version.toVersionString()}")
bootstrap[AppConfig] = config
}
/**
* If the native libraries for lwjgl aren't included in the jar, set the path using
* `System.setProperty("org.lwjgl.librarypath", "your/natives/path")`
*/
protected open fun initializeLwjglNative() {
println("LWJGL Version: ${Version.getVersion()}")
}
protected open fun initializeBootstrap() {
initializeDebug()
initializeSystem()
initializeLogging()
initializeNumber()
initializeString()
initializeTime()
initializeBufferFactory()
initializeJson()
initializeGl()
initializeWindow()
initializeGlState()
initializeMouseInput()
initializeKeyInput()
initializeCamera()
initializeFiles()
initializeRequest()
initializeTimeDriver()
initializeAssetManager()
initializeTextures()
initializeAudio()
initializeFocusManager()
initializeInteractivity()
initializeCursorManager()
initializeSelectionManager()
initializePersistence()
initializeTextFormatters()
initializeComponents()
bootstrap.then {
initializeStage()
initializePopUpManager()
initializeSpecialInteractivity()
}
}
protected open fun initializeDebug() {
config.debug = config.debug || System.getProperty("debug")?.toLowerCase() == "true"
if (config.debug) {
assertionsEnabled = true
Log.info("Assertions enabled")
}
}
protected open fun initializeSystem() {
lineSeparator = System.lineSeparator()
}
protected open fun initializeLogging() {
if (config.debug) {
Log.level = ILogger.DEBUG
} else {
Log.level = ILogger.INFO
}
}
/**
* Initializes number constants and methods
*/
protected open fun initializeNumber() {
}
protected open fun initializeString() {
encodeUriComponent2 = {
str ->
URLEncoder.encode(str, "UTF-8")
}
decodeUriComponent2 = {
str ->
URLDecoder.decode(str, "UTF-8")
}
}
protected open fun initializeTime() {
time = TimeProviderImpl()
}
protected open fun initializeBufferFactory() {
BufferFactory.instance = JvmBufferFactory()
}
private fun initializeJson() {
bootstrap[JSON_KEY] = JsonSerializer
}
protected open fun initializeGl() {
bootstrap[Gl20] = if (config.debug) JvmGl20Debug() else LwjglGl20()
}
protected open fun initializeWindow() {
bootstrap.on(Gl20) {
val window = GlfwWindowImpl(config.window, config.gl, bootstrap[Gl20], config.debug)
windowId = window.windowId
bootstrap[Window] = window
}
}
protected open fun initializeGlState() {
bootstrap.on(Gl20) {
bootstrap[GlState] = GlState(bootstrap[Gl20])
}
}
protected open fun initializeMouseInput() {
bootstrap.on(Window) {
bootstrap[MouseInput] = JvmMouseInput(windowId)
}
}
protected open fun initializeKeyInput() {
bootstrap.on(Window) {
bootstrap[KeyInput] = LwjglKeyInput(windowId)
}
}
protected open fun initializeCamera() {
bootstrap.on(Window) {
val camera = OrthographicCamera()
bootstrap[Camera] = camera
bootstrap[Window].autoCenterCamera(camera)
}
}
protected open fun initializeFiles() {
val manifestFile = File(config.rootPath + config.assetsManifestPath)
if (!manifestFile.exists()) throw FileNotFoundException(config.rootPath + config.assetsManifestPath)
val reader = FileReader(manifestFile)
val jsonStr = reader.readText()
val files = FilesImpl(JsonSerializer.read(jsonStr, FilesManifestSerializer))
bootstrap[Files] = files
}
protected open fun initializeRequest() {
RestServiceFactory.instance = JvmHttpRequest
}
protected open fun initializeFocusManager() {
bootstrap[FocusManager] = FocusManagerImpl()
}
protected open fun initializeAssetManager() {
bootstrap.on(Files, TimeDriver) {
val assetManager = AssetManagerImpl(config.rootPath, bootstrap[Files])
val isAsync = true
assetManager.setLoaderFactory(AssetTypes.TEXT, { JvmTextLoader(Charsets.UTF_8, isAsync, bootstrap[TimeDriver]) })
bootstrap[AssetManager] = assetManager
}
}
protected open fun initializeTextures() {
bootstrap.on(AssetManager, Gl20, GlState, TimeDriver) {
val isAsync = true
bootstrap[AssetManager].setLoaderFactory(AssetTypes.TEXTURE, { JvmTextureLoader(bootstrap[Gl20], bootstrap[GlState], isAsync, bootstrap[TimeDriver]) })
}
}
protected open fun initializeAudio() {
try {
val audioManager = OpenAlAudioManager()
bootstrap[AudioManager] = audioManager
bootstrap.on(AssetManager, TimeDriver) {
val timeDriver = bootstrap[TimeDriver]
timeDriver.addChild(audioManager)
val assetManager = bootstrap[AssetManager]
val isAsync = true
OpenAlSoundLoader.registerDefaultDecoders()
assetManager.setLoaderFactory(AssetTypes.SOUND, { OpenAlSoundLoader(audioManager, isAsync, timeDriver) })
OpenAlMusicLoader.registerDefaultDecoders()
assetManager.setLoaderFactory(AssetTypes.MUSIC, { OpenAlMusicLoader(audioManager) })
}
} catch (e: NoAudioException) {
Log.warn("No Audio device found.")
}
}
protected open fun initializeInteractivity() {
bootstrap.on(MouseInput, KeyInput, FocusManager) {
bootstrap[InteractivityManager] = InteractivityManagerImpl(bootstrap[MouseInput], bootstrap[KeyInput], bootstrap[FocusManager])
}
}
protected open fun initializeTimeDriver() {
val timeDriver = TimeDriverImpl()
timeDriver.activate()
bootstrap[TimeDriver] = timeDriver
}
protected open fun initializeCursorManager() {
bootstrap.on(AssetManager, Window) {
bootstrap[CursorManager] = JvmCursorManager(bootstrap[AssetManager], windowId)
}
}
protected open fun initializeSelectionManager() {
bootstrap[SelectionManager] = SelectionManagerImpl()
}
protected open fun initializePersistence() {
bootstrap[Persistence] = LwjglPersistence(config.version, config.window.title)
}
protected open fun initializeTextFormatters() {
bootstrap[NumberFormatter.FACTORY_KEY] = { NumberFormatterImpl(it) }
bootstrap[DateTimeFormatter.FACTORY_KEY] = { DateTimeFormatterImpl(it) }
}
/**
* The last chance to set dependencies on the application scope.
*/
protected open fun initializeComponents() {
bootstrap[NativeComponent.FACTORY_KEY] = { NativeComponentDummy }
bootstrap[NativeContainer.FACTORY_KEY] = { NativeContainerDummy }
bootstrap[TextField.FACTORY_KEY] = ::GlTextField
bootstrap[EditableTextField.FACTORY_KEY] = ::GlEditableTextField
bootstrap[TextInput.FACTORY_KEY] = ::GlTextInput
bootstrap[TextArea.FACTORY_KEY] = ::GlTextArea
bootstrap[TextureComponent.FACTORY_KEY] = ::GlTextureComponent
bootstrap[ScrollArea.FACTORY_KEY] = ::GlScrollArea
bootstrap[ScrollRect.FACTORY_KEY] = ::GlScrollRect
bootstrap[Rect.FACTORY_KEY] = ::GlRect
}
protected open fun initializeStage() {
bootstrap[Stage] = GlStageImpl(OwnedImpl(null, bootstrap.injector))
}
protected open fun initializePopUpManager() {
bootstrap[PopUpManager] = PopUpManagerImpl(bootstrap[Stage])
}
protected open fun initializeSpecialInteractivity() {
val clickDispatcher = bootstrap.clickDispatcher()
clickDispatcher.init()
bootstrap.fakeFocusMouse()
}
open fun Scoped.run() {
JvmApplicationRunner(injector, windowId)
dispose()
}
private fun dispose() {
println("Application#dispose")
// Should be disposed in the reverse order they were created.
BitmapFontRegistry.dispose()
bootstrap.dispose()
}
}
class JvmApplicationRunner(
override val injector: Injector,
windowId: Long
) : Scoped {
private val window = inject(Window)
private val appConfig = inject(AppConfig)
private val timeDriver = inject(TimeDriver)
private val stage = inject(Stage)
private val refreshCallback = object : GLFWWindowRefreshCallback() {
override fun invoke(windowId: Long) {
window.requestRender()
tick()
}
}
init {
Log.info("Application#start")
stage.activate()
// The window has been damaged.
GLFW.glfwSetWindowRefreshCallback(windowId, refreshCallback)
var timeMs = time.nowMs()
while (!window.isCloseRequested()) {
// Poll for window events. Input callbacks will be invoked at this time.
GLFW.glfwPollEvents()
tick()
val t = time.nowMs()
val sleepTime = (appConfig.stepTime * 1000f - (t - timeMs)).toLong()
if (sleepTime > 0) Thread.sleep(sleepTime)
timeMs = t
}
GLFW.glfwSetWindowRefreshCallback(windowId, null)
}
private var nextTick: Long = 0
private fun tick() {
val stepTimeFloat = appConfig.stepTime
val stepTimeMs = 1000 / appConfig.frameRate
var loops = 0
val now: Long = time.msElapsed()
// Do a best attempt to keep the time driver in sync, but stage updates and renders may be sacrificed.
while (now > nextTick) {
nextTick += stepTimeMs
timeDriver.update(stepTimeFloat)
if (++loops > MAX_FRAME_SKIP) {
// If we're too far behind, break and reset.
nextTick = time.msElapsed() + stepTimeMs
break
}
}
if (window.shouldRender(true)) {
stage.update()
window.renderBegin()
stage.render()
window.renderEnd()
}
// TODO: capped frame rates?
}
companion object {
/**
* The maximum number of update() calls before a render is required.
*/
private val MAX_FRAME_SKIP = 10
}
} | 0 | Kotlin | 3 | 0 | a84b559fe1d1cad01eb9223ad9af73b4d5fb5bc8 | 14,195 | Acorn | Apache License 2.0 |
decompose/src/commonTest/kotlin/com/arkivanov/decompose/router/stack/ChildStackTest.kt | arkivanov | 437,015,897 | false | null | package com.arkivanov.decompose.router.stack
import com.arkivanov.decompose.Child
import kotlin.test.Test
import kotlin.test.assertContentEquals
@Suppress("TestFunctionName")
class ChildStackTest {
@Test
fun GIVEN_back_stack_empty_WHEN_items_THEN_returns_list_with_active_child() {
val activeChild = child(configuration = "A")
val stack = ChildStack(active = activeChild, backStack = emptyList())
val items = stack.items
assertContentEquals(listOf(activeChild), items)
}
@Test
fun GIVEN_back_stack_not_empty_WHEN_items_THEN_returns_list_with_back_stack_and_active_child() {
val activeChild = child(configuration = "A")
val backStack = List(3) { child(configuration = it.toString()) }
val stack = ChildStack(active = activeChild, backStack = backStack)
val items = stack.items
assertContentEquals(backStack + activeChild, items)
}
private fun child(configuration: String): Child.Created<String, String> =
Child.Created(configuration = configuration, instance = configuration)
}
| 6 | Kotlin | 37 | 976 | 5e9d7de05b3c4d15a9036b72a99e5927683c5742 | 1,094 | Decompose | Apache License 2.0 |
core/src/jsMain/kotlin/kotlinx/rpc/internal/WithRPCStubObject.js.kt | Kotlin | 739,292,079 | false | null | /*
* Copyright 2023-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("detekt.MatchingDeclarationName")
package kotlinx.rpc.internal
import js.objects.Object
import kotlinx.rpc.RPC
import kotlin.reflect.AssociatedObjectKey
import kotlin.reflect.ExperimentalAssociatedObjects
import kotlin.reflect.KClass
import kotlin.reflect.findAssociatedObject
@InternalRPCApi
@AssociatedObjectKey
@OptIn(ExperimentalAssociatedObjects::class)
@Target(AnnotationTarget.CLASS)
public annotation class WithRPCStubObject(
@Suppress("unused")
val stub: KClass<out RPCStubObject<out RPC>>
)
@InternalRPCApi
public actual fun <R : Any> findRPCStubProvider(kClass: KClass<*>, resultKClass: KClass<R>): R {
val associatedObject = kClass.findAssociatedObjectImpl(WithRPCStubObject::class, resultKClass)
?: internalError("Unable to find $kClass associated object")
if (resultKClass.isInstance(associatedObject)) {
@Suppress("UNCHECKED_CAST")
return associatedObject as R
}
internalError(
"Located associated object is not of desired type $resultKClass, " +
"instead found $associatedObject of class " +
(associatedObject::class.qualifiedClassNameOrNull ?: associatedObject::class.js.name)
)
}
private val KClass<*>.jClass get(): JsClass<*> = asDynamic().jClass_1.unsafeCast<JsClass<*>>()
/**
* Workaround for bugs in [findAssociatedObject]
* See KT-70132 for more info.
*
* This function uses std-lib's implementation and accounts for the bug in the compiler
*/
internal fun <T : Annotation, R : Any> KClass<*>.findAssociatedObjectImpl(
annotationClass: KClass<T>,
resultKClass: KClass<R>,
): Any? {
val key = annotationClass.jClass.asDynamic().`$metadata$`?.associatedObjectKey?.unsafeCast<Int>() ?: return null
val map = jClass.asDynamic().`$metadata$`?.associatedObjects ?: return null
val factory = map[key] ?: return fallbackFindAssociatedObjectImpl(map, resultKClass)
return factory()
}
private fun <R : Any> fallbackFindAssociatedObjectImpl(map: dynamic, resultKClass: KClass<R>): R? {
return Object.entries(map as Any)
.mapNotNull { (_, factory) ->
val unsafeFactory = factory.asDynamic()
val maybeObject = unsafeFactory()
if (resultKClass.isInstance(maybeObject)) {
maybeObject.unsafeCast<R>()
} else {
null
}
}
.singleOrNull()
}
| 29 | null | 17 | 733 | b946964ca7838d40ba68ad98fe4056f3ed17c635 | 2,537 | kotlinx-rpc | Apache License 2.0 |
ocpp-1-6-core/src/main/kotlin/com/izivia/ocpp/core16/model/logstatusnotification/enumeration/UpdateLogStatusEnumType.kt | IZIVIA | 501,708,979 | false | {"Kotlin": 1934096} | package com.izivia.ocpp.core16.model.logstatusnotification.enumeration
enum class UpdateLogStatusEnumType(val value: String) {
BadMessage("BadMessage"),
Idle("Idle"),
NotSupportedOperation("NotSupportedOperation"),
PermissionDenied("PermissionDenied"),
Uploaded("Uploaded"),
UploadFailure("UploadFailure"),
Uploading("Uploading")
}
| 6 | Kotlin | 10 | 32 | bd8e7334ae05ea75d02d96a508269acbe076bcd8 | 361 | ocpp-toolkit | MIT License |
app/src/main/java/com/niu/jetpack_android_online/pages/publish/PreviewActivity.kt | frannnnnk | 869,532,182 | false | {"Kotlin": 116154} | package com.niu.jetpack_android_online.pages.publish
import androidx.appcompat.app.AppCompatActivity
class PreviewActivity : AppCompatActivity() {
} | 0 | Kotlin | 0 | 0 | ef6f71986283c7932e66b081ee11bdf4429ccc10 | 150 | jetpack_android_online | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/DriverWoman.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.DriverWoman: ImageVector
get() {
if (_driverWoman != null) {
return _driverWoman!!
}
_driverWoman = Builder(name = "DriverWoman", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(18.0f, 24.0f)
horizontalLineToRelative(-3.0f)
curveToRelative(0.0f, -1.654f, -1.346f, -3.0f, -3.0f, -3.0f)
reflectiveCurveToRelative(-3.0f, 1.346f, -3.0f, 3.0f)
horizontalLineToRelative(-3.0f)
curveToRelative(0.0f, -3.309f, 2.691f, -6.0f, 6.0f, -6.0f)
reflectiveCurveToRelative(6.0f, 2.691f, 6.0f, 6.0f)
close()
moveTo(20.771f, 17.989f)
curveToRelative(-0.671f, -2.349f, -2.846f, -3.989f, -5.289f, -3.989f)
horizontalLineToRelative(-6.966f)
curveToRelative(-2.442f, 0.0f, -4.617f, 1.64f, -5.289f, 3.989f)
lineToRelative(-1.717f, 6.011f)
horizontalLineToRelative(3.12f)
lineToRelative(1.482f, -5.187f)
curveToRelative(0.305f, -1.067f, 1.293f, -1.813f, 2.404f, -1.813f)
horizontalLineToRelative(6.966f)
curveToRelative(1.11f, 0.0f, 2.099f, 0.746f, 2.404f, 1.813f)
lineToRelative(1.482f, 5.187f)
horizontalLineToRelative(3.12f)
lineToRelative(-1.717f, -6.011f)
close()
moveTo(12.0f, 12.0f)
curveToRelative(0.836f, 0.0f, 1.627f, -0.183f, 2.351f, -0.495f)
lineToRelative(-0.525f, -3.085f)
curveToRelative(-0.5f, 0.399f, -1.256f, 0.579f, -1.826f, 0.579f)
curveToRelative(-1.654f, 0.0f, -3.0f, -1.346f, -3.0f, -3.0f)
curveToRelative(1.145f, 0.0f, 3.621f, -1.282f, 4.849f, -2.418f)
curveToRelative(0.865f, 0.576f, 1.508f, 1.528f, 1.666f, 2.631f)
lineToRelative(0.984f, 5.787f)
curveToRelative(1.232f, 0.182f, 2.384f, 0.663f, 3.363f, 1.385f)
curveToRelative(-0.002f, -0.007f, -1.386f, -7.653f, -1.386f, -7.653f)
curveToRelative(-0.497f, -3.271f, -3.271f, -5.732f, -6.477f, -5.732f)
reflectiveCurveToRelative(-5.979f, 2.46f, -6.477f, 5.732f)
curveToRelative(0.0f, 0.0f, -1.376f, 7.622f, -1.382f, 7.648f)
curveToRelative(0.978f, -0.72f, 2.128f, -1.2f, 3.358f, -1.381f)
horizontalLineToRelative(4.5f)
close()
}
}
.build()
return _driverWoman!!
}
private var _driverWoman: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,545 | icons | MIT License |
buildSrc/src/main/kotlin/Dependencies.kt | imnithish | 475,069,026 | false | {"Kotlin": 64768} | object Dependencies {
val kotlin by lazy { "androidx.core:core-ktx:${Versions.kotlin}" }
val compose by lazy { "androidx.compose.ui:ui:${Versions.compose}" }
val composeFoundation by lazy { "androidx.compose.foundation:foundation:1.2.0-alpha06" }
val material by lazy { "androidx.compose.material:material:${Versions.compose}" }
val composePreview by lazy { "androidx.compose.ui:ui-tooling-preview:${Versions.compose}" }
val androidXLifecycle by lazy { "androidx.lifecycle:lifecycle-runtime-ktx:${Versions.androidx_lifecycle}" }
val activityCompose by lazy { "androidx.activity:activity-compose:${Versions.activity_compose}" }
val jUnit by lazy { "junit:junit:4.13.2" }
val jUnitTest by lazy { "androidx.test.ext:junit:1.1.3" }
val espressoAndroidTest by lazy { "androidx.test.espresso:espresso-core:3.4.0" }
val composeJUnitAndroidTest by lazy { "androidx.compose.ui:ui-test-junit4:1.1.1" }
val composeTooling by lazy { "androidx.compose.ui:ui-tooling:1.1.1" }
object Networking {
val okHttpBOM by lazy { "com.squareup.okhttp3:okhttp-bom:${Versions.okhttp_bom}" }
val okHttp by lazy { "com.squareup.okhttp3:okhttp" }
val okHttpLoggingInterceptor by lazy { "com.squareup.okhttp3:logging-interceptor" }
val retrofit by lazy { "com.squareup.retrofit2:retrofit:${Versions.retrofit}" }
}
object Accompanist {
val navigationAnimation by lazy { "com.google.accompanist:accompanist-navigation-animation:${Versions.accompanist}" }
val pager by lazy { "com.google.accompanist:accompanist-pager:${Versions.accompanist}" }
val pagerIndicator by lazy { "com.google.accompanist:accompanist-pager-indicators:${Versions.accompanist}" }
val systemUIController by lazy { "com.google.accompanist:accompanist-systemuicontroller:${Versions.accompanist}" }
val flowRow by lazy { "com.google.accompanist:accompanist-flowlayout:${Versions.accompanist}" }
}
} | 0 | Kotlin | 1 | 1 | a940dd4d3236e8cdc2084175ae60872c7aa972de | 1,973 | enefte-compose | MIT License |
kmp-firebase/src/commonMain/kotlin/com/tweener/firebase/auth/provider/FirebaseAuthProvider.kt | Tweener | 766,294,641 | false | {"Kotlin": 92894, "Ruby": 2255} | package com.tweener.firebase.auth.provider
import com.tweener.firebase.auth.datasource.FirebaseAuthDataSource
import dev.gitlive.firebase.auth.FirebaseUser
import kotlinx.coroutines.flow.Flow
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
/**
* FirebaseAuthProvider class for handling Firebase Authentication.
*
* This abstract class defines the common interface and shared functionality for platform-specific authentication implementations.
*
* @param SignInParams The type of the parameters required for the sign-in process.
* @param firebaseAuthDataSource The data source for Firebase authentication.
*
* @author <NAME>
* @since 26/07/2024
*/
abstract class FirebaseAuthProvider<SignInParams>(
protected val firebaseAuthDataSource: FirebaseAuthDataSource,
) {
/**
* Abstract method to initiate the Google sign-in process.
*
* @param params The parameters required for the sign-in process.
* @param onResponse Callback to handle the result of the sign-in process. It returns a Result object containing a FirebaseUser on success, or an exception on failure.
*/
abstract suspend fun signIn(params: SignInParams? = null, onResponse: (Result<FirebaseUser>) -> Unit)
/**
* Signs out the current user.
*/
suspend fun signOut() {
firebaseAuthDataSource.signOut()
}
/**
* Checks if a user is currently signed in.
*
* @return A Flow emitting a Boolean indicating whether a user is logged in.
*/
fun isUserSignedIn(): Flow<Boolean> = firebaseAuthDataSource.isUserLoggedIn()
/**
* Retrieves the currently signed-in user.
*
* @return The currently signed-in FirebaseUser, or null if no user is signed in.
*/
fun getCurrentUser(): Flow<FirebaseUser?> = firebaseAuthDataSource.getCurrentUser()
/**
* Asserts the given [params] are not null or throws a [MissingSignInParamsException].
*
* @param params The parameters required for the sign-in process.
* @throws MissingSignInParamsException
*/
@OptIn(ExperimentalContracts::class)
protected fun assertSignInParamsNotNull(params: SignInParams? = null): SignInParams {
contract {
returns() implies (params != null)
}
if (params == null) {
throw MissingSignInParamsException(this)
}
return params
}
}
| 1 | Kotlin | 1 | 16 | d71a74fbf04bab5adce4726265f2aacf60918466 | 2,414 | kmp-bom | Apache License 2.0 |
app/src/main/java/net/sucipto/kotlinplayground/entity/Person.kt | tegalan | 179,918,888 | false | null | package net.sucipto.kotlinplayground.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "persons")
data class Person(@PrimaryKey(autoGenerate = true) val id: Int?, val name: String) | 0 | Kotlin | 0 | 0 | 5875f7911a9d0954ae447970db0914c2afb3db52 | 219 | android-jetpack-playground | MIT License |
src/Day02.kt | copperwall | 572,339,673 | false | null | import kotlin.Exception
const val TIE = 3
const val LOSE = 0
const val WIN = 6
enum class Move {
ROCK, PAPER, SCISSORS
}
enum class Outcome {
LOSS, TIE, WIN
}
fun stringToOutcome(s: String): Outcome {
return when (s) {
"X" -> Outcome.LOSS
"Y" -> Outcome.TIE
"Z" -> Outcome.WIN
else -> throw Exception("Unknown string $s")
}
}
val pointsForMove = mapOf(Move.ROCK to 1, Move.PAPER to 2, Move.SCISSORS to 3)
fun strToMove(move: String): Move {
if (move == "A" || move == "X") return Move.ROCK
if (move == "B" || move == "Y") return Move.PAPER
if (move == "C" || move == "Z") return Move.SCISSORS
throw Exception("Unknown move $move")
}
fun main() {
part2()
}
fun part2() {
val testInput = readInput("Day02")
var sum = 0
for (roundStr in testInput) {
sum += calculateRound2(roundStr)
}
println(sum)
}
fun part1() {
val testInput = readInput("Day02")
var sum = 0
for (roundStr in testInput) {
sum += calculateRound1(roundStr)
}
println(sum)
}
fun calculateRound1(round: String): Int {
val (opponentMove, myMove) = round.split(" ").map {
strToMove(it)
}
val movePoints = pointsForMove.getValue(myMove)
val gamePoints = gameLogic(opponentMove, myMove)
return movePoints + gamePoints
}
fun determineMyMove(opponentMove: Move, outcome: Outcome): Move {
when (opponentMove) {
Move.ROCK -> {
return when (outcome) {
Outcome.WIN -> Move.PAPER
Outcome.LOSS -> Move.SCISSORS
Outcome.TIE -> Move.ROCK
}
}
Move.PAPER -> {
return when (outcome) {
Outcome.WIN -> Move.SCISSORS
Outcome.LOSS -> Move.ROCK
Outcome.TIE -> Move.PAPER
}
}
else -> {
return when (outcome) {
Outcome.WIN -> Move.ROCK
Outcome.LOSS -> Move.PAPER
Outcome.TIE -> Move.SCISSORS
}
}
}
}
fun calculateRound2(round: String): Int {
val (opponentMoveStr, outcomeStr) = round.split(" ")
val outcome = stringToOutcome(outcomeStr)
val opponentMove = strToMove(opponentMoveStr)
val myMove = determineMyMove(opponentMove, outcome)
val movePoints = pointsForMove.getValue(myMove)
val gamePoints = gameLogic(opponentMove, myMove)
return movePoints + gamePoints
}
fun gameLogic(opponent: Move, me: Move): Int {
// Tie
if (opponent == me) {
return TIE
}
return if (opponent == Move.ROCK) {
if (me == Move.SCISSORS) LOSE else WIN
} else if (opponent == Move.SCISSORS) {
if (me == Move.PAPER) LOSE else WIN
} else {
// Opponent Paper
if (me == Move.ROCK) LOSE else WIN
}
} | 0 | Kotlin | 0 | 1 | f7b856952920ebd651bf78b0e15e9460524c39bb | 2,854 | advent-of-code-2022 | Apache License 2.0 |
core/src/main/kotlin/io/github/llmagentbuilder/core/planner/ChatOptionsConfigurer.kt | LLMAgentBuilder | 780,391,516 | false | {"Kotlin": 121686, "Mustache": 20143, "TypeScript": 7650, "Handlebars": 4563, "Java": 3523, "Python": 1902, "CSS": 1545, "JavaScript": 89} | package io.github.llmagentbuilder.core
import org.springframework.ai.chat.prompt.ChatOptions
/**
* Configure [ChatOptions]
*/
interface ChatOptionsConfigurer {
data class ChatOptionsConfig(
val stopSequence: List<String>? = null,
)
/**
* Checks if the [ChatOptions] can be configured
* @param chatOptions Default [ChatOptions]
*/
fun supports(chatOptions: ChatOptions?): Boolean
/**
* Should return a new [ChatOptions]
*
* @param chatOptions Default [ChatOptions]
* @param config configuration
* @return A new [ChatOptions]
*/
fun configure(
chatOptions: ChatOptions?,
config: ChatOptionsConfig
): ChatOptions
} | 0 | Kotlin | 0 | 0 | dfab459c5d657051693786c08be4ffcf791f7637 | 715 | llm-agent-builder | Apache License 2.0 |
library/core/src/main/kotlin/inflow/InflowsCache.kt | alexvasilkov | 319,002,522 | false | null | package inflow
import inflow.internal.InflowsCacheImpl
/**
* Cache provider used to keep entries in memory to avoid frequent initializations.
*
* Implementations are required to be thread-safe because [get] and [clear] methods can be
* potentially called from different threads.
*/
public interface InflowsCache<K, V> {
/**
* Gets a value for the [key] or creates a new one using [provider] if no cached value is found.
* It will also trigger a cache clean up to remove old or expired items.
*/
public fun get(key: K, provider: (K) -> V): V
/**
* Sets optional removal listener to perform final clean up.
*/
public fun doOnRemove(action: (V) -> Unit)
/**
* Removes all cached entries.
*/
public fun clear()
public companion object {
/**
* Creates an instance of [InflowsCache] which keeps up to [maxSize] entries (defaults to
* `10`) and optionally removes all items that were accessed more than [expireAfterAccess]
* milliseconds ago (defaults to `0` meaning that no time-based expiration will be used).
*/
public fun <P, T> create(
maxSize: Int = 10,
expireAfterAccess: Long = 0L
): InflowsCache<P, Inflow<T>> = InflowsCacheImpl(maxSize, expireAfterAccess)
}
}
| 0 | Kotlin | 0 | 1 | 6c0b1ad39d18a234b06d5cea058c56f60ef93e35 | 1,326 | Inflow | Apache License 2.0 |
dm-transport-main-mp/src/commonMain/kotlin/ModelForRequest/Serializer.kt | otuskotlin | 382,547,521 | false | null | package ModelForRequest
import ModelForRequest.cruds.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.polymorphic
val jsonRequest = Json {
prettyPrint = true
serializersModule = SerializersModule {
polymorphic(BaseMessage::class) {
subclass(CreateWorkoutRequest::class, CreateWorkoutRequest.serializer())
subclass(ReadWorkoutRequest::class, ReadWorkoutRequest.serializer())
subclass(UpdateWorkoutRequest::class, UpdateWorkoutRequest.serializer())
subclass(DeleteWorkoutRequest::class, DeleteWorkoutRequest.serializer())
subclass(SearchWorkoutRequest::class, SearchWorkoutRequest.serializer())
subclass(CreateWorkoutResponse::class, CreateWorkoutResponse.serializer())
subclass(ReadWorkoutResponse::class, ReadWorkoutResponse.serializer())
subclass(UpdateWorkoutResponse::class, UpdateWorkoutResponse.serializer())
subclass(DeleteWorkoutResponse::class, DeleteWorkoutResponse.serializer())
subclass(SearchWorkoutResponse::class, SearchWorkoutResponse.serializer())
}
}
}
| 1 | Kotlin | 1 | 0 | ab962d306cab6512c5cffe61b87e810ddc28f193 | 1,094 | ok-202105-workout-dm | MIT License |
app/android/src/androidTest/kotlin/cinescout/android/ScreenshotGenerator.kt | fardavide | 280,630,732 | false | {"Kotlin": 2374797, "Shell": 11599} | @file:Suppress("DEPRECATION")
package cinescout.android
import android.graphics.Bitmap
import androidx.compose.ui.test.onRoot
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.runner.screenshot.Screenshot
import cinescout.android.testutil.ComposeAppTest
import cinescout.android.testutil.homeRobot
import cinescout.android.testutil.runComposeAppTest
import cinescout.screenplay.domain.sample.ScreenplaySample
import cinescout.suggestions.domain.sample.SuggestedScreenplaySample
import cinescout.test.compose.util.await
import cinescout.test.mock.junit4.MockAppRule
import org.junit.Ignore
import org.junit.Rule
import java.io.FileOutputStream
import kotlin.test.Test
@Ignore("Manual run only")
class ScreenshotGenerator {
private val device = Device.Phone
@get:Rule
val appRule = MockAppRule {
newInstall()
}
@Test
fun forYou() {
appRule {
newInstall()
forYou {
movie(SuggestedScreenplaySample.Inception)
}
}
runComposeAppTest {
homeRobot
.openForYou()
.selectMoviesType()
.awaitScreenplay(ScreenplaySample.Inception.title)
.awaitIdle()
.await(milliseconds = 2_000)
capture("for_you_$device.png")
}
}
@Test
fun details() {
appRule {
newInstall()
forYou {
movie(SuggestedScreenplaySample.Inception)
}
}
runComposeAppTest {
homeRobot
.openForYou()
.selectMoviesType()
.awaitScreenplay(ScreenplaySample.Inception.title)
.openDetails()
.awaitIdle()
.await(milliseconds = 2_000)
capture("details_$device.png")
}
}
@Test
fun lists() {
appRule {
newInstall()
watchlist {
add(ScreenplaySample.Inception)
add(ScreenplaySample.BreakingBad)
add(ScreenplaySample.Grimm)
}
}
runComposeAppTest {
homeRobot
.openMyLists()
.awaitScreenplay(ScreenplaySample.Inception.title)
.awaitIdle()
.await(milliseconds = 2_000)
capture("lists_$device.png")
}
}
@Test
fun search() {
appRule {
newInstall()
cached {
add(ScreenplaySample.BreakingBad)
add(ScreenplaySample.Dexter)
add(ScreenplaySample.Grimm)
add(ScreenplaySample.Inception)
add(ScreenplaySample.TheWolfOfWallStreet)
add(ScreenplaySample.War)
}
}
runComposeAppTest {
homeRobot
.openSearch()
.awaitScreenplay(ScreenplaySample.BreakingBad.title)
.awaitIdle()
.await(milliseconds = 2_000)
capture("search_$device.png")
}
}
}
@Suppress("unused")
private enum class Device(val string: String) {
Foldable("fold"),
Phone("phone"),
Tablet("tablet");
override fun toString() = string
}
private fun ComposeAppTest.capture(name: String) {
waitForIdle()
val compressFormat = Bitmap.CompressFormat.PNG
val bitmap = Screenshot
.capture()
.setName(name)
.setFormat(compressFormat)
.bitmap
val path = InstrumentationRegistry.getInstrumentation().targetContext.filesDir.canonicalPath
FileOutputStream("$path/$name").use { out ->
bitmap.compress(compressFormat, 100, out)
}
onRoot()
// adb shell 'ls /data/data/studio.forface.cinescout2/files/*png' | tr -d '\r' | xargs -n1 adb pull
}
| 11 | Kotlin | 2 | 6 | 7a875cd67a3df0ab98af520485122652bd5de560 | 3,858 | CineScout | Apache License 2.0 |
EasyKardexAndroid/data/src/test/java/com/jmarkstar/easykardex/data/api/CategoryServiceE2ETest.kt | jmarkstar | 192,662,781 | false | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Created by jmarkstar on 8/5/19 1:19 AM
*
*/
package com.jmarkstar.easykardex.data.api
import android.os.Build
import com.jmarkstar.easykardex.data.entities.CategoryEntity
import org.junit.Assert
import org.junit.runner.RunWith
import org.koin.test.inject
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import com.jmarkstar.easykardex.data.category
import com.jmarkstar.easykardex.data.utils.LibraryConstants
import kotlinx.coroutines.runBlocking
import org.junit.Test
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [Build.VERSION_CODES.O_MR1])
class CategoryServiceE2ETest: BaseAuthenticatedServiceE2ETest() {
private val categoryService: CategoryService by inject()
@Test
fun `create and delete category successly`() = runBlocking {
//Create
val newItem = create()
//Delete
delete(newItem.id!!)
}
@Test
fun `create category failure Empty name`() = runBlocking {
val brandWithoutName = CategoryEntity(name = LibraryConstants.EMPTY)
val createResult = categoryService.create(brandWithoutName)
Assert.assertEquals(true, createResult.code() == 400)
}
@Test
fun `update category successly`() = runBlocking {
val newItem = create()
val id = newItem.id!!
val newName = "Technology"
newItem.name = newName
val updateResult = categoryService.update(id, newItem)
Assert.assertEquals(true, updateResult.code() == 200)
Assert.assertNotNull(updateResult.body())
val updatedBrand = updateResult.body()!!
Assert.assertTrue(updatedBrand.name == newName)
delete(id)
}
@Test
fun `update category failure Empty name`() = runBlocking {
val newItem = create()
val id = newItem.id!!
newItem.name = LibraryConstants.EMPTY
val createResult = categoryService.update(id, newItem)
Assert.assertEquals(true, createResult.code() == 400)
delete(id)
}
@Test
fun `update category failure Brand not found`() = runBlocking {
val createResult = categoryService.update(-1, category)
Assert.assertEquals(true, createResult.code() == 404)
}
@Test
fun `delete category failure Brand not found`() = runBlocking {
val createResult = categoryService.delete(-1)
Assert.assertEquals(true, createResult.code() == 404)
}
@Test
fun `get all categories success`() = runBlocking {
val getAllResult = categoryService.getAll()
Assert.assertEquals(true, getAllResult.code() == 200)
Assert.assertNotNull(getAllResult.body())
Assert.assertEquals(true, getAllResult.body()!!.isNotEmpty())
}
@Test
fun `get Category by Id Success`() = runBlocking {
val newCategory = create()
val newCategoryId = newCategory.id!!
val getByIdResult = categoryService.findById(newCategoryId)
Assert.assertEquals(true, getByIdResult.code() == 200)
Assert.assertNotNull(getByIdResult.body())
delete(newCategoryId)
}
@Test
fun `get Category by Id failure Not found`() = runBlocking {
val createResult = categoryService.findById(-1)
Assert.assertEquals(true, createResult.code() == 404)
}
private suspend fun create(): CategoryEntity {
val createResult = categoryService.create(category)
Assert.assertEquals(true, createResult.code() == 201)
Assert.assertNotNull(createResult.body())
Assert.assertNotNull(createResult.body()?.id)
//Update
val newItem = createResult.body()!!
Assert.assertTrue(newItem.name == category.name)
return newItem
}
private suspend fun delete(id: Long) {
val deleteResult = categoryService.delete(id)
Assert.assertEquals(true, deleteResult.code() == 204)
}
} | 0 | Kotlin | 2 | 1 | 073f44ec3493a117052bcc88efd5e0ddbff81bb8 | 5,068 | EasyKardex | MIT License |
finance/src/main/java/com/scitrader/finance/pane/DefaultPane.kt | ABTSoftware | 468,421,926 | false | {"Kotlin": 296559, "Java": 3061} | package com.scitrader.finance.pane
import android.view.View
import androidx.appcompat.widget.AppCompatImageButton
import com.scichart.charting.modifiers.ModifierGroup
import com.scichart.charting.visuals.SciChartSurface
import com.scichart.charting.visuals.axes.IAxis
import com.scichart.core.utility.touch.IMotionEventManager
import com.scitrader.finance.ISciFinanceChart
import com.scitrader.finance.R
import com.scitrader.finance.core.event.FinanceChartAnimateRangeEvent
import com.scitrader.finance.core.event.IFinanceChartEvent
import com.scitrader.finance.core.event.IFinanceChartEventListener
import com.scitrader.finance.core.ui.ResizeableStackLayout
import com.scitrader.finance.pane.modifiers.FinancePinchZoomModifier
import com.scitrader.finance.pane.modifiers.FinanceZoomPanModifier
import com.scitrader.finance.pane.modifiers.crosshair.CrosshairModifier
import com.scitrader.finance.pane.modifiers.legend.StudyLegend
import com.scitrader.finance.state.PropertyState
import com.scitrader.finance.study.IStudy
import com.scitrader.finance.study.StudyId
import java.util.concurrent.atomic.AtomicInteger
open class DefaultPane(
override val chart: SciChartSurface,
override val xAxis: IAxis,
override val paneId: PaneId,
private val studyLegend: StudyLegend,
private val expandButton: View,
private val sciChartLogo: View,
private val modifiers: DefaultChartModifiers,
override val layoutParams: ResizeableStackLayout.LayoutParams
) : IPane, IFinanceChartEventListener {
private val studiesCounter = AtomicInteger(0)
override val rootView: View
get() = chart
override var isCursorEnabled: Boolean
get() = modifiers.isCursorEnabled
set(value) {
modifiers.isCursorEnabled = value
studyLegend.showSeriesTooltips = value
}
override var chartTheme: Int
get() = chart.theme
set(value) { chart.theme = value }
override var isXAxisVisible: Boolean
get() = xAxis.visibility == View.VISIBLE
set(value) {
xAxis.visibility = if(value) View.VISIBLE else View.GONE
updateLogoVisibility(value)
}
override var isExpandButtonEnabled: Boolean
get() = expandButton.isEnabled
set(value) {
expandButton.isEnabled = value
expandButton.alpha = if (value) 1F else 0.3F
}
private fun updateLogoVisibility(isXAxisVisible: Boolean) {
if (isXAxisVisible) {
placeLogo()
} else {
removeLogo()
}
}
private fun placeLogo() {
with(chart.modifierSurface) {
safeAdd(sciChartLogo)
}
}
private fun removeLogo() {
with(chart.modifierSurface) {
safeRemove(sciChartLogo)
}
}
override fun placeInto(financeChart: ISciFinanceChart) {
financeChart.addListener(this)
financeChart.addPane(this)
// set finance chart as source of touch events for modifier group
modifiers.modifierGroup.let { modifierGroup ->
chart.services.getService(IMotionEventManager::class.java)?.unsubscribe(modifierGroup)
financeChart.services.getService(IMotionEventManager::class.java)?.subscribe(financeChart, modifierGroup)
}
expandButton.setOnClickListener {
val isExpanded = financeChart.toggleFullscreenOnPane(paneId)
(expandButton as? AppCompatImageButton)?.let {
it.setImageResource(if (isExpanded) R.drawable.collapse_chart else R.drawable.expand_chart)
}
}
}
override fun removeFrom(financeChart: ISciFinanceChart) {
expandButton.setOnClickListener(null)
removeLogo()
// remove finance chart subscription for modifier group
modifiers.modifierGroup.let { modifierGroup ->
financeChart.services.getService(IMotionEventManager::class.java)?.unsubscribe(modifierGroup)
}
financeChart.removeListener(this)
financeChart.removePane(this)
}
override fun addStudy(study: IStudy) {
studiesCounter.incrementAndGet()
study.placeInto(this)
val studyTooltip = study.getStudyTooltip(chart.context)
studyLegend.addTooltip(studyTooltip)
}
override fun removeStudy(study: IStudy) {
study.removeFrom(this)
studiesCounter.decrementAndGet()
studyLegend.removeTooltip(study.id)
}
override val hasStudies: Boolean
get() = studiesCounter.get() > 0
override fun onStudyChanged(studyId: StudyId) {
studyLegend.onStudyChanged(studyId)
}
override fun onExpandAnimationStart() {}
override fun onExpandAnimationFinish() {
modifiers.crosshairModifier.normalizePointToDraw()
}
override fun savePropertyStateTo(chartState: PropertyState, paneState: PropertyState) {
paneState.writeString(paneLayoutParamsKey, ResizeableStackLayout.LayoutParams.convertToJsonString(layoutParams))
modifiers.crosshairModifier.savePropertyStateTo(chartState, paneState)
}
override fun restorePropertyStateFrom(chartState: PropertyState, paneState: PropertyState) {
paneState.readString(paneLayoutParamsKey)?.let {
ResizeableStackLayout.LayoutParams.assignLayoutParamsFromJsonString(layoutParams, it)
}
modifiers.crosshairModifier.restorePropertyStateFrom(chartState, paneState)
}
override fun onEvent(event: IFinanceChartEvent) {
if (event is FinanceChartAnimateRangeEvent) {
chart.xAxes.firstOrNull()?.let {
it.animateVisibleRangeTo(event.range, 200)
}
}
}
data class DefaultChartModifiers(val modifierGroup: ModifierGroup, val crosshairModifier: CrosshairModifier, val pinchZoomModifier: FinancePinchZoomModifier, val zoomPanModifier: FinanceZoomPanModifier) {
var isCursorEnabled: Boolean
get() = crosshairModifier.isEnabled
set(value) {
crosshairModifier.isEnabled = value
zoomPanModifier.isEnabled = !value
}
}
companion object {
internal const val paneLayoutParamsKey = "paneLayoutParamsKey"
}
}
| 3 | Kotlin | 0 | 2 | 00245ef7ee93ee79b1b5a1e8a6a77bce0f02777b | 6,255 | Finance.Android | Apache License 2.0 |
app/src/main/java/com/alba/kotlintest/DataObjectAndPrivateObjectOfKotlin.kt | benAlba | 226,633,377 | false | null | package com.alba.kotlintest
//数据类 关键字为data
data class Earth(val name: String, val age: Int)
//密封类用来表示受限的类继承结构:当一个值为有限几种的类型,而不能有任何其他类型时
//密封类的一个子类可以有包含状态的多个实例
sealed class Expr
data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr): Expr()
object NotANumber : Expr()
fun eval(expr: Expr): Double = when(expr) {
is Const -> expr.number
is Sum -> eval(expr.e1) + eval(expr.e2)
NotANumber -> Double.NaN
}
fun main(args: Array<String>){
val jack = Earth(name = "Jack", age = 20)
/**通过copy()函数复制对象并修改部分属性*/
val olderJack = jack.copy(age = 60)
println(jack)
println(olderJack)
//什么是组件函数? 什么是结构声明?
//组件函数允许数据类在解构声明中使用
val jane = Earth("Jane",35)
val (name, age) = jane
println("$name, $age years of age") //Jane, 35 years of age
}
| 0 | Kotlin | 0 | 0 | 771cba04970293e5a86d36cbabc357ae0dd26b8a | 819 | KotlinTest | Apache License 2.0 |
app/src/main/java/com/crossbowffs/usticker/StickerProvider.kt | apsun | 118,216,679 | false | null | package com.crossbowffs.usticker
import android.content.ContentProvider
import android.content.ContentValues
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.provider.DocumentsContract
import java.io.FileNotFoundException
/**
* Provides sticker files to the Firebase indexing service.
* Only supports reading files via openFile().
*/
class StickerProvider : ContentProvider() {
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {
val path = uri.lastPathSegment ?: throw FileNotFoundException("Invalid URI: $uri")
Klog.i("Requesting sticker: $path")
val stickerDir = Prefs.getStickerDir(context!!) ?: throw FileNotFoundException("Sticker directory not set")
val fileUri = DocumentsContract.buildDocumentUriUsingTree(stickerDir, path)
try {
return context!!.contentResolver.openFileDescriptor(fileUri, mode)
} catch (e: Exception) {
Klog.e("openFileDescriptor() failed", e)
throw e
}
}
override fun onCreate() = true
override fun query(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?) = null
override fun getType(uri: Uri) = null
override fun insert(uri: Uri, values: ContentValues?) = null
override fun delete(
uri: Uri,
selection: String?,
selectionArgs: Array<String>?) = 0
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<String>?) = 0
}
| 6 | Kotlin | 5 | 69 | 732ec3c75bb78b566925c92e119b34920165d987 | 1,621 | uSticker | MIT License |
neetcode/src/main/java/org/arrays/Arrays&Hashing.kt | gouthamhusky | 682,822,938 | false | {"Kotlin": 24242, "Java": 24233} | package org.arrays
import kotlin.math.max
fun containsDuplicate(nums: IntArray): Boolean = nums.size > nums.toSet().size
fun isAnagram(s: String, t: String): Boolean {
if (s.length != t.length)
return false
val list = MutableList(26){0}
for (i in s.indices){
val sPosition = s[i].toInt() - 97
val tPosition = t[i].toInt() - 97
list[sPosition]++
list[tPosition]--
}
list.forEach {
if (it != 0)
return false
}
return true
}
fun twoSum(nums: IntArray, target: Int): IntArray {
val map = mutableMapOf<Int, Int>()
for (i in nums.indices){
if (map.containsKey(target - nums[i]))
return intArrayOf(i, map[target - nums[i]]!!)
map[nums[i]] = i
}
return intArrayOf()
}
fun topKFrequent(nums: IntArray, k: Int): IntArray {
val map = mutableMapOf<Int, Int>()
val ans = mutableListOf<Int>()
val frequency = MutableList<MutableList<Int>>(nums.size + 1){
mutableListOf()
}
for (num in nums){
map.put(num, map.getOrDefault(num, 0) + 1)
}
for ((key, v) in map){
frequency[v].add(key)
}
for (i in frequency.size - 1 downTo 0){
for (j in frequency[i]){
ans.add(j)
if (ans.size == k)
return ans.toIntArray()
}
}
return intArrayOf()
}
fun groupAnagrams(strs: Array<String>): List<List<String>> {
val map = mutableMapOf<String, List<String>>()
val ans = mutableListOf<List<String>>()
for (str in strs){
val charArray = IntArray(26){0}
for (c in str){
charArray[c.toInt() - 97]++
}
val key = charArray.joinToString("")
if (map.containsKey(key)){
map[key] = map[key]!!.plus(str)
}
else{
map[key] = listOf(str)
}
}
for (v in map.values)
ans.add(v)
return ans
}
fun longestConsecutive(nums: IntArray): Int {
val set = mutableSetOf<Int>()
var max = Int.MIN_VALUE
var count = 0
for (num in nums){
set.add(num)
}
for (num in set){
if (! set.contains(num - 1)){
var length = 0
var seq = num
while (set.contains(seq +1)){
length++
seq++
}
max = max(max, length)
}
}
return max
}
fun isValidSudoku(board: Array<CharArray>): Boolean {
val rowMap = hashMapOf<Int, MutableSet<Char>>()
val colMap = hashMapOf<String, Set<Int>>()
val gridMap = hashMapOf<String, Set<Int>>()
// checking the rows
for (ri in board.indices){
val currRow = board[ri]
val rowSet = hashSetOf<Char>()
for (c in currRow.indices){
if (currRow[c] == '.')
continue
if (rowSet.contains(currRow[c]))
return false
rowSet.add(currRow[c])
}
}
// checking the columns
for (r in board.indices){
val colSet = hashSetOf<Char>()
for (c in board[r].indices){
if (board[c][r] == '.')
continue
if (colSet.contains(board[c][r]))
return false
colSet.add(board[c][r])
}
}
for (r in 0..<9 step 3){
for (c in 0 ..<9 step 3){
if (!checkGrid(r, c, board))
return false
}
}
return true
}
fun checkGrid(row: Int, col: Int, board: Array<CharArray>): Boolean{
val rowBound = row + 3
val colBound = col + 3
for (i in row..<rowBound){
val gridSet = hashSetOf<Char>()
for (j in col ..<colBound){
if (board[i][j] == '.')
continue
if (gridSet.contains(board[i][j]))
return false
}
}
return true
}
fun main() {
groupAnagrams(arrayOf("bdddddddddd","bbbbbbbbbbc"))
} | 0 | Kotlin | 0 | 0 | a0e158c8f9df8b2e1f84660d5b0721af97593920 | 3,910 | leetcode-journey | MIT License |
samples/demoapp/src/main/java/com/joaquimverges/demoapp/DetailFragment.kt | joaquim-verges | 126,538,789 | false | null | package com.joaquimverges.demoapp
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.joaquimverges.demoapp.logic.MyDetailLogic
import com.joaquimverges.demoapp.ui.MyDetailUi
import com.joaquimverges.helium.core.assemble
import com.joaquimverges.helium.core.plus
import com.joaquimverges.helium.core.retained.getRetainedLogicBlock
class DetailFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val logic = getRetainedLogicBlock<MyDetailLogic>()
val ui = MyDetailUi(inflater, container)
assemble(logic + ui)
return ui.view
}
} | 3 | Kotlin | 18 | 345 | f2e2166fcd802696982da00ea785cbb1c473cdeb | 766 | Helium | Apache License 2.0 |
src/main/kotlin/fr/zakaoai/coldlibrarybackend/infrastructure/model/myanimelist/MALAnimeListNode.kt | zakaoai | 344,490,461 | false | {"Kotlin": 133016, "Dockerfile": 683} | package fr.zakaoai.coldlibrarybackend.infrastructure.model.myanimelist
data class MALAnimeListNode(
val id: Int,
val title: String,
val main_picture: MalPicture,
val start_date: String?,
val end_date: String?,
val mean: Float,
val rank: Int,
val popularity: Int,
val genres: List<MALGenre>,
val media_type: String,
val status: String,
val num_episodes: Int,
val start_season: MALSeason?,
val broadcast: MALBroadcast?,
val rating: String
)
| 12 | Kotlin | 0 | 0 | c8b23af801528dd0ac5cc07b04222d31ba9b5509 | 502 | cold-library-backend | MIT License |
app/src/main/java/com/fhernandezri/protegest/adapters/AchievementAdapter.kt | RaksoSec | 813,606,279 | false | {"Kotlin": 122740} | package com.fhernandezri.protegest.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.fhernandezri.protegest.R
import com.fhernandezri.protegest.models.Achievement
class AchievementAdapter(private val achievements: List<Achievement>) : RecyclerView.Adapter<AchievementAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val name: TextView = view.findViewById(R.id.achievementName)
val description: TextView = view.findViewById(R.id.achievementDescription)
val xp: TextView = view.findViewById(R.id.achievementXp)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.achievement_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val achievement = achievements[position]
holder.name.text = achievement.name
holder.description.text = achievement.description
holder.xp.text = "${achievement.xp} XP"
}
override fun getItemCount() = achievements.size
} | 0 | Kotlin | 0 | 0 | 5bbf58a075ab6556f46cde9fca69f948717e28bd | 1,283 | ProteGest | MIT License |
scanners/scanner-database/src/main/kotlin/co/nilin/opex/chainscanner/database/dto/Dto.kt | opexdev | 410,208,131 | false | null | package co.nilin.opex.chainscanner.database.dto
import co.nilin.opex.chainscanner.core.model.Token
import co.nilin.opex.chainscanner.database.model.TokenModel
fun TokenModel.toPlainObject() = Token(chain, symbol, name, address, id)
fun Token.toModel() = TokenModel(chain, symbol, name, address, id)
| 0 | Kotlin | 3 | 2 | 48f15d33777b5502d8003b34ce814c31cb24c54e | 302 | chain-scanner | MIT License |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/GrateDroplet.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.GrateDroplet: ImageVector
get() {
if (_grateDroplet != null) {
return _grateDroplet!!
}
_grateDroplet = Builder(name = "GrateDroplet", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(24.0f, 19.0f)
curveToRelative(0.0f, 1.336f, -0.521f, 2.591f, -1.465f, 3.535f)
reflectiveCurveToRelative(-2.2f, 1.465f, -3.535f, 1.465f)
reflectiveCurveToRelative(-2.592f, -0.521f, -3.536f, -1.465f)
reflectiveCurveToRelative(-1.464f, -2.199f, -1.464f, -3.535f)
reflectiveCurveToRelative(0.521f, -2.592f, 1.465f, -3.535f)
lineToRelative(3.535f, -3.458f)
lineToRelative(3.527f, 3.45f)
curveToRelative(0.952f, 0.951f, 1.473f, 2.207f, 1.473f, 3.543f)
close()
moveTo(22.0f, 19.0f)
curveToRelative(0.0f, -0.802f, -0.313f, -1.555f, -0.879f, -2.121f)
lineToRelative(-2.121f, -2.075f)
lineToRelative(-2.129f, 2.083f)
curveToRelative(-0.559f, 0.559f, -0.871f, 1.312f, -0.871f, 2.113f)
reflectiveCurveToRelative(0.312f, 1.555f, 0.879f, 2.121f)
curveToRelative(1.132f, 1.134f, 3.108f, 1.134f, 4.242f, 0.0f)
curveToRelative(0.566f, -0.566f, 0.879f, -1.319f, 0.879f, -2.121f)
close()
moveTo(12.0f, 12.0f)
verticalLineToRelative(10.0f)
lineTo(0.0f, 22.0f)
lineTo(0.0f, 3.0f)
curveTo(0.0f, 1.346f, 1.346f, 0.0f, 3.0f, 0.0f)
horizontalLineToRelative(16.0f)
curveToRelative(1.654f, 0.0f, 3.0f, 1.346f, 3.0f, 3.0f)
verticalLineToRelative(9.144f)
lineToRelative(-2.0f, -1.956f)
lineTo(20.0f, 3.0f)
curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(9.165f)
lineToRelative(-0.853f, 0.835f)
horizontalLineToRelative(-4.147f)
close()
moveTo(12.0f, 2.0f)
verticalLineToRelative(8.0f)
horizontalLineToRelative(3.0f)
lineTo(15.0f, 2.0f)
horizontalLineToRelative(-3.0f)
close()
moveTo(10.0f, 2.0f)
horizontalLineToRelative(-3.0f)
verticalLineToRelative(8.0f)
horizontalLineToRelative(3.0f)
lineTo(10.0f, 2.0f)
close()
moveTo(2.0f, 3.0f)
verticalLineToRelative(7.0f)
horizontalLineToRelative(3.0f)
lineTo(5.0f, 2.0f)
horizontalLineToRelative(-2.0f)
curveToRelative(-0.552f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f)
close()
moveTo(2.0f, 20.0f)
horizontalLineToRelative(3.0f)
verticalLineToRelative(-8.0f)
horizontalLineToRelative(-3.0f)
verticalLineToRelative(8.0f)
close()
moveTo(10.0f, 12.0f)
horizontalLineToRelative(-3.0f)
verticalLineToRelative(8.0f)
horizontalLineToRelative(3.0f)
verticalLineToRelative(-8.0f)
close()
}
}
.build()
return _grateDroplet!!
}
private var _grateDroplet: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,462 | icons | MIT License |
src/main/kotlin/org/jglrxavpok/kameboy/ui/options/GraphicsOptions.kt | jglrxavpok | 123,712,183 | false | null | package org.jglrxavpok.kameboy.ui.options
import org.jglrxavpok.kameboy.processing.video.ColorPalette
import org.jglrxavpok.kameboy.processing.video.PaletteMemory
import org.jglrxavpok.kameboy.processing.video.Palettes
import org.jglrxavpok.kameboy.ui.Audio
import org.jglrxavpok.kameboy.ui.Config
import org.jglrxavpok.kameboy.ui.Rendering
import java.awt.FlowLayout
import javax.swing.BoxLayout
import javax.swing.JComboBox
import javax.swing.JLabel
import javax.swing.JPanel
object GraphicsOptions : JPanel() {
val paletteSelection = JComboBox<ColorPalette>(Palettes)
val curveSelection = JComboBox<PaletteMemory.CGBColorCurves>(PaletteMemory.CGBColorCurves.values())
init {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
paletteSelection.selectedIndex = Config[Rendering.paletteIndex]
paletteSelection.addActionListener {
Config[Rendering.paletteIndex] = paletteSelection.selectedIndex
Config.save()
}
curveSelection.selectedItem = Config[Rendering.CGBColorCurve]
curveSelection.addActionListener {
Config[Rendering.CGBColorCurve] = curveSelection.selectedItem as PaletteMemory.CGBColorCurves
Config.save()
}
sub("Gameboy DMG Palette") {
layout = FlowLayout()
add(paletteSelection)
}
sub("Gameboy Color color curve") {
layout = FlowLayout()
add(curveSelection)
}
}
}
| 0 | Kotlin | 0 | 3 | a07f8a8b402176cb00809377238c19a07039a177 | 1,472 | KameBoy | MIT License |
src/test/kotlin/Examples/DefiningAMapSpek.kt | mplacona | 130,415,261 | false | null | package Examples
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.jupiter.api.Assertions
class DefiningAMapSpek: Spek({
context("Defining a map in Kotlin"){
describe("Defining a map without types or the use of put") {
it("should return a map that has the same structure as one manually defined") {
val expected = HashMap<String, String>()
expected["keyA"] = "valueA"
expected["keyB"] = "valueB"
expected["keyC"] = "valueC"
val actual = createImplicitMap()
Assertions.assertEquals(expected, actual)
}
}
}
}) | 0 | Kotlin | 1 | 13 | fd732d1d957009cfbf1291d2575e26c514938ca4 | 778 | RealKotlinTips | Apache License 2.0 |
core/testing/src/main/java/com/niyaj/testing/repository/TestMarketTypeRepository.kt | skniyajali | 644,752,474 | false | {"Kotlin": 5045629, "Shell": 16584, "Ruby": 1461, "Java": 232} | /*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.niyaj.testing.repository
import com.niyaj.common.result.Resource
import com.niyaj.common.utils.getStartDateLong
import com.niyaj.data.repository.MarketTypeRepository
import com.niyaj.model.MarketType
import com.niyaj.model.searchMarketType
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.update
import org.jetbrains.annotations.TestOnly
class TestMarketTypeRepository : MarketTypeRepository {
/**
* The backing market type list for testing
*/
private val items = MutableStateFlow(mutableListOf<MarketType>())
override suspend fun getAllMarketTypes(searchText: String): Flow<List<MarketType>> {
return items.mapLatest { it.searchMarketType(searchText) }
}
override suspend fun getMarketTypeById(id: Int): MarketType? {
return items.value.find { it.typeId == id }
}
override suspend fun createOrUpdateMarketType(marketType: MarketType): Resource<Boolean> {
val index = items.value.indexOfFirst { it.typeId == marketType.typeId }
if (index != -1) {
items.value[index] = marketType
} else {
items.value.add(marketType)
}
return Resource.Success(true)
}
override suspend fun deleteMarketTypes(items: List<Int>): Resource<Boolean> {
return Resource.Success(this.items.value.removeAll { it.typeId in items })
}
override suspend fun findMarketTypeByName(typeName: String, typeId: Int?): Boolean {
return items.value.any {
if (typeId != null) {
it.typeName == typeName && it.typeId != typeId
} else {
it.typeName == typeName
}
}
}
override suspend fun importDataFromFilesToDatabase(data: List<MarketType>): Resource<Boolean> {
data.forEach {
createOrUpdateMarketType(it)
}
return Resource.Success(true)
}
@TestOnly
fun createTestItem(): MarketType {
val item = MarketType(
typeId = 1,
typeName = "Test Type",
listTypes = listOf("Test List Type"),
createdAt = getStartDateLong,
)
items.value.add(item)
return item
}
@TestOnly
fun updateMarketTypeData(marketTypes: List<MarketType>) {
items.update { marketTypes.toMutableList() }
}
}
| 36 | Kotlin | 0 | 1 | 5cc18164cfb9e685aabb373d904f3c9d6e4aaba9 | 3,040 | PoposRoom | Apache License 2.0 |
katana-server/src/main/kotlin/jp/katana/server/io/DecompressException.kt | hiroki19990625 | 194,672,872 | false | null | package jp.katana.server.io
import java.io.IOException
class DecompressException(message: String) : IOException(message) | 0 | Kotlin | 1 | 2 | aab8ae69beed267ea0ef9eab2ebd23b994ac0f25 | 122 | katana | MIT License |
app/src/main/java/org/lineageos/glimpse/flow/QueryFlow.kt | LineageOS | 750,973,545 | false | {"Kotlin": 184842} | /*
* SPDX-FileCopyrightText: 2023 The LineageOS Project
* SPDX-License-Identifier: Apache-2.0
*/
package org.lineageos.recorder.flow
import android.database.Cursor
import kotlinx.coroutines.flow.Flow
abstract class QueryFlow<T> {
/** A flow of the data specified by the query */
abstract fun flowData(): Flow<List<T>>
/** A flow of the cursor specified by the query */
abstract fun flowCursor(): Flow<Cursor?>
}
| 2 | Kotlin | 7 | 9 | a6050c7f9713353d2b3fea769f085a87e271a429 | 435 | android_packages_apps_Glimpse | Apache License 2.0 |
infra/src/main/kotlin/fr/sacane/jmanager/server/adapters/ServerTransactionAdapter.kt | Sacane | 531,082,439 | false | null | package fr.sacane.jmanager.server.adapters
import fr.sacane.jmanager.domain.hexadoc.DatasourceAdapter
import fr.sacane.jmanager.domain.models.*
import fr.sacane.jmanager.domain.port.serverside.TransactionRegister
import fr.sacane.jmanager.server.entity.CategoryResource
import fr.sacane.jmanager.server.repositories.CategoryRepository
import fr.sacane.jmanager.server.repositories.UserRepository
import fr.sacane.jmanager.server.spring.SpringLayerService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.lang.Exception
import java.time.Month
@Service
@DatasourceAdapter
class ServerTransactionAdapter : TransactionRegister{
companion object{
private val logger = LoggerFactory.getLogger("infra.server.adapters.ServerAdapter")
}
@Autowired
private lateinit var service: SpringLayerService
override fun getSheets(user: UserId, accountLabel: String): List<Sheet> {
return service.getSheets(user, accountLabel)
}
override fun getSheetsByDateAndAccount(
userId: UserId,
month: Month,
year: Int,
labelAccount: String
): List<Sheet> {
return service.getSheetsByDateAndAccount(userId, month, year, labelAccount)
}
override fun getAccounts(user: UserId): List<Account> {
logger.debug("Trying to reach accounts of user ${user.get()}")
return service.getAccounts(user)
}
override fun saveAccount(userId: UserId, account: Account): Account? {
return service.saveAccount(userId, account)
}
override fun saveSheet(userId: UserId, accountLabel: String, sheet: Sheet): Sheet? {
return service.saveSheet(userId, accountLabel, sheet)
}
override fun saveCategory(userId: UserId, category: Category): Category? {
return service.saveCategory(userId, category)
}
override fun removeCategory(userId: UserId, labelCategory: String): Category? {
return service.removeCategory(userId, labelCategory)
}
}
| 0 | Kotlin | 0 | 0 | 8d181a000b7cde2b36dd318a5482de30061bcb82 | 2,070 | JManager-back | MIT License |
android/Rental/app/src/main/java/com/project/pradyotprakash/rental/data/services/LocationService.kt | pradyotprksh | 385,586,594 | false | null | package com.project.pradyotprakash.rental.data.services
import com.project.pradyotprakash.rental.domain.modal.DefaultEntity
import com.project.pradyotprakash.rental.domain.modal.LocationEntity
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface LocationService {
@GET("/renter/location")
suspend fun searchLocation(
@Query("search_text") searchedText: String,
@Query("zip_code") zipCode: String,
@Query("latitude") latitude: String,
@Query("longitude") longitude: String,
@Query("exactly_one") exactly_one: Boolean,
): Response<DefaultEntity<List<LocationEntity>>>
} | 0 | Kotlin | 7 | 9 | e10e007fab12c3d056920741c06ff599a64cca21 | 658 | development_learning | MIT License |
kotlin-electron/src/jsMain/generated/electron/main/MessagePortMain.kt | JetBrains | 93,250,841 | false | {"Kotlin": 12635434, "JavaScript": 423801} | // Generated by Karakum - do not modify it manually!
package electron.main
typealias MessagePortMain = electron.core.MessagePortMain
| 38 | Kotlin | 162 | 1,347 | 997ed3902482883db4a9657585426f6ca167d556 | 135 | kotlin-wrappers | Apache License 2.0 |
PluginsAndFeatures/azure-toolkit-for-intellij/rider/src/org/jetbrains/plugins/azure/identity/ad/actions/RegisterApplicationInAzureAdAction.kt | JetBrains | 137,064,201 | true | {"Java": 6824035, "Kotlin": 2388176, "C#": 183917, "Scala": 151332, "Gherkin": 108427, "JavaScript": 98350, "HTML": 23518, "CSS": 21770, "Groovy": 21447, "Shell": 21354, "XSLT": 7141, "Dockerfile": 3518, "Batchfile": 2155} | /**
* Copyright (c) 2020-2023 JetBrains s.r.o.
*
* All rights reserved.
*
* MIT License
*
* 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.
*/
@file:Suppress("UnstableApiUsage")
package org.jetbrains.plugins.azure.identity.ad.actions
import com.intellij.ide.BrowserUtil
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.PerformInBackgroundOption
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.platform.backend.workspace.WorkspaceModel
import com.intellij.platform.backend.workspace.virtualFile
import com.jetbrains.rider.projectView.workspace.ProjectModelEntity
import com.jetbrains.rider.projectView.workspace.containingProjectEntity
import com.jetbrains.rider.projectView.workspace.getProjectModelEntities
import com.jetbrains.rider.projectView.workspace.getVirtualFileAsParent
import com.jetbrains.rider.util.idea.PsiFile
import com.microsoft.azure.management.graphrbac.GraphErrorException
import com.microsoft.azure.management.graphrbac.implementation.ApplicationCreateParametersInner
import com.microsoft.azure.management.graphrbac.implementation.ApplicationInner
import com.microsoft.azure.management.graphrbac.implementation.ApplicationUpdateParametersInner
import com.microsoft.azure.management.graphrbac.implementation.GraphRbacManagementClientImpl
import com.microsoft.azuretools.authmanage.AuthMethodManager
import com.microsoft.azuretools.authmanage.RefreshableTokenCredentials
import com.microsoft.azuretools.authmanage.models.SubscriptionDetail
import com.microsoft.azuretools.sdkmanage.AzureManager
import com.microsoft.intellij.actions.AzureSignInAction
import com.microsoft.intellij.serviceexplorer.azure.database.actions.runWhenSignedIn
import icons.CommonIcons
import org.jetbrains.plugins.azure.AzureNotifications
import org.jetbrains.plugins.azure.RiderAzureBundle
import org.jetbrains.plugins.azure.identity.ad.appsettings.AppSettingsAzureAdSection
import org.jetbrains.plugins.azure.identity.ad.appsettings.AppSettingsAzureAdSectionManager
import org.jetbrains.plugins.azure.identity.ad.ui.RegisterApplicationInAzureAdDialog
import org.jetbrains.plugins.azure.isValidGuid
import java.net.URI
import java.util.*
import javax.swing.event.HyperlinkEvent
class RegisterApplicationInAzureAdAction
: AnAction(
RiderAzureBundle.message("action.identity.ad.register_app.name"),
RiderAzureBundle.message("action.identity.ad.register_app.description"),
CommonIcons.AzureActiveDirectory) {
companion object {
private const val appSettingsJsonFileName = "appsettings.json"
fun isAppSettingsJsonFileName(fileName: String?): Boolean {
if (fileName == null) return false
return fileName.equals(appSettingsJsonFileName, true)
|| (fileName.startsWith("appsettings.", true) && fileName.endsWith(".json", true))
}
private val logger = Logger.getInstance(RegisterApplicationInAzureAdAction::class.java)
}
override fun update(e: AnActionEvent) {
val project = e.project ?: return
val projectModelNode = tryGetProjectModelEntityFromFile(project, e.dataContext.PsiFile?.virtualFile)
e.presentation.isEnabledAndVisible = projectModelNode != null &&
tryGetAppSettingsJsonVirtualFile(projectModelNode) != null
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
runWhenSignedIn(project) {
val projectModelNode = tryGetProjectModelEntityFromFile(project, e.dataContext.PsiFile?.virtualFile)
?: return@runWhenSignedIn
val appSettingsJsonVirtualFile = tryGetAppSettingsJsonVirtualFile(projectModelNode) ?: return@runWhenSignedIn
if (appSettingsJsonVirtualFile.isDirectory || !appSettingsJsonVirtualFile.exists()) return@runWhenSignedIn
val application = ApplicationManager.getApplication()
val azureManager = AuthMethodManager.getInstance().azureManager ?: return@runWhenSignedIn
// Read local settings
val azureAdSettings = AppSettingsAzureAdSectionManager()
.readAzureAdSectionFrom(appSettingsJsonVirtualFile, project)
val matchingTenantIdFromAppSettings = if (azureAdSettings != null
&& !azureAdSettings.isDefaultProjectTemplateContent()
&& azureAdSettings.tenantId != null) azureAdSettings.tenantId
else null
// Retrieve matching subscription/tenant
object : Task.Backgroundable(project, RiderAzureBundle.message("progress.common.start.retrieving_subscription"), true, PerformInBackgroundOption.DEAF) {
override fun run(indicator: ProgressIndicator) {
logger.debug("Retrieving Azure subscription details...")
val selectedSubscriptions = azureManager.subscriptionManager.subscriptionDetails
.asSequence()
.filter { it.isSelected }
.toList()
logger.debug("Retrieved ${selectedSubscriptions.count()} Azure subscriptions")
// One subscription? Only one tenant? No popup needed
val bestMatchingSubscription = when {
matchingTenantIdFromAppSettings != null -> selectedSubscriptions.firstOrNull { it.tenantId == matchingTenantIdFromAppSettings }
selectedSubscriptions.count() == 1 -> selectedSubscriptions.first()
else -> null
}
if (bestMatchingSubscription != null) {
application.invokeLater {
if (project.isDisposed) return@invokeLater
fetchDataAndShowDialog(projectModelNode, project, azureManager, bestMatchingSubscription)
}
return
}
// Multiple subscriptions? Popup.
application.invokeLater {
if (project.isDisposed) return@invokeLater
val step = object : BaseListPopupStep<SubscriptionDetail>(RiderAzureBundle.message("popup.common.start.select_subscription"), selectedSubscriptions) {
override fun getTextFor(value: SubscriptionDetail?): String {
if (value != null) {
return "${value.subscriptionName} (${value.subscriptionId})"
}
return super.getTextFor(value)
}
override fun onChosen(selectedValue: SubscriptionDetail, finalChoice: Boolean): PopupStep<*>? {
doFinalStep {
fetchDataAndShowDialog(projectModelNode, project, azureManager, selectedValue)
}
return PopupStep.FINAL_CHOICE
}
}
logger.debug("Showing popup to select Azure subscription")
val popup = JBPopupFactory.getInstance().createListPopup(step)
popup.showCenteredInCurrentWindow(project)
}
}
}.queue()
}
}
private fun fetchDataAndShowDialog(entity: ProjectModelEntity,
project: Project,
azureManager: AzureManager,
selectedSubscription: SubscriptionDetail) {
val appSettingsJsonVirtualFile = tryGetAppSettingsJsonVirtualFile(entity) ?: return
if (appSettingsJsonVirtualFile.isDirectory || !appSettingsJsonVirtualFile.exists()) return
val application = ApplicationManager.getApplication()
// Create graph client
logger.debug("Using subscription ${selectedSubscription.subscriptionId}; tenant ${selectedSubscription.tenantId}")
val tokenCredentials = RefreshableTokenCredentials(azureManager, selectedSubscription.tenantId)
val graphClient = GraphRbacManagementClientImpl(
azureManager.environment.azureEnvironment.graphEndpoint(), tokenCredentials).withTenantID(selectedSubscription.tenantId)
// Read local settings
val azureAdSettings = AppSettingsAzureAdSectionManager()
.readAzureAdSectionFrom(appSettingsJsonVirtualFile, project)
// Build model
val domain = try {
defaultDomainForTenant(graphClient)
} catch (e: GraphErrorException) {
logger.error("Failed to get default domain for tenant", e)
reportError(project,
RiderAzureBundle.message("notification.identity.ad.register_app.failed.common.subtitle"),
RiderAzureBundle.message("notification.identity.ad.register_app.failed.get_default_domain.message", selectedSubscription.tenantId))
return
}
val model = if (azureAdSettings == null || azureAdSettings.isDefaultProjectTemplateContent()) {
buildDefaultRegistrationModel(entity, domain)
} else {
buildRegistrationModelFrom(azureAdSettings, domain, graphClient, entity)
}
// Show dialog
val dialog = RegisterApplicationInAzureAdDialog(project, model)
if (dialog.showAndGet()) {
object : Task.Backgroundable(project, RiderAzureBundle.message("progress.identity.ad.registering"), true, PerformInBackgroundOption.DEAF) {
override fun run(indicator: ProgressIndicator) {
// 1. Save changes to AD
val existingApplication = if (model.updatedClientId.isNotEmpty()) {
tryGetRegisteredApplication(model.updatedClientId, graphClient)
} else if (azureAdSettings != null && !azureAdSettings.isDefaultProjectTemplateContent() && azureAdSettings.clientId != null) {
tryGetRegisteredApplication(azureAdSettings.clientId, graphClient)
} else null
if (indicator.isCanceled) return
logger.debug("Updating Azure AD application registration...")
val updatedApplication = if (existingApplication != null && model.allowOverwrite && model.hasChanges) {
// Update
var parameters = ApplicationUpdateParametersInner()
if (model.updatedDisplayName != model.originalDisplayName)
parameters = parameters.withDisplayName(model.updatedDisplayName)
if (model.updatedCallbackUrl != model.originalCallbackUrl) {
val replyUrls = existingApplication.replyUrls()
replyUrls.remove(model.originalCallbackUrl)
replyUrls.add(model.updatedCallbackUrl)
parameters = parameters.withReplyUrls(replyUrls)
}
if (model.updatedIsMultiTenant != model.originalIsMultiTenant)
parameters = parameters.withAvailableToOtherTenants(model.updatedIsMultiTenant)
try {
graphClient.applications().patch(existingApplication.objectId(), parameters)
graphClient.applications().get(existingApplication.objectId())
} catch (e: GraphErrorException) {
logger.error("Failed to update application", e)
reportError(project,
RiderAzureBundle.message("notification.identity.ad.register_app.failed.common.subtitle"),
RiderAzureBundle.message("notification.identity.ad.register_app.failed.update.message", selectedSubscription.tenantId, e.body().message()))
return
}
} else if (existingApplication == null) {
// Create
try {
graphClient.applications().create(ApplicationCreateParametersInner()
.withDisplayName(model.updatedDisplayName)
.withIdentifierUris(listOf("https://" + domain + "/" + (model.updatedDisplayName + UUID.randomUUID().toString().substring(0, 6)).filter { it.isLetterOrDigit() }))
.withReplyUrls(listOf(model.updatedCallbackUrl))
.withAvailableToOtherTenants(model.updatedIsMultiTenant))
} catch (e: GraphErrorException) {
logger.error("Failed to create application", e)
if (e.body().code() == "403") {
reportError(project,
RiderAzureBundle.message("notification.identity.ad.register_app.failed.common.subtitle"),
RiderAzureBundle.message("notification.identity.ad.register_app.failed.create.permissions"),
"https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-how-applications-are-added#who-has-permission-to-add-applications-to-my-azure-ad-instance")
} else {
reportError(project,
RiderAzureBundle.message("notification.identity.ad.register_app.failed.common.subtitle"),
RiderAzureBundle.message("notification.identity.ad.register_app.failed.create.message", e.body().message()))
}
return
}
} else null
// 2. Save changes to appsettings.json
application.invokeLater {
logger.debug("Saving changes to appsettings.json...")
AppSettingsAzureAdSectionManager()
.writeAzureAdSectionTo(AppSettingsAzureAdSection(
instance = azureAdSettings?.instance,
domain = model.updatedDomain,
tenantId = selectedSubscription.tenantId,
clientId = updatedApplication?.appId() ?: existingApplication?.appId()
?: azureAdSettings?.clientId,
callbackPath = URI.create(model.updatedCallbackUrl).rawPath
), appSettingsJsonVirtualFile, project, model.hasChanges)
}
}
}.queue()
}
}
private fun tryGetProjectModelEntityFromFile(project: Project, file: VirtualFile?): ProjectModelEntity? {
if (file == null) return null
return WorkspaceModel.getInstance(project)
.getProjectModelEntities(file, project)
.mapNotNull { it.containingProjectEntity() }
.firstOrNull()
}
private fun tryGetAppSettingsJsonVirtualFile(entity: ProjectModelEntity): VirtualFile? {
val itemVirtualFile = entity.url?.virtualFile
if (isAppSettingsJsonFileName(itemVirtualFile?.name)) return itemVirtualFile
return entity.containingProjectEntity()?.getVirtualFileAsParent()?.findChild(appSettingsJsonFileName)
}
private fun defaultDomainForTenant(graphClient: GraphRbacManagementClientImpl) =
graphClient.domains().list()
.filter { it.isDefault }
.map { it.name() }
.firstOrNull() ?: ""
private fun tryGetRegisteredApplication(clientId: String?, graphClient: GraphRbacManagementClientImpl): ApplicationInner? {
if (clientId == null || !clientId.isValidGuid()) return null
try {
val matchingApplication = graphClient.applications()
.list("appId eq '$clientId'")
.firstOrNull()
if (matchingApplication != null) {
return graphClient.applications().get(matchingApplication.objectId())
}
} catch (e: Throwable) {
logger.error(e)
}
return null
}
private fun buildDefaultRegistrationModel(entity: ProjectModelEntity, domain: String) =
RegisterApplicationInAzureAdDialog.RegistrationModel(
originalDisplayName = entity.containingProjectEntity()!!.name,
originalClientId = "",
originalDomain = domain,
originalCallbackUrl = "https://localhost:5001/signin-oidc", // IMPROVEMENT: can we get the URL from the current project?
originalIsMultiTenant = false,
allowOverwrite = false
)
private fun buildRegistrationModelFrom(
azureAdSettings: AppSettingsAzureAdSection,
domain: String,
graphClient: GraphRbacManagementClientImpl,
entity: ProjectModelEntity
): RegisterApplicationInAzureAdDialog.RegistrationModel {
// 1. If an application exists, use its data.
val application = tryGetRegisteredApplication(azureAdSettings.clientId, graphClient)
if (application != null) {
val replyUrls = application.replyUrls()
.filter { azureAdSettings.callbackPath != null && it.endsWith(azureAdSettings.callbackPath) }
return RegisterApplicationInAzureAdDialog.RegistrationModel(
originalDisplayName = application.displayName(),
originalClientId = application.appId(),
originalDomain = azureAdSettings.domain ?: domain,
originalCallbackUrl = replyUrls.firstOrNull()
?: "https://localhost:5001/" + (azureAdSettings.callbackPath?.trimStart('/') ?: "signin-oidc"),
originalIsMultiTenant = application.availableToOtherTenants(),
allowOverwrite = false
)
}
// 2. If no application exists, use whatever we can recover from appsettings.json
return RegisterApplicationInAzureAdDialog.RegistrationModel(
originalDisplayName = entity.containingProjectEntity()!!.name,
originalClientId = azureAdSettings.clientId ?: "",
originalDomain = azureAdSettings.domain ?: domain,
originalCallbackUrl = "https://localhost:5001/" + (azureAdSettings.callbackPath?.trimStart('/') ?: "signin-oidc"),
originalIsMultiTenant = false,
allowOverwrite = false
)
}
private fun reportError(project: Project, subtitle: String, message: String, helpUrl: String? = null) {
AzureNotifications.notify(project,
title = RiderAzureBundle.message("common.azure"),
subtitle = subtitle,
content = message,
type = NotificationType.ERROR,
action = if (!helpUrl.isNullOrEmpty()) {
object : AnAction(RiderAzureBundle.message("notification.identity.ad.register_app.learn.more")) {
override fun actionPerformed(e: AnActionEvent) = BrowserUtil.browse(helpUrl)
}
} else {
null
})
}
} | 73 | Java | 10 | 41 | a8b64627376a5144a71725853ba4217b97044722 | 21,336 | azure-tools-for-intellij | MIT License |
server/src/main/kotlin/com/tikhon/app/events/MessengerEventType.kt | Tihon-Ustinov | 578,343,105 | false | null | package com.tikhon.app.events
enum class MessengerEventType {
ADD_PROJECT
} | 0 | Kotlin | 0 | 0 | afe128ac61ed592dcd591495b7aaa82936062ca2 | 80 | git-notifier | Apache License 2.0 |
Animation/src/commonMain/kotlin/io/nacular/doodle/animation/Animator.kt | tchigher | 312,263,221 | true | {"Kotlin": 1510103} | package io.nacular.doodle.animation
import io.nacular.doodle.animation.transition.FixedSpeedLinear
import io.nacular.doodle.animation.transition.FixedTimeLinear
import io.nacular.doodle.animation.transition.NoChange
import io.nacular.doodle.animation.transition.SpeedUpSlowDown
import io.nacular.doodle.animation.transition.Transition
import io.nacular.doodle.utils.Completable
import io.nacular.doodle.utils.Pool
import io.nacular.measured.units.InverseUnits
import io.nacular.measured.units.Measure
import io.nacular.measured.units.Time
import io.nacular.measured.units.Units
import io.nacular.measured.units.UnitsRatio
import io.nacular.measured.units.times
import kotlin.jvm.JvmName
/**
* Created by Nicholas Eddy on 3/29/18.
*/
class NoneUnit: Units("")
val noneUnits = NoneUnit()
@JvmName("fixedSpeedLinearNumber")
fun <T: Number> fixedSpeedLinear(speed: Measure<InverseUnits<Time>>): (T, T) -> Transition<NoneUnit> = { _,end -> FixedSpeedLinear(1 * noneUnits * speed, end * noneUnits) }
@JvmName("fixedSpeedLinearUnit")
fun <T: Units> fixedSpeedLinear(speed: Measure<UnitsRatio<T, Time>>): (Measure<T>, Measure<T>) -> Transition<T> = { _,end -> FixedSpeedLinear(speed, end) }
fun <T: Number> fixedTimeLinear(time: Measure<Time>): (T, T) -> Transition<NoneUnit> = { _,end -> FixedTimeLinear(time, end * noneUnits) }
fun <T: Units> fixedTimeLinearM(time: Measure<Time>): (Measure<T>, Measure<T>) -> Transition<T> = { _,end -> FixedTimeLinear(time, end) }
fun <T: Number> speedUpSlowDown(time: Measure<Time>, accelerationFraction: Float = 0.5f): (T, T) -> Transition<NoneUnit> = { _,end -> SpeedUpSlowDown(time, end * noneUnits, accelerationFraction) }
fun <T: Units> speedUpSlowDownM(time: Measure<Time>, accelerationFraction: Float = 0.5f): (Measure<T>, Measure<T>) -> Transition<T> = { _,end -> SpeedUpSlowDown(time, end, accelerationFraction) }
fun <T: Number> noChange (time: Measure<Time>): (T) -> Transition<NoneUnit> = { NoChange(time) }
fun <T: Units> noChangeM(time: Measure<Time>): (Measure<T>) -> Transition<T> = { NoChange(time) }
interface Animation: Completable
interface Animator {
interface Listener {
fun changed (animator: Animator, animations: Set<Animation>) {}
fun cancelled(animator: Animator, animations: Set<Animation>) {}
fun completed(animator: Animator, animations: Set<Animation>) {}
}
interface TransitionBuilder<T: Number> {
infix fun then(transition: Transition<NoneUnit>): TransitionBuilder<T>
operator fun invoke(block: (T) -> Unit): Animation
}
interface MeasureTransitionBuilder<T: Units> {
infix fun then(transition: Transition<T>): MeasureTransitionBuilder<T>
operator fun invoke(block: (Measure<T>) -> Unit): Animation
}
interface NumberRangeUsing<T: Number> {
infix fun using(transition: (start: T, end: T) -> Transition<NoneUnit>): TransitionBuilder<T>
}
interface NumberUsing<T: Number> {
infix fun using(transition: (start: T) -> Transition<NoneUnit>): TransitionBuilder<T>
}
interface MeasureRangeUsing<T: Units> {
infix fun using(transition: (start: Measure<T>, end: Measure<T>) -> Transition<T>): MeasureTransitionBuilder<T>
}
interface MeasureUsing<T: Units> {
infix fun using(transition: (start: Measure<T>) -> Transition<T>): MeasureTransitionBuilder<T>
}
operator fun <T: Number> invoke(range: Pair<T, T>) = object: NumberRangeUsing<T> {
override fun using(transition: (start: T, end: T) -> Transition<NoneUnit>) = range using transition
}
operator fun <T: Number> invoke(value: T) = object: NumberUsing<T> {
override fun using(transition: (start: T) -> Transition<NoneUnit>) = value using transition
}
operator fun <T: Units> invoke(range: Pair<Measure<T>, Measure<T>>) = object: MeasureRangeUsing<T> {
override fun using(transition: (start: Measure<T>, end: Measure<T>) -> Transition<T>) = range using transition
}
operator fun <T: Units> invoke(value: Measure<T>) = object: MeasureUsing<T> {
override fun using(transition: (start: Measure<T>) -> Transition<T>) = value using transition
}
infix fun <T: Number> Pair<T, T>.using(transition: (start: T, end: T) -> Transition<NoneUnit>): TransitionBuilder<T>
infix fun <T: Number> T.using(transition: (start: T) -> Transition<NoneUnit>): TransitionBuilder<T>
infix fun <T: Units> Pair<Measure<T>, Measure<T>>.using(transition: (start: Measure<T>, end: Measure<T>) -> Transition<T>): MeasureTransitionBuilder<T>
infix fun <T: Units> Measure<T>.using(transition: (start: Measure<T>) -> Transition<T>): MeasureTransitionBuilder<T>
operator fun invoke(block: Animator.() -> Unit): Completable
val listeners: Pool<Listener>
} | 0 | null | 0 | 0 | f878abf3163a49d515038f6699a4124f087e9885 | 4,789 | doodle | MIT License |
src/math/Sphere.kt | Capster | 707,893,823 | false | {"Kotlin": 178235, "HTML": 717} | package math
import com.curiouscreature.kotlin.math.Float3
data class Sphere(val center: Float3, val radius: Float)
| 0 | Kotlin | 0 | 1 | bad9ee8f1d0a9cbc676fac6768784dbb147776a9 | 118 | kotlin-webgl | MIT License |
buildSrc/src/main/kotlin/com/saveourtool/buildutils/DetektConfiguration.kt | saveourtool | 604,687,354 | false | {"Kotlin": 74976} | package com.saveourtool.buildutils
import io.gitlab.arturbosch.detekt.Detekt
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.kotlin.dsl.invoke
import org.gradle.kotlin.dsl.named
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.withType
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import org.jetbrains.kotlin.gradle.tasks.KotlinNativeCompile
import java.io.File
private const val PREFIX = "detekt"
/**
* Configures _Detekt_ for this project.
*/
fun Project.configureDetekt() {
tasks.withType<Detekt> {
parallel = true
autoCorrect = hasProperty("detektAutoCorrect")
config.setFrom(file(projectDir / "config" / "detekt" / "detekt.yml"))
include("**/*.kt")
reports {
val reportDir = buildDir / "reports" / "detekt"
sarif {
required.set(true)
outputLocation.set(file(reportDir / "$name.sarif"))
}
html {
required.set(true)
outputLocation.set(file(reportDir / "$name.html"))
}
sequenceOf(xml, txt, md).forEach { report ->
report.required.set(false)
}
}
}
detekt("detektCommonMain")
detekt("detektCommonTest")
detekt("detektJvmMain")
detekt("detektJvmTest")
detekt("detektNativeMain")
detekt("detektNativeTest")
tasks.register<DefaultTask>("detektAll") {
group = "verification"
dependsOn(
tasks.named<Detekt>("detektCommonMain"),
tasks.named<Detekt>("detektCommonTest"),
tasks.named<Detekt>("detektJvmMain"),
tasks.named<Detekt>("detektJvmTest"),
tasks.named<Detekt>("detektNativeMain"),
tasks.named<Detekt>("detektNativeTest"),
)
}
}
/**
* Configures a _Detekt_ task, creating it if necessary.
*
* @param configuration extra configuration, may be empty.
*/
private fun Project.detekt(
name: String,
configuration: Detekt.() -> Unit = {},
) {
val taskProvider = when (tasks.findByName(name)) {
null -> tasks.register<Detekt>(name)
else -> tasks.named<Detekt>(name)
}
taskProvider {
val sourceSetName = name.sourceSetName
source = fileTree(projectDir / "src" / sourceSetName)
val isTest = sourceSetName.endsWith("Test")
val dependencyNamePrefix = when {
isTest -> "compileTestKotlin"
else -> "compileKotlin"
}
val isNative = sourceSetName.startsWith("native")
when {
isNative -> dependsOn(
tasks.named<KotlinNativeCompile>(dependencyNamePrefix + "MingwX64"),
tasks.named<KotlinNativeCompile>(dependencyNamePrefix + "LinuxX64"),
tasks.named<KotlinNativeCompile>(dependencyNamePrefix + "MacosX64"),
)
else -> dependsOn(tasks.named<KotlinCompile>(dependencyNamePrefix + "Jvm"))
}
}
taskProvider(configuration)
}
private val String.sourceSetName: String
get() {
val suffix = when {
startsWith(PREFIX) -> substring(PREFIX.length).decapitalize()
else -> null
}
return when {
suffix.isNullOrEmpty() -> this
else -> suffix
}
}
private operator fun File.div(relative: String): File =
resolve(relative)
| 3 | Kotlin | 1 | 9 | 7882eec963f7b89a6337e25d03294cb13aebd525 | 3,428 | okio-extras | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.