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
app/src/main/java/com/system/moneycontrol/model/entities/DialogItem.kt
enirsilvaferraz
138,302,967
false
{"Kotlin": 71910}
package com.system.moneycontrol.model.entities interface DialogItem { fun getDescription(): String }
0
Kotlin
0
0
7087fde3fbd7433d294cb43e874939df4f10b7e1
105
Money-Control
Apache License 2.0
src/main/kotlin/com/github/rafaelldi/tyeplugin/runConfig/tyeRun/TyeCommandLineState.kt
rohan-buechner
399,365,891
true
{"Kotlin": 77343, "Java": 6341}
package com.github.rafaelldi.tyeplugin.runConfig.tyeRun import com.github.rafaelldi.tyeplugin.cli.TyeCliClient import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.CommandLineState import com.intellij.execution.process.OSProcessHandler import com.intellij.execution.process.ProcessHandler import com.intellij.execution.process.ProcessTerminatedListener import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.components.service import com.intellij.openapi.project.Project open class TyeCommandLineState( environment: ExecutionEnvironment, private val runConfig: TyeRunConfiguration, private val project: Project ) : CommandLineState(environment) { override fun startProcess(): ProcessHandler { val tyeCliClient = project.service<TyeCliClient>() val options = buildOptions() val commandLine = tyeCliClient.run(options) val handler = OSProcessHandler(commandLine) handler.startNotify() ProcessTerminatedListener.attach(handler, environment.project) return handler } private fun buildOptions(): TyeCliClient.RunOptions = TyeCliClient.RunOptions( runConfig.pathArgument?.path ?: throw ExecutionException("Path argument not specified."), runConfig.portArgument, runConfig.noBuildArgument, runConfig.dockerArgument, runConfig.dashboardArgument, runConfig.verbosityArgument, runConfig.tagsArgument, runConfig.logsProvider.argumentName, if (runConfig.logsProvider.isProviderUrlEnabled()) runConfig.logsProviderUrl else null, runConfig.tracesProvider.argumentName, if (runConfig.tracesProvider.isProviderUrlEnabled()) runConfig.tracesProviderUrl else null ) }
0
Kotlin
0
0
6cfe645b1360a700085d17a450e59c80ec654e6e
1,801
tye-plugin
MIT License
src/main/kotlin/fr/pturpin/coursera/greedy/MaximumAdvertisementRevenue.kt
TurpIF
159,055,822
false
null
package fr.pturpin.coursera.greedy import java.util.* class MaximumAdvertisementRevenue { private val profitsPerClick = PriorityQueue<Int>() private val averageNumbersOfClicksPerDay = PriorityQueue<Int>() fun addProfitPerClick(profit: Int) { profitsPerClick.add(profit) } fun addAverageNumberOfClicksPerDay(numberOfClicks: Int) { averageNumbersOfClicksPerDay.add(numberOfClicks) } fun getMaximumSumOfProducts(): Long { var sum = 0L while (profitsPerClick.isNotEmpty() && averageNumbersOfClicksPerDay.isNotEmpty()) { val profit = profitsPerClick.remove() val numberOfClicks = averageNumbersOfClicksPerDay.remove() sum += profit.toLong() * numberOfClicks } return sum } } fun main(args: Array<String>) { val maximumAdvertisementRevenue = MaximumAdvertisementRevenue() readLine()!! // Ignored readLine()!!.split(" ") .map { it.toInt() } .forEach { maximumAdvertisementRevenue.addProfitPerClick(it) } readLine()!!.split(" ") .map { it.toInt() } .forEach { maximumAdvertisementRevenue.addAverageNumberOfClicksPerDay(it) } val maximumSumOfProducts = maximumAdvertisementRevenue.getMaximumSumOfProducts() print(maximumSumOfProducts) }
0
Kotlin
0
0
86860f8214f9d4ced7e052e008b91a5232830ea0
1,313
coursera-algo-toolbox
MIT License
src/main/kotlin/no/nav/fo/veilarbregistrering/enhet/adapter/OrganisasjonDto.kt
navikt
131,013,336
false
{"Kotlin": 892346, "PLpgSQL": 853, "PLSQL": 546, "Dockerfile": 87}
package no.nav.fo.veilarbregistrering.enhet.adapter class OrganisasjonDto(val organisasjonsnummer: String, val organisasjonDetaljer: OrganisasjonDetaljerDto)
17
Kotlin
5
6
b608c00bb1a2d1fce4fa7703b24f51e692ad5860
158
veilarbregistrering
MIT License
save-frontend-common/src/main/kotlin/com/saveourtool/save/frontend/common/components/basic/contests/PublicTestCardComponent.kt
saveourtool
300,279,336
false
{"Kotlin": 3413689, "SCSS": 86430, "JavaScript": 9061, "HTML": 8852, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366}
@file:Suppress("FILE_NAME_MATCH_CLASS", "FILE_WILDCARD_IMPORTS", "LargeClass") package com.saveourtool.save.frontend.components.basic.contests import com.saveourtool.save.frontend.common.components.basic.contests.PublicTestComponentProps import com.saveourtool.save.frontend.components.basic.* import com.saveourtool.save.frontend.externals.markdown.reactMarkdown import com.saveourtool.save.frontend.externals.markdown.rehype.rehypeHighlightPlugin import com.saveourtool.save.frontend.utils.* import com.saveourtool.save.test.TestFilesContent import com.saveourtool.save.testsuite.TestSuiteVersioned import js.core.jso import react.* import react.dom.html.ReactHTML.div import react.dom.html.ReactHTML.h6 import web.cssom.ClassName /** * Component that allows to see public tests */ val publicTestComponent = publicTestComponent() private val backgroundCard = cardComponent(hasBg = true, isPaddingBottomNull = true) private val publicTestCard = cardComponent(hasBg = true, isBordered = true, isPaddingBottomNull = true) /** * Contest creation component props */ external interface PublicTestComponentProps : Props { /** * Name of current contest */ var contestName: String /** * List of test suites attached to current contest */ var contestTestSuites: List<TestSuiteVersioned> } private fun ChildrenBuilder.displayTestLines(header: String, lines: List<String>, language: String? = null) = div { div { className = ClassName("text-xs text-center font-weight-bold text-primary text-uppercase mb-3") +header } val reactMarkdownOptions: dynamic = jso { this.children = wrapTestLines(lines, language) this.rehypePlugins = arrayOf(::rehypeHighlightPlugin) } publicTestCard { +reactMarkdown(reactMarkdownOptions) } } @Suppress( "TOO_LONG_FUNCTION", "LongMethod", "MAGIC_NUMBER", "AVOID_NULL_CHECKS" ) private fun publicTestComponent() = FC<PublicTestComponentProps> { props -> val (selectedTestSuite, setSelectedTestSuite) = useState<TestSuiteVersioned?>(null) val (publicTest, setPublicTest) = useState<TestFilesContent?>(null) useRequest(dependencies = arrayOf(selectedTestSuite)) { selectedTestSuite?.let { selectedTestSuite -> val response = get( "$apiUrl/contests/${props.contestName}/public-test?testSuiteId=${selectedTestSuite.id}", jsonHeaders, loadingHandler = ::loadingHandler, responseHandler = ::noopResponseHandler, ) if (response.ok) { val testFilesContent: TestFilesContent = response.decodeFromJsonString() setPublicTest(testFilesContent) } else { setPublicTest(TestFilesContent.empty) } } } if (props.contestTestSuites.isEmpty()) { h6 { className = ClassName("text-center") +"No public tests are provided yet." } } else { div { className = ClassName("d-flex justify-content-center") // ========== Test Suite Selector ========== div { className = ClassName("col-6") showAvailableTestSuites( props.contestTestSuites, selectedTestSuite?.let { listOf(it) } ?: emptyList(), null, ) { testSuite -> if (testSuite == selectedTestSuite) { setSelectedTestSuite(null) setPublicTest(null) } else { setSelectedTestSuite(testSuite) } } } // ========== Public test card ========== div { className = ClassName("col-6") publicTest?.let { publicTest -> div { if (publicTest.testLines.isEmpty()) { div { className = ClassName("text-center") +"Public tests are not provided for this test suite" } } else { backgroundCard { div { className = ClassName("ml-2 mr-2") div { className = ClassName("mt-3 mb-3") displayTestLines("Test", publicTest.testLines, publicTest.language) } publicTest.expectedLines?.let { div { className = ClassName("mt-3 mb-2") displayTestLines("Expected", it, publicTest.language) } } } } } } } } } } } private fun wrapTestLines(testLines: List<String>, language: String?) = """ |```${ language ?: "" } |${testLines.joinToString("\n")} |```""".trimMargin()
202
Kotlin
3
38
e101105f8e449253d5fbe81ece2668654d08639f
5,356
save-cloud
MIT License
save-frontend-common/src/main/kotlin/com/saveourtool/save/frontend/common/components/basic/contests/PublicTestCardComponent.kt
saveourtool
300,279,336
false
{"Kotlin": 3413689, "SCSS": 86430, "JavaScript": 9061, "HTML": 8852, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366}
@file:Suppress("FILE_NAME_MATCH_CLASS", "FILE_WILDCARD_IMPORTS", "LargeClass") package com.saveourtool.save.frontend.components.basic.contests import com.saveourtool.save.frontend.common.components.basic.contests.PublicTestComponentProps import com.saveourtool.save.frontend.components.basic.* import com.saveourtool.save.frontend.externals.markdown.reactMarkdown import com.saveourtool.save.frontend.externals.markdown.rehype.rehypeHighlightPlugin import com.saveourtool.save.frontend.utils.* import com.saveourtool.save.test.TestFilesContent import com.saveourtool.save.testsuite.TestSuiteVersioned import js.core.jso import react.* import react.dom.html.ReactHTML.div import react.dom.html.ReactHTML.h6 import web.cssom.ClassName /** * Component that allows to see public tests */ val publicTestComponent = publicTestComponent() private val backgroundCard = cardComponent(hasBg = true, isPaddingBottomNull = true) private val publicTestCard = cardComponent(hasBg = true, isBordered = true, isPaddingBottomNull = true) /** * Contest creation component props */ external interface PublicTestComponentProps : Props { /** * Name of current contest */ var contestName: String /** * List of test suites attached to current contest */ var contestTestSuites: List<TestSuiteVersioned> } private fun ChildrenBuilder.displayTestLines(header: String, lines: List<String>, language: String? = null) = div { div { className = ClassName("text-xs text-center font-weight-bold text-primary text-uppercase mb-3") +header } val reactMarkdownOptions: dynamic = jso { this.children = wrapTestLines(lines, language) this.rehypePlugins = arrayOf(::rehypeHighlightPlugin) } publicTestCard { +reactMarkdown(reactMarkdownOptions) } } @Suppress( "TOO_LONG_FUNCTION", "LongMethod", "MAGIC_NUMBER", "AVOID_NULL_CHECKS" ) private fun publicTestComponent() = FC<PublicTestComponentProps> { props -> val (selectedTestSuite, setSelectedTestSuite) = useState<TestSuiteVersioned?>(null) val (publicTest, setPublicTest) = useState<TestFilesContent?>(null) useRequest(dependencies = arrayOf(selectedTestSuite)) { selectedTestSuite?.let { selectedTestSuite -> val response = get( "$apiUrl/contests/${props.contestName}/public-test?testSuiteId=${selectedTestSuite.id}", jsonHeaders, loadingHandler = ::loadingHandler, responseHandler = ::noopResponseHandler, ) if (response.ok) { val testFilesContent: TestFilesContent = response.decodeFromJsonString() setPublicTest(testFilesContent) } else { setPublicTest(TestFilesContent.empty) } } } if (props.contestTestSuites.isEmpty()) { h6 { className = ClassName("text-center") +"No public tests are provided yet." } } else { div { className = ClassName("d-flex justify-content-center") // ========== Test Suite Selector ========== div { className = ClassName("col-6") showAvailableTestSuites( props.contestTestSuites, selectedTestSuite?.let { listOf(it) } ?: emptyList(), null, ) { testSuite -> if (testSuite == selectedTestSuite) { setSelectedTestSuite(null) setPublicTest(null) } else { setSelectedTestSuite(testSuite) } } } // ========== Public test card ========== div { className = ClassName("col-6") publicTest?.let { publicTest -> div { if (publicTest.testLines.isEmpty()) { div { className = ClassName("text-center") +"Public tests are not provided for this test suite" } } else { backgroundCard { div { className = ClassName("ml-2 mr-2") div { className = ClassName("mt-3 mb-3") displayTestLines("Test", publicTest.testLines, publicTest.language) } publicTest.expectedLines?.let { div { className = ClassName("mt-3 mb-2") displayTestLines("Expected", it, publicTest.language) } } } } } } } } } } } private fun wrapTestLines(testLines: List<String>, language: String?) = """ |```${ language ?: "" } |${testLines.joinToString("\n")} |```""".trimMargin()
202
Kotlin
3
38
e101105f8e449253d5fbe81ece2668654d08639f
5,356
save-cloud
MIT License
plugins/git4idea/tests/git4idea/history/GitFileHistoryTest.kt
hieuprogrammer
284,920,751
true
null
/* * Copyright 2000-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 git4idea.history import com.intellij.dvcs.DvcsUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.Executor import com.intellij.openapi.vcs.Executor.ourCurrentDir import com.intellij.openapi.vcs.Executor.touch import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.history.VcsFileRevision import com.intellij.util.CollectConsumer import com.intellij.util.Consumer import com.intellij.util.ExceptionUtil import com.intellij.vcsUtil.VcsUtil import git4idea.GitFileRevision import git4idea.test.* import junit.framework.TestCase import java.io.File import java.io.IOException import java.util.* class GitFileHistoryTest : GitSingleRepoTest() { fun `test commit message with escape sequence`() { touch("a.txt") add() val message = "Before \u001B[30;47mescaped\u001B[0m after" commit(message) val history = GitFileHistory.collectHistory(project, VcsUtil.getFilePath(projectRoot, "a.txt"), "-1") assertEquals("Commit message is incorrect", message, history[0].commitMessage) } // Inspired by IDEA-89347 @Throws(Exception::class) fun `test cyclic rename`() { val commits = ArrayList<TestCommit>() commits.add(add("PostHighlightingPass.java", Executor.mkdir("source"))) commits.add(modify(commits.last().file)) commits.add(move(commits.last().file, Executor.mkdir("codeInside-impl"))) commits.add(modify(commits.last().file)) commits.add(move(commits.last().file, Executor.mkdir("codeInside"))) commits.add(modify(commits.last().file)) commits.add(move(commits.last().file, Executor.mkdir("lang-impl"))) commits.add(modify(commits.last().file)) commits.add(move(commits.last().file, Executor.child("source"))) commits.add(modify(commits.last().file)) commits.add(move(commits.last().file, Executor.mkdir("java"))) commits.add(modify(commits.last().file)) commits.reverse() updateChangeListManager() val history = GitFileHistory.collectHistory(myProject, VcsUtil.getFilePath(commits.first().file)) assertSameHistory(commits, history) } @Throws(Exception::class) fun `test history`() { val commits = ArrayList<TestCommit>() commits.add(add("a.txt", ourCurrentDir())) commits.add(modify(commits.last().file)) commits.add(rename(commits.last().file, File(Executor.mkdir("dir"), "b.txt"))) for (i in 0..3) { commits.add(modify(commits.last().file)) } commits.reverse() val history = GitFileHistory.collectHistory(myProject, VcsUtil.getFilePath(commits.first().file)) assertSameHistory(commits, history) } @Throws(Exception::class) fun `test appendable history`() { val commits = ArrayList<TestCommit>() commits.add(add("a.txt", ourCurrentDir())) commits.add(modify(commits.last().file)) commits.add(rename(commits.last().file, File(Executor.mkdir("dir"), "b.txt"))) for (i in 0..3) { commits.add(modify(commits.last().file)) } commits.reverse() val history = ArrayList<GitFileRevision>() GitFileHistory.loadHistory(myProject, VcsUtil.getFilePath(commits.first().file), repo.root, null, CollectConsumer(history), Consumer { exception: VcsException -> TestCase.fail("No exception expected " + ExceptionUtil.getThrowableText(exception)) }) assertSameHistory(commits, history) } private fun assertSameHistory(expected: List<TestCommit>, actual: List<VcsFileRevision>) { TestCase.assertEquals("History size doesn't match. Actual history: \n" + toReadable(actual), expected.size, actual.size) TestCase.assertEquals("History is different.", toReadable(expected), toReadable(actual)) } private class TestCommit(val hash: String, val commitMessage: String, val file: File) private fun move(file: File, dir: File): TestCommit { repo.mv(file, dir) val message = "Moved ${file.path} to ${dir.name}" repo.addCommit(message) return TestCommit(last(), message, File(dir, file.name)) } private fun rename(file: File, newFile: File): TestCommit { repo.mv(file, newFile) val message = "Renamed ${file.path} to ${newFile.name}" repo.addCommit(message) return TestCommit(last(), message, newFile) } @Throws(IOException::class) private fun modify(file: File): TestCommit { FileUtil.appendToFile(file, "Modified") val message = "Modified ${file.path}" repo.addCommit(message) return TestCommit(last(), message, file) } private fun add(fileName: String, dir: File): TestCommit { val relativePath = dir.relativeTo(ourCurrentDir()).path val file = touch("$relativePath/$fileName", "Initial content") val message = "Created $fileName in ${dir.name}" repo.addCommit(message) return TestCommit(last(), message, file) } private fun toReadable(history: Collection<VcsFileRevision>): String { val maxSubjectLength = history.map { it.commitMessage?.length ?: 0 }.max() ?: 0 val sb = StringBuilder() for (revision in history) { val rev = revision as GitFileRevision val relPath = FileUtil.getRelativePath(File(projectPath), rev.path.ioFile) sb.append(String.format("%s %-" + maxSubjectLength + "s %s%n", DvcsUtil.getShortHash(rev.hash), rev.commitMessage, relPath)) } return sb.toString() } private fun toReadable(history: List<TestCommit>): String { val maxSubjectLength = history.map { it.commitMessage.length }.max() ?: 0 val sb = StringBuilder() for (commit in history) { val relPath = FileUtil.getRelativePath(File(projectPath), commit.file) sb.append(String.format("%s %-" + maxSubjectLength + "s %s%n", DvcsUtil.getShortHash(commit.hash), commit.commitMessage, relPath)) } return sb.toString() } }
1
null
1
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
6,440
intellij-community
Apache License 2.0
common/src/commonMain/kotlin/org/jetbrains/kotlinconf/presentation/SessionDetailsPresenter.kt
sensensen404
153,995,114
true
{"Kotlin": 108763, "Swift": 21923, "Ruby": 309}
package org.jetbrains.kotlinconf.presentation import org.jetbrains.kotlinconf.* import org.jetbrains.kotlinconf.data.* import kotlin.coroutines.* class SessionDetailsPresenter( private val uiContext: CoroutineContext, private val view: SessionDetailsView, private val sessionId: String, private val repository: DataRepository ) { private lateinit var session: SessionModel private var rating: SessionRating? = null private val onRefreshListener: () -> Unit = this::refreshDataFromRepo fun onCreate() { refreshDataFromRepo() repository.onRefreshListeners += onRefreshListener } fun onDestroy() { repository.onRefreshListeners -= onRefreshListener } fun rateSessionClicked(newRating: SessionRating) { launchAndCatch(uiContext, view::showError) { view.setRatingClickable(false) if (rating != newRating) { rating = newRating repository.addRating(sessionId, newRating) } else { rating = null repository.removeRating(sessionId) } view.setupRatingButtons(rating) } finally { view.setRatingClickable(true) } } fun onFavoriteButtonClicked() { launchAndCatch(uiContext, view::showError) { val isFavorite = isFavorite() repository.setFavorite(session.id, !isFavorite) } finally { refreshDataFromRepo() } } private fun refreshDataFromRepo() { session = repository.sessions?.firstOrNull { it.id == sessionId } ?: return view.updateView(isFavorite(), session) rating = repository.getRating(sessionId) view.setupRatingButtons(rating) } private fun isFavorite() = repository.favorites?.any { it.id == sessionId } ?: false }
1
Kotlin
1
0
8d8b0e758777a69c6ec8c1bfe2f3f4415ca1008b
1,872
kotlinconf-app
Apache License 2.0
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/application/CloseBehavior.kt
Xanik
282,687,897
true
{"Kotlin": 1516693, "Java": 96889}
package org.hexworks.zircon.api.application enum class CloseBehavior { EXIT_ON_CLOSE, DO_NOTHING_ON_CLOSE }
1
null
1
2
bf435cddeb55f7c3a9da5dd5c29be13af8354d0f
116
zircon
Apache License 2.0
src/nl/rubensten/texifyidea/inspections/latex/LatexInclusionLoopInspection.kt
xinsongyan
185,682,709
true
{"Markdown": 5, "Text": 1, "Ignore List": 1, "Kotlin": 234, "Java": 142, "JFlex": 2, "CODEOWNERS": 1, "XML": 3, "HTML": 60, "Python": 1}
package nl.rubensten.texifyidea.inspections.latex import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import nl.rubensten.texifyidea.algorithm.BFS import nl.rubensten.texifyidea.index.LatexCommandsIndex import nl.rubensten.texifyidea.insight.InsightGroup import nl.rubensten.texifyidea.inspections.TexifyInspectionBase import nl.rubensten.texifyidea.util.findInclusions import nl.rubensten.texifyidea.util.findRelativeFile import nl.rubensten.texifyidea.util.findRootFile import nl.rubensten.texifyidea.util.requiredParameter /** * @author <NAME> */ open class LatexInclusionLoopInspection : TexifyInspectionBase() { override fun getInspectionGroup() = InsightGroup.LATEX override fun getInspectionId() = "InclusionLoop" override fun getDisplayName() = "Inclusion loops" override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): MutableList<ProblemDescriptor> { val descriptors = descriptorList() // Run a BFS on all file inclusions to check for duplicate files. val root = file.findRootFile() val covered: MutableSet<PsiFile> = mutableSetOf(root) val duplicate: MutableSet<PsiFile> = HashSet() val bfs = BFS(root, PsiFile::findInclusions) bfs.setIterationAction { // Set that contains all the inclusions in the current file. // This is used to disregard files that have been included multiple times in the same file. val inThisFile = HashSet<PsiFile>() val inclusions = it.findInclusions() for (inclusion in inclusions) { if (covered.contains(inclusion) && inclusion !in inThisFile) { duplicate.add(inclusion) } covered.add(inclusion) inThisFile.add(inclusion) } BFS.BFSAction.CONTINUE } bfs.execute() // Look through all commands to see if they include duplicates. val commands = LatexCommandsIndex.getItems(file) for (cmd in commands) { val name = cmd.name if ("\\input" != name && "\\include" != name && "\\includeonly" != name) { continue } val param = cmd.requiredParameter(0) ?: continue val targetFile = root.findRelativeFile(param) if (!duplicate.contains(targetFile)) { continue } descriptors.add(manager.createProblemDescriptor( cmd, TextRange(name.length + 1, cmd.textLength - 1), "File inclusion loop found.", ProblemHighlightType.GENERIC_ERROR, isOntheFly )) } return descriptors } }
0
Kotlin
0
0
8d495a84477611412c3f2e68bc7e6dbff69f45e7
2,968
TeXiFy-IDEA
MIT License
src/main/kotlin/org/jetbrains/bio/span/Islands.kt
Ghazala-Sultan
407,095,932
true
{"Kotlin": 315618, "Shell": 920}
package org.jetbrains.bio.span import com.google.common.cache.Cache import com.google.common.cache.CacheBuilder import org.jetbrains.bio.dataframe.BitterSet import org.jetbrains.bio.dataframe.DataFrame import org.jetbrains.bio.experiments.fit.* import org.jetbrains.bio.genome.Chromosome import org.jetbrains.bio.genome.GenomeQuery import org.jetbrains.bio.genome.containers.genomeMap import org.jetbrains.bio.statistics.hypothesis.Fdr import org.jetbrains.bio.util.CancellableState import org.jetbrains.bio.viktor.F64Array import kotlin.math.ln import kotlin.math.log10 import kotlin.math.min /** * The islands are called in five steps. * * 1) Estimate posterior probabilities * 2) Pick bins with probability of H_0 <= nullProbabilityThreshold * 3) Using gap merge bins into islands (before q-values) * 4) Assign score to each island as median(log(ps)) * log(length) * 5) Compute qvalues on scores * * @param offsets All the data is binarized, so offsets stores positions in base pair. * @param fdr is used to limit False Discovery Rate at given level. * @param gap enriched bins yielded after FDR control are merged if distance is less or equal than gap. * @param nullProbabilityThreshold threshold to collect candidate islands * @param coverageDataFrame is used to compute either coverage or log fold change. */ internal fun SpanFitResults.getChromosomeIslands( logNullMemberships: F64Array, offsets: IntArray, chromosome: Chromosome, fdr: Double, gap: Int, nullProbabilityThreshold: Double, coverageDataFrame: DataFrame? = null ): List<Peak> { val logNullProbabilityThreshold = ln(nullProbabilityThreshold) val candidateBins = BitterSet(logNullMemberships.size) 0.until(candidateBins.size()) .filter { logNullMemberships[it] <= logNullProbabilityThreshold } .forEach(candidateBins::set) val candidateIslands = candidateBins.aggregate(gap) if (candidateIslands.isEmpty()) { return emptyList() } // Assign p-value like scores to merged peaks using SICER inspired scheme val islandsLogNullMemberships = F64Array(candidateIslands.size) { islandIndex -> // SICER scheme sum(-log(ps)) leads to huge bias towards long islands // Use median * log(length) val (i, j) = candidateIslands[islandIndex] val medianLogNullMembership = (i until j) .map { logNullMemberships[it] } .filter { it <= logNullProbabilityThreshold } .toDoubleArray().median() medianLogNullMembership * ln((j - i).toDouble()) } val islandQValues = islandsQValuesCache.get(Triple(this, chromosome, gap)) { Fdr.qvalidate(islandsLogNullMemberships) } val islands = candidateIslands.indices .filter { islandQValues[it] < fdr } .map { islandIndex -> val (i, j) = candidateIslands[islandIndex] val islandLogNullMembership = islandsLogNullMemberships[islandIndex] val islandQValue = islandQValues[islandIndex] val islandStart = offsets[i] val islandEnd = if (j < offsets.size) offsets[j] else chromosome.length // Score should be proportional to length of peak and average original q-value val score = min(1000.0, -log10(islandQValue)) // Value is either coverage of fold change var value = 0.0 if (coverageDataFrame != null) { if (coverageDataFrame.labels.size == 1 || coverageDataFrame.labels.all { it.startsWith(SpanPeakCallingExperiment.TRACK_PREFIX) } ) { value = coverageDataFrame.partialMean(i, j) } else if (coverageDataFrame.labels.all { it.startsWith(SpanDifferentialPeakCallingExperiment.TRACK1_PREFIX) || it.startsWith(SpanDifferentialPeakCallingExperiment.TRACK2_PREFIX) }) { val track1 = coverageDataFrame.partialMean(i, j, coverageDataFrame.labels .filter { it.startsWith(SpanDifferentialPeakCallingExperiment.TRACK1_PREFIX) }) val track2 = coverageDataFrame.partialMean(i, j, coverageDataFrame.labels .filter { it.startsWith(SpanDifferentialPeakCallingExperiment.TRACK2_PREFIX) }) // Value if LogFC value = if (track2 != 0.0) ln(track1) - ln(track2) else Double.MAX_VALUE } else { Peak.LOG.debug("Failed to compute value for ${coverageDataFrame.labels}") } } Peak( chromosome, islandStart, islandEnd, mlogpvalue = -islandLogNullMembership, mlogqvalue = -log10(islandQValue), value = value, score = score.toInt() ) } return islands } fun SpanFitResults.getIslands( genomeQuery: GenomeQuery, fdr: Double, gap: Int, nullProbabilityThreshold: Double, cancellableState: CancellableState? = null ): List<Peak> { val coverage = fitInfo.scoresDataFrame() if (coverage.isEmpty()) { SpanFitResults.LOG.debug("No coverage caches present, peak scores won't be computed.") } val map = genomeMap(genomeQuery, parallel = true) { chromosome -> cancellableState?.checkCanceled() // Check that we have information for requested chromosome if (chromosome.name in fitInfo.chromosomesSizes) { val f64LogNullMemberships = logNullMemberships[chromosome.name]!!.f64Array(SpanModelFitExperiment.NULL) val offsets = fitInfo.offsets(chromosome) getChromosomeIslands(f64LogNullMemberships, offsets, chromosome, fdr, gap, nullProbabilityThreshold, coverage[chromosome]) } else { SpanFitResults.LOG.debug("NO peaks information for chromosome: ${chromosome.name} in fitInfo ${fitInfo.build}") emptyList() } } return genomeQuery.get().flatMap { map[it] } } const val SPAN_ISLANDS_DEFAULT_NULL_PROBABILITY = 0.2 /** * During SPAN models optimizations we iterate over different FDR and GAPs parameters, * So Q-values estimation is superfluous for each parameters combination. * Use cache with weak values to avoid memory overflow. */ private val islandsQValuesCache: Cache<Triple<SpanFitResults, Chromosome, Int>, F64Array> = CacheBuilder.newBuilder().weakValues().build()
0
null
0
0
fd32082523e9ce859a70b4bc4a61bfc2d3f4d751
6,663
span
MIT License
core/src/main/kotlin/com/github/quillraven/darkmatter/ui/TextDialog.kt
Quillraven
255,084,653
false
null
package com.github.quillraven.darkmatter.ui import com.badlogic.gdx.scenes.scene2d.ui.Dialog import com.badlogic.gdx.utils.Align import com.badlogic.gdx.utils.I18NBundle import com.github.quillraven.darkmatter.V_HEIGHT_PIXELS import com.github.quillraven.darkmatter.V_WIDTH_PIXELS import ktx.actors.onClick import ktx.scene2d.Scene2DSkin import ktx.scene2d.label import ktx.scene2d.scene2d import ktx.scene2d.scrollPane import ktx.scene2d.textButton private const val ELEMENT_PADDING = 7f private const val DIALOG_WIDTH_SCALE = 0.95f private const val DIALOG_HEIGHT_SCALE = 0.75f private const val SCROLL_PANE_PAD_RIGHT = -7f // align with background frame border class TextDialog( bundle: I18NBundle, txtBundleKey: String ) : Dialog("", Scene2DSkin.defaultSkin, SkinWindow.DEFAULT.name) { init { buttonTable.defaults().padBottom(ELEMENT_PADDING) button(scene2d.textButton(bundle["close"], SkinTextButton.DEFAULT.name).apply { labelCell.padLeft(ELEMENT_PADDING).padRight(ELEMENT_PADDING) onClick { hide() } }) buttonTable.pack() contentTable.defaults().fill().expand() contentTable.add(scene2d.scrollPane(SkinScrollPane.DEFAULT.name) { setScrollbarsVisible(true) fadeScrollBars = false variableSizeKnobs = false label(bundle[txtBundleKey], SkinLabel.DEFAULT.name) { setWrap(true) setAlignment(Align.topLeft) } }).padRight(SCROLL_PANE_PAD_RIGHT) contentTable.pack() // we don't scale or rotate the dialog -> set transform to false to // avoid additional texture bindings and draw calls isTransform = false } override fun getPrefWidth() = V_WIDTH_PIXELS * DIALOG_WIDTH_SCALE override fun getPrefHeight() = V_HEIGHT_PIXELS * DIALOG_HEIGHT_SCALE }
0
Kotlin
9
51
676da9ddaec5b61e8ff08253cae99d01705dedb8
1,880
Dark-Matter
MIT License
app/src/main/java/com/roque/rueda/gbm/coding/challenge/ipc/IpcFragment.kt
RoqueRueda
496,494,846
false
{"Kotlin": 27661}
package com.roque.rueda.gbm.coding.challenge.ipc import android.os.Build import android.os.Bundle import android.util.DisplayMetrics import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.core.view.marginBottom import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.anychart.AnyChart import com.anychart.chart.common.dataentry.ValueDataEntry import com.google.android.material.snackbar.Snackbar import com.roque.rueda.gbm.coding.challenge.R import com.roque.rueda.gbm.coding.challenge.databinding.FragmentIpcBinding import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch /** * A simple [Fragment] subclass as the default destination in the navigation. */ @AndroidEntryPoint class IpcFragment : Fragment() { private var _binding: FragmentIpcBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! private val ipcViewModel: IpcViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentIpcBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupObservers() lifecycleScope.launchWhenResumed { ipcViewModel.fetchIpcIndex() } } private fun setupObservers() { lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { ipcViewModel.iuState.collect { when (it) { is IpcIndexUiState.Error -> showError(it) IpcIndexUiState.Loading -> showLoading() is IpcIndexUiState.Success -> showChartData(it) } } } } } private fun showChartData(success: IpcIndexUiState.Success) { val data = success.ipcIndexList val anyChartView = binding.anyChartView anyChartView.setProgressBar(binding.loadingIndicator) val cartesian = AnyChart.line() cartesian.title(getString(R.string.ipc_chart_title)) cartesian.yAxis(0).title(getString(R.string.price)) cartesian.xAxis(0).title(getString(R.string.date)) val chartData = data.map { ChartDataEntry(it.date.orEmpty(), it.price ?: 0.0) } cartesian.line(chartData) anyChartView.setChart(cartesian) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val windowMetrics = requireActivity().windowManager.currentWindowMetrics anyChartView.layoutParams.width = windowMetrics.bounds.width() - 30 anyChartView.layoutParams.height = windowMetrics.bounds.height() / 2 } else { val displayMetrics = DisplayMetrics() val windowMetrics = requireActivity().windowManager.defaultDisplay.getMetrics(displayMetrics) anyChartView.layoutParams.width = displayMetrics.widthPixels - 30 anyChartView.layoutParams.height = displayMetrics.heightPixels / 2 } } private fun showError(error: IpcIndexUiState.Error) { Snackbar.make(binding.anyChartView, error.errorResult.message, Snackbar.LENGTH_INDEFINITE) .setAnchorView(R.id.any_chart_view) .setAction("Retry") { ipcViewModel.fetchIpcIndex() } .show() } private fun showLoading() { binding.loadingIndicator.isVisible = true } override fun onDestroyView() { super.onDestroyView() _binding = null } private class ChartDataEntry(date: String, price: Number) : ValueDataEntry(date, price) }
0
Kotlin
0
0
b2d5365a6a2811cab1fa0a4eb0faec0c7aaa5a78
4,086
coding-challenge
MIT License
sphinx/application/data/features/feature-repository/src/main/java/chat/sphinx/feature_repository/mappers/feed/FeedModelDboPresenterMapper.kt
stakwork
340,103,148
false
{"Kotlin": 4002700, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453}
package chat.sphinx.feature_repository.mappers.feed import chat.sphinx.conceptcoredb.FeedModelDbo import chat.sphinx.feature_repository.mappers.ClassMapper import chat.sphinx.wrapper_feed.FeedModel import io.matthewnelson.concept_coroutines.CoroutineDispatchers internal class FeedModelDboPresenterMapper( dispatchers: CoroutineDispatchers, ): ClassMapper<FeedModelDbo, FeedModel>(dispatchers) { override suspend fun mapFrom(value: FeedModelDbo): FeedModel { return FeedModel( value.id, value.type, value.suggested, ) } override suspend fun mapTo(value: FeedModel): FeedModelDbo { return FeedModelDbo( value.id, value.type, value.suggested, ) } }
99
Kotlin
11
18
01d4be42df107d5e4fa8d2411f5390aeea60ea74
773
sphinx-kotlin
MIT License
app/src/main/java/com/kickstarter/ui/activities/compose/login/CreatePasswordScreen.kt
kickstarter
76,278,501
false
null
package com.kickstarter.ui.activities.compose import android.content.res.Configuration import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.Divider import androidx.compose.material.IconButton import androidx.compose.material.Scaffold import androidx.compose.material.ScaffoldState import androidx.compose.material.SnackbarHost import androidx.compose.material.Text import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.tooling.preview.Preview import com.kickstarter.R import com.kickstarter.libs.utils.extensions.validPassword import com.kickstarter.ui.compose.designsystem.KSErrorSnackbar import com.kickstarter.ui.compose.designsystem.KSHiddenTextInput import com.kickstarter.ui.compose.designsystem.KSLinearProgressIndicator import com.kickstarter.ui.compose.designsystem.KSTheme import com.kickstarter.ui.compose.designsystem.KSTheme.colors import com.kickstarter.ui.compose.designsystem.KSTheme.dimensions import com.kickstarter.ui.compose.designsystem.KSTheme.typography import com.kickstarter.ui.toolbars.compose.TopToolBar @Composable @Preview(name = "Light", uiMode = Configuration.UI_MODE_NIGHT_NO) @Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) fun ChangePasswordPreview() { KSTheme { ChangePasswordScreen( onBackClicked = { }, onAcceptButtonClicked = { _, _ -> }, showProgressBar = false, scaffoldState = rememberScaffoldState() ) } } @Composable fun ChangePasswordScreen( onBackClicked: () -> Unit, onAcceptButtonClicked: (currentPass: String, newPass: String) -> Unit, showProgressBar: Boolean, scaffoldState: ScaffoldState ) { var currentPassword by rememberSaveable { mutableStateOf("") } var newPasswordLine1 by rememberSaveable { mutableStateOf("") } var newPasswordLine2 by rememberSaveable { mutableStateOf("") } val acceptButtonEnabled = when { currentPassword.validPassword() && newPasswordLine1.validPassword() && newPasswordLine2.validPassword() && newPasswordLine1 == newPasswordLine2 -> true else -> false } val warningText = when { newPasswordLine1.validPassword() && newPasswordLine2.isNotEmpty() && newPasswordLine2 != newPasswordLine1 -> { stringResource(id = R.string.Passwords_matching_message) } newPasswordLine1.isNotEmpty() && newPasswordLine1.length < 6 -> { stringResource(id = R.string.Password_min_length_message) } else -> "" } val focusManager = LocalFocusManager.current Scaffold( scaffoldState = scaffoldState, topBar = { TopToolBar( title = stringResource(id = R.string.Change_password), titleColor = colors.kds_support_700, leftOnClickAction = onBackClicked, leftIconColor = colors.kds_support_700, backgroundColor = colors.kds_white, right = { IconButton( onClick = { onAcceptButtonClicked.invoke( currentPassword, newPasswordLine1 ) }, enabled = acceptButtonEnabled ) { Image( painter = painterResource(id = R.drawable.icon__check), contentDescription = null, colorFilter = ColorFilter.tint( color = if (acceptButtonEnabled) colors.kds_create_700 else colors.kds_support_300 ) ) } } ) }, snackbarHost = { SnackbarHost( hostState = scaffoldState.snackbarHostState, snackbar = { data -> KSErrorSnackbar(text = data.message) } ) } ) { padding -> Column( Modifier .background(colors.kds_support_100) .fillMaxSize() .verticalScroll(rememberScrollState()) .padding(padding) ) { AnimatedVisibility(visible = showProgressBar) { KSLinearProgressIndicator(modifier = Modifier.fillMaxWidth()) } Text( modifier = Modifier.padding(dimensions.paddingMedium), text = stringResource( id = R.string.Well_ask_you_to_sign_back_into_the_Kickstarter_app_once_youve_changed_your_password ), style = typography.body2, color = colors.kds_support_700 ) Column( Modifier .background(color = colors.kds_white) .padding(dimensions.paddingMedium) .fillMaxWidth() ) { KSHiddenTextInput( modifier = Modifier.fillMaxWidth(), onValueChanged = { currentPassword = it }, label = stringResource(id = R.string.Current_password), keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next), keyboardActions = KeyboardActions( onNext = { focusManager.moveFocus( focusDirection = FocusDirection.Down ) } ) ) Spacer(modifier = Modifier.height(dimensions.listItemSpacingMedium)) KSHiddenTextInput( modifier = Modifier.fillMaxWidth(), onValueChanged = { newPasswordLine1 = it }, label = stringResource(id = R.string.New_password), keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next), keyboardActions = KeyboardActions( onNext = { focusManager.moveFocus( focusDirection = FocusDirection.Down ) } ) ) Spacer(modifier = Modifier.height(dimensions.listItemSpacingMedium)) KSHiddenTextInput( modifier = Modifier.fillMaxWidth(), onValueChanged = { newPasswordLine2 = it }, label = stringResource(id = R.string.Confirm_password), keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), keyboardActions = KeyboardActions( onDone = { focusManager.clearFocus() } ) ) } Divider(color = colors.kds_support_300) AnimatedVisibility(visible = warningText.isNotEmpty()) { Text( modifier = Modifier.padding(dimensions.paddingMedium), text = warningText, style = typography.body2, color = colors.kds_support_700 ) } } } }
8
null
989
5,752
a9187fb484c4d12137c7919a2a53339d67cab0cb
8,701
android-oss
Apache License 2.0
feature-forecast/src/androidTest/java/de/niklasbednarczyk/nbweather/feature/forecast/screens/overview/models/ForecastOverviewModelsTest.kt
NiklasBednarczyk
529,683,941
false
{"Kotlin": 1300133}
package de.niklasbednarczyk.nbweather.feature.forecast.screens.overview.models import de.niklasbednarczyk.nbweather.core.common.settings.order.NBOrderModel import de.niklasbednarczyk.nbweather.core.common.string.NBString import de.niklasbednarczyk.nbweather.core.common.string.NBString.Companion.asString import de.niklasbednarczyk.nbweather.core.ui.R import de.niklasbednarczyk.nbweather.data.onecall.types.weather.WeatherConditionType import de.niklasbednarczyk.nbweather.data.onecall.types.weather.WeatherIconType import de.niklasbednarczyk.nbweather.feature.forecast.models.sunandmoon.SunAndMoonItem import de.niklasbednarczyk.nbweather.feature.forecast.screens.NBForecastModelsTest import org.junit.Test import java.util.Locale import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull class ForecastOverviewModelsTest : NBForecastModelsTest { @Test fun alerts_shouldConvertCorrectly() { // Arrange val nationalWeatherAlertsEmpty = createTestNationalWeatherAlerts(0) val nationalWeatherAlertsFull = createTestNationalWeatherAlerts(5) // Act val alertsEmpty = ForecastOverviewAlertsModel.from(nationalWeatherAlertsEmpty) val alertsFull = ForecastOverviewAlertsModel.from(nationalWeatherAlertsFull) // Assert assertNull(alertsEmpty) assertNotNull(alertsFull) } @Test fun alerts_eventName_shouldConvertCorrectly() { // Arrange val nationalWeatherAlertNull = createTestNationalWeatherAlert( eventNameText = null ) val nationalWeatherAlertNotNull1 = createTestNationalWeatherAlert( eventNameText = "Event Name 1" ) val nationalWeatherAlertNotNull2 = createTestNationalWeatherAlert( eventNameText = "Event Name 2" ) // Act val alertsNullFirst = ForecastOverviewAlertsModel.from( listOf( nationalWeatherAlertNull, nationalWeatherAlertNotNull1, nationalWeatherAlertNotNull2 ) ) val alertsNotNull1First = ForecastOverviewAlertsModel.from( listOf( nationalWeatherAlertNotNull1, nationalWeatherAlertNotNull2, nationalWeatherAlertNull ) ) val alertsNotNull2First = ForecastOverviewAlertsModel.from( listOf( nationalWeatherAlertNotNull2, nationalWeatherAlertNull, nationalWeatherAlertNotNull1 ) ) // Assert assertEquals( NBString.ResString(R.string.screen_forecast_overview_alerts_event_name_fallback) .asString(context), alertsNullFirst?.eventName.asString(context) ) assertEquals( nationalWeatherAlertNotNull1.eventName, alertsNotNull1First?.eventName, ) assertEquals( nationalWeatherAlertNotNull2.eventName, alertsNotNull2First?.eventName, ) } @Test fun alerts_otherAlertsText_shouldConvertCorrectly() { // Arrange val nationalWeatherAlertsSize1 = createTestNationalWeatherAlerts(1) val nationalWeatherAlertsSize2 = createTestNationalWeatherAlerts(2) val nationalWeatherAlertsSize3 = createTestNationalWeatherAlerts(3) // Act val alertsSize1 = ForecastOverviewAlertsModel.from(nationalWeatherAlertsSize1) val alertsSize2 = ForecastOverviewAlertsModel.from(nationalWeatherAlertsSize2) val alertsSize3 = ForecastOverviewAlertsModel.from(nationalWeatherAlertsSize3) // Assert assertNull(alertsSize1?.otherAlerts) assertEquals("+1", alertsSize2?.otherAlerts.asString(context)) assertEquals("+2", alertsSize3?.otherAlerts.asString(context)) } @Test fun currentWeather_shouldConvertCorrectly() { // Arrange val currentWeatherDataAllNull = createTestCurrentWeather( feelsLikeTemperatureValue = null, pressureValue = null, humidityValue = null, dewPointTemperatureValue = null, cloudinessValue = null, uvIndexValue = null, visibilityValue = null, windSpeedValue = null, windGustValue = null, windDegreesValue = null, rain1hVolumeValue = null, snow1hVolumeValue = null ) val currentWeatherDataOnly1NotNull = createTestCurrentWeather( feelsLikeTemperatureValue = 1.0, pressureValue = null, humidityValue = null, dewPointTemperatureValue = null, cloudinessValue = null, uvIndexValue = null, visibilityValue = null, windSpeedValue = null, windGustValue = null, windDegreesValue = null, rain1hVolumeValue = null, snow1hVolumeValue = null ) val currentWeatherDataAllNotNull = createTestCurrentWeather() val todayNull = createTestDailyForecast( probabilityOfPrecipitationValue = null ) val todayNotNull = createTestDailyForecast() // Act val currentWeatherAllNull = ForecastOverviewCurrentWeatherModel.from( currentWeather = currentWeatherDataAllNull, today = todayNull ) val currentWeatherOnly1NotNull = ForecastOverviewCurrentWeatherModel.from( currentWeather = currentWeatherDataOnly1NotNull, today = todayNull ) val currentWeatherAllNotNull = ForecastOverviewCurrentWeatherModel.from( currentWeather = currentWeatherDataAllNotNull, today = todayNotNull ) // Assert assertNull(currentWeatherAllNull) assertNotNull(currentWeatherOnly1NotNull) assertListDoesContain( currentWeatherOnly1NotNull.items, currentWeatherDataOnly1NotNull.feelsLikeTemperature ) assertListHasSize(currentWeatherOnly1NotNull.items, 1) assertNotNull(currentWeatherAllNotNull) assertListDoesContain( currentWeatherAllNotNull.items, currentWeatherDataAllNotNull.feelsLikeTemperature ) assertListDoesContain( currentWeatherAllNotNull.items, currentWeatherDataAllNotNull.pressure ) assertListDoesContain( currentWeatherAllNotNull.items, currentWeatherDataAllNotNull.humidity ) assertListDoesContain( currentWeatherAllNotNull.items, currentWeatherDataAllNotNull.dewPointTemperature ) assertListDoesContain( currentWeatherAllNotNull.items, currentWeatherDataAllNotNull.cloudiness ) assertListDoesContain( currentWeatherAllNotNull.items, currentWeatherDataAllNotNull.uvIndex ) assertListDoesContain( currentWeatherAllNotNull.items, currentWeatherDataAllNotNull.visibility ) assertListDoesContain( currentWeatherAllNotNull.items, currentWeatherDataAllNotNull.windSpeed ) assertListDoesContain( currentWeatherAllNotNull.items, currentWeatherDataAllNotNull.windGust ) assertListDoesContain( currentWeatherAllNotNull.items, currentWeatherDataAllNotNull.windDegrees ) assertListDoesContain( currentWeatherAllNotNull.items, currentWeatherDataAllNotNull.rain1hVolume ) assertListDoesContain( currentWeatherAllNotNull.items, currentWeatherDataAllNotNull.snow1hVolume ) assertListDoesContain( currentWeatherAllNotNull.items, todayNotNull.probabilityOfPrecipitation ) assertListHasSize(currentWeatherAllNotNull.items, 13) } @Test fun daily_shouldConvertCorrectly() { // Arrange val dailyForecastsEmpty = createTestDailyForecasts(0) val dailyForecastsLimitTemperaturesSame = listOf( createTestDailyForecast( temperatureMinDailyValue = 1.0, temperatureMaxDailyValue = 1.0 ), createTestDailyForecast( temperatureMinDailyValue = 1.0, temperatureMaxDailyValue = 1.0 ) ) val dailyForecastsLimitTemperaturesDifferent = listOf( createTestDailyForecast( temperatureMinDailyValue = 0.0, temperatureMaxDailyValue = 1.0 ), createTestDailyForecast( temperatureMinDailyValue = -1.0, temperatureMaxDailyValue = 0.0 ) ) // Act val dailyEmpty = ForecastOverviewDailyModel.from( timezoneOffset = testTimezoneOffset, dailyForecasts = dailyForecastsEmpty ) val dailyLimitTemperaturesSame = ForecastOverviewDailyModel.from( timezoneOffset = testTimezoneOffset, dailyForecasts = dailyForecastsLimitTemperaturesSame ) val dailyLimitTemperaturesDifferent = ForecastOverviewDailyModel.from( timezoneOffset = testTimezoneOffset, dailyForecasts = dailyForecastsLimitTemperaturesDifferent ) // Assert assertNull(dailyEmpty) assertNull(dailyLimitTemperaturesSame) assertNotNull(dailyLimitTemperaturesDifferent) assertListHasSize(dailyLimitTemperaturesDifferent.items, 2) assertEquals(-1.0, dailyLimitTemperaturesDifferent.minTemperatureTotalValue) assertEquals(1.0, dailyLimitTemperaturesDifferent.maxTemperatureTotalValue) } @Test fun daily_calcFactor_shouldCalculateCorrectly() { // Arrange val daily = ForecastOverviewDailyModel( items = emptyList(), maxTemperatureTotalValue = 10.0, minTemperatureTotalValue = -10.0 ) val currentPlus10 = 10.0 val currentPlus5 = 5.0 val current0 = 0.0 val currentMinus5 = -5.0 val currentMinus10 = -10.0 // Act val factorPlus10 = daily.calcFactor(currentPlus10) val factorPlus5 = daily.calcFactor(currentPlus5) val factor0 = daily.calcFactor(current0) val factorMinus5 = daily.calcFactor(currentMinus5) val factorMinus10 = daily.calcFactor(currentMinus10) // Assert assertEquals(0.00f, factorPlus10) assertEquals(0.25f, factorPlus5) assertEquals(0.50f, factor0) assertEquals(0.75f, factorMinus5) assertEquals(1.00f, factorMinus10) } @Test fun hourly_shouldConvertCorrectly() { // Arrange val hourlyForecastsEmpty = createTestHourlyForecasts(0) val hourlyForecastsWithOneNullValue = listOf( createTestHourlyForecast( forecastTimeValue = 1 ), createTestHourlyForecast( forecastTimeValue = null ), createTestHourlyForecast( forecastTimeValue = 3 ) ) val hourlyForecastsFull = createTestHourlyForecasts(3) // Act val hourlyEmpty = ForecastOverviewHourlyModel.from( timezoneOffset = testTimezoneOffset, hourlyForecasts = hourlyForecastsEmpty ) val hourlyWithOneNullValue = ForecastOverviewHourlyModel.from( timezoneOffset = testTimezoneOffset, hourlyForecasts = hourlyForecastsWithOneNullValue ) val hourlyFull = ForecastOverviewHourlyModel.from( timezoneOffset = testTimezoneOffset, hourlyForecasts = hourlyForecastsFull ) // Assert assertNull(hourlyEmpty) assertNull(hourlyWithOneNullValue) assertNotNull(hourlyFull) assertListHasSize(hourlyFull.itemPairs, 2) } @Test fun item_shouldConvertCorrectly() { // Arrange + Act val itemsEmpty = ForecastOverviewItem.from( timezoneOffset = null, currentWeather = null, minutelyForecasts = listOf(), hourlyForecasts = listOf(), dailyForecasts = listOf(), nationalWeatherAlerts = listOf(), today = null ) val itemsFull = ForecastOverviewItem.from( timezoneOffset = testTimezoneOffset, currentWeather = createTestCurrentWeather(), minutelyForecasts = createTestMinutelyForecasts(60), hourlyForecasts = createTestHourlyForecasts(3), dailyForecasts = createTestDailyForecasts(3), nationalWeatherAlerts = createTestNationalWeatherAlerts(3), today = createTestDailyForecast() ) // Assert assertNull(itemsEmpty) assertNotNull(itemsFull) assertListHasSize(itemsFull, 7) } @Test fun item_getSortOrder_shouldConvertCorrectly() { // Arrange val currentWeatherData = createTestCurrentWeather() val minutelyForecasts = createTestMinutelyForecasts(60) val hourlyForecasts = createTestHourlyForecasts(3) val dailyForecasts = createTestDailyForecasts(3) val nationalWeatherAlerts = createTestNationalWeatherAlerts(3) val today = createTestDailyForecast() val alerts = ForecastOverviewAlertsModel.from( nationalWeatherAlerts = nationalWeatherAlerts )!! val currentWeather = ForecastOverviewCurrentWeatherModel.from( currentWeather = currentWeatherData, today = today )!! val daily = ForecastOverviewDailyModel.from( timezoneOffset = testTimezoneOffset, dailyForecasts = dailyForecasts )!! val hourly = ForecastOverviewHourlyModel.from( timezoneOffset = testTimezoneOffset, hourlyForecasts = hourlyForecasts )!! val precipitation = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecasts )!! val summary = ForecastOverviewSummaryModel.from( timezoneOffset = testTimezoneOffset, currentWeather = currentWeatherData, today = today )!! val sunAndMoon = ForecastOverviewSunAndMoonModel.from( timezoneOffset = testTimezoneOffset, currentWeather = currentWeatherData, today = today )!! val order = NBOrderModel( currentWeatherOrder = 5, dailyOrder = 4, hourlyOrder = 3, precipitationOrder = 2, sunAndMoonOrder = 1 ) // Act val sortOrderAlerts = alerts.getSortOrder(order) val sortOrderCurrentWeather = currentWeather.getSortOrder(order) val sortOrderDaily = daily.getSortOrder(order) val sortOrderHourly = hourly.getSortOrder(order) val sortOrderPrecipitation = precipitation.getSortOrder(order) val sortOrderSummary = summary.getSortOrder(order) val sortOrderSunAndMoon = sunAndMoon.getSortOrder(order) // Assert assertEquals(-2, sortOrderAlerts) assertEquals(5, sortOrderCurrentWeather) assertEquals(4, sortOrderDaily) assertEquals(3, sortOrderHourly) assertEquals(2, sortOrderPrecipitation) assertEquals(-1, sortOrderSummary) assertEquals(1, sortOrderSunAndMoon) } @Test fun precipitation_headline_shouldConvertCorrectly() { // Arrange setLocale(Locale.US) val minutelyForecastsNone = createTestMinutelyForecasts(0.0) val minutelyForecastsFull = createTestMinutelyForecasts(1.0) val minutelyForecastsStartingOne = createTestMinutelyForecasts( precipitationValue0 = 0.0, precipitationValue1 = 1.0, precipitationValue2 = 0.0, precipitationValue3 = 0.0 ) val minutelyForecastsStartingOther = createTestMinutelyForecasts( precipitationValue0 = 0.0, precipitationValue1 = 0.0, precipitationValue2 = 1.0, precipitationValue3 = 0.0 ) val minutelyForecastsBreakingOne = createTestMinutelyForecasts( precipitationValue0 = 1.0, precipitationValue1 = 0.0, precipitationValue2 = 1.0, precipitationValue3 = 0.0 ) val minutelyForecastsBreakingOther = createTestMinutelyForecasts( precipitationValue0 = 1.0, precipitationValue1 = 1.0, precipitationValue2 = 0.0, precipitationValue3 = 1.0 ) val minutelyForecastsEndingOne = createTestMinutelyForecasts( precipitationValue0 = 1.0, precipitationValue1 = 0.0, precipitationValue2 = 0.0, precipitationValue3 = 0.0 ) val minutelyForecastsEndingOther = createTestMinutelyForecasts( precipitationValue0 = 1.0, precipitationValue1 = 1.0, precipitationValue2 = 0.0, precipitationValue3 = 0.0 ) // Act val precipitationNone = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsNone ) val precipitationFull = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsFull ) val precipitationStartingOne = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsStartingOne ) val precipitationStartingOther = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsStartingOther ) val precipitationBreakingOne = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsBreakingOne ) val precipitationBreakingOther = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsBreakingOther ) val precipitationEndingOne = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsEndingOne ) val precipitationEndingOther = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsEndingOther ) // Assert assertEquals( "No precipitation within an hour", precipitationNone?.headline.asString(context) ) assertEquals( "Precipitation won't end within an hour", precipitationFull?.headline.asString(context) ) assertEquals( "Precipitation starting in 1 minute", precipitationStartingOne?.headline.asString(context) ) assertEquals( "Precipitation starting in 2 minutes", precipitationStartingOther?.headline.asString(context) ) assertEquals( "A break in precipitation in 1 minute", precipitationBreakingOne?.headline.asString(context) ) assertEquals( "A break in precipitation in 2 minutes", precipitationBreakingOther?.headline.asString(context) ) assertEquals( "Precipitation ending in 1 minute", precipitationEndingOne?.headline.asString(context) ) assertEquals( "Precipitation ending in 2 minutes", precipitationEndingOther?.headline.asString(context) ) } @Test fun precipitation_precipitationFactors_shouldConvertCorrectly() { // Arrange val minutelyForecastsSize59 = createTestMinutelyForecasts(59) val minutelyForecastsSize60 = createTestMinutelyForecasts(60) val minutelyForecastsSize61 = createTestMinutelyForecasts(61) val minutelyForecastsOnlyMin = createTestMinutelyForecasts(Double.MIN_VALUE) val minutelyForecastsOnlyMax = createTestMinutelyForecasts(Double.MAX_VALUE) val expectedPrecipitationFactorsOnlyMin = List(60) { 0f } val expectedPrecipitationFactorsOnlyMax = List(60) { 1f } // Act val precipitationSize59 = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsSize59 ) val precipitationSize60 = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsSize60 ) val precipitationSize61 = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsSize61 ) val precipitationOnlyMin = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsOnlyMin ) val precipitationOnlyMax = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecastsOnlyMax ) // Assert assertNull(precipitationSize59) assertNotNull(precipitationSize60) assertListHasSize(precipitationSize60.precipitationFactors, 60) assertNotNull(precipitationSize61) assertListHasSize(precipitationSize61.precipitationFactors, 60) assertNotNull(precipitationOnlyMin) assertListsContainSameItems( expectedPrecipitationFactorsOnlyMin, precipitationOnlyMin.precipitationFactors ) assertNotNull(precipitationOnlyMax) assertListsContainSameItems( expectedPrecipitationFactorsOnlyMax, precipitationOnlyMax.precipitationFactors ) } @Test fun precipitation_times_shouldConvertCorrectly() { // Arrange val minutelyForecasts = createTestMinutelyForecasts(60) val expectedTime0Value = minutelyForecasts[0].forecastTime?.value val expectedTime15Value = minutelyForecasts[15].forecastTime?.value val expectedTime30Value = minutelyForecasts[30].forecastTime?.value val expectedTime45Value = minutelyForecasts[45].forecastTime?.value // Act val precipitation = ForecastOverviewPrecipitationModel.from( timezoneOffset = testTimezoneOffset, minutelyForecasts = minutelyForecasts ) // Assert assertValue(expectedTime0Value, precipitation?.time0?.dt?.value) assertValue(expectedTime15Value, precipitation?.time15?.dt?.value) assertValue(expectedTime30Value, precipitation?.time30?.dt?.value) assertValue(expectedTime45Value, precipitation?.time45?.dt?.value) } @Test fun summary_shouldConvertCorrectly() { // Arrange val currentWeather = createTestCurrentWeather( currentTimeValue = 1L, currentTemperatureValue = 2.0, weatherIcon = WeatherIconType.D_CLEAR_SKY, weatherCondition = WeatherConditionType.FOG ) val today = createTestDailyForecast( temperatureMinDailyValue = 3.0, temperatureMaxDailyValue = 4.0 ) // Act val summaryNull = ForecastOverviewSummaryModel.from( timezoneOffset = testTimezoneOffset, currentWeather = null, today = null ) val summaryNotNull = ForecastOverviewSummaryModel.from( timezoneOffset = testTimezoneOffset, currentWeather = currentWeather, today = today ) // Assert assertNull(summaryNull) assertNotNull(summaryNotNull) assertEquals( currentWeather.currentTemperature?.unitsValue?.value, summaryNotNull.currentTemperature.value.toDouble() ) assertEquals( today.temperature?.minDailyTemperature?.unitsValue?.value, summaryNotNull.minTemperature.unitsValue.value ) assertEquals( today.temperature?.maxDailyTemperature?.unitsValue?.value, summaryNotNull.maxTemperature.unitsValue.value ) assertEquals( currentWeather.weather?.icon, summaryNotNull.weatherIcon ) assertEquals( currentWeather.weather?.condition, summaryNotNull.weatherCondition ) assertEquals( currentWeather.currentTime?.value, summaryNotNull.currentTime.dt.value ) } @Test fun sunAndMoon_shouldConvertCorrectly() { // Arrange val currentWeather = createTestCurrentWeather() val today = createTestDailyForecast() // Act val sunAndMoonAllNull = ForecastOverviewSunAndMoonModel.from( timezoneOffset = testTimezoneOffset, currentWeather = null, today = null ) val sunAndMoonNullAndNotNull = ForecastOverviewSunAndMoonModel.from( timezoneOffset = testTimezoneOffset, currentWeather = null, today = today ) val sunAndMoonNotNullAndNull = ForecastOverviewSunAndMoonModel.from( timezoneOffset = testTimezoneOffset, currentWeather = currentWeather, today = null ) val sunAndMoonAllNotNull = ForecastOverviewSunAndMoonModel.from( timezoneOffset = testTimezoneOffset, currentWeather = currentWeather, today = today ) // Assert assertNull(sunAndMoonAllNull) assertNull(sunAndMoonNullAndNotNull) assertNull(sunAndMoonNotNullAndNull) assertNotNull(sunAndMoonAllNotNull) assertEquals(currentWeather.currentTime?.value, sunAndMoonAllNotNull.currentTime.dt.value) assertListHasSize(sunAndMoonAllNotNull.items, 3) val moonPhase = sunAndMoonAllNotNull.items.getFirstItemFromList(SunAndMoonItem.MoonPhase::class.java) val moonTimes = sunAndMoonAllNotNull.items.getFirstItemFromList(SunAndMoonItem.MoonTimes::class.java) val sunTimes = sunAndMoonAllNotNull.items.getFirstItemFromList(SunAndMoonItem.SunTimes::class.java) assertEquals(today.moonPhase, moonPhase.moonPhase) assertEquals(today.moonrise?.value, moonTimes.moonrise.dt.value) assertEquals(today.moonset?.value, moonTimes.moonset.dt.value) assertEquals(today.sunrise?.value, sunTimes.sunrise.dt.value) assertEquals(today.sunset?.value, sunTimes.sunset.dt.value) } }
15
Kotlin
0
1
e10dbb86dc6e37eda9dba29dd1ee51aa19c4477d
27,312
NBWeather
MIT License
app/src/main/java/com/nedaluof/radiox/domain/usecase/radiostations/RadioStationsRemoteMediator.kt
nedaluof
837,587,136
false
{"Kotlin": 38016}
package com.nedaluof.radiox.domain.usecase.radiostations import androidx.paging.ExperimentalPagingApi import androidx.paging.LoadType import androidx.paging.PagingState import androidx.paging.RemoteMediator import com.nedaluof.radiox.data.datasource.local.db.entities.RadioStationEntity import com.nedaluof.radiox.data.datasource.local.db.entities.RadioStationPagingKeyEntity import com.nedaluof.radiox.data.datasource.remote.response.asEntity import com.nedaluof.radiox.data.repository.RadioStationsRepository import kotlinx.coroutines.delay import timber.log.Timber import java.util.concurrent.TimeUnit /** * Created By NedaluOf - 6/30/2024. */ @OptIn(ExperimentalPagingApi::class) class RadioStationsRemoteMediator( private val countryCode: String, private val repository: RadioStationsRepository ) : RemoteMediator<Int, RadioStationEntity>() { override suspend fun initialize(): InitializeAction { val cacheTimeout = TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS) return if (System.currentTimeMillis() - (repository.getLastCreationTimeOfPagingKey() ?: 0) < cacheTimeout ) { InitializeAction.SKIP_INITIAL_REFRESH } else { InitializeAction.LAUNCH_INITIAL_REFRESH } } private suspend fun getPagingKeyClosestToCurrentPosition(state: PagingState<Int, RadioStationEntity>): RadioStationPagingKeyEntity? { return state.anchorPosition?.let { position -> state.closestItemToPosition(position)?.let { entity -> repository.getRadioStationPagingKeyById(entity.id) } } } private suspend fun getPagingKeyForFirstItem(state: PagingState<Int, RadioStationEntity>): RadioStationPagingKeyEntity? { return state.pages.firstOrNull { it.data.isNotEmpty() }?.data?.firstOrNull()?.let { entity -> repository.getRadioStationPagingKeyById(entity.id) } } private suspend fun getPagingKeyForLastItem(state: PagingState<Int, RadioStationEntity>): RadioStationPagingKeyEntity? { return state.pages.lastOrNull { it.data.isNotEmpty() }?.data?.lastOrNull()?.let { entity -> repository.getRadioStationPagingKeyById(entity.id) } } override suspend fun load( loadType: LoadType, state: PagingState<Int, RadioStationEntity> ): MediatorResult { val currentPage: Int = when (loadType) { LoadType.REFRESH -> { val pagingKey = getPagingKeyClosestToCurrentPosition(state) pagingKey?.nextKey?.minus(PAGE) ?: PAGE } LoadType.PREPEND -> { val pagingKey = getPagingKeyForFirstItem(state) pagingKey?.prevKey ?: return MediatorResult.Success(endOfPaginationReached = pagingKey != null) } LoadType.APPEND -> { val pagingKey = getPagingKeyForLastItem(state) pagingKey?.nextKey ?: PAGE } } try { val apiResponse = repository.loadRadioStations(countryCode, currentPage) val radioStations = apiResponse.body()?.map { dto -> dto.asEntity() } val dataList = radioStations ?: emptyList() val endOfPaginationReached = dataList.isEmpty() /** * to avoid rate limit error from the api owners * which is 100 request per minute * */ delay(1000) repository.transactionBlock { if (loadType == LoadType.REFRESH) { //clear tables if LoadType is REFRESH repository.clearRadioStationPagingKeyTable() repository.clearRadioStationsTable() } //calculate new keys val prevKey = if (currentPage > PAGE) currentPage - PAGE else null val nextKey = if (endOfPaginationReached) null else currentPage + PAGE val pagingKeys = dataList.map { station -> RadioStationPagingKeyEntity( station.stationUuid ?: "", prevKey, currentPage, nextKey, ) } repository.insertRadioStationPagingKeys(pagingKeys) repository.insertRadioStationEntitiesList(dataList) } return MediatorResult.Success(endOfPaginationReached = endOfPaginationReached) } catch (exception: Exception) { Timber.e(exception.message) return MediatorResult.Error(exception) } } companion object { private const val PAGE = 1 } }
0
Kotlin
0
0
5b25a9c07515580d118e61aa0bc1ca51dbf29718
4,249
RadioX
Apache License 2.0
app/src/main/java/com/verma/gitman/repository/GithubRepo.kt
RedVrma
739,808,431
false
{"Kotlin": 38253}
package com.verma.gitman.repository import com.apollographql.apollo.api.Response import com.verma.gitsearch.api.GithubService import schema.github.GetUserFollowersQuery import schema.github.GetUserFollowingQuery import schema.github.GetUserProfileQuery import schema.github.SearchUsersQuery class GithubRepo(private val githubService: GithubService) { suspend fun getUsers(q: String, endCursor: String?): Response<SearchUsersQuery.Data> { return githubService.getUsers(q, endCursor) } suspend fun getUserProfile(login: String): Response<GetUserProfileQuery.Data> { return githubService.getUserProfile(login) } suspend fun getUserFollowers( login: String, endCursor: String? ): Response<GetUserFollowersQuery.Data> { return githubService.getUserFollowers(login, endCursor) } suspend fun getUserFollowing( login: String, endCursor: String? ): Response<GetUserFollowingQuery.Data> { return githubService.getUserFollowing(login, endCursor) } }
0
Kotlin
0
0
9d14ec8487ec06534a6e70ef0d4ee3a1e54173f6
1,052
Gitman---Github-Api-consumption-using-GraphQl
Apache License 2.0
app/src/main/java/eu/kanade/tachiyomi/widget/preference/LibrarySyncPreference.kt
TachiWeb
66,624,691
false
null
package eu.kanade.tachiyomi.widget.preference import android.content.Context import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceViewHolder import android.util.AttributeSet import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.librarysync.LibrarySyncManager import kotlinx.android.synthetic.main.preference_widget_imageview_switch.view.* import uy.kohesive.injekt.injectLazy class LibrarySyncPreference @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : Preference(context, attrs) { val sync: LibrarySyncManager by injectLazy() init { widgetLayoutResource = R.layout.preference_widget_imageview_switch } var imageResource: Int? = null override fun onAttached() { super.onAttached() updatePreferenceUI() } /** * Select correct status icon and set correct summary */ fun updatePreferenceUI() { imageResource = if (getPrefValue()) { //Sync enabled if (sync.syncAvailable) { //Sync is working if (sync.lastFailedSyncCount > 5) { //But last 5+ syncs have failed! setSummary(R.string.sync_status_error_many_failed) R.drawable.ic_warning_yellow_24dp } else { //Sync is OK setSummary(R.string.sync_status_ok) R.drawable.ic_done_green_24dp } } else { //Something is wrong with sync setSummary(sync.syncError) R.drawable.ic_warning_yellow_24dp } } else { //Sync not enabled setSummary(R.string.sync_status_not_enabled) android.R.color.transparent } } override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) //Set selected status icon holder.itemView.switch_image_view.setImageResource(imageResource!!) //Set switch value holder.itemView.switch_switch_view.setOnCheckedChangeListener(null) holder.itemView.switch_switch_view.isChecked = getPrefValue() holder.itemView.switch_switch_view.setOnCheckedChangeListener { compoundButton, b -> persistBoolean(b) notifyChanged() } } private fun getPrefValue() = getPersistedBoolean(false) override fun onClick() { super.onClick() persistBoolean(!getPrefValue()) notifyChanged() } public override fun notifyChanged() { super.notifyChanged() updatePreferenceUI() } }
0
null
0
5
9dac958ed1414338dfff825c8d7dbe78fb98209a
2,694
tachiyomi
Apache License 2.0
compiler/testData/codegen/box/controlStructures/tryCatchInExpressions/unmatchedInlineMarkers.kt
JakeWharton
99,388,807
false
null
inline fun catchAll(x: String, block: () -> Unit): String { try { block() } catch (e: Throwable) { } return x } inline fun throwIt(msg: String) { throw Exception(msg) } inline fun bar(x: String): String = x + catchAll("") { throwIt("oops!") } fun box(): String = bar("OK")
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
320
kotlin
Apache License 2.0
consumer/src/test/kotlin/integrations/kafka/SchemaRegistryContainer.kt
neo4j-contrib
125,791,389
false
null
package integrations.kafka import org.testcontainers.containers.GenericContainer import org.testcontainers.containers.wait.strategy.Wait import org.testcontainers.containers.KafkaContainer import org.testcontainers.containers.KafkaContainer.KAFKA_PORT import org.testcontainers.containers.Network import org.testcontainers.containers.SocatContainer import java.util.stream.Stream class SchemaRegistryContainer(version: String): GenericContainer<SchemaRegistryContainer>("confluentinc/cp-schema-registry:$version") { private lateinit var proxy: SocatContainer override fun doStart() { val networkAlias = networkAliases[0] proxy = SocatContainer() .withNetwork(network) .withTarget(PORT, networkAlias) proxy.start() waitingFor(Wait.forHttp("/subjects") .forPort(PORT) .forStatusCode(200)) super.doStart() } fun withKafka(kafka: KafkaContainer): SchemaRegistryContainer { return withKafka(kafka.network, kafka.networkAliases.map { "PLAINTEXT://$it:9092" }.joinToString(",")) } fun withKafka(network: Network, bootstrapServers: String): SchemaRegistryContainer { withNetwork(network) withEnv("SCHEMA_REGISTRY_HOST_NAME", "schema-registry") withEnv("SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS", bootstrapServers) return self() } fun getSchemaRegistryUrl() = "http://${proxy.containerIpAddress}:${proxy.firstMappedPort}" override fun stop() { Stream.of(Runnable { super.stop() }, Runnable { proxy.stop() }).parallel().forEach { it.run() } } companion object { @JvmStatic val PORT = 8081 } }
105
Kotlin
60
149
6bfff36e717a1c869f632a48684e15df1c992e08
1,713
neo4j-streams
Apache License 2.0
app/src/main/java/xyz/sentrionic/harmony/persistence/StoryQueryUtils.kt
sentrionic
220,498,638
false
{"Kotlin": 325826}
package xyz.sentrionic.harmony.persistence import androidx.lifecycle.LiveData import xyz.sentrionic.harmony.models.StoryPost import xyz.sentrionic.harmony.persistence.StoryQueryUtils.Companion.ORDER_BY_ASC_DATE_UPDATED import xyz.sentrionic.harmony.persistence.StoryQueryUtils.Companion.ORDER_BY_ASC_USERNAME import xyz.sentrionic.harmony.persistence.StoryQueryUtils.Companion.ORDER_BY_DESC_DATE_UPDATED import xyz.sentrionic.harmony.persistence.StoryQueryUtils.Companion.ORDER_BY_DESC_USERNAME class StoryQueryUtils { companion object{ private val TAG: String = "AppDebug" // values const val STORY_ORDER_ASC: String = "" const val STORY_ORDER_DESC: String = "-" const val STORY_FILTER_USERNAME = "username" const val STORY_FILTER_DATE_PUBLISHED = "date_published" val ORDER_BY_ASC_DATE_UPDATED = STORY_ORDER_ASC + STORY_FILTER_DATE_PUBLISHED val ORDER_BY_DESC_DATE_UPDATED = STORY_ORDER_DESC + STORY_FILTER_DATE_PUBLISHED val ORDER_BY_ASC_USERNAME = STORY_ORDER_ASC + STORY_FILTER_USERNAME val ORDER_BY_DESC_USERNAME = STORY_ORDER_DESC + STORY_FILTER_USERNAME } } fun StoryPostDao.returnOrderedStoryQuery( query: String, filterAndOrder: String, page: Int ): LiveData<List<StoryPost>> { when { filterAndOrder.contains(ORDER_BY_DESC_DATE_UPDATED) ->{ return searchStoryPostsOrderByDateDESC( query = query, page = page) } filterAndOrder.contains(ORDER_BY_ASC_DATE_UPDATED) ->{ return searchStoryPostsOrderByDateASC( query = query, page = page) } filterAndOrder.contains(ORDER_BY_DESC_USERNAME) ->{ return searchStoryPostsOrderByAuthorDESC( query = query, page = page) } filterAndOrder.contains(ORDER_BY_ASC_USERNAME) ->{ return searchStoryPostsOrderByAuthorASC( query = query, page = page) } else -> return searchStoryPostsOrderByDateASC( query = query, page = page ) } }
0
Kotlin
0
1
0751148a2566ad11098ddd7f122cade7c1792dc3
2,195
HarmonyApp
MIT License
keel-scm/src/test/kotlin/com/netflix/spinnaker/keel/preview/PreviewEnvironmentCodeEventListenerTests.kt
spinnaker
107,462,081
false
null
package com.netflix.spinnaker.keel.preview import com.netflix.spectator.api.Registry import com.netflix.spectator.api.Tag import com.netflix.spectator.api.Timer import com.netflix.spinnaker.keel.api.ArtifactReferenceProvider import com.netflix.spinnaker.keel.api.DeliveryConfig import com.netflix.spinnaker.keel.api.DependencyType.LOAD_BALANCER import com.netflix.spinnaker.keel.api.DependencyType.SECURITY_GROUP import com.netflix.spinnaker.keel.api.Dependent import com.netflix.spinnaker.keel.api.Environment import com.netflix.spinnaker.keel.api.Moniker import com.netflix.spinnaker.keel.api.Monikered import com.netflix.spinnaker.keel.api.PreviewEnvironmentSpec import com.netflix.spinnaker.keel.api.Resource import com.netflix.spinnaker.keel.api.artifacts.ArtifactOriginFilter import com.netflix.spinnaker.keel.api.artifacts.branchName import com.netflix.spinnaker.keel.api.artifacts.branchStartsWith import com.netflix.spinnaker.keel.api.ec2.ClusterDependencies import com.netflix.spinnaker.keel.api.ec2.ClusterSpec import com.netflix.spinnaker.keel.api.ec2.EC2_CLUSTER_V1 import com.netflix.spinnaker.keel.api.ec2.EC2_CLUSTER_V1_1 import com.netflix.spinnaker.keel.api.ec2.EC2_SECURITY_GROUP_V1 import com.netflix.spinnaker.keel.api.ec2.SecurityGroupSpec import com.netflix.spinnaker.keel.api.ec2.old.ClusterV1Spec import com.netflix.spinnaker.keel.api.ec2.old.ClusterV1Spec.ImageProvider import com.netflix.spinnaker.keel.core.api.ManualJudgementConstraint import com.netflix.spinnaker.keel.core.api.SubmittedDeliveryConfig import com.netflix.spinnaker.keel.core.api.SubmittedEnvironment import com.netflix.spinnaker.keel.core.api.TagAmiPostDeployAction import com.netflix.spinnaker.keel.core.name import com.netflix.spinnaker.keel.front50.Front50Cache import com.netflix.spinnaker.keel.front50.model.Application import com.netflix.spinnaker.keel.front50.model.DataSources import com.netflix.spinnaker.keel.front50.model.ManagedDeliveryConfig import com.netflix.spinnaker.keel.igor.DeliveryConfigImporter import com.netflix.spinnaker.keel.notifications.DeliveryConfigImportFailed import com.netflix.spinnaker.keel.notifications.DismissibleNotification import com.netflix.spinnaker.keel.persistence.DismissibleNotificationRepository import com.netflix.spinnaker.keel.persistence.EnvironmentDeletionRepository import com.netflix.spinnaker.keel.persistence.KeelRepository import com.netflix.spinnaker.keel.preview.PreviewEnvironmentCodeEventListener.Companion.APPLICATION_RETRIEVAL_ERROR import com.netflix.spinnaker.keel.preview.PreviewEnvironmentCodeEventListener.Companion.CODE_EVENT_COUNTER import com.netflix.spinnaker.keel.preview.PreviewEnvironmentCodeEventListener.Companion.COMMIT_HANDLING_DURATION import com.netflix.spinnaker.keel.preview.PreviewEnvironmentCodeEventListener.Companion.DELIVERY_CONFIG_NOT_FOUND import com.netflix.spinnaker.keel.preview.PreviewEnvironmentCodeEventListener.Companion.PREVIEW_ENVIRONMENT_MARK_FOR_DELETION_SUCCESS import com.netflix.spinnaker.keel.preview.PreviewEnvironmentCodeEventListener.Companion.PREVIEW_ENVIRONMENT_UPSERT_ERROR import com.netflix.spinnaker.keel.preview.PreviewEnvironmentCodeEventListener.Companion.PREVIEW_ENVIRONMENT_UPSERT_SUCCESS import com.netflix.spinnaker.keel.resources.ResourceFactory import com.netflix.spinnaker.keel.resources.ResourceSpecIdentifier import com.netflix.spinnaker.keel.resources.SpecMigrator import com.netflix.spinnaker.keel.scm.DELIVERY_CONFIG_RETRIEVAL_ERROR import com.netflix.spinnaker.keel.scm.DELIVERY_CONFIG_RETRIEVAL_SUCCESS import com.netflix.spinnaker.keel.scm.PrDeclinedEvent import com.netflix.spinnaker.keel.scm.PrDeletedEvent import com.netflix.spinnaker.keel.scm.PrMergedEvent import com.netflix.spinnaker.keel.scm.PrOpenedEvent import com.netflix.spinnaker.keel.scm.PrUpdatedEvent import com.netflix.spinnaker.keel.scm.ScmUtils import com.netflix.spinnaker.keel.scm.toTags import com.netflix.spinnaker.keel.test.DummyArtifactReferenceResourceSpec import com.netflix.spinnaker.keel.test.DummyLocatableResourceSpec import com.netflix.spinnaker.keel.test.DummyResourceSpec import com.netflix.spinnaker.keel.test.applicationLoadBalancer import com.netflix.spinnaker.keel.test.configuredTestObjectMapper import com.netflix.spinnaker.keel.test.debianArtifact import com.netflix.spinnaker.keel.test.dockerArtifact import com.netflix.spinnaker.keel.test.locatableResource import com.netflix.spinnaker.keel.test.resource import com.netflix.spinnaker.keel.test.submittedResource import com.netflix.spinnaker.keel.test.titusCluster import com.netflix.spinnaker.keel.validators.DeliveryConfigValidator import com.netflix.spinnaker.kork.exceptions.SystemException import com.netflix.spinnaker.time.MutableClock import dev.minutest.TestContextBuilder import dev.minutest.junit.JUnit5Minutests import dev.minutest.rootContext import io.mockk.called import io.mockk.just import io.mockk.mockk import io.mockk.runs import io.mockk.slot import io.mockk.spyk import org.springframework.context.ApplicationEventPublisher import strikt.api.expect import strikt.api.expectThat import strikt.assertions.contains import strikt.assertions.containsExactlyInAnyOrder import strikt.assertions.containsKeys import strikt.assertions.isA import strikt.assertions.isEmpty import strikt.assertions.isEqualTo import strikt.assertions.isLessThanOrEqualTo import strikt.assertions.one import java.time.Clock import java.time.Duration import io.mockk.coEvery as every import io.mockk.coVerify as verify class PreviewEnvironmentCodeEventListenerTests : JUnit5Minutests { class Fixture { private val objectMapper = configuredTestObjectMapper() private val clock: Clock = MutableClock() val fakeTimer: Timer = mockk() val repository: KeelRepository = mockk() val environmentDeletionRepository: EnvironmentDeletionRepository = mockk() val notificationRepository: DismissibleNotificationRepository = mockk() val importer: DeliveryConfigImporter = mockk() val front50Cache: Front50Cache = mockk() val springEnv: org.springframework.core.env.Environment = mockk() val spectator: Registry = mockk() val eventPublisher: ApplicationEventPublisher = mockk() val validator: DeliveryConfigValidator = mockk() val scmUtils: ScmUtils = mockk() // need to copy/paste this here because it's in keel-ec2-plugin val ec2ClusterMigrator = object : SpecMigrator<ClusterV1Spec, ClusterSpec> { override val input = EC2_CLUSTER_V1 override val output = EC2_CLUSTER_V1_1 override fun migrate(spec: ClusterV1Spec): ClusterSpec = with(spec) { ClusterSpec( moniker = moniker, artifactReference = imageProvider?.reference, deployWith = deployWith, locations = locations, _defaults = defaults, overrides = overrides ) } } val resourceFactory: ResourceFactory = spyk( ResourceFactory( objectMapper = objectMapper, resourceSpecIdentifier = ResourceSpecIdentifier(EC2_CLUSTER_V1, EC2_CLUSTER_V1_1), specMigrators = listOf(ec2ClusterMigrator) ) ) val subject = spyk( PreviewEnvironmentCodeEventListener( repository = repository, environmentDeletionRepository = environmentDeletionRepository, notificationRepository = notificationRepository, deliveryConfigImporter = importer, deliveryConfigValidator = validator, front50Cache = front50Cache, objectMapper = objectMapper, springEnv = springEnv, spectator = spectator, clock = clock, eventPublisher = eventPublisher, scmUtils = scmUtils, resourceFactory = resourceFactory ) ) val appConfig = Application( name = "fnord", email = "<EMAIL>", repoType = "stash", repoProjectKey = "myorg", repoSlug = "myrepo", dataSources = DataSources(enabled = emptyList(), disabled = emptyList()) ) val dockerFromMain = dockerArtifact() val dockerFromBranch = dockerFromMain.copy( reference = "docker-from-branch", from = ArtifactOriginFilter(branch = branchStartsWith("feature/")) ) val dockerWithNonMatchingFilter = dockerFromBranch.copy( reference = "fnord-non-matching", from = ArtifactOriginFilter(branch = branchName("not-the-right-branch")) ) val applicationLoadBalancer = applicationLoadBalancer() val cluster = titusCluster(artifact = dockerFromMain) val defaultAppSecurityGroup = Resource( kind = EC2_SECURITY_GROUP_V1.kind, metadata = mapOf("id" to "fnord", "application" to "fnord"), spec = SecurityGroupSpec( moniker = Moniker("fnord"), locations = cluster.spec.locations, description = "default app security group" ) ) val defaultElbSecurityGroup = Resource( kind = EC2_SECURITY_GROUP_V1.kind, metadata = mapOf("id" to "fnord", "application" to "fnord"), spec = SecurityGroupSpec( moniker = Moniker("fnord", "elb"), locations = cluster.spec.locations, description = "default load balancer security group" ) ) val clusterNamedAfterApp = titusCluster( moniker = Moniker("fnord"), artifact = dockerFromMain ) val clusterWithDependencies = titusCluster( moniker = Moniker("fnord", "dependent"), artifact = dockerFromMain ).run { copy( spec = spec.copy( _defaults = spec.defaults.copy( dependencies = ClusterDependencies( loadBalancerNames = setOf(applicationLoadBalancer.name), securityGroupNames = setOf(defaultAppSecurityGroup.name, defaultElbSecurityGroup.name) ) ) ) ) } val debianFromMain = debianArtifact() val debianFromBranch = debianFromMain.copy( reference = "debian-from-branch", from = ArtifactOriginFilter(branchStartsWith("feature/")) ) val clusterWithOldSpecVersion = resource( kind = EC2_CLUSTER_V1.kind, spec = ClusterV1Spec( moniker = Moniker("fnord", "old"), imageProvider = ImageProvider(debianFromMain.reference), locations = applicationLoadBalancer.spec.locations ) ) var deliveryConfig = DeliveryConfig( application = "fnord", name = "myconfig", serviceAccount = "<EMAIL>", artifacts = setOf(dockerFromMain, dockerFromBranch, debianFromMain, debianFromBranch), environments = setOf( Environment( name = "test", resources = setOf( applicationLoadBalancer, cluster, clusterNamedAfterApp, // name conflict with default sec group, but different kind defaultAppSecurityGroup, defaultElbSecurityGroup, clusterWithDependencies, clusterWithOldSpecVersion ), constraints = setOf(ManualJudgementConstraint()), postDeploy = listOf(TagAmiPostDeployAction()) ) ), previewEnvironments = setOf( PreviewEnvironmentSpec( branch = branchStartsWith("feature/"), baseEnvironment = "test" ) ) ) val previewEnv = slot<Environment>() fun setupMocks() { every { springEnv.getProperty("keel.previewEnvironments.enabled", Boolean::class.java, true) } returns true every { spectator.counter(any(), any<Iterable<Tag>>()) } returns mockk { every { increment() } just runs } every { validator.validate(any()) } just runs every { spectator.timer(any(), any<Iterable<Tag>>()) } returns fakeTimer every { fakeTimer.record(any<Duration>()) } just runs every { eventPublisher.publishEvent(any<Object>()) } just runs every { repository.allDeliveryConfigs(any()) } returns setOf(deliveryConfig) every { front50Cache.applicationByName(deliveryConfig.application) } returns appConfig every { importer.import(any(), manifestPath = any()) } returns with(deliveryConfig) { SubmittedDeliveryConfig( application = application, name = name, serviceAccount = serviceAccount, metadata = metadata, artifacts = artifacts, previewEnvironments = previewEnvironments, environments = environments.map { env -> SubmittedEnvironment( name = env.name, resources = env.resources.map { res -> submittedResource(res.kind, res.spec) }.toSet(), constraints = env.constraints, postDeploy = env.postDeploy ) }.toSet() ) } every { repository.upsertResource<DummyResourceSpec>(any(), any()) } just runs every { repository.storeEnvironment(any(), capture(previewEnv)) } just runs every { environmentDeletionRepository.markForDeletion(any()) } just runs every { notificationRepository.dismissNotification(any<Class<DismissibleNotification>>(), any(), any()) } returns true every { scmUtils.getPullRequestLink(any()) } returns "https://commit-link.org" } } val prOpenedEvent = PrOpenedEvent( repoKey = "stash/myorg/myrepo", pullRequestBranch = "feature/abc", targetBranch = "main", pullRequestId = "42" ) val prUpdatedEvent = PrUpdatedEvent( repoKey = "stash/myorg/myrepo", pullRequestBranch = "feature/abc", targetBranch = "main", pullRequestId = "42" ) val prMergedEvent = PrMergedEvent( repoKey = "stash/myorg/myrepo", pullRequestBranch = "feature/abc", targetBranch = "main", pullRequestId = "42", commitHash = "a34afb13b" ) val prDeclinedEvent = PrDeclinedEvent( repoKey = "stash/myorg/myrepo", pullRequestBranch = "feature/abc", targetBranch = "main", pullRequestId = "42" ) val prDeletedEvent = PrDeletedEvent( repoKey = "stash/myorg/myrepo", pullRequestBranch = "feature/abc", targetBranch = "main", pullRequestId = "42" ) fun tests() = rootContext<Fixture> { fixture { Fixture() } context("a delivery config exists in a branch") { before { setupMocks() } listOf(prOpenedEvent, prUpdatedEvent).forEach { prEvent -> context("a PR event matching a preview environment spec is received") { before { subject.handlePrEvent(prEvent) } test("the delivery config is imported from the branch in the PR event") { verify(exactly = 1) { importer.import( codeEvent = any(), manifestPath = any(), ) } } test("delivery config import failure notification is dismissed on successful import") { verify { notificationRepository.dismissNotification( any<Class<DismissibleNotification>>(), deliveryConfig.application, prEvent.pullRequestBranch, any() ) } } test("a successful delivery config retrieval is counted") { val tags = mutableListOf<Iterable<Tag>>() verify { spectator.counter(CODE_EVENT_COUNTER, capture(tags)) } expectThat(tags).one { contains(DELIVERY_CONFIG_RETRIEVAL_SUCCESS.toTags()) } } test("a successful preview environment upsert is counted") { val tags = mutableListOf<Iterable<Tag>>() verify { spectator.counter(CODE_EVENT_COUNTER, capture(tags)) } expectThat(tags).one { contains(PREVIEW_ENVIRONMENT_UPSERT_SUCCESS.toTags()) } } test("a duration is recorded for successful handling of the PR event") { verify(exactly = 1) { spectator.timer(COMMIT_HANDLING_DURATION, any<Iterable<Tag>>()) fakeTimer.record(any<Duration>()) } } test("a preview environment and associated resources are created/updated") { previewEnv.captured.resources.forEach { previewResource -> verify { repository.upsertResource(previewResource, deliveryConfig.name) } } verify { repository.storeEnvironment(deliveryConfig.name, previewEnv.captured) } } test("the preview environment has no constraints or post-deploy actions") { expectThat(previewEnv.captured.constraints).isEmpty() expectThat(previewEnv.captured.postDeploy).isEmpty() } test("the name of the preview environment is generated correctly") { val baseEnv = deliveryConfig.environments.first() val branchDetail = prEvent.pullRequestBranch.toPreviewName() expectThat(previewEnv.captured) { get { name }.isEqualTo("${baseEnv.name}-$branchDetail") } } test("relevant metadata is added to the preview environment") { expectThat(previewEnv.captured.metadata).containsKeys("basedOn", "repoKey", "branch", "pullRequestId") } test("resources are migrated to their latest version before processing") { val baseEnv = deliveryConfig.environments.first() verify(exactly = baseEnv.resources.size) { resourceFactory.migrate(any()) } @Suppress("DEPRECATION") expect { that(clusterWithOldSpecVersion.kind) .isEqualTo(EC2_CLUSTER_V1.kind) that(previewEnv.captured.resources.find { it.basedOn == clusterWithOldSpecVersion.id }!!.kind) .isEqualTo(EC2_CLUSTER_V1_1.kind) } } test("the name of monikered resources is updated with branch detail") { val baseEnv = deliveryConfig.environments.first() val baseResource = baseEnv.resources.first() as Resource<Monikered> val previewResource = previewEnv.captured.resources.first() expectThat(previewResource.spec) .isA<Monikered>() .get { moniker } .isEqualTo(subject.withBranchDetail(baseResource, prEvent.pullRequestBranch).spec.moniker) } test("updated resource names respect the max allowed length") { // monikered resources with and without stack and detail listOf( locatableResource(moniker = Moniker(app = "fnord", stack = "stack", detail = "detail")), locatableResource(moniker = Moniker(app = "fnord", stack = "stack")), locatableResource(moniker = Moniker(app = "fnord")), ).forEach { resource -> val updatedName = subject.withBranchDetail(resource, "feature/a-very-long-branch-name").name expectThat(updatedName.length) .describedAs("length of preview resource name $updatedName (${updatedName.length})") .isLessThanOrEqualTo(MAX_RESOURCE_NAME_LENGTH) } } test("updated resource names are DNS-compatible") { val resource = locatableResource(moniker = Moniker(app = "fnord")) val updatedName = subject.withBranchDetail(resource, "feature/a_branch_name_with_underscores").name expectThat(updatedName).not().contains("_") } test("the artifact reference in a resource is updated to match the preview environment branch filter") { expectThat(previewEnv.captured.resources.find { it.basedOn == cluster.id }?.spec) .isA<ArtifactReferenceProvider>() .get { artifactReference }.isEqualTo(dockerFromBranch.reference) expectThat(previewEnv.captured.resources.find { it.basedOn == clusterWithOldSpecVersion.id }?.spec) // this also demonstrates that the old cluster spec gets migrated and now supports the standard artifact reference interface .isA<ArtifactReferenceProvider>() .get { artifactReference }.isEqualTo(debianFromBranch.reference) } test("the names of resource dependencies present in the preview environment are adjusted to match") { val branchDetail = prEvent.pullRequestBranch.toPreviewName() val dependency = applicationLoadBalancer expectThat(previewEnv.captured.resources.find { it.basedOn == clusterWithDependencies.id }?.spec) .isA<Dependent>() .get { dependsOn.first { it.type == LOAD_BALANCER }.name } .isEqualTo(dependency.spec.moniker.withBranchDetail(branchDetail).name) } test("the names of the default security groups are not changed in the dependencies") { expectThat(previewEnv.captured.resources.find { it.basedOn == clusterWithDependencies.id }?.spec) .isA<Dependent>() .get { dependsOn.filter { it.type == SECURITY_GROUP }.map { it.name }.toSet() } .containsExactlyInAnyOrder(defaultAppSecurityGroup.name, defaultElbSecurityGroup.name) } } context("without an artifact in the delivery config matching the branch filter") { modifyFixture { deliveryConfig = deliveryConfig.run { copy( artifacts = artifacts.map { if (it == dockerFromBranch) dockerWithNonMatchingFilter else it }.toSet() ) } } before { setupMocks() // to pick up the updated delivery config above subject.handlePrEvent(prEvent) } test("the artifact reference in a resource is not updated") { expectThat(previewEnv.captured.resources.find { it.basedOn == cluster.id }?.spec) .isA<ArtifactReferenceProvider>() .get { artifactReference }.isEqualTo(dockerFromMain.reference) } } } context("an app with custom manifest path") { val manifestPath = "custom/spinnaker.yml" before { every { front50Cache.applicationByName(deliveryConfig.application) } returns appConfig.copy(managedDelivery = ManagedDeliveryConfig(manifestPath = manifestPath)) } test("importing the manifest from the correct path") { subject.handlePrEvent(prOpenedEvent) verify(exactly = 1) { importer.import( codeEvent = any(), manifestPath = manifestPath ) } } } context("a PR event NOT matching a preview environment spec is received") { before { val nonMatchingPrEvent = prOpenedEvent.copy(pullRequestBranch = "not-a-match") subject.handlePrEvent(nonMatchingPrEvent) } testEventIgnored() test("a delivery config not found is counted") { val tags = mutableListOf<Iterable<Tag>>() verify { spectator.counter(CODE_EVENT_COUNTER, capture(tags)) } expectThat(tags).one { contains(DELIVERY_CONFIG_NOT_FOUND.toTags()) } } test("duration metric is not recorded") { verify { fakeTimer wasNot called } } } context("a PR event not associated with a PR is received") { before { subject.handlePrEvent(prOpenedEvent.copy(pullRequestId = "-1")) } testEventIgnored() } listOf(prMergedEvent, prDeclinedEvent, prDeletedEvent).forEach { prEvent -> context("a ${prEvent::class.simpleName} event matching a preview environment spec is received") { before { // just to trigger saving the preview environment subject.handlePrEvent(prEvent) every { repository.getDeliveryConfig(deliveryConfig.name) } returns deliveryConfig.copy( environments = deliveryConfig.environments + setOf(previewEnv.captured) ) subject.handlePrFinished(prEvent) } test("the matching preview environment is marked for deletion") { verify { environmentDeletionRepository.markForDeletion(previewEnv.captured) } } test("a metric is counted for successfully marking for deletion") { val tags = mutableListOf<Iterable<Tag>>() verify { spectator.counter(CODE_EVENT_COUNTER, capture(tags)) } expectThat(tags).one { contains(PREVIEW_ENVIRONMENT_MARK_FOR_DELETION_SUCCESS.toTags()) } } } } } context("a PR event matching a preview spec branch filter but from a different app's repo") { before { setupMocks() every { front50Cache.applicationByName("fnord") } returns appConfig.copy( repoProjectKey = "anotherorg", repoSlug = "another-repo" ) subject.handlePrEvent(prOpenedEvent) } test("event is ignored") { verify(exactly = 0) { repository.upsertResource<DummyLocatableResourceSpec>(any(), deliveryConfig.name) repository.upsertResource<DummyArtifactReferenceResourceSpec>(any(), deliveryConfig.name) repository.storeEnvironment(deliveryConfig.name, any()) } verify { importer wasNot called } } } context("with feature flag disabled") { modifyFixture { every { springEnv.getProperty("keel.previewEnvironments.enabled", Boolean::class.java, true) } returns false } before { val nonMatchingPrEvent = prOpenedEvent.copy(pullRequestBranch = "not-a-match") subject.handlePrEvent(nonMatchingPrEvent) } testEventIgnored() } context("other error scenarios") { before { setupMocks() } context("failure to retrieve delivery config") { modifyFixture { every { importer.import(any(), manifestPath = any()) } throws SystemException("oh noes!") } before { subject.handlePrEvent(prOpenedEvent) } test("a delivery config retrieval error is counted") { val tags = mutableListOf<Iterable<Tag>>() verify { spectator.counter(CODE_EVENT_COUNTER, capture(tags)) } expectThat(tags).one { contains(DELIVERY_CONFIG_RETRIEVAL_ERROR.toTags()) } } test("an event is published") { verify { eventPublisher.publishEvent(any<DeliveryConfigImportFailed>()) } } } context("failure to retrieve application") { modifyFixture { every { front50Cache.applicationByName(deliveryConfig.application) } throws SystemException("oh noes!") } before { subject.handlePrEvent(prOpenedEvent) } test("an application retrieval error is counted") { val tags = mutableListOf<Iterable<Tag>>() verify { spectator.counter(CODE_EVENT_COUNTER, capture(tags)) } expectThat(tags).one { contains(APPLICATION_RETRIEVAL_ERROR.toTags()) } } } context("failure to upsert preview environment") { modifyFixture { every { repository.storeEnvironment(any(), any()) } throws SystemException("oh noes!") } before { subject.handlePrEvent(prOpenedEvent) } test("an upsert error is counted") { val tags = mutableListOf<Iterable<Tag>>() verify { spectator.counter(CODE_EVENT_COUNTER, capture(tags)) } expectThat(tags).one { contains(PREVIEW_ENVIRONMENT_UPSERT_ERROR.toTags()) } } } } } private fun TestContextBuilder<Fixture, Fixture>.testEventIgnored() { test("event is ignored") { verify(exactly = 0) { repository.upsertResource<DummyLocatableResourceSpec>(any(), deliveryConfig.name) repository.upsertResource<DummyArtifactReferenceResourceSpec>(any(), deliveryConfig.name) repository.storeEnvironment(deliveryConfig.name, any()) } verify { importer wasNot called } } } }
13
null
132
99
6115964c42e863cfd269616a836145b883f165f3
28,815
keel
Apache License 2.0
mobile/src/main/java/com/siliconlabs/bledemo/Bluetooth/BLE/TimeoutGattCallback.kt
SiliconLabs
85,345,875
false
null
package com.siliconlabs.bledemo.bluetooth.ble import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCallback abstract class TimeoutGattCallback : BluetoothGattCallback() { open fun onTimeout() {} open fun onMaxRetriesExceeded(gatt: BluetoothGatt) {} }
20
Kotlin
70
96
a4e476451c17abaa67b1ba85c81dd6146e5c5715
284
EFRConnect-android
Apache License 2.0
app/src/main/java/org/sil/storyproducer/viewmodel/SlideViewModelBuilder.kt
sillsdev
93,890,166
false
{"Kotlin": 819773, "HTML": 168357, "Java": 164820, "Dockerfile": 1612, "Shell": 770}
package org.sil.storyproducer.viewmodel import android.text.Layout import org.sil.storyproducer.model.PhaseType import org.sil.storyproducer.model.Slide import org.sil.storyproducer.model.SlideType import org.sil.storyproducer.model.Workspace import org.sil.storyproducer.tools.media.graphics.TextOverlay import java.text.SimpleDateFormat import java.util.* class SlideViewModelBuilder( val slide: Slide ) { fun build(): SlideViewModel { return SlideViewModel( buildOverlayText(), buildScriptureText(), buildScriptureReference() ) } fun buildScriptureText(): String { return slide.content } fun buildScriptureReference(): String { return arrayOf(slide.reference, slide.subtitle, slide.title) .firstOrNull { it.isNotEmpty() } .orEmpty() } fun buildOverlayText(): TextOverlay? { return if (Workspace.activePhase.phaseType == PhaseType.LEARN) buildOverlayText(false, true) else buildOverlayText(false, false) } fun buildOverlayText(dispStory: Boolean = false, origTitle: Boolean = false) : TextOverlay? { //There is no text overlay on normal slides or "no slides" if(!dispStory){ if(slide.slideType in arrayOf(SlideType.NUMBEREDPAGE, SlideType.NONE )) return null } val tOverlay = when(slide.slideType) { SlideType.FRONTCOVER -> getFrontCoverOverlayText(origTitle) else -> TextOverlay(slide.translatedContent) } val fontSize : Int = when(slide.slideType){ SlideType.FRONTCOVER, SlideType.ENDPAGE -> 32 SlideType.COPYRIGHT -> 12 SlideType.NUMBEREDPAGE, SlideType.LOCALSONG, SlideType.NONE -> 12 } tOverlay.setFontSize(fontSize) if(slide.slideType in arrayOf(SlideType.NUMBEREDPAGE,SlideType.LOCALSONG)) tOverlay.setVerticalAlign(Layout.Alignment.ALIGN_OPPOSITE) return tOverlay } private fun getFrontCoverOverlayText(origTitle: Boolean): TextOverlay { return if (origTitle) TextOverlay(getFrontCoverTitle()) else TextOverlay(slide.translatedContent) } internal fun getFrontCoverTitle(): String { return slide.content .replace("Title ideas:", "Title ideas:\n") .split("\n") .filterNot { it.isEmpty() } .elementAtOrNull(1).orEmpty().trim() // The 'first title idea' is the text we want to show. .let { "\\[[^\\]]*\\]?".toRegex().replace(it, "") } // Drop any content within square brackets. .let { "[\\.\\!\\?].*".toRegex().replace(it, "") } // remove everything after a .!? if there is one .let { "\\s+".toRegex().replace(it, " ") } // Make all double spaces one space. } }
95
Kotlin
8
5
a3dd3fc194f62c21fcf1b49a34bae454c35a3c88
2,928
StoryProducer
MIT License
src/main/kotlin/com/cognifide/gradle/aem/base/vlt/SyncTask.kt
shwinnbin
148,231,699
true
{"Kotlin": 260207, "Shell": 5207, "Java": 1813, "Batchfile": 233}
package com.cognifide.gradle.aem.base.vlt import com.cognifide.gradle.aem.api.AemDefaultTask open class SyncTask : AemDefaultTask() { companion object { val NAME = "aemSync" } init { description = "Check out then clean JCR content." } }
0
Kotlin
0
0
e913b5f11b9dc0ed6e27908f3cd3c26ba47ba544
272
gradle-aem-plugin
Apache License 2.0
compose/compiler/compiler-hosted/integration-tests/src/test/java/androidx/compose/compiler/plugins/kotlin/ComposerParamTransformTests.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 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.compiler.plugins.kotlin import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction import org.jetbrains.kotlin.ir.declarations.IrValueParameter import org.jetbrains.kotlin.ir.expressions.IrGetValue import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid import org.junit.Test class ComposerParamTransformTests : ComposeIrTransformTest() { private fun composerParam( source: String, expectedTransformed: String, validator: (element: IrElement) -> Unit = { }, dumpTree: Boolean = false ) = verifyComposeIrTransform( """ @file:OptIn( ExperimentalComposeApi::class, InternalComposeApi::class, ComposeCompilerApi::class ) package test import androidx.compose.runtime.ExperimentalComposeApi import androidx.compose.runtime.InternalComposeApi import androidx.compose.runtime.ComposeCompilerApi import androidx.compose.runtime.Composable import androidx.compose.runtime.ComposableContract $source """.trimIndent(), expectedTransformed, "", validator, dumpTree ) @Test fun testCallingProperties(): Unit = composerParam( """ val bar: Int @Composable get() { return 123 } @ComposableContract(restartable = false) @Composable fun Example() { bar } """, """ val bar: Int get() { %composer.startReplaceableGroup(<>, "C:Test.kt#2487m") val tmp0 = 123 %composer.endReplaceableGroup() return tmp0 } @ComposableContract(restartable = false) @Composable fun Example(%composer: Composer<*>?, %changed: Int) { %composer.startReplaceableGroup(<>, "C(Example)<bar>:Test.kt#2487m") bar %composer.endReplaceableGroup() } """ ) @Test fun testAbstractComposable(): Unit = composerParam( """ abstract class BaseFoo { @ComposableContract(restartable = false) @Composable abstract fun bar() } class FooImpl : BaseFoo() { @ComposableContract(restartable = false) @Composable override fun bar() {} } """, """ @StabilityInferred(parameters = 0) abstract class BaseFoo { @ComposableContract(restartable = false) @Composable abstract fun bar(%composer: Composer<*>?, %changed: Int) static val %stable: Int = 0 } @StabilityInferred(parameters = 0) class FooImpl : BaseFoo { @ComposableContract(restartable = false) @Composable override fun bar(%composer: Composer<*>?, %changed: Int) { %composer.startReplaceableGroup(<>, "C(bar):Test.kt#2487m") %composer.endReplaceableGroup() } static val %stable: Int = 0 } """ ) @Test fun testLocalClassAndObjectLiterals(): Unit = composerParam( """ @ComposableContract(restartable = false) @Composable fun Wat() {} @ComposableContract(restartable = false) @Composable fun Foo(x: Int) { Wat() @ComposableContract(restartable = false) @Composable fun goo() { Wat() } class Bar { @ComposableContract(restartable = false) @Composable fun baz() { Wat() } } goo() Bar().baz() } """, """ @ComposableContract(restartable = false) @Composable fun Wat(%composer: Composer<*>?, %changed: Int) { %composer.startReplaceableGroup(<>, "C(Wat):Test.kt#2487m") %composer.endReplaceableGroup() } @ComposableContract(restartable = false) @Composable fun Foo(x: Int, %composer: Composer<*>?, %changed: Int) { %composer.startReplaceableGroup(<>, "C(Foo)<Wat()>,<goo()>,<baz()>:Test.kt#2487m") Wat(%composer, 0) @ComposableContract(restartable = false) @Composable fun goo(%composer: Composer<*>?, %changed: Int) { %composer.startReplaceableGroup(<>, "C(goo)<Wat()>:Test.kt#2487m") Wat(%composer, 0) %composer.endReplaceableGroup() } class Bar { @ComposableContract(restartable = false) @Composable fun baz(%composer: Composer<*>?, %changed: Int) { %composer.startReplaceableGroup(<>, "C(baz)<Wat()>:Test.kt#2487m") Wat(%composer, 0) %composer.endReplaceableGroup() } } goo(%composer, 0) Bar().baz(%composer, 0) %composer.endReplaceableGroup() } """ ) @Test fun testNonComposableCode(): Unit = composerParam( """ fun A() {} val b: Int get() = 123 fun C(x: Int) { var x = 0 x++ class D { fun E() { A() } val F: Int get() = 123 } val g = object { fun H() {} } } fun I(block: () -> Unit) { block() } fun J() { I { I { A() } } } """, """ fun A() { } val b: Int get() { return 123 } fun C(x: Int) { var x = 0 x++ class D { fun E() { A() } val F: Int get() { return 123 } } val g = object { fun H() { } } } fun I(block: Function0<Unit>) { block() } fun J() { I { I { A() } } } """ ) @Test fun testCircularCall(): Unit = composerParam( """ @ComposableContract(restartable = false) @Composable fun Example() { Example() } """, """ @ComposableContract(restartable = false) @Composable fun Example(%composer: Composer<*>?, %changed: Int) { %composer.startReplaceableGroup(<>, "C(Example)<Exampl...>:Test.kt#2487m") Example(%composer, 0) %composer.endReplaceableGroup() } """ ) @Test fun testInlineCall(): Unit = composerParam( """ @Composable inline fun Example(content: @Composable () -> Unit) { content() } @ComposableContract(restartable = false) @Composable fun Test() { Example {} } """, """ @Composable fun Example(content: Function2<Composer<*>, Int, Unit>, %composer: Composer<*>?, %changed: Int) { %composer.startReplaceableGroup(<>, "C(Example)<conten...>:Test.kt#2487m") content(%composer, 0b1110 and %changed) %composer.endReplaceableGroup() } @ComposableContract(restartable = false) @Composable fun Test(%composer: Composer<*>?, %changed: Int) { %composer.startReplaceableGroup(<>, "C(Test)<Exampl...>:Test.kt#2487m") Example({ %composer: Composer<*>?, %changed: Int -> %composer.startReplaceableGroup(<>, "C:Test.kt#2487m") if (%changed and 0b1011 xor 0b0010 !== 0 || !%composer.skipping) { Unit } else { %composer.skipToGroupEnd() } %composer.endReplaceableGroup() }, %composer, 0) %composer.endReplaceableGroup() } """ ) @Test fun testDexNaming(): Unit = composerParam( """ val myProperty: () -> Unit @Composable get() { return { } } """, """ val myProperty: Function0<Unit> get() { %composer.startReplaceableGroup(<>, "C:Test.kt#2487m") val tmp0 = { } %composer.endReplaceableGroup() return tmp0 } """ ) @Test fun testInnerClass(): Unit = composerParam( """ interface A { fun b() {} } class C { val foo = 1 inner class D : A { override fun b() { print(foo) } } } """, """ interface A { open fun b() { } } @StabilityInferred(parameters = 0) class C { val foo: Int = 1 inner class D : A { override fun b() { print(foo) } } static val %stable: Int = 0 } """ ) @Test fun testKeyCall() { composerParam( """ import androidx.compose.runtime.key @Composable fun Wrapper(block: @Composable () -> Unit) { block() } @Composable fun Leaf(text: String) { } @Composable fun Test(value: Int) { key(value) { Wrapper { Leaf("Value ${'$'}value") } } } """, """ @Composable fun Wrapper(block: Function2<Composer<*>, Int, Unit>, %composer: Composer<*>?, %changed: Int) { %composer.startRestartGroup(<>, "C(Wrapper)<block(...>:Test.kt#2487m") val %dirty = %changed if (%changed and 0b1110 === 0) { %dirty = %dirty or if (%composer.changed(block)) 0b0100 else 0b0010 } if (%dirty and 0b1011 xor 0b0010 !== 0 || !%composer.skipping) { block(%composer, 0b1110 and %dirty) } else { %composer.skipToGroupEnd() } %composer.endRestartGroup()?.updateScope { %composer: Composer<*>?, %force: Int -> Wrapper(block, %composer, %changed or 0b0001) } } @Composable fun Leaf(text: String, %composer: Composer<*>?, %changed: Int) { %composer.startRestartGroup(<>, "C(Leaf):Test.kt#2487m") val %dirty = %changed if (%changed and 0b1110 === 0) { %dirty = %dirty or if (%composer.changed(text)) 0b0100 else 0b0010 } if (%dirty and 0b1011 xor 0b0010 !== 0 || !%composer.skipping) { } else { %composer.skipToGroupEnd() } %composer.endRestartGroup()?.updateScope { %composer: Composer<*>?, %force: Int -> Leaf(text, %composer, %changed or 0b0001) } } @Composable fun Test(value: Int, %composer: Composer<*>?, %changed: Int) { %composer.startRestartGroup(<>, "C(Test):Test.kt#2487m") val %dirty = %changed if (%changed and 0b1110 === 0) { %dirty = %dirty or if (%composer.changed(value)) 0b0100 else 0b0010 } if (%dirty and 0b1011 xor 0b0010 !== 0 || !%composer.skipping) { %composer.startMovableGroup(<>, value, "<Wrappe...>") Wrapper(composableLambda(%composer, <>, true, "C<Leaf("...>:Test.kt#2487m") { %composer: Composer<*>?, %changed: Int -> if (%changed and 0b1011 xor 0b0010 !== 0 || !%composer.skipping) { Leaf("Value %value", %composer, 0) } else { %composer.skipToGroupEnd() } }, %composer, 0b0110) %composer.endMovableGroup() } else { %composer.skipToGroupEnd() } %composer.endRestartGroup()?.updateScope { %composer: Composer<*>?, %force: Int -> Test(value, %composer, %changed or 0b0001) } } """, validator = { element -> // Validate that no composers are captured by nested lambdas var currentComposer: IrValueParameter? = null element.accept( object : IrElementVisitorVoid { override fun visitSimpleFunction(declaration: IrSimpleFunction) { val composer = declaration.valueParameters.firstOrNull { it.name == KtxNameConventions.COMPOSER_PARAMETER } val oldComposer = currentComposer if (composer != null) currentComposer = composer super.visitSimpleFunction(declaration) currentComposer = oldComposer } override fun visitElement(element: IrElement) { element.acceptChildren(this, null) } override fun visitGetValue(expression: IrGetValue) { super.visitGetValue(expression) val value = expression.symbol.owner if ( value is IrValueParameter && value.name == KtxNameConventions.COMPOSER_PARAMETER ) { assertEquals( "Composer unexpectedly captured", currentComposer, value ) } } }, null ) } ) } @Test fun testComposableNestedCall() { composerParam( """ @Composable fun composeVector( composable: @Composable () -> Unit ) { emit { emit { composable() } } } @Composable inline fun emit(composable: @Composable () -> Unit) { composable() } """, """ @Composable fun composeVector(composable: Function2<Composer<*>, Int, Unit>, %composer: Composer<*>?, %changed: Int) { %composer.startRestartGroup(<>, "C(composeVector)<emit>:Test.kt#2487m") val %dirty = %changed if (%changed and 0b1110 === 0) { %dirty = %dirty or if (%composer.changed(composable)) 0b0100 else 0b0010 } if (%dirty and 0b1011 xor 0b0010 !== 0 || !%composer.skipping) { emit({ %composer: Composer<*>?, %changed: Int -> %composer.startReplaceableGroup(<>, "C<emit>:Test.kt#2487m") if (%changed and 0b1011 xor 0b0010 !== 0 || !%composer.skipping) { emit({ %composer: Composer<*>?, %changed: Int -> %composer.startReplaceableGroup(<>, "C<compos...>:Test.kt#2487m") if (%changed and 0b1011 xor 0b0010 !== 0 || !%composer.skipping) { composable(%composer, 0b1110 and %dirty) } else { %composer.skipToGroupEnd() } %composer.endReplaceableGroup() }, %composer, 0) } else { %composer.skipToGroupEnd() } %composer.endReplaceableGroup() }, %composer, 0) } else { %composer.skipToGroupEnd() } %composer.endRestartGroup()?.updateScope { %composer: Composer<*>?, %force: Int -> composeVector(composable, %composer, %changed or 0b0001) } } @Composable fun emit(composable: Function2<Composer<*>, Int, Unit>, %composer: Composer<*>?, %changed: Int) { %composer.startReplaceableGroup(<>, "C(emit)<compos...>:Test.kt#2487m") composable(%composer, 0b1110 and %changed) %composer.endReplaceableGroup() } """.trimIndent() ) } }
23
null
843
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
18,739
androidx
Apache License 2.0
app/src/main/java/com/kangaroo/wtcoin/app/Contants.kt
smartbackme
388,015,857
false
null
package com.kangaroo.wtcoin.app /** * author : WaTaNaBe * e-mail : <EMAIL> * time : 2020/09/14 * desc : */ internal const val LIAN_LENGTH = 200 internal const val LIAN_LEVEL1 = 2 internal const val LIAN_LEVEL2 = 4 internal const val LIAN_LEVEL3 = 16 internal const val LIAN_LEVEL4 = 64
0
Kotlin
1
0
372f1ca6d26ba2e9e24295e63280dd888ae51b64
295
Creative-Challenge-WTCoin
MIT License
jetbrains-core/tst/software/aws/toolkits/jetbrains/settings/MockAwsSettings.kt
tbtmuse
224,356,807
true
{"Kotlin": 1736421, "Java": 176230, "C#": 117036}
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.settings import java.util.UUID class MockAwsSettings( override var isTelemetryEnabled: Boolean, override var promptedForTelemetry: Boolean, override val clientId: UUID ) : AwsSettings
0
Kotlin
0
1
1a850add5272b430e0e129109f6ee4972fd3df4c
353
aws-toolkit-jetbrains
Apache License 2.0
src/main/kotlin/com/github/cpjinan/plugin/akariartifact/AkariArtifact.kt
CPJiNan
755,792,734
false
{"Kotlin": 159973}
package com.github.cpjinan.plugin.akariartifact import taboolib.common.platform.Plugin import taboolib.platform.BukkitPlugin object AkariArtifact : Plugin() { val plugin by lazy { BukkitPlugin.getInstance() } }
0
Kotlin
0
1
8ed61ddd4667af4894a1e6b2130385a2936440fb
216
AkariArtifact
Creative Commons Zero v1.0 Universal
app/src/main/java/com/jin/businfo_gumi/widget/Toasty.kt
JinSagong
366,760,371
false
null
package com.jin.businfo_gumi.widget import android.widget.Toast import androidx.annotation.StringRes import com.jin.businfo_gumi.MainApplication.Companion.appContext import com.jin.businfo_gumi.R import com.muddzdev.styleabletoast.StyleableToast @Suppress("UNUSED") object Toasty { private var toast: StyleableToast? = null private fun messageToast(msg: String) = StyleableToast.makeText( appContext, msg, Toast.LENGTH_LONG, R.style.MsgToast ) private fun alertToast(msg: String) = StyleableToast.makeText( appContext, msg, Toast.LENGTH_SHORT, R.style.AlertToast ) fun cancel() = toast?.cancel() fun msg(@StringRes msgId: Int) { toast?.cancel() toast = messageToast(appContext.getString(msgId)) toast!!.show() } fun msg(msg: String) { toast?.cancel() toast = messageToast(msg) toast!!.show() } fun alert(@StringRes msgId: Int) { toast?.cancel() toast = alertToast(appContext.getString(msgId)) toast!!.show() } fun alert(msg: String) { toast?.cancel() toast = alertToast(msg) toast!!.show() } }
0
Kotlin
0
1
30fde56859de44467730a202b0f74208f1a73d64
1,170
GumiBusInfo
Intel Open Source License
taskmanager/src/main/java/com/example/alexeyglushkov/taskmanager/tools/WeakRefList.kt
soniccat
28,707,156
false
{"Gradle": 23, "INI": 3, "Shell": 1, "Text": 3, "Ignore List": 21, "Batchfile": 1, "Markdown": 1, "Proguard": 20, "Kotlin": 259, "XML": 122, "Java": 299, "Java Properties": 1, "Gherkin": 1, "Ruby": 5}
package com.example.alexeyglushkov.taskmanager.tools import java.lang.ref.WeakReference import java.util.ArrayList /** * Created by alexeyglushkov on 23.08.15. */ class WeakRefList<T> : ArrayList<WeakReference<T>>() { override fun iterator(): MutableIterator<WeakReference<T>> { clean() return super.iterator() } fun clean() { var i = this.size while (--i >= 0) { if (get(i).get() == null) { removeAt(i) } } } fun containsValue(element: T): Boolean { for (ref in this) { if (ref.get() === element) { return true } } return false } override fun contains(element: WeakReference<T>): Boolean { return super.contains(element) } fun removeValue(element: T): Boolean { var i = 0 for (ref in this) { if (ref.get() === element) { removeAt(i) return true } ++i } return false } override fun remove(element: WeakReference<T>): Boolean { return super.remove(element) } companion object { private val serialVersionUID = 4962762847646156417L } }
1
null
1
1
0e0fa442e16d5544f7694042cf40cafde3672173
1,271
android-taskmanager
MIT License
paymentsheet/src/test/java/com/stripe/android/paymentsheet/forms/FormViewModelTest.kt
endronk
378,098,509
false
null
package com.stripe.android.paymentsheet.forms import com.google.common.truth.Truth.assertThat import com.stripe.android.paymentsheet.elements.common.TextFieldController import com.stripe.android.paymentsheet.specifications.FormElementSpec.SectionSpec.SectionFieldSpec.Email import com.stripe.android.paymentsheet.specifications.FormElementSpec.SectionSpec.SectionFieldSpec.Name import com.stripe.android.paymentsheet.specifications.sofort import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.junit.Test /** * Using sofort as a complex enough example to test the form view model class. */ class FormViewModelTest { @Test fun `Verify params are set when element flows are complete`() = runBlocking { val formViewModel = FormViewModel(sofort.layout) val nameElement = formViewModel.getController(Name) as TextFieldController val emailElement = formViewModel.getController(Email) as TextFieldController nameElement.onValueChange("joe") assertThat( formViewModel.completeFormValues.first()?.fieldValuePairs?.get(Name) ).isNull() emailElement.onValueChange("<EMAIL>") assertThat( formViewModel.completeFormValues.first()?.fieldValuePairs?.get(Email) ).isEqualTo("<EMAIL>") assertThat( formViewModel.completeFormValues.first()?.fieldValuePairs?.get(Name) ).isEqualTo("joe") emailElement.onValueChange("invalid.email@IncompleteDomain") assertThat( formViewModel.completeFormValues.first()?.fieldValuePairs?.get(Name) ).isNull() } }
1
null
1
1
05d4053ad8e980744e8e7c277857d3e92bc1b608
1,638
stripe-android
MIT License
library/src/main/java/com/kenargo/compound_widgets/WidgetTitleAndEditText.kt
kenargo
232,925,307
false
{"Gradle": 4, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Kotlin": 22, "XML": 61, "Java": 3, "INI": 1}
package com.kenargo.compound_widgets import android.content.Context import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.FrameLayout import com.kenargo.myapplicationlibrary.R import kotlinx.android.synthetic.main.widget_title_and_edit_text.view.* class WidgetTitleAndEditText @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { private var onTextChangedListener: TextWatcher? = null fun addTextChangedListener(listener: TextWatcher?) { onTextChangedListener = listener } // I'm not exposing the OnTextChange listener because I have a callback interface for conversion from display format to value; that's better I think private fun initSubView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) { LayoutInflater.from(context).inflate(R.layout.widget_title_and_edit_text, this, true) // TODO: I don't know wht just getting a pointer to the widget causes the designer to fail but it does so for now // just get the pointer only in runtime mode applyAttributes(context, attrs, defStyleAttr) editTextWidgetTitleAndEditTextValue.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { onTextChangedListener?.afterTextChanged(s) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { onTextChangedListener?.beforeTextChanged(s, start, count, after) } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { onTextChangedListener?.onTextChanged(s, start, before, count) } }) } private fun applyAttributes(context: Context, attrs: AttributeSet?, defStyleAttr: Int) { if (attrs == null) { return } val typedArray = context.theme.obtainStyledAttributes( attrs, R.styleable.WidgetTitleAndEditText, defStyleAttr, 0 ) var inputType = Integer.MIN_VALUE try { for (index in 0 until typedArray.length()) { val attribute: Int = try { typedArray.getIndex(index) } catch (ignore: Exception) { continue } when (attribute) { R.styleable.WidgetTitleAndEditText_android_text -> { textViewWidgetTitleAndEditTextTitle.text = typedArray.getText(R.styleable.WidgetTitleAndEditText_android_text) } R.styleable.WidgetTitleAndEditText_widgetTitleAndEditTextUnits -> { textViewWidgetTitleAndEditTextUnits.text = typedArray.getText(R.styleable.WidgetTitleAndEditText_widgetTitleAndEditTextUnits) } R.styleable.WidgetTitleAndEditText_widgetTitleAndEditTextEditText -> { editTextWidgetTitleAndEditTextValue.setText( typedArray.getText(R.styleable.WidgetTitleAndEditText_widgetTitleAndEditTextEditText) ) } R.styleable.WidgetTitleAndEditText_android_inputType -> { inputType = typedArray.getInt( R.styleable.WidgetTitleAndEditText_android_inputType, Integer.MIN_VALUE ) } R.styleable.WidgetTitleAndEditText_android_subtitle -> { textViewWidgetTitleAndEditTextSubtitle.text = typedArray.getText(R.styleable.WidgetTitleAndEditText_android_subtitle) } } } } finally { textViewWidgetTitleAndEditTextSubtitle.visibility = if (textViewWidgetTitleAndEditTextSubtitle.text.isNullOrEmpty()) { View.GONE } else { View.VISIBLE } textViewWidgetTitleAndEditTextUnits.visibility = if (textViewWidgetTitleAndEditTextUnits.text.isNullOrEmpty()) { View.GONE } else { View.VISIBLE } // If the user didn't specify the inputType then set a reasonable one based on range if (inputType != Integer.MIN_VALUE) { editTextWidgetTitleAndEditTextValue.inputType = inputType } typedArray.recycle() } } private fun isValidNumber(text: String): Boolean { return text.matches(Regex("^\\s*-?[0-9]{1,10}\\s*\$")) } private fun hideKeyboard() { val imm = context.applicationContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow( editTextWidgetTitleAndEditTextValue.windowToken, InputMethodManager.HIDE_NOT_ALWAYS ) } fun setTitle(title: String?) { if (title.isNullOrEmpty()) { textViewWidgetTitleAndEditTextTitle.visibility = View.GONE } else { textViewWidgetTitleAndEditTextTitle.text = title textViewWidgetTitleAndEditTextTitle.visibility = View.VISIBLE } } fun setUnitsText(subTitle: String?) { if (TextUtils.isEmpty(subTitle)) { textViewWidgetTitleAndEditTextUnits.visibility = View.GONE } else { textViewWidgetTitleAndEditTextUnits.text = subTitle textViewWidgetTitleAndEditTextUnits.visibility = View.VISIBLE } } fun setInputType(inputType: Int) { editTextWidgetTitleAndEditTextValue.inputType = inputType } init { initSubView(context, attrs!!, defStyleAttr) } }
1
null
1
1
6d29c3503eb3ba5830e05950dd9fca04952fce27
6,098
compound_widgets
Apache License 2.0
src/main/kotlin/no/nav/syfo/Bootstrap.kt
navikt
257,523,904
false
null
package no.nav.syfo import io.ktor.application.* import io.ktor.routing.* import io.ktor.server.engine.* import io.ktor.server.netty.* import no.nav.syfo.application.* import no.nav.syfo.application.api.registerNaisApi import no.nav.syfo.application.mq.* import no.nav.syfo.db.Database import no.nav.syfo.kafka.* import org.apache.kafka.clients.producer.KafkaProducer import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.concurrent.TimeUnit import javax.jms.Session val logger: Logger = LoggerFactory.getLogger("no.nav.syfo.padm2") fun main() { logger.info("Padm2 starting with java version: " + Runtime.version()) val env = Environment() val applicationState = ApplicationState() val database = Database( env = env, ) val applicationEngineEnvironment = applicationEngineEnvironment { log = logger connector { port = env.applicationPort } module { routing { registerNaisApi(applicationState) } } } applicationEngineEnvironment.monitor.subscribe(ApplicationStarted) { applicationState.ready = true logger.info("Application is ready") launchListeners( applicationState = applicationState, env = env, database = database, ) } val server = embeddedServer( factory = Netty, environment = applicationEngineEnvironment, ) Runtime.getRuntime().addShutdownHook( Thread { server.stop(10, 10, TimeUnit.SECONDS) } ) server.start(false) } fun launchListeners( applicationState: ApplicationState, env: Environment, database: Database, ) { val dialogmeldingProducer = DialogmeldingProducer( kafkaProducerDialogmelding = KafkaProducer<String, DialogmeldingForKafka>( kafkaDialogmeldingProducerConfig(env.kafka) ), ) launchBackgroundTask( applicationState = applicationState, ) { val factory = connectionFactory(env) factory.createConnection(env.serviceuserUsername, env.serviceuserPassword).use { connection -> connection.start() val session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE) val inputconsumer = session.consumerForQueue(env.inputQueueName) val mqSender = MQSender( env = env, ) val blockingApplicationRunner = BlockingApplicationRunner( applicationState = applicationState, database = database, env = env, inputconsumer = inputconsumer, mqSender = mqSender, dialogmeldingProducer = dialogmeldingProducer, ) blockingApplicationRunner.run() } } launchBackgroundTask( applicationState = applicationState, ) { val mqSender = MQSender( env = env, ) val dialogmeldingProcessor = DialogmeldingProcessor( database = database, env = env, mqSender = mqSender, dialogmeldingProducer = dialogmeldingProducer, ) val rerunCronJob = RerunCronJob( database = database, dialogmeldingProcessor = dialogmeldingProcessor, ) CronjobRunner( applicationState = applicationState, ).start(cronjob = rerunCronJob) } }
1
Kotlin
0
0
ff3bd6ad74ec8436e06b9e4ccc8d96f1eb800690
3,483
padm2
MIT License
crypto/src/test/kotlin/org/web3k/crypto/SignTest.kt
zla-io
136,006,148
false
{"Kotlin": 82252}
package org.web3k.crypto import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.jupiter.api.Test import org.web3k.common.hexStringToByteArray import java.security.SignatureException private val TEST_MESSAGE = "A test message".toByteArray() class SignTest { @Test fun testSignMessage() { val signatureData = signMessage(TEST_MESSAGE, KEY_PAIR) val expected = SignatureData( 27.toByte(), "0x9631f6d21dec448a213585a4a41a28ef3d4337548aa34734478b563036163786".hexStringToByteArray(), "0x2ff816ee6bbb82719e983ecd8a33a4b45d32a4b58377ef1381163d75eedc900b".hexStringToByteArray() ) assertThat(signatureData).isEqualTo(expected) } @Test @Throws(SignatureException::class) fun testSignedMessageToKey() { val signatureData = signMessage(TEST_MESSAGE, KEY_PAIR) val key = signedMessageToKey(TEST_MESSAGE, signatureData) assertThat(key).isEqualTo(PUBLIC_KEY) } @Test fun testPublicKeyFromPrivateKey() { assertThat(publicKeyFromPrivate(PRIVATE_KEY)).isEqualTo(PUBLIC_KEY) } @Test fun testInvalidSignatureData() { assertThatThrownBy { signedMessageToKey(TEST_MESSAGE, SignatureData(27.toByte(), byteArrayOf(1), byteArrayOf(0))) }.isInstanceOf(IllegalArgumentException::class.java) } }
1
Kotlin
0
0
48eb53a65f367f4c2094112e698b02703848b8af
1,440
web3k
Apache License 2.0
analysis/src/org/jetbrains/kotlin/idea/references/SyntheticPropertyAccessorReference.kt
JetBrains
278,369,660
false
null
/* * Copyright 2010-2015 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.idea.references import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.util.SmartList import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator import org.jetbrains.kotlin.idea.core.copied import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.utils.addIfNotNull sealed class SyntheticPropertyAccessorReference(expression: KtNameReferenceExpression, private val getter: Boolean) : KtSimpleReference<KtNameReferenceExpression>(expression) { override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> { val descriptors = super.getTargetDescriptors(context) if (descriptors.none { it is SyntheticJavaPropertyDescriptor }) return emptyList() val result = SmartList<FunctionDescriptor>() for (descriptor in descriptors) { if (descriptor is SyntheticJavaPropertyDescriptor) { if (getter) { result.add(descriptor.getMethod) } else { result.addIfNotNull(descriptor.setMethod) } } } return result } override fun isReferenceTo(element: PsiElement): Boolean { if (element !is PsiMethod || !isAccessorName(element.name)) return false if (!getter && expression.readWriteAccess(true) == ReferenceAccess.READ) return false return super.isReferenceTo(element) } private fun isAccessorName(name: String): Boolean { if (getter) { return name.startsWith("get") || name.startsWith("is") } return name.startsWith("set") } override fun getRangeInElement() = TextRange(0, expression.textLength) override fun canRename() = true private fun renameByPropertyName(newName: String): PsiElement? { val nameIdentifier = KtPsiFactory(expression).createNameIdentifier(newName) expression.getReferencedNameElement().replace(nameIdentifier) return expression } private fun KtExpression.createCall( psiFactory: KtPsiFactory, newName: String? = null, argument: KtExpression? = null ): KtExpression { return if (this is KtQualifiedExpression) { copied().also { val selector = it.getQualifiedElementSelector() as? KtExpression selector?.replace(selector.createCall(psiFactory, newName, argument)) } } else { psiFactory.buildExpression { if (newName != null) { appendFixedText(newName) } else { appendExpression(this@createCall) } appendFixedText("(") if (argument != null) { appendExpression(argument) } appendFixedText(")") } } } override fun handleElementRename(newElementName: String): PsiElement? { if (!Name.isValidIdentifier(newElementName)) return expression val newNameAsName = Name.identifier(newElementName) val newName = if (getter) { SyntheticJavaPropertyDescriptor.propertyNameByGetMethodName(newNameAsName) } else { //TODO: it's not correct //TODO: setIsY -> setIsIsY bug SyntheticJavaPropertyDescriptor.propertyNameBySetMethodName( newNameAsName, withIsPrefix = expression.getReferencedNameAsName().asString().startsWith( "is" ) ) } // get/set becomes ordinary method if (newName == null) { val psiFactory = KtPsiFactory(expression) val newGetterName = if (getter) newElementName else JvmAbi.getterName(expression.getReferencedName()) if (expression.readWriteAccess(false) == ReferenceAccess.READ) { return expression.replaced(expression.createCall(psiFactory, newGetterName)) } val newSetterName = if (getter) JvmAbi.setterName(expression.getReferencedName()) else newElementName val fullExpression = expression.getQualifiedExpressionForSelectorOrThis() fullExpression.getAssignmentByLHS()?.let { assignment -> val rhs = assignment.right ?: return expression val operationToken = assignment.operationToken as? KtSingleValueToken val counterpartOp = OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS[operationToken] val setterArgument = if (counterpartOp != null) { val getterCall = if (getter) fullExpression.createCall(psiFactory, newGetterName) else fullExpression psiFactory.createExpressionByPattern("$0 ${counterpartOp.value} $1", getterCall, rhs) } else { rhs } val newSetterCall = fullExpression.createCall(psiFactory, newSetterName, setterArgument) return assignment.replaced(newSetterCall).getQualifiedElementSelector() } fullExpression.getStrictParentOfType<KtUnaryExpression>()?.let { unaryExpr -> val operationToken = unaryExpr.operationToken as? KtSingleValueToken ?: return expression if (operationToken !in OperatorConventions.INCREMENT_OPERATIONS) return expression val operationName = OperatorConventions.getNameForOperationSymbol(operationToken) val originalValue = if (getter) fullExpression.createCall(psiFactory, newGetterName) else fullExpression val incDecValue = psiFactory.createExpressionByPattern("$0.$operationName()", originalValue) val parent = unaryExpr.parent val context = parent.parentsWithSelf.firstOrNull { it is KtBlockExpression || it is KtDeclarationContainer } if (context == parent || context == null) { val newSetterCall = fullExpression.createCall(psiFactory, newSetterName, incDecValue) return unaryExpr.replaced(newSetterCall).getQualifiedElementSelector() } else { val anchor = parent.parentsWithSelf.firstOrNull { it.parent == context } val validator = NewDeclarationNameValidator( context, anchor, NewDeclarationNameValidator.Target.VARIABLES ) val varName = KotlinNameSuggester.suggestNamesByExpressionAndType( unaryExpr, null, unaryExpr.analyze(), validator, "p" ).first() val isPrefix = unaryExpr is KtPrefixExpression val varInitializer = if (isPrefix) incDecValue else originalValue val newVar = psiFactory.createDeclarationByPattern<KtProperty>("val $varName = $0", varInitializer) val setterArgument = psiFactory.createExpression(if (isPrefix) varName else "$varName.$operationName()") val newSetterCall = fullExpression.createCall(psiFactory, newSetterName, setterArgument) val newLine = psiFactory.createNewLine() context.addBefore(newVar, anchor) context.addBefore(newLine, anchor) context.addBefore(newSetterCall, anchor) return unaryExpr.replaced(psiFactory.createExpression(varName)) } } return expression } return renameByPropertyName(newName.identifier) } override val resolvesByNames: Collection<Name> get() = listOf(element.getReferencedNameAsName()) class Getter(expression: KtNameReferenceExpression) : SyntheticPropertyAccessorReference(expression, true) class Setter(expression: KtNameReferenceExpression) : SyntheticPropertyAccessorReference(expression, false) }
191
null
4372
82
cc81d7505bc3e9ad503d706998ae8026c067e838
9,452
intellij-kotlin
Apache License 2.0
app/src/main/java/com/olabode/wilson/pytutor/ui/onboarding/OnBoardingAdapter.kt
whilson03
173,095,316
false
null
package com.olabode.wilson.pytutor.ui.onboarding import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.olabode.wilson.pytutor.databinding.SlideItemContainerBinding import com.olabode.wilson.pytutor.models.IntroSlideItem import com.olabode.wilson.pytutor.ui.onboarding.OnboardingAdapter.OnBoardingViewHolder /** * Created by <NAME> on 10/25/20. */ class OnboardingAdapter(private val sliderItems: List<IntroSlideItem>) : RecyclerView.Adapter<OnBoardingViewHolder>() { class OnBoardingViewHolder(private val binding: SlideItemContainerBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(introSlideItem: IntroSlideItem) { binding.sliderTitle.text = introSlideItem.title binding.sliderTextDescription.text = introSlideItem.description binding.sliderImage.setImageResource(introSlideItem.icon) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OnBoardingViewHolder { val binding = SlideItemContainerBinding.inflate(LayoutInflater.from(parent.context), parent, false) return OnBoardingViewHolder(binding) } override fun getItemCount(): Int { return sliderItems.size } override fun onBindViewHolder(holder: OnBoardingViewHolder, position: Int) { holder.bind(sliderItems[position]) } }
2
Kotlin
3
4
440cdf95f1c7e750fcadb49623d6f15b993163cd
1,423
PyTutor
MIT License
compiler/testData/codegen/box/reflection/multifileClasses/javaFieldForVarAndConstVal.kt
JakeWharton
99,388,807
false
null
// IGNORE_BACKEND_FIR: JVM_IR // IGNORE_BACKEND: JVM_IR // TARGET_BACKEND: JVM // WITH_REFLECT // FULL_JDK // FILE: 1.kt @file:kotlin.jvm.JvmName("Test") @file:kotlin.jvm.JvmMultifileClass package test import kotlin.reflect.jvm.* import kotlin.test.assertEquals fun testX() { val field = ::x.javaField ?: throw AssertionError("No java field for ${::x.name}") try { field.get(null) throw AssertionError("Fail: field.get should fail because the field is private") } catch (e: IllegalAccessException) { // OK } field.setAccessible(true) assertEquals("I am x", field.get(null)) field.set(null, "OK") } fun testY() { val field = ::y.javaField ?: throw AssertionError("No java field for ${::y.name}") assertEquals("I am const y", field.get(null)) // Accessible = false should have no effect because the field is public field.setAccessible(false) assertEquals("I am const y", field.get(null)) } fun testZ() { val field = refZ.javaField ?: throw AssertionError("No java field for ${refZ.name}") try { field.get(null) throw AssertionError("IllegalAccessError expected") } catch (e: IllegalAccessException) { // OK } field.setAccessible(true) assertEquals("I am private const val Z", field.get(null)) } fun box(): String { testX() testY() testZ() return x } // FILE: 2.kt @file:kotlin.jvm.JvmName("Test") @file:kotlin.jvm.JvmMultifileClass package test var x = "I am x" const val y = "I am const y" private const val z = "I am private const val Z" val refZ = ::z
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
1,615
kotlin
Apache License 2.0
idea/testData/decompiler/decompiledText/DependencyOnNestedClasses.expected.kt
JakeWharton
99,388,807
false
null
// IntelliJ API Decompiler stub source generated from a class file // Implementation of methods is not available package test public final class DependencyOnNestedClasses() : dependency.D.Nested { internal final fun f(nc: dependency.D.Companion.NestedInClassObject, i: dependency.D.Inner, ii: dependency.D.Inner.Inner, nn: dependency.D.Nested.Nested): dependency.D.Nested { /* compiled code */ } }
1
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
403
kotlin
Apache License 2.0
plugins/kotlin/code-insight/intentions-shared/tests/testData/intentions/unfolding/functionCallToIf/multiArguments3.kt
ingokegel
72,937,917
true
null
// AFTER-WARNING: Parameter 'x' is never used // AFTER-WARNING: Parameter 'y' is never used // AFTER-WARNING: Parameter 'z' is never used fun test(b: Boolean) { <caret>println(x = 1, y = if (b) 2 else 4, z = 3) } fun println(x: Int, y: Int, z: Int) {}
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
256
intellij-community
Apache License 2.0
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/adapter/CoroutineAdapters.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 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.camera.camera2.pipe.integration.adapter import androidx.concurrent.futures.CallbackToFutureAdapter import com.google.common.util.concurrent.ListenableFuture import java.util.concurrent.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.withTimeoutOrNull /** * Convert a job into a ListenableFuture<Void>. * * The return value of the Future is null, and canceling the future will not cancel the Job. The tag * field may be used to help debug futures. */ fun Job.asListenableFuture(tag: Any? = "Job.asListenableFuture"): ListenableFuture<Void> { val resolver: CallbackToFutureAdapter.Resolver<Void> = CallbackToFutureAdapter.Resolver<Void> { completer -> this.invokeOnCompletion { if (it != null) { if (it is CancellationException) { completer.setCancelled() } else { completer.setException(it) } } else { completer.set(null) } } tag } return CallbackToFutureAdapter.getFuture(resolver) } /** Convert a job into a ListenableFuture<T>. */ @OptIn(ExperimentalCoroutinesApi::class) fun <T> Deferred<T>.asListenableFuture( tag: Any? = "Deferred.asListenableFuture" ): ListenableFuture<T> { val resolver: CallbackToFutureAdapter.Resolver<T> = CallbackToFutureAdapter.Resolver<T> { completer -> this.invokeOnCompletion { if (it != null) { if (it is CancellationException) { completer.setCancelled() } else { completer.setException(it) } } else { // Ignore exceptions - This should never throw in this situation. completer.set(this.getCompleted()) } } tag } return CallbackToFutureAdapter.getFuture(resolver) } fun <T> Deferred<T>.propagateTo(destination: CompletableDeferred<T>) { invokeOnCompletion { propagateOnceTo(destination, it) } } @OptIn(ExperimentalCoroutinesApi::class) fun <T> Deferred<T>.propagateOnceTo( destination: CompletableDeferred<T>, throwable: Throwable?, ) { if (throwable != null) { if (throwable is CancellationException) { destination.cancel(throwable) } else { destination.completeExceptionally(throwable) } } else { // Ignore exceptions - This should never throw in this situation. destination.complete(getCompleted()) } } /** * Waits for [Deferred.await] to be completed until the given timeout. * * @return true if `Deferred.await` had completed, false otherwise. */ suspend fun <T> Deferred<T>.awaitUntil(timeoutMillis: Long) = withTimeoutOrNull(timeoutMillis) { this@awaitUntil.await() }?.let { true } ?: false
29
null
983
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
3,731
androidx
Apache License 2.0
src/test/kotlin/no/nav/tilleggsstonader/sak/infrastruktur/mocks/JournalpostClientConfig.kt
navikt
685,490,225
false
{"Kotlin": 1395663, "Gherkin": 37257, "HTML": 33935, "Shell": 924, "Dockerfile": 164}
package no.nav.tilleggsstonader.sak.infrastruktur.mocks import io.mockk.every import io.mockk.mockk import no.nav.tilleggsstonader.kontrakter.dokarkiv.ArkiverDokumentResponse import no.nav.tilleggsstonader.kontrakter.dokarkiv.OppdaterJournalpostResponse import no.nav.tilleggsstonader.kontrakter.felles.BrukerIdType import no.nav.tilleggsstonader.kontrakter.felles.Tema import no.nav.tilleggsstonader.kontrakter.journalpost.AvsenderMottaker import no.nav.tilleggsstonader.kontrakter.journalpost.AvsenderMottakerIdType import no.nav.tilleggsstonader.kontrakter.journalpost.Bruker import no.nav.tilleggsstonader.kontrakter.journalpost.DokumentInfo import no.nav.tilleggsstonader.kontrakter.journalpost.Dokumentvariant import no.nav.tilleggsstonader.kontrakter.journalpost.Dokumentvariantformat import no.nav.tilleggsstonader.kontrakter.journalpost.Journalpost import no.nav.tilleggsstonader.kontrakter.journalpost.JournalposterForBrukerRequest import no.nav.tilleggsstonader.kontrakter.journalpost.Journalposttype import no.nav.tilleggsstonader.kontrakter.journalpost.Journalstatus import no.nav.tilleggsstonader.kontrakter.journalpost.LogiskVedlegg import no.nav.tilleggsstonader.kontrakter.journalpost.RelevantDato import no.nav.tilleggsstonader.libs.utils.osloNow import no.nav.tilleggsstonader.sak.journalføring.JournalpostClient import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Primary import org.springframework.context.annotation.Profile import org.springframework.web.client.RestClientException @Configuration @Profile("mock-journalpost") class JournalpostClientConfig { @Bean @Primary fun journalpostClient(): JournalpostClient { val journalpostClient = mockk<JournalpostClient>() val journalposter: MutableMap<Long, Journalpost> = listOf(journalpost).associateBy { it.journalpostId.toLong() } .toMutableMap() every { journalpostClient.hentJournalpost(any()) } answers { val journalpostId = firstArg<String>() journalposter[journalpostId.toLong()] ?: error("Finner ikke journalpost med id=$journalpostId") } every { journalpostClient.distribuerJournalpost(any(), any()) } returns "bestillingId" every { journalpostClient.opprettJournalpost( any(), any(), ) } returns ArkiverDokumentResponse(journalpostId = "journalpostId", ferdigstilt = true) every { journalpostClient.hentDokument(any(), any(), any()) } returns dummyPdf every { journalpostClient.oppdaterJournalpost(any(), any(), any()) } answers { val journalpostId = secondArg<String>() OppdaterJournalpostResponse(journalpostId) } every { journalpostClient.ferdigstillJournalpost(any(), any(), any()) } answers { val journalpostId = firstArg<String>() OppdaterJournalpostResponse(journalpostId) } mockFeiletDistribusjon(journalpostClient) every { journalpostClient.ferdigstillJournalpost(any(), any(), any()) } returns mockk() every { journalpostClient.oppdaterJournalpost(any(), any(), any()) } returns mockk() every { journalpostClient.oppdaterLogiskeVedlegg(any(), any()) } answers { firstArg() } every { journalpostClient.finnJournalposterForBruker(any()) } answers { journalposter.values.filter { it.bruker?.id == firstArg<JournalposterForBrukerRequest>().brukerId.id } } return journalpostClient } private fun mockFeiletDistribusjon(journalpostClient: JournalpostClient) { every { journalpostClient.distribuerJournalpost( match { it.journalpostId == journalpostIdMedFeil }, any(), ) } throws RestClientException("noe feilet") } private val journalpost = Journalpost( "1", Journalposttype.I, journalstatus = Journalstatus.MOTTATT, tema = Tema.TSO.toString(), behandlingstema = "ab0300", tittel = "Søknad om barnetilsyn", bruker = Bruker("12345678910", BrukerIdType.FNR), avsenderMottaker = avsenderMottaker(), journalforendeEnhet = "tilleggsstonader-sak", relevanteDatoer = listOf( RelevantDato(osloNow().minusDays(7), "DATO_REGISTRERT"), RelevantDato(osloNow(), "DATO_JOURNALFOERT"), ), dokumenter = listOf( DokumentInfo( dokumentInfoId = "1", tittel = "Dummy dokument 1", logiskeVedlegg = listOf( LogiskVedlegg("1", "Dokumentasjon på sykdom"), LogiskVedlegg("2", "Inntektsendring"), LogiskVedlegg("3", "Samværsmelding"), ), dokumentvarianter = listOf( Dokumentvariant( variantformat = Dokumentvariantformat.ARKIV, saksbehandlerHarTilgang = true, ), ), ), DokumentInfo( dokumentInfoId = "2", tittel = "Dummy dokument 2", dokumentvarianter = listOf( Dokumentvariant( variantformat = Dokumentvariantformat.ARKIV, saksbehandlerHarTilgang = true, ), ), ), ), ) private val dummyPdf = this::class.java.classLoader.getResource("interntVedtak/internt_vedtak.pdf")!!.readBytes() private fun avsenderMottaker() = AvsenderMottaker( id = "12345678910", type = AvsenderMottakerIdType.FNR, navn = "<NAME>", land = "NOR", erLikBruker = true, ) companion object { const val journalpostIdMedFeil = "journalpostIdMedFeil" } }
4
Kotlin
1
0
e9b8839f142c7859d57222a5bcb2727217539e0b
6,118
tilleggsstonader-sak
MIT License
http4k-security/oauth/src/test/kotlin/org/http4k/security/oauth/server/OAuthServerTest.kt
http4k
86,003,479
false
null
package org.http4k.security.oauth.server import com.natpryce.hamkrest.and import com.natpryce.hamkrest.assertion.assertThat import org.http4k.core.Filter import org.http4k.core.Method.GET import org.http4k.core.Method.POST import org.http4k.core.NoOp import org.http4k.core.Request import org.http4k.core.Status.Companion.OK import org.http4k.core.body.form import org.http4k.core.then import org.http4k.filter.ClientFilters.Cookies import org.http4k.filter.ClientFilters.FollowRedirects import org.http4k.filter.debug import org.http4k.hamkrest.hasBody import org.http4k.hamkrest.hasStatus import org.junit.jupiter.api.Test class OAuthServerTest { @Test fun `can follow authorization code flow`() { val authenticationServer = customOauthAuthorizationServer() val consumerApp = oauthClientApp(authenticationServer) val browser = Cookies().then(authenticationServer + consumerApp).debug() val browserWithRedirection = FollowRedirects().then(browser) val preAuthResponse = browser(Request(GET, "/a-protected-resource")) val loginPage = preAuthResponse.header("location")!! val loginPageResponse = browser(Request(GET, loginPage)) assertThat(loginPageResponse, hasStatus(OK) and hasBody("Please authenticate")) val postAuthResponse = browserWithRedirection(Request(POST, loginPage).form("some", "credentials")) assertThat(postAuthResponse, hasStatus(OK) and hasBody("user resource")) } @Test fun `authorization flow with oauth request persistence`() { val authenticationServer = customOauthAuthorizationServerWithPersistence() val consumerApp = oauthClientApp(authenticationServer) val browser = Filter.NoOp .then(Cookies()) .then(authenticationServer + consumerApp) val browserWithRedirection = FollowRedirects().then(browser) val preAuthResponse = browser(Request(GET, "/a-protected-resource")) val loginPage = preAuthResponse.header("location")!! val loginPageResponse = browser(Request(GET, loginPage)) assertThat(loginPageResponse, hasStatus(OK) and hasBody("Please authenticate")) val postAuthResponse = browser(Request(POST, loginPage).form("some", "credentials")) val verifyPage = postAuthResponse.header("location")!! val verifyPageResponse = browser(Request(GET, verifyPage)) assertThat(verifyPageResponse, hasStatus(OK) and hasBody("Allow my-app to access name and age?")) val postConfirmationResponse = browserWithRedirection(Request(POST, verifyPage)) assertThat(postConfirmationResponse, hasStatus(OK) and hasBody("user resource")) } }
34
null
249
2,615
7ad276aa9c48552a115a59178839477f34d486b1
2,703
http4k
Apache License 2.0
allure-model/src/main/kotlin/io/qameta/allure/model/WithStatusDetails.kt
aartikov
222,651,686
true
{"Kotlin": 488317, "Java": 10748}
package io.qameta.allure.model interface WithStatusDetails : WithStatus { var statusDetails: StatusDetails? }
0
Kotlin
0
1
a79c8ffab972f44184abe214a55b963d8af4449f
115
Kaspresso
Apache License 2.0
app/src/main/java/com/example/mywiki/ui/webView/WebViewActivity.kt
uditbhaskar
368,022,314
false
null
package com.example.mywiki.ui.webView import android.annotation.SuppressLint import android.os.Bundle import android.view.View import android.webkit.WebView import android.webkit.WebViewClient import androidx.lifecycle.Observer import com.example.mywiki.databinding.ActivityWebviewBinding import com.example.mywiki.di.component.ActivityComponent import com.example.mywiki.ui.base.BaseActivity import javax.inject.Inject class WebViewActivity : BaseActivity<WebViewModel>() { companion object { const val TAG = "WebViewActivity" } @Inject lateinit var binding: ActivityWebviewBinding override fun provideLayoutView(): View = binding.root override fun injectDependencies(activityComponent: ActivityComponent) { activityComponent.inject(this) } @SuppressLint("SetJavaScriptEnabled") override fun setupView(savedInstanceState: Bundle?) { binding.webView.apply { settings.javaScriptEnabled = true webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean { view?.loadUrl(url) return true } override fun onPageCommitVisible(view: WebView?, url: String?) { super.onPageCommitVisible(view, url) binding.progressBar.visibility = View.GONE } } binding.webView.loadUrl("https://en.wikipedia.org/?curid=${intent.getStringExtra("pageId")}") } binding.ivBack.setOnClickListener{ viewModel.onBackPressed() } } override fun setupObservers() { super.setupObservers() viewModel.launchHome.observe(this, Observer { it.getIfNotHandled()?.run { finish() } }) } }
0
Kotlin
6
8
952fe8a9493d5821cb3a2584f0a3ae21dfb9cec0
1,884
MyWiki
MIT License
fileloader/src/main/java/me/bytebeats/fileloader/FileLoaderClientProxy.kt
bytebeats
394,566,766
false
null
package me.bytebeats.fileloader import okhttp3.* import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody.Companion.toRequestBody import java.io.IOException import java.io.InputStream import java.util.concurrent.TimeUnit import kotlin.jvm.Throws /** * Created by bytebeats on 2021/8/10 : 15:52 * E-mail: <EMAIL> * Quote: Peasant. Educated. Worker */ class FileLoaderClientProxy(private val client: OkHttpClient? = null) { private var mClient = OkHttpClient.Builder() .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .build() init { if (client != null) { mClient = client } } private fun newCall(request: Request): Call = mClient.newCall(request) fun cancelRequest(tag: String?): Boolean { if (!tag.isNullOrEmpty()) { for (runningCall in mClient.dispatcher.runningCalls()) { if (tag == runningCall.request().tag()) { runningCall.cancel() return true } } for (queuedCall in mClient.dispatcher.queuedCalls()) { if (tag == queuedCall.request().tag()) { queuedCall.cancel() return true } } } return false } @Throws(IOException::class) fun execute(request: Request): Response { return newCall(request).execute() } private fun executeAsync(request: Request, callback: Callback) { newCall(request).enqueue(callback) } private fun buildRequest(url: String, headers: Map<String, String>?, tag: String?): Request { val builder = Request.Builder().url(url).tag(tag) headers?.let { it.entries.forEach { entry -> builder.header(entry.key, entry.value) } } return builder.build() } fun doGet(url: String, headers: Map<String, String>?, tag: String?): String? { val resp = execute(buildRequest(url, headers, tag)) return if (resp.isSuccessful) { resp.body?.string() } else { resp.message } } fun doGetAsync(url: String, headers: Map<String, String>?, tag: String?, callback: Callback) { executeAsync(buildRequest(url, headers, tag), callback) } @Throws(IOException::class) fun doGetStream(url: String, headers: Map<String, String>?, tag: String?): InputStream? { val resp = execute(buildRequest(url, headers, tag)) if (resp.isSuccessful) { return resp.body?.byteStream() } else { throw IOException("Unexpected code: $resp") } } private fun buildFormRequest( url: String, headers: Map<String, String>?, params: Map<String, String?>?, tag: String? ): Request { val requestBuilder = Request.Builder().url(url).tag(tag) headers?.let { it.entries.forEach { entry -> requestBuilder.header(entry.key, entry.value) } } val formBuilder = FormBody.Builder() params?.let { for (entry in it.entries) { formBuilder.add(entry.key, entry.value ?: "") } } return requestBuilder.post(formBuilder.build()).build() } fun doPost( url: String, headers: Map<String, String>?, params: Map<String, String?>?, tag: String? ): String? { val resp = execute(buildFormRequest(url, headers, params, tag)) return if (resp.isSuccessful) { resp.body?.string() } else { resp.message } } fun doPostAsync( url: String, headers: Map<String, String>?, params: Map<String, String?>?, tag: String?, callback: Callback ) { executeAsync(buildFormRequest(url, headers, params, tag), callback) } private fun buildJsonRequest( url: String, headers: Map<String, String>?, postJsonBody: String, tag: String? ): Request { val requestBuilder = Request.Builder().url(url).tag(tag) .post(postJsonBody.toRequestBody("application/json".toMediaTypeOrNull())) headers?.let { for (entry in it.entries) { requestBuilder.header(entry.key, entry.value) } } return requestBuilder.build() } fun doPostJson( url: String, headers: Map<String, String>?, postJsonBody: String, tag: String? ): String? { val resp = execute(buildJsonRequest(url, headers, postJsonBody, tag)) return if (resp.isSuccessful) { resp.body?.string() } else { resp.message } } fun doPostJsonAsync( url: String, headers: Map<String, String>?, postJsonBody: String, tag: String?, callback: Callback ) { executeAsync(buildJsonRequest(url, headers, postJsonBody, tag), callback) } companion object { private const val DEFAULT_TIMEOUT = 30L } }
0
Kotlin
0
1
294510d9307c633a4ee2466746838f1774aa28f5
5,258
OkHttpFileLoader
MIT License
livingdoc-converters/src/main/kotlin/org/livingdoc/converters/JSONConverter.kt
LivingDoc
85,412,044
false
null
package org.livingdoc.converters import com.beust.klaxon.JsonObject import com.beust.klaxon.Klaxon import com.beust.klaxon.KlaxonException import org.livingdoc.api.conversion.ConversionException import org.livingdoc.api.conversion.TypeConverter import java.io.StringReader import java.lang.reflect.AnnotatedElement import java.lang.reflect.Field import java.lang.reflect.Parameter /** * A TypeConverter to convert json strings into custom Types. This is not a Default TypeConverter and must always be * explicitly specified to be used. */ class JSONConverter<T> : TypeConverter<T> { override fun convert(value: String, element: AnnotatedElement?, documentClass: Class<*>?): T { val typeClass = getType(element ?: throw IllegalArgumentException("The element must be given")) val klaxon = Klaxon() val json = try { klaxon.parser(typeClass.kotlin).parse(StringReader(value)) as? JsonObject ?: throw ConversionException("Only json objects con be converted: $value") } catch (e: KlaxonException) { throw ConversionException("Can not parse json string '$value'", e) } catch (e: IllegalStateException) { // unhandled exception from the lexer throw ConversionException("Can not parse json string '$value'", e) } try { return klaxon.fromJsonObject(json, typeClass, typeClass.kotlin) as T } catch (e: KlaxonException) { throw ConversionException( "Can not create object of type '$typeClass' from json '${json.toJsonString( prettyPrint = true )}'", e ) } } private fun getType(element: AnnotatedElement): Class<*> { return when (element) { is Field -> element.type is Parameter -> element.type else -> error("annotated element is of a not supported type: $element") } ?: throw TypeConverters.NoTypeConverterFoundException(element) } /** * This type converter can convert json to every target type. */ override fun canConvertTo(targetType: Class<*>) = true }
34
Kotlin
16
14
f3d52b8bacbdf81905e4b4a753d75f584329b297
2,165
livingdoc
Apache License 2.0
z2-core/src/commonMain/kotlin/hu/simplexion/z2/services/factory/ServiceImplFactory.kt
spxbhuhb
665,463,766
false
{"Kotlin": 1812530, "CSS": 171914, "Java": 20900, "JavaScript": 1950, "HTML": 1854}
package hu.simplexion.z2.services.factory import hu.simplexion.z2.services.ServiceContext import hu.simplexion.z2.services.ServiceImpl interface ServiceImplFactory { operator fun plusAssign(template: ServiceImpl<*>) operator fun get(serviceName: String, context: ServiceContext): ServiceImpl<*>? }
5
Kotlin
0
1
da267d17fcfa20631ba3d539efd7cbe42a4aa8ca
310
z2-pre
Apache License 2.0
library/src/main/java/io/github/deweyreed/scrollhmspicker/ScrollHmsPicker.kt
DeweyReed
121,510,804
false
null
package io.github.deweyreed.scrollhmspicker import android.content.Context import android.graphics.Typeface import android.os.Parcel import android.os.Parcelable import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import android.widget.TextView import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.core.content.ContextCompat import cn.carbswang.android.numberpickerview.library.NumberPickerView /** * Created on 2018/2/13. */ @Suppress("MemberVisibilityCanBePrivate", "unused") open class ScrollHmsPicker @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { protected val pickerHours: NumberPickerView protected val textHours: TextView protected val pickerMinutes: NumberPickerView protected val textMinutes: TextView protected val pickerSeconds: NumberPickerView protected val textSeconds: TextView private var autoStep: Boolean = false private var enable99Hours = false var hours: Int get() = pickerHours.value set(value) = setSafeHours(value) var minutes: Int get() = pickerMinutes.value set(value) = setSafeMinutes(value) var seconds: Int get() = pickerSeconds.value set(value) = setSafeSeconds(value) init { orientation = HORIZONTAL LayoutInflater.from(context).inflate(R.layout.shp_scrollhmspicker, this) val res = resources val ta = context.obtainStyledAttributes(attrs, R.styleable.ScrollHmsPicker) val colorNormal = ta.getColor( R.styleable.ScrollHmsPicker_shp_normal_color, color(android.R.color.darker_gray) ) @ColorInt val colorSelected = ta.getColor( R.styleable.ScrollHmsPicker_shp_selected_color, color(android.R.color.holo_red_light) ) val hours = ta.getInteger(R.styleable.ScrollHmsPicker_shp_hours, 0) val minutes = ta.getInteger(R.styleable.ScrollHmsPicker_shp_minutes, 0) val seconds = ta.getInteger(R.styleable.ScrollHmsPicker_shp_seconds, 0) val autoStep = ta.getBoolean(R.styleable.ScrollHmsPicker_shp_auto_step, false) val showHours = ta.getBoolean(R.styleable.ScrollHmsPicker_shp_show_hours, true) val showMinutes = ta.getBoolean(R.styleable.ScrollHmsPicker_shp_show_minutes, true) val showSeconds = ta.getBoolean(R.styleable.ScrollHmsPicker_shp_show_seconds, true) enable99Hours = ta.getBoolean(R.styleable.ScrollHmsPicker_shp_enable_99_hours, false) ta.recycle() pickerHours = findViewById<NumberPickerView>(R.id.pickerHours).apply { maxValue = 99 } textHours = findViewById(R.id.textHours) setHoursVisibility(showHours) set99Hours(enable99Hours) pickerMinutes = findViewById<NumberPickerView>(R.id.pickerMinutes).apply { maxValue = 59 } textMinutes = findViewById(R.id.textMinutes) setMinutesVisibility(showMinutes) pickerSeconds = findViewById<NumberPickerView>(R.id.pickerSeconds).apply { maxValue = 59 } textSeconds = findViewById(R.id.textSeconds) setSecondsVisibility(showSeconds) setSafeHours(hours) setSafeMinutes(minutes) setSafeSeconds(seconds) setAutoStep(autoStep) arrayOf(pickerHours, pickerMinutes, pickerSeconds).forEach { it.setContentTextTypeface(Typeface.SANS_SERIF) it.setNormalTextColor(colorNormal) it.setSelectedTextColor(colorSelected) } // //----------| // | // selected | |--| <- label // | |--| // | ----> move label to the bottom of selected item // ---------| padding == (selected size - label size) / 2 // val textMarginTop = ((res.getDimension(R.dimen.shp_text_size_selected_item) - res.getDimension(R.dimen.shp_text_size_label)) / 2).toInt() arrayOf(textHours, textMinutes, textSeconds).forEach { view -> view.setTextColor(colorSelected) // align texts to the bottom of the selected text view.layoutParams = (view.layoutParams as LayoutParams).also { it.topMargin = textMarginTop } } } fun setColorNormal(@ColorRes res: Int) { setColorIntNormal(color(res)) } fun setColorIntNormal(@ColorInt color: Int) { arrayOf(pickerHours, pickerMinutes, pickerSeconds).forEach { it.setNormalTextColor(color) } } fun setColorSelected(@ColorRes res: Int) { setColorIntSelected(color(res)) } fun setColorIntSelected(@ColorInt color: Int) { arrayOf(pickerHours, pickerMinutes, pickerSeconds).forEach { it.setSelectedTextColor(color) } arrayOf(textHours, textMinutes, textSeconds).forEach { it.setTextColor(color) } } fun setAutoStep(newValue: Boolean) { if (newValue != autoStep) { autoStep = newValue if (autoStep) { pickerMinutes.setOnValueChangeListenerInScrolling { _, oldVal, newVal -> val hoursVal = pickerHours.value if (oldVal == 59 && newVal == 0) { pickerHours.smoothScrollToValue((hoursVal + 1) % (if (enable99Hours) 100 else 24)) } else if (oldVal == 0 && newVal == 59) { pickerHours.smoothScrollToValue(if (hoursVal > 0) hoursVal - 1 else ((if (enable99Hours) 99 else 23))) } } pickerSeconds.setOnValueChangeListenerInScrolling { _, oldVal, newVal -> val minutesVal = pickerMinutes.value if (oldVal == 59 && newVal == 0) { pickerMinutes.smoothScrollToValue((minutesVal + 1) % 60) } else if (oldVal == 0 && newVal == 59) { pickerMinutes.smoothScrollToValue(if (minutesVal > 0) minutesVal - 1 else 59) } } } else { pickerMinutes.setOnValueChangeListenerInScrolling(null) pickerSeconds.setOnValueChangeListenerInScrolling(null) } } } fun setHoursVisibility(show: Boolean) { val visibility = if (show) VISIBLE else GONE pickerHours.visibility = visibility textHours.visibility = visibility } fun setMinutesVisibility(show: Boolean) { val visibility = if (show) VISIBLE else GONE pickerMinutes.visibility = visibility textMinutes.visibility = visibility } fun setSecondsVisibility(show: Boolean) { val visibility = if (show) VISIBLE else GONE pickerSeconds.visibility = visibility textSeconds.visibility = visibility } fun set99Hours(enable: Boolean) { enable99Hours = enable pickerHours.setMinAndMaxShowIndex(0, if (enable) 99 else 23) } fun setTypeface(newTypeface: Typeface) { pickerHours.setContentTextTypeface(newTypeface) pickerHours.setHintTextTypeface(newTypeface) textHours.typeface = newTypeface pickerMinutes.setContentTextTypeface(newTypeface) pickerMinutes.setHintTextTypeface(newTypeface) textMinutes.typeface = newTypeface pickerSeconds.setContentTextTypeface(newTypeface) pickerSeconds.setHintTextTypeface(newTypeface) textSeconds.typeface = newTypeface } fun getTypeface(): Typeface { return textHours.typeface } private fun setSafeHours(hours: Int) { if (hours in 0..(if (enable99Hours) 99 else 23)) scrollToValue(pickerHours, hours) } private fun setSafeMinutes(minutes: Int) { if (minutes in 0..59) scrollToValue(pickerMinutes, minutes) } private fun setSafeSeconds(seconds: Int) { if (seconds in 0..59) scrollToValue(pickerSeconds, seconds) } private fun scrollToValue(picker: NumberPickerView, value: Int) { // if (animateToValue) { // post { picker.smoothScrollToValue(value) } // } else { picker.value = value // } } override fun onSaveInstanceState(): Parcelable { val parent = super.onSaveInstanceState() return (if (parent != null) SavedState(parent) else SavedState()).also { state -> state.hours = hours state.minutes = minutes state.seconds = seconds } } override fun onRestoreInstanceState(state: Parcelable?) { if (state is SavedState) { super.onRestoreInstanceState(state.superState) hours = state.hours minutes = state.minutes seconds = state.seconds } else { super.onRestoreInstanceState(state) } } private class SavedState : BaseSavedState { var hours: Int = 0 var minutes: Int = 0 var seconds: Int = 0 constructor() : super(Parcel.obtain()) constructor(superState: Parcelable) : super(superState) private constructor(source: Parcel?) : super(source) { source?.run { hours = source.readInt() minutes = source.readInt() seconds = source.readInt() } } override fun writeToParcel(out: Parcel?, flags: Int) { super.writeToParcel(out, flags) out?.run { writeInt(hours) writeInt(minutes) writeInt(seconds) } } private companion object { @JvmField val CREATOR = object : Parcelable.Creator<SavedState> { override fun createFromParcel(source: Parcel?): SavedState = SavedState(source) override fun newArray(size: Int): Array<SavedState?> = arrayOfNulls(size) } } } private fun View.color(@ColorRes id: Int) = ContextCompat.getColor(this.context, id) }
0
Kotlin
11
31
dc0ba4f00bccdf9f3e4673cecad93587652ce356
10,279
ScrollHmsPicker
MIT License
tests/testutils/src/main/kotlin/io/element/android/tests/testutils/LongTask.kt
vector-im
546,522,002
false
null
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.tests.testutils import kotlinx.coroutines.delay /** * Workaround for https://github.com/cashapp/molecule/issues/249. * This functions should be removed/deprecated right after we find a proper fix. */ suspend inline fun <T> simulateLongTask(lambda: () -> T): T { delay(1) return lambda() }
101
Kotlin
32
239
3414351bfd143c174732da539e25350030249b67
932
element-x-android
Apache License 2.0
app/src/main/java/com/talhaoz/martianstalker/models/MissionDetailsModel.kt
talhaoz
303,740,794
false
{"Kotlin": 29900}
package com.talhaoz.martianstalker.model import com.google.gson.annotations.SerializedName data class MissionDetailsModel( @SerializedName("photos") val photos: ArrayList<Photo> )
0
Kotlin
0
0
ccf4a8749420871da6967c68fadb8c7a40962b81
189
Martian-Scouter
Apache License 2.0
sync/sync-settings-impl/src/test/java/com/duckduckgo/sync/settings/impl/SettingsSyncDataPersisterTest.kt
hojat72elect
822,396,044
false
{"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.sync.settings.impl import androidx.arch.core.executor.testing.* import androidx.room.* import androidx.test.ext.junit.runners.* import androidx.test.platform.app.* import com.duckduckgo.app.* import com.duckduckgo.common.test.CoroutineTestRule import com.duckduckgo.common.test.FileUtilities import com.duckduckgo.sync.api.engine.* import com.duckduckgo.sync.api.engine.SyncMergeResult.Success import com.duckduckgo.sync.api.engine.SyncableDataPersister.SyncConflictResolution.DEDUPLICATION import com.duckduckgo.sync.api.engine.SyncableDataPersister.SyncConflictResolution.TIMESTAMP import kotlinx.coroutines.* import org.junit.* import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.runner.* import org.mockito.Mockito.* @RunWith(AndroidJUnit4::class) class SettingsSyncDataPersisterTest { @get:Rule @Suppress("unused") var instantTaskExecutorRule = InstantTaskExecutorRule() @get:Rule var coroutineRule = CoroutineTestRule() val db = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getInstrumentation().targetContext, SettingsDatabase::class.java) .allowMainThreadQueries() .build() val metadataDao = db.settingsSyncDao() val duckAddressSetting = spy(FakeSyncableSetting()) val settingSyncStore = FakeSettingsSyncStore() val syncableSettingsPP = SyncableSettingsPluginPoint(mutableListOf(duckAddressSetting)) private val testee = SettingsSyncDataPersister( syncableSettings = syncableSettingsPP, settingsSyncMetadataDao = metadataDao, syncSettingsSyncStore = settingSyncStore, syncCrypto = FakeCrypto(), dispatchers = coroutineRule.testDispatcherProvider, ) @After fun after() { db.close() } @Test fun whenPersistChangesDeduplicationWithdValueThenCallDeduplicateWithValue() { val result = testee.onSuccess( changes = SyncChangesResponse( type = SyncableType.SETTINGS, jsonString = responseWithValuesObject, ), conflictResolution = DEDUPLICATION, ) assertTrue(result is Success) verify(duckAddressSetting).deduplicate("fake_value") } @Test fun whenPersistChangesDeduplicationWithDeletedValueThenCallDeduplicateWithNull() { val result = testee.onSuccess( changes = SyncChangesResponse( type = SyncableType.SETTINGS, jsonString = responseWithDeletedObject, ), conflictResolution = DEDUPLICATION, ) assertTrue(result is Success) verify(duckAddressSetting).deduplicate(null) } @Test fun whenPersistChangesTimestampAndNoRecentChangeThenCallMergeWithValue() { settingSyncStore.startTimeStamp = "2023-08-31T10:06:16.022Z" val result = testee.onSuccess( changes = SyncChangesResponse( type = SyncableType.SETTINGS, jsonString = responseWithValuesObject, ), conflictResolution = TIMESTAMP, ) assertTrue(result is Success) verify(duckAddressSetting).save("fake_value") } @Test fun whenPersistChangesTimestampWithDeletedValueThenCallSaveWithNull() { val result = testee.onSuccess( changes = SyncChangesResponse( type = SyncableType.SETTINGS, jsonString = responseWithDeletedObject, ), conflictResolution = TIMESTAMP, ) assertTrue(result is Success) verify(duckAddressSetting).save(null) } @Test fun whenPersistChangesTimestampButRecentlyModifiedThenSkip() { settingSyncStore.startTimeStamp = "2023-08-31T10:06:16.022Z" metadataDao.addOrUpdate( SettingsSyncMetadataEntity( key = "fake_setting", modified_at = "2023-08-31T10:06:17.022Z", deleted_at = null, ), ) val result = testee.onSuccess( changes = SyncChangesResponse( type = SyncableType.SETTINGS, jsonString = responseWithValuesObject, ), conflictResolution = TIMESTAMP, ) assertTrue(result is Success) verify(duckAddressSetting, times(0)).save("fake_value") } @Test fun whenPersistChangesSucceedsThenUpdateServerAndClientTimestamps() { settingSyncStore.startTimeStamp = "2023-08-31T10:06:16.022Z" val result = testee.onSuccess( changes = SyncChangesResponse( type = SyncableType.SETTINGS, jsonString = responseWithValuesObject, ), conflictResolution = DEDUPLICATION, ) assertTrue(result is Success) assertEquals("2023-08-31T10:06:16.022Z", settingSyncStore.serverModifiedSince) assertEquals("2023-08-31T10:06:16.022Z", settingSyncStore.clientModifiedSince) } companion object { val responseWithDeletedObject = FileUtilities.loadText(javaClass.classLoader!!, "json/settings_with_deleted_object_response.json") val responseWithValuesObject = FileUtilities.loadText(javaClass.classLoader!!, "json/settings_with_values_response.json") } }
0
Kotlin
0
0
54351d039b85138a85cbfc7fc3bd5bc53637559f
5,310
DuckDuckGo
Apache License 2.0
designer/src/com/android/tools/idea/common/lint/AttributeKey.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 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 com.android.tools.idea.common.lint import com.android.tools.idea.common.model.NlComponent data class AttributeKey( val component: NlComponent, val namespace: String, val attributeName: String, )
5
null
230
948
10110983c7e784122d94c7467e9d243aba943bf4
831
android
Apache License 2.0
mobile/src/main/java/ch/epfl/sdp/mobile/state/StatefulPuzzleGameScreen.kt
epfl-SDP
462,385,783
false
null
@file:OptIn(ExperimentalPermissionsApi::class) package ch.epfl.sdp.mobile.state import android.Manifest.permission.RECORD_AUDIO import androidx.compose.foundation.layout.PaddingValues import androidx.compose.material.SnackbarHostState import androidx.compose.runtime.* import androidx.compose.ui.Modifier import ch.epfl.sdp.mobile.application.authentication.AuthenticatedUser import ch.epfl.sdp.mobile.application.chess.* import ch.epfl.sdp.mobile.state.game.ActualPuzzleGameScreenState import ch.epfl.sdp.mobile.ui.puzzles.PuzzleGameScreen import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.PermissionState import com.google.accompanist.permissions.rememberPermissionState /** * The [StatefulPuzzleGameScreen] to be used for the Navigation. * * @param user the currently logged-in user. * @param puzzleId the identifier for the puzzle. * @param actions the [StatefulGameScreenActions] to perform. * @param modifier the [Modifier] for the composable. * @param paddingValues the [PaddingValues] for this composable. * @param audioPermissionState the [PermissionState] which provides access to audio content. */ @OptIn(ExperimentalPermissionsApi::class) @Composable fun StatefulPuzzleGameScreen( user: AuthenticatedUser, puzzleId: String, actions: StatefulGameScreenActions, modifier: Modifier = Modifier, paddingValues: PaddingValues = PaddingValues(), audioPermissionState: PermissionState = rememberPermissionState(RECORD_AUDIO), ) { val chessFacade = LocalChessFacade.current val speechFacade = LocalSpeechFacade.current val scope = rememberCoroutineScope() val puzzle = chessFacade.puzzle(uid = puzzleId) ?: Puzzle() val currentUser = rememberUpdatedState(user) val currentActions = rememberUpdatedState(actions) val currentStrings = rememberUpdatedState(LocalLocalizedStrings.current) val snackbarHostState = remember { SnackbarHostState() } val puzzleGameScreenState = remember( currentActions, currentStrings, currentUser, puzzle, audioPermissionState, speechFacade, scope, ) { ActualPuzzleGameScreenState( currentActions = currentActions, currentStrings = currentStrings, currentUser = currentUser, puzzle = puzzle, permission = audioPermissionState, speechFacade = speechFacade, snackbarHostState = snackbarHostState, scope = scope, ) } StatefulPromoteDialog(puzzleGameScreenState) PuzzleGameScreen( state = puzzleGameScreenState, modifier = modifier, contentPadding = paddingValues, snackbarHostState = snackbarHostState, ) }
15
Kotlin
3
13
71f6e2a5978087205b35f82e89ed4005902d697e
2,784
android
MIT License
src/main/kotlin/no/roedt/ringesentralen/sms/LagreSMSResponse.kt
Roedt
300,015,002
false
{"Kotlin": 268735, "Dockerfile": 1250, "Java": 456, "HTML": 181}
package no.roedt.ringesentralen.sms import io.quarkus.runtime.annotations.RegisterForReflection @RegisterForReflection data class LagreSMSResponse( val id: Int )
16
Kotlin
0
1
6c681c37cbd1e06ddc98554beda447464776dfc9
168
ringesentralen-backend
MIT License
http4k-cloudevents/src/main/kotlin/org/http4k/format/cloudEventsExtensions.kt
http4k
86,003,479
false
null
package org.http4k.format import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import io.cloudevents.CloudEvent import io.cloudevents.CloudEventData import io.cloudevents.core.builder.CloudEventBuilder import io.cloudevents.core.builder.withDataContentType import io.cloudevents.jackson.JsonCloudEventData import io.cloudevents.jackson.PojoCloudEventDataMapper import org.http4k.core.ContentType.Companion.APPLICATION_JSON import org.http4k.lens.BiDiLens import org.http4k.lens.BiDiLensSpec import org.http4k.lens.LensGet import org.http4k.lens.LensSet import org.http4k.lens.ParamMeta.ObjectParam inline fun <reified T : CloudEventData> ConfigurableJackson.cloudEventDataLens(): BiDiLens<CloudEvent, T> { val get = LensGet<CloudEvent, T> { _, target -> target.data?.let { listOf(PojoCloudEventDataMapper.from(mapper, jacksonTypeRef<T>()).map(it).value) } ?: emptyList() } val set = LensSet<CloudEvent, T> { _, values, event -> values.fold(event) { acc, next -> CloudEventBuilder.from(acc) .withDataContentType(APPLICATION_JSON) .withData(JsonCloudEventData.wrap(asJsonObject(next))) .build() } } return object : BiDiLensSpec<CloudEvent, T>("CloudEvent", ObjectParam, get, set) {}.required(T::class.simpleName!!) }
28
null
198
2,069
fb14ae0112d3e5ac1d34f4d73941dfd25b942a44
1,341
http4k
Apache License 2.0
sdk/src/main/java/com/qonversion/android/sdk/internal/di/module/FragmentModule.kt
qonversion
224,974,105
false
{"Kotlin": 604976, "Java": 9442, "Ruby": 2698}
package com.qonversion.android.sdk.internal.di.module import com.qonversion.android.sdk.automations.internal.macros.ScreenProcessor import com.qonversion.android.sdk.internal.di.scope.ActivityScope import com.qonversion.android.sdk.automations.mvp.ScreenContract import dagger.Module import dagger.Provides @Module internal class FragmentModule(private val view: ScreenContract.View) { @ActivityScope @Provides fun provideScreenView(): ScreenContract.View { return view } @ActivityScope @Provides fun provideScreenProcessor(): ScreenProcessor { return ScreenProcessor() } }
2
Kotlin
21
122
619465b65dbf2612486ec3adad9b0a8750d76c7b
626
android-sdk
MIT License
common/src/test/kotlin/pdl/AdressebeskyttelseTest.kt
navikt
499,112,118
false
{"Kotlin": 105937}
package pdl import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import no.nav.etterlatte.libs.common.pdl.Adressebeskyttelse import no.nav.etterlatte.libs.common.pdl.AdressebeskyttelseBolkPerson import no.nav.etterlatte.libs.common.pdl.AdressebeskyttelsePerson import no.nav.etterlatte.libs.common.pdl.AdressebeskyttelseResponse import no.nav.etterlatte.libs.common.pdl.Gradering import no.nav.etterlatte.libs.common.pdl.HentAdressebeskyttelse import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows internal class AdressebeskyttelseTest { private val mapper = jacksonObjectMapper() @Test fun `Verifiser at gradering har korrekt rekkefoelge`() { assertEquals(0, Gradering.STRENGT_FORTROLIG_UTLAND.ordinal) assertEquals(1, Gradering.STRENGT_FORTROLIG.ordinal) assertEquals(2, Gradering.FORTROLIG.ordinal) assertEquals(3, Gradering.UGRADERT.ordinal) } @Test fun `Verifiser prioritering av gradering`() { val graderinger1 = listOf( Gradering.UGRADERT, Gradering.STRENGT_FORTROLIG, Gradering.STRENGT_FORTROLIG_UTLAND, Gradering.FORTROLIG ) assertEquals(Gradering.STRENGT_FORTROLIG_UTLAND, graderinger1.minOrNull()) val graderinger2 = listOf( Gradering.FORTROLIG, Gradering.STRENGT_FORTROLIG, Gradering.UGRADERT ) assertEquals(Gradering.STRENGT_FORTROLIG, graderinger2.minOrNull()) val graderinger3 = listOf( Gradering.FORTROLIG, Gradering.UGRADERT ) assertEquals(Gradering.FORTROLIG, graderinger3.minOrNull()) val graderinger4 = listOf( Gradering.UGRADERT ) assertEquals(Gradering.UGRADERT, graderinger4.minOrNull()) val graderinger5 = emptyList<Gradering>() assertNull(graderinger5.minOrNull()) } @Test fun `Sjekk at valueOf paa gradering fungerer som forventet`() { assertEquals(Gradering.STRENGT_FORTROLIG_UTLAND, Gradering.valueOf("STRENGT_FORTROLIG_UTLAND")) assertEquals(Gradering.STRENGT_FORTROLIG, Gradering.valueOf("STRENGT_FORTROLIG")) assertEquals(Gradering.FORTROLIG, Gradering.valueOf("FORTROLIG")) assertEquals(Gradering.UGRADERT, Gradering.valueOf("UGRADERT")) assertThrows<Throwable> { Gradering.valueOf("ukjent") } } @Test fun `Sjekk at serde av gradering fungerer som forventet`() { val serialized = "\"FORTROLIG\"" val deserialized = mapper.readValue(serialized, jacksonTypeRef<Gradering>()) assertEquals(Gradering.FORTROLIG, deserialized) val reSerialized = mapper.writeValueAsString(deserialized) assertEquals(serialized, reSerialized) } @Test fun `Sjekk serde av AdressebeskyttelseResponse`() { val response = AdressebeskyttelseResponse( HentAdressebeskyttelse( listOfNotNull( mockPerson(Gradering.FORTROLIG), mockPerson(Gradering.STRENGT_FORTROLIG_UTLAND, Gradering.STRENGT_FORTROLIG) ) ) ) val serialized = mapper.writeValueAsString(response) assertTrue(serialized.contains(Gradering.FORTROLIG.name)) assertTrue(serialized.contains(Gradering.STRENGT_FORTROLIG_UTLAND.name)) assertTrue(serialized.contains(Gradering.STRENGT_FORTROLIG.name)) assertTrue(serialized.contains("12345678910")) val deserialized = mapper.readValue(serialized, jacksonTypeRef<AdressebeskyttelseResponse>()) val personBolk = deserialized.data!!.hentPersonBolk!! assertEquals(2, personBolk.size) val adressebeskyttelseListe = personBolk.flatMap { it.person!!.adressebeskyttelse } assertEquals(3, adressebeskyttelseListe.size) } private fun mockPerson(vararg gradering: Gradering?) = AdressebeskyttelseBolkPerson( ident = "12345678910", person = AdressebeskyttelsePerson( gradering.filterNotNull().map { Adressebeskyttelse(it) } ) ) }
0
Kotlin
0
0
db2203c428e3dd862fa8c2706715cf4cdf10f89e
4,362
pensjon-etterlatte-libs
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/codedeploy/CfnDeploymentGroupGitHubLocationPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.services.codedeploy import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.codedeploy.CfnDeploymentGroup /** * `GitHubLocation` is a property of the * [CodeDeploy DeploymentGroup Revision](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision.html) * property that specifies the location of an application revision that is stored in GitHub. * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.codedeploy.*; * GitHubLocationProperty gitHubLocationProperty = GitHubLocationProperty.builder() * .commitId("commitId") * .repository("repository") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-githublocation.html) */ @CdkDslMarker public class CfnDeploymentGroupGitHubLocationPropertyDsl { private val cdkBuilder: CfnDeploymentGroup.GitHubLocationProperty.Builder = CfnDeploymentGroup.GitHubLocationProperty.builder() /** * @param commitId The SHA1 commit ID of the GitHub commit that represents the bundled artifacts * for the application revision. */ public fun commitId(commitId: String) { cdkBuilder.commitId(commitId) } /** * @param repository The GitHub account and repository pair that stores a reference to the * commit that represents the bundled artifacts for the application revision. Specify the * value as `account/repository` . */ public fun repository(repository: String) { cdkBuilder.repository(repository) } public fun build(): CfnDeploymentGroup.GitHubLocationProperty = cdkBuilder.build() }
3
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
2,119
awscdk-dsl-kotlin
Apache License 2.0
kotlin/kotlin-1.6.10/src/main/kotlin/dev/nulli/jvm_benchmarks/kotlin_1_6_10/DataSize.kt
ahaim5357
464,627,517
false
null
package dev.nulli.jvm_benchmarks.kotlin_1_6_10 import org.openjdk.jol.info.ClassLayout import kotlin.reflect.KClass fun main() { viewClassData("Integer", Int::class) viewObjectData("Int Array 100", IntArray(100)) viewObjectData("Int Array 1K", IntArray(1000)) viewObjectData("Int Array 5K", IntArray(5000)) viewObjectData("Int Array 50K", IntArray(50000)) viewObjectData("Int Array 1M", IntArray(1000000)) viewObjectData("Int Array 2M", IntArray(2000000)) viewObjectData("Int Array 3M", IntArray(3000000)) viewObjectData("Int Array 5M", IntArray(5000000)) viewObjectData("Int Array 7M", IntArray(7000000)) viewObjectData("Int Array 10M", IntArray(10000000)) viewObjectData("Int Array 20M", IntArray(20000000)) viewObjectData("Int Array 30M", IntArray(30000000)) viewObjectData("Int Array 50M", IntArray(50000000)) viewObjectData("Int Array 70M", IntArray(70000000)) viewObjectData("Int Array 100M", IntArray(100000000)) } private fun <T : Any> viewClassData(name: String, t: KClass<T>) { viewData(name, ClassLayout.parseClass(t.java)) } private fun <T> viewObjectData(name: String, t: T) { viewData(name, ClassLayout.parseInstance(t)) } private fun viewData(name: String, layout: ClassLayout) { println("#########################################") println("Class Layout: $name") println("-----------------------------------------") println(layout.toPrintable()) println("#########################################") }
0
Kotlin
0
0
6596cf17b0e3f996cd438634f6736030c95a5a63
1,513
jvm-benchmarks
MIT License
app/src/main/java/com/everdeng/android/app/wanandroid/widget/MyWebView.kt
devallever
391,037,939
false
null
package com.everdeng.android.app.wanandroid.widget import android.content.Context import android.util.AttributeSet import android.view.KeyEvent import android.webkit.WebView class MyWebView: WebView { constructor( context: Context): super(context) constructor(context: Context, attributeSet: AttributeSet): super(context, attributeSet) constructor(context: Context, attributeSet: AttributeSet, themeRes: Int): super(context, attributeSet, themeRes) override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK && canGoBack()) { goBack();// 返回前一个页面 return true; } return super.onKeyDown(keyCode, event) } }
1
null
1
3
e98d1996a44bcebe477b5a11b6df0cfade29b7fe
718
WanAndroid
Apache License 2.0
app/src/main/java/com/moka/framework/base/BaseFragment.kt
moka-a
70,499,969
false
null
package com.moka.framework.base import android.app.AlertDialog import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.moka.framework.extenstion.hideSoftKey import com.moka.framework.util.MLog import com.moka.mokatoyapp.R import org.jetbrains.anko.support.v4.act import rx.subscriptions.CompositeSubscription abstract class BaseFragment : Fragment() { private var TAG = javaClass.simpleName private var compositeSubscription: CompositeSubscription? = null private var loadingDialog: AlertDialog? = null /** * LifeCycle method implement */ override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { MLog.a("lifeCycle", TAG + " onCreateView called ####") return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) MLog.a("lifeCycle", TAG + " onViewCreated called ####") } override fun onStart() { super.onStart() MLog.a("lifeCycle", TAG + " onStart called ####") } /** ###### onPause */ override fun onResume() { super.onResume() MLog.a("lifeCycle", TAG + " onResume called ####") } /** ###### onResume */ override fun onPause() { super.onPause() MLog.a("lifeCycle", TAG + " onPause called ####") } override fun onStop() { super.onStop() MLog.a("lifeCycle", TAG + " onStop called ####") } override fun onDestroyView() { super.onDestroyView() MLog.a("lifeCycle", TAG + " onDestroyView called ####") if (null != compositeSubscription) compositeSubscription!!.clear() } /** **/ fun getCompositeSubscription(): CompositeSubscription { if (null == compositeSubscription) compositeSubscription = CompositeSubscription() return compositeSubscription!! } fun dismissSoftKeyOnTouch(rootView: View) { rootView.setOnTouchListener { view, motionEvent -> hideSoftKey(act) false } } /** * About LoadingDailog */ private fun getLoadingDialog(): AlertDialog { if (null == loadingDialog) { val builder = AlertDialog.Builder(act) val rootView = act.layoutInflater.inflate(R.layout.dialog_loading, null) builder.setView(rootView) builder.setCancelable(false) loadingDialog = builder.create() } return loadingDialog!! } fun showLoadingDialog() { if (!getLoadingDialog().isShowing && isAdded) loadingDialog!!.show() } fun dismissLoadingDialog() { if (null != loadingDialog && loadingDialog!!.isShowing) loadingDialog!!.dismiss() } }
1
null
1
15
b625a2f77826bd10d464fe0292ee545378c039bd
3,000
moka-sample-android
The Unlicense
idea/testData/debugger/tinyApp/src/evaluate/singleBreakpoint/callableBug.kt
JakeWharton
99,388,807
false
null
package callableBug fun main(args: Array<String>) { val callable = 1 array(1, 2).map { it + 1 //Breakpoint! }.forEach { it + 2 } } // STEP_INTO: 1 // EXPRESSION: callable // RESULT: 1: I // EXPRESSION: it // RESULT: 2: I
0
null
30
83
4383335168338df9bbbe2a63cb213a68d0858104
250
kotlin
Apache License 2.0
app/src/main/java/com/stocksexchange/android/database/tables/OrdersTable.kt
nscoincommunity
277,168,471
true
{"Kotlin": 2814235}
package com.stocksexchange.android.database.tables import com.stocksexchange.api.model.rest.Order import com.stocksexchange.api.model.rest.OrderStatus import com.stocksexchange.android.database.daos.OrderDao import com.stocksexchange.android.database.model.DatabaseOrder import com.stocksexchange.android.database.tables.base.BaseTable import com.stocksexchange.android.database.utils.QueryBuilder import com.stocksexchange.android.mappings.mapToDatabaseOrder import com.stocksexchange.android.mappings.mapToDatabaseOrderList import com.stocksexchange.android.mappings.mapToOrder import com.stocksexchange.android.mappings.mapToOrderList import com.stocksexchange.api.model.rest.parameters.OrderParameters import com.stocksexchange.core.model.Result class OrdersTable( private val orderDao: OrderDao ) : BaseTable() { @Synchronized fun save(order: Order) { orderDao.insert(order.mapToDatabaseOrder()) } @Synchronized fun save(orders: List<Order>) { orderDao.insert(orders.mapToDatabaseOrderList()) } @Synchronized fun delete(order: Order) { orderDao.delete(order.mapToDatabaseOrder()) } @Synchronized fun delete(status: OrderStatus) { orderDao.delete(QueryBuilder.Orders.getDeleteQuery(status)) } @Synchronized fun deleteAll() { orderDao.deleteAll() } @Synchronized fun search(params: OrderParameters, currencyPairIds: List<Int>): Result<List<Order>> { val query = QueryBuilder.Orders.getSearchQuery( status = params.status, currencyPairIds = currencyPairIds, sortOrder = params.sortOrder.name, limit = params.limit, offset = params.offset ) return orderDao.search(query).toResult( List<DatabaseOrder>::mapToOrderList ) } @Synchronized fun getOrder(id: Long): Result<Order> { return orderDao.get(id).toResult(DatabaseOrder::mapToOrder) } @Synchronized fun getOrders(params: OrderParameters): Result<List<Order>> { val query = QueryBuilder.Orders.getQuery( status = params.status, currencyPairId = params.currencyPairIdStrOrEmptyStr, sortOrder = params.sortOrder.name, limit = params.limit, offset = params.offset ) return orderDao.get(query).toResult( List<DatabaseOrder>::mapToOrderList ) } }
0
null
0
0
52766afab4f96506a2d9ed34bf3564b6de7af8c3
2,471
Android-app
MIT License
src/main/kotlin/com/niclas_van_eyk/laravel_make_integration/run/PHPScriptRunListener.kt
NiclasvanEyk
277,648,794
false
null
package com.niclas_van_eyk.laravel_make_integration.run import com.intellij.execution.process.ProcessEvent import com.intellij.execution.process.ProcessListener import com.intellij.openapi.util.Key class PHPScriptRunListener: ProcessListener { val texts = ArrayList<String>() override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) { println(event.text) texts.add(event.text) } override fun processTerminated(event: ProcessEvent) { println("Terminated with exit code ${event.exitCode}!") } override fun startNotified(event: ProcessEvent) { } }
7
null
1
9
773808cb47dd3e6f45f97dfb9bd048ae6db2e550
614
jetbrains-laravel-make-integration
Apache License 2.0
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/drops/DropTable.kt
2011Scape
578,880,245
false
null
package gg.rsmod.plugins.content.drops /** * Represents a drop table. * @param name The name of this table. * @param entries The drop entries. */ data class DropTable(val name: String?, val entries: Array<TableBuilder.Entry>) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as DropTable if (name != other.name) return false if (!entries.contentEquals(other.entries)) return false return true } override fun hashCode(): Int { var result = name?.hashCode() ?: 0 result = 31 * result + entries.contentHashCode() return result } }
5
null
8
34
e5400cc71bfa087164153d468979c5a3abc24841
716
game
Apache License 2.0
plugins/lombok/testData/box/data.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// FULL_JDK // WITH_STDLIB // FILE: DataExample.java import lombok.*; import java.util.List; import java.util.Arrays; @Data public class DataExample { private final String name; @Setter(AccessLevel.PACKAGE) private int age; private double score; private String[] tags; @ToString(includeFieldNames=true) @Data(staticConstructor="of") public static class Exercise<T> { private final String name; private final T value; private final List<T> list; } public static void usage() { val obj = new DataExample("name"); obj.getName(); obj.getTags(); obj.setScore(1.5); Exercise<Integer> ex = Exercise.of("name", 12, Arrays.asList(1, 2, 3)); } } // FILE: test.kt fun box(): String { val obj = DataExample("name") obj.getName() assertEquals(obj.name, "name") obj.getTags() val tags = obj.tags obj.setScore(1.5) assertEquals(obj.score, 1.5) obj.score = 2.5 assertEquals(obj.score, 2.5) val ex: DataExample.Exercise<Int> = DataExample.Exercise.of("name", 12, listOf(1, 2, 3)) return "OK" }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,133
kotlin
Apache License 2.0
publishing-sdk/src/main/java/com/ably/tracking/publisher/MabpoxHelpers.kt
ably
313,556,297
false
null
package com.ably.tracking.publisher import com.ably.tracking.Location import com.mapbox.api.directions.v5.DirectionsCriteria import com.mapbox.geojson.Point /** * Returns list of [Point] that Mapbox will treat as a route for a trip. * First element in the list is the starting position. * Last element in the list is the final position. * */ internal fun getRouteCoordinates( startingLocation: Location, destination: Destination ): List<Point> = listOf( Point.fromLngLat(startingLocation.longitude, startingLocation.latitude), Point.fromLngLat(destination.longitude, destination.latitude) ) internal fun RoutingProfile.toMapboxProfileName() = when (this) { RoutingProfile.DRIVING -> DirectionsCriteria.PROFILE_DRIVING RoutingProfile.CYCLING -> DirectionsCriteria.PROFILE_CYCLING RoutingProfile.WALKING -> DirectionsCriteria.PROFILE_WALKING RoutingProfile.DRIVING_TRAFFIC -> DirectionsCriteria.PROFILE_DRIVING_TRAFFIC }
101
null
6
9
dca56bac165ebc1474cf2afb863728c2aad4aeb4
977
ably-asset-tracking-android
Apache License 2.0
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/TrophySolid.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.lineawesomeicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.LineAwesomeIcons public val LineAwesomeIcons.TrophySolid: ImageVector get() { if (_trophySolid != null) { return _trophySolid!! } _trophySolid = Builder(name = "TrophySolid", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.0f, 4.0f) curveTo(6.059f, 4.0f, 5.086f, 4.355f, 4.313f, 5.031f) curveTo(3.539f, 5.707f, 3.0f, 6.746f, 3.0f, 8.0f) curveTo(3.0f, 9.063f, 3.445f, 9.969f, 4.0f, 10.688f) curveTo(4.555f, 11.406f, 5.227f, 11.973f, 5.844f, 12.531f) curveTo(7.078f, 13.648f, 8.0f, 14.566f, 8.0f, 16.0f) curveTo(8.0f, 16.152f, 7.852f, 16.52f, 7.656f, 16.813f) curveTo(7.461f, 17.105f, 7.281f, 17.281f, 7.281f, 17.281f) lineTo(8.719f, 18.688f) curveTo(8.719f, 18.688f, 9.039f, 18.367f, 9.344f, 17.906f) curveTo(9.605f, 17.512f, 9.891f, 17.004f, 9.969f, 16.344f) curveTo(10.082f, 16.668f, 10.191f, 17.0f, 10.313f, 17.313f) curveTo(11.0f, 19.086f, 11.793f, 20.676f, 12.688f, 21.875f) curveTo(13.012f, 22.313f, 13.348f, 22.699f, 13.719f, 23.031f) curveTo(11.652f, 23.18f, 10.0f, 24.898f, 10.0f, 27.0f) lineTo(10.0f, 28.0f) lineTo(22.0f, 28.0f) lineTo(22.0f, 27.0f) curveTo(22.0f, 24.875f, 20.316f, 23.148f, 18.219f, 23.031f) curveTo(18.594f, 22.699f, 18.953f, 22.309f, 19.281f, 21.875f) curveTo(20.18f, 20.68f, 20.961f, 19.086f, 21.656f, 17.313f) curveTo(21.785f, 16.98f, 21.91f, 16.625f, 22.031f, 16.281f) curveTo(22.098f, 16.969f, 22.387f, 17.5f, 22.656f, 17.906f) curveTo(22.961f, 18.367f, 23.281f, 18.688f, 23.281f, 18.688f) lineTo(24.719f, 17.281f) curveTo(24.719f, 17.281f, 24.539f, 17.105f, 24.344f, 16.813f) curveTo(24.148f, 16.52f, 24.0f, 16.152f, 24.0f, 16.0f) curveTo(24.0f, 14.566f, 24.922f, 13.648f, 26.156f, 12.531f) curveTo(26.773f, 11.973f, 27.445f, 11.406f, 28.0f, 10.688f) curveTo(28.555f, 9.969f, 29.0f, 9.063f, 29.0f, 8.0f) curveTo(29.0f, 6.746f, 28.461f, 5.707f, 27.688f, 5.031f) curveTo(26.914f, 4.355f, 25.941f, 4.0f, 25.0f, 4.0f) curveTo(23.723f, 4.0f, 22.848f, 4.582f, 22.375f, 5.0f) lineTo(9.625f, 5.0f) curveTo(9.152f, 4.582f, 8.277f, 4.0f, 7.0f, 4.0f) close() moveTo(7.0f, 6.0f) curveTo(7.473f, 6.0f, 7.777f, 6.148f, 8.0f, 6.281f) curveTo(8.027f, 8.32f, 8.379f, 10.633f, 8.938f, 12.906f) curveTo(8.406f, 12.188f, 7.742f, 11.59f, 7.156f, 11.063f) curveTo(6.523f, 10.492f, 5.945f, 9.965f, 5.563f, 9.469f) curveTo(5.18f, 8.973f, 5.0f, 8.543f, 5.0f, 8.0f) curveTo(5.0f, 7.301f, 5.273f, 6.867f, 5.656f, 6.531f) curveTo(6.039f, 6.195f, 6.566f, 6.0f, 7.0f, 6.0f) close() moveTo(25.0f, 6.0f) curveTo(25.434f, 6.0f, 25.961f, 6.195f, 26.344f, 6.531f) curveTo(26.727f, 6.867f, 27.0f, 7.301f, 27.0f, 8.0f) curveTo(27.0f, 8.543f, 26.82f, 8.973f, 26.438f, 9.469f) curveTo(26.055f, 9.965f, 25.477f, 10.492f, 24.844f, 11.063f) curveTo(24.246f, 11.602f, 23.57f, 12.223f, 23.031f, 12.969f) curveTo(23.605f, 10.68f, 23.973f, 8.348f, 24.0f, 6.281f) curveTo(24.223f, 6.148f, 24.527f, 6.0f, 25.0f, 6.0f) close() moveTo(10.125f, 7.0f) lineTo(21.875f, 7.0f) curveTo(21.723f, 9.973f, 20.953f, 13.598f, 19.781f, 16.594f) curveTo(19.133f, 18.25f, 18.383f, 19.688f, 17.656f, 20.656f) curveTo(16.93f, 21.625f, 16.266f, 22.0f, 15.969f, 22.0f) curveTo(15.676f, 22.0f, 15.035f, 21.625f, 14.313f, 20.656f) curveTo(13.59f, 19.688f, 12.832f, 18.254f, 12.188f, 16.594f) curveTo(11.023f, 13.594f, 10.277f, 9.957f, 10.125f, 7.0f) close() moveTo(15.0f, 10.0f) lineTo(15.0f, 15.0f) lineTo(17.0f, 15.0f) lineTo(17.0f, 10.0f) close() moveTo(14.0f, 25.0f) lineTo(18.0f, 25.0f) curveTo(18.719f, 25.0f, 19.211f, 25.441f, 19.563f, 26.0f) lineTo(12.438f, 26.0f) curveTo(12.789f, 25.441f, 13.281f, 25.0f, 14.0f, 25.0f) close() } } .build() return _trophySolid!! } private var _trophySolid: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
5,703
compose-icons
MIT License
GaiaXAnalyze/GXAnalyzeAndroid/src/main/java/com/alibaba/gaiax/analyze/GXValue.kt
alibaba
456,772,654
false
{"C": 3164040, "Kotlin": 1542817, "Rust": 1390378, "Objective-C": 919399, "Java": 650249, "JavaScript": 260489, "TypeScript": 229724, "C++": 223843, "CSS": 154159, "HTML": 113541, "MDX": 86833, "Objective-C++": 60116, "Swift": 25131, "Shell": 12787, "Makefile": 12210, "Ruby": 6268, "CMake": 4674, "Batchfile": 3816, "SCSS": 837}
package com.alibaba.gaiax.analyze abstract class GXValue { fun <T : GXValue?> cast(clazz: Class<T>): T { return if (clazz.isInstance(this)) { this as T } else { throw RuntimeException("expected: " + clazz.simpleName + ", actual: " + javaClass.simpleName) } } abstract fun getValue(): Any? }
27
C
118
950
125d0cd701adb58ec7ae5e719d3939cd2c5aee5b
353
GaiaX
Apache License 2.0
QuickBaseLib/src/main/java/cn/chawloo/base/ext/ExtensionFun.kt
ChawLoo
500,638,671
false
{"Kotlin": 202722}
package cn.chawloo.base.ext import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.os.Bundle import android.os.Parcelable import com.hjq.toast.Toaster import java.io.Serializable /** * 扩展函数,放一些不知道怎么分类的扩展函数 知道后可以迁移 * @author Create by 鲁超 on 2022/6/7 0007 14:16:32 *----------Dragon be here!----------/ * ┌─┐ ┌─┐ * ┌─┘─┴──────┘─┴─┐ * │ │ * │ ─ │ * │ ┬─┘ └─┬ │ * │ │ * │ ┴ │ * │ │ * └───┐ ┌───┘ * │ │神兽保佑 * │ │代码无BUG! * │ └──────┐ * │ ├┐ * │ ┌┘ * └┐ ┐ ┌───┬─┐ ┌┘ * │ ┤ ┤ │ ┤ ┤ * └─┴─┘ └─┴─┘ *─────────────神兽出没───────────────/ */ fun String?.insertClipboard(context: Context, title: String = "标题已复制") { val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboardManager.setPrimaryClip(ClipData.newPlainText(null, this)) Toaster.show(title) } fun <T> Bundle.put(key: String, value: T) { when (value) { is Boolean -> putBoolean(key, value) is BooleanArray -> putBooleanArray(key, value) is String -> putString(key, value) is Int -> putInt(key, value) is IntArray -> putIntArray(key, value) is Short -> putShort(key, value) is ShortArray -> putShortArray(key, value) is Long -> putLong(key, value) is LongArray -> putLongArray(key, value) is Byte -> putByte(key, value) is ByteArray -> putByteArray(key, value) is Char -> putChar(key, value) is CharArray -> putCharArray(key, value) is CharSequence -> putCharSequence(key, value) is Float -> putFloat(key, value) is FloatArray -> putFloatArray(key, value) is Bundle -> putBundle(key, value) is Parcelable -> putParcelable(key, value) is Serializable -> putSerializable(key, value) else -> throw IllegalArgumentException("Type of property $key is not supported") } } fun <T> Bundle.get(key: String, default: T): T { return get(key) as? T ?: default }
0
Kotlin
0
2
c5d4063dcf4eb45b15b94d62f690632719cab801
2,234
QuickBaseLib
Apache License 2.0
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/CatchRuntimeException.kt
winterDroid
101,016,375
true
{"Kotlin": 446738, "Groovy": 1433, "Java": 163}
package io.gitlab.arturbosch.detekt.rules.exceptions import io.gitlab.arturbosch.detekt.api.Config import org.jetbrains.kotlin.psi.KtCatchClause /** * @author <NAME> */ class CatchRuntimeException(config: Config = Config.empty) : ExceptionsRule(config) { override fun visitCatchSection(catchClause: KtCatchClause) { catchClause.addFindingIfExceptionClassMatchesExact { "RuntimeException" } } }
0
Kotlin
2
0
cd839f2e6767ad884d3224ab51045fcc58e2504a
404
detekt-old
Apache License 2.0
domain/src/main/java/com/nowiwr01p/domain/news/article/data/CreateArticleMode.kt
nowiwr01w
584,138,480
false
null
package com.nowiwr01p.domain.news.article.data enum class CreateArticleMode { SEND_TO_REVIEW, PUBLISH_REVIEWED }
0
Kotlin
1
3
0ebdf8f0cc072cf1f07810a6c36e710f373bfc7f
121
Protest
MIT License
domain/src/main/java/com/duccnv/cleanmoviedb/domain/model/Transformer.kt
ahmedalkhashab
260,399,969
false
{"Gradle": 4, "Gradle Kotlin DSL": 6, "Java Properties": 2, "Markdown": 3, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Kotlin": 121, "JSON": 5, "Proguard": 2, "Java": 3, "XML": 26}
package com.duccnv.cleanmoviedb.domain.model import io.reactivex.ObservableTransformer abstract class Transformer<T> : ObservableTransformer<T, T>
1
null
1
1
d157e2f275b20c8601766ce36c8a91841c133faa
148
clean_movie_db
Apache License 2.0
shared/src/commonMain/kotlin/eu/baroncelli/dkmpsample/shared/viewmodel/screens/countrydetail/CountryDetailEvents.kt
developerY
367,396,321
true
{"Kotlin": 62642, "Swift": 15399}
package eu.baroncelli.dkmpsample.shared.viewmodel.screens.countrydetail import eu.baroncelli.dkmpsample.shared.viewmodel.Events /********** INTERNAL event function, called by the StateProvider's callOnInit **********/ internal fun Events.loadCountryDetailData(country: String) = screenCoroutine { stateReducers.updateCountryDetail(country) }
0
null
0
0
9d8d62570eec47693d117d4352c314af6ffc8d96
348
D-KMP-sample
Apache License 2.0
shared/src/commonMain/kotlin/org/nautilusapp/nautilus/userauth/AccountType.kt
nautilus-frc
663,757,256
false
{"Kotlin": 651562, "Swift": 121224}
package org.nautilusapp.nautilus.userauth import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder @Serializable(with = AccountTypeSerializer::class) enum class AccountType(val value: Int) { SUPERUSER(4), ADMIN(3), LEAD(2), BASE(1), UNVERIFIED(0),; companion object { fun of(value: Int?): AccountType { return when(value) { in 4..Int.MAX_VALUE -> SUPERUSER 3 -> ADMIN 2 -> LEAD 1 -> BASE else -> UNVERIFIED } } } } object AccountTypeSerializer: KSerializer<AccountType> { override val descriptor: SerialDescriptor get() = PrimitiveSerialDescriptor("AccountType", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): AccountType { val num = decoder.decodeInt() return AccountType.of(num) } override fun serialize(encoder: Encoder, value: AccountType) { val number = value.value encoder.encodeInt(number) } }
8
Kotlin
0
0
007923615c2d574f6b58ac334f48603ca078adfc
1,334
companion
MIT License
v1/src/main/kotlin/com/example/forsubmit/domain/user/infrastructure/userinfo/dto/GithubUserInfoResponse.kt
jhhong0509
433,380,334
false
{"Kotlin": 84514, "Groovy": 81151, "Vim Snippet": 690}
package com.example.forsubmit.domain.user.infrastructure.userinfo.dto import com.fasterxml.jackson.annotation.JsonProperty class GithubUserInfoResponse( @JsonProperty("name") private val userName: String, @JsonProperty("login") private val userId: String ): BaseUserInfoResponse { override fun getAccountId(): String = userId override fun getName(): String = userName }
5
Kotlin
4
29
3f8effaca61e6d8f328e3aca7356cbd1d67335b4
396
Kopring-Best-Practice
Apache License 2.0
src/main/kotlin/com/example/demo/math/SimpleMath.kt
HoracioGomes
632,593,664
false
null
package com.example.demo.math import kotlin.math.sqrt class SimpleMath { fun sum(num1: Double, num2: Double) = num1 + num2 fun sub(num1: Double, num2: Double) = num1 - num2 fun mult(num1: Double, num2: Double) = num1 * num2 fun div(num1: Double, num2: Double) = num1 / num2 fun mean(num1: Double, num2: Double) = (num1 + num2) / 2 fun square(num: Double) = sqrt(num) }
0
Kotlin
0
0
150648e07e35566b90e6bed34346595c71484e1f
395
Calculadora-SpringBoot-With-Kotlin
Apache License 2.0
app/src/main/java/social/entourage/android/api/model/feed/NewsfeedItem.kt
ReseauEntourage
30,242,877
false
{"Kotlin": 1827995}
package social.entourage.android.api.model.feed import com.google.gson.* import social.entourage.android.api.model.BaseEntourage import timber.log.Timber import java.lang.reflect.Type /** * Created by mihaiionescu on 05/05/16. */ class NewsfeedItem { // ---------------------------------- // ATTRIBUTES // ---------------------------------- var type: String? = null var data: Any? = null // ---------------------------------- // PUBLIC METHODS // ---------------------------------- val id: Long get() { return (data as? BaseEntourage)?.id ?: 0 } class NewsfeedItemJsonAdapter : JsonDeserializer<NewsfeedItem> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): NewsfeedItem { val newsfeed = NewsfeedItem() val jsonObject = json.asJsonObject jsonObject[TYPE].asString?.let { newsfeed.type = it val jsonData = jsonObject[DATA].asJsonObject if (jsonData !=null) { try { getClassFromString(it, jsonData["group_type"]?.asString, jsonData["entourage_type"]?.asString)?.let { newsfeedClass -> val gson = GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .create() newsfeed.data = gson.fromJson<Any>(jsonData, newsfeedClass) } } catch (e: Exception) { Timber.e(e) } } } return newsfeed } } companion object { // ---------------------------------- // CONSTANTS // ---------------------------------- const val STATUS_ALL = "all" const val STATUS_ACTIVE = "active" const val STATUS_CLOSED = "closed" const val TYPE = "type" const val DATA = "data" fun getClassFromString(type: String, groupType:String?, actionGroupType: String?): Class<*>? { return when (type) { BaseEntourage.NEWSFEED_TYPE -> BaseEntourage.getClassFromString(groupType, actionGroupType) Announcement.NEWSFEED_TYPE -> Announcement::class.java else -> null } } } }
1
Kotlin
2
9
b5bc8b3c2180a11589271dbbb87f7dc7d44e4243
2,583
entourage-android
MIT License
feature-wallet-impl/src/main/java/jp/co/soramitsu/wallet/impl/presentation/balance/list/model/BalanceModel.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.wallet.impl.presentation.balance.list.model import jp.co.soramitsu.common.utils.fractionToPercentage import jp.co.soramitsu.common.utils.isZero import jp.co.soramitsu.common.utils.orZero import jp.co.soramitsu.common.utils.percentageToFraction import jp.co.soramitsu.common.utils.sumByBigDecimal import jp.co.soramitsu.wallet.impl.presentation.model.AssetWithStateModel import java.math.BigDecimal import java.math.RoundingMode class BalanceModel(val assetModels: List<AssetWithStateModel>, val fiatSymbol: String) { val totalBalance = calculateTotalBalance() val totalBalanceChange = calculateTotalBalanceChange() val isShowLoading = checkIsShowLoading() val isUpdating = checkIsUpdating() val isTokensUpdated = checkIsTokensUpdated() val totalTransferableBalance = calculateTotalTransferableBalance() val totalTransferableBalanceChange = calculateTotalTransferableBalanceChange() val rate = when { totalBalance == null -> null totalBalance.isZero() -> BigDecimal.ZERO else -> totalBalanceChange.divide(totalBalance, RoundingMode.HALF_UP).fractionToPercentage() } val transferableRate = when { totalTransferableBalance == null -> null totalTransferableBalance.isZero() -> BigDecimal.ZERO else -> totalTransferableBalanceChange.divide(totalTransferableBalance, RoundingMode.HALF_UP).fractionToPercentage() } private fun calculateTotalBalance(): BigDecimal? { return if (assetModels.filter { it.asset.token.fiatSymbol == fiatSymbol }.any { it.asset.fiatAmount != null }) { assetModels.sumByBigDecimal { it.asset.fiatAmount.orZero() } } else { null } } private fun calculateTotalTransferableBalance(): BigDecimal? { return if (assetModels.filter { it.asset.token.fiatSymbol == fiatSymbol }.any { it.asset.available != null }) { assetModels.sumByBigDecimal { it.asset.availableFiat.orZero() } } else { null } } private fun calculateTotalBalanceChange(): BigDecimal { return assetModels.fold(BigDecimal.ZERO) { acc, current -> val toAdd = current.asset.totalFiat?.multiply(current.asset.token.recentRateChange.orZero())?.percentageToFraction().orZero() acc + toAdd } } private fun calculateTotalTransferableBalanceChange(): BigDecimal { return assetModels.fold(BigDecimal.ZERO) { acc, current -> val toAdd = current.asset.availableFiat?.multiply(current.asset.token.recentRateChange.orZero())?.percentageToFraction().orZero() acc + toAdd } } private fun checkIsUpdating(): Boolean = assetModels.any { it.state.isFiatUpdating } private fun checkIsShowLoading(): Boolean { val amountTotal = assetModels.size val pareto = 0.8 val amountOfCurrentBalanceUpdating = assetModels.filter { it.state.isBalanceUpdating }.size val assumedAmountOfUpdated = amountTotal - amountOfCurrentBalanceUpdating val isLoading = assumedAmountOfUpdated < amountTotal * pareto return isLoading } private fun checkIsTokensUpdated(): Boolean { return !assetModels.any { it.state.isTokenFiatChanged == true } } }
11
Kotlin
22
70
70153dee5a1f2ea18cf51d09d3bb8e4d8d1e0c87
3,351
fearless-Android
Apache License 2.0
src/main/kotlin/dev/storozhenko/familybot/executors/pm/GetChatListExecutor.kt
AngryJKirk
114,262,178
false
null
package dev.storozhenko.familybot.executors.pm import dev.storozhenko.familybot.common.extensions.send import dev.storozhenko.familybot.models.router.ExecutorContext import dev.storozhenko.familybot.models.telegram.Chat import dev.storozhenko.familybot.repos.CommonRepository import dev.storozhenko.familybot.telegram.BotConfig import org.springframework.stereotype.Component import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMemberCount import org.telegram.telegrambots.meta.bots.AbsSender @Component class GetChatListExecutor( private val commonRepository: CommonRepository, botConfig: BotConfig ) : OnlyBotOwnerExecutor(botConfig) { override fun getMessagePrefix() = "chats" override fun execute(context: ExecutorContext): suspend (AbsSender) -> Unit { val chats = commonRepository.getChats() return { sender -> sender.send(context, "Active chats count=${chats.size}") val totalUsersCount = chats.sumOf { chat -> calculate(sender, chat) } sender.send(context, "Total users count=$totalUsersCount") } } private fun calculate( sender: AbsSender, chat: Chat ): Int { return runCatching { sender.execute(GetChatMemberCount(chat.idString)) } .getOrElse { 0 } } }
0
Kotlin
4
97
aff071c72503ffb9ad276fb9cc33d8408196795d
1,337
familybot
Apache License 2.0
app/src/main/java/com/app/moodtrack_android/util/NotificationQuestionnaireUtil.kt
martinheitmann
431,879,047
false
{"Kotlin": 272822}
package com.app.moodtrack_android.util import android.util.Log import com.app.moodtrack_android.model.notificationquestionnaire.NQCondition import com.app.moodtrack_android.model.notificationquestionnaire.NQEdge import com.app.moodtrack_android.model.notificationquestionnaire.NQNode import com.app.moodtrack_android.model.notificationquestionnaire.query_objects.NotificationQuestionnaireByTimeOfDay import com.app.moodtrack_android.model.notificationquestionnaire.question.NQQuestionChoice class NotificationQuestionnaireUtil { companion object { val TAG = "NotifQuestionnaireUtil" fun getInitialQuestion(notificationQuestionnaire: NotificationQuestionnaireByTimeOfDay): NQNode? { val nodes = notificationQuestionnaire.nodes nodes.find { n -> n.isSourceNode }?.let { return it } ?: return null } fun evaluateCondition(receivedChoice: NQQuestionChoice, condition: NQCondition) : Boolean? { try { val result: Boolean? val choiceValueType = receivedChoice.choiceValueType val choiceValue = receivedChoice.choiceValue val conditionString = condition.condition val conditionValue = condition.conditionValue result = when(choiceValueType){ NotificationChoiceType.TEXT.conditionType -> { Log.d(TAG, "evaluateCondition: evaluating text condition.") NotificationConditionUtil.evaluate(choiceValue, conditionString) } NotificationChoiceType.NUMBER.conditionType -> { Log.d(TAG, "evaluateCondition: evaluating number condition.") val choiceValueAsInt = choiceValue.toInt() val conditionValueAsInt = conditionValue.toInt() NotificationConditionUtil.evaluate(conditionString, choiceValueAsInt, conditionValueAsInt) } NotificationChoiceType.BOOLEAN.conditionType -> { Log.d(TAG, "evaluateCondition: evaluating boolean condition.") val choiceValueAsBool = choiceValue.toBoolean() NotificationConditionUtil.evaluate(choiceValueAsBool, conditionString) } else -> return null } Log.d(TAG, "evaluateCondition: evaluating returned $result.") return result } catch(e: Throwable){ Log.d(TAG, e.stackTraceToString()) return null } } fun getOutgoingEdgesForNode(currentNode: NQNode, notificationQuestionnaire: NotificationQuestionnaireByTimeOfDay): List<NQEdge> { return notificationQuestionnaire.edges.filter { e -> e.source == currentNode._id } } fun evaluateEdgeConditions(receivedChoice: NQQuestionChoice, edges: List<NQEdge>): NQEdge? { Log.d(TAG, "evaluateEdgeConditions: Invoked with ${edges.size} argument edges.") edges.forEach { edge -> val evalRes = evaluateCondition(receivedChoice, edge.condition) if(evalRes == true) return edge } return null } fun getNextNode(edgeToNextNode: NQEdge, notificationQuestionnaire: NotificationQuestionnaireByTimeOfDay): NQNode? { return notificationQuestionnaire.nodes.find { n -> n._id == edgeToNextNode.target } } } }
0
Kotlin
1
0
9b774c65c5e99e646c50370f17d97575b07ac46b
3,567
moodtrack-android
MIT License
coil-base/src/main/java/coil/memory/StrongMemoryCache.kt
ianhanniballake
384,854,300
true
{"Kotlin": 621189, "Shell": 1087}
package coil.memory import android.content.ComponentCallbacks2 import android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND import android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW import android.content.ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN import android.graphics.Bitmap import android.util.Log import androidx.collection.LruCache import coil.bitmap.BitmapReferenceCounter import coil.memory.MemoryCache.Key import coil.memory.RealMemoryCache.Value import coil.util.Logger import coil.util.allocationByteCountCompat import coil.util.log /** An in-memory cache that holds strong references [Bitmap]s. */ internal interface StrongMemoryCache { companion object { operator fun invoke( weakMemoryCache: WeakMemoryCache, referenceCounter: BitmapReferenceCounter, maxSize: Int, logger: Logger? ): StrongMemoryCache { return when { maxSize > 0 -> RealStrongMemoryCache(weakMemoryCache, referenceCounter, maxSize, logger) weakMemoryCache is RealWeakMemoryCache -> ForwardingStrongMemoryCache(weakMemoryCache) else -> EmptyStrongMemoryCache } } } /** The current size of the memory cache in bytes. */ val size: Int /** The maximum size of the memory cache in bytes. */ val maxSize: Int /** Get the value associated with [key]. */ fun get(key: Key): Value? /** Set the value associated with [key]. */ fun set(key: Key, bitmap: Bitmap, isSampled: Boolean) /** Remove the value referenced by [key] from this cache. */ fun remove(key: Key): Boolean /** Remove all values from this cache. */ fun clearMemory() /** @see ComponentCallbacks2.onTrimMemory */ fun trimMemory(level: Int) } /** A [StrongMemoryCache] implementation that caches nothing. */ private object EmptyStrongMemoryCache : StrongMemoryCache { override val size get() = 0 override val maxSize get() = 0 override fun get(key: Key): Value? = null override fun set(key: Key, bitmap: Bitmap, isSampled: Boolean) {} override fun remove(key: Key) = false override fun clearMemory() {} override fun trimMemory(level: Int) {} } /** A [StrongMemoryCache] implementation that caches nothing and delegates all [set] operations to a [weakMemoryCache]. */ private class ForwardingStrongMemoryCache( private val weakMemoryCache: WeakMemoryCache ) : StrongMemoryCache { override val size get() = 0 override val maxSize get() = 0 override fun get(key: Key): Value? = null override fun set(key: Key, bitmap: Bitmap, isSampled: Boolean) { weakMemoryCache.set(key, bitmap, isSampled, bitmap.allocationByteCountCompat) } override fun remove(key: Key) = false override fun clearMemory() {} override fun trimMemory(level: Int) {} } /** A [StrongMemoryCache] implementation backed by an [LruCache]. */ private class RealStrongMemoryCache( private val weakMemoryCache: WeakMemoryCache, private val referenceCounter: BitmapReferenceCounter, maxSize: Int, private val logger: Logger? ) : StrongMemoryCache { private val cache = object : LruCache<Key, InternalValue>(maxSize) { override fun entryRemoved( evicted: Boolean, key: Key, oldValue: InternalValue, newValue: InternalValue? ) { val isPooled = referenceCounter.decrement(oldValue.bitmap) if (!isPooled) { // Add the bitmap to the WeakMemoryCache if it wasn't just added to the BitmapPool. weakMemoryCache.set(key, oldValue.bitmap, oldValue.isSampled, oldValue.size) } } override fun sizeOf(key: Key, value: InternalValue) = value.size } override val size get() = cache.size() override val maxSize get() = cache.maxSize() @Synchronized override fun get(key: Key): Value? = cache.get(key) @Synchronized override fun set(key: Key, bitmap: Bitmap, isSampled: Boolean) { // If the bitmap is too big for the cache, don't even attempt to store it. Doing so will cause // the cache to be cleared. Instead just evict an existing element with the same key if it exists. val size = bitmap.allocationByteCountCompat if (size > maxSize) { val previous = cache.remove(key) if (previous == null) { // If previous != null, the value was already added to the weak memory cache in LruCache.entryRemoved. weakMemoryCache.set(key, bitmap, isSampled, size) } return } referenceCounter.increment(bitmap) cache.put(key, InternalValue(bitmap, isSampled, size)) } @Synchronized override fun remove(key: Key): Boolean { return cache.remove(key) != null } @Synchronized override fun clearMemory() { logger?.log(TAG, Log.VERBOSE) { "clearMemory" } cache.trimToSize(-1) } @Synchronized override fun trimMemory(level: Int) { logger?.log(TAG, Log.VERBOSE) { "trimMemory, level=$level" } if (level >= TRIM_MEMORY_BACKGROUND) { clearMemory() } else if (level in TRIM_MEMORY_RUNNING_LOW until TRIM_MEMORY_UI_HIDDEN) { cache.trimToSize(size / 2) } } private class InternalValue( override val bitmap: Bitmap, override val isSampled: Boolean, val size: Int ) : Value companion object { private const val TAG = "RealStrongMemoryCache" } }
0
null
0
1
f152e172dbfe6b9c231967242f16dc63fda422e8
5,623
coil
Apache License 2.0
src/main/kotlin/no/nav/k9/tjenester/mock/MockApis.kt
navikt
238,874,021
false
{"Kotlin": 1562879, "JavaScript": 741, "Shell": 659, "Dockerfile": 343, "PLpgSQL": 167}
package no.nav.k9.los.tjenester.mock import io.ktor.server.application.call import io.ktor.server.html.respondHtml import io.ktor.http.HttpStatusCode import io.ktor.server.request.receive import io.ktor.server.response.respond import io.ktor.server.routing.Route import io.ktor.server.routing.get import io.ktor.server.routing.post import kotlinx.coroutines.runBlocking import kotlinx.html.InputType import kotlinx.html.a import kotlinx.html.body import kotlinx.html.button import kotlinx.html.classes import kotlinx.html.div import kotlinx.html.h1 import kotlinx.html.head import kotlinx.html.id import kotlinx.html.input import kotlinx.html.onChange import kotlinx.html.onClick import kotlinx.html.option import kotlinx.html.p import kotlinx.html.script import kotlinx.html.select import kotlinx.html.span import kotlinx.html.styleLink import kotlinx.html.table import kotlinx.html.td import kotlinx.html.textInput import kotlinx.html.thead import kotlinx.html.title import kotlinx.html.tr import no.nav.k9.los.KoinProfile import no.nav.k9.los.aksjonspunktbehandling.K9punsjEventHandler import no.nav.k9.los.aksjonspunktbehandling.K9sakEventHandler import no.nav.k9.los.domene.modell.AksjonspunktDefWrapper import no.nav.k9.los.domene.modell.BehandlingStatus import no.nav.k9.los.domene.modell.Fagsystem import no.nav.k9.los.domene.repository.BehandlingProsessEventK9Repository import no.nav.k9.los.domene.repository.OppgaveKøRepository import no.nav.k9.los.domene.repository.OppgaveRepository import no.nav.k9.los.domene.repository.PunsjEventK9Repository import no.nav.k9.los.domene.repository.SaksbehandlerRepository import no.nav.k9.los.integrasjon.kafka.dto.BehandlingProsessEventDto import no.nav.k9.los.integrasjon.kafka.dto.EventHendelse import no.nav.k9.los.integrasjon.kafka.dto.PunsjEventDto import no.nav.k9.kodeverk.behandling.aksjonspunkt.AksjonspunktDefinisjon import no.nav.k9.sak.typer.AktørId import no.nav.k9.sak.typer.JournalpostId import org.koin.ktor.ext.inject import java.time.LocalDate import java.time.LocalDateTime import java.util.* import kotlin.collections.set fun Route.MockGrensesnitt() { val k9sakEventHandler by inject<K9sakEventHandler>() val k9punsjEventHandler by inject<K9punsjEventHandler>() val behandlingProsessEventRepository by inject<BehandlingProsessEventK9Repository>() val punsjEventK9Repository by inject<PunsjEventK9Repository>() val oppgaveKøRepository by inject<OppgaveKøRepository>() val oppgaveRepository by inject<OppgaveRepository>() val saksbehandlerRepository by inject<SaksbehandlerRepository>() val profile by inject<KoinProfile>() get { if (profile == KoinProfile.PROD) { call.respond(HttpStatusCode.NotFound) } else { call.respondHtml { head { title { +"Test app for k9-los" } styleLink("/static/bootstrap.css") script(src = "/static/script.js") {} } body { div { classes = setOf("container ") a { href = "/mock/endreBehandling" +"Endre behandling" } h1 { +"Testside for k9-los" } p { +"Aksjonspunkter toggles av og på som hendelser. En behandling regnes som avsluttet dersom den er opprettet og ikke lengre har noen aksjonspunkter som operative" } div { classes = setOf("input-group", "mb-3") div { classes = setOf("input-group-prepend") span { classes = setOf("input-group-text") +"EksternId" } } textInput { classes = setOf("form-control") id = "uuid" value = UUID.randomUUID().toString() } } div { classes = setOf("input-group", "mb-3") div { classes = setOf("input-group-prepend") span { classes = setOf("input-group-text") +"Aktørid" } } textInput { classes = setOf("form-control") id = "aktørid" value = "26104500284" } } for (aksjonspunkt in AksjonspunkterMock().aksjonspunkter()) { div { classes = setOf("input-group") div { classes = setOf("input-group-prepend") div { classes = setOf("input-group-text") input(InputType.checkBox) { id = "Checkbox${aksjonspunkt.kode}" onClick = "toggle('${aksjonspunkt.kode}')" } } } div { classes = setOf("input-group-text display-4") +"${aksjonspunkt.kode} ${aksjonspunkt.navn} Type: ${aksjonspunkt.behandlingsstegtype} Plassering: ${aksjonspunkt.plassering} Totrinn: ${aksjonspunkt.totrinn}" } } } } } } } } post("/toggleaksjonspunkt") { if (profile == KoinProfile.PROD) { call.respond(HttpStatusCode.NotFound) } else { val aksjonspunktToggle = call.receive<AksjonspunktToggle>() // punsj time if (AksjonspunktDefWrapper.aksjonspunkterFraPunsj().map { a -> a.kode }.contains(aksjonspunktToggle.kode)) { val modell = punsjEventK9Repository.hent(UUID.fromString(aksjonspunktToggle.eksternid)) val punsjEventDto = if (modell.erTom()) { PunsjEventDto( eksternId = UUID.fromString(aksjonspunktToggle.eksternid), aksjonspunktKoderMedStatusListe = mutableMapOf(aksjonspunktToggle.kode to "OPPR"), journalpostId = JournalpostId("133742069666"), eventTid = LocalDateTime.now(), aktørId = AktørId(aksjonspunktToggle.aktørid) ) } else { val sisteEvent = modell.sisteEvent() sisteEvent.aksjonspunktKoderMedStatusListe[aksjonspunktToggle.kode] = if (aksjonspunktToggle.toggle) "OPPR" else "AVSL" PunsjEventDto( eksternId = sisteEvent.eksternId, aksjonspunktKoderMedStatusListe = sisteEvent.aksjonspunktKoderMedStatusListe, journalpostId = sisteEvent.journalpostId, eventTid = LocalDateTime.now(), aktørId = sisteEvent.aktørId ) } k9punsjEventHandler.prosesser(punsjEventDto) } else { val modell = behandlingProsessEventRepository.hent(UUID.fromString(aksjonspunktToggle.eksternid)) val event = if (modell.erTom()) { BehandlingProsessEventDto( UUID.fromString(aksjonspunktToggle.eksternid), Fagsystem.K9SAK, "Saksnummer", aksjonspunktToggle.aktørid, vedtaksdato = null, 1234L, LocalDate.now(), LocalDateTime.now(), EventHendelse.AKSJONSPUNKT_OPPRETTET, behandlingStatus = "UTRED", aksjonspunktKoderMedStatusListe = mutableMapOf(aksjonspunktToggle.kode to "OPPR"), behandlingSteg = "", opprettetBehandling = LocalDateTime.now(), eldsteDatoMedEndringFraSøker = LocalDateTime.now(), behandlingTypeKode = "BT-004", ytelseTypeKode = "OMP", aksjonspunktTilstander = emptyList() ) } else { val sisteEvent = modell.sisteEvent() sisteEvent.aksjonspunktKoderMedStatusListe[aksjonspunktToggle.kode] = if (aksjonspunktToggle.toggle) "OPPR" else "AVSL" BehandlingProsessEventDto( sisteEvent.eksternId, sisteEvent.fagsystem, sisteEvent.saksnummer, sisteEvent.aktørId, vedtaksdato = null, sisteEvent.behandlingId, LocalDate.now(), LocalDateTime.now(), EventHendelse.AKSJONSPUNKT_OPPRETTET, behandlingStatus = sisteEvent.behandlingStatus, aksjonspunktKoderMedStatusListe = sisteEvent.aksjonspunktKoderMedStatusListe, behandlingSteg = "", opprettetBehandling = LocalDateTime.now(), eldsteDatoMedEndringFraSøker = LocalDateTime.now(), behandlingTypeKode = "BT-004", ytelseTypeKode = sisteEvent.ytelseTypeKode, aksjonspunktTilstander = emptyList() ) } k9sakEventHandler.prosesser(event) } call.respond(HttpStatusCode.Accepted) } } get("/10000AktiveEventer") { if (profile == KoinProfile.PROD) { call.respond(HttpStatusCode.NotFound) } else { for (i in 0..10000 step 1) { val event = BehandlingProsessEventDto( UUID.randomUUID(), Fagsystem.K9SAK, "Saksnummer", UUID.randomUUID().toString(), vedtaksdato = null, 1234L, LocalDate.now(), LocalDateTime.now(), EventHendelse.AKSJONSPUNKT_OPPRETTET, behandlingStatus = "UTRED", aksjonspunktKoderMedStatusListe = mutableMapOf(AksjonspunktDefinisjon.AVKLAR_OPPHOLDSRETT.kode to "OPPR"), behandlingSteg = "", opprettetBehandling = LocalDateTime.now(), eldsteDatoMedEndringFraSøker = LocalDateTime.now(), behandlingTypeKode = "BT-004", ytelseTypeKode = "OMP", aksjonspunktTilstander = emptyList() // TODO skal være lik aksjonspunktKoderMedStatus ) k9sakEventHandler.prosesser(event) } call.respond(HttpStatusCode.Accepted) } } get("/endreBehandling") { if (profile == KoinProfile.PROD) { call.respond(HttpStatusCode.NotFound) } else { val valgtKø = call.request.queryParameters["valgtKø"] val ferdigStill = call.request.queryParameters["ferdigstill"] if (ferdigStill != null) { k9sakEventHandler.prosesser( behandlingProsessEventRepository.hent(UUID.fromString(ferdigStill)).sisteEvent() .copy( behandlingStatus = BehandlingStatus.AVSLUTTET.kode, aksjonspunktKoderMedStatusListe = mutableMapOf(), eventTid = LocalDateTime.now() ) ) } val oppgavekøer = oppgaveKøRepository.hentIkkeTaHensyn() call.respondHtml { head { title { +"Test app for k9-los" } styleLink("/static/bootstrap.css") script(src = "/static/script.js") {} } body { div { classes = setOf("container ") a { href = "/mock" +"Mock" } h1 { +"Endre behandling" } select { classes = setOf("form-control") id = "valgtKø" //language=JavaScript onChange = "window.location.search ='?valgtKø=' + document.getElementById('valgtKø').value;" option { disabled = true selected = true +"Velg kø" } option { selected = "reserverte" == valgtKø value = "reserverte" +"Reserverte" } for (oppgaveKø in oppgavekøer) { option { selected = oppgaveKø.id.toString() == valgtKø value = oppgaveKø.id.toString() +oppgaveKø.navn } } } if (valgtKø != null) { val oppgaver = runBlocking { if (valgtKø == "reserverte") { oppgaveRepository .hentOppgaver( saksbehandlerRepository.hentAlleSaksbehandlereIkkeTaHensyn() .flatMap { it.reservasjoner }) } else { oppgaveRepository .hentOppgaver(oppgavekøer.first { it.id == UUID.fromString(valgtKø) } .oppgaverOgDatoer.take(20).map { it.id }) } } table { classes = setOf("table") thead { tr { td { +"Saksnummer" } td { +"Behandlingstatus" } td { +"" } } } for (oppgave in oppgaver) { tr { td { +oppgave.fagsakSaksnummer } td { +oppgave.behandlingStatus.navn } td { button { classes = setOf("btn", "btn-dark") //language=JavaScript onClick = "window.location.search = (window.location.search.lastIndexOf('&') == -1 ? window.location.search : window.location.search.substr(0,window.location.search.lastIndexOf('&'))) +'&ferdigstill=${oppgave.eksternId}';" +"Ferdigstill" } } } } } } } } } } } }
9
Kotlin
0
0
c75348901ee4aad513888a7111e005090900c6f9
17,141
k9-los-api
MIT License
compiler/testData/diagnostics/testsWithStdLib/tryCatch/falsePositiveSmartcasts.kt
JetBrains
3,432,266
false
null
// !WITH_NEW_INFERENCE // !LANGUAGE: +NewDataFlowForTryExpressions // !DIAGNOSTICS: -UNUSED_VARIABLE -UNUSED_VALUE -VARIABLE_WITH_REDUNDANT_INITIALIZER // SKIP_TXT // Related issue: KT-28370 class ExcA : Exception() class ExcB : Exception() fun test1() { var x: String? = null x = "" try { x = null } catch (e: Exception) { <!DEBUG_INFO_SMARTCAST{OI}!>x<!><!UNSAFE_CALL{NI}!>.<!>length // smartcast shouldn't be allowed (OOME could happen after `x = null`) throw e } finally { // smartcast shouldn't be allowed, `x = null` could've happened <!DEBUG_INFO_SMARTCAST{OI}!>x<!><!UNSAFE_CALL{NI}!>.<!>length } // smartcast shouldn't be allowed, `x = null` could've happened <!DEBUG_INFO_SMARTCAST{OI}!>x<!><!UNSAFE_CALL{NI}!>.<!>length } // With old DFA of try/catch info about unsound smartcasts after try // removes only if there is at least one catch branch that not returns Nothing fun test2() { var x: String? = null x = "" try { x = null } catch (e: Exception) { // BAD <!DEBUG_INFO_SMARTCAST{OI}!>x<!><!UNSAFE_CALL{NI}!>.<!>length } finally { x<!UNSAFE_CALL!>.<!>length } x<!UNSAFE_CALL!>.<!>length } fun test3() { var t2: Boolean? = true if (t2 != null) { // or `t2 is Boolean` try { throw Exception() } catch (e: Exception) { t2 = null } <!DEBUG_INFO_SMARTCAST{OI}!>t2<!><!UNSAFE_CALL{NI}!>.<!>not() // wrong smartcast, NPE } } fun test4() { var t2: Boolean? = true if (t2 != null) { // or `t2 is Boolean` try { t2 = null } finally { } <!DEBUG_INFO_SMARTCAST{OI}!>t2<!><!UNSAFE_CALL{NI}!>.<!>not() // wrong smartcast, NPE } } fun test5() { var s1: String? = null var s2: String? = null s1 = "" s2 = "" try { TODO() } catch (e: ExcA) { s1 = "" } catch (e: ExcB) { s2 = null return } finally { <!DEBUG_INFO_SMARTCAST{OI}!>s1<!><!UNSAFE_CALL{NI}!>.<!>length <!DEBUG_INFO_SMARTCAST{OI}!>s2<!><!UNSAFE_CALL{NI}!>.<!>length } <!DEBUG_INFO_SMARTCAST{OI}!>s1<!><!UNSAFE_CALL{NI}!>.<!>length <!DEBUG_INFO_SMARTCAST!>s2<!>.length } fun test6(s1: String?, s2: String?) { var s: String? = null s = "" try { s = null requireNotNull(s1) } catch (e: Exception) { return } finally { <!DEBUG_INFO_SMARTCAST{OI}!>s<!><!UNSAFE_CALL{NI}!>.<!>length requireNotNull(s2) } <!DEBUG_INFO_SMARTCAST{OI}!>s<!><!UNSAFE_CALL{NI}!>.<!>length <!DEBUG_INFO_SMARTCAST{NI}!>s1<!><!UNSAFE_CALL{OI}!>.<!>length <!DEBUG_INFO_SMARTCAST!>s2<!>.length }
182
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
2,772
kotlin
Apache License 2.0
kotlinpoet/src/main/java/com/squareup/kotlinpoet/TypeName.kt
LloydFinch
224,367,360
false
null
/* * Copyright (C) 2015 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ @file:JvmName("TypeNames") package com.squareup.kotlinpoet import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import java.lang.reflect.GenericArrayType import java.lang.reflect.Modifier.isStatic import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.lang.reflect.TypeVariable import java.lang.reflect.WildcardType import java.util.Collections import javax.lang.model.element.Modifier import javax.lang.model.element.TypeElement import javax.lang.model.element.TypeParameterElement import javax.lang.model.type.ArrayType import javax.lang.model.type.DeclaredType import javax.lang.model.type.ErrorType import javax.lang.model.type.NoType import javax.lang.model.type.PrimitiveType import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror import javax.lang.model.util.SimpleTypeVisitor7 import kotlin.reflect.KClass import kotlin.reflect.KTypeProjection import kotlin.reflect.KVariance import kotlin.reflect.typeOf /** * Any type in Kotlin's type system. This class identifies simple types like `Int` and `String`, * nullable types like `Int?`, composite types like `Array<String>` and `Set<String>`, and * unassignable types like `Unit`. * * Type names are dumb identifiers only and do not model the values they name. For example, the * type name for `kotlin.List` doesn't know about the `size()` function, the fact that lists are * collections, or even that it accepts a single type parameter. * * Instances of this class are immutable value objects that implement `equals()` and `hashCode()` * properly. * * Referencing existing types * -------------------------- * * In an annotation processor you can get a type name instance for a type mirror by calling * [asTypeName]. In reflection code, you can use [asTypeName]. * Defining new types * ------------------ * * Create new reference types like `com.example.HelloWorld` with [ClassName.bestGuess]. To build composite * types like `Set<Long>`, use the factory methods on [ParameterizedTypeName], [TypeVariableName], * and [WildcardTypeName]. */ sealed class TypeName constructor( val isNullable: Boolean, annotations: List<AnnotationSpec>, internal val tagMap: TagMap ) : Taggable by tagMap { val annotations = annotations.toImmutableList() /** Lazily-initialized toString of this type name. */ private val cachedString: String by lazy { buildCodeString { emitAnnotations(this) emit(this) if (isNullable) emit("?") } } fun copy( nullable: Boolean = this.isNullable, annotations: List<AnnotationSpec> = this.annotations.toList() ): TypeName { return copy(nullable, annotations, emptyMap()) } abstract fun copy( nullable: Boolean = this.isNullable, annotations: List<AnnotationSpec> = this.annotations.toList(), tags: Map<KClass<*>, Any> = this.tags ): TypeName val isAnnotated get() = annotations.isNotEmpty() override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false if (javaClass != other.javaClass) return false return toString() == other.toString() } override fun hashCode() = toString().hashCode() override fun toString() = cachedString internal abstract fun emit(out: CodeWriter): CodeWriter internal fun emitAnnotations(out: CodeWriter) { for (annotation in annotations) { annotation.emit(out, true) out.emit(" ") } } internal fun emitNullable(out: CodeWriter) { if (isNullable) { out.emit("?") } } companion object { internal fun get( mirror: TypeMirror, typeVariables: Map<TypeParameterElement, TypeVariableName> ): TypeName { return mirror.accept(object : SimpleTypeVisitor7<TypeName, Void?>() { override fun visitPrimitive(t: PrimitiveType, p: Void?): TypeName { return when (t.kind) { TypeKind.BOOLEAN -> BOOLEAN TypeKind.BYTE -> BYTE TypeKind.SHORT -> SHORT TypeKind.INT -> INT TypeKind.LONG -> LONG TypeKind.CHAR -> CHAR TypeKind.FLOAT -> FLOAT TypeKind.DOUBLE -> DOUBLE else -> throw AssertionError() } } override fun visitDeclared(t: DeclaredType, p: Void?): TypeName { val rawType: ClassName = (t.asElement() as TypeElement).asClassName() val enclosingType = t.enclosingType val enclosing = if (enclosingType.kind != TypeKind.NONE && Modifier.STATIC !in t.asElement().modifiers) enclosingType.accept(this, null) else null if (t.typeArguments.isEmpty() && enclosing !is ParameterizedTypeName) { return rawType } val typeArgumentNames = mutableListOf<TypeName>() for (typeArgument in t.typeArguments) { typeArgumentNames += get(typeArgument, typeVariables) } return if (enclosing is ParameterizedTypeName) enclosing.nestedClass(rawType.simpleName, typeArgumentNames) else ParameterizedTypeName(null, rawType, typeArgumentNames) } override fun visitError(t: ErrorType, p: Void?): TypeName { return visitDeclared(t, p) } override fun visitArray(t: ArrayType, p: Void?): ParameterizedTypeName { return ARRAY.parameterizedBy(TypeName.get(t.componentType, typeVariables)) } override fun visitTypeVariable( t: javax.lang.model.type.TypeVariable, p: Void? ): TypeName { return TypeVariableName.get(t, typeVariables.toMutableMap()) } override fun visitWildcard(t: javax.lang.model.type.WildcardType, p: Void?): TypeName { return WildcardTypeName.get(t, typeVariables) } override fun visitNoType(t: NoType, p: Void?): TypeName { if (t.kind == TypeKind.VOID) return UNIT return super.visitUnknown(t, p) } override fun defaultAction(e: TypeMirror?, p: Void?): TypeName { throw IllegalArgumentException("Unexpected type mirror: " + e!!) } }, null) } internal fun get(type: Type, map: MutableMap<Type, TypeVariableName>): TypeName { return when (type) { is Class<*> -> when { type === Void.TYPE -> UNIT type === Boolean::class.javaPrimitiveType -> BOOLEAN type === Byte::class.javaPrimitiveType -> BYTE type === Short::class.javaPrimitiveType -> SHORT type === Int::class.javaPrimitiveType -> INT type === Long::class.javaPrimitiveType -> LONG type === Char::class.javaPrimitiveType -> CHAR type === Float::class.javaPrimitiveType -> FLOAT type === Double::class.javaPrimitiveType -> DOUBLE type.isArray -> ARRAY.parameterizedBy(get(type.componentType, map)) else -> type.asClassName() } is ParameterizedType -> ParameterizedTypeName.get(type, map) is WildcardType -> WildcardTypeName.get(type, map) is TypeVariable<*> -> TypeVariableName.get(type, map) is GenericArrayType -> ARRAY.parameterizedBy(get(type.genericComponentType, map)) else -> throw IllegalArgumentException("unexpected type: " + type) } } } } @JvmField val ANY = ClassName("kotlin", "Any") @JvmField val ARRAY = ClassName("kotlin", "Array") @JvmField val UNIT = Unit::class.asClassName() @JvmField val BOOLEAN = ClassName("kotlin", "Boolean") @JvmField val BYTE = ClassName("kotlin", "Byte") @JvmField val SHORT = ClassName("kotlin", "Short") @JvmField val INT = ClassName("kotlin", "Int") @JvmField val LONG = ClassName("kotlin", "Long") @JvmField val CHAR = ClassName("kotlin", "Char") @JvmField val FLOAT = ClassName("kotlin", "Float") @JvmField val DOUBLE = ClassName("kotlin", "Double") @JvmField val STRING = ClassName("kotlin", "String") @JvmField val CHAR_SEQUENCE = ClassName("kotlin", "CharSequence") @JvmField val COMPARABLE = ClassName("kotlin", "Comparable") @JvmField val THROWABLE = ClassName("kotlin", "Throwable") @JvmField val ANNOTATION = ClassName("kotlin", "Annotation") @JvmField val NOTHING = ClassName("kotlin", "Nothing") @JvmField val NUMBER = ClassName("kotlin", "Number") @JvmField val ITERABLE = ClassName("kotlin.collections", "Iterable") @JvmField val COLLECTION = ClassName("kotlin.collections", "Collection") @JvmField val LIST = ClassName("kotlin.collections", "List") @JvmField val SET = ClassName("kotlin.collections", "Set") @JvmField val MAP = ClassName("kotlin.collections", "Map") @JvmField val MAP_ENTRY = MAP.nestedClass("Entry") @JvmField val MUTABLE_ITERABLE = ClassName("kotlin.collections", "MutableIterable") @JvmField val MUTABLE_COLLECTION = ClassName("kotlin.collections", "MutableCollection") @JvmField val MUTABLE_LIST = ClassName("kotlin.collections", "MutableList") @JvmField val MUTABLE_SET = ClassName("kotlin.collections", "MutableSet") @JvmField val MUTABLE_MAP = ClassName("kotlin.collections", "MutableMap") @JvmField val MUTABLE_MAP_ENTRY = MUTABLE_MAP.nestedClass("Entry") @JvmField val BOOLEAN_ARRAY = ClassName("kotlin", "BooleanArray") @JvmField val BYTE_ARRAY = ClassName("kotlin", "ByteArray") @JvmField val CHAR_ARRAY = ClassName("kotlin", "CharArray") @JvmField val SHORT_ARRAY = ClassName("kotlin", "ShortArray") @JvmField val INT_ARRAY = ClassName("kotlin", "IntArray") @JvmField val LONG_ARRAY = ClassName("kotlin", "LongArray") @JvmField val FLOAT_ARRAY = ClassName("kotlin", "FloatArray") @JvmField val DOUBLE_ARRAY = ClassName("kotlin", "DoubleArray") @JvmField val ENUM = ClassName("kotlin", "Enum") @JvmField val U_BYTE = ClassName("kotlin", "UByte") @JvmField val U_SHORT = ClassName("kotlin", "UShort") @JvmField val U_INT = ClassName("kotlin", "UInt") @JvmField val U_LONG = ClassName("kotlin", "ULong") @JvmField val U_BYTE_ARRAY = ClassName("kotlin", "UByteArray") @JvmField val U_SHORT_ARRAY = ClassName("kotlin", "UShortArray") @JvmField val U_INT_ARRAY = ClassName("kotlin", "UIntArray") @JvmField val U_LONG_ARRAY = ClassName("kotlin", "ULongArray") /** The wildcard type `*` which is shorthand for `out Any?`. */ @JvmField val STAR = WildcardTypeName.producerOf(ANY.copy(nullable = true)) /** [Dynamic] is a singleton `object` type, so this is a shorthand for it in Java. */ @JvmField val DYNAMIC = Dynamic /** Returns a [TypeName] equivalent to this [TypeMirror]. */ @JvmName("get") fun TypeMirror.asTypeName() = TypeName.get(this, mutableMapOf()) /** Returns a [TypeName] equivalent to this [KClass]. */ @JvmName("get") fun KClass<*>.asTypeName() = asClassName() /** Returns a [TypeName] equivalent to this [Type]. */ @JvmName("get") fun Type.asTypeName() = TypeName.get(this, mutableMapOf()) @ExperimentalStdlibApi inline fun <reified T> typeNameOf(): TypeName = typeOf<T>().asTypeName() /** A fully-qualified class name for top-level and member classes. */ class ClassName internal constructor( names: List<String>, nullable: Boolean = false, annotations: List<AnnotationSpec> = emptyList(), tags: Map<KClass<*>, Any> = emptyMap() ) : TypeName(nullable, annotations, TagMap(tags)), Comparable<ClassName> { /** * Returns a class name created from the given parts. For example, calling this with package name * `"java.util"` and simple names `"Map"`, `"Entry"` yields `Map.Entry`. */ @Deprecated("", level = DeprecationLevel.HIDDEN) constructor(packageName: String, simpleName: String, vararg simpleNames: String) : this(listOf(packageName, simpleName, *simpleNames)) /** * Returns a class name created from the given parts. For example, calling this with package name * `"java.util"` and simple names `"Map"`, `"Entry"` yields `Map.Entry`. */ constructor(packageName: String, vararg simpleNames: String) : this(listOf(packageName, *simpleNames)) { require(simpleNames.isNotEmpty()) { "simpleNames must not be empty" } require(simpleNames.none { it.isEmpty() }) { "simpleNames must not contain empty items: ${simpleNames.contentToString()}" } } /** * Returns a class name created from the given parts. For example, calling this with package name * `"java.util"` and simple names `"Map"`, `"Entry"` yields `Map.Entry`. */ constructor(packageName: String, simpleNames: List<String>) : this(mutableListOf(packageName).apply { addAll(simpleNames) }) { require(simpleNames.isNotEmpty()) { "simpleNames must not be empty" } require(simpleNames.none { it.isEmpty() }) { "simpleNames must not contain empty items: $simpleNames" } } /** From top to bottom. This will be `["java.util", "Map", "Entry"]` for `Map.Entry`. */ private val names = names.toImmutableList() /** Fully qualified name using `.` as a separator, like `kotlin.collections.Map.Entry`. */ val canonicalName = if (names[0].isEmpty()) names.subList(1, names.size).joinToString(".") else names.joinToString(".") /** Package name, like `"kotlin.collections"` for `Map.Entry`. */ val packageName get() = names[0] /** Simple name of this class, like `"Entry"` for `Map.Entry`. */ val simpleName get() = names[names.size - 1] /** * The enclosing classes, outermost first, followed by the simple name. This is `["Map", "Entry"]` * for `Map.Entry`. */ val simpleNames get() = names.subList(1, names.size) init { for (i in 1 until names.size) { require(names[i].isName) { "part ${names[i]} is keyword" } } } override fun copy( nullable: Boolean, annotations: List<AnnotationSpec>, tags: Map<KClass<*>, Any> ): ClassName { return ClassName(names, nullable, annotations, tags) } /** * Returns the enclosing class, like `Map` for `Map.Entry`. Returns null if this class is not * nested in another class. */ fun enclosingClassName(): ClassName? { return if (names.size != 2) ClassName(names.subList(0, names.size - 1)) else null } /** * Returns the top class in this nesting group. Equivalent to chained calls to * [ClassName.enclosingClassName] until the result's enclosing class is null. */ fun topLevelClassName() = ClassName(names.subList(0, 2)) /** * Fully qualified name using `.` to separate package from the top level class name, and `$` to * separate nested classes, like `kotlin.collections.Map$Entry`. */ fun reflectionName(): String { // trivial case: no nested names if (names.size == 2) { return if (packageName.isEmpty()) names[1] else packageName + "." + names[1] } // concat top level class name and nested names return buildString { append(topLevelClassName()) for (name in simpleNames.subList(1, simpleNames.size)) { append('$').append(name) } } } /** * Callable reference to the constructor of this class. Emits the enclosing class if one exists, * followed by the reference operator `::`, followed by either [simpleName] or the * fully-qualified name if this is a top-level class. * * Note: As `::$packageName.$simpleName` is not valid syntax, an aliased import may be required * for a top-level class with a conflicting name. */ fun constructorReference(): CodeBlock { val enclosing = enclosingClassName() return if (enclosing != null) { CodeBlock.of("%T::%N", enclosing, simpleName) } else { CodeBlock.of("::%T", this) } } /** Returns a new [ClassName] instance for the specified `name` as nested inside this class. */ fun nestedClass(name: String) = ClassName(names + name) /** * Returns a class that shares the same enclosing package or class. If this class is enclosed by * another class, this is equivalent to `enclosingClassName().nestedClass(name)`. Otherwise * it is equivalent to `get(packageName(), name)`. */ fun peerClass(name: String): ClassName { val result = names.toMutableList() result[result.size - 1] = name return ClassName(result) } /** * Orders by the fully-qualified name. Nested types are ordered immediately after their * enclosing type. For example, the following types are ordered by this method: * * ``` * com.example.Robot * com.example.Robot.Motor * com.example.RoboticVacuum * ``` */ override fun compareTo(other: ClassName) = canonicalName.compareTo(other.canonicalName) override fun emit(out: CodeWriter) = out.emit(out.lookupName(this).escapeSegmentsIfNecessary()) companion object { /** * Returns a new [ClassName] instance for the given fully-qualified class name string. This * method assumes that the input is ASCII and follows typical Java style (lowercase package * names, UpperCamelCase class names) and may produce incorrect results or throw * [IllegalArgumentException] otherwise. For that reason, the constructor should be preferred as * it can create [ClassName] instances without such restrictions. */ @JvmStatic fun bestGuess(classNameString: String): ClassName { val names = mutableListOf<String>() // Add the package name, like "java.util.concurrent", or "" for no package. var p = 0 while (p < classNameString.length && Character.isLowerCase(classNameString.codePointAt(p))) { p = classNameString.indexOf('.', p) + 1 require(p != 0) { "couldn't make a guess for $classNameString" } } names += if (p != 0) classNameString.substring(0, p - 1) else "" // Add the class names, like "Map" and "Entry". for (part in classNameString.substring(p).split('.')) { require(part.isNotEmpty() && Character.isUpperCase(part.codePointAt(0))) { "couldn't make a guess for $classNameString" } names += part } require(names.size >= 2) { "couldn't make a guess for $classNameString" } return ClassName(names) } } } object Dynamic : TypeName(false, emptyList(), TagMap(emptyMap())) { override fun copy( nullable: Boolean, annotations: List<AnnotationSpec>, tags: Map<KClass<*>, Any> ) = throw UnsupportedOperationException("dynamic doesn't support copying") override fun emit(out: CodeWriter) = out.apply { emit("dynamic") } } class LambdaTypeName private constructor( val receiver: TypeName? = null, parameters: List<ParameterSpec> = emptyList(), val returnType: TypeName = UNIT, nullable: Boolean = false, val isSuspending: Boolean = false, annotations: List<AnnotationSpec> = emptyList(), tags: Map<KClass<*>, Any> = emptyMap() ) : TypeName(nullable, annotations, TagMap(tags)) { val parameters = parameters.toImmutableList() init { for (param in parameters) { require(param.annotations.isEmpty()) { "Parameters with annotations are not allowed" } require(param.modifiers.isEmpty()) { "Parameters with modifiers are not allowed" } require(param.defaultValue == null) { "Parameters with default values are not allowed" } } } override fun copy( nullable: Boolean, annotations: List<AnnotationSpec>, tags: Map<KClass<*>, Any> ): LambdaTypeName { return copy(nullable, annotations, this.isSuspending, tags) } fun copy( nullable: Boolean = this.isNullable, annotations: List<AnnotationSpec> = this.annotations.toList(), suspending: Boolean = this.isSuspending, tags: Map<KClass<*>, Any> = this.tags.toMap() ): LambdaTypeName { return LambdaTypeName(receiver, parameters, returnType, nullable, suspending, annotations, tags) } override fun emit(out: CodeWriter): CodeWriter { emitAnnotations(out) if (isNullable) { out.emit("(") } if (isSuspending) { out.emit("suspend ") } receiver?.let { if (it.isAnnotated) { out.emitCode("(%T).", it) } else { out.emitCode("%T.", it) } } parameters.emit(out) out.emitCode(if (returnType is LambdaTypeName) " -> (%T)" else " -> %T", returnType) if (isNullable) { out.emit(")") } return out } companion object { /** Returns a lambda type with `returnType` and parameters listed in `parameters`. */ @JvmStatic fun get( receiver: TypeName? = null, parameters: List<ParameterSpec> = emptyList(), returnType: TypeName ) = LambdaTypeName(receiver, parameters, returnType) /** Returns a lambda type with `returnType` and parameters listed in `parameters`. */ @JvmStatic fun get( receiver: TypeName? = null, vararg parameters: TypeName = emptyArray(), returnType: TypeName ): LambdaTypeName { return LambdaTypeName( receiver, parameters.toList().map { ParameterSpec.unnamed(it) }, returnType) } /** Returns a lambda type with `returnType` and parameters listed in `parameters`. */ @JvmStatic fun get( receiver: TypeName? = null, vararg parameters: ParameterSpec = emptyArray(), returnType: TypeName ) = LambdaTypeName(receiver, parameters.toList(), returnType) } } class ParameterizedTypeName internal constructor( private val enclosingType: TypeName?, val rawType: ClassName, typeArguments: List<TypeName>, nullable: Boolean = false, annotations: List<AnnotationSpec> = emptyList(), tags: Map<KClass<*>, Any> = emptyMap() ) : TypeName(nullable, annotations, TagMap(tags)) { val typeArguments = typeArguments.toImmutableList() init { require(typeArguments.isNotEmpty() || enclosingType != null) { "no type arguments: $rawType" } } override fun copy( nullable: Boolean, annotations: List<AnnotationSpec>, tags: Map<KClass<*>, Any> ): ParameterizedTypeName { return ParameterizedTypeName(enclosingType, rawType, typeArguments, nullable, annotations, tags) } fun plusParameter(typeArgument: TypeName) = ParameterizedTypeName(enclosingType, rawType, typeArguments + typeArgument, isNullable, annotations) fun plusParameter(typeArgument: KClass<*>) = plusParameter(typeArgument.asClassName()) fun plusParameter(typeArgument: Class<*>) = plusParameter(typeArgument.asClassName()) override fun emit(out: CodeWriter): CodeWriter { if (enclosingType != null) { enclosingType.emitAnnotations(out) enclosingType.emit(out) out.emit("." + rawType.simpleName) } else { rawType.emitAnnotations(out) rawType.emit(out) } if (typeArguments.isNotEmpty()) { out.emit("<") typeArguments.forEachIndexed { index, parameter -> if (index > 0) out.emit(", ") parameter.emitAnnotations(out) parameter.emit(out) parameter.emitNullable(out) } out.emit(">") } return out } /** * Returns a new [ParameterizedTypeName] instance for the specified `name` as nested inside this * class, with the specified `typeArguments`. */ fun nestedClass(name: String, typeArguments: List<TypeName>) = ParameterizedTypeName(this, rawType.nestedClass(name), typeArguments) companion object { /** Returns a parameterized type, applying `typeArguments` to `this`. */ @JvmStatic @JvmName("get") fun ClassName.parameterizedBy(vararg typeArguments: TypeName) = ParameterizedTypeName(null, this, typeArguments.toList()) /** Returns a parameterized type, applying `typeArguments` to `this`. */ @JvmStatic @JvmName("get") fun KClass<*>.parameterizedBy(vararg typeArguments: KClass<*>) = ParameterizedTypeName(null, asClassName(), typeArguments.map { it.asTypeName() }) /** Returns a parameterized type, applying `typeArguments` to `this`. */ @JvmStatic @JvmName("get") fun Class<*>.parameterizedBy(vararg typeArguments: Type) = ParameterizedTypeName(null, asClassName(), typeArguments.map { it.asTypeName() }) /** Returns a parameterized type, applying `typeArguments` to `this`. */ @JvmStatic @JvmName("get") fun ClassName.parameterizedBy(typeArguments: List<TypeName>) = ParameterizedTypeName(null, this, typeArguments) /** Returns a parameterized type, applying `typeArguments` to `this`. */ @JvmStatic @JvmName("get") fun KClass<*>.parameterizedBy(typeArguments: Iterable<KClass<*>>) = ParameterizedTypeName(null, asClassName(), typeArguments.map { it.asTypeName() }) /** Returns a parameterized type, applying `typeArguments` to `this`. */ @JvmStatic @JvmName("get") fun Class<*>.parameterizedBy(typeArguments: Iterable<Type>) = ParameterizedTypeName(null, asClassName(), typeArguments.map { it.asTypeName() }) /** Returns a parameterized type, applying `typeArgument` to `this`. */ @JvmStatic @JvmName("get") fun ClassName.plusParameter(typeArgument: TypeName) = parameterizedBy(typeArgument) /** Returns a parameterized type, applying `typeArgument` to `this`. */ @JvmStatic @JvmName("get") fun KClass<*>.plusParameter(typeArgument: KClass<*>) = parameterizedBy(typeArgument) /** Returns a parameterized type, applying `typeArgument` to `this`. */ @JvmStatic @JvmName("get") fun Class<*>.plusParameter(typeArgument: Class<*>) = parameterizedBy(typeArgument) /** Returns a parameterized type equivalent to `type`. */ internal fun get( type: ParameterizedType, map: MutableMap<Type, TypeVariableName> ): ParameterizedTypeName { val rawType = (type.rawType as Class<*>).asClassName() val ownerType = if (type.ownerType is ParameterizedType && !isStatic((type.rawType as Class<*>).modifiers)) type.ownerType as ParameterizedType else null val typeArguments = type.actualTypeArguments.map { TypeName.get(it, map = map) } return if (ownerType != null) get(ownerType, map = map).nestedClass(rawType.simpleName, typeArguments) else ParameterizedTypeName(null, rawType, typeArguments) } /** Returns a type name equivalent to type with given list of type arguments. */ internal fun get( type: KClass<*>, nullable: Boolean, typeArguments: List<KTypeProjection> ): TypeName { if (typeArguments.isEmpty()) { return type.asTypeName().run { if (nullable) copy(nullable = true) else this } } val effectiveType = if (type.java.isArray) Array<Unit>::class else type val enclosingClass = type.java.enclosingClass?.kotlin return ParameterizedTypeName( enclosingClass?.let { get(it, false, typeArguments.drop(effectiveType.typeParameters.size)) }, effectiveType.asTypeName(), typeArguments.take(effectiveType.typeParameters.size).map { (paramVariance, paramType) -> val typeName = paramType?.asTypeName() ?: return@map STAR when (paramVariance) { null -> STAR KVariance.INVARIANT -> typeName KVariance.IN -> WildcardTypeName.consumerOf(typeName) KVariance.OUT -> WildcardTypeName.producerOf(typeName) } }, nullable, effectiveType.annotations.map { AnnotationSpec.get(it) }) } } } class TypeVariableName private constructor( val name: String, val bounds: List<TypeName>, /** Either [KModifier.IN], [KModifier.OUT], or null. */ val variance: KModifier? = null, val isReified: Boolean = false, nullable: Boolean = false, annotations: List<AnnotationSpec> = emptyList(), tags: Map<KClass<*>, Any> = emptyMap() ) : TypeName(nullable, annotations, TagMap(tags)) { override fun copy( nullable: Boolean, annotations: List<AnnotationSpec>, tags: Map<KClass<*>, Any> ): TypeVariableName { return copy(nullable, annotations, this.bounds, this.isReified, tags) } fun copy( nullable: Boolean = this.isNullable, annotations: List<AnnotationSpec> = this.annotations.toList(), bounds: List<TypeName> = this.bounds.toList(), reified: Boolean = this.isReified, tags: Map<KClass<*>, Any> = this.tagMap.tags ): TypeVariableName { return TypeVariableName(name, bounds.withoutImplicitBound(), variance, reified, nullable, annotations, tags) } private fun List<TypeName>.withoutImplicitBound(): List<TypeName> { return if (size == 1) this else filterNot { it == NULLABLE_ANY } } override fun emit(out: CodeWriter) = out.emit(name) companion object { internal fun of( name: String, bounds: List<TypeName>, variance: KModifier? ): TypeVariableName { require(variance == null || variance.isOneOf(KModifier.IN, KModifier.OUT)) { "$variance is an invalid variance modifier, the only allowed values are in and out!" } require(bounds.isNotEmpty()) { "$name has no bounds" } // Strip Any? from bounds if it is present. return TypeVariableName(name, bounds, variance) } /** Returns type variable named `name` with `variance` and without bounds. */ @JvmStatic @JvmName("get") @JvmOverloads operator fun invoke(name: String, variance: KModifier? = null) = TypeVariableName.of( name = name, bounds = NULLABLE_ANY_LIST, variance = variance ) /** Returns type variable named `name` with `variance` and `bounds`. */ @JvmStatic @JvmName("get") @JvmOverloads operator fun invoke(name: String, vararg bounds: TypeName, variance: KModifier? = null) = TypeVariableName.of( name = name, bounds = bounds.toList().ifEmpty(::NULLABLE_ANY_LIST), variance = variance ) /** Returns type variable named `name` with `variance` and `bounds`. */ @JvmStatic @JvmName("get") @JvmOverloads operator fun invoke(name: String, vararg bounds: KClass<*>, variance: KModifier? = null) = TypeVariableName.of( name = name, bounds = bounds.map(KClass<*>::asTypeName).ifEmpty(::NULLABLE_ANY_LIST), variance = variance ) /** Returns type variable named `name` with `variance` and `bounds`. */ @JvmStatic @JvmName("get") @JvmOverloads operator fun invoke(name: String, vararg bounds: Type, variance: KModifier? = null) = TypeVariableName.of( name = name, bounds = bounds.map(Type::asTypeName).ifEmpty(::NULLABLE_ANY_LIST), variance = variance ) /** Returns type variable named `name` with `variance` and `bounds`. */ @JvmStatic @JvmName("get") @JvmOverloads operator fun invoke(name: String, bounds: List<TypeName>, variance: KModifier? = null) = TypeVariableName.of(name, bounds.ifEmpty(::NULLABLE_ANY_LIST), variance) /** Returns type variable named `name` with `variance` and `bounds`. */ @JvmStatic @JvmName("getWithClasses") @JvmOverloads operator fun invoke(name: String, bounds: Iterable<KClass<*>>, variance: KModifier? = null) = TypeVariableName.of(name, bounds.map { it.asTypeName() }.ifEmpty(::NULLABLE_ANY_LIST), variance) /** Returns type variable named `name` with `variance` and `bounds`. */ @JvmStatic @JvmName("getWithTypes") @JvmOverloads operator fun invoke(name: String, bounds: Iterable<Type>, variance: KModifier? = null) = TypeVariableName.of(name, bounds.map { it.asTypeName() }.ifEmpty(::NULLABLE_ANY_LIST), variance) /** * Make a TypeVariableName for the given TypeMirror. This form is used internally to avoid * infinite recursion in cases like `Enum<E extends Enum<E>>`. When we encounter such a * thing, we will make a TypeVariableName without bounds and add that to the `typeVariables` * map before looking up the bounds. Then if we encounter this TypeVariable again while * constructing the bounds, we can just return it from the map. And, the code that put the entry * in `variables` will make sure that the bounds are filled in before returning. */ internal fun get( mirror: javax.lang.model.type.TypeVariable, typeVariables: MutableMap<TypeParameterElement, TypeVariableName> ): TypeVariableName { val element = mirror.asElement() as TypeParameterElement var typeVariableName: TypeVariableName? = typeVariables[element] if (typeVariableName == null) { // Since the bounds field is public, we need to make it an unmodifiableList. But we control // the List that that wraps, which means we can change it before returning. val bounds = mutableListOf<TypeName>() val visibleBounds = Collections.unmodifiableList(bounds) typeVariableName = TypeVariableName(element.simpleName.toString(), visibleBounds) typeVariables[element] = typeVariableName for (typeMirror in element.bounds) { bounds += TypeName.get(typeMirror, typeVariables) } bounds.remove(ANY) bounds.remove(JAVA_OBJECT) if (bounds.isEmpty()) { bounds.add(NULLABLE_ANY) } } return typeVariableName } /** Returns type variable equivalent to `type`. */ internal fun get( type: TypeVariable<*>, map: MutableMap<Type, TypeVariableName> = mutableMapOf() ): TypeVariableName { var result: TypeVariableName? = map[type] if (result == null) { val bounds = mutableListOf<TypeName>() val visibleBounds = Collections.unmodifiableList(bounds) result = TypeVariableName(type.name, visibleBounds) map[type] = result for (bound in type.bounds) { bounds += TypeName.get(bound, map) } bounds.remove(ANY) bounds.remove(JAVA_OBJECT) if (bounds.isEmpty()) { bounds.add(NULLABLE_ANY) } } return result } internal val NULLABLE_ANY_LIST = listOf(NULLABLE_ANY) private val JAVA_OBJECT = ClassName("java.lang", "Object") } } class WildcardTypeName private constructor( outTypes: List<TypeName>, inTypes: List<TypeName>, nullable: Boolean = false, annotations: List<AnnotationSpec> = emptyList(), tags: Map<KClass<*>, Any> = emptyMap() ) : TypeName(nullable, annotations, TagMap(tags)) { val outTypes = outTypes.toImmutableList() val inTypes = inTypes.toImmutableList() init { require(this.outTypes.size == 1) { "unexpected out types: $outTypes" } } override fun copy( nullable: Boolean, annotations: List<AnnotationSpec>, tags: Map<KClass<*>, Any> ): WildcardTypeName { return WildcardTypeName(outTypes, inTypes, nullable, annotations, tags) } override fun emit(out: CodeWriter): CodeWriter { return when { inTypes.size == 1 -> out.emitCode("in %T", inTypes[0]) outTypes == STAR.outTypes -> out.emit("*") else -> out.emitCode("out %T", outTypes[0]) } } companion object { /** * Returns a type that represents an unknown type that produces `outType`. For example, if * `outType` is `CharSequence`, this returns `out CharSequence`. If `outType` is `Any?`, this * returns `*`, which is shorthand for `out Any?`. */ @JvmStatic fun producerOf(outType: TypeName) = WildcardTypeName(listOf(outType), emptyList()) @JvmStatic fun producerOf(outType: Type) = producerOf(outType.asTypeName()) @JvmStatic fun producerOf(outType: KClass<*>) = producerOf(outType.asTypeName()) /** * Returns a type that represents an unknown type that consumes `inType`. For example, if * `inType` is `String`, this returns `in String`. */ @JvmStatic fun consumerOf(inType: TypeName) = WildcardTypeName(listOf(ANY), listOf(inType)) @JvmStatic fun consumerOf(inType: Type) = consumerOf(inType.asTypeName()) @JvmStatic fun consumerOf(inType: KClass<*>) = consumerOf(inType.asTypeName()) internal fun get( mirror: javax.lang.model.type.WildcardType, typeVariables: Map<TypeParameterElement, TypeVariableName> ): TypeName { val outType = mirror.extendsBound if (outType == null) { val inType = mirror.superBound return if (inType == null) { STAR } else { consumerOf(TypeName.get(inType, typeVariables)) } } else { return producerOf(TypeName.get(outType, typeVariables)) } } internal fun get( wildcardName: WildcardType, map: MutableMap<Type, TypeVariableName> ): TypeName { return WildcardTypeName( wildcardName.upperBounds.map { TypeName.get(it, map = map) }, wildcardName.lowerBounds.map { TypeName.get(it, map = map) }) } } }
1
null
1
2
c73c349b32d1de0d5b5233fa61a40bd15d4a51e1
37,145
kotlinpoet
Apache License 2.0
app/src/main/java/com/github/skytoph/taski/presentation/habit/list/component/HabitDaily.kt
skytoph
708,362,840
false
{"Kotlin": 602263}
@file:OptIn(ExperimentalMaterial3Api::class) package com.github.skytoph.taski.presentation.habit.list.component import androidx.compose.animation.Animatable import androidx.compose.animation.core.tween import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Check import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewParameter import androidx.compose.ui.unit.dp import com.github.skytoph.taski.R import com.github.skytoph.taski.presentation.core.component.HabitTitleWithIcon import com.github.skytoph.taski.presentation.core.component.ProgressCircle import com.github.skytoph.taski.presentation.core.preview.HabitProvider import com.github.skytoph.taski.presentation.habit.HabitUi import com.github.skytoph.taski.presentation.habit.HabitWithHistoryUi import com.github.skytoph.taski.presentation.habit.list.EntryUi import com.github.skytoph.taski.presentation.habit.list.HistoryUi import com.github.skytoph.taski.ui.theme.HabitMateTheme @OptIn(ExperimentalFoundationApi::class) @Composable fun HabitDaily( habit: HabitUi, history: HistoryUi, updateEntries: (Int) -> Unit = {}, onDone: (HabitUi, Int) -> Unit = { _, _ -> }, onClick: () -> Unit = {}, onLongClick: () -> Unit = {}, modifier: Modifier = Modifier ) { BoxWithConstraints(modifier = modifier.fillMaxWidth()) { val entries = calculateNumberOfDailyEntries(maxWidth = maxWidth) updateEntries(entries) Card( modifier = Modifier .fillMaxWidth() .wrapContentHeight() .clip(CardDefaults.shape) .combinedClickable(onClick = onClick, onLongClick = onLongClick) .semantics { contentDescription = "habit" }, colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer), ) { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .height(48.dp) ) { HabitTitleWithIcon( modifier = Modifier .weight(1f) .padding(horizontal = 8.dp), icon = habit.icon.vector(LocalContext.current), color = habit.color, title = habit.title ) LazyRow(horizontalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.entries_daily_spaced_by))) { if (entries == history.entries.size) items(items = history.entries, key = { it.daysAgo }) { entry -> CheckIcon( onDone = onDone, habit = habit, percentDone = entry.percentDone, daysAgo = entry.daysAgo, timesDone = entry.timesDone ) } } } } } } @Composable private fun CheckIcon( onDone: (HabitUi, Int) -> Unit, habit: HabitUi, percentDone: Float, daysAgo: Int, timesDone: Int ) { val defaultColor = MaterialTheme.colorScheme.secondaryContainer val color = remember { Animatable(if (percentDone >= 1f) habit.color else defaultColor) } LaunchedEffect(timesDone) { color.animateTo( targetValue = if (percentDone >= 1f) habit.color else defaultColor, animationSpec = tween( durationMillis = 300, delayMillis = if (habit.goal > 1 && percentDone >= 1f) 300 else 0 ) ) } IconButton(onClick = { onDone(habit, daysAgo) }) { Box { Icon( imageVector = Icons.Outlined.Check, contentDescription = null, modifier = Modifier .background(color = color.value, shape = CircleShape) .size(26.dp) .padding(6.dp), tint = Color.White ) if (habit.goal > 1) ProgressCircle( goal = habit.goal, done = timesDone, size = 26.dp, color = habit.color ) } } } @Composable @Preview(showBackground = true, showSystemUi = true) fun DarkHabitDailyPreview( @PreviewParameter(HabitProvider::class, limit = 1) habit: HabitWithHistoryUi<HistoryUi> ) { HabitMateTheme(darkTheme = true) { HabitDaily(habit = habit.habit, history = HistoryUi(entries = listOf(EntryUi()))) } }
0
Kotlin
0
1
6639c40403f384c2125b6370499fcd6a0120a72b
6,342
HabitMate
The Unlicense
meistercharts-commons/src/commonMain/kotlin/com/meistercharts/annotations/Snapped.kt
Neckar-IT
599,079,962
false
{"Kotlin": 5819931, "HTML": 87784, "JavaScript": 1378, "CSS": 1114}
package com.meistercharts.annotations import it.neckar.open.unit.other.px /** * Marks values that have been snapped (usually to physical pixels) */ @Retention(AnnotationRetention.SOURCE) @Target( AnnotationTarget.CLASS, AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY, AnnotationTarget.FIELD, AnnotationTarget.LOCAL_VARIABLE, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.CONSTRUCTOR, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.TYPE, AnnotationTarget.EXPRESSION, AnnotationTarget.FILE, AnnotationTarget.TYPEALIAS ) @MustBeDocumented @px annotation class Snapped
3
Kotlin
3
5
ed849503e845b9d603598e8d379f6525a7a92ee2
716
meistercharts
Apache License 2.0
app/src/main/java/boc/hackathon/kubaras/data/Transaction.kt
BocHackathon-4-0
702,047,644
false
{"Kotlin": 56677}
package boc.hackathon.kubaras.data import kotlinx.serialization.Serializable @Serializable data class Transaction( val amount: Double, val currency: String, val description: String, val fee: Int, val id: String, val receiver_account: String, val reference_number: String, val sender_account: String, val status: String, val timestamp: String, val transaction_type: String )
0
Kotlin
0
0
a297055f463525ead0925cac1e2e51bbbad91f44
419
SmartInvestMoneyBox
MIT License
src/main/kotlin/com/wynntils/launchy/data/Group.kt
Wynntils
561,288,557
false
null
package com.mineinabyss.launchy.data import kotlinx.serialization.Serializable @Serializable data class Group( val name: String, val enabledByDefault: Boolean = false, val forceEnabled: Boolean = false, val forceDisabled: Boolean = false, )
5
null
6
8
e1282da59725ea1e6ba953eb7ead8522aba4455e
259
launchy
MIT License
bbfgradle/tmp/arrays/JavaAndKotlin/javaAndKotlin360.kt
DaniilStepanov
346,008,310
false
null
// FILE: BoxFunKt.java import kotlin.Metadata; import kotlin.jvm.internal.Intrinsics; import org.jetbrains.annotations.NotNull; class BoxFunKt { @NotNull public static final String box() { String s = "s"; s = s + 1; return Intrinsics.areEqual(s, "s1") ? "OK" : "fail"; } } // FILE: useAnonymousObjectAsIterator.kt // IGNORE_BACKEND_FIR: JVM_IR // KT-5869 operator fun <T> Iterator<T>.iterator(): Iterator<T> = this
1
null
1
1
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
448
kotlinWithFuzzer
Apache License 2.0
zircon.development/src/main/kotlin/org/codetome/zircon/main.kt
mdr0id
142,499,841
true
{"Kotlin": 772586, "Java": 70338}
package org.codetome.zircon import org.codetome.zircon.poc.drawableupgrade.* fun main(args: Array<String>) { testRender() System.exit(0) } private fun testRender() { val width = 20 val height = 10 val renderer = Renderer() val tileGrid = TileGrid(width, height) val tile = Tile('y') val image = TileImage(3, 3) (0..3).forEach { y -> (0..3).forEach { x -> image.setTileAt(Position(x, y), Tile('x')) } } val otherImage = TileImage(2, 1) otherImage.setTileAt(Position(0, 0), Tile('z')) otherImage.setTileAt(Position(1, 0), Tile('z')) image.draw(otherImage, Position(1, 1)) (0..height).forEach { y -> (0..width).forEach { x -> tileGrid.setTileAt(Position(x, y), Tile('_')) } } renderer.render(tileGrid) println() println() tileGrid.draw(image, Position(4, 5)) renderer.render(tileGrid) println() println() tileGrid.draw(tile, Position(15, 2)) renderer.render(tileGrid) println() println() tileGrid.setTileAt(Position(8, 9), tile) renderer.render(tileGrid) }
0
Kotlin
0
0
58cade5b8ecb2663d6880d3220db70f6e7bb6f91
1,143
zircon
MIT License
app/src/main/kotlin/ir/erfansn/nsmavpn/data/source/local/VpnServersLocalDataSource.kt
erfansn
547,180,309
false
{"Kotlin": 611093, "HTML": 313045}
/* * Copyright 2024 Erfan Sn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ir.erfansn.nsmavpn.data.source.local import androidx.datastore.core.DataStore import ir.erfansn.nsmavpn.data.source.local.datastore.Server import ir.erfansn.nsmavpn.data.source.local.datastore.VpnServers import ir.erfansn.nsmavpn.data.source.local.datastore.copy import ir.erfansn.nsmavpn.di.DefaultDispatcher import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext import javax.inject.Inject interface VpnServersLocalDataSource { suspend fun getAvailableSstpVpnServers(): List<Server> suspend fun getUnavailableVpnServers(): List<Server> suspend fun saveSstpVpnServers(servers: List<Server>) suspend fun saveAsUnavailableVpnServers(servers: List<Server>) suspend fun deleteFromUnavailableVpnServers(servers: List<Server>) } class DefaultVpnServersLocalDataSource @Inject constructor( private val dataStore: DataStore<VpnServers>, @DefaultDispatcher private val defaultDispatcher: CoroutineDispatcher, ) : VpnServersLocalDataSource { private val vpnServers: Flow<VpnServers> = dataStore.data override suspend fun getAvailableSstpVpnServers(): List<Server> = withContext(defaultDispatcher) { with(vpnServers.first()) { sstpServersList - unavailableServersList.toSet() } } override suspend fun getUnavailableVpnServers(): List<Server> = vpnServers.first().unavailableServersList override suspend fun saveSstpVpnServers(servers: List<Server>) { dataStore.updateData { it.copy { with(sstpServers) { val newServersAddresses = servers.map { server -> server.address } val previousServers = filter { server -> server.address !in newServersAddresses } clear() addAll(servers + previousServers) } } } } override suspend fun saveAsUnavailableVpnServers(servers: List<Server>) { dataStore.updateData { it.copy { unavailableServers += servers } } } override suspend fun deleteFromUnavailableVpnServers(servers: List<Server>) { dataStore.updateData { it.copy { with(unavailableServers) { val reducedServers = filter { server -> server !in servers } clear() addAll(reducedServers) } } } } }
13
Kotlin
1
35
230181bfc03b19bd5bb52818ee0b8b19078a4ec1
3,132
NsmaVPN
Apache License 2.0
json-builder/kotlin/src/generated/kotlin/com/yandex/div/dsl/model/UrlVariable.kt
divkit
523,491,444
false
{"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38}
// Generated code. Do not modify. package com.yandex.div.dsl.model import java.net.URI import com.fasterxml.jackson.annotation.* import com.yandex.div.dsl.* import com.yandex.div.dsl.context.* import com.yandex.div.dsl.type.* import com.yandex.div.dsl.util.* class UrlVariable internal constructor( @JsonIgnore val name: Property<String>?, @JsonIgnore val value: Property<URI>?, ) : DivVariable { @JsonProperty("type") override val type = "url" @JsonAnyGetter internal fun properties(): Map<String, Any> { return propertyMapOf( "name" to name, "value" to value, ) } } fun <T> TemplateContext<T>.urlVariable(): LiteralProperty<UrlVariable> { return value(UrlVariable( name = null, value = null, )) } fun <T> TemplateContext<T>.urlVariable( name: Property<String>? = null, value: Property<URI>? = null, ): LiteralProperty<UrlVariable> { return value(UrlVariable( name = name, value = value, )) } fun <T> TemplateContext<T>.urlVariable( name: String? = null, value: URI? = null, ): LiteralProperty<UrlVariable> { return value(UrlVariable( name = optionalValue(name), value = optionalValue(value), )) } fun CardContext.urlVariable( name: ValueProperty<String>, value: ValueProperty<URI>, ): UrlVariable { return UrlVariable( name = name, value = value, ) } fun CardContext.urlVariable( name: String, value: URI, ): UrlVariable { return UrlVariable( name = value(name), value = value(value), ) }
5
Kotlin
128
2,240
dd102394ed7b240ace9eaef9228567f98e54d9cf
1,617
divkit
Apache License 2.0
app/src/main/java/com/dtsedemo/mtwoauth/manager/FacebookAuthManager.kt
mahmutyetisir
299,620,801
false
null
package com.dtsedemo.mtwoauth.manager import com.dtsedemo.mtwoauth.common.observableCreate import com.dtsedemo.mtwoauth.model.ResultEvent import com.dtsedemo.mtwoauth.model.User import com.huawei.agconnect.auth.AGConnectAuth import com.huawei.agconnect.auth.FacebookAuthProvider import io.reactivex.rxjava3.core.Observable interface FacebookAuthManager : Auth { fun login(accessToken: String): Observable<ResultEvent<Boolean>> fun logout(): Observable<ResultEvent<Unit>> fun getUser(): User? } class FacebookAuthManagerImpl(agConnectAuth: AGConnectAuth) : BaseAuthManager<FacebookAuthManager>(agConnectAuth), FacebookAuthManager { override val job: FacebookAuthManager = this override fun login(accessToken: String): Observable<ResultEvent<Boolean>> { return observableCreate { subscriber -> agConnectAuth.signIn(FacebookAuthProvider.credentialWithToken(accessToken)) .addOnSuccessListener { subscriber.onNext(ResultEvent.Success(true)) subscriber.onComplete() } .addOnFailureListener { subscriber.onNext(ResultEvent.Error(it)) subscriber.onComplete() } } } override fun getUser(): User? { val currentUser = agConnectAuth.currentUser return if (currentUser == null) null else User( currentUser.email, currentUser.uid, currentUser.displayName ) } }
0
null
1
4
fc0ed75785f1a523229e3a2a9a211e0b5886568f
1,521
HuaweiAuth
Apache License 2.0
solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomLength.kt
tuProlog
230,784,338
false
null
package it.unibo.tuprolog.solve.stdlib.primitive import it.unibo.tuprolog.core.Atom import it.unibo.tuprolog.core.Integer import it.unibo.tuprolog.core.Substitution import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.core.Var import it.unibo.tuprolog.solve.ExecutionContext import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object AtomLength : BinaryRelation.Functional<ExecutionContext>("atom_length") { override fun Solve.Request<ExecutionContext>.computeOneSubstitution( first: Term, second: Term, ): Substitution = when { first is Var -> { ensuringAllArgumentsAreInstantiated() Substitution.failed() } second is Var -> { ensuringArgumentIsAtom(0) val atomLength = (first as Atom).value.length Substitution.of(second, Integer.of(atomLength)) } else -> { ensuringArgumentIsAtom(0) ensuringArgumentIsNonNegativeInteger(1) val atomLength = Integer.of((first as Atom).value.length) mgu(atomLength, second) } } }
92
null
8
93
3223ffc302e5da0efe2b254045fa1b6a1a122519
1,230
2p-kt
Apache License 2.0
app/src/main/java/ilkadam/ilksohbet/presentation/bottomnavigation/components/CustomNavItem.kt
ademkocamaz
803,881,747
false
{"Kotlin": 261729}
package ilkadam.ilksohbet.presentation.bottomnavigation.components import androidx.compose.material3.IconButton import androidx.compose.runtime.Composable @Composable fun CustomNavItem( onClick: () -> Unit, iconSelected: @Composable () -> Unit ) { IconButton(onClick = { onClick() }, content = { iconSelected() } ) }
0
Kotlin
0
0
cd06a2de124fdbc8c78085da8e9d8bcc46a74033
354
ilkMuhabbet
MIT License
app/src/main/java/space/pal/sig/service/SpaceNotificationManager.kt
icatalin201
179,758,397
false
null
package space.pal.sig.service import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.os.Build import androidx.core.app.NotificationCompat import space.pal.sig.R import space.pal.sig.view.splash.SplashActivity import java.security.SecureRandom /** * SpaceNow * Created by Catalin on 7/17/2020 */ object SpaceNotificationManager { private const val NOTIFICATION_CHANNEL_ID = "space_now_channel_01" private const val CHANNEL_NAME = "Space Now" private const val CHANNEL_DESCRIPTION = "Space Now - The Space at your fingertips" @JvmStatic fun createNotificationChannel(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val importance = NotificationManager.IMPORTANCE_HIGH val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, CHANNEL_NAME, importance) channel.description = CHANNEL_DESCRIPTION val notificationManager = context.getSystemService(NotificationManager::class.java) notificationManager?.createNotificationChannel(channel) } } @JvmStatic @JvmOverloads fun createBigNotification( context: Context, text: String, bitmap: Bitmap, id: Int = SecureRandom().nextInt() ) { val intent = Intent(context, SplashActivity::class.java) val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) val notification = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID) .setContentTitle(context.getString(R.string.app_name)) .setContentText(text) .setSmallIcon(R.drawable.ic_icons8_launchpad) .setContentIntent(pendingIntent) .setLargeIcon(bitmap) .setStyle(NotificationCompat.BigPictureStyle().bigPicture(bitmap)) .setAutoCancel(true) .build() val notificationManager = context .getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(id, notification) } @JvmStatic @JvmOverloads fun createNotification( context: Context, text: String, id: Int = SecureRandom().nextInt() ) { val intent = Intent(context, SplashActivity::class.java) val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) val notification = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID) .setContentTitle(context.getString(R.string.app_name)) .setContentText(text) .setSmallIcon(R.drawable.ic_icons8_launchpad) .setContentIntent(pendingIntent) .setAutoCancel(true) .build() val notificationManager = context .getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(id, notification) } }
0
Kotlin
0
0
9f8485e7ef1580be8c84dd34babd99571bed277a
3,228
SpaceNow
Apache License 2.0
bank-api-demo/src/main/kotlin/org/antop/account/BankApiApplication.kt
antop-dev
203,771,713
false
null
package org.antop.account import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class BankApiApplication fun main(args: Array<String>) { runApplication<BankApiApplication>(*args) }
1
null
1
1
f88069137f1ea7ea67278c8d9dd1d74f378e2bf3
272
glory-of-rest
MIT License