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
data/db/src/commonMain/kotlin/io/github/droidkaigi/confsched2020/data/db/StaffDatabase.kt
DroidKaigi
202,978,106
false
null
package io.github.droidkaigi.confsched2020.data.db import io.github.droidkaigi.confsched2020.data.api.response.StaffResponse import io.github.droidkaigi.confsched2020.data.db.entity.StaffEntity import kotlinx.coroutines.flow.Flow interface StaffDatabase { fun staffs(): Flow<List<StaffEntity>> suspend fun save(apiResponse: StaffResponse) }
46
Kotlin
331
785
4c5533e4611d4bf6007284dd1f61db2fc92eb0ae
351
conference-app-2020
Apache License 2.0
book-service/src/main/kotlin/com/github/nenadjakic/library/book/entity/Book.kt
nenadjakic
803,872,281
false
{"Kotlin": 37185, "TypeScript": 13061, "HTML": 2991, "SCSS": 2530, "Dockerfile": 1722, "Shell": 1290, "CSS": 231}
package com.github.nenadjakic.library.book.entity import jakarta.persistence.* import org.hibernate.annotations.SoftDelete import org.hibernate.annotations.SoftDeleteType import java.util.* @Entity @Table(name = "book") @SoftDelete(columnName = "deleted", strategy = SoftDeleteType.DELETED) class Book : Auditable<String>() { @Id @GeneratedValue(strategy = GenerationType.UUID) var id: UUID? = null @Column(name = "isbn", length = 1000, nullable = false, unique = true) lateinit var isbn: String @Column(name = "title", length = 1000, nullable = false) lateinit var title: String @Column(name = "edition") var edition: Int? = null @Column(name = "page_count") var pageCount: Int? = null /* @ManyToOne @JoinColumn(name = "main_author_id", nullable = false) lateinit var author: Author @OneToMany private var _otherAuthors: MutableSet<Author> = mutableSetOf() var otherAuthors: Set<Author> get() = _otherAuthors.toSet() set(value) { _otherAuthors.clear() _otherAuthors.addAll(value) } */ }
0
Kotlin
0
1
db38cf00c6996b7af77e36339022ca5930c0039e
1,112
library-management
MIT License
compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/expressions/impl/IrCompositeImpl.kt
JakeWharton
99,388,807
true
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.ir.expressions.impl import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.expressions.IrComposite import org.jetbrains.kotlin.ir.expressions.IrStatementOrigin import org.jetbrains.kotlin.ir.visitors.IrElementVisitor import org.jetbrains.kotlin.types.KotlinType class IrCompositeImpl(startOffset: Int, endOffset: Int, type: KotlinType, origin: IrStatementOrigin? = null) : IrContainerExpressionBase(startOffset, endOffset, type, origin), IrComposite { constructor(startOffset: Int, endOffset: Int, type: KotlinType, origin: IrStatementOrigin?, statements: List<IrStatement>) : this(startOffset, endOffset, type, origin) { this.statements.addAll(statements) } override fun <R, D> accept(visitor: IrElementVisitor<R, D>, data: D): R = visitor.visitComposite(this, data) }
0
Kotlin
4
83
4383335168338df9bbbe2a63cb213a68d0858104
1,468
kotlin
Apache License 2.0
ksoup/src/commonTest/kotlin/com/fleeksoft/ksoup/nodes/PositionTest.kt
fleeksoft
719,100,459
false
null
package com.fleeksoft.ksoup.nodes import com.fleeksoft.ksoup.Ksoup import com.fleeksoft.ksoup.parser.Parser import com.fleeksoft.ksoup.select.NodeTraversor import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue /** * Functional tests for the Position tracking behavior (across nodes, treebuilder, etc.) */ internal class PositionTest { @Test fun parserTrackDefaults() { val htmlParser = Parser.htmlParser() assertFalse(htmlParser.isTrackPosition) htmlParser.setTrackPosition(true) assertTrue(htmlParser.isTrackPosition) val xmlParser = Parser.htmlParser() assertFalse(xmlParser.isTrackPosition) xmlParser.setTrackPosition(true) assertTrue(xmlParser.isTrackPosition) } @Test fun tracksPosition() { val html = "<p id=1\n class=foo>\n<span>Hello\n &reg;\n there &copy.</span> now.\n <!-- comment --> " val doc = Ksoup.parse(html, TrackingParser) val body = doc.expectFirst("body") val p = doc.expectFirst("p") val span = doc.expectFirst("span") val text = span.firstChild() as TextNode? assertNotNull(text) val now = span.nextSibling() as TextNode? assertNotNull(now) val comment = now.nextSibling() as Comment? assertNotNull(comment) assertFalse(body.sourceRange().isTracked()) val pRange = p.sourceRange() assertEquals("1,1:0-2,12:19", pRange.toString()) // no explicit P closer val pEndRange = p.endSourceRange() assertFalse(pEndRange.isTracked()) val pStart = pRange.start() assertTrue(pStart.isTracked) assertEquals(0, pStart.pos()) assertEquals(1, pStart.columnNumber()) assertEquals(1, pStart.lineNumber()) assertEquals("1,1:0", pStart.toString()) val pEnd = pRange.end() assertTrue(pStart.isTracked) assertEquals(19, pEnd.pos()) assertEquals(12, pEnd.columnNumber()) assertEquals(2, pEnd.lineNumber()) assertEquals("2,12:19", pEnd.toString()) assertEquals("3,1:20", span.sourceRange().start().toString()) assertEquals("3,7:26", span.sourceRange().end().toString()) // span end tag val spanEnd = span.endSourceRange() assertTrue(spanEnd.isTracked()) assertEquals("5,14:52-5,21:59", spanEnd.toString()) val wholeText = text.getWholeText() assertEquals("Hello\n ®\n there ©.", wholeText) val textOrig = "Hello\n &reg;\n there &copy." val textRange = text.sourceRange() assertEquals(textRange.end().pos() - textRange.start().pos(), textOrig.length) assertEquals("3,7:26", textRange.start().toString()) assertEquals("5,14:52", textRange.end().toString()) assertEquals("6,2:66", comment.sourceRange().start().toString()) assertEquals("6,18:82", comment.sourceRange().end().toString()) } @Test fun tracksMarkup() { val html = "<!doctype\nhtml>\n<title>jsoup &copy;\n2022</title><body>\n<![CDATA[\n<jsoup>\n]]>" val doc = Ksoup.parse(html, TrackingParser) val doctype = doc.documentType() assertNotNull(doctype) assertEquals("html", doctype.name()) assertEquals("1,1:0-2,6:15", doctype.sourceRange().toString()) val title = doc.expectFirst("title") val titleText = title.firstChild() as TextNode? assertNotNull(titleText) assertEquals("jsoup ©\n2022", title.text()) assertEquals(titleText.getWholeText(), title.text()) assertEquals("3,1:16-3,8:23", title.sourceRange().toString()) assertEquals("3,8:23-4,5:40", titleText.sourceRange().toString()) val cdata = doc.body().childNode(1) as CDataNode assertEquals("\n<jsoup>\n", cdata.text()) assertEquals("5,1:55-7,4:76", cdata.sourceRange().toString()) } @Test fun tracksDataNodes() { val html = "<head>\n<script>foo;\nbar()\n5 <= 4;</script>" val doc = Ksoup.parse(html, TrackingParser) val script = doc.expectFirst("script") assertNotNull(script) assertEquals("2,1:7-2,9:15", script.sourceRange().toString()) val data = script.firstChild() as DataNode? assertNotNull(data) assertEquals("2,9:15-4,8:33", data.sourceRange().toString()) } @Test fun tracksXml() { val xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!doctype html>\n<rss url=foo>\nXML\n</rss>\n<!-- comment -->" val doc = Ksoup.parse(xml, Parser.xmlParser().setTrackPosition(true)) val decl = doc.childNode(0) as XmlDeclaration assertEquals("1,1:0-1,39:38", decl.sourceRange().toString()) val doctype = doc.childNode(2) as DocumentType assertEquals("2,1:39-2,16:54", doctype.sourceRange().toString()) val rss = doc.firstElementChild() assertNotNull(rss) assertEquals("3,1:55-3,14:68", rss.sourceRange().toString()) assertEquals("5,1:73-5,7:79", rss.endSourceRange().toString()) val text = rss.firstChild() as TextNode? assertNotNull(text) assertEquals("3,14:68-5,1:73", text.sourceRange().toString()) val comment = rss.nextSibling()!!.nextSibling() as Comment? assertEquals("6,1:80-6,17:96", comment!!.sourceRange().toString()) } @Test fun tracksTableMovedText() { val html = "<table>foo<tr>bar<td>baz</td>qux</tr>coo</table>" val doc = Ksoup.parse(html, TrackingParser) val textNodes: MutableList<TextNode> = ArrayList() NodeTraversor.traverse({ node, depth -> if (node is TextNode) { textNodes.add(node) } }, doc) assertEquals(5, textNodes.size) assertEquals("1,8:7-1,11:10", textNodes[0].sourceRange().toString()) assertEquals("1,15:14-1,18:17", textNodes[1].sourceRange().toString()) assertEquals("1,22:21-1,25:24", textNodes[2].sourceRange().toString()) assertEquals("1,30:29-1,33:32", textNodes[3].sourceRange().toString()) assertEquals("1,38:37-1,41:40", textNodes[4].sourceRange().toString()) } @Test fun tracksClosingHtmlTagsInXml() { // verifies https://github.com/jhy/jsoup/issues/1935 val xml = "<p>One</p><title>Two</title><data>Three</data>" val doc = Ksoup.parse(xml, Parser.xmlParser().setTrackPosition(true)) val els = doc.children() for (el in els) { assertTrue(el.sourceRange().isTracked()) assertTrue(el.endSourceRange().isTracked()) } } @Test fun tracksClosingHeadingTags() { // https://github.com/jhy/jsoup/issues/1987 val html = "<h1>One</h1><h2>Two</h2><h10>Ten</h10>" val doc = Ksoup.parse(html, TrackingParser) val els = doc.body().children() for (el in els) { assertTrue(el.sourceRange().isTracked()) assertTrue(el.endSourceRange().isTracked()) } val h2 = doc.expectFirst("h2") assertEquals("1,13:12-1,17:16", h2.sourceRange().toString()) assertEquals("1,20:19-1,25:24", h2.endSourceRange().toString()) } companion object { var TrackingParser = Parser.htmlParser().setTrackPosition(true) } }
4
null
2
62
911a3cfcd7062ae5f57039d1d50c9011b71d13eb
7,387
ksoup
Apache License 2.0
ToDo/app/src/main/java/com/example/hassanusman/getdisciplined/ui/base/BasePresenter.kt
HassanUsman
111,360,831
false
{"Ignore List": 2, "Markdown": 2, "Gradle": 3, "Java Properties": 3, "Shell": 1, "Batchfile": 1, "Proguard": 1, "Java": 2, "XML": 102, "Kotlin": 74, "JSON": 3, "Text": 1}
package com.example.hassanusman.getdisciplined.ui.base import com.example.hassanusman.getdisciplined.data.DataManager import com.example.hassanusman.getdisciplined.utils.rx.SchedulerProvider import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject /** * Created by HassanUsman on 11/09/2017. */ open class BasePresenter<V : MvpView> @Inject constructor(var dataManager: DataManager, var schedulerProvider: SchedulerProvider?, var compositeDisposable: CompositeDisposable?) : MvpPresenter<V> { var mvpView: V? = null override fun onAttach(mvpView: V) { this.mvpView = mvpView } override fun onDetach() { compositeDisposable?.dispose() mvpView = null } }
1
Kotlin
5
62
362bdc4576928299726c0feeb276782ae85fd0f0
780
ToDo
Apache License 2.0
ui/ui-core/src/test/java/androidx/ui/engine/geometry/RRectTest.kt
FYI-Google
258,765,297
false
null
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 androidx.compose.ui.geometry import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class RRectTest { @Test fun `RRect_contains()`() { val rrect = RRect( Rect(1.0f, 1.0f, 2.0f, 2.0f), topLeft = Radius(0.5f), topRight = Radius(0.25f), bottomRight = Radius(0.25f, 0.75f), bottomLeft = Radius.Zero ) assertFalse(rrect.contains(Offset(1.0f, 1.0f))) assertFalse(rrect.contains(Offset(1.1f, 1.1f))) assertTrue(rrect.contains(Offset(1.15f, 1.15f))) assertFalse(rrect.contains(Offset(2.0f, 1.0f))) assertFalse(rrect.contains(Offset(1.93f, 1.07f))) assertFalse(rrect.contains(Offset(1.97f, 1.7f))) assertTrue(rrect.contains(Offset(1.7f, 1.97f))) assertTrue(rrect.contains(Offset(1.0f, 1.99f))) } @Test fun `RRect_contains() large radii`() { val rrect = RRect( Rect(1.0f, 1.0f, 2.0f, 2.0f), topLeft = Radius(5000.0f), topRight = Radius(2500.0f), bottomRight = Radius(2500.0f, 7500.0f), bottomLeft = Radius.Zero ) assertFalse(rrect.contains(Offset(1.0f, 1.0f))) assertFalse(rrect.contains(Offset(1.1f, 1.1f))) assertTrue(rrect.contains(Offset(1.15f, 1.15f))) assertFalse(rrect.contains(Offset(2.0f, 1.0f))) assertFalse(rrect.contains(Offset(1.93f, 1.07f))) assertFalse(rrect.contains(Offset(1.97f, 1.7f))) assertTrue(rrect.contains(Offset(1.7f, 1.97f))) assertTrue(rrect.contains(Offset(1.0f, 1.99f))) } }
0
null
1
6
b9cd83371e928380610719dfbf97c87c58e80916
2,396
platform_frameworks_support
Apache License 2.0
shared/src/commonMain/kotlin/App.kt
mrjoechen
669,421,109
false
{"Kotlin": 436969, "Java": 23934, "Swift": 580, "Shell": 228}
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import com.alpha.showcase.common.ui.MainNavHost import com.alpha.showcase.common.ui.theme.MyApplicationTheme @Composable fun App() { MyApplicationTheme { Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { MainNavHost() } } }
0
Kotlin
0
0
6b3c425ac81fb1eb464f5c9351a4efb6993cbd27
516
Showcase-multiplatform
Apache License 2.0
app/src/main/java/com/loftechs/sample/common/event/CallCDREvent.kt
LoFTechs
355,161,561
false
{"Kotlin": 443779, "Java": 1512}
package com.loftechs.sample.common.event import com.loftechs.sample.call.list.CallLogData data class CallCDREvent( val receiverID: String, val callLogData: CallLogData, )
0
Kotlin
1
1
1b19f8c779e2e051b326e3c491a262c76d5df731
189
LTSample-Android-Kotlin
MIT License
app/src/main/java/org/ddosolitary/okcagent/ssh/SshAgentService.kt
DDoSolitary
197,309,939
false
null
package org.ddosolitary.okcagent.ssh import android.content.Intent import android.util.Base64 import android.util.Log import com.bugsnag.android.Bugsnag import org.ddosolitary.okcagent.AgentService import org.ddosolitary.okcagent.R import org.ddosolitary.okcagent.showError import org.openintents.ssh.authentication.SshAuthenticationApi.EXTRA_ERROR import org.openintents.ssh.authentication.SshAuthenticationApiError import org.openintents.ssh.authentication.request.SigningRequest import org.openintents.ssh.authentication.request.SshPublicKeyRequest import org.openintents.ssh.authentication.response.SigningResponse import org.openintents.ssh.authentication.response.SshPublicKeyResponse import java.net.Socket import java.util.concurrent.Semaphore private const val LOG_TAG = "SshAgentService" class SshAgentService : AgentService() { override fun getErrorMessage(intent: Intent): String? { return intent.getParcelableExtra<SshAuthenticationApiError>(EXTRA_ERROR)?.message } override fun runAgent(port: Int, intent: Intent) { var socket: Socket? = null try { socket = Socket("127.0.0.1", port) val input = socket.getInputStream() val output = socket.getOutputStream() val keys = SshKeyInfo.load(this) val lock = Semaphore(0) var connRes = false SshApi(this) { res -> if (!res) showError(this@SshAgentService, R.string.error_connect) connRes = res lock.release() }.use { api -> api.connect() lock.acquire() check(connRes) val executeApi = { reqIntent: Intent -> api.executeApi(reqIntent) } val publicKeys = mutableListOf<SshPublicKeyInfo>() for (key in keys) { val resIntent = callApi(executeApi, SshPublicKeyRequest(key.id).toIntent(), port, null) ?: return val pubKeyStr = SshPublicKeyResponse(resIntent).sshPublicKey val info = SshPublicKeyInfo( Base64.decode( pubKeyStr.substring(pubKeyStr.indexOf(' ') + 1), Base64.DEFAULT ), key.description.toByteArray(Charsets.UTF_8) ) publicKeys.add(info) } while (true) { val req = SshAgentMessage.readFromStream(input) ?: break val resMsg = when (req.type) { SSH_AGENTC_REQUEST_IDENTITIES -> { SshAgentMessage( SSH_AGENT_IDENTITIES_ANSWER, SshIdentitiesResponse(publicKeys).toBytes() ) } SSH_AGENTC_SIGN_REQUEST -> { val signReq = SshSignRequest(req.contents!!) val keyId = keys[publicKeys.indexOfFirst { it.publicKey contentEquals signReq.keyBlob }].id val resIntent = callApi( executeApi, SigningRequest(signReq.data, keyId, signReq.flags).toIntent(), port, null ) if (resIntent != null) { SshAgentMessage( SSH_AGENT_SIGN_RESPONSE, SshSignResponse(SigningResponse(resIntent).signature).toBytes() ) } else null } else -> null } (resMsg ?: SshAgentMessage(SSH_AGENT_FAILURE, null)).writeToStream(output) } } } catch (e: Exception) { Bugsnag.notify(e) Log.e(LOG_TAG, Log.getStackTraceString(e)) try { socket?.setSoLinger(true, 0) } catch (e2: Exception) { Log.w(LOG_TAG, "Failed to set linger option on exception: %s".format(e2)) showError(this, e.toString()) } } finally { try { socket?.close() } catch (e: Exception) { Log.w(LOG_TAG, "Failed to close the socket on exit: %s".format(e)) } checkThreadExit(port) } } override fun onCreate() { super.onCreate() startForeground( R.string.notification_ssh_title, R.string.notification_ssh_content, R.integer.notification_id_ssh ) } }
17
Kotlin
8
99
817bc018b59f7fbba992e98601f7c72278ce9acd
3,631
OkcAgent
MIT License
src/test/kotlin/io/github/lobodpav/spock/test/idea/SpockCodeInsightFixtureTestCase.kt
lobodpav
671,811,601
false
null
package io.github.lobodpav.spock.test.idea import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase /** * Since Spock Specifications cannot extend both [spock.lang.Specification] and * [LightJavaCodeInsightFixtureTestCase], this wrapper allows for injection of the * fixture into specifications via the [WithIdea] annotation. * * The [groovyOnClasspath] and [spockOnClasspath] arguments allow custom setup * for [com.intellij.openapi.actionSystem.AnAction] testing. */ class SpockCodeInsightFixtureTestCase( private val groovyOnClasspath: Boolean = true, private val spockOnClasspath: Boolean = true, ) : LightJavaCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor = SpockLightProjectDescriptor().apply { // Adds Spock dependency to avoid ERROR inspections about missing spock libraries (e.g. `Specification`) if (groovyOnClasspath) withRepositoryLibrary("org.apache.groovy:groovy:4.0.13", false) if (spockOnClasspath) withRepositoryLibrary("org.spockframework:spock-core:2.3-groovy-4.0", false) } val fixture: JavaCodeInsightTestFixture get() = super.myFixture fun setup() { super.setUp() } fun cleanup() { super.tearDown() invokeWriteAction { VirtualFileManager.getInstance().findFileByUrl(SpockLightProjectDescriptor.TEMP_DIRECTORY) ?.children?.forEach { it.delete(this) } } } }
0
null
0
2
f8acf0da8ef61c8d70681a16ab97473fcb84261d
1,665
spock-intellij-plugin
Apache License 2.0
api/src/main/java/com/gromyk/api/services/SearchService.kt
YGromyk
192,622,071
false
null
package com.gromyk.api.services import com.gromyk.api.dtos.search.SearchArtistResponse import retrofit2.http.GET import retrofit2.http.Query interface SearchService { @GET("?method=artist.search") suspend fun searchArtist(@Query("artist") artist: String): SearchArtistResponse? }
1
null
1
1
3d0aab86f7372066b08fc6ebdfea8e08e06f4f90
289
lastFM.AF
Apache License 2.0
src/main/kotlin/insyncwithfoo/ryecharm/configurations/uv/Configurations.kt
InSyncWithFoo
849,672,176
false
{"Kotlin": 264146, "Python": 3171, "HTML": 624}
package insyncwithfoo.ryecharm.configurations.uv import insyncwithfoo.ryecharm.Commented import insyncwithfoo.ryecharm.Keyed import insyncwithfoo.ryecharm.MillisecondsOrNoLimit import insyncwithfoo.ryecharm.configurations.Copyable import insyncwithfoo.ryecharm.configurations.DisplayableState import insyncwithfoo.ryecharm.configurations.HasTimeouts import insyncwithfoo.ryecharm.configurations.ProjectOverrideState import insyncwithfoo.ryecharm.configurations.SettingName import insyncwithfoo.ryecharm.message internal class UVConfigurations : DisplayableState(), HasTimeouts, Copyable { var executable by string(null) var configurationFile by string(null) var packageManaging by property(true) var packageManagingNonUVProject by property(false) override var timeouts by map<SettingName, MillisecondsOrNoLimit>() } internal enum class UVTimeouts(override val key: String, override val comment: String) : Keyed, Commented { RUN("run", message("configurations.timeouts.uv.run")), INIT("init", message("configurations.timeouts.uv.init")), ADD("add", message("configurations.timeouts.uv.add")), REMOVE("remove", message("configurations.timeouts.uv.remove")), SYNC("sync", message("configurations.timeouts.uv.sync")), LOCK("lock", message("configurations.timeouts.uv.lock")), TREE("tree", message("configurations.timeouts.uv.tree")), TOOL_RUN("tool run", message("configurations.timeouts.uv.toolrun")), TOOL_INSTALL("tool install", message("configurations.timeouts.uv.toolinstall")), TOOL_UPGRADE("tool upgrade", message("configurations.timeouts.uv.toolupgrade")), TOOL_LIST("tool list", message("configurations.timeouts.uv.toollist")), TOOL_UNINSTALL("tool uninstall", message("configurations.timeouts.uv.tooluninstall")), TOOL_UPDATE_SHELL("tool update-shell", message("configurations.timeouts.uv.toolupdateshell")), TOOL_DIR("tool dir", message("configurations.timeouts.uv.tooldir")), PYTHON_LIST("python list", message("configurations.timeouts.uv.pythonlist")), PYTHON_INSTALL("python install", message("configurations.timeouts.uv.pythoninstall")), PYTHON_FIND("python find", message("configurations.timeouts.uv.pythonfind")), PYTHON_PIN("python pin", message("configurations.timeouts.uv.pythonpin")), PYTHON_DIR("python dir", message("configurations.timeouts.uv.pythondir")), PYTHON_UNINSTALL("python uninstall", message("configurations.timeouts.uv.pythonuninstall")), PIP_COMPILE("pip compile", message("configurations.timeouts.uv.pipcompile")), PIP_SYNC("pip sync", message("configurations.timeouts.uv.pipsync")), PIP_INSTALL("pip install", message("configurations.timeouts.uv.pipinstall")), PIP_UNINSTALL("pip uninstall", message("configurations.timeouts.uv.pipuninstall")), PIP_FREEZE("pip freeze", message("configurations.timeouts.uv.pipfreeze")), PIP_LIST("pip list", message("configurations.timeouts.uv.piplist")), PIP_SHOW("pip show", message("configurations.timeouts.uv.pipshow")), PIP_TREE("pip tree", message("configurations.timeouts.uv.piptree")), PIP_CHECK("pip check", message("configurations.timeouts.uv.pipcheck")), VENV("venv", message("configurations.timeouts.uv.venv")), CACHE("cache", message("configurations.timeouts.uv.cache")), VERSION("version", message("configurations.timeouts.uv.version")); override val label by ::key } internal class UVOverrides : DisplayableState(), ProjectOverrideState { override var names by map<SettingName, Boolean>() }
2
Kotlin
1
7
c1a04b622fbfb02a2fb155d8c9aa069520eda23e
3,551
ryecharm
MIT License
BaseDebug/src/main/java/com/bihe0832/android/base/debug/tab/bottom/DebugSimpleBottomTabFragment.kt
AndroidAppFactory
222,415,705
false
null
package com.bihe0832.android.base.debug.tab.bottom import android.view.View import com.bihe0832.android.base.debug.R import com.bihe0832.android.base.debug.dialog.DebugDialogFragment import com.bihe0832.android.base.debug.download.DebugDownloadFragment import com.bihe0832.android.base.debug.file.DebugFileFragment import com.bihe0832.android.base.debug.permission.DebugPermissionFragment import com.bihe0832.android.common.ui.bottom.bar.CommonMainFragment import com.bihe0832.android.common.ui.bottom.bar.SimpleBottomBarTab import com.bihe0832.android.framework.ui.BaseFragment import com.bihe0832.android.lib.ui.bottom.bar.BaseBottomBarTab class DebugSimpleBottomTabFragment : CommonMainFragment() { override fun getDefaultTabID(): Int { return 1 } override fun getFragments(): ArrayList<BaseFragment> { return ArrayList<BaseFragment>().apply { add(DebugDialogFragment()) add(DebugDownloadFragment()) add(DebugPermissionFragment()) add(DebugFileFragment()) } } override fun getBottomBarTabs(): ArrayList<BaseBottomBarTab> { ArrayList<BaseBottomBarTab>().apply { add(SimpleBottomBarTab(context, R.drawable.icon_camera, "弹框")) add(SimpleBottomBarTab(context, R.drawable.icon_author, "下载")) add(SimpleBottomBarTab(context, R.drawable.icon_feedback, "权限")) add(SimpleBottomBarTab(context, R.drawable.icon_cloud, "文件")) }.let { return it } } override fun initView(view: View) { super.initView(view) // getBottomBar().getItem(0).showUnreadMsg(0) // getBottomBar().getItem(1).showUnreadMsg(2) // getBottomBar().getItem(2).showUnreadMsg(22) // getBottomBar().getItem(3).showUnreadMsg(200) } }
0
null
21
72
e11cbca06d092a3bdd5a58dd4a5260b1f4a208d8
1,817
AndroidAppFactory
MIT License
detekt-test/src/main/kotlin/io/gitlab/arturbosch/detekt/test/CompileExtensions.kt
mlegy
212,993,385
true
{"Kotlin": 1474242, "Groovy": 3832, "Shell": 1055, "HTML": 698}
package io.gitlab.arturbosch.detekt.test import java.nio.file.Path /** * Use this method if you define a kt file/class as a plain string in your test. */ fun compileContentForTest(content: String) = KtTestCompiler.compileFromContent(content) /** * Use this method if you test a kt file/class in the test resources. */ fun compileForTest(path: Path) = KtTestCompiler.compile(path)
3
null
0
1
c37812e0b8af0ec304fcefce5152dfc9845d52c8
387
detekt
Apache License 2.0
test-common/src/commonMain/kotlin/io/github/jan/supabase/testing/KtorUtils.kt
supabase-community
495,084,592
false
{"Kotlin": 691880}
package io.github.jan.supabase.testing import io.ktor.client.engine.mock.toByteArray import io.ktor.http.content.OutgoingContent import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement suspend fun OutgoingContent.toJsonElement(): JsonElement { return Json.decodeFromString(toByteArray().decodeToString()) }
19
Kotlin
31
291
7421ef38051610eca9002aaebe4b5a437b1da7d1
341
supabase-kt
MIT License
ktorfit-lib-common/src/commonMain/kotlin/de/jensklingenberg/ktorfit/converter/builtin/KtorfitDefaultConverterFactory.kt
Foso
203,655,484
false
null
package de.jensklingenberg.ktorfit.converter.builtin import de.jensklingenberg.ktorfit.Ktorfit import de.jensklingenberg.ktorfit.Response import de.jensklingenberg.ktorfit.converter.Converter import de.jensklingenberg.ktorfit.internal.TypeData import io.ktor.client.call.* import io.ktor.client.statement.* /** * Converter for [Response] */ internal class KtorfitDefaultConverterFactory : Converter.Factory { open class DefaultResponseClassSuspendConverter(val typeData: TypeData, val ktorfit: Ktorfit) : Converter.SuspendResponseConverter<HttpResponse, Response<Any?>> { override suspend fun convert(response: HttpResponse): Response<Any?> { val typeInfo = typeData.typeArgs.first().typeInfo return try { val rawResponse = response val code: Int = rawResponse.status.value when { code < 200 || code >= 300 -> { val errorBody = rawResponse.body<Any>() Response.error(errorBody, rawResponse) } code == 204 || code == 205 -> { Response.success<Any>(null, rawResponse) } else -> { val convertedBody = ktorfit.nextSuspendResponseConverter( null, typeData.typeArgs.first() )?.convert(rawResponse) ?: rawResponse.body<Any>(typeInfo) Response.success(convertedBody, rawResponse) } } } catch (exception: Exception) { throw exception } } } override fun suspendResponseConverter( typeData: TypeData, ktorfit: Ktorfit ): Converter.SuspendResponseConverter<HttpResponse, *>? { if (typeData.typeInfo.type == Response::class) { return DefaultResponseClassSuspendConverter(typeData, ktorfit) } return null } }
26
null
30
985
77bdb11430e2c787eb69e3c48780eea99e8a75b4
2,076
Ktorfit
Apache License 2.0
app/src/main/java/com/stevesoltys/seedvault/plugins/saf/DocumentsProviderStoragePlugin.kt
LineageOS
293,909,131
false
null
/* * SPDX-FileCopyrightText: 2020 The Calyx Institute * SPDX-License-Identifier: Apache-2.0 */ package com.stevesoltys.seedvault.plugins.saf import android.content.Context import android.content.pm.PackageManager import android.net.Uri import android.os.Environment import android.os.StatFs import android.provider.DocumentsContract import android.provider.DocumentsContract.Root.COLUMN_AVAILABLE_BYTES import android.provider.DocumentsContract.Root.COLUMN_ROOT_ID import android.util.Log import androidx.core.database.getIntOrNull import androidx.documentfile.provider.DocumentFile import com.stevesoltys.seedvault.getStorageContext import com.stevesoltys.seedvault.plugins.EncryptedMetadata import com.stevesoltys.seedvault.plugins.StoragePlugin import com.stevesoltys.seedvault.plugins.chunkFolderRegex import com.stevesoltys.seedvault.plugins.tokenRegex import com.stevesoltys.seedvault.ui.storage.AUTHORITY_STORAGE import com.stevesoltys.seedvault.ui.storage.ROOT_ID_DEVICE import app.grapheneos.backup.storage.plugin.PluginConstants.SNAPSHOT_EXT import java.io.FileNotFoundException import java.io.IOException import java.io.InputStream import java.io.OutputStream private val TAG = DocumentsProviderStoragePlugin::class.java.simpleName internal class DocumentsProviderStoragePlugin( private val appContext: Context, private val storage: DocumentsStorage, ) : StoragePlugin<Uri> { /** * Attention: This context might be from a different user. Use with care. */ private val context: Context get() = appContext.getStorageContext { storage.safStorage.isUsb } private val packageManager: PackageManager = appContext.packageManager override suspend fun test(): Boolean { val dir = storage.rootBackupDir return dir != null && dir.exists() } override suspend fun getFreeSpace(): Long? { val rootId = storage.safStorage.rootId ?: return null val authority = storage.safStorage.uri.authority // using DocumentsContract#buildRootUri(String, String) with rootId directly doesn't work val rootUri = DocumentsContract.buildRootsUri(authority) val projection = arrayOf(COLUMN_AVAILABLE_BYTES) // query directly for our rootId val bytesAvailable = context.contentResolver.query( rootUri, projection, "$COLUMN_ROOT_ID=?", arrayOf(rootId), null )?.use { c -> if (!c.moveToNext()) return@use null // no results val bytes = c.getIntOrNull(c.getColumnIndex(COLUMN_AVAILABLE_BYTES)) if (bytes != null && bytes >= 0) return@use bytes.toLong() else return@use null } // if we didn't get anything from SAF, try some known hacks return if (bytesAvailable == null && authority == AUTHORITY_STORAGE) { if (rootId == ROOT_ID_DEVICE) { StatFs(Environment.getDataDirectory().absolutePath).availableBytes } else if (storage.safStorage.isUsb) { val documentId = storage.safStorage.uri.lastPathSegment ?: return null StatFs("/mnt/media_rw/${documentId.trimEnd(':')}").availableBytes } else null } else bytesAvailable } @Throws(IOException::class) override suspend fun startNewRestoreSet(token: Long) { // reset current storage storage.reset(token) } @Throws(IOException::class) override suspend fun initializeDevice() { // reset storage without new token, so folders get recreated // otherwise stale DocumentFiles will hang around storage.reset(null) } @Throws(IOException::class) override suspend fun hasData(token: Long, name: String): Boolean { val setDir = storage.getSetDir(token) ?: return false return setDir.findFileBlocking(context, name) != null } @Throws(IOException::class) override suspend fun getOutputStream(token: Long, name: String): OutputStream { val setDir = storage.getSetDir(token) ?: throw IOException() val file = setDir.createOrGetFile(context, name) return storage.getOutputStream(file) } @Throws(IOException::class) override suspend fun getInputStream(token: Long, name: String): InputStream { val setDir = storage.getSetDir(token) ?: throw IOException() val file = setDir.findFileBlocking(context, name) ?: throw FileNotFoundException() return storage.getInputStream(file) } @Throws(IOException::class) override suspend fun removeData(token: Long, name: String) { val setDir = storage.getSetDir(token) ?: throw IOException() val file = setDir.findFileBlocking(context, name) ?: return if (!file.delete()) throw IOException("Failed to delete $name") } override suspend fun getAvailableBackups(): Sequence<EncryptedMetadata>? { val rootDir = storage.rootBackupDir ?: return null val backupSets = getBackups(context, rootDir) val iterator = backupSets.iterator() return generateSequence { if (!iterator.hasNext()) return@generateSequence null // end sequence val backupSet = iterator.next() EncryptedMetadata(backupSet.token) { storage.getInputStream(backupSet.metadataFile) } } } override val providerPackageName: String? by lazy { val authority = storage.getAuthority() ?: return@lazy null val providerInfo = packageManager.resolveContentProvider(authority, 0) ?: return@lazy null providerInfo.packageName } } class BackupSet(val token: Long, val metadataFile: DocumentFile) internal suspend fun getBackups(context: Context, rootDir: DocumentFile): List<BackupSet> { val backupSets = ArrayList<BackupSet>() val files = try { // block until the DocumentsProvider has results rootDir.listFilesBlocking(context) } catch (e: IOException) { Log.e(TAG, "Error loading backups from storage", e) return backupSets } for (set in files) { // retrieve name only once as this causes a DB query val name = set.name // get current token from set or continue to next file/set val token = set.getTokenOrNull(name) ?: continue // block until children of set are available val metadata = try { set.findFileBlocking(context, FILE_BACKUP_METADATA) } catch (e: IOException) { Log.e(TAG, "Error reading metadata file in backup set folder: $name", e) null } if (metadata == null) { Log.w(TAG, "Missing metadata file in backup set folder: $name") } else { backupSets.add(BackupSet(token, metadata)) } } return backupSets } private fun DocumentFile.getTokenOrNull(name: String?): Long? { val looksLikeToken = name != null && tokenRegex.matches(name) // check for isDirectory only if we already have a valid token (causes DB query) if (!looksLikeToken || !isDirectory) { // only log unexpected output if (name != null && isUnexpectedFile(name)) { Log.w(TAG, "Found invalid backup set folder: $name") } return null } return try { name?.toLong() } catch (e: NumberFormatException) { throw AssertionError(e) } } private fun isUnexpectedFile(name: String): Boolean { return name != FILE_NO_MEDIA && !chunkFolderRegex.matches(name) && !name.endsWith(SNAPSHOT_EXT) }
95
null
68
28
c906fd7834ed027fbc6c4dacea1b15525a882013
7,523
android_packages_apps_Seedvault
Apache License 2.0
feature-info/src/main/java/com/paulrybitskyi/gamedge/feature/info/presentation/widgets/screenshots/GameInfoScreenshotUiModelMapper.kt
mars885
289,036,871
false
{"Kotlin": 1318694, "Shell": 593}
/* * Copyright 2021 <NAME>, <EMAIL> * * 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.paulrybitskyi.gamedge.feature.info.presentation.widgets.screenshots import com.paulrybitskyi.gamedge.core.factories.IgdbImageSize import com.paulrybitskyi.gamedge.core.factories.IgdbImageUrlFactory import com.paulrybitskyi.gamedge.common.domain.games.entities.Image import com.paulrybitskyi.hiltbinder.BindType import javax.inject.Inject internal interface GameInfoScreenshotUiModelMapper { fun mapToUiModel(image: Image): GameInfoScreenshotUiModel? } @BindType(installIn = BindType.Component.VIEW_MODEL) internal class GameInfoScreenshotUiModelMapperImpl @Inject constructor( private val igdbImageUrlFactory: IgdbImageUrlFactory, ) : GameInfoScreenshotUiModelMapper { override fun mapToUiModel(image: Image): GameInfoScreenshotUiModel? { val screenshotUrl = igdbImageUrlFactory.createUrl( image, IgdbImageUrlFactory.Config(IgdbImageSize.MEDIUM_SCREENSHOT), ) ?: return null return GameInfoScreenshotUiModel( id = image.id, url = screenshotUrl, ) } } internal fun GameInfoScreenshotUiModelMapper.mapToUiModels( images: List<Image>, ): List<GameInfoScreenshotUiModel> { if (images.isEmpty()) return emptyList() return images.mapNotNull(::mapToUiModel) }
4
Kotlin
63
659
69b3ada08cb877af9b775c6a4f3d9eb1c3470d9c
1,880
gamedge
Apache License 2.0
app/src/main/java/com/example/rangkul/ui/createpost/CreatePostActivity.kt
ferry582
664,228,510
false
null
package com.example.rangkul.ui.createpost import android.app.Activity import android.app.Dialog import android.content.Intent import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.MotionEvent import android.view.Window import android.widget.ImageView import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.core.content.ContextCompat import androidx.core.view.doOnLayout import com.bumptech.glide.Glide import com.example.rangkul.R import com.example.rangkul.data.model.DiaryData import com.example.rangkul.data.model.ImageListData import com.github.dhaval2404.imagepicker.ImagePicker import com.example.rangkul.data.model.PostData import com.example.rangkul.data.model.UserData import com.example.rangkul.databinding.ActivityCreatePostBinding import com.example.rangkul.ui.MainActivity import com.example.rangkul.utils.* import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import java.util.Date @AndroidEntryPoint class CreatePostActivity : AppCompatActivity(), SelectMoodBottomSheetFragment.SelectedMoodListener { private lateinit var binding: ActivityCreatePostBinding private lateinit var selectedCategory: String private var postType: String = "Public" // Default post type private val viewModel: CreatePostViewModel by viewModels() private var imageLocalUri: Uri? = null private var selectedMood: ImageListData? = null private val startForPostImageResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> val resultCode = result.resultCode val data = result.data when (resultCode) { Activity.RESULT_OK -> { val fileUri = data?.data!! imageLocalUri = fileUri binding.ivImagePost.setImageURI(imageLocalUri) binding.chipAddImage.hide() binding.chipChangePhoto.show() binding.chipDeletePhoto.show() binding.cvImagePost.show() loadingVisibility(false) } ImagePicker.RESULT_ERROR -> { loadingVisibility(false) toast("ImagePicker: ${ImagePicker.getError(data)}") } else -> { loadingVisibility(false) Log.e("CreatePostActivity","Task Cancelled") } } } // Get selected mood from bottom sheet dialog fragment override fun selectedMood(selectedMood: ImageListData) { this.selectedMood = selectedMood binding.civEmoticon.setImageResource(selectedMood.image) binding.tvUserMood.text = selectedMood.name binding.tvUserMood.setTextColor(ContextCompat.getColor(this, R.color.black)) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityCreatePostBinding.inflate(layoutInflater) setContentView(binding.root) setToolbar() // binding.etCaption.doOnLayout { // var prevY = 0f // binding.etCaption.setOnTouchListener { v, event -> // if (v.id == R.id.etComment) { // when (event.action) { // MotionEvent.ACTION_DOWN -> { // prevY = event.y // v.parent.requestDisallowInterceptTouchEvent(true) // } // MotionEvent.ACTION_MOVE -> { // if (event.y > prevY) { // // Jika gerakan ke atas, gulirkan ke atas // binding.etCaption.scrollBy(0, (prevY - event.y).toInt()) // } else { // // Jika gerakan ke bawah, gulirkan ke bawah // binding.etCaption.scrollBy(0, (prevY - event.y).toInt()) // } // prevY = event.y // } // MotionEvent.ACTION_UP -> v.parent.requestDisallowInterceptTouchEvent(false) // } // } // false // } // } // Set Category selectedCategory = intent.getStringExtra("SELECTED_CATEGORY").toString() binding.tvSelectedCategory.text = selectedCategory // Set User name binding.tvUserName.text = currentUserData().userName // Set profile picture binding.civProfilePicture.apply { if (currentUserData().profilePicture.isNullOrEmpty()) setImageResource(R.drawable.ic_profile_picture_default) else { Glide .with(context) .load(currentUserData().profilePicture) .placeholder(R.drawable.ic_profile_picture_default) .error(R.drawable.ic_baseline_error_24) .into(binding.civProfilePicture) } } binding.clDiary.setOnClickListener { val commentOptionsBottomDialogFragment = SelectMoodBottomSheetFragment(this) commentOptionsBottomDialogFragment.show( supportFragmentManager, "SelectMoodBottomSheetFragment" ) } binding.chipGroupPostType.setOnCheckedStateChangeListener { group, _ -> when (group.checkedChipId) { R.id.chipPublic -> { updateUI("Public") postType = "Public" } R.id.chipAnonymous -> { updateUI("Anonymous") postType = "Anonymous" } else -> { updateUI("Diary") postType = "Diary" } } } binding.chipAddImage.setOnClickListener { startImagePicker() } binding.chipChangePhoto.setOnClickListener { startImagePicker() } binding.chipDeletePhoto.setOnClickListener { binding.chipAddImage.show() binding.chipChangePhoto.hide() binding.chipDeletePhoto.hide() binding.cvImagePost.hide() imageLocalUri = null } // publish post binding.btPublish.setOnClickListener { binding.btPublish.isClickable = false // To prevent multiple clicks when the task has started hideKeyboard() if (inputValidation()) { isCaptionContainProfanity() } } observeAddPost() observeAddDiary() } private fun isCaptionContainProfanity() { loadingVisibility(true) viewModel.getProfanityCheck(binding.etCaption.text.toString()) { state -> when(state) { is UiState.Loading -> { loadingVisibility(true) } is UiState.Failure -> { loadingVisibility(false) toast(state.error) binding.btPublish.isClickable = true } is UiState.Success -> { loadingVisibility(false) if (state.data.toBoolean()) { showProfanityDialog() binding.btPublish.isClickable = true } else isPostImageExist() } } } } private fun showProfanityDialog() { val dialog = Dialog(this) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) dialog.setContentView(R.layout.dialog_profanity_detected) dialog.show() dialog.findViewById<ImageView>(R.id.ivCloseDialog).setOnClickListener { dialog.dismiss() } } private fun observeAddDiary() { viewModel.addDiary.observe(this) {state -> when(state) { is UiState.Loading -> { loadingVisibility(true) } is UiState.Failure -> { loadingVisibility(false) toast(state.error) binding.btPublish.isClickable = true } is UiState.Success -> { loadingVisibility(false) val intent = Intent(this@CreatePostActivity, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) intent.putExtra("PUBLISH_DIARY_SUCCESSFUL", "true") startActivity(intent) } } } } private fun observeAddPost() { viewModel.addPost.observe(this) {state -> when(state) { is UiState.Loading -> { loadingVisibility(true) } is UiState.Failure -> { loadingVisibility(false) toast(state.error) binding.btPublish.isClickable = true } is UiState.Success -> { loadingVisibility(false) val intent = Intent(this@CreatePostActivity, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) intent.putExtra("PUBLISH_POST_SUCCESSFUL", "true") startActivity(intent) } } } } private fun startImagePicker() { loadingVisibility(true) ImagePicker.with(this) .cropSquare() .compress(1024) .galleryOnly() .createIntent { intent -> startForPostImageResult.launch(intent) } } private fun addDiaryData(imageUrl: String?) { viewModel.addDiary( DiaryData( diaryId = "", createdBy = currentUserData().userId, createdAt = Date(), caption = binding.etCaption.text.toString(), image = imageUrl, type = postType, modifiedAt = Date(), moodTitle = selectedMood!!.name, moodImage = selectedMood!!.image ) ) } private fun addPostData(imageUrl: String?) { viewModel.addPost( PostData( postId = "", createdBy = currentUserData().userId, createdAt = Date(), caption = binding.etCaption.text.toString(), category = selectedCategory, image = imageUrl, type = postType, modifiedAt = Date(), userName = currentUserData().userName, profilePicture = currentUserData().profilePicture, userBadge = currentUserData().badge, commentsCount = 0, likesCount = 0, likeVisibility = true, commentVisibility = true ) ) } private fun isPostImageExist() { if (imageLocalUri != null){ viewModel.onUploadPostImage(imageLocalUri!!){ state -> when (state) { is UiState.Loading -> { loadingVisibility(true) } is UiState.Failure -> { loadingVisibility(false) toast(state.error) binding.btPublish.isClickable = true } is UiState.Success -> { loadingVisibility(false) if (postType == "Diary") { addDiaryData(state.data.toString()) } else { addPostData(state.data.toString()) } } } } }else{ if (postType == "Diary") { addDiaryData(null) } else { addPostData(null) } } } private fun currentUserData(): UserData { var user = UserData() viewModel.getSessionData { if (it != null) { user = it } } return user } private fun loadingVisibility(isLoading: Boolean) { if (isLoading) { binding.tvPublish.hide() binding.progressBar.show() if (postType == "Diary") binding.ivLockIcon.hide() } else { if (postType == "Diary") binding.ivLockIcon.show() binding.tvPublish.show() binding.progressBar.hide() } } private fun inputValidation(): Boolean { var isValid = true if (postType == "Diary" && selectedMood == null) { isValid = false Snackbar.make(binding.root, "You haven't chosen any mood yet", Snackbar.LENGTH_SHORT).show() binding.btPublish.isClickable = true } if (binding.etCaption.text.toString().trim().isEmpty()) { isValid = false binding.etCaption.error = "Caption can't be empty!" binding.btPublish.isClickable = true } return isValid } private fun updateUI(type: String) { if (type == "Diary") { binding.clPublicAnonymous.hide() binding.clDiary.show() binding.tvTitleToolbar.text = getString(R.string.title_create_post_diary) binding.ivLockIcon.show() } else { binding.clPublicAnonymous.show() binding.clDiary.hide() binding.ivLockIcon.hide() if (type == "Public") binding.tvTitleToolbar.text = getString(R.string.title_create_post_public) else binding.tvTitleToolbar.text = getString(R.string.title_create_post_anonymous) } } private fun setToolbar() { setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_back_grey) supportActionBar?.setDisplayShowTitleEnabled(false) } }
0
Kotlin
1
0
b55700d33903a5cd992d181ef7f07c35829c1f23
14,678
rangkul_app
MIT License
src/main/kotlin/kotlinx/kover/api/KoverTaskExtension.kt
Kotlin
394,574,917
false
null
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("RedundantVisibilityModifier") package kotlinx.kover.api import org.gradle.api.model.* import org.gradle.api.provider.* import org.gradle.api.tasks.* import java.io.* /** * Extension for Kover plugin that additionally configures test tasks and * runs them with coverage agent to generate coverage execution data. */ open class KoverTaskExtension(objects: ObjectFactory) { /** * Specifies whether instrumentation is disabled for an extended test task. */ @get:Input public var isDisabled: Boolean = false /** * Specifies file path of generated binary file with coverage data. */ @get:OutputFile public val binaryReportFile: Property<File> = objects.property(File::class.java) /** * Specifies class instrumentation inclusion rules. * Only the specified classes may be instrumented, for the remaining classes there will be zero coverage. * Exclusion rules have priority over inclusion ones. * * Inclusion rules are represented as a set of fully-qualified names of the classes being instrumented. * It's possible to use `*` and `?` wildcards. */ @get:Input public var includes: List<String> = emptyList() /** * Specifies class instrumentation exclusion rules. * The specified classes will not be instrumented and there will be zero coverage for them. * Exclusion rules have priority over inclusion ones. * * Exclusion rules are represented as a set of fully-qualified names of the classes being instrumented. * It's possible to use `*` and `?` wildcards. */ @get:Input public var excludes: List<String> = emptyList() }
34
Kotlin
14
520
e1f3fbc4232216bf55b3c43ca0ad193e639afd68
1,788
kotlinx-kover
Apache License 2.0
App/app/src/main/java/com/apps/travel_app/ui/components/FullHeightBottomSheet.kt
robertodavinci
427,414,757
false
null
package com.apps.travel_app.ui.components import android.content.res.Resources import android.util.DisplayMetrics import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.MaterialTheme.colors import androidx.compose.material.rememberSwipeableState import androidx.compose.material.swipeable import androidx.compose.runtime.* import androidx.compose.ui.Alignment.Companion.CenterHorizontally import androidx.compose.ui.Alignment.Companion.TopEnd import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.dp import com.apps.travel_app.ui.theme.cardRadius import com.apps.travel_app.ui.theme.iconLightColor import kotlinx.coroutines.launch import kotlin.math.roundToInt enum class States { EXPANDED, COLLAPSED } private var changed: MutableState<States?> = mutableStateOf(null) fun changeState(state: States) { changed.value = state } @ExperimentalMaterialApi @Composable fun FullHeightBottomSheet( mH: Float = convertPixelsToDp(Resources.getSystem().displayMetrics.heightPixels / 2), MH: Int = 0, button: @Composable (() -> Unit)? = null, background: Color = colors.background, body: @Composable (States) -> Unit ) { changed = remember { mutableStateOf(null) } val swipeableState = rememberSwipeableState(initialValue = States.COLLAPSED) val scrollState = rememberScrollState() val composableScope = rememberCoroutineScope() fun setStatus() { composableScope.launch { swipeableState.animateTo(changed.value!!, tween( durationMillis = 500 ) ) changed.value = null } } if (changed.value != null) { setStatus() } val connection = remember { object : NestedScrollConnection { override fun onPreScroll( available: Offset, source: NestedScrollSource ): Offset { val delta = available.y return if (delta < 0) { swipeableState.performDrag(delta).toOffset() } else { Offset.Zero } } override fun onPostScroll( consumed: Offset, available: Offset, source: NestedScrollSource ): Offset { val delta = available.y return swipeableState.performDrag(delta).toOffset() } override suspend fun onPreFling(available: Velocity): Velocity { return if (available.y < 0 && scrollState.value == 0) { swipeableState.performFling(available.y) available } else { Velocity.Zero } } override suspend fun onPostFling( consumed: Velocity, available: Velocity ): Velocity { swipeableState.performFling(velocity = available.y) return super.onPostFling(consumed, available) } private fun Float.toOffset() = Offset(0f, this) } } val maxHeight = Resources.getSystem().displayMetrics.heightPixels - convertDpToPixel(mH) Box( Modifier .offset { IntOffset( 0, swipeableState.offset.value.roundToInt() ) } .height(convertPixelsToDp(Resources.getSystem().displayMetrics.heightPixels).dp) ) { Column( Modifier .swipeable( state = swipeableState, orientation = Orientation.Vertical, anchors = mapOf( MH.toFloat() to States.EXPANDED, maxHeight.toFloat() to States.COLLAPSED, ) ) .graphicsLayer { shape = RoundedCornerShape( cardRadius ) clip = true shadowElevation = 200f } .background( background ) .fillMaxSize() .nestedScroll(connection) ) { Box(modifier = Modifier .padding(10.dp) .graphicsLayer { shape = RoundedCornerShape(100) clip = true } .background(iconLightColor) .height(7.dp) .width(70.dp) .align(CenterHorizontally) .alpha(0.5f)) Box( Modifier .fillMaxSize() .verticalScroll(scrollState) ) { body(swipeableState.currentValue) } } if (button != null) { Box( modifier = Modifier .fillMaxWidth() .offset( x = (-30).dp, y = (20 + -swipeableState.offset.value / maxHeight * 40).dp ), contentAlignment = TopEnd ) { button() } } } } /** * This method converts device specific pixels to density independent pixels. * * @param px A value in px (pixels) unit. Which we need to convert into db * @param context Context to get resources and device specific display metrics * @return A float value to represent dp equivalent to px value */ fun convertPixelsToDp(px: Int): Float { return px / (Resources.getSystem().displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT) } /** * This method converts dp unit to equivalent pixels, depending on device density. * * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels * @param context Context to get resources and device specific display metrics * @return A float value to represent px equivalent to dp depending on device density */ fun convertDpToPixel(dp: Float): Float { return dp * (Resources.getSystem().displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT) }
0
Kotlin
0
1
bf71efbc93c84f25492acbd0dd96d9d9a15bc0d4
7,116
android-dev-travel-app
MIT License
app/src/main/java/com/msg/gfo_v2/gfo/data/remote/dto/datasource/auth/request/CommentRequest.kt
Project-GFO
564,264,624
false
null
package com.msg.gfo_v2.gfo.data.remote.dto.datasource.auth.request import com.google.gson.annotations.SerializedName data class CommentRequest( @SerializedName("comment") var comment: String )
1
Kotlin
0
0
157dd12cbcbef3755c21c38cd0e1457f90bf12b4
203
GFO-Android
MIT License
generating-gradle-plugin/src/com/hendraanggrian/generating/JsonRSpec.kt
hendraanggrian
105,137,170
false
null
package com.hendraanggrian.generating import org.gradle.api.provider.Property /** Settings for customizing the field generation of json file. */ @RSpecMarker interface JsonRSpec { /** * Determine whether adapter should also write inner json object. * Default is false. */ var recursive: Property<Boolean> /** * Extended property of [recursive] that will also write inner json array. * Default is true. */ var writeArray: Property<Boolean> }
0
Kotlin
0
2
42e048980c1a694d095d82552155417e1bda81f2
491
generating-gradle-plugin
Apache License 2.0
RonChatting/src/main/java/com/ron/chatting/models/RonMessageModel.kt
ronil-gwalani
759,772,759
false
{"Kotlin": 64291}
package com.ron.chatting.models internal data class RonMessageModel( val message: String?=null, val timeStamp: String?=null, val senderId: String?=null, val messageId: String?=null, )
0
Kotlin
0
0
d5ef064e3fc94cb2f30f075d37ea967b92f0d55a
201
Ron-Chatting
MIT License
core/ui_kit/lib/src/main/java/com/shevelev/wizard_camera/core/ui_kit/lib/buttons/PulseImageButton.kt
AlShevelev
262,626,159
false
null
package com.shevelev.wizard_camera.main_activity.view.widgets.pulse_image_button import android.animation.AnimatorSet import android.annotation.SuppressLint import android.content.Context import android.graphics.drawable.VectorDrawable import android.util.AttributeSet import android.widget.ImageView import com.shevelev.wizard_camera.R import com.shevelev.wizard_camera.shared.animation.AnimationUtils @SuppressLint("AppCompatCustomView") class PulseImageButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ImageView(context, attrs, defStyleAttr) { private var animSet: AnimatorSet? = null private val activeIcon: VectorDrawable private val inactiveIcon: VectorDrawable private val minScale = 0.8f private val maxScale = 1f var isActive = false set(value) { field = value setImageDrawable(if(field) activeIcon else inactiveIcon) } private var onClickListener: ((Boolean) -> Unit)? = null init { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.PulseImageButton) activeIcon = typedArray.getDrawable(R.styleable.PulseImageButton_pulse_button_active_icon) as VectorDrawable inactiveIcon = typedArray.getDrawable(R.styleable.PulseImageButton_pulse_button_inactive_icon) as VectorDrawable typedArray.recycle() scaleType = ScaleType.FIT_XY scaleX = maxScale scaleY = maxScale setImageDrawable(inactiveIcon) super.setOnClickListener { processClick() } } fun setOnPulseButtonClickListener(listener: ((Boolean) -> Unit)?) { onClickListener = listener } private fun processClick() { animSet?.cancel() scaleX = maxScale scaleY = maxScale val duration = resources.getInteger(android.R.integer.config_shortAnimTime).toLong() val reduceAnimation = AnimationUtils.getFloatAnimator( duration = duration, from = maxScale, to = minScale, updateListener = { scaleX = it scaleY = it }, completeListener = { isActive = !isActive } ) val increaseAnimation = AnimationUtils.getFloatAnimator( duration = duration, from = minScale, to = maxScale, updateListener = { scaleX = it scaleY = it }, completeListener = { onClickListener?.invoke(isActive) } ) animSet = AnimatorSet() .apply { playSequentially(reduceAnimation, increaseAnimation) start() } } }
1
null
5
53
61adcb56875f38ec92b66a686b9449efef580f74
2,783
WizardCamera
Apache License 2.0
springmvc-automapping/src/main/kotlin/nxcloud/ext/springmvc/automapping/spring/AutoMappingRequestHandlerRegistrar.kt
Sunshow
588,022,200
false
{"Kotlin": 53322}
package nxcloud.ext.springmvc.automapping.spring import io.github.oshai.kotlinlogging.KotlinLogging import nxcloud.ext.springmvc.automapping.context.AutoMappingContext import nxcloud.ext.springmvc.automapping.spi.AutoMappingBeanRequestResolver import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.config.BeanPostProcessor import org.springframework.context.annotation.Lazy import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping class AutoMappingRequestHandlerRegistrar : BeanPostProcessor { private val logger = KotlinLogging.logger {} @Autowired private lateinit var autoMappingContext: AutoMappingContext @Autowired(required = false) private var autoMappingBeanRequestResolvers: List<AutoMappingBeanRequestResolver>? = null @Autowired(required = false) private lateinit var autoMappingRequestParameterTypeBinding: AutoMappingRequestParameterTypeBinding @Lazy @Autowired private lateinit var requestMappingHandlerMapping: RequestMappingHandlerMapping override fun postProcessAfterInitialization(bean: Any, beanName: String): Any { if (!autoMappingContext.isSupported(bean.javaClass)) { return bean } logger.info { "处理自动映射 Bean: $beanName - ${bean.javaClass.canonicalName}" } autoMappingBeanRequestResolvers ?.forEach { if (it.isSupported(bean, beanName)) { it.resolveMapping(bean, beanName) .forEach { registration -> // 逐个注册 requestMappingHandlerMapping.registerMapping( registration.mapping, registration.bean, registration.method ) autoMappingRequestParameterTypeBinding.registerBinding( registration.method, registration.declaringMethod, registration.mapping ) logger.info { "注册自动映射: ${bean.javaClass.canonicalName} - ${registration.mapping}" } } } } return bean } }
0
Kotlin
0
0
9ea4a16961e5598c62a96a45760f7a30dd9b03b8
2,433
nxcloud-springmvc-automapping
Apache License 2.0
src/day15/Code.kt
fcolasuonno
221,697,249
false
null
package day15 import java.io.File fun main() { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } data class Disc(val delay: Int, val positions: Int, var currentPos: Int) { fun positionAt(time: Long) = ((time + delay + currentPos) % positions).toInt() } private val lineStructure = """Disc #(\d+) has (\d+) positions; at time=0, it is at position (\d+).""".toRegex() fun parse(input: List<String>) = input.map { lineStructure.matchEntire(it)?.destructured?.let { val (disc, positions, currentPos) = it.toList() Disc(disc.toInt(), positions.toInt(), currentPos.toInt()) } }.requireNoNulls() fun part1(input: List<Disc>): Any? = generateSequence(0L) { it + 1 }.first { time -> input.all { it.positionAt(time) == 0 } } fun part2(input: List<Disc>) = (input + Disc(input.size + 1, 11, 0)).let { newInput -> generateSequence(0L) { it + 1 }.first { time -> newInput.all { it.positionAt(time) == 0 } } }
0
Kotlin
0
0
73110eb4b40f474e91e53a1569b9a24455984900
1,148
AOC2016
MIT License
app/src/main/java/com/rfb/projetoapitmdb/presentation/view/fragments/UpcomingMoviesFragment.kt
rubensfbr
768,066,787
false
{"Kotlin": 46148}
package com.rfb.projetoapitmdb.presentation.view.fragments import android.os.Bundle import android.view.View import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.rfb.exapitmdb.R import com.rfb.exapitmdb.databinding.FragmentUpcomingMoviesBinding import com.rfb.projetoapitmdb.data.adapter.UpcomingMoviesAdapter import com.rfb.projetoapitmdb.domain.model.UpcomingMovies import com.rfb.projetoapitmdb.presentation.viewmodel.UpcomingMoviesViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class UpcomingMoviesFragment : Fragment(R.layout.fragment_upcoming_movies) { private lateinit var binding: FragmentUpcomingMoviesBinding private val viewModel: UpcomingMoviesViewModel by viewModels() private lateinit var recyclerView: RecyclerView private val adapter = UpcomingMoviesAdapter({ onClick(it) }, { onBottonListener() }) private var page = 1 private var init = 1 override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding = FragmentUpcomingMoviesBinding.bind(view) callRecyclerView() } override fun onStart() { super.onStart() if (init == 1) { getUpcomingMovies() init++ } } override fun onResume() { super.onResume() observe() } private fun onBottonListener() { if (page < 1000) { page++ } getUpcomingMovies(page) } private fun getUpcomingMovies(page: Int = 1) { viewModel.getUpcomingMovies(page) } private fun observe() { viewModel._upcomingMovies.observe(this) { adapter.setList(it) } } private fun callRecyclerView() { recyclerView = binding.recyclerUpcomingMovies recyclerView.layoutManager = LinearLayoutManager(requireContext()) recyclerView.setHasFixedSize(true) recyclerView.adapter = adapter } private fun onClick(it: UpcomingMovies) { val args = bundleOf( "id" to it.id ) findNavController().navigate(R.id.detailsFragment, args = args) } }
0
Kotlin
0
0
20f8c81f634bdf417f669e1119239ef78bad7e89
2,401
ProjetoApiTMDB
Apache License 2.0
MVIPractice/data/src/main/java/com/kimmandoo/data/model/FileResponse.kt
kimmandoo
810,895,614
false
{"Kotlin": 300640}
package com.kimmandoo.data.model import kotlinx.serialization.Serializable @Serializable data class FileResponse( val id: Long, val fileName: String, val createdAt: String, val filePath: String )
0
Kotlin
0
0
9a8ea13862807e5064362abaab34cef720c379cf
214
android-drill
MIT License
app/src/main/java/com/udacity/asteroidradar/data/db/AsteroidEntity.kt
Maniak-pl
328,315,093
false
null
package com.udacity.asteroidradar.data.db import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class AsteroidEntity( @PrimaryKey val id: Long, val codename: String, val closeApproachDate: String, val absoluteMagnitude: Double, val estimatedDiameter: Double, val relativeVelocity: Double, val distanceFromEarth: Double, val isPotentiallyHazardous: Boolean )
0
Kotlin
0
0
20b3375074fd3aa5be12693a8b3477dd4f8751f6
414
AsteroidRadar
Apache License 2.0
app/src/main/java/com/mikescamell/motionlayout/MikezoActivity.kt
mikescamell
170,377,235
false
null
package com.mikescamell.motionlayout import android.os.Bundle import android.util.Log import androidx.annotation.IdRes import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.motion.widget.MotionLayout import androidx.constraintlayout.motion.widget.TransitionAdapter import androidx.core.view.isGone import androidx.core.view.isVisible import kotlinx.android.synthetic.main.mikezo_cards.* class MikezoActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.mikezo_cards) bottomCardButton.setOnClickListener { when (root.currentState) { R.id.fanOut -> { root.setTransition(R.id.fanOut, R.id.topCardOnTop) root.transitionToEnd() collapsedCardCompletedListener(R.id.bottomCardOnTop) midnightPieCheckBox.isVisible = true } R.id.bottomCardOnTop -> { Log.d("Mikezo", "Card 1 already on top") } R.id.middleCardOnTop -> { root.setTransition(R.id.middleCardOnTop, R.id.bottomCardOnTop) root.transitionToEnd() legumeBlueCheckBox.isGone = true midnightPieCheckBox.isVisible = true } R.id.topCardOnTop -> { root.setTransition(R.id.topCardOnTop, R.id.bottomCardOnTop) root.transitionToEnd() hotWaffleCheckBox.isGone = true midnightPieCheckBox.isVisible = true } } } middleCardButton.setOnClickListener { when (root.currentState) { R.id.fanOut -> { root.setTransition(R.id.fanOut, R.id.topCardOnTop) root.transitionToEnd() collapsedCardCompletedListener(R.id.middleCardOnTop) legumeBlueCheckBox.isVisible = true } R.id.bottomCardOnTop -> { root.setTransition(R.id.bottomCardOnTop, R.id.middleCardOnTop) root.transitionToEnd() midnightPieCheckBox.isGone = true legumeBlueCheckBox.isVisible = true } R.id.middleCardOnTop -> { Log.d("Mikezo", "Card 2 already on top") } R.id.topCardOnTop -> { root.setTransition(R.id.topCardOnTop, R.id.middleCardOnTop) root.transitionToEnd() hotWaffleCheckBox.isGone = true legumeBlueCheckBox.isVisible = true } } } topCardButton.setOnClickListener { when (root.currentState) { R.id.fanOut -> { root.setTransition(R.id.fanOut, R.id.topCardOnTop) root.transitionToEnd() hotWaffleCheckBox.isVisible = true } R.id.bottomCardOnTop -> { root.setTransition(R.id.bottomCardOnTop, R.id.topCardOnTop) root.transitionToEnd() midnightPieCheckBox.isGone = true hotWaffleCheckBox.isVisible = true } R.id.middleCardOnTop -> { root.setTransition(R.id.middleCardOnTop, R.id.topCardOnTop) root.transitionToEnd() legumeBlueCheckBox.isGone = true hotWaffleCheckBox.isVisible = true } R.id.topCardOnTop -> { Log.d("Mikezo", "Card 3 already on top") } } } } private fun collapsedCardCompletedListener(@IdRes endStateId: Int) { root.setTransitionListener(object : TransitionAdapter() { override fun onTransitionCompleted(motionLayout: MotionLayout, currentId: Int) { if (currentId == R.id.topCardOnTop) { root.setTransition(R.id.topCardOnTop, endStateId) root.transitionToEnd() } root.setTransitionListener(null) } }) } }
0
null
22
215
703fec696f9304057e2f5b73a79dd3b724a08d66
4,361
Loco-MotionLayout
Apache License 2.0
android/feature/analyze/src/main/java/com/jaino/analyze/result/AnalyzeResultFragment.kt
pknu-wap
615,959,763
false
null
package com.jaino.analyze.result import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import com.jaino.analyze.R import com.jaino.analyze.databinding.FragmentAnalyzeResultBinding class AnalyzeResultFragment : Fragment(){ private var _binding: FragmentAnalyzeResultBinding? = null private val binding get() = requireNotNull(_binding) { "binding object is not initialized" } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = DataBindingUtil.inflate(inflater, R.layout.fragment_analyze_result, container, false) binding.lifecycleOwner = viewLifecycleOwner return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } override fun onDestroy() { _binding = null super.onDestroy() } }
4
Kotlin
2
4
d14a2e8855f93689c921fef534c6181d6bcab257
1,100
2023_1_WAT_BeJuRyu
MIT License
media/src/androidMain/kotlin/DefaultMediaManager.kt
splendo
191,371,940
false
null
/* Copyright 2023 Splendo Consulting B.V. The Netherlands 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.splendo.kaluga.media import android.media.MediaPlayer import android.media.PlaybackParams import android.os.Build import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onSubscription import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import java.io.IOException import kotlin.coroutines.CoroutineContext import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds typealias AndroidMediaPlayer = android.media.MediaPlayer typealias AndroidTrackInfo = android.media.MediaPlayer.TrackInfo /** * Default implementation of [PlayableMedia] * @param source the [MediaSource] on which the media is found * @param mediaPlayer the [android.media.MediaPlayer] playing the media */ actual class DefaultPlayableMedia(override val source: MediaSource, private val mediaPlayer: AndroidMediaPlayer) : PlayableMedia { override val duration: Duration get() = mediaPlayer.duration.milliseconds override val currentPlayTime: Duration get() = mediaPlayer.currentPosition.milliseconds override val tracks get() = mediaPlayer.trackInfo.mapIndexed { index, trackInfo -> trackInfo.asTrackInfo(index) } private val mutex = Mutex() private var videoSizeListener: android.media.MediaPlayer.OnVideoSizeChangedListener? = null private val _resolution = MutableStateFlow(Resolution.ZERO) override val resolution: Flow<Resolution> = _resolution.asSharedFlow().onSubscription { mutex.withLock { if (_resolution.subscriptionCount.value > 0 && videoSizeListener == null) { videoSizeListener = MediaPlayer.OnVideoSizeChangedListener { _, width, height -> _resolution.value = Resolution(width, height) } mediaPlayer.setOnVideoSizeChangedListener(videoSizeListener) } } }.onCompletion { mutex.withLock { if (_resolution.subscriptionCount.value == 0) { mediaPlayer.setOnVideoSizeChangedListener(null) } } } } private fun AndroidTrackInfo.asTrackInfo(identifier: Int): TrackInfo = TrackInfo( identifier, when (trackType) { AndroidTrackInfo.MEDIA_TRACK_TYPE_VIDEO -> TrackInfo.Type.VIDEO AndroidTrackInfo.MEDIA_TRACK_TYPE_AUDIO -> TrackInfo.Type.AUDIO AndroidTrackInfo.MEDIA_TRACK_TYPE_METADATA -> TrackInfo.Type.METADATA AndroidTrackInfo.MEDIA_TRACK_TYPE_SUBTITLE -> TrackInfo.Type.SUBTITLE AndroidTrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT -> TrackInfo.Type.TIMED_TEXT else -> TrackInfo.Type.UNKNOWN }, language, ) /** * Default implementation of [BaseMediaManager] * @param mediaSurfaceProvider a [MediaSurfaceProvider] that will automatically call [renderVideoOnSurface] for the latest [MediaSurface] * @param coroutineContext the [CoroutineContext] on which the media will be managed */ actual class DefaultMediaManager(mediaSurfaceProvider: MediaSurfaceProvider?, coroutineContext: CoroutineContext) : BaseMediaManager(mediaSurfaceProvider, coroutineContext) { /** * Builder for creating a [DefaultMediaManager] */ class Builder : BaseMediaManager.Builder { override fun create(mediaSurfaceProvider: MediaSurfaceProvider?, coroutineContext: CoroutineContext): DefaultMediaManager = DefaultMediaManager( mediaSurfaceProvider, coroutineContext, ) } private val mediaPlayer = AndroidMediaPlayer() private val volume = MutableStateFlow(1.0f) override val currentVolume: Flow<Float> = volume.asSharedFlow() override suspend fun updateVolume(volume: Float) { mediaPlayer.setVolume(volume, volume) this.volume.value = volume } init { mediaPlayer.setOnSeekCompleteListener { handleSeekCompleted(true) } mediaPlayer.setOnCompletionListener { handleCompleted() } mediaPlayer.setOnErrorListener { _, _, extra -> val error = when (extra) { AndroidMediaPlayer.MEDIA_ERROR_IO -> PlaybackError.IO AndroidMediaPlayer.MEDIA_ERROR_MALFORMED -> PlaybackError.MalformedMediaSource AndroidMediaPlayer.MEDIA_ERROR_UNSUPPORTED -> PlaybackError.Unsupported AndroidMediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK -> PlaybackError.Unsupported AndroidMediaPlayer.MEDIA_ERROR_TIMED_OUT -> PlaybackError.TimedOut else -> PlaybackError.Unknown } handleError(error) false } } override fun cleanUp() { mediaPlayer.release() } override fun handleCreatePlayableMedia(source: MediaSource): PlayableMedia? = try { when (source) { is MediaSource.Asset -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mediaPlayer.setDataSource(source.descriptor) } else { mediaPlayer.setDataSource(source.descriptor.fileDescriptor) } is MediaSource.File -> mediaPlayer.setDataSource(source.descriptor) is MediaSource.Url -> mediaPlayer.setDataSource(source.url.toExternalForm()) is MediaSource.Content -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { mediaPlayer.setDataSource(source.context, source.uri, source.headers, source.cookies) } else { mediaPlayer.setDataSource(source.context, source.uri, source.headers) } } DefaultPlayableMedia(source, mediaPlayer) } catch (e: Throwable) { when (e) { is IllegalStateException -> null is IOException -> null is IllegalArgumentException -> null is SecurityException -> null else -> throw e } } override fun initialize(playableMedia: PlayableMedia) { mediaPlayer.setOnPreparedListener { mediaPlayer.setOnPreparedListener(null) handlePrepared(DefaultPlayableMedia(playableMedia.source, it)) } mediaPlayer.prepareAsync() } override suspend fun renderVideoOnSurface(surface: MediaSurface?) { try { mediaPlayer.setDisplay(surface?.holder) } catch (e: IllegalStateException) { // } } override fun play(rate: Float) { try { mediaPlayer.playbackParams = PlaybackParams().apply { speed = rate } if (!mediaPlayer.isPlaying) { mediaPlayer.start() } } catch (e: IllegalStateException) { handleError(PlaybackError.Unknown) } } override fun pause() = try { mediaPlayer.pause() } catch (e: IllegalStateException) { handleError(PlaybackError.Unknown) } override fun stop() = try { mediaPlayer.stop() } catch (e: IllegalStateException) { handleError(PlaybackError.Unknown) } override fun startSeek(duration: Duration) = try { mediaPlayer.seekTo(duration.inWholeMilliseconds.toInt()) } catch (e: IllegalStateException) { handleSeekCompleted(false) } override fun handleReset() { mediaPlayer.reset() } }
87
null
7
315
4094d5625a4cacb851b313d4e96bce6faac1c81f
8,006
kaluga
Apache License 2.0
tonapi-tl/src/dht/db/DhtDbBucket.kt
ton-community
448,983,229
false
null
package org.ton.api.dht.db import kotlinx.serialization.Serializable import org.ton.api.dht.DhtNode import org.ton.api.dht.DhtNodes import org.ton.tl.* @Serializable public data class DhtDbBucket( val nodes: DhtNodes ) : TlObject<DhtDbBucket>, Collection<DhtNode> by nodes { public constructor(nodes: List<DhtNode>) : this(DhtNodes(nodes)) override fun tlCodec(): TlCodec<DhtDbBucket> = Companion public companion object : TlConstructor<DhtDbBucket>( schema = "dht.db.bucket nodes:dht.nodes = dht.db.Bucket" ) { override fun encode(writer: TlWriter, value: DhtDbBucket) { writer.write(DhtNodes, value.nodes) } override fun decode(reader: TlReader): DhtDbBucket { val nodes = reader.read(DhtNodes) return DhtDbBucket(nodes) } } }
21
null
24
80
7eb82e9b04a2e518182ebfc56c165fbfcc916be9
834
ton-kotlin
Apache License 2.0
sharepalette/src/main/java/com/sharepalette/SharePaletteFragment.kt
LisandroDiMeo
498,795,486
false
{"Kotlin": 271603, "Java": 23638}
package com.cureya.cure4mind.settings 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.cureya.cure4mind.R import com.cureya.cure4mind.databinding.OurMissionBinding class Our_Mission:Fragment() { private lateinit var binding: OurMissionBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = OurMissionBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.apply { dashboardBackButton.setOnClickListener { findNavController().navigate(R.id.action_our_Mission_to_informationFragment) } } } }
0
null
3
0
843a0df6d2684c6bde4cdb5d8940e54bb8ae5bb3
993
Cure4Mind
MIT License
purchases/src/main/kotlin/com/revenuecat/purchases/models/Transaction.kt
RevenueCat
127,346,826
false
null
package com.revenuecat.purchases.models import android.os.Parcelable import com.revenuecat.purchases.utils.getDate import kotlinx.parcelize.Parcelize import org.json.JSONObject import java.util.Date @Parcelize data class Transaction( val transactionIdentifier: String, @Deprecated( "Use transactionIdentifier instead", ReplaceWith("transactionIdentifier") ) val revenuecatId: String, val productIdentifier: String, @Deprecated( "Use productIdentifier instead", ReplaceWith("productIdentifier") ) val productId: String, val purchaseDate: Date ) : Parcelable { internal constructor(productId: String, jsonObject: JSONObject) : this( transactionIdentifier = jsonObject.getString("id"), revenuecatId = jsonObject.getString("id"), productIdentifier = productId, productId = productId, purchaseDate = jsonObject.getDate("purchase_date") ) }
30
null
52
253
dad31133777389a224e9a570daec17f5c4c795ca
954
purchases-android
MIT License
skiko/src/jvmMain/kotlin/org/jetbrains/skiko/LibraryLoadException.kt
JetBrains
282,864,178
false
null
package org.jetbrains.skiko import java.lang.RuntimeException class LibraryLoadException(message: String) : RuntimeException(message)
42
Kotlin
43
840
cf67c819f15ffcd8b6ecee3edb29ae2cdce1f2fe
135
skiko
Apache License 2.0
skiko/src/jvmMain/kotlin/org/jetbrains/skiko/LibraryLoadException.kt
JetBrains
282,864,178
false
null
package org.jetbrains.skiko import java.lang.RuntimeException class LibraryLoadException(message: String) : RuntimeException(message)
42
Kotlin
43
840
cf67c819f15ffcd8b6ecee3edb29ae2cdce1f2fe
135
skiko
Apache License 2.0
platform/uicomponents/src/main/java/platform/uicomponents/components/errorview/DefaultErrorView.kt
Alaksion
575,132,918
false
{"Kotlin": 170796}
package platform.uicomponents.components.errorview import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.ArrowBack import androidx.compose.material.icons.rounded.Warning import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewParameter import platform.error.InternalException import platform.uicomponents.MviSampleSizes import platform.uicomponents.components.PreviewContainer import platform.uicomponents.components.spacers.VerticalSpacer import platform.uicomponents.components.spacers.WeightSpacer @OptIn(ExperimentalMaterial3Api::class) @Composable fun DefaultErrorView( error: Throwable, options: DefaultErrorViewOptions, ) { Scaffold( topBar = { options.onBackClick?.let { TopAppBar( navigationIcon = { IconButton(onClick = it) { Icon(imageVector = Icons.Outlined.ArrowBack, contentDescription = null) } }, title = {} ) } } ) { Column( modifier = Modifier .fillMaxSize() .padding(it) ) { WeightSpacer(weight = 1f) Icon( imageVector = Icons.Rounded.Warning, contentDescription = null, modifier = Modifier .size(MviSampleSizes.xxLarge3) .align(Alignment.CenterHorizontally), tint = MaterialTheme.colorScheme.primary ) VerticalSpacer(height = MviSampleSizes.small) Text( text = "An error Occurred", modifier = Modifier.align(Alignment.CenterHorizontally), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.SemiBold ) VerticalSpacer(height = MviSampleSizes.xSmall2) Text( text = when (error) { is InternalException.Generic -> error.text else -> "Looks like something is wrong, try again later" }, modifier = Modifier.align(Alignment.CenterHorizontally), style = MaterialTheme.typography.bodyMedium, ) WeightSpacer(weight = 1f) VerticalSpacer(height = MviSampleSizes.medium) Column( Modifier.fillMaxWidth() ) { options.primaryButton?.let { primaryButton -> Button( onClick = primaryButton.onClick, modifier = Modifier.fillMaxWidth(), enabled = primaryButton.enabled ) { Text(text = primaryButton.title) } } options.secondaryButton?.let { secondaryButton -> OutlinedButton( onClick = secondaryButton.onClick, modifier = Modifier.fillMaxWidth(), enabled = secondaryButton.enabled ) { Text(text = secondaryButton.title) } } } } } } @Suppress("ThrowingExceptionsWithoutMessageOrCause") @Preview(showBackground = true) @Composable private fun Preview( @PreviewParameter(DefaultErrorViewOptionsProvider::class) options: DefaultErrorViewOptions ) { PreviewContainer { DefaultErrorView( error = IllegalArgumentException(), options = options ) } }
1
Kotlin
0
1
9de8ede5950c4a5671f1d135bac95d6ff7c43302
4,554
Photo-Gallery-App
The Unlicense
cartmodule/src/main/java/com/kad/cartmodule/fragment/CartFragment.kt
richaelguitar
144,366,833
false
null
package com.kad.cartmodule.fragment import android.view.View import android.widget.Toast import com.kad.basemodule.BaseLazyLoadFragment import com.kad.cartmodule.R import com.kad.routermodule.util.CoreServiceManager import kotlinx.android.synthetic.main.cart_fragment_layout.* class CartFragment : BaseLazyLoadFragment(){ override fun getLayoutId(): Int { return R.layout.cart_fragment_layout } override fun initView(view: View) { btn_go_goods_detail!!.setOnClickListener{ CoreServiceManager.instance.iGoodsService.showDetail("123456") } } override fun initData() { val count:Int = CoreServiceManager.instance.iCartService.showCartCount() Toast.makeText(activity,"购物车商品数量="+count,Toast.LENGTH_SHORT).show() } override fun getPageArguments() { } }
1
Kotlin
1
2
e0fb69cb3e28ecd9aef6bf0f94c3770da22f477f
840
ComponentApp
Apache License 2.0
src/main/java/me/shadowalzazel/mcodyssey/enchantments/armor/Moonpatch.kt
ShadowAlzazel
511,383,377
false
{"Kotlin": 1044746}
package me.shadowalzazel.mcodyssey.enchantments.armor import me.shadowalzazel.mcodyssey.enchantments.OdysseyEnchantment import net.kyori.adventure.text.Component import net.minecraft.tags.ItemTags import net.minecraft.world.entity.EquipmentSlot import net.minecraft.world.item.enchantment.Enchantment.constantCost import net.minecraft.world.item.enchantment.Enchantment.dynamicCost import org.bukkit.Material import org.bukkit.enchantments.Enchantment import org.bukkit.enchantments.Enchantment.MENDING import org.bukkit.inventory.ItemStack object Moonpatch : OdysseyEnchantment( "moonpatch", "Moonpatch", 1, 1, constantCost(20), dynamicCost(30, 10), 5, ItemTags.DURABILITY_ENCHANTABLE, ItemTags.DURABILITY_ENCHANTABLE, EquipmentSlot.entries.toTypedArray() ) { //override fun getMinCost(level: Int): Int = 20 //override fun getMaxCost(level: Int): Int = getMinCost(level) + 50 override fun checkBukkitConflict(other: Enchantment): Boolean { return when (other) { MENDING -> { true } else -> { false } } } override fun canEnchantItem(item: ItemStack): Boolean { return when (item.type) { Material.ENCHANTED_BOOK, Material.NETHERITE_HELMET, Material.DIAMOND_HELMET, Material.IRON_HELMET, Material.GOLDEN_HELMET, Material.CHAINMAIL_HELMET, Material.LEATHER_HELMET, Material.NETHERITE_CHESTPLATE, Material.DIAMOND_CHESTPLATE, Material.IRON_CHESTPLATE, Material.GOLDEN_CHESTPLATE, Material.CHAINMAIL_CHESTPLATE, Material.LEATHER_CHESTPLATE, Material.NETHERITE_LEGGINGS, Material.DIAMOND_LEGGINGS, Material.IRON_LEGGINGS, Material.GOLDEN_LEGGINGS, Material.CHAINMAIL_LEGGINGS, Material.LEATHER_LEGGINGS, Material.NETHERITE_BOOTS, Material.DIAMOND_BOOTS, Material.IRON_BOOTS, Material.GOLDEN_BOOTS, Material.CHAINMAIL_BOOTS, Material.LEATHER_BOOTS, Material.ELYTRA -> { true } else -> { false } } } override fun getDescriptionToolTip(inputLevel: Int): List<Component> { val amount = inputLevel val text1 = "Regenerates $amount=[level] durability per second" val text2 = "at night when the moon is visible." return listOf( getGrayComponentText(text1), getGrayComponentText(text2), ) } }
0
Kotlin
0
3
797cbcef57f6dd88ae63870b5e95f376b98992f9
2,473
MinecraftOdyssey
MIT License
yaj-rpc-annotation-processor/src/main/kotlin/info/laht/yajrpc/annotationprocessor/Processor.kt
markaren
122,771,040
false
null
package info.laht.yajrpc.annotationprocessor import com.google.auto.service.AutoService import com.squareup.kotlinpoet.* import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import info.laht.yajrpc.RpcMethod import info.laht.yajrpc.net.RpcClient import java.io.File import javax.annotation.processing.* import javax.lang.model.SourceVersion import javax.lang.model.element.Element import javax.lang.model.element.ElementKind import javax.lang.model.element.ExecutableElement import javax.lang.model.element.TypeElement import javax.lang.model.type.TypeKind import javax.tools.Diagnostic import kotlin.reflect.jvm.internal.impl.builtins.jvm.JavaToKotlinClassMap import kotlin.reflect.jvm.internal.impl.name.FqName @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.SOURCE) annotation class GenerateRpcWrapper(val serviceName : String = "") @AutoService(Processor::class) @SupportedSourceVersion(SourceVersion.RELEASE_8) @SupportedAnnotationTypes("info.laht.yajrpc.annotationprocessor.GenerateRpcWrapper") @SupportedOptions(GenerateWrappersProcessor.KAPT_KOTLIN_GENERATED_OPTION_NAME) class GenerateWrappersProcessor : AbstractProcessor() { companion object { const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated" } override fun process(annotations: MutableSet<out TypeElement>, roundEnv: RoundEnvironment): Boolean { val elements = roundEnv.getElementsAnnotatedWith(GenerateRpcWrapper::class.java) val kaptKotlinGeneratedDir = processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME] ?: run { processingEnv.messager.printMessage(Diagnostic.Kind.ERROR, "Can't find the target directory for generated Kotlin files.") return false } if(elements.isNotEmpty()){ val builder = FileSpec.builder("info.laht.yajrpc", "Wrappers") for(element in elements){ val type = TypeSpec.classBuilder("${element.simpleName}Wrapper") type.primaryConstructor(FunSpec.constructorBuilder() .addParameter("client", RpcClient::class) .build()) type.addProperty(PropertySpec.builder("client", RpcClient::class) .initializer("client") .addModifiers(KModifier.PRIVATE) .build() ) val wrapperOptions = element.getAnnotation(GenerateRpcWrapper::class.java) val methods = element.enclosedElements .filter { it.kind == ElementKind.METHOD && it.getAnnotation(RpcMethod::class.java) != null} .map { it as ExecutableElement } for(method in methods){ val methodSpec = FunSpec.builder(method.simpleName.toString()) methodSpec.addTypeVariables(method.typeParameters.map { it.asTypeVariableName() }) methodSpec.returns(method.returnType.asTypeName().javaToKotlinType()) for(parameter in method.parameters){ methodSpec.addParameter(parameter.simpleName.toString(), parameter.toTypeName()) } methodSpec.addStatement("val result = client.write(\"${wrapperOptions.serviceName.nullIfEmpty() ?: element.simpleName}.${method.simpleName}\", RpcParams.listParams(${method.parameters.joinToString( ", " ) { it.simpleName }})).get()") methodSpec.addStatement("if(result.hasError) throw RuntimeException(result.error!!.toString())") if (method.returnType.kind != TypeKind.VOID) { methodSpec.addStatement("return if(result.hasResult) result.getResult()!! else throw RuntimeException(\"No result\")") } type.addFunction(methodSpec.build()) } builder.addType(type.build()) } val outputDirectory = File(kaptKotlinGeneratedDir) builder.build().writeTo(outputDirectory) } return true } } private fun String.nullIfEmpty() = if(this.isEmpty()) null else this //See https://github.com/square/kotlinpoet/issues/236 fun Element.toTypeName(): TypeName = asType().asTypeName().javaToKotlinType() fun TypeName.javaToKotlinType(): TypeName { return if (this is ParameterizedTypeName) { (rawType.javaToKotlinType() as ClassName).parameterizedBy(*typeArguments.map { it.javaToKotlinType() }.toTypedArray()) } else { val className = JavaToKotlinClassMap.INSTANCE.mapJavaToKotlin(FqName(toString())) ?.asSingleFqName()?.asString() return if (className == null) { this } else { ClassName.bestGuess(className) } } }
0
null
7
16
b06ec8256d7987048ec0a7c7221e5b17dd0cd731
4,873
YAJ-RPC
MIT License
core/data/tests/can_generate_generic_struct/output.kt
1Password
540,976,791
false
{"Rust": 295227, "Swift": 71050, "Go": 49378, "Kotlin": 26255, "Scala": 23528, "TypeScript": 10539, "Nix": 1858, "Just": 527}
package com.agilebits.onepassword import kotlinx.serialization.Serializable import kotlinx.serialization.SerialName @Serializable data class GenericStruct<A, B> ( val field_a: A, val field_b: List<B> ) @Serializable data class GenericStructUsingGenericStruct<T> ( val struct_field: GenericStruct<String, T>, val second_struct_field: GenericStruct<T, String>, val third_struct_field: GenericStruct<T, List<T>> ) @Serializable sealed class EnumUsingGenericStruct { @Serializable @SerialName("VariantA") data class VariantA(val content: GenericStruct<String, Float>): EnumUsingGenericStruct() @Serializable @SerialName("VariantB") data class VariantB(val content: GenericStruct<String, Int>): EnumUsingGenericStruct() @Serializable @SerialName("VariantC") data class VariantC(val content: GenericStruct<String, Boolean>): EnumUsingGenericStruct() @Serializable @SerialName("VariantD") data class VariantD(val content: GenericStructUsingGenericStruct<Unit>): EnumUsingGenericStruct() }
65
Rust
95
2,393
da98c89ab769f2931907224672e648daa4a2d9f9
1,004
typeshare
Apache License 2.0
setup/src/main/kotlin/tech/antibytes/gradle/kmock/config/quality/StableApi.kt
bitPogo
455,829,905
false
{"Kotlin": 3506361}
/* * Copyright (c) 2024 Matthias Geisler (bitPogo) / All rights reserved. * * Use of this source code is governed by Apache v2.0 */ package tech.antibytes.gradle.kmock.config.quality import tech.antibytes.gradle.quality.api.StableApiConfiguration object StableApi { val api = StableApiConfiguration( excludeProjects = excludes, ) }
3
Kotlin
2
56
9a94e2842f615b08d4e2942c4987278a3d5c9f43
355
kmock
Apache License 2.0
cli/src/test/kotlin/uk/gov/justice/digital/cli/command/CreateDomainTest.kt
ministryofjustice
620,391,775
false
null
package uk.gov.justice.digital.cli.command import io.mockk.every import io.mockk.mockk import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import uk.gov.justice.digital.cli.DomainBuilder import uk.gov.justice.digital.cli.service.DomainService import uk.gov.justice.digital.cli.service.JsonParsingFailedException import uk.gov.justice.digital.cli.test.DomainJsonResources import java.io.File import java.lang.RuntimeException import java.util.* import kotlin.text.Charsets.UTF_8 class CreateDomainTest { private val mockDomainBuilder: DomainBuilder = mockk() private val mockDomainService: DomainService = mockk() private val underTest = CreateDomain(mockDomainService) @TempDir var tempDir: File? = null @Test fun `create domain should create a new domain given a valid domain definition file`() { val validFilename = "$tempDir/${UUID.randomUUID()}.json" File(validFilename).writeText(DomainJsonResources.validDomain, UTF_8) val domainPath = "/domain/12345" every { mockDomainService.createDomain(any<String>()) } answers { domainPath } val capturedOutput = captureCommandOutput() underTest.parent = mockDomainBuilder underTest.filename = validFilename underTest.run() val expectedOutput = "@|bold,green Domain successfully created with id: $domainPath|@" assertEquals(expectedOutput, capturedOutput.joinToString()) } @Test fun `create domain should display an error given a domain definition that could not be parsed before sending`() { val validFilename = "$tempDir/${UUID.randomUUID()}.json" File(validFilename).writeText(DomainJsonResources.invalidDomain, UTF_8) every { mockDomainService.createDomain(any<String>()) } throws( JsonParsingFailedException( "Unexpected character ('s' (code 115)): was expecting double-quote to start field name on line: 11 at column: 4", RuntimeException("Json parsing failed") )) val capturedOutput = captureCommandOutput() underTest.parent = mockDomainBuilder underTest.filename = validFilename underTest.run() val expectedOutput = """ @|red,bold Error: Could not create new domain|@ @|white,bold Cause: Unexpected character ('s' (code 115)): was expecting double-quote to start field name on line: 11 at column: 4|@ @|blue,bold Possible fixes|@ 1. Read the cause above since it will usually describe the problem with the JSON and what needs to be done to fix it 2. Ensure that your JSON is syntactically valid 3. Ensure that all mandatory fields have been given a value 4. Ensure that the status value is fully capitalised """.trimIndent() assertEquals(expectedOutput, capturedOutput.joinToString()) } @Test fun `create domain should display a file not found error given an invalid file name`() { val invalidFilename = "does-not-exist" val capturedOutput = captureCommandOutput() underTest.parent = mockDomainBuilder underTest.filename = invalidFilename underTest.run() val expectedOutput = """@|red,bold File $invalidFilename not found|@""" assertEquals(expectedOutput, capturedOutput.joinToString()) } private fun captureCommandOutput(): MutableList<String> { val capturedOutput = mutableListOf<String>() every { mockDomainBuilder.print(capture(capturedOutput)) } answers { } return capturedOutput } }
1
null
1
2
11f4737c5b5f16fc80b52c9690874679dd6567ef
3,747
digital-prison-reporting-domain-builder
MIT License
app-data/src/main/java/com/kotlin/android/app/data/entity/search/Cinema.kt
R-Gang-H
538,443,254
false
null
package com.kotlin.android.app.data.entity.search import com.kotlin.android.app.data.ProguardRule import java.io.Serializable /** * 联合搜索/search/unionSearch * 影院 * * Created on 2020/10/15. * * @author o.s */ data class Cinema( val address: String? = null, // 地址 val baiduLatitude: Double? = null, // 百度维度 val baiduLongitude: Double? = null, // 百度经度 val business: String? = null, val cinemaId: Long? = null, // 影院Id val cityId: Long? = null, // 城市Id 取 LocationIdCity val cityName: String? = null, val cover: String? = null, val district: String? = null, val feature: Feature? = null, // 影院特色 val latitude: Double? = null, // google 维度 val longitude: Double? = null, //google 经度 val loveDeep: Long? = null, // 喜爱度 val name: String? = null, // 影院名称 // 二期新增 val distance: Double? = null, // 当前位置到该影院的距离 单位 公里 // 传入longitude和latitude两个参数,而且影院已采集经度、纬度,则显示 // 否则 显示 0.0 val featureInfos: String? = null // 影设备设施 ) : ProguardRule, Serializable
0
Kotlin
0
1
e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28
1,169
Mtime
Apache License 2.0
app/src/main/java/com/murano500k/dogbreeds/viewmodel/ListBreedsViewModel.kt
murano500k
307,665,888
false
null
package com.murano500k.dogbreeds.viewmodel import android.util.Log import androidx.databinding.ObservableBoolean import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.* import com.murano500k.dogbreeds.TAG import com.murano500k.dogbreeds.model.DogBreed import com.murano500k.dogbreeds.repository.MainRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class ListBreedsViewModel @ViewModelInject constructor( private val mainRepository: MainRepository ) : ViewModel() { val isLoading: ObservableBoolean = ObservableBoolean(false) private val _toastLiveData: MutableLiveData<String> = MutableLiveData() init { Log.w(TAG, "init: ", ) viewModelScope.launch(Dispatchers.IO){ Log.w(TAG, "launch: ", ) mainRepository.fetchUpdatedDogBreedsList() } } var listBreedsLiveDataFromDb = mainRepository.getListBreedsLiveData().map { it.distinctBy { item -> item.breed }.sortedBy { dogBreed -> dogBreed.imageUrl } } }
0
Kotlin
0
0
42d73dbc2c291cfe35f424e23e7b71145a7f821d
1,040
DogBreeds
Apache License 2.0
app/src/main/java/com/example/prolificinteractive/digitallibrary/api/LibraryRepositoryProvider.kt
jgsamudio
154,833,432
false
null
package com.example.prolificinteractive.digitallibrary.api class LibraryApiServiceProvider { val apiService = LibraryApiService.create() }
0
Kotlin
0
0
6e52e334b1766f5446a3d7406862e8c336a41ce7
144
DigitalLibrary
MIT License
app/src/main/java/io/sample/smartaccess/data/ble/GattAdvertiseFactory.kt
CoreWillSoft
668,573,101
false
null
package io.sample.smartaccess.data.ble import android.bluetooth.le.AdvertiseData import android.bluetooth.le.AdvertiseSettings interface GattAdvertiseFactory { fun settings(): AdvertiseSettings fun data(): AdvertiseData } internal class GattAdvertiseFactoryImpl : GattAdvertiseFactory { override fun settings(): AdvertiseSettings = AdvertiseSettings.Builder() .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY) .setConnectable(true) .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH) .build() override fun data(): AdvertiseData = AdvertiseData.Builder() .setIncludeDeviceName(true) .addManufacturerData(0x004C, byteArrayOf()) // .addServiceUuid(ParcelUuid(SERVICE_UUID)) .build() }
0
Kotlin
0
0
ebf3259988ccf047ecc9820f4c89c9e5466fcd59
795
smart-access-sample-android
MIT License
example/src/main/java/wtf/qase/datetimepicker/example/MainActivity.kt
Qase
130,849,129
false
null
package wtf.qase.datetimepicker.example import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import wtf.qase.datetimepicker.DateTimePickerDialog import java.text.SimpleDateFormat import java.util.Date import java.util.Locale class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener { _ -> openDateTimePickerDialog() } } private fun openDateTimePickerDialog() { val callback: (date: Date) -> Unit = { newDate -> val sdf = SimpleDateFormat("dd.MM.yyyy - HH:mm", Locale.getDefault()) textView?.text = sdf.format(newDate) } val currentDate = Date() DateTimePickerDialog.show( supportFragmentManager, "fragment_datepicker", callback, currentDate, DateTimePickerDialog.TIME_DATE ) } }
1
Kotlin
1
1
a8cc7443800c9bf6148e2f49493398dc0a3dac2b
1,083
AndroidDateTimePicker
MIT License
winter/src/main/kotlin/io/jentz/winter/TypeKey.kt
andreycooper
215,816,411
true
{"Kotlin": 378817, "Java": 11491, "Ruby": 1282}
package io.jentz.winter import java.lang.reflect.ParameterizedType import java.lang.reflect.Type /** * Interface for all type keys. */ interface TypeKey<in A, out R : Any> { val qualifier: Any? /** * Test if [other] has the same type. * Like [equals] without looking onto the [qualifier]. */ fun typeEquals(other: TypeKey<*, *>): Boolean } class ClassTypeKey<R : Any> @JvmOverloads constructor( val type: Class<R>, override val qualifier: Any? = null ) : TypeKey<Unit, R> { private var _hashCode = 0 override fun typeEquals(other: TypeKey<*, *>): Boolean { if (other === this) return true if (other is GenericClassTypeKey<*>) return Types.equals(type, other.type) if (other !is ClassTypeKey) return false return other.type == type } override fun equals(other: Any?): Boolean { return other is TypeKey<*, *> && other.qualifier == qualifier && typeEquals(other) } override fun hashCode(): Int { if (_hashCode == 0) { _hashCode = Types.hashCode(type, qualifier) } return _hashCode } override fun toString(): String = "ClassTypeKey($type qualifier = $qualifier)" } abstract class GenericClassTypeKey<R : Any> @JvmOverloads constructor( override val qualifier: Any? = null ) : TypeKey<Unit, R> { private var _hashCode = 0 val type: Type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] override fun typeEquals(other: TypeKey<*, *>): Boolean { if (other === this) return true if (other is ClassTypeKey) return Types.equals(other.type, type) if (other is GenericClassTypeKey<*>) return Types.equals(type, other.type) return false } override fun equals(other: Any?): Boolean { return other is TypeKey<*, *> && other.qualifier == qualifier && typeEquals(other) } override fun hashCode(): Int { if (_hashCode == 0) { _hashCode = Types.hashCode(type) _hashCode = 31 * _hashCode + (qualifier?.hashCode() ?: 0) } return _hashCode } override fun toString(): String = "GenericClassTypeKey($type qualifier = $qualifier)" } class CompoundClassTypeKey<A, R : Any> @JvmOverloads constructor( val firstType: Class<A>, val secondType: Class<R>, override val qualifier: Any? = null ) : TypeKey<A, R> { private var _hashCode = 0 override fun typeEquals(other: TypeKey<*, *>): Boolean { if (other === this) return true if (other is GenericCompoundClassTypeKey<*, *>) { return Types.equals(other.argumentType, firstType) && Types.equals(other.returnType, secondType) } if (other !is CompoundClassTypeKey) return false return other.firstType == firstType && other.secondType == secondType } override fun equals(other: Any?): Boolean { return other is TypeKey<*, *> && other.qualifier == qualifier && typeEquals(other) } override fun hashCode(): Int { if (_hashCode == 0) { _hashCode = Types.hashCode(firstType, secondType, qualifier) } return _hashCode } override fun toString(): String = "CompoundClassTypeKey($firstType $secondType qualifier = $qualifier)" } abstract class GenericCompoundClassTypeKey<A, R : Any> @JvmOverloads constructor( override val qualifier: Any? = null ) : TypeKey<A, R> { private var _hashCode = 0 val argumentType: Type = (javaClass.genericSuperclass as ParameterizedType) .actualTypeArguments[0] val returnType: Type = (javaClass.genericSuperclass as ParameterizedType) .actualTypeArguments[1] override fun typeEquals(other: TypeKey<*, *>): Boolean { if (other === this) return true if (other is CompoundClassTypeKey) { return Types.equals(other.firstType, argumentType) && Types.equals(other.secondType, returnType) } if (other !is GenericCompoundClassTypeKey<*, *>) return false return Types.equals(argumentType, other.argumentType) && Types.equals(returnType, other.returnType) } override fun equals(other: Any?): Boolean { return other is TypeKey<*, *> && other.qualifier == qualifier && typeEquals(other) } override fun hashCode(): Int { if (_hashCode == 0) { _hashCode = Types.hashCode(argumentType) _hashCode = 31 * _hashCode + Types.hashCode(returnType) _hashCode = 31 * _hashCode + (qualifier?.hashCode() ?: 0) } return _hashCode } override fun toString(): String = "GenericCompoundClassTypeKey($argumentType $returnType qualifier = $qualifier)" }
0
null
0
0
4fd5ca4e9547198860719ce2a23f47d8141335f4
4,787
winter
Apache License 2.0
feature/listing/src/main/java/com/utsman/listing/di/module.kt
irmansyah
317,537,024
true
{"Kotlin": 124069}
/* * Created by <NAME> on 28/11/20 3:54 PM * Copyright (c) 2020 . All rights reserved. */ package com.utsman.listing.di import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val listPagingUseCase = module { single { providePagingUseCase(get(), get()) } single { provideInstalledAppUseCase(get()) } } val listInstalledViewModel = module { viewModel { providePagingViewModel(get()) } viewModel { provideInstalledAppViewModel(get()) } viewModel { provideSearchPagingViewModel(get()) } }
0
null
0
0
6e3ed614f5fcfb81a0c879e5aa96e4e4d2a63e68
594
store-apps-mvvm-clean-architecture
Apache License 2.0
requestly-android-okhttp/src/main/kotlin/io/requestly/android/okhttp/internal/data/har/log/entry/cache/SecondaryRequest.kt
requestly
473,092,599
false
null
package io.requestly.android.okhttp.internal.data.har.log.entry.cache import com.google.gson.annotations.SerializedName // https://github.com/ahmadnassri/har-spec/blob/master/versions/1.2.md#beforerequest--afterrequest // http://www.softwareishard.com/blog/har-12-spec/#cache internal data class SecondaryRequest( @SerializedName("expires") val expires: String? = null, @SerializedName("lastAccess") val lastAccess: String, @SerializedName("eTag") val eTag: String, @SerializedName("hitCount") val hitCount: Int, @SerializedName("comment") val comment: String? = null )
7
null
346
70
319e8a96c2e49bc75bed0ce79a8ff51730ff0f96
592
requestly-android-sdk
Apache License 2.0
backend/src/main/kotlin/com/myproject/backend/jpa/Account.kt
nikita03565
376,825,314
false
{"JavaScript": 58829, "Kotlin": 46101, "HTML": 1437, "CSS": 1005}
package com.myproject.backend.jpa import com.fasterxml.jackson.annotation.JsonIgnore import javax.persistence.* @Entity @Table(name = "account") data class Account ( @Id @GeneratedValue(strategy = GenerationType.AUTO) val id: Long? = null, @Column(name = "nickname") var nickname: String, @Column(name = "routing_number") var routingNumber: String, @Column(name = "account_number") var accountNumber: String, @Column(name = "amount") var amount: Float? = null, @Column(name = "received_amount") var received_amount: Float = 0f, @Column(name = "allocation_type") var allocationType: String, @Column(name = "priority") var priority: Int, @Column(name = "employee_id") val employeeId: Long, // @JsonIgnore Moved to separate endpoint // @ManyToOne // @JoinColumn(name="employee_id", nullable=false, insertable = false, updatable = false) // val employee: Employee )
0
JavaScript
0
0
c7b1c46dca45f6fe0f211b13124a31a2d94d1ff4
961
kotlin-react
Apache License 2.0
app/src/main/java/com/github/sg4yk/audioplayer/utils/MediaHunter.kt
SG4YK
263,589,223
false
null
package com.github.sg4yk.audioplayer.utils import android.content.ContentUris import android.content.ContentValues import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Build import android.provider.MediaStore import android.support.v4.media.MediaMetadataCompat import android.util.Log import android.util.Size import androidx.annotation.RequiresApi import androidx.annotation.WorkerThread import androidx.core.database.getIntOrNull import androidx.core.database.getLongOrNull import androidx.core.database.getStringOrNull import com.github.sg4yk.audioplayer.media.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.withContext @WorkerThread object MediaHunter { const val VOLUME_EXTERNAL = "external" const val ALBUM_NOT_EXIST = -1L val ALBUM_ART_ROOT = Uri.parse("content://media/external/audio/albumart") private val cachedIdMapping: MutableMap<Long, Long> = mutableMapOf() private val audioProjection = arrayOf( MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.TRACK, MediaStore.Audio.Media.YEAR, MediaStore.Audio.Media.DURATION ) private val albumProjection = arrayOf( MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ARTIST, MediaStore.Audio.Albums.FIRST_YEAR, MediaStore.Audio.Albums.LAST_YEAR, MediaStore.Audio.Albums.NUMBER_OF_SONGS ) private val artistAlbumProjection = arrayOf( MediaStore.Audio.Artists.Albums.ALBUM_ID, MediaStore.Audio.Artists.Albums.ALBUM, MediaStore.Audio.Artists.Albums.ARTIST, MediaStore.Audio.Artists.Albums.FIRST_YEAR, MediaStore.Audio.Artists.Albums.LAST_YEAR, MediaStore.Audio.Artists.Albums.NUMBER_OF_SONGS ) private val playlistProjection = arrayOf( MediaStore.Audio.Playlists._ID, MediaStore.Audio.Playlists.NAME, MediaStore.Audio.Playlists.DATE_ADDED, MediaStore.Audio.Playlists.DATE_MODIFIED ) private val playlistAudioProjection = arrayOf( MediaStore.Audio.Playlists.Members.AUDIO_ID, MediaStore.Audio.Playlists.Members.TITLE, MediaStore.Audio.Playlists.Members.ARTIST, MediaStore.Audio.Playlists.Members.ARTIST_ID, MediaStore.Audio.Playlists.Members.ALBUM, MediaStore.Audio.Playlists.Members.ALBUM_ID, MediaStore.Audio.Playlists.Members.TRACK, MediaStore.Audio.Playlists.Members.YEAR, MediaStore.Audio.Playlists.Members.DURATION, MediaStore.Audio.Playlists.Members._ID, MediaStore.Audio.Playlists.Members.PLAY_ORDER ) private val metadataProjection = arrayOf( MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID ) suspend fun getAllAudio(ctx: Context): MutableList<Audio> { return queryAudio(ctx, sortOrder = "${MediaStore.Audio.Media.DATE_ADDED} DESC") } suspend fun getAllMetadata(ctx: Context): List<MediaMetadataCompat> { val metadata = queryMetadata(ctx, sortOrder = "${MediaStore.Audio.Media.DATE_ADDED} DESC") return metadata } fun getMetadataByAlbumId(ctx: Context, albumId: String): MutableList<MediaMetadataCompat> { // val metadata = queryMetadata(ctx, sortOrder = "${MediaStore.Audio.Media.DATE_ADDED} DESC") return queryMetadata( ctx, selection = "${MediaStore.Audio.Media.ALBUM_ID} = ?", args = arrayOf(albumId), sortOrder = MediaStore.Audio.Media.TRACK ) } suspend fun getAudioByAlbumId(ctx: Context, albumId: String): MutableList<Audio> { return queryAudio( ctx, selection = "${MediaStore.Audio.Media.ALBUM_ID} = ?", args = arrayOf(albumId), sortOrder = MediaStore.Audio.Media.TRACK ) } suspend fun getAllAlbums(ctx: Context): MutableList<Album> { return queryAlbum(ctx) } suspend fun getAlbumIdFromAudioId(ctx: Context, mediaId: String, noCache: Boolean = false): Long { return getAlbumIdFromAudioId(ctx, mediaId.toLong()) } suspend fun getAlbumIdFromAudioId(ctx: Context, audioId: Long, noCache: Boolean = false): Long { if (!noCache) { try { // album id is cached val audioId = cachedIdMapping.getValue(audioId) return audioId } catch (e: Exception) { Log.w("MediaHunter", e.message) } } var albumId = ALBUM_NOT_EXIST // album id not cached ctx.contentResolver.query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Audio.Media.ALBUM_ID), "${MediaStore.Audio.Media._ID} = ?", arrayOf(audioId.toString()), null )?.use { cursor -> val albumIdColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID) if (cursor.moveToNext()) { albumId = cursor.getLongOrNull(albumIdColumn) ?: ALBUM_NOT_EXIST } } return albumId } @RequiresApi(Build.VERSION_CODES.Q) fun getAlbumArt(ctx: Context, audioId: String, size: Int): Bitmap? { val uri = ContentUris.withAppendedId( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, audioId.toLong() ) return ctx.contentResolver.loadThumbnail(uri, Size(size, size), null) } @RequiresApi(Build.VERSION_CODES.Q) suspend fun getThumbnail(ctx: Context, uri: String, size: Int): Bitmap? { return withContext(Dispatchers.IO) { ctx.contentResolver.loadThumbnail(Uri.parse(uri), Size(size, size), null) } } suspend fun getThumbnail(ctx: Context, uri: Uri, size: Int): Bitmap? { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { withContext(Dispatchers.IO + SupervisorJob()) { ctx.contentResolver.loadThumbnail(uri, Size(size, size), null) } } else { withContext(Dispatchers.IO + SupervisorJob()) { var albumArt: Bitmap? = null val audioId = uri.lastPathSegment val albumId = getAlbumIdFromAudioId(ctx, audioId!!) if (albumId != null) { albumArt = getAlbumArtFromAlbumId(ctx, albumId.toString()) } albumArt } } } suspend fun getAlbumArtFromAlbumId(ctx: Context, albumId: String): Bitmap? { var albumArt: Bitmap? = null ctx.contentResolver.query( MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Audio.Albums.ALBUM_ART), "${MediaStore.Audio.Albums._ID} =?", arrayOf(albumId), null )?.use { cursor -> val albumArtColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ART) if (cursor.moveToNext()) { val albumArtPath = cursor.getString(albumArtColumn) if (albumArt != null || albumArtPath != "") { try { albumArt = BitmapFactory.decodeFile(albumArtPath) } catch (e: Exception) { Log.e("MediaHunter", e.message) } } } } return albumArt } suspend fun getArtUriFromAlbumId(albumId: Long): Uri { return ContentUris.withAppendedId(ALBUM_ART_ROOT, albumId) } val artistProjection = arrayOf( MediaStore.Audio.Artists._ID, MediaStore.Audio.Artists.ARTIST ) suspend fun getAllArtists(ctx: Context): MutableList<Artist> { return queryArtist(ctx) } suspend fun getAlbumsByArtistId(ctx: Context, artistId: Long): MutableList<Album> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { return queryAlbum( ctx, uri = MediaStore.Audio.Artists.Albums.getContentUri(VOLUME_EXTERNAL, artistId), projection = artistAlbumProjection ) } else { return queryAlbum( ctx, selection = "${MediaStore.Audio.Albums.ARTIST_ID} = ?", args = arrayOf(artistId.toString()) ) } } suspend fun getAllPlaylists(ctx: Context): MutableList<Playlist> { return queryPlaylist(ctx, sortOrder = MediaStore.Audio.Playlists.DEFAULT_SORT_ORDER) } suspend fun createPlaylist(ctx: Context, name: String): Uri? { val resolver = ctx.contentResolver val playListDetail = ContentValues().apply { put(MediaStore.Audio.Playlists.NAME, name) put(MediaStore.Audio.Playlists.DATE_ADDED, System.currentTimeMillis()) put(MediaStore.Audio.Playlists.DATE_MODIFIED, System.currentTimeMillis()) } return resolver.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, playListDetail) } suspend fun deletePlaylist(ctx: Context, playlistId: String): Int { val resolver = ctx.contentResolver return resolver.delete( MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, "${MediaStore.Audio.Playlists._ID} = ?", arrayOf(playlistId) ) } suspend fun renamePlaylist(ctx: Context, playlistId: String, name: String): Int { val resolver = ctx.contentResolver val contentValues = ContentValues().apply { put(MediaStore.Audio.Playlists.NAME, name) } return resolver.update( MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, contentValues, "${MediaStore.Audio.Playlists._ID} = ?", arrayOf(playlistId) ) } suspend fun getMetadataByPlayListId(ctx: Context, playlistId: String): MutableList<MediaMetadataCompat> { val uri = MediaStore.Audio.Playlists.Members.getContentUri(VOLUME_EXTERNAL, playlistId.toLong()) val result = queryMetadata( ctx, uri = uri, projection = playlistAudioProjection, sortOrder = MediaStore.Audio.Playlists.Members.PLAY_ORDER ) return result } suspend fun getAudioByPlayListId(ctx: Context, playlistId: Long): MutableList<Audio> { val uri = MediaStore.Audio.Playlists.Members.getContentUri(VOLUME_EXTERNAL, playlistId) return queryAudio( ctx, uri = uri, projection = playlistAudioProjection, sortOrder = MediaStore.Audio.Playlists.Members.PLAY_ORDER ) } suspend fun addToPlaylist(ctx: Context, playlistId: Long, audioList: List<Audio>): Int { var res = 0 audioList.forEach { res += if (addToPlaylist(ctx, playlistId, it)) 1 else 0 } return res } suspend fun addToPlaylist(ctx: Context, playlistId: Long, audio: Audio): Boolean { val resolver = ctx.contentResolver val uri = MediaStore.Audio.Playlists.Members.getContentUri(VOLUME_EXTERNAL, playlistId) val audioDetail = ContentValues().apply { put(MediaStore.Audio.Playlists.Members.AUDIO_ID, audio.id) put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, 1) } try { val result = resolver.insert(uri, audioDetail) return result != null } catch (e: Exception) { Log.w("MediaHunter", e) return false } } suspend fun removeFromPlaylist(ctx: Context, playlistId: Long, id: Long): Int { val resolver = ctx.contentResolver val uri = MediaStore.Audio.Playlists.Members.getContentUri(VOLUME_EXTERNAL, playlistId) return resolver.delete( uri, "${MediaStore.Audio.Playlists.Members._ID} = ?", arrayOf(id.toString()) ) } private fun queryMetadata( ctx: Context, uri: Uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection: Array<String> = audioProjection, selection: String? = null, args: Array<String>? = null, sortOrder: String? = null ): MutableList<MediaMetadataCompat> { val metadataList = mutableListOf<MediaMetadataCompat>() ctx.contentResolver.query( uri, projection, selection, args, sortOrder )?.use { cursor -> val idColumn = cursor.getColumnIndexOrThrow(projection[0]) val titleColumn = cursor.getColumnIndexOrThrow(projection[1]) val artistColumn = cursor.getColumnIndexOrThrow(projection[2]) val albumColumn = cursor.getColumnIndexOrThrow(projection[4]) val trackColumn = cursor.getColumnIndexOrThrow(projection[6]) val yearColumn = cursor.getColumnIndexOrThrow(projection[7]) val durationColumn = cursor.getColumnIndexOrThrow(projection[8]) var id: Long? = null var title: String? = null var artist: String? = null var album: String? = null var track: Int? = null var year: Int? = null var audioUri: Uri? = null var duration: Int? = null while (cursor.moveToNext()) { id = cursor.getLong(idColumn) title = cursor.getStringOrNull(titleColumn) artist = cursor.getStringOrNull(artistColumn) album = cursor.getStringOrNull(albumColumn) track = cursor.getIntOrNull(trackColumn) year = cursor.getIntOrNull(yearColumn) duration = cursor.getIntOrNull(durationColumn) audioUri = id.let { ContentUris.withAppendedId( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, it ) } val metadata = MediaMetadataCompat.Builder().apply { putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, id.toString()) putString(MediaMetadataCompat.METADATA_KEY_TITLE, title) putString(MediaMetadataCompat.METADATA_KEY_ARTIST, artist) putString(MediaMetadataCompat.METADATA_KEY_ALBUM, album) if (track != null) { putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, track.toLong()) } track?.let { putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, it.toLong()) } year?.let { putLong(MediaMetadataCompat.METADATA_KEY_YEAR, it.toLong()) } putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, audioUri.toString()) putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION, "$artist - $album") putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration!!.toLong()) }.build() metadataList += metadata } } return metadataList } private fun queryAudio( ctx: Context, uri: Uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection: Array<String> = audioProjection, selection: String? = null, args: Array<String>? = null, sortOrder: String? = null ): MutableList<Audio> { val audioList = mutableListOf<Audio>() ctx.contentResolver.query( uri, projection, selection, args, sortOrder )?.use { cursor -> val idColumn = cursor.getColumnIndexOrThrow(projection[0]) val titleColumn = cursor.getColumnIndexOrThrow(projection[1]) val artistColumn = cursor.getColumnIndexOrThrow(projection[2]) val artistIdColumn = cursor.getColumnIndexOrThrow(projection[3]) val albumColumn = cursor.getColumnIndexOrThrow(projection[4]) val albumIdColumn = cursor.getColumnIndexOrThrow(projection[5]) val trackColumn = cursor.getColumnIndexOrThrow(projection[6]) val yearColumn = cursor.getColumnIndexOrThrow(projection[7]) val durationColumn = cursor.getColumnIndexOrThrow(projection[8]) var id: Long = 0L var title: String? = null var artist: String? = null var artistId: Long? = null var album: String? = null var albumId: Long? = null var track: Int? = null var year: Int? = null var duration: Long? = null var contentUri: Uri = Uri.EMPTY cachedIdMapping[id] = albumId ?: ALBUM_NOT_EXIST while (cursor.moveToNext()) { id = cursor.getLong(idColumn) title = cursor.getStringOrNull(titleColumn) artist = cursor.getStringOrNull(artistColumn) artistId = cursor.getLongOrNull(artistIdColumn) album = cursor.getStringOrNull(albumColumn) albumId = cursor.getLongOrNull(albumIdColumn) track = cursor.getIntOrNull(trackColumn) year = cursor.getIntOrNull(yearColumn) duration = cursor.getLongOrNull(durationColumn) contentUri = ContentUris.withAppendedId( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id ) try { cachedIdMapping.put(id, albumId ?: ALBUM_NOT_EXIST) } catch (e: Exception) { Log.w("MediaHunter", e.message) } audioList.add(Audio(contentUri, id, title, artist, artistId, album, albumId, track, year, duration)) } title = null artist = null album = null albumId = null year = null duration = null } return audioList } private fun queryAlbum( ctx: Context, uri: Uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, projection: Array<String> = albumProjection, selection: String? = null, args: Array<String>? = null, sortOrder: String? = MediaStore.Audio.Albums.DEFAULT_SORT_ORDER ): MutableList<Album> { val albumList = mutableListOf<Album>() ctx.contentResolver.query( uri, projection, selection, args, sortOrder )?.use { cursor -> val idColumn = cursor.getColumnIndexOrThrow(projection[0]) val albumColumn = cursor.getColumnIndexOrThrow(projection[1]) val artistColumn = cursor.getColumnIndexOrThrow(projection[2]) val firstYearColumn = cursor.getColumnIndexOrThrow(projection[3]) val lastYearColumn = cursor.getColumnIndexOrThrow(projection[4]) val songsColumn = cursor.getColumnIndexOrThrow(projection[5]) while (cursor.moveToNext()) { val id = idColumn.let { cursor.getLong(it) } val album = albumColumn.let { cursor.getStringOrNull(it) } val artist = artistColumn.let { cursor.getStringOrNull(it) } val firstYear = firstYearColumn.let { cursor.getIntOrNull(it) } val lastYear = lastYearColumn.let { cursor.getIntOrNull(it) } val songs = songsColumn.let { cursor.getIntOrNull(it) } val contentUri = ContentUris.withAppendedId( MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, id ) albumList += Album(contentUri, id, album, artist, firstYear, lastYear, songs) } } return albumList } private fun queryArtist( ctx: Context, uri: Uri = MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, projection: Array<String> = artistProjection, selection: String? = null, args: Array<String>? = null, sortOrder: String? = MediaStore.Audio.Artists.DEFAULT_SORT_ORDER ): MutableList<Artist> { val artistList = mutableListOf<Artist>() ctx.contentResolver.query( uri, projection, selection, args, sortOrder )?.use { cursor -> val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists._ID) val artistColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST) var id: Long? = null var artist: String? = null while (cursor.moveToNext()) { id = idColumn.let { cursor.getLong(it) } artist = artistColumn.let { cursor.getStringOrNull(it) } val contentUri = ContentUris.withAppendedId( MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, id ) artistList += Artist(contentUri, id, artist) } } return artistList } private fun queryPlaylist( ctx: Context, uri: Uri = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection: Array<String> = playlistProjection, selection: String? = null, args: Array<String>? = null, sortOrder: String? = MediaStore.Audio.Playlists.DEFAULT_SORT_ORDER ): MutableList<Playlist> { val playlistList = mutableListOf<Playlist>() ctx.contentResolver.query( uri, projection, selection, args, sortOrder )?.use { cursor -> val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists._ID) val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.NAME) val dateAddedColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.DATE_ADDED) val dateModifiedColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.DATE_MODIFIED) while (cursor.moveToNext()) { val id = cursor.getLong(idColumn) val name = cursor.getStringOrNull(nameColumn) val dateAdded = cursor.getLongOrNull(dateAddedColumn) val dateModified = cursor.getLongOrNull(dateModifiedColumn) val contentUri = ContentUris.withAppendedId( MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, id ) playlistList += Playlist(contentUri, id, name, dateAdded, dateModified) } } return playlistList } // for playlist ui only suspend fun getPlaylistAudioByPlayListId(ctx: Context, playlistId: Long): MutableList<PlaylistAudio> { val uri = MediaStore.Audio.Playlists.Members.getContentUri(VOLUME_EXTERNAL, playlistId) val audioList = mutableListOf<PlaylistAudio>() ctx.contentResolver.query( uri, playlistAudioProjection, null, null, MediaStore.Audio.Playlists.Members.PLAY_ORDER )?.use { cursor -> val audioIdColumn = cursor.getColumnIndexOrThrow(playlistAudioProjection[0]) val titleColumn = cursor.getColumnIndexOrThrow(playlistAudioProjection[1]) val artistColumn = cursor.getColumnIndexOrThrow(playlistAudioProjection[2]) val artistIdColumn = cursor.getColumnIndexOrThrow(playlistAudioProjection[3]) val albumColumn = cursor.getColumnIndexOrThrow(playlistAudioProjection[4]) val albumIdColumn = cursor.getColumnIndexOrThrow(playlistAudioProjection[5]) val trackColumn = cursor.getColumnIndexOrThrow(playlistAudioProjection[6]) val yearColumn = cursor.getColumnIndexOrThrow(playlistAudioProjection[7]) val durationColumn = cursor.getColumnIndexOrThrow(playlistAudioProjection[8]) val idColumn = cursor.getColumnIndexOrThrow(playlistAudioProjection[9]) val playOrderColumn = cursor.getColumnIndexOrThrow(playlistAudioProjection[10]) var audioId: Long = 0L var title: String? = null var artist: String? = null var artistId: Long? = null var album: String? = null var albumId: Long? = null var track: Int? = null var year: Int? = null var duration: Long? = null var contentUri: Uri = Uri.EMPTY var id: Long = 0L var playOrder: Int? = null while (cursor.moveToNext()) { audioId = cursor.getLong(audioIdColumn) title = cursor.getStringOrNull(titleColumn) artist = cursor.getStringOrNull(artistColumn) artistId = cursor.getLongOrNull(artistIdColumn) album = cursor.getStringOrNull(albumColumn) albumId = cursor.getLongOrNull(albumIdColumn) track = cursor.getIntOrNull(trackColumn) year = cursor.getIntOrNull(yearColumn) duration = cursor.getLongOrNull(durationColumn) id = cursor.getLong(idColumn) playOrder = cursor.getIntOrNull(playOrderColumn) contentUri = ContentUris.withAppendedId( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, audioId ) try { cachedIdMapping.put(audioId, albumId ?: ALBUM_NOT_EXIST) } catch (e: Exception) { Log.w("MediaHunter", e.message) } audioList.add( PlaylistAudio( Audio( contentUri, audioId, title, artist, artistId, album, albumId, track, year, duration ), id, playOrder ) ) } title = null artist = null album = null albumId = null year = null duration = null } return audioList } }
0
Kotlin
0
0
9c3e9a45bfd9b65c5c67b582d8b23344833e2d7d
26,580
AudioPlayer
Apache License 2.0
src/main/kotlin/com/deflatedpickle/undulation/functions/extensions/Window.kt
DeflatedPickle
286,105,109
false
null
package com.deflatedpickle.undulation.functions.extensions import java.awt.GraphicsEnvironment import java.awt.Window // https://stackoverflow.com/a/33799118 fun Window.getScreenDevice() = GraphicsEnvironment .getLocalGraphicsEnvironment() .screenDevices .firstOrNull { it.defaultConfiguration.bounds.intersects(bounds) }
0
Kotlin
0
0
5d70e04922775b05094ce9a586680f2e3c6e033a
335
undulation
MIT License
app/src/main/java/com/pkgname/appname/utils/SharedWebServices.kt
Ammar-Ishfaq
503,248,832
false
{"Kotlin": 15808}
package com.pkgname.appname.utils import com.pkgname.appname.backend.ApiService import com.pkgname.appname.models.requestModels.login.LoginModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class SharedWebServices( private val apiServices: ApiService // private val app: App ) { private val dispatcher = Dispatchers.IO //Login User suspend fun loginUser( email: String, password: String ) = withContext(dispatcher) { val body = LoginModel(email, password) safeApiCall { Result.success(apiServices.loginUser(body)) } } suspend fun logoutUser( user_id: String ) = withContext(dispatcher) { safeApiCall { Result.success(apiServices.logoutUser(user_id)) } } }
0
Kotlin
0
0
8f8aba52b18731609bfbc738a5a9c32f06de4c0e
779
HiltTemplate
MIT License
smithy-swift-codegen/src/main/kotlin/software/amazon/smithy/swift/codegen/ServiceGenerator.kt
awslabs
242,852,561
false
null
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package software.amazon.smithy.swift.codegen import software.amazon.smithy.codegen.core.CodegenException import software.amazon.smithy.codegen.core.Symbol import software.amazon.smithy.codegen.core.SymbolProvider import software.amazon.smithy.model.Model import software.amazon.smithy.model.knowledge.OperationIndex import software.amazon.smithy.model.knowledge.TopDownIndex import software.amazon.smithy.model.shapes.OperationShape import software.amazon.smithy.model.shapes.StructureShape import software.amazon.smithy.model.traits.StreamingTrait import software.amazon.smithy.swift.codegen.integration.DefaultServiceConfig import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.SectionId import software.amazon.smithy.swift.codegen.model.toLowerCamelCase /* * Generates a Swift protocol for the service */ class ServiceGenerator( settings: SwiftSettings, private val model: Model, private val symbolProvider: SymbolProvider, private val writer: SwiftWriter, private val delegator: SwiftDelegator, private val protocolGenerator: ProtocolGenerator? = null, private val protocolGenerationContext: ProtocolGenerator.GenerationContext? ) { private var service = settings.getService(model) private val serviceSymbol: Symbol by lazy { symbolProvider.toSymbol(service) } private val serviceConfig: DefaultServiceConfig by lazy { DefaultServiceConfig(writer, serviceSymbol.name) } private val rootNamespace = settings.moduleName companion object { /** * Renders the definition of operation */ fun renderOperationDefinition( model: Model, symbolProvider: SymbolProvider, writer: SwiftWriter, opIndex: OperationIndex, op: OperationShape, insideProtocol: Boolean = false ) { val operationName = op.toLowerCamelCase() // Theoretically this shouldn't happen since we insert empty input/outputs for operations that don't have one or the other to allow for sdk evolution if (!op.input.isPresent || !op.output.isPresent) throw CodegenException("model should have been preprocessed to ensure operations always have an input or output shape: $op.id") val inputShape = opIndex.getInput(op).get() val inputShapeName = symbolProvider.toSymbol(inputShape).name val inputParam = "input: $inputShapeName" val outputShape = opIndex.getOutput(op).get() val outputShapeName = symbolProvider.toSymbol(outputShape).name if (op.id.name == "createBucket") { print("we are here") } writer.writeShapeDocs(op) writer.writeAvailableAttribute(model, op) val accessSpecifier = if (insideProtocol) "" else "public " writer.write( "${accessSpecifier}func \$L(\$L) async throws -> \$L", operationName, inputParam, outputShapeName ) } } fun render() { // add imports writer.addImport(serviceSymbol) // generate protocol renderSwiftProtocol() } /** * Generates an appropriate Swift Protocol for a Smithy Service shape. * * For example, given the following Smithy model: * * ``` * namespace smithy.example * * use aws.protocols#awsJson1_1 * * @awsJson1_1 * service Example { * version: "1.0.0", * operations: [GetFoo] * } * * operation GetFoo { * input: GetFooInput, * output: GetFooOutput, * errors: [GetFooError] * } * * ``` * We will generate the following: * ``` * public protocol ExampleServiceProtocol { * func getFoo(input: GetFooInput) async throws -> GetFooResponse * } * ``` */ private fun renderSwiftProtocol() { val topDownIndex = TopDownIndex.of(model) val operations = topDownIndex.getContainedOperations(service) val operationsIndex = OperationIndex.of(model) writer.writeShapeDocs(service) writer.writeAvailableAttribute(model, service) writer.openBlock("public protocol ${serviceSymbol.name}Protocol {") .call { operations.forEach { op -> renderOperationDefinition(model, symbolProvider, writer, operationsIndex, op, true) } } .closeBlock("}") .write("") val sectionContext = mapOf( "serviceSymbol" to serviceSymbol, "protocolGenerator" to protocolGenerator, "protocolGenerationContext" to protocolGenerationContext ) writer.declareSection(ConfigurationProtocolSectionId, sectionContext) { writer.openBlock( "public protocol \$L : \$L {", "}", serviceConfig.typeProtocol, serviceConfig.getTypeInheritance() ) { } }.write("") } object ConfigurationProtocolSectionId : SectionId } /** * An extension to see if a structure shape has a the streaming trait*. * * @model model is the smithy model. * @return true if has the streaming trait on itself or its target. */ fun StructureShape.hasStreamingMember(model: Model): Boolean { return this.allMembers.values.any { val streamingTrait = StreamingTrait::class.java it.hasTrait(streamingTrait) || model.getShape(it.target).get().hasTrait(streamingTrait) } }
9
null
18
26
83826f8a0191ecfe770c9c1f1e8f3f0d547f90af
5,812
smithy-swift
Apache License 2.0
src/main/kotlin/ru/gildor/gradle/firebase/testlab/internal/ResultArtifacts.kt
gildor
77,550,683
false
null
package ru.gildor.gradle.firebase.testlab.internal import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty interface Artifacts { var junit: Boolean var logcat: Boolean var video: Boolean var instrumentation: Boolean fun getArtifactPaths(): List<String> } @Suppress("unused") class ArtifactsImpl : Artifacts { override var junit by PathBoolean("test_result_*.xml", true) override var logcat by PathBoolean("logcat") override var video by PathBoolean("video.mp4") override var instrumentation by PathBoolean("instrumentation.results") override fun getArtifactPaths() = paths.toList() private val paths = mutableListOf<String>() class PathBoolean( private var path: String, private var value: Boolean = false ) : ReadWriteProperty<ArtifactsImpl, Boolean> { override fun getValue(thisRef: ArtifactsImpl, property: KProperty<*>) = value override fun setValue(thisRef: ArtifactsImpl, property: KProperty<*>, value: Boolean) { this.value = value if (value) { thisRef.paths += path } else { thisRef.paths -= path } } } }
7
Kotlin
2
19
4ecfd5dd21011ecd6a858a16a013baf06da73adf
1,224
gradle-firebase-test-lab-plugin
Apache License 2.0
src/main/kotlin/dev/tmsoft/lib/query/paging/ContinuousList.kt
turbomates
377,843,961
false
{"Kotlin": 203986, "Makefile": 1218}
@file:Suppress("NestedBlockDepth", "SpreadOperator") package dev.tmsoft.lib.query.paging import dev.tmsoft.lib.exposed.sql.RowNumberFunction import dev.tmsoft.lib.serialization.elementSerializer import kotlinx.coroutines.coroutineScope import kotlinx.serialization.KSerializer import kotlinx.serialization.SerializationException import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.descriptors.buildClassSerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.json.JsonEncoder import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import org.jetbrains.exposed.sql.Expression import org.jetbrains.exposed.sql.ExpressionAlias import org.jetbrains.exposed.sql.ExpressionWithColumnType import org.jetbrains.exposed.sql.LongColumnType import org.jetbrains.exposed.sql.Min import org.jetbrains.exposed.sql.Query import org.jetbrains.exposed.sql.ResultRow import org.jetbrains.exposed.sql.SortOrder import org.jetbrains.exposed.sql.alias import org.jetbrains.exposed.sql.ops.SingleValueInListOp suspend fun <T> Query.toContinuousList( page: PagingParameters, effector: ResultRow.() -> T, sortingParameters: List<SortingParameter> = emptyList(), includeCount: Boolean = false ): ContinuousList<T> { return toContinuousListBuilder(page, sortingParameters, includeCount) { this.map { effector(it) } } } @JvmName("toContinuousListIterable") suspend fun <T> Query.toContinuousList( page: PagingParameters, effector: Iterable<ResultRow>.() -> List<T>, sortingParameters: List<SortingParameter> = emptyList(), includeCount: Boolean = false ): ContinuousList<T> { return toContinuousListBuilder(page, sortingParameters, includeCount) { effector() } } @Suppress("SpreadOperator") suspend fun <T> Query.toContinuousListBuilder( page: PagingParameters, sortingParameters: List<SortingParameter> = emptyList(), includeCount: Boolean = false, effector: Query.() -> List<T> ): ContinuousList<T> = coroutineScope { var count: Long? = null if (targets.count() > 1) { val rootTable = targets.first() if (rootTable.primaryKey != null) { val primaryKey = rootTable.primaryKey!!.columns.first() val primaryKeyAlias = primaryKey.alias("uniq_field_id") val countQuery = Query(set, where) adjustWhereIn(primaryKey, sortingParameters, page.pageSize + 1, page.offset) if (includeCount) { count = countQuery.distinctSubQuery(primaryKeyAlias, sortingParameters).count() } } } else { sortedWith(sortingParameters) count = copy().count() limit(page.pageSize + 1, page.offset) } var result = effector() var hasMore = false if (result.count() > page.pageSize) { hasMore = result.count() > page.pageSize result = result.dropLast(1) } ContinuousList(result, page.pageSize, page.currentPage, hasMore, count) } fun <T> Query.adjustWhereIn( primaryKey: ExpressionWithColumnType<T>, sortingParameters: List<SortingParameter>, limit: Int, offset: Long ) { val primaryKeyAlias = primaryKey.alias("uniq_field_id") val ids = distinctSubQuery(primaryKeyAlias, sortingParameters) .limit(limit, offset) .map { it[primaryKeyAlias.aliasOnlyExpression()] } adjustWhere { SingleValueInListOp(primaryKey, ids) } sortedWith(sortingParameters) } private fun Query.sortedWith(sortingParameters: List<SortingParameter>): Query { return apply { buildSortingParameters(sortingParameters).run { if (isNotEmpty()) orderBy(*this) } } } fun Query.buildSortingParameters(sortingParameters: List<SortingParameter>): Array<Pair<Expression<*>, SortOrder>> { val columns = targets.map { it.columns }.flatten() return sortingParameters .associate { sortingParameter -> val column = columns.find { sortingParameter.name == it.name } ?: throw IllegalArgumentException("Unknown sorting parameter: ${sortingParameter.name}") column to sortingParameter.sortOrder } .toList().toTypedArray() } //SELECT %s AS dctrn_count FROM (SELECT DISTINCT %s FROM (%s) dctrn_result) dctrn_table private fun <T> Query.distinctSubQuery( column: ExpressionAlias<T>, sortingParameters: List<SortingParameter> ): Query { val query = Query(set, where) val rowNumber = RowNumberFunction(buildSortingParameters(sortingParameters) + orderByExpressions).alias("row_number") val subQuery = query.adjustSelect { select(listOf(column) + rowNumber) } .withDistinct().alias("subquery") val minColumn = Min(rowNumber.aliasOnlyExpression(), LongColumnType()).alias("min_column") return subQuery .select( listOf<Expression<*>>( column.aliasOnlyExpression(), minColumn ) ) .withDistinct() .groupBy(column.aliasOnlyExpression()) .orderBy(minColumn) } data class ContinuousList<T>( val data: List<T>, val pageSize: Int, val currentPage: Int, val hasMore: Boolean = false, val count: Long? = null ) object ContinuousListSerializer : KSerializer<ContinuousList<*>> { override val descriptor: SerialDescriptor = buildClassSerialDescriptor("ContinuousListDescriptor") @Suppress("UNCHECKED_CAST") override fun serialize(encoder: Encoder, value: ContinuousList<*>) { val output = encoder as? JsonEncoder ?: throw SerializationException("This class can be saved only by Json") val encoded = output.json.encodeToString( ListSerializer(value.data.elementSerializer()) as KSerializer<Any>, value.data ) val map = mutableMapOf( "pageSize" to JsonPrimitive(value.pageSize), "page" to JsonPrimitive(value.currentPage), "hasMore" to JsonPrimitive(value.hasMore), "data" to output.json.parseToJsonElement(encoded) ) if (value.count != null) map["count"] = JsonPrimitive(value.count) val tree = JsonObject(map) output.encodeJsonElement(tree) } override fun deserialize(decoder: Decoder): ContinuousList<*> { throw NotImplementedError() } }
0
Kotlin
2
0
c1487817e5210e0c2db4f3047aeb71ad21bd164e
6,443
kotlin-back-sdk
Apache License 2.0
packages/amplify_datastore/android/src/main/kotlin/com/amazonaws/amplify/amplify_datastore/DataStoreObserveEventStreamHandler.kt
aws-amplify
253,571,453
false
null
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.amplify.amplify_datastore import android.os.Handler import android.os.Looper import com.amazonaws.amplify.amplify_core.exception.ExceptionMessages import com.amplifyframework.core.model.SerializedModel import io.flutter.plugin.common.EventChannel class DataStoreObserveEventStreamHandler : EventChannel.StreamHandler { private var eventSink: EventChannel.EventSink? = null private val handler = Handler(Looper.getMainLooper()) override fun onListen(argunents: Any?, sink: EventChannel.EventSink) { eventSink = sink } fun sendEvent(flutterEvent: Map<String, Any>) { handler.post { eventSink?.success(flutterEvent) } } fun endOfStream() { eventSink?.endOfStream() } fun error(errorCode: String, details: Any?) { handler.post { eventSink?.error(errorCode, ExceptionMessages.defaultFallbackExceptionMessage, details) } } override fun onCancel(p0: Any?) { eventSink = null } }
202
null
184
953
bb033ba326f6fb0c5a26662f84d00dd88b092f54
1,568
amplify-flutter
Apache License 2.0
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/wrappers/FinalNewline.kt
detekt
71,729,669
false
null
package io.gitlab.arturbosch.detekt.formatting.wrappers import com.pinterest.ktlint.core.api.FeatureInAlphaState import com.pinterest.ktlint.core.api.UsesEditorConfigProperties import com.pinterest.ktlint.ruleset.standard.FinalNewlineRule import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault import io.gitlab.arturbosch.detekt.api.internal.AutoCorrectable import io.gitlab.arturbosch.detekt.api.internal.Configuration import io.gitlab.arturbosch.detekt.api.internal.config import io.gitlab.arturbosch.detekt.formatting.FormattingRule /** * See <a href="https://ktlint.github.io">ktlint-website</a> for documentation. */ @OptIn(FeatureInAlphaState::class) @ActiveByDefault(since = "1.0.0") @AutoCorrectable(since = "1.0.0") class FinalNewline(config: Config) : FormattingRule(config) { override val wrapping = FinalNewlineRule() override val issue = issueFor("Detects missing final newlines") @Configuration("report absence or presence of a newline") private val insertFinalNewLine by config(true) override fun overrideEditorConfigProperties(): Map<UsesEditorConfigProperties.EditorConfigProperty<*>, String> = mapOf(FinalNewlineRule.insertNewLineProperty to insertFinalNewLine.toString()) }
146
null
563
4,176
7250c885d7ca35c1b26f0af565067229375c9145
1,283
detekt
Apache License 2.0
design/ui/src/main/java/com/mikhaellopez/ui/state/UiState.kt
lopspower
522,617,808
false
{"Kotlin": 168656, "Java": 749}
package com.mikhaellopez.ui.state import androidx.compose.runtime.Immutable @Immutable sealed class UiState { data class Content<T>( val data: T, val isRefresh: Boolean = false, val snackMessage: String? = null ) : UiState() { companion object { fun <T> createRefresh(data: T): Content<T> = Content(data, isRefresh = true) fun <T> createSnack(data: T, message: String): Content<T> = Content(data, snackMessage = message) } override fun toString(): String = "UiState.Content(isRefresh=$isRefresh, snackMessage=$snackMessage, data=$data)" } data class Error(val message: String, val isLoading: Boolean = false) : UiState() { companion object { fun createRetry(message: String) = Error(message, isLoading = true) } override fun toString(): String = "UiState.Error(isLoading=$isLoading, message=$message)" } data class Loading(val default: Boolean = false) : UiState() { companion object { fun createDefault() = Loading(default = true) } override fun toString(): String = "UiState.Loading(default=$default)" } }
0
Kotlin
6
111
ce41ce693cdb09facc455224b8af8fedcff74ad1
1,256
PokeCardCompose
Apache License 2.0
app/src/main/kotlin/io/github/plastix/kotlinboilerplate/ui/base/BaseActivity.kt
Plastix
65,548,118
false
null
package io.github.plastix.kotlinboilerplate.ui.base import android.os.Bundle import android.support.annotation.CallSuper import android.support.v7.app.AppCompatActivity import io.github.plastix.kotlinboilerplate.ApplicationComponent import io.github.plastix.kotlinboilerplate.KotlinBoilerplateApp abstract class BaseActivity: AppCompatActivity() { @CallSuper override fun onCreate(savedInstanceState: Bundle?){ super.onCreate(savedInstanceState) injectDependencies(KotlinBoilerplateApp.graph) } abstract fun injectDependencies(graph: ApplicationComponent) }
3
Kotlin
50
282
443762ca4f331cd2d37a042298e57416d3c63ab1
593
Kotlin-Android-Boilerplate
MIT License
app/src/main/java/com/gmribas/desafioverity/presentation/model/UserUIModel.kt
gmribas
655,080,888
false
null
package com.gmribas.desafioverity.presentation.model data class UserUIModel( val login: String, val id: Long, val avatarURL: String )
0
Kotlin
0
0
009f0fcf695e7e5be54de920f0ca431bc972a01e
146
DesafioVerity
Apache License 2.0
language/kmm-langx/src/iosMain/kotlin/io/tagd/langx/ref/concurrent/atomic/AtomicReference.kt
pavan2you
589,617,975
false
{"Kotlin": 575333, "Shell": 5268, "Swift": 1392}
@file:Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING") package io.tagd.langx.ref.concurrent.atomic actual class AtomicReference<V> actual constructor(value: V) { actual fun get(): V { TODO("Not yet implemented") } actual fun set(value: V) { } actual fun getAndSet(value: V): V { TODO("Not yet implemented") } actual fun compareAndSet(expect: V, update: V): Boolean { TODO("Not yet implemented") } }
3
Kotlin
3
2
dd2aaf1e4f20850f31b7024f7f8e4bd33f467f3d
468
kmm-clean-architecture
Apache License 2.0
skellig-test-step-reader/src/main/kotlin/org/skellig/teststep/reader/value/expression/ValueComparisonExpression.kt
skellig-framework
263,021,995
false
{"Kotlin": 793363, "CSS": 525608, "Java": 185441, "HTML": 11313, "FreeMarker": 9740, "ANTLR": 2041}
package org.skellig.teststep.reader.value.expression import java.math.BigDecimal class ValueComparisonExpression( private val operator: String, private val leftExpression: ValueExpression, private val rightExpression: ValueExpression ) : ValueExpression { override fun evaluate(context: ValueExpressionContext): Any { var evaluatedLeft = leftExpression.evaluate(context) var evaluatedRight = rightExpression.evaluate(context) return if (evaluatedLeft is String || evaluatedRight is String) { when (operator) { "==" -> evaluatedLeft.toString() == evaluatedRight.toString() "!=" -> evaluatedLeft.toString() != evaluatedRight.toString() else -> throw IllegalArgumentException("Invalid comparison operator for String values: $operator") } } else { if (!(evaluatedLeft is BigDecimal && evaluatedRight is BigDecimal)) { evaluatedLeft = evaluatedLeft.toString().toBigDecimal() evaluatedRight = evaluatedRight.toString().toBigDecimal() } when (operator) { ">" -> evaluatedLeft > evaluatedRight ">=" -> evaluatedLeft >= evaluatedRight "<" -> evaluatedLeft < evaluatedRight "<=" -> evaluatedLeft <= evaluatedRight "==" -> evaluatedLeft == evaluatedRight "!=" -> evaluatedLeft != evaluatedRight else -> throw IllegalArgumentException("Invalid comparison operator for numeric values: $operator") } } } override fun toString(): String { return "$leftExpression $operator $rightExpression" } override fun equals(other: Any?): Boolean { return if (other is ValueComparisonExpression) operator == other.operator && leftExpression == other.leftExpression && rightExpression == other.rightExpression else false } override fun hashCode(): Int { return operator.hashCode() + leftExpression.hashCode() + rightExpression.hashCode() } }
17
Kotlin
0
2
64238035cbec9c73268da3e5997fd485f86906fe
2,151
skellig-core
Apache License 2.0
Demo/src/main/java/com/angcyo/uicore/demo/BluetoothDemo.kt
angcyo
229,037,572
false
{"Shell": 3505}
package com.angcyo.uicore.demo import android.app.Application import android.os.Bundle import com.angcyo.bluetooth.BluetoothModel import com.angcyo.core.vmApp import com.angcyo.dsladapter.DslAdapterItem import com.angcyo.dsladapter.addToAfter import com.angcyo.dsladapter.removeFromAfter import com.angcyo.library.app import com.angcyo.library.ex.nowTimeString import com.angcyo.uicore.base.AppDslFragment import com.angcyo.uicore.dslitem.AppBluetoothDeviceItem import com.angcyo.widget.progress.ArcLoadingView /** * @author <a href="mailto:<EMAIL>">angcyo</a> * @since 2022/03/12 */ class BluetoothDemo : AppDslFragment() { val bluetoothModel = vmApp<BluetoothModel>() val emptyDeviceFilter = EmptyDeviceFilter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) BluetoothModel.init(app() as Application) } override fun initBaseView(savedInstanceState: Bundle?) { super.initBaseView(savedInstanceState) bluetoothModel.bluetoothStateData.observe { it?.let { _adapter[0]?.updateAdapterItem() } } bluetoothModel.bluetoothDeviceData.observe { device -> device?.let { _adapter.render { //移除旧的item dataItems.removeAll { it is AppBluetoothDeviceItem && it.bleDevice?.mac == device.mac } //添加新的item AppBluetoothDeviceItem()() { itemData = device bleDevice = device time = nowTimeString() } } } } renderDslAdapter { DslAdapterItem()(headerItems) { itemLayoutId = R.layout.item_bluetooth_layout itemBindOverride = { itemHolder, itemPosition, adapterItem, payloads -> itemHolder.tv(R.id.lib_text_view)?.text = "蓝牙设备:${BluetoothModel.isSupportBle()} 蓝牙开关:${BluetoothModel.isBlueEnable()}" if (bluetoothModel.bluetoothStateData.value == BluetoothModel.BLUETOOTH_STATE_SCANNING) { itemHolder.v<ArcLoadingView>(R.id.arc_load_view)?.startLoading() } else { itemHolder.v<ArcLoadingView>(R.id.arc_load_view)?.endLoading() itemHolder.v<ArcLoadingView>(R.id.arc_load_view)?.progress = 0f } itemHolder.tv(R.id.start_scan_button)?.text = if (bluetoothModel.bluetoothStateData.value == BluetoothModel.BLUETOOTH_STATE_SCANNING) "停止扫描" else "开始扫描" //start itemHolder.click(R.id.start_scan_button) { if (bluetoothModel.bluetoothStateData.value == BluetoothModel.BLUETOOTH_STATE_SCANNING) { bluetoothModel.stopScan() } else { dataItems.clear() bluetoothModel.startScan(requireActivity()) } } //filter itemHolder.check( R.id.filter_switch, emptyDeviceFilter.isEnable ) { buttonView, isChecked -> emptyDeviceFilter.isEnable = isChecked if (isChecked) { emptyDeviceFilter.addToAfter(_adapter) } else { emptyDeviceFilter.removeFromAfter(_adapter) } } } } } } override fun onFragmentNotFirstShow(bundle: Bundle?) { super.onFragmentNotFirstShow(bundle) _adapter[0]?.updateAdapterItem() } }
0
Shell
2
1
e981f6530e91023ae8fb722b2cacd091e5a0fb24
3,936
UICoreDemo
MIT License
mesh-exam/feature/discover/src/main/java/io/flaterlab/meshexam/presentation/discover/ui/info/ExamInfoDialogFragment.kt
chorobaev
434,863,301
false
{"Kotlin": 467494, "Java": 1951}
package io.flaterlab.meshexam.presentation.discover.ui.info import android.os.Bundle import android.view.View import androidx.core.view.isInvisible import androidx.fragment.app.FragmentManager import dagger.hilt.android.AndroidEntryPoint import io.flaterlab.meshexam.androidbase.ViewBindingBottomSheetDialogFragment import io.flaterlab.meshexam.androidbase.ViewBindingProvider import io.flaterlab.meshexam.androidbase.ext.clickWithDebounce import io.flaterlab.meshexam.androidbase.setLauncher import io.flaterlab.meshexam.androidbase.text.setText import io.flaterlab.meshexam.presentation.discover.databinding.DialogExamInfoBinding import io.flaterlab.meshexam.presentation.discover.databinding.ItemExamInfoBinding import io.flaterlab.meshexam.presentation.discover.dvo.ExamInfoItemDvo import io.flaterlab.meshexam.presentation.discover.router.DiscoverRouter import javax.inject.Inject @AndroidEntryPoint internal class ExamInfoDialogFragment : ViewBindingBottomSheetDialogFragment<DialogExamInfoBinding> { @Deprecated(message = DEPRECATION_MESSAGE, level = DeprecationLevel.ERROR) constructor() constructor(launcher: ExamInfoLauncher) { setLauncher(launcher) } companion object { fun show(launcher: ExamInfoLauncher, fragmentManager: FragmentManager) { ExamInfoDialogFragment(launcher).show( fragmentManager, ExamInfoDialogFragment::class.java.canonicalName ) } } @Inject lateinit var discoverRouter: DiscoverRouter private val viewModel: ExamInfoViewModel by vm() override val viewBinder: ViewBindingProvider<DialogExamInfoBinding> get() = DialogExamInfoBinding::inflate override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.examName.observe(viewLifecycleOwner, binding.tvExamName::setText) viewModel.examInfoItemList.observe(viewLifecycleOwner, ::onInfoItemsReceived) viewModel.commandEditClient.observe(viewLifecycleOwner) { discoverRouter.openEditProfile(it) } viewModel.commandJoinExam.observe(viewLifecycleOwner) { examId -> dismiss() discoverRouter.joinExam(examId) } binding.btnJoinExam.clickWithDebounce(action = viewModel::onJoinClicked) } private fun onInfoItemsReceived(items: List<ExamInfoItemDvo>) = with(binding.containerExamInfoItems) { removeAllViews() items.forEach { exam -> addView(createExamInfoItemView(exam)) } } private fun createExamInfoItemView(item: ExamInfoItemDvo): View { return ItemExamInfoBinding.inflate(layoutInflater) .apply { tvExamInfoItemTitle.setText(item.title) tvExamInfoItemValue.setText(item.value) btnExamInfoEdit.isInvisible = !item.isEditable btnExamInfoEdit.clickWithDebounce(action = item.onEdit) } .root } }
0
Kotlin
0
2
364c4fcb70a461fc02d2a5ef2590ad5f8975aab5
3,050
mesh-exam
MIT License
app/src/main/java/com/kar/enes/app/utils/CustomBindingAdapter.kt
eneskarpuzoglu
232,054,605
false
null
package com.kar.enes.app.utils import android.widget.ImageView import androidx.databinding.BindingAdapter import com.bumptech.glide.Glide /** * Created by M.Enes on 1/3/2020. */ object CustomBindingAdapter { @JvmStatic @BindingAdapter("bind:image_url") fun loadImage(imageView: ImageView, url: String) { Glide.with(imageView.context).load(url).into(imageView) } }
0
Kotlin
0
0
bfba1270277960d00d1b0fe9c78fa2d748c698bd
392
news
Apache License 2.0
frontend/screen/tools/src/commonMain/kotlin/com/mindovercnc/linuxcnc/screen/tools/root/tabs/cuttinginsert/ui/FeedsAndSpeedsTable.kt
85vmh
543,628,296
false
null
package ui.screen.tools.root.tabs.cuttinginsert import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.mindovercnc.model.FeedsAndSpeeds import com.mindovercnc.linuxcnc.format.toFixedDigitsString import com.mindovercnc.linuxcnc.widgets.VerticalDivider import scroll.VerticalScrollbar import scroll.draggableScroll private enum class FeedsAndSpeedsColumns(val text: String, val unit: String? = null, val size: Dp = Dp.Unspecified) { Material(text = "Material", size = 120.dp), Category(text = "Code", size = 40.dp), DOC(text = "DoC (ap)", unit = "mm"), Feed(text = "Feed (fn)", unit = "mm/rev"), Speed(text = "Speed (vc)", unit = "m/min"), Actions(text = "Actions", size = 140.dp), } @OptIn(ExperimentalFoundationApi::class) @Composable fun FeedsAndSpeedsTable( feedsAndSpeedsList: List<FeedsAndSpeeds>, editableIndex: Int? = null, onEdit: (FeedsAndSpeeds) -> Unit, onDelete: (FeedsAndSpeeds) -> Unit, ) { Box { val scope = rememberCoroutineScope() val scrollState = rememberLazyListState() LazyColumn( modifier = Modifier.draggableScroll(scrollState, scope), state = scrollState ) { stickyHeader { FeedsAndSpeedsHeader(modifier = Modifier.height(40.dp)) } itemsIndexed(feedsAndSpeedsList) { index, item -> if (editableIndex == index) { Box( modifier = Modifier .fillMaxWidth() .height(250.dp), contentAlignment = Alignment.Center ) { AddEditFeedsAndSpeeds(initialFeedsAndSpeeds = item) } } else { FeedsAndSpeedsItemView( item = item, onEditClicked = onEdit, onDeleteClicked = onDelete ) } Divider(color = Color.LightGray, thickness = 0.5.dp) } } VerticalScrollbar( Modifier.align(Alignment.CenterEnd).width(30.dp), scrollState ) } } @Composable private fun FeedsAndSpeedsHeader( modifier: Modifier = Modifier ) { Surface( color = MaterialTheme.colorScheme.primaryContainer ) { Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically ) { FeedsAndSpeedsColumns.entries.forEach { val columnModifier = when (it.size) { Dp.Unspecified -> Modifier.weight(1f) else -> Modifier.width(it.size) } Column( modifier = columnModifier, horizontalAlignment = Alignment.CenterHorizontally ) { Text( textAlign = TextAlign.Center, style = MaterialTheme.typography.titleSmall, text = it.text ) if (it.unit != null) { Text( textAlign = TextAlign.Center, style = MaterialTheme.typography.bodySmall, text = it.unit ) } } if (it != FeedsAndSpeedsColumns.entries.last()) { VerticalDivider(color = Color.LightGray) } } } } } @Composable private fun FeedsAndSpeedsItemView( item: FeedsAndSpeeds, onEditClicked: (FeedsAndSpeeds) -> Unit, onDeleteClicked: (FeedsAndSpeeds) -> Unit, modifier: Modifier = Modifier, ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = modifier.height(60.dp) ) { Text( modifier = Modifier.width(FeedsAndSpeedsColumns.Material.size), textAlign = TextAlign.Center, style = MaterialTheme.typography.bodyMedium, text = item.materialName ) VerticalDivider() Text( modifier = Modifier.width(FeedsAndSpeedsColumns.Category.size), textAlign = TextAlign.Center, style = MaterialTheme.typography.bodyMedium, text = item.materialCategory.name ) VerticalDivider() val formattedAp = "${item.ap.start.toDouble().toFixedDigitsString(2)} - ${ item.ap.endInclusive.toDouble().toFixedDigitsString(2) }" Text( modifier = Modifier.weight(1f), textAlign = TextAlign.Center, style = MaterialTheme.typography.bodyMedium, text = formattedAp ) VerticalDivider() val formattedFn = "${item.fn.start.toDouble().toFixedDigitsString(2)} - ${ item.fn.endInclusive.toDouble().toFixedDigitsString(2) }" Text( modifier = Modifier.weight(1f), textAlign = TextAlign.Center, text = formattedFn, style = MaterialTheme.typography.bodyMedium, ) VerticalDivider() val formattedVc = "${item.vc.first} - ${item.vc.last}" Text( modifier = Modifier.weight(1f), textAlign = TextAlign.Center, text = formattedVc, style = MaterialTheme.typography.bodyMedium, ) VerticalDivider() Row( modifier = Modifier.width(FeedsAndSpeedsColumns.Actions.size), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly ) { IconButton( modifier = Modifier, onClick = { onEditClicked.invoke(item) }) { Icon(Icons.Default.Edit, contentDescription = "") } VerticalDivider() IconButton( modifier = Modifier, onClick = { onDeleteClicked.invoke(item) }) { Icon(Icons.Default.Delete, contentDescription = "") } } } }
0
Kotlin
1
2
d9105f82d90ac6dbf4b6e0da160c706d67630d7f
7,053
mindovercnclathe
Apache License 2.0
compiler/testData/ir/interpreter/defaultEquals.kt
JetBrains
3,432,266
false
null
@CompileTimeCalculation class A @CompileTimeCalculation fun getTheSameValue(a: Any): Any = a @CompileTimeCalculation fun theSameObjectEquals(value: Any): Boolean { return value == getTheSameValue(value) && value === getTheSameValue(value) } const val equals1 = A().<!EVALUATED: `false`!>equals(A())<!> const val equals2 = <!EVALUATED: `true`!>theSameObjectEquals(A())<!>
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
378
kotlin
Apache License 2.0
src/main/kotlin/com/sandrabot/sandra/constants/Constants.kt
sandrabot
121,549,855
false
null
/* * Copyright 2017-2021 <NAME> and <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.sandrabot.sandra.constants import com.sandrabot.sandra.SandraInfo object Constants { const val APPLICATION_ID = 302915036492333067L const val PATREON_CAMPAIGN = 1386347 const val DEFAULT_COOLDOWN = 2000 const val AVERY = 579335274388258858L const val LOGAN = 275012982725935105L const val GABBY = 276856260253712384L const val GUILD_HANGOUT = 340937384239824897L const val PREFIX = "s." const val BETA_PREFIX = "b." const val TWITCH = "https://twitch.tv/averen" const val HASTEBIN = "https://haste.averen.dev" const val TWITTER_GABBY = "https://twitter.com/CandyCanvasArt" const val DIRECT_SUPPORT = "https://discord.com/invite/ybuvfZR" const val DIRECT_INVITE = "https://discord.com/api/oauth2/authorize?" + "client_id=$APPLICATION_ID&permissions=473296087&scope=bot" val DEVELOPERS = arrayOf(AVERY, LOGAN) val VERSION = "${SandraInfo.VERSION}_${SandraInfo.COMMIT.substring(0, 8)}" val USER_AGENT = "Sandra/$VERSION (+${Website.WEBSITE})" }
2
null
3
7
f2373e7801ec57cab10d69da19302565beb1887b
1,649
sandra
Apache License 2.0
data/src/main/kotlin/data/tinder/login/LoginProviderModule.kt
alouanemed
106,109,153
false
null
package data.tinder.login import dagger.Module import dagger.Provides import data.crash.FirebaseCrashReporterModule import reporter.CrashReporter import javax.inject.Singleton @Module(includes = arrayOf(LoginFacadeModule::class, FirebaseCrashReporterModule::class)) internal class LoginProviderModule { @Provides @Singleton fun loginProvider(loginFacade: LoginFacade, crashReporter: CrashReporter): LoginProviderImpl = LoginProviderImpl(loginFacade, crashReporter) }
0
Kotlin
0
0
678ad00d08630cfcff8de1bbea2a9000927c8e68
515
dinger
MIT License
src/main/kotlin/dev3/blockchainapiservice/features/contract/deployment/repository/ContractDeploymentRequestRepository.kt
0xDev3
539,904,697
false
null
package dev3.blockchainapiservice.features.contract.deployment.repository import dev3.blockchainapiservice.features.contract.deployment.model.filters.ContractDeploymentRequestFilters import dev3.blockchainapiservice.features.contract.deployment.model.params.StoreContractDeploymentRequestParams import dev3.blockchainapiservice.features.contract.deployment.model.result.ContractDeploymentRequest import dev3.blockchainapiservice.generated.jooq.id.ContractDeploymentRequestId import dev3.blockchainapiservice.generated.jooq.id.ProjectId import dev3.blockchainapiservice.util.ChainId import dev3.blockchainapiservice.util.ContractAddress import dev3.blockchainapiservice.util.TransactionHash import dev3.blockchainapiservice.util.WalletAddress interface ContractDeploymentRequestRepository { fun store(params: StoreContractDeploymentRequestParams, metadataProjectId: ProjectId): ContractDeploymentRequest fun markAsDeleted(id: ContractDeploymentRequestId): Boolean fun getById(id: ContractDeploymentRequestId): ContractDeploymentRequest? fun getByAliasAndProjectId(alias: String, projectId: ProjectId): ContractDeploymentRequest? fun getByContractAddressAndChainId(contractAddress: ContractAddress, chainId: ChainId): ContractDeploymentRequest? fun getByContractAddressChainIdAndProjectId( contractAddress: ContractAddress, chainId: ChainId, projectId: ProjectId ): ContractDeploymentRequest? fun getAllByProjectId( projectId: ProjectId, filters: ContractDeploymentRequestFilters ): List<ContractDeploymentRequest> fun setTxInfo(id: ContractDeploymentRequestId, txHash: TransactionHash, deployer: WalletAddress): Boolean fun setContractAddress(id: ContractDeploymentRequestId, contractAddress: ContractAddress): Boolean }
0
Kotlin
0
0
d9aa8802cf140e0cdd3b701fa2a9c30764b4ad5f
1,808
blockchain-api-service
MIT License
fuzzer/fuzzing_output/crashing_tests/verified/innerConstructorFromTopLevelOneStringArg.kt-988335090.kt
ItsLastDay
102,885,402
false
null
class A { inner class Inner(val result: Int) } fun Any.box(): String { val result = (if (((A::Inner)) !in false) { ((A::Inner)) } else { this })((::A)(), 111).((result) ?: (result)) + (A::Inner)(A(), 222).result if (result != 333) { return "Fail $result" } return "OK" }
1
null
1
6
bb80db8b1383a6c7f186bea95c53faff4c0e0281
273
KotlinFuzzer
MIT License
src/main/kotlin/C_0051359b.kt
argcc
777,572,651
false
{"Kotlin": 866115}
package org.example class C_0051359b { var float_0x0 = 0 var resist1 = MutableList(7) { 0f } var resist2 = MutableList(7) { 0f } var float_0x3c = 0 var float_0x40 = 0 var float_0x44 = 0 }
0
Kotlin
0
0
415f3190279236c8c1335a0f8556f3bb9eac5256
212
ei_reverse_consp
MIT License
plugins/kotlin/idea/tests/testData/editor/enterHandler/multilineString/withTabs/tabs2/EnterWithTextOnNewLineMargin.kt
ingokegel
72,937,917
true
null
// SET_TRUE: USE_TAB_CHARACTER // SET_INT: TAB_SIZE=2 // SET_INT: INDENT_SIZE=2 val a = """blah blah blah | blah blah<caret> """ // IGNORE_FORMATTER
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
160
intellij-community
Apache License 2.0
plugins/kotlin/idea/tests/testData/editor/enterHandler/multilineString/withTabs/tabs2/EnterWithTextOnNewLineMargin.kt
ingokegel
72,937,917
true
null
// SET_TRUE: USE_TAB_CHARACTER // SET_INT: TAB_SIZE=2 // SET_INT: INDENT_SIZE=2 val a = """blah blah blah | blah blah<caret> """ // IGNORE_FORMATTER
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
160
intellij-community
Apache License 2.0
src/main/kotlin/dev/boilerplate/gabrieltay/microservice/resolver/Mutataion.kt
Gabrieltay
175,142,367
false
null
package dev.boilerplate.gabrieltay.microservice.resolver import com.coxautodev.graphql.tools.GraphQLMutationResolver import dev.boilerplate.gabrieltay.microservice.model.Human import org.springframework.stereotype.Component import java.util.* @Component class Mutataion: GraphQLMutationResolver { fun createHuman(createHumanInput: Map<String, String>): Human { var name: String? = null if (createHumanInput.containsKey("name")) { name = createHumanInput.get("name") } var homePlanet: String? = "Jakku" if (createHumanInput.containsKey("homePlanet")) { homePlanet = createHumanInput.get("homePlanet") } return Human(UUID.randomUUID().toString(), name!!, emptyList(), homePlanet ) } }
0
Kotlin
0
0
bce53634cb179988294cc1efd1458dc37ce9a91f
777
microservice
MIT License
diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/rules/kdoc/KdocMethods.kt
akuleshov7
280,211,043
false
null
package org.cqfn.diktat.ruleset.rules.kdoc import com.pinterest.ktlint.core.KtLint.FILE_PATH_USER_DATA_KEY import com.pinterest.ktlint.core.Rule import com.pinterest.ktlint.core.ast.ElementType.BINARY_EXPRESSION import com.pinterest.ktlint.core.ast.ElementType.BLOCK import com.pinterest.ktlint.core.ast.ElementType.CALLABLE_REFERENCE_EXPRESSION import com.pinterest.ktlint.core.ast.ElementType.CALL_EXPRESSION import com.pinterest.ktlint.core.ast.ElementType.COLLECTION_LITERAL_EXPRESSION import com.pinterest.ktlint.core.ast.ElementType.FUN import com.pinterest.ktlint.core.ast.ElementType.KDOC import com.pinterest.ktlint.core.ast.ElementType.KDOC_SECTION import com.pinterest.ktlint.core.ast.ElementType.KDOC_TAG_NAME import com.pinterest.ktlint.core.ast.ElementType.KDOC_TEXT import com.pinterest.ktlint.core.ast.ElementType.LAMBDA_EXPRESSION import com.pinterest.ktlint.core.ast.ElementType.MODIFIER_LIST import com.pinterest.ktlint.core.ast.ElementType.REFERENCE_EXPRESSION import com.pinterest.ktlint.core.ast.ElementType.SAFE_ACCESS_EXPRESSION import com.pinterest.ktlint.core.ast.ElementType.THROW import com.pinterest.ktlint.core.ast.ElementType.TYPE_REFERENCE import com.pinterest.ktlint.core.ast.ElementType.WHEN_CONDITION_WITH_EXPRESSION import org.cqfn.diktat.common.config.rules.RulesConfig import org.cqfn.diktat.common.config.rules.getCommonConfiguration import org.cqfn.diktat.ruleset.constants.Warnings.MISSING_KDOC_ON_FUNCTION import org.cqfn.diktat.ruleset.constants.Warnings.KDOC_TRIVIAL_KDOC_ON_FUNCTION import org.cqfn.diktat.ruleset.constants.Warnings.KDOC_WITHOUT_PARAM_TAG import org.cqfn.diktat.ruleset.constants.Warnings.KDOC_WITHOUT_RETURN_TAG import org.cqfn.diktat.ruleset.constants.Warnings.KDOC_WITHOUT_THROWS_TAG import org.cqfn.diktat.ruleset.utils.* import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl import org.jetbrains.kotlin.com.intellij.psi.tree.TokenSet import org.jetbrains.kotlin.kdoc.parser.KDocKnownTag import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.psi.KtThrowExpression import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.psi.psiUtil.referenceExpression /** * This rule checks that whenever the method has arguments, return value, can throw exceptions, * KDoc block should contain `@param`, `@return`, `@throws`. * For `@return` check methods with explicit return type are supported and methods with inferred return * type are supported the following way: they should either declare return type `Unit` or have `@return` tag. * Currently only `throw` keyword from this methods body is supported for `@throws` check. */ @Suppress("ForbiddenComment") class KdocMethods(private val configRules: List<RulesConfig>) : Rule("kdoc-methods") { companion object { // expression body of function can have a lot of 'ElementType's, this list might be not full private val expressionBodyTypes = setOf(BINARY_EXPRESSION, CALL_EXPRESSION, LAMBDA_EXPRESSION, REFERENCE_EXPRESSION, CALLABLE_REFERENCE_EXPRESSION, SAFE_ACCESS_EXPRESSION, WHEN_CONDITION_WITH_EXPRESSION, COLLECTION_LITERAL_EXPRESSION) private val uselessKdocRegex = """^([rR]eturn|[gGsS]et)[s]?\s+\w+(\s+\w+)?$""".toRegex() } private lateinit var emitWarn: ((offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit) private var isFixMode: Boolean = false override fun visit(node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit) { isFixMode = autoCorrect emitWarn = emit if (node.elementType == FUN && node.getFirstChildWithType(MODIFIER_LIST).isAccessibleOutside()) { val config = configRules.getCommonConfiguration().value val fileName = node.getRootNode().getFileName() val isTestMethod = node.hasTestAnnotation() || isLocatedInTest(fileName.splitPathToDirs(), config.testAnchors) if (!isTestMethod && !node.isStandardMethod() && !node.isSingleLineGetterOrSetter()) { checkSignatureDescription(node) } } else if (node.elementType == KDOC_SECTION) { checkKdocBody(node) } } @Suppress("UnsafeCallOnNullableType") private fun checkSignatureDescription(node: ASTNode) { val kDoc = node.getFirstChildWithType(KDOC) val kDocTags = kDoc?.kDocTags() val name = node.getIdentifierName()!!.text val (missingParameters, kDocMissingParameters) = getMissingParameters(node, kDocTags) val explicitlyThrownExceptions = getExplicitlyThrownExceptions(node) val missingExceptions = explicitlyThrownExceptions .minus(kDocTags ?.filter { it.knownTag == KDocKnownTag.THROWS } ?.mapNotNull { it.getSubjectName() } ?.toSet() ?: setOf() ) val paramCheckFailed = (missingParameters.isNotEmpty() && !node.isSingleLineGetterOrSetter()) || kDocMissingParameters.isNotEmpty() val returnCheckFailed = checkReturnCheckFailed(node, kDocTags) val throwsCheckFailed = missingExceptions.isNotEmpty() if (paramCheckFailed) handleParamCheck(node, kDoc, missingParameters, kDocMissingParameters, kDocTags) if (returnCheckFailed) handleReturnCheck(node, kDoc, kDocTags) if (throwsCheckFailed) handleThrowsCheck(node, kDoc, missingExceptions) // if no tag failed, we have too little information to suggest KDoc - it would just be empty val anyTagFailed = paramCheckFailed || returnCheckFailed || throwsCheckFailed if (kDoc == null && anyTagFailed) { addKdocTemplate(node, name, missingParameters, explicitlyThrownExceptions, returnCheckFailed) } else if (kDoc == null) { MISSING_KDOC_ON_FUNCTION.warn(configRules, emitWarn, false, name, node.startOffset, node) } } private fun getMissingParameters(node: ASTNode, kDocTags: Collection<KDocTag>?): Pair<List<String?>, List<KDocTag>> { val parameterNames = node.parameterNames() val kDocParamList = kDocTags?.filter { it.knownTag == KDocKnownTag.PARAM && it.getSubjectName() != null } return if (parameterNames.isEmpty()) { Pair(emptyList(), kDocParamList ?: listOf()) } else if (kDocParamList != null && kDocParamList.isNotEmpty()) { Pair(parameterNames.minus(kDocParamList.map { it.getSubjectName() }), kDocParamList.filter { it.getSubjectName() !in parameterNames }) } else { Pair(parameterNames.toList(), listOf()) } } private fun checkReturnCheckFailed(node: ASTNode, kDocTags: Collection<KDocTag>?): Boolean { if (node.isSingleLineGetterOrSetter()) return false val explicitReturnType = node.getFirstChildWithType(TYPE_REFERENCE) val hasExplicitNotUnitReturnType = explicitReturnType != null && explicitReturnType.text != "Unit" val hasExplicitUnitReturnType = explicitReturnType != null && explicitReturnType.text == "Unit" val isFunWithExpressionBody = expressionBodyTypes.any { node.hasChildOfType(it) } val hasReturnKDoc = kDocTags != null && kDocTags.hasKnownKDocTag(KDocKnownTag.RETURN) return (hasExplicitNotUnitReturnType || isFunWithExpressionBody && !hasExplicitUnitReturnType) && !hasReturnKDoc } private fun getExplicitlyThrownExceptions(node: ASTNode): Set<String> { val codeBlock = node.getFirstChildWithType(BLOCK) val throwKeywords = codeBlock?.findAllNodesWithSpecificType(THROW) return throwKeywords ?.map { it.psi as KtThrowExpression } ?.mapNotNull { it.thrownExpression?.referenceExpression()?.text } ?.toSet() ?: setOf() } @Suppress("UnsafeCallOnNullableType") private fun handleParamCheck(node: ASTNode, kDoc: ASTNode?, missingParameters: Collection<String?>, kDocMissingParameters: List<KDocTag>, kDocTags: Collection<KDocTag>?) { kDocMissingParameters.forEach { KDOC_WITHOUT_PARAM_TAG.warn(configRules, emitWarn, false, "${it.getSubjectName()} param isn't present in argument list", it.node.startOffset, it.node) } if (missingParameters.isNotEmpty()) { KDOC_WITHOUT_PARAM_TAG.warnAndFix(configRules, emitWarn, isFixMode, "${node.getIdentifierName()!!.text} (${missingParameters.joinToString()})", node.startOffset, node) { val beforeTag = kDocTags?.find { it.knownTag == KDocKnownTag.RETURN } ?: kDocTags?.find { it.knownTag == KDocKnownTag.THROWS } missingParameters.forEach { kDoc?.insertTagBefore(beforeTag?.node) { addChild(LeafPsiElement(KDOC_TAG_NAME, "@param")) addChild(PsiWhiteSpaceImpl(" ")) addChild(LeafPsiElement(KDOC_TEXT, it)) } } } } } @Suppress("UnsafeCallOnNullableType") private fun handleReturnCheck(node: ASTNode, kDoc: ASTNode?, kDocTags: Collection<KDocTag>? ) { KDOC_WITHOUT_RETURN_TAG.warnAndFix(configRules, emitWarn, isFixMode, node.getIdentifierName()!!.text, node.startOffset, node) { val beforeTag = kDocTags?.find { it.knownTag == KDocKnownTag.THROWS } kDoc?.insertTagBefore(beforeTag?.node) { addChild(LeafPsiElement(KDOC_TAG_NAME, "@return")) } } } @Suppress("UnsafeCallOnNullableType") private fun handleThrowsCheck(node: ASTNode, kDoc: ASTNode?, missingExceptions: Collection<String> ) { KDOC_WITHOUT_THROWS_TAG.warnAndFix(configRules, emitWarn, isFixMode, "${node.getIdentifierName()!!.text} (${missingExceptions.joinToString()})", node.startOffset, node) { missingExceptions.forEach { kDoc?.insertTagBefore(null) { addChild(LeafPsiElement(KDOC_TAG_NAME, "@throws")) addChild(LeafPsiElement(KDOC_TEXT, " ")) addChild(LeafPsiElement(KDOC_TEXT, it)) } } } } @Suppress("UnsafeCallOnNullableType") private fun addKdocTemplate(node: ASTNode, name: String, missingParameters: Collection<String?>, explicitlyThrownExceptions: Collection<String>, returnCheckFailed: Boolean ) { MISSING_KDOC_ON_FUNCTION.warnAndFix(configRules, emitWarn, isFixMode, name, node.startOffset, node) { val kDocTemplate = "/**\n" + (missingParameters.joinToString("") { " * @param $it\n" } + (if (returnCheckFailed) " * @return\n" else "") + explicitlyThrownExceptions.joinToString("") { " * @throws $it\n" } + " */\n" ) val kdocNode = KotlinParser().createNode(kDocTemplate).findChildByType(KDOC)!! node.appendNewlineMergingWhiteSpace(node.firstChildNode, node.firstChildNode) node.addChild(kdocNode, node.firstChildNode) } } private fun checkKdocBody(node: ASTNode) { val kdocTextNodes = node.getChildren(TokenSet.create(KDOC_TEXT)) if (kdocTextNodes.size == 1) { val kdocText = kdocTextNodes.first().text.trim() if (kdocText.matches(uselessKdocRegex)) { KDOC_TRIVIAL_KDOC_ON_FUNCTION.warn(configRules, emitWarn, isFixMode, kdocText, kdocTextNodes.first().startOffset, node) } } } private fun ASTNode.isSingleLineGetterOrSetter() = isGetterOrSetter() && (expressionBodyTypes.any { hasChildOfType(it) } || getBodyLines().size == 1) }
1
null
1
1
9eefb12b73fd6b44d164199c3ef0295c8908054d
12,466
diKTat
MIT License
src/commonMain/kotlin/coingecko/constant/Currency.kt
DrewCarlson
267,978,965
false
{"Kotlin": 56533}
package coingecko.constant object Currency { // Fiat const val AED = "aed" const val ARS = "ars" const val AUD = "aud" const val BDT = "bdt" const val BHD = "bhd" const val BMD = "bmd" const val BRL = "brl" const val CAD = "cad" const val CHF = "chf" const val CLP = "clp" const val CNY = "cny" const val CZK = "czk" const val DKK = "dkk" const val EUR = "eur" const val GBP = "gbp" const val HKD = "hkd" const val HUF = "huf" const val IDR = "idr" const val ILS = "ils" const val INR = "inr" const val JPY = "jpy" const val KRW = "krw" const val KWD = "kwd" const val LKR = "lkr" const val MMK = "mmk" const val MXN = "mxn" const val MYR = "myr" const val NOK = "nok" const val NZD = "nzd" const val PHP = "php" const val PKR = "pkr" const val PLN = "pln" const val RUB = "rub" const val SAR = "sar" const val SEK = "sek" const val SGD = "sgd" const val THB = "thb" const val TRY = "try" const val TWD = "twd" const val UAH = "uah" const val USD = "usd" const val VEF = "vef" const val VND = "vnd" const val XAG = "xag" const val XAU = "xau" const val XDR = "xdr" const val ZAR = "zar" // crypto const val BNB = "bnb" const val EOS = "eos" const val BTC = "btc" const val BCH = "bch" const val ETH = "eth" const val LTC = "ltc" const val XLM = "xlm" const val XRP = "xrp" }
5
Kotlin
9
44
64d96a5971fa9b47c2786ad6f44ceea71ab6fb5f
1,505
CoinGecko-Kotlin
MIT License
core/src/main/java/com/endiar/movieverse/core/domain/usecase/RemoteUseCase.kt
nandrasaputra
220,730,565
false
null
package com.endiar.movieverse.core.domain.usecase import com.endiar.movieverse.core.data.DiscoverListing import com.endiar.movieverse.core.data.Resource import com.endiar.movieverse.core.domain.model.FilmDetail import com.endiar.movieverse.core.domain.model.FilmGist import com.endiar.movieverse.core.domain.model.FilmSearch import kotlinx.coroutines.flow.Flow interface RemoteUseCase { fun getTrendingFilm(): Flow<Resource<List<FilmGist>>> fun getNowPlayingFilm(): Flow<Resource<List<FilmGist>>> fun getDetailMovie(id: Int): Flow<Resource<FilmDetail>> fun getDetailTV(id: Int): Flow<Resource<FilmDetail>> fun getDiscoverMovie(): DiscoverListing<FilmGist> fun getDiscoverTV(): DiscoverListing<FilmGist> fun searchMovie(query: String): Flow<Resource<List<FilmSearch>>> fun searchTV(query: String): Flow<Resource<List<FilmSearch>>> }
0
Kotlin
3
3
a40bb90311ec8d2a8e3fa26c96ceaaf6603b485b
865
Movieverse
Apache License 2.0
src/test/kotlin/dev/shtanko/algorithms/extensions/ArrayExtensionTest.kt
ashtanko
515,874,521
false
null
/* * MIT License * Copyright (c) 2022 <NAME> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.shtanko.algorithms.extensions import org.junit.jupiter.api.Assertions.assertArrayEquals import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test class ArrayExtensionTest { @Test fun `simple swap test`() { val arr = arrayOf(4, 8) arr.swap(1, 0) assertArrayEquals(arrayOf(8, 4), arr) } @Test fun `loop swap test`() { val arr = arrayOf(4, 8, 15, 16) for (i in 0 until arr.size - 1) { arr.swap(i, i + 1) } assertArrayEquals(arrayOf(8, 15, 16, 4), arr) } @Test fun `simple reverse test`() { val arr = arrayOf(4, 8, 15, 16, 23, 42) arr.reverse() assertArrayEquals(arrayOf(42, 23, 16, 15, 8, 4), arr) } @Test fun `two pointers technique reverse test`() { val arr = arrayOf(4, 8, 15, 16, 23, 42) arr.reverse2() assertArrayEquals(arrayOf(42, 23, 16, 15, 8, 4), arr) } @Test fun `flip test`() { val arr = arrayOf(4, 8, 15, 16, 23, 42) arr.flip(0, arr.size - 1) val expected = arrayOf(42, 23, 16, 15, 8, 4) assertArrayEquals(expected, arr) } @Test fun `char swap test`() { val arr = charArrayOf('A', 'B') arr.swap(1, 0) assertArrayEquals(charArrayOf('B', 'A'), arr) } @Test fun `int array swap test`() { val arr = intArrayOf(4, 8) arr.swap(1, 0) assertArrayEquals(intArrayOf(8, 4), arr) } @Test fun `second function on empty array test`() { val array = intArrayOf() assertThrows(NoSuchElementException::class.java) { array.second() } } @Test fun `second function on single item array test`() { val array = intArrayOf(1) assertThrows(ArrayIndexOutOfBoundsException::class.java) { array.second() } } @Test fun `second function on array test`() { val array = intArrayOf(1, 2) assertEquals(2, array.second()) } }
2
Kotlin
1
9
ee3d5c874d2cb1ee88027ca5f214f876676e57b0
3,229
the-algorithms
MIT License
buildSrc/src/main/kotlin/KotlinMultiplatformExtension.kt
shepeliev
329,550,581
false
{"Kotlin": 234175, "Shell": 14665}
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension fun KotlinMultiplatformExtension.configureKotlinCompilerArgs(vararg args: String) { targets.all { compilations.all { kotlinOptions { freeCompilerArgs += setOf( "-opt-in=kotlin.RequiresOptIn", "-Xexpect-actual-classes", *args ) } } } }
12
Kotlin
37
178
6444981b9eba3478c844edb53e5b3ed6b2cd66eb
444
webrtc-kmp
Apache License 2.0
dikt/src/main/kotlin/io/github/vantoozz/dikt/bind.kt
vantoozz
459,342,787
false
{"Kotlin": 42612}
package io.github.vantoozz.dikt import kotlin.reflect.KClass inline fun <reified T : Any> MutableContainer.bind( noinline provider: (Container) -> T, ) = set(T::class, provider) inline fun <reified T : Any> MutableContainer.bind( implementation: T?, ) = set(T::class) { implementation } inline fun <reified T : Any> MutableContainer.bind( implementationClass: KClass<out T>, ) = set(T::class, implementationClass)
0
Kotlin
0
1
f1f49e514859d3923cd5e7cc18ef77c820f455bf
430
dikt
MIT License
src/main/kotlin/no/nav/familie/ba/sak/kjerne/brev/domene/maler/OpphørMedEndring.kt
navikt
224,639,942
false
null
package no.nav.familie.ba.sak.kjerne.brev.domene.maler import no.nav.familie.ba.sak.common.tilDagMånedÅr import no.nav.familie.ba.sak.kjerne.brev.domene.maler.brevperioder.BrevPeriode import java.time.LocalDate data class OpphørMedEndring( override val mal: Brevmal, override val data: OpphørMedEndringData, ) : Vedtaksbrev { constructor( mal: Brevmal = Brevmal.VEDTAK_OPPHØR_MED_ENDRING, vedtakFellesfelter: VedtakFellesfelter, etterbetaling: Etterbetaling? = null, erFeilutbetalingPåBehandling: Boolean, etterbetalingInstitusjon: EtterbetalingInstitusjon? = null, refusjonEosAvklart: RefusjonEøsAvklart? = null, refusjonEosUavklart: RefusjonEøsUavklart? = null, ) : this( mal = mal, data = OpphørMedEndringData( delmalData = OpphørMedEndringData.Delmaler( signaturVedtak = SignaturVedtak( enhet = vedtakFellesfelter.enhet, saksbehandler = vedtakFellesfelter.saksbehandler, beslutter = vedtakFellesfelter.beslutter, ), hjemmeltekst = vedtakFellesfelter.hjemmeltekst, feilutbetaling = erFeilutbetalingPåBehandling, etterbetaling = etterbetaling, etterbetalingInstitusjon = etterbetalingInstitusjon, korrigertVedtak = vedtakFellesfelter.korrigertVedtakData, refusjonEosAvklart = refusjonEosAvklart != null, refusjonEosUavklart = refusjonEosUavklart != null, ), flettefelter = object : FlettefelterForDokument { val perioderMedRefusjonEosAvklart: Flettefelt = refusjonEosAvklart?.perioderMedRefusjonEøsAvklart val perioderMedRefusjonEosUavklart: Flettefelt = refusjonEosUavklart?.perioderMedRefusjonEøsUavklart override val brevOpprettetDato = flettefelt(LocalDate.now().tilDagMånedÅr()) override val navn = flettefelt(vedtakFellesfelter.søkerNavn) override val fodselsnummer = flettefelt(vedtakFellesfelter.søkerFødselsnummer) override val organisasjonsnummer = flettefelt(vedtakFellesfelter.organisasjonsnummer) override val gjelder = flettefelt(vedtakFellesfelter.gjelder) }, perioder = vedtakFellesfelter.perioder, ), ) } data class OpphørMedEndringData( override val delmalData: Delmaler, override val flettefelter: FlettefelterForDokument, override val perioder: List<BrevPeriode>, ) : VedtaksbrevData { data class Delmaler( val signaturVedtak: SignaturVedtak, val feilutbetaling: Boolean, val hjemmeltekst: Hjemmeltekst, val etterbetaling: Etterbetaling?, val etterbetalingInstitusjon: EtterbetalingInstitusjon?, val korrigertVedtak: KorrigertVedtakData?, val refusjonEosAvklart: Boolean, val refusjonEosUavklart: Boolean, ) }
17
Kotlin
1
9
1a1ad3043cb51c472577eaf23749d0e0bf54b261
3,116
familie-ba-sak
MIT License
src/main/kotlin/no/nav/syfo/juridisklogg/Logg.kt
navikt
258,142,447
false
null
package no.nav.syfo.juridisklogg data class Logg( val meldingsId: String, val meldingsInnhold: String, val avsender: String, val mottaker: String, val joarkRef: String = "", var antallAarLagres: Number )
0
Kotlin
0
0
15b9a4a80fca123eb9efb88b0deaa498735178fb
229
syfosmaltinn
MIT License
app/src/main/java/com/situm/capacitycontroltestsuite/data/PreferenceProvider.kt
situmtech
295,709,844
false
null
package com.situm.capacitycontroltestsuite.data import com.situm.capacitycontroltestsuite.model.User import org.koin.core.KoinComponent interface PreferenceProvider: KoinComponent { fun saveUser(user: User) fun getUser(): User? fun removeUser() }
0
Kotlin
1
0
67d1b2c03e26f6100433f08b9ffbdb6521477ec9
262
situm-android-module-capacitycontrol
MIT License
feature/groups/domain/src/main/java/br/com/jwar/sharedbill/groups/domain/usecases/GetGroupsStreamUseCase.kt
wellingtonrib
535,153,218
false
{"Kotlin": 448034, "JavaScript": 2075}
package br.com.jwar.sharedbill.groups.domain.usecases import br.com.jwar.sharedbill.groups.domain.model.Group import kotlinx.coroutines.flow.Flow interface GetGroupsStreamUseCase { suspend operator fun invoke(): Flow<Result<List<Group>>> }
17
Kotlin
0
0
5343aac247f77437164505e3b977e4ef8fe764da
246
SharedBill
Creative Commons Attribution 4.0 International
app/src/admin/java/dev/forcecodes/truckme/ui/statistics/StatisticsViewModel.kt
forceporquillo
403,934,320
false
{"Kotlin": 465111}
package dev.forcecodes.truckme.ui.statistics import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import dev.forcecodes.truckme.core.data.delivery.ItemDeliveredStats import dev.forcecodes.truckme.core.domain.statistics.DAILY import dev.forcecodes.truckme.core.domain.statistics.FilteredDailyStatisticsUseCase import dev.forcecodes.truckme.core.domain.statistics.DeliveredItemStatsUseCase import dev.forcecodes.truckme.core.domain.statistics.ForceRefreshUseCase import dev.forcecodes.truckme.core.domain.statistics.QueryParams import dev.forcecodes.truckme.core.domain.statistics.StatisticsSortType import dev.forcecodes.truckme.core.util.Result import dev.forcecodes.truckme.core.util.successOr import dev.forcecodes.truckme.core.util.tryOffer import dev.forcecodes.truckme.ui.auth.signin.SignInViewModelDelegate import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch import timber.log.Timber import timber.log.Timber.Forest import javax.inject.Inject @HiltViewModel class StatisticsViewModel @Inject constructor( private val filteredDailyStatisticsUseCase: FilteredDailyStatisticsUseCase, private val deliveredItemStatsUseCase: DeliveredItemStatsUseCase, private val forceRefreshUseCase: ForceRefreshUseCase, signInViewModelDelegate: SignInViewModelDelegate, ) : ViewModel(), SignInViewModelDelegate by signInViewModelDelegate { private val _filterType = MutableStateFlow<List<String>>(emptyList()) val filterType = _filterType.asStateFlow() private val _itemDeliveredStats = MutableStateFlow<List<ItemDeliveredStats>>(emptyList()) val itemDeliveredStats = _itemDeliveredStats.asStateFlow() @StatisticsSortType private var sortFilterType: String = DAILY init { refresh() filterStatsBy(null) filterTypeBy() } fun filterTypeBy(@StatisticsSortType type: String = DAILY) { if (sortFilterType != type){ sortFilterType = type } viewModelScope.launch { filteredDailyStatisticsUseCase(type).collect { result -> _filterType.value = result.successOr(emptyList()).also { list -> if (list.isNotEmpty()) { filterStatsBy(list.first()) } } } } } private fun refresh() { viewModelScope.launch { forceRefreshUseCase(userIdValue ?: return@launch) .collect() } } var previousFilter: String? = "" fun filterStatsBy(field: String?) { if (previousFilter != field) { previousFilter = field } viewModelScope.launch { val userIdOrIgnore = userIdValue ?: return@launch val params = QueryParams(userIdOrIgnore, sortFilterType, field) deliveredItemStatsUseCase(params).collect { list -> _itemDeliveredStats.value = list.successOr(emptyList()) } } } }
0
Kotlin
1
3
54ac8235c4920abfd0a2cd5ded5db56cd7c392e3
3,015
truck-me-android
Apache License 2.0
app/src/main/kotlin/com/flixclusive/mobile/MobileAppUiState.kt
rhenwinch
659,237,375
false
{"Kotlin": 1637525, "Java": 18011}
package com.flixclusive.mobile import com.flixclusive.model.provider.SourceDataState internal data class MobileAppUiState( val isInPlayer: Boolean = false, val isShowingUpdateDialog: Boolean = false, val isShowingBottomSheetCard: Boolean = false, val isLongClickedFilmInWatchlist: Boolean = false, val isLongClickedFilmInWatchHistory: Boolean = false, val sourceDataState: SourceDataState = SourceDataState.Idle, val isInPipMode: Boolean = false, )
26
Kotlin
22
264
5128cac1ac119e84a6725fd655eb0da427964c5f
479
Flixclusive
MIT License
mvp/sample-mvp-dialog/src/main/java/ru/surfstudio/android/mvp/dialog/sample/ui/screen/dialogs/complex/ComplexDialogFragment.kt
surfstudio
139,034,657
false
null
package ru.surfstudio.android.mvp.dialog.sample.ui.screen.dialogs.complex import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.complex_dialog_layout.* import ru.surfstudio.android.core.mvp.configurator.BaseFragmentViewConfigurator import ru.surfstudio.android.core.mvp.presenter.CorePresenter import ru.surfstudio.android.mvp.dialog.complex.CoreDialogFragmentView import ru.surfstudio.android.mvp.dialog.sample.R import javax.inject.Inject class ComplexDialogFragment : CoreDialogFragmentView() { @Inject internal lateinit var presenter: ComplexDialogPresenter override fun getPresenters(): Array<CorePresenter<*>> = arrayOf(presenter) override fun createConfigurator(): BaseFragmentViewConfigurator<*, *> { return ComplexDialogScreenConfigurator(arguments!!) } override fun getScreenName(): String = "Complex Dialog Fragment" override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.complex_dialog_layout, container) } override fun onViewCreated(view: View, savedInstanceState: Bundle?, viewRecreated: Boolean) { increase_btn.setOnClickListener { presenter.increment() } decrease_btn.setOnClickListener { presenter.decrement() } apply_btn.setOnClickListener { presenter.applyChanges() } } fun render(sm: ComplexDialogScreenModel) { value_tv.text = sm.sampleData.toString() } }
5
null
30
249
6d73ebcaac4b4bd7186e84964cac2396a55ce2cc
1,571
SurfAndroidStandard
Apache License 2.0
app/src/main/java/thiago/dias/pokemonquiz/Screen2.kt
brunorochaa
733,248,995
false
{"Kotlin": 27946}
package thiago.dias.pokemonquiz import android.content.Context import android.content.Intent import android.media.MediaPlayer import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.VibrationEffect import android.os.Vibrator import android.view.View import android.widget.RadioButton import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.activity_screen1.* import kotlinx.android.synthetic.main.activity_screen2.* import thiago.dias.pokemonquiz.extension.toast import thiago.dias.pokemonquiz.model.Question import thiago.dias.pokemonquiz.model.Quiz class Screen2 : AppCompatActivity() { private lateinit var mediaPlayer: MediaPlayer override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_screen2) activity2ButtonNext.visibility = View.INVISIBLE vibrate() Quiz.questionsShuffle() val question = Quiz.questionsArray.get(0) getScore() activity2textViewScore.text = Quiz.score().toString() activity2TextViewDescription.text = question.questionDescription activity2RadioButtonOption1.text = question.option1 activity2RadioButtonOption2.text = question.option2 activity2RadioButtonOption3.text = question.option3 activity2RadioButtonOption4.text = question.option4 activity2ButtonAnswer.setOnClickListener { activity2ButtonNext.visibility = View.VISIBLE activity2ButtonAnswer.visibility = View.INVISIBLE val id = activity2RadioGroup.checkedRadioButtonId val radio: RadioButton = findViewById(id) if (Quiz.verifyTheCorrectAnswer(radio.text.toString())) { toast("${Quiz.context?.getText(R.string.thats_correct)}") play(R.raw.pikachu_sound) getScore() } else { toast("${Quiz.context?.getText(R.string.thats_incorrect)}") play(R.raw.pikachu_attack) } } activity2ButtonNext.setOnClickListener { startActivity(Intent(this@Screen2, Screen3::class.java)) finish() } } fun getScore() { activity2textViewScore.text = Quiz.score().toString() } private fun play(sound: Int) { mediaPlayer = MediaPlayer.create(this@Screen2, sound) mediaPlayer.start() } private fun stop() { if(mediaPlayer.isPlaying) { mediaPlayer.stop() } } private fun vibrate() { val pattern = longArrayOf(0, 200, 100, 300) val hardware = this@Screen2.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator hardware?.let { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { hardware.vibrate(VibrationEffect.createWaveform(pattern, -1)) } else{ hardware.vibrate(pattern, -1) } } } }
0
Kotlin
0
0
3ed8f37b4f694482e58ce43d6fe5a63dc987cc3a
3,039
quiz-pokemon
MIT License
drestaurant-apps/drestaurant-microservices-websockets/drestaurant-microservices-websockets-command-courier/src/main/kotlin/com/drestaurant/DrestaurantCourierApplication.kt
zouhang1992
158,381,352
true
{"Markdown": 14, "Batchfile": 1, "Shell": 2, "YAML": 27, "Maven POM": 38, "Text": 1, "Ignore List": 1, "INI": 7, "Kotlin": 295, "JavaScript": 4, "HTML": 3, "Java": 4}
package com.drestaurant import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration import org.springframework.boot.runApplication @SpringBootApplication(exclude = [SecurityAutoConfiguration::class]) class DrestaurantCourierApplication fun main(args: Array<String>) { runApplication<DrestaurantCourierApplication>(*args) }
0
Kotlin
1
0
d6ba738b1ffed86c9494bb6d8264e404ed4ea027
426
digital-restaurant
Apache License 2.0
app/src/main/java/br/com/mauker/githubapp/ghrepositories/view/MainActivity.kt
Mauker1
601,832,597
false
null
package br.com.mauker.githubapp.ghrepositories.view import android.content.Intent import android.content.res.Configuration import android.os.Bundle import android.speech.RecognizerIntent import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.paging.LoadState import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import br.com.mauker.githubapp.R import br.com.mauker.githubapp.databinding.ActivityMainBinding import br.com.mauker.materialsearchview.MaterialSearchView import br.com.mauker.materialsearchview.db.model.History import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import timber.log.Timber @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val viewModel: MainViewModel by viewModels() private var pageAdapter: GhRepositoryListAdapter? = null private var curQuery: String? = null //region lifecycle methods override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) setupSearchView() setupRecyclerView() } override fun onResume() { super.onResume() binding.searchView.onViewResumed() } override fun onStop() { super.onStop() binding.searchView.onViewStopped() } override fun onSaveInstanceState(outState: Bundle) { Timber.i("Saving state.") Timber.i("Current query: $curQuery") curQuery?.let { outState.putString(KEY_CURRENT_QUERY, it) } super.onSaveInstanceState(outState) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) Timber.i("Restoring state.") savedInstanceState.getString(KEY_CURRENT_QUERY)?.let { Timber.i("Restored query: $it") curQuery = it lifecycleScope.launch { viewModel.restoreGhRepositories()?.collectLatest { pagingData -> pageAdapter?.submitData(pagingData) } } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_search -> { // Open the search view on the menu item click. binding.searchView.openSearch() return true } } return super.onOptionsItemSelected(item) } @Deprecated("Deprecated in Java") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == RESULT_OK) { val matches = data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS) if (matches != null && matches.size > 0) { val searchWrd = matches[0] if (searchWrd.isNotBlank()) { binding.searchView.setQuery(searchWrd, false) } } return } super.onActivityResult(requestCode, resultCode, data) } //endregion @Deprecated("Deprecated in Java") override fun onBackPressed() { if (binding.searchView.isOpen) { // Close the search on the back button press. binding.searchView.closeSearch() } else { super.onBackPressed() } } //region private utility methods private fun setupSearchView() { val clickListener = object: MaterialSearchView.OnHistoryItemClickListener { override fun onClick(history: History) { binding.searchView.setQuery(history.query, false) } override fun onLongClick(history: History) = Unit } binding.searchView.run { setOnQueryTextListener(object : MaterialSearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { Timber.i("Search query submitted. Query: $query") runQuery(query) return false } override fun onQueryTextChange(newText: String): Boolean { return false } }) setOnItemClickListener(clickListener) adjustTintAlpha(0.8f) } } private fun setupRecyclerView() { val ghAdapter = GhRepositoryListAdapter() pageAdapter = ghAdapter val isLandscape = resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE val isTablet = resources.getBoolean(R.bool.isTablet) binding.rvRepositories.run { layoutManager = when { isLandscape && !isTablet || !isLandscape && isTablet -> { GridLayoutManager(this@MainActivity, 2) } // We can assume that it's a tablet as well isLandscape -> { GridLayoutManager(this@MainActivity, 3) } else -> { LinearLayoutManager( context, LinearLayoutManager.VERTICAL, false ) } } adapter = pageAdapter } lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { ghAdapter.loadStateFlow.collect { binding.prependProgress.isVisible = it.source.prepend is LoadState.Loading || it.source.refresh is LoadState.Loading binding.appendProgress.isVisible = it.source.append is LoadState.Loading binding.txtInitState.isVisible = it.source.refresh is LoadState.NotLoading && ghAdapter.itemCount == 0 when { it.source.append is LoadState.Error || it.source.prepend is LoadState.Error -> { Toast.makeText( this@MainActivity, getString(R.string.error_loading_data), Toast.LENGTH_LONG ).show() } } } } } } private fun runQuery(query: String) { curQuery = query if (query.isNotBlank()) { lifecycleScope.launch { viewModel.getGhRepositories(query).collectLatest { pageAdapter?.submitData(it) } } } } //endregion companion object { private const val KEY_CURRENT_QUERY = "KEY_CURRENT_QUERY" } }
0
Kotlin
0
0
2705433ec5de89681ef3715bbbbf4361b9de160b
7,477
GithubRepoApp
MIT License
src/main/org/lrs/kmodernlrs/controllers/filters/CORSFilter.kt
dtarnawczyk
73,920,384
false
null
package org.lrs.kmodernlrs.controllers.filters import org.apache.log4j.Logger import org.lrs.kmodernlrs.Constants import org.springframework.stereotype.Component import org.springframework.web.filter.OncePerRequestFilter import javax.servlet.FilterChain import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse @Component class CORSFilter : OncePerRequestFilter() { val log: Logger = Logger.getLogger(CORSFilter::class.java) override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain) { response.setHeader("Access-Control-Allow-Origin", "*") response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE") response.setHeader("Access-Control-Max-Age", "3600") response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type, " + Constants.XAPI_VERSION_HEADER) filterChain.doFilter(request, response) } }
0
Kotlin
1
4
e534a527635660fe330980411bc8116200af355b
1,039
modernlrs
Apache License 2.0
app/src/main/java/com/github/jayteealao/pastelmusic/app/ui/icons/pastelicons.kt
jayteealao
530,847,226
false
{"Kotlin": 194323}
package com.github.jayteealao.pastelmusic.app.ui.icons import androidx.annotation.DrawableRes import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.ArrowBack import androidx.compose.material.icons.rounded.Clear import androidx.compose.material.icons.rounded.Favorite import androidx.compose.material.icons.rounded.Home import androidx.compose.material.icons.rounded.Info import androidx.compose.material.icons.rounded.Search import androidx.compose.material.icons.rounded.Settings import androidx.compose.ui.graphics.vector.ImageVector import com.github.jayteealao.pastelmusic.app.R object PastelIcons { val Home = Icon.ImageVectorIcon(Icons.Rounded.Home) val Search = Icon.ImageVectorIcon(Icons.Rounded.Search) val Favorite = Icon.ImageVectorIcon(Icons.Rounded.Favorite) val Settings = Icon.ImageVectorIcon(Icons.Rounded.Settings) val ArrowBack = Icon.ImageVectorIcon(Icons.Rounded.ArrowBack) val Clear = Icon.ImageVectorIcon(Icons.Rounded.Clear) val Music = Icon.DrawableResourceIcon(R.drawable.ic_music) val Repeat = Icon.DrawableResourceIcon(R.drawable.ic_repeat) val RepeatOne = Icon.DrawableResourceIcon(R.drawable.ic_repeat_one) val Shuffle = Icon.DrawableResourceIcon(R.drawable.ic_shuffle) val SkipPrevious = Icon.DrawableResourceIcon(R.drawable.ic_skip_previous) val Play = Icon.DrawableResourceIcon(R.drawable.ic_play) val Pause = Icon.DrawableResourceIcon(R.drawable.ic_pause) val SkipNext = Icon.DrawableResourceIcon(R.drawable.ic_skip_next) val GitHub = Icon.DrawableResourceIcon(R.drawable.ic_github) val Info = Icon.ImageVectorIcon(Icons.Rounded.Info) val Security = Icon.DrawableResourceIcon(R.drawable.ic_security) } sealed interface Icon { data class ImageVectorIcon(val imageVector: ImageVector) : Icon data class DrawableResourceIcon(@DrawableRes val resourceId: Int) : Icon }
0
Kotlin
0
0
34294059654b8fdbc194fe4df419f5118a523070
1,914
PastelMusic
MIT License
platform/platform-impl/src/com/intellij/openapi/project/DumbServiceTracker.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.project import com.intellij.platform.backend.observation.ActivityInProgressWitness import kotlinx.coroutines.suspendCancellableCoroutine class DumbServiceInProgressWitness : ActivityInProgressWitness { override val presentableName: String = "dumb-mode" override suspend fun isInProgress(project: Project): Boolean = DumbService.isDumb(project) override suspend fun awaitConfiguration(project: Project) { suspendCancellableCoroutine { DumbService.getInstance(project).runWhenSmart { it.resumeWith(Result.success(Unit)) } } } }
7
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
716
intellij-community
Apache License 2.0
app/src/main/java/com/dream/juiceandroid/developers/codelab/activity/DataBindingActivity.kt
juicelover
582,477,247
false
{"Kotlin": 169228, "Java": 5219}
package com.dream.juiceandroid.developers.codelab.activity import com.dream.juiceandroid.R import com.dream.juiceandroid.databinding.ActivityDataBindingBinding import com.dream.juiceandroid.developers.codelab.viewModel.DataBindingViewModel import com.juiceandroid.base_lib.activity.BaseActivity import org.koin.androidx.viewmodel.ext.android.viewModel /** * @author juice * @date 2023-01-09 08:57:20 * @desc dataBinding * @link https://developers.google.cn/codelabs/android-databinding#0 */ class DataBindingActivity : BaseActivity<ActivityDataBindingBinding>() { private val mViewModel by viewModel<DataBindingViewModel>() override fun getLayoutId(): Int = R.layout.activity_data_binding override fun initView() { bindingView.lifecycleOwner = this bindingView.vm = mViewModel bindingView.toolbarJuiceCreate.apply { setNavigationOnClickListener { finish() } } } override fun loadData(isRefresh: Boolean) { } }
0
Kotlin
0
0
6ab6a8f15a89f0e83ddcb54f882d4e2cbd5e3fa7
991
JuiceAndroidKt
Apache License 2.0