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
ospf-kotlin-core-plugin/ospf-kotlin-core-plugin-heuristic/src/main/fuookami/ospf/kotlin/core/backend/plugins/heuristic/ga/MutationOperation.kt
fuookami
359,831,793
false
{"Kotlin": 2440181, "Python": 6629}
package fuookami.ospf.kotlin.core.backend.plugins.heuristic.ga import fuookami.ospf.kotlin.utils.math.* import fuookami.ospf.kotlin.utils.math.ordinary.* import fuookami.ospf.kotlin.utils.operator.* import fuookami.ospf.kotlin.utils.functional.* import fuookami.ospf.kotlin.core.frontend.model.callback.* import kotlin.random.Random interface MutationMode { /** * calculate mutation rate * * @param population * @param model * @return */ operator fun invoke( population: Population, model: CallBackModelInterface ): Flt64 } data object StaticMutationMode : MutationMode { override fun invoke(population: Population, model: CallBackModelInterface): Flt64 { return population.mutationRange.upperBound.toFlt64() } } data object AdaptiveDynamicMutationMode : MutationMode { override fun invoke(population: Population, model: CallBackModelInterface): Flt64 { val (minFitness, maxFitness) = population.chromosomes .mapNotNull { it.fitness } .minMaxWithPartialThreeWayComparatorOrNull { lhs, rhs -> model.compareObjective(lhs, rhs) } ?: return population.mutationRange.upperBound.toFlt64() val x = abs(maxFitness - minFitness) / max(minFitness, maxFitness) return if (x ls Flt64.decimalPrecision) { population.mutationRange.upperBound.toFlt64() } else { return min( population.mutationRange.lowerBound.toFlt64() * x, population.mutationRange.upperBound.toFlt64() ) } } } interface MutationOperation { operator fun invoke( chromosome: Chromosome, mutationRate: Flt64, model: CallBackModelInterface ): Chromosome? } class UniformMutationOperation( val rng: Random ) : MutationOperation { override fun invoke(chromosome: Chromosome, mutationRate: Flt64, model: CallBackModelInterface): Chromosome? { val newGene = chromosome.gene.toMutableList() var flag = false for (i in newGene.indices) { if (Flt64(rng.nextDouble()) ls mutationRate) { flag = true newGene[i] = model.tokens.find(i)!!.random(rng) } } return if (flag) { Chromosome( fitness = if (model.constraintSatisfied(newGene) != false) { model.objective(newGene) } else { null }, gene = newGene ) } else { null } } } class NonUniformMutationOperation( val rng: Random ) : MutationOperation { override fun invoke(chromosome: Chromosome, mutationRate: Flt64, model: CallBackModelInterface): Chromosome? { TODO("Not yet implemented") } } class GaussianMutationOperation( val rng: Random ) : MutationOperation { override fun invoke(chromosome: Chromosome, mutationRate: Flt64, model: CallBackModelInterface): Chromosome? { TODO("Not yet implemented") } }
0
Kotlin
0
4
b34cda509b31884e6a15d77f00a6134d001868de
3,070
ospf-kotlin
Apache License 2.0
src/test/kotlin/com/flash/interview/messaging/sensitive_words_service/adapters/in/controllers/MessagingControllerTest.kt
Ntuks
877,815,476
false
{"Kotlin": 42553, "Dockerfile": 757, "Shell": 725}
package com.flash.interview.messaging.sensitive_words_service.adapters.`in`.controllers import com.fasterxml.jackson.databind.ObjectMapper import com.flash.interview.messaging.sensitive_words_service.adapters.`in`.dtos.* import com.flash.interview.messaging.sensitive_words_service.domain.application.SensitiveWordService import com.flash.interview.messaging.sensitive_words_service.domain.application.TestSecurityConfig import com.flash.interview.messaging.sensitive_words_service.domain.models.RedactedMessage import com.flash.interview.messaging.sensitive_words_service.domain.models.SensitiveWord import io.mockk.every import org.junit.jupiter.api.Test import org.mockito.Mockito.* import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.context.annotation.Import import org.springframework.http.MediaType import org.springframework.security.test.context.support.WithMockUser import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.* import org.springframework.test.web.servlet.result.MockMvcResultMatchers.* @WebMvcTest(MessagingController::class) @Import(TestSecurityConfig::class) class MessagingControllerTest { @Autowired private lateinit var mockMvc: MockMvc @MockBean private lateinit var sensitiveWordService: SensitiveWordService @Autowired private lateinit var objectMapper: ObjectMapper @Test @WithMockUser(username = "admin", password = "<PASSWORD>", roles = ["admin"]) // Simulate a logged-in user for admin endpoints fun `should add sensitive word successfully`() { val request = CreateSensitiveWordsRequest(setOf("badword")) mockMvc.perform( post("/api/v1/messages/admin/addSensitiveWord") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request))) .andDo { println(it.response.contentAsString) } .andDo { println(it.response.status) } .andDo { println(it.response.errorMessage) } .andExpect(status().isOk) .andExpect(content().string("Word added successfully")) verify(sensitiveWordService, times(1)).createSensitiveWords(request.sensitiveWords) } @Test @WithMockUser(username = "admin", password = "<PASSWORD>", roles = ["admin"]) fun `should get sensitive words successfully`() { val sensitiveWords = listOf("badword", "anotherBadWord") val sensitiveWordsResponse = SensitiveWordsResponse( sensitiveWords = listOf( SensitiveWord(id = "0", text = sensitiveWords[0]), SensitiveWord(id = "1", text = sensitiveWords[1]) ) ) val expectedWords = sensitiveWords.mapIndexed { id: Int, test: String -> SensitiveWord(id.toString(), test) } `when`(sensitiveWordService.getSensitiveWords()) .thenReturn(Result.success(expectedWords)) mockMvc.perform(get("/api/v1/messages/admin/getSensitiveWords")) .andDo { println(it.response.contentAsString) } .andDo { println(it.response.status) } .andDo { println(it.response.errorMessage) } .andExpect(status().isOk) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().string(objectMapper.writeValueAsString(sensitiveWordsResponse))) verify(sensitiveWordService, times(1)).getSensitiveWords() } @Test @WithMockUser(username = "admin", password = "<PASSWORD>", roles = ["admin"]) fun `should update sensitive word successfully`() { val request = UpdateSensitiveWordRequest(id = "1", text = "firstWord") val updatedWord = SensitiveWord(id = "1", text = "updatedBadword") val response = SensitiveWordsResponse(listOf(updatedWord)) `when`(sensitiveWordService.updateSensitiveWords( sensitiveWord = SensitiveWord(request.id, request.text) )).thenReturn(Result.success(updatedWord)) mockMvc.perform( put("/api/v1/messages/admin/updateSensitiveWord") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) ) .andDo { println(it.response.contentAsString) } .andDo { println(it.response.status) } .andDo { println(it.response.errorMessage) } .andExpect(status().isOk) .andExpect(content().string(objectMapper.writeValueAsString(response))) verify(sensitiveWordService, times(1)).updateSensitiveWords(updatedWord.copy(text = request.text)) } @Test @WithMockUser(username = "admin", password = "<PASSWORD>", roles = ["admin"]) fun `should delete sensitive word successfully`() { val id = "1" mockMvc.perform( delete("/api/v1/messages/admin/deleteSensitiveWord") .param("id", id) ) .andExpect(status().isNoContent) verify(sensitiveWordService, times(1)).deleteSensitiveWords(id) } @Test @WithMockUser(username = "admin", password = "<PASSWORD>", roles = ["admin"]) fun `should redact message successfully`() { val request = MessageRequest("This is a badword in the message.") val redactedMessage = RedactedMessage("This is a ***** in the message.") val response = MessageResponse( originalMessage = request.message, redactedMessage = redactedMessage.content, redactedWordsCount = 1 ) `when`(sensitiveWordService.redactSensitiveWords(request.message)) .thenReturn( Result.success(redactedMessage to 1) ) mockMvc.perform( post("/api/v1/messages/redact") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(request)) ) .andDo { println(it.response.contentAsString) } .andDo { println(it.response.status) } .andDo { println(it.response.errorMessage) } .andExpect(status().isOk) .andExpect(content().string(objectMapper.writeValueAsString(response))) verify(sensitiveWordService, times(1)).redactSensitiveWords(request.message) } }
0
Kotlin
0
0
a5056f18d50739bbeaa063c6f08a2a10edf543b2
6,500
sensitive-words-service
MIT License
java-agent/src/nativeMain/kotlin/com/epam/drill/agent/Config.kt
Drill4J
240,284,351
false
null
/** * Copyright 2020 - 2022 EPAM Systems * * 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.epam.drill.agent import kotlin.native.concurrent.* import kotlin.time.* data class Config( val classScanDelay: Duration = Duration.ZERO, val scanClassPath: String = "", val logLevel: String = "ERROR", val logFile: String? = null, val logLimit: Int = 512, val isAsyncApp: Boolean = false, val isWebApp: Boolean = false, val isKafka: Boolean = false, val isCadence: Boolean = false, val isTlsApp: Boolean = false ) private val _config = AtomicReference(Config().freeze()).freeze() val config: Config get() = _config.value fun updateConfig(block: Config.() -> Config): Config = _config.value.block().freeze().also { _config.value = it }
1
Kotlin
1
6
09e64956d74fece85c7ff33470ed3b138e0721b2
1,295
java-agent
Apache License 2.0
kotlin-common/src/main/java/com/zhouhaoo/common/extensions/ActivityExt.kt
zhouhaoo
110,637,983
false
null
/* * Copyright (c) 2018 zhouhaoo * * 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.zhouhaoo.common.extensions import android.app.Activity import android.content.Intent import android.content.pm.ActivityInfo import android.content.res.Configuration import android.net.Uri import android.os.Bundle import android.util.Patterns /** * Created by zhou on 2018/3/30. */ /** *## Activity的普通跳转 * * @param finishSelf true 为跳转后关闭自己,默认不关闭 */ inline fun <reified T : Activity> Activity.start(finishSelf: Boolean = false) { startActivity(intentFor<T>(this)) if (finishSelf) finish() } /** *## Activity的带结果返回跳转 * */ inline fun <reified T : Activity> Activity.startActivityForResult( requestCode: Int, options: Bundle? = null, action: String? = null) { startActivityForResult(intentFor<T>(this).setAction(action), requestCode, options) } inline fun webIntent(url: String): Intent = if (Patterns.WEB_URL.matcher(url).matches()) { Intent(Intent.ACTION_VIEW, Uri.parse(url)) } else { throw IllegalArgumentException("Passed url: $url does not match URL pattern.") } inline fun Activity.lockCurrentScreenOrientation() { requestedOrientation = when (resources.configuration.orientation) { Configuration.ORIENTATION_LANDSCAPE -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE else -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT } } inline fun Activity.unlockScreenOrientation() { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR }
1
null
1
10
73c95dd5032c0d7b91a9bacd9db03cebf5afc118
2,087
kotlin-common
Apache License 2.0
lib/src/test/java/com/what3words/androidwrapper/VoiceBuilderWithCoordinatesTests.kt
what3words
201,899,599
false
null
package com.what3words.androidwrapper import android.media.AudioFormat import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.core.util.Consumer import com.google.common.truth.Truth.assertThat import com.google.gson.Gson import com.what3words.androidwrapper.voice.Microphone import com.what3words.androidwrapper.voice.VoiceApi import com.what3words.androidwrapper.voice.VoiceApi.Companion.BASE_URL_WITH_COORDINATES import com.what3words.androidwrapper.voice.VoiceApiListenerWithCoordinates import com.what3words.javawrapper.request.BoundingBox import com.what3words.javawrapper.request.Coordinates import com.what3words.javawrapper.response.APIError import com.what3words.javawrapper.response.APIResponse import com.what3words.javawrapper.response.SuggestionWithCoordinates import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.justRun import io.mockk.mockk import io.mockk.verify import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runBlockingTest import okhttp3.WebSocket import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule @ExperimentalCoroutinesApi class VoiceBuilderWithCoordinatesTests { @get:Rule var coroutinesTestRule = CoroutineTestRule() @get:Rule val testInstantTaskExecutorRule: TestRule = InstantTaskExecutorRule() @MockK private lateinit var socket: WebSocket @MockK private lateinit var voiceApi: VoiceApi @MockK private lateinit var microphone: Microphone @MockK private var suggestionsCallback = mockk<Consumer<List<SuggestionWithCoordinates>>>() @MockK private var errorCallback = mockk<Consumer<APIResponse.What3WordsError>>() @Before fun setup() { voiceApi = mockk() socket = mockk() microphone = mockk() suggestionsCallback = mockk() errorCallback = mockk() justRun { voiceApi.forceStop() voiceApi.open(any(), any(), any(), any<VoiceApiListenerWithCoordinates>()) microphone.startRecording(socket) microphone.stopRecording() suggestionsCallback.accept(any()) errorCallback.accept(any()) } every { microphone.recordingRate } answers { 44000 } every { microphone.encoding } answers { AudioFormat.ENCODING_DEFAULT } } @Test fun `startListening then force stopListening`() = coroutinesTestRule.testDispatcher.runBlockingTest { // given val what3WordsV3 = What3WordsV3("key", voiceApi, coroutinesTestRule.testDispatcherProvider) val builder = what3WordsV3.autosuggestWithCoordinates(microphone, "en") builder.onSuggestions(suggestionsCallback) builder.onError(errorCallback) // when startListening and connected successfully builder.startListening() builder.connected(socket) // then assertThat(builder.isListening()).isTrue() verify(exactly = 1) { voiceApi.open(any(), any(), any(), builder) } verify(exactly = 1) { microphone.startRecording(socket) } // when forced stop builder.stopListening() // then assertThat(builder.isListening()).isFalse() verify(exactly = 1) { voiceApi.forceStop() } verify(exactly = 1) { microphone.stopRecording() } verify(exactly = 0) { suggestionsCallback.accept(any()) } verify(exactly = 0) { errorCallback.accept(any()) } } @Test fun `startListening then error occurs`() = coroutinesTestRule.testDispatcher.runBlockingTest { // given val what3WordsV3 = What3WordsV3("key", voiceApi, coroutinesTestRule.testDispatcherProvider) val builder = what3WordsV3.autosuggestWithCoordinates(microphone, "en") builder.onSuggestions(suggestionsCallback) builder.onError(errorCallback) // when startListening and connected successfully builder.startListening() builder.connected(socket) // then assertThat(builder.isListening()).isTrue() verify(exactly = 1) { voiceApi.open(any(), any(), any(), builder) } verify(exactly = 1) { microphone.startRecording(socket) } // when builder.error(APIError()) // then assertThat(builder.isListening()).isFalse() verify(exactly = 0) { voiceApi.forceStop() } verify(exactly = 1) { microphone.stopRecording() } verify(exactly = 0) { suggestionsCallback.accept(any()) } verify(exactly = 1) { errorCallback.accept(any()) } } @Test fun `startListening then returns suggestions`() = coroutinesTestRule.testDispatcher.runBlockingTest { // given val what3WordsV3 = What3WordsV3("key", voiceApi, coroutinesTestRule.testDispatcherProvider) val builder = what3WordsV3.autosuggestWithCoordinates(microphone, "en") builder.onSuggestions(suggestionsCallback) builder.onError(errorCallback) // when startListening and connected successfully builder.startListening() builder.connected(socket) // then assertThat(builder.isListening()).isTrue() verify(exactly = 1) { voiceApi.open(any(), any(), any(), builder) } verify(exactly = 1) { microphone.startRecording(socket) } val suggestionsJson = ClassLoader.getSystemResource("suggestions-with-coordinates.json").readText() val suggestions = Gson().fromJson(suggestionsJson, Array<SuggestionWithCoordinates>::class.java) .toList() // when builder.suggestionsWithCoordinates(suggestions) // then assertThat(builder.isListening()).isFalse() verify(exactly = 0) { voiceApi.forceStop() } verify(exactly = 1) { microphone.stopRecording() } verify(exactly = 1) { suggestionsCallback.accept(suggestions) } verify(exactly = 0) { errorCallback.accept(any()) } } @Test fun `focus is set expect param url`() = coroutinesTestRule.testDispatcher.runBlockingTest { // given val expectedUrl = "$BASE_URL_WITH_COORDINATES?voice-language=en&focus=51.1,-0.152" val what3WordsV3 = What3WordsV3("key", voiceApi, coroutinesTestRule.testDispatcherProvider) val builder = what3WordsV3.autosuggestWithCoordinates(microphone, "en") .onSuggestions(suggestionsCallback) .onError(errorCallback) // when builder.focus(Coordinates(51.1, -0.152)) .startListening() // then assertThat(builder.isListening()).isTrue() verify(exactly = 1) { voiceApi.open(any(), any(), expectedUrl, builder) } } @Test fun `focus is set with nFocusResults expect param url`() = coroutinesTestRule.testDispatcher.runBlockingTest { // given val expectedUrl = "$BASE_URL_WITH_COORDINATES?voice-language=en&focus=51.1,-0.152&n-focus-results=3" val what3WordsV3 = What3WordsV3("key", voiceApi, coroutinesTestRule.testDispatcherProvider) val builder = what3WordsV3.autosuggestWithCoordinates(microphone, "en") .onSuggestions(suggestionsCallback) .onError(errorCallback) // when builder.focus(Coordinates(51.1, -0.152)).nFocusResults(3) .startListening() // then assertThat(builder.isListening()).isTrue() verify(exactly = 1) { voiceApi.open(any(), any(), expectedUrl, builder) } } @Test fun `nResults is set expect param url`() = coroutinesTestRule.testDispatcher.runBlockingTest { // given val expectedUrl = "$BASE_URL_WITH_COORDINATES?voice-language=en&n-results=3" val what3WordsV3 = What3WordsV3("key", voiceApi, coroutinesTestRule.testDispatcherProvider) val builder = what3WordsV3.autosuggestWithCoordinates(microphone, "en") .onSuggestions(suggestionsCallback) .onError(errorCallback) // when builder.nResults(3).startListening() // then assertThat(builder.isListening()).isTrue() verify(exactly = 1) { voiceApi.open(any(), any(), expectedUrl, builder) } } @Test fun `clipToCountry is set expect param url`() = coroutinesTestRule.testDispatcher.runBlockingTest { // given val expectedUrl = "$BASE_URL_WITH_COORDINATES?voice-language=en&clip-to-country=GB,FR" val what3WordsV3 = What3WordsV3("key", voiceApi, coroutinesTestRule.testDispatcherProvider) val builder = what3WordsV3.autosuggestWithCoordinates(microphone, "en") .onSuggestions(suggestionsCallback) .onError(errorCallback) // when builder.clipToCountry(listOf("GB", "FR")).startListening() // then assertThat(builder.isListening()).isTrue() verify(exactly = 1) { voiceApi.open(any(), any(), expectedUrl, builder) } } @Test fun `clipToCircle is set without radius expect param url`() = coroutinesTestRule.testDispatcher.runBlockingTest { // given val expectedUrl = "$BASE_URL_WITH_COORDINATES?voice-language=en&clip-to-circle=51.1,-0.152,1.0" val what3WordsV3 = What3WordsV3("key", voiceApi, coroutinesTestRule.testDispatcherProvider) val builder = what3WordsV3.autosuggestWithCoordinates(microphone, "en") .onSuggestions(suggestionsCallback) .onError(errorCallback) // when builder.clipToCircle(Coordinates(51.1, -0.152)).startListening() // then assertThat(builder.isListening()).isTrue() verify(exactly = 1) { voiceApi.open(any(), any(), expectedUrl, builder) } } @Test fun `clipToCircle is set with radius expect param url`() = coroutinesTestRule.testDispatcher.runBlockingTest { // given val expectedUrl = "$BASE_URL_WITH_COORDINATES?voice-language=en&clip-to-circle=51.1,-0.152,100.0" val what3WordsV3 = What3WordsV3("key", voiceApi, coroutinesTestRule.testDispatcherProvider) val builder = what3WordsV3.autosuggestWithCoordinates(microphone, "en") .onSuggestions(suggestionsCallback) .onError(errorCallback) // when builder.clipToCircle(Coordinates(51.1, -0.152), 100.0).startListening() // then assertThat(builder.isListening()).isTrue() verify(exactly = 1) { voiceApi.open(any(), any(), expectedUrl, builder) } } @Test fun `clipToBoundingBox is set expect param url`() = coroutinesTestRule.testDispatcher.runBlockingTest { // given val expectedUrl = "$BASE_URL_WITH_COORDINATES?voice-language=en&clip-to-bounding-box=51.1,-0.152,51.1,-0.152" val what3WordsV3 = What3WordsV3("key", voiceApi, coroutinesTestRule.testDispatcherProvider) val builder = what3WordsV3.autosuggestWithCoordinates(microphone, "en") .onSuggestions(suggestionsCallback) .onError(errorCallback) // when builder.clipToBoundingBox( BoundingBox(Coordinates(51.1, -0.152), Coordinates(51.1, -0.152)) ).startListening() // then assertThat(builder.isListening()).isTrue() verify(exactly = 1) { voiceApi.open(any(), any(), expectedUrl, builder) } } @Test fun `clipToPolygon is set expect param url`() = coroutinesTestRule.testDispatcher.runBlockingTest { // given val expectedUrl = "$BASE_URL_WITH_COORDINATES?voice-language=en&clip-to-polygon=51.1,-0.152,51.1,-0.152,51.1,-0.152" val what3WordsV3 = What3WordsV3("key", voiceApi, coroutinesTestRule.testDispatcherProvider) val builder = what3WordsV3.autosuggestWithCoordinates(microphone, "en") .onSuggestions(suggestionsCallback) .onError(errorCallback) // when builder.clipToPolygon( listOf( Coordinates(51.1, -0.152), Coordinates(51.1, -0.152), Coordinates(51.1, -0.152) ) ).startListening() // then assertThat(builder.isListening()).isTrue() verify(exactly = 1) { voiceApi.open(any(), any(), expectedUrl, builder) } } }
1
Kotlin
2
1
95ab9c58149bff97acb4ae2aa7900489e245b133
13,156
w3w-android-wrapper
MIT License
src/main/kotlin/Utils.kt
fscarponi
578,734,253
false
{"Kotlin": 28665}
import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.litote.kmongo.util.KMongoUtil import java.math.BigInteger import java.security.MessageDigest import java.util.regex.Pattern fun String.prependIfMissing(prep: String) = if (startsWith(prep)) this else prep + this fun environmentString( tag: String, name: String = tag, default: String? = null, transform: ((String) -> String)? = null ) = (System.getenv(name) ?: default)?.let { if (transform != null) transform(it) else it } ?: error("Cannot find $name in environment") fun environmentBoolean( tag: String, name: String = tag, default: Boolean? = null, transform: ((Boolean) -> Boolean)? = null ) = (System.getenv(name)?.toBoolean() ?: default)?.let { if (transform != null) transform(it) else it } ?: error("Cannot find $name in environment") fun String.isAValidMail() = Pattern.compile( "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]|[\\w-]{2,}))@" + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?" + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\." + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?" + "[0-9]{1,2}|25[0-5]|2[0-4][0-9]))|" + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$" ).matcher(this).matches() fun String.digestMD5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16).padStart(32, '0') inline fun <reified T> Json.encodeToBson(element: T) = KMongoUtil.toBson(this.encodeToString(element))
0
Kotlin
0
0
13f91b08bf419582ce06b8347020862cc0f7a4d0
1,448
bepractice
MIT License
app/src/main/java/com/maskjs/korona_zakupy/ui/register/part2/RegisterPart2Fragment.kt
Vek0n
253,303,463
false
null
package com.maskjs.korona_zakupy.ui.register.part2 import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.addCallback import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import com.maskjs.korona_zakupy.R import com.maskjs.korona_zakupy.databinding.FragmentRegisterPart2Binding import com.maskjs.korona_zakupy.ui.base.BaseFragment import com.maskjs.korona_zakupy.ui.register.IRegisterNavigation import org.koin.android.scope.lifecycleScope import org.koin.android.viewmodel.scope.getViewModel import org.koin.core.parameter.parametersOf class RegisterPart2Fragment : BaseFragment() { private var registerNavigation: IRegisterNavigation? = null private lateinit var registerViewModel: RegisterPart2ViewModel private lateinit var layoutDataBinding: FragmentRegisterPart2Binding override fun onAttach(context: Context) { super.onAttach(context) registerViewModel = requireActivity().lifecycleScope.getViewModel<RegisterPart2ViewModel>(requireActivity()){ parametersOf(errorMessages)} registerNavigation = context as? IRegisterNavigation if(registerNavigation == null) throw ClassCastException("Error!") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val callback = requireActivity().onBackPressedDispatcher.addCallback(this) { registerNavigation?.goToReg1Fragment() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { initialize(inflater,container) observeUiElements() setUiListener() return layoutDataBinding.root } private fun initialize(inflater: LayoutInflater,container: ViewGroup?){ layoutDataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_register_part2,container,false) layoutDataBinding.lifecycleOwner = this@RegisterPart2Fragment layoutDataBinding.registerViewModel = registerViewModel } private fun observeUiElements(){ observeUserName() observeEmail() observePassword() observeConfirmPassword() } private fun observeUserName(){ registerViewModel.userNameInputTextLayoutModel.textContent.observe(viewLifecycleOwner, Observer { registerViewModel.validateUserName() }) } private fun observeEmail(){ registerViewModel.emailInputTextLayoutModel.textContent.observe(viewLifecycleOwner, Observer { registerViewModel.validateEmail() }) } private fun observePassword(){ registerViewModel.passwordInputTextLayoutModel.textContent.observe(viewLifecycleOwner, Observer { registerViewModel.validatePassword() }) } private fun observeConfirmPassword(){ registerViewModel.confirmPasswordInputTextLayoutModel.textContent.observe(viewLifecycleOwner, Observer { registerViewModel.validateConfirmPassword() }) } private fun setUiListener(){ layoutDataBinding.textViewToLogin.setOnClickListener { registerNavigation?.goToLoginActivityInRegFragment() } layoutDataBinding.fabReg1.setOnClickListener { checkValidation() } } private fun checkValidation(){ if(registerViewModel.checkValidation()) { registerViewModel.save() registerNavigation?.goToReg3Fragment() } } }
0
Kotlin
0
0
732c1cdb41a86ad33f5c61485a38cf4efa7a0f91
3,648
Korona-Zakupy-Android-App
MIT License
app/src/main/java/cn/kaicity/app/iguangke/view/HeaderTitleView.kt
wukaicheng
282,888,775
false
null
package cn.kaicity.app.iguangke.view
0
Kotlin
0
0
9edd1742d38d56458556b9e10a20616c367b9fba
38
iguanke
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/datasync/CfnLocationNFS.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 149148378}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.datasync import io.cloudshiftdev.awscdk.CfnResource import io.cloudshiftdev.awscdk.CfnTag import io.cloudshiftdev.awscdk.IInspectable import io.cloudshiftdev.awscdk.IResolvable import io.cloudshiftdev.awscdk.ITaggable import io.cloudshiftdev.awscdk.TagManager import io.cloudshiftdev.awscdk.TreeInspector import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import kotlin.Any import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlin.jvm.JvmName import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct import software.constructs.Construct as SoftwareConstructsConstruct /** * The `AWS::DataSync::LocationNFS` resource specifies a Network File System (NFS) file server that * AWS DataSync can use as a transfer source or destination. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.datasync.*; * CfnLocationNFS cfnLocationNFS = CfnLocationNFS.Builder.create(this, "MyCfnLocationNFS") * .onPremConfig(OnPremConfigProperty.builder() * .agentArns(List.of("agentArns")) * .build()) * // the properties below are optional * .mountOptions(MountOptionsProperty.builder() * .version("version") * .build()) * .serverHostname("serverHostname") * .subdirectory("subdirectory") * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html) */ public open class CfnLocationNFS internal constructor( internal override val cdkObject: software.amazon.awscdk.services.datasync.CfnLocationNFS, ) : CfnResource(cdkObject), IInspectable, ITaggable { /** * The Amazon Resource Name (ARN) of the NFS location that you created. */ public open fun attrLocationArn(): String = unwrap(this).getAttrLocationArn() /** * The URI of the NFS location that you created. */ public open fun attrLocationUri(): String = unwrap(this).getAttrLocationUri() /** * Examines the CloudFormation resource and discloses attributes. * * @param inspector tree inspector to collect and process attributes. */ public override fun inspect(inspector: TreeInspector) { unwrap(this).inspect(inspector.let(TreeInspector::unwrap)) } /** * Specifies the options that DataSync can use to mount your NFS file server. */ public open fun mountOptions(): Any? = unwrap(this).getMountOptions() /** * Specifies the options that DataSync can use to mount your NFS file server. */ public open fun mountOptions(`value`: IResolvable) { unwrap(this).setMountOptions(`value`.let(IResolvable::unwrap)) } /** * Specifies the options that DataSync can use to mount your NFS file server. */ public open fun mountOptions(`value`: MountOptionsProperty) { unwrap(this).setMountOptions(`value`.let(MountOptionsProperty::unwrap)) } /** * Specifies the options that DataSync can use to mount your NFS file server. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("a9b22858853b8359d646bd681ee53e427c6af8dcb5d72845a37b747060760769") public open fun mountOptions(`value`: MountOptionsProperty.Builder.() -> Unit): Unit = mountOptions(MountOptionsProperty(`value`)) /** * Specifies the Amazon Resource Name (ARN) of the DataSync agent that want to connect to your NFS * file server. */ public open fun onPremConfig(): Any = unwrap(this).getOnPremConfig() /** * Specifies the Amazon Resource Name (ARN) of the DataSync agent that want to connect to your NFS * file server. */ public open fun onPremConfig(`value`: IResolvable) { unwrap(this).setOnPremConfig(`value`.let(IResolvable::unwrap)) } /** * Specifies the Amazon Resource Name (ARN) of the DataSync agent that want to connect to your NFS * file server. */ public open fun onPremConfig(`value`: OnPremConfigProperty) { unwrap(this).setOnPremConfig(`value`.let(OnPremConfigProperty::unwrap)) } /** * Specifies the Amazon Resource Name (ARN) of the DataSync agent that want to connect to your NFS * file server. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("f328cb85a4520771a5c3249f99e0e412aa4de6fe0af00582df57c9ea64185a75") public open fun onPremConfig(`value`: OnPremConfigProperty.Builder.() -> Unit): Unit = onPremConfig(OnPremConfigProperty(`value`)) /** * Specifies the Domain Name System (DNS) name or IP version 4 address of the NFS file server that * your DataSync agent connects to. */ public open fun serverHostname(): String? = unwrap(this).getServerHostname() /** * Specifies the Domain Name System (DNS) name or IP version 4 address of the NFS file server that * your DataSync agent connects to. */ public open fun serverHostname(`value`: String) { unwrap(this).setServerHostname(`value`) } /** * Specifies the export path in your NFS file server that you want DataSync to mount. */ public open fun subdirectory(): String? = unwrap(this).getSubdirectory() /** * Specifies the export path in your NFS file server that you want DataSync to mount. */ public open fun subdirectory(`value`: String) { unwrap(this).setSubdirectory(`value`) } /** * Tag Manager which manages the tags for this resource. */ public override fun tags(): TagManager = unwrap(this).getTags().let(TagManager::wrap) /** * Specifies labels that help you categorize, filter, and search for your AWS resources. */ public open fun tagsRaw(): List<CfnTag> = unwrap(this).getTagsRaw()?.map(CfnTag::wrap) ?: emptyList() /** * Specifies labels that help you categorize, filter, and search for your AWS resources. */ public open fun tagsRaw(`value`: List<CfnTag>) { unwrap(this).setTagsRaw(`value`.map(CfnTag::unwrap)) } /** * Specifies labels that help you categorize, filter, and search for your AWS resources. */ public open fun tagsRaw(vararg `value`: CfnTag): Unit = tagsRaw(`value`.toList()) /** * A fluent builder for [io.cloudshiftdev.awscdk.services.datasync.CfnLocationNFS]. */ @CdkDslMarker public interface Builder { /** * Specifies the options that DataSync can use to mount your NFS file server. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-mountoptions) * @param mountOptions Specifies the options that DataSync can use to mount your NFS file * server. */ public fun mountOptions(mountOptions: IResolvable) /** * Specifies the options that DataSync can use to mount your NFS file server. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-mountoptions) * @param mountOptions Specifies the options that DataSync can use to mount your NFS file * server. */ public fun mountOptions(mountOptions: MountOptionsProperty) /** * Specifies the options that DataSync can use to mount your NFS file server. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-mountoptions) * @param mountOptions Specifies the options that DataSync can use to mount your NFS file * server. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("25a432ce7f1c75dc7f0fe7de40701517a3b87f70b0202663b66a2091262a75ad") public fun mountOptions(mountOptions: MountOptionsProperty.Builder.() -> Unit) /** * Specifies the Amazon Resource Name (ARN) of the DataSync agent that want to connect to your * NFS file server. * * You can specify more than one agent. For more information, see [Using multiple agents for * transfers](https://docs.aws.amazon.com/datasync/latest/userguide/multiple-agents.html) . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-onpremconfig) * @param onPremConfig Specifies the Amazon Resource Name (ARN) of the DataSync agent that want * to connect to your NFS file server. */ public fun onPremConfig(onPremConfig: IResolvable) /** * Specifies the Amazon Resource Name (ARN) of the DataSync agent that want to connect to your * NFS file server. * * You can specify more than one agent. For more information, see [Using multiple agents for * transfers](https://docs.aws.amazon.com/datasync/latest/userguide/multiple-agents.html) . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-onpremconfig) * @param onPremConfig Specifies the Amazon Resource Name (ARN) of the DataSync agent that want * to connect to your NFS file server. */ public fun onPremConfig(onPremConfig: OnPremConfigProperty) /** * Specifies the Amazon Resource Name (ARN) of the DataSync agent that want to connect to your * NFS file server. * * You can specify more than one agent. For more information, see [Using multiple agents for * transfers](https://docs.aws.amazon.com/datasync/latest/userguide/multiple-agents.html) . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-onpremconfig) * @param onPremConfig Specifies the Amazon Resource Name (ARN) of the DataSync agent that want * to connect to your NFS file server. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("2cd9f0ae144cf14221414b6db7af184a49d45996e7a95573bd995075ba3c701f") public fun onPremConfig(onPremConfig: OnPremConfigProperty.Builder.() -> Unit) /** * Specifies the Domain Name System (DNS) name or IP version 4 address of the NFS file server * that your DataSync agent connects to. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-serverhostname) * @param serverHostname Specifies the Domain Name System (DNS) name or IP version 4 address of * the NFS file server that your DataSync agent connects to. */ public fun serverHostname(serverHostname: String) /** * Specifies the export path in your NFS file server that you want DataSync to mount. * * This path (or a subdirectory of the path) is where DataSync transfers data to or from. For * information on configuring an export for DataSync, see [Accessing NFS file * servers](https://docs.aws.amazon.com/datasync/latest/userguide/create-nfs-location.html#accessing-nfs) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-subdirectory) * @param subdirectory Specifies the export path in your NFS file server that you want DataSync * to mount. */ public fun subdirectory(subdirectory: String) /** * Specifies labels that help you categorize, filter, and search for your AWS resources. * * We recommend creating at least a name tag for your location. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-tags) * @param tags Specifies labels that help you categorize, filter, and search for your AWS * resources. */ public fun tags(tags: List<CfnTag>) /** * Specifies labels that help you categorize, filter, and search for your AWS resources. * * We recommend creating at least a name tag for your location. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-tags) * @param tags Specifies labels that help you categorize, filter, and search for your AWS * resources. */ public fun tags(vararg tags: CfnTag) } private class BuilderImpl( scope: SoftwareConstructsConstruct, id: String, ) : Builder { private val cdkBuilder: software.amazon.awscdk.services.datasync.CfnLocationNFS.Builder = software.amazon.awscdk.services.datasync.CfnLocationNFS.Builder.create(scope, id) /** * Specifies the options that DataSync can use to mount your NFS file server. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-mountoptions) * @param mountOptions Specifies the options that DataSync can use to mount your NFS file * server. */ override fun mountOptions(mountOptions: IResolvable) { cdkBuilder.mountOptions(mountOptions.let(IResolvable::unwrap)) } /** * Specifies the options that DataSync can use to mount your NFS file server. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-mountoptions) * @param mountOptions Specifies the options that DataSync can use to mount your NFS file * server. */ override fun mountOptions(mountOptions: MountOptionsProperty) { cdkBuilder.mountOptions(mountOptions.let(MountOptionsProperty::unwrap)) } /** * Specifies the options that DataSync can use to mount your NFS file server. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-mountoptions) * @param mountOptions Specifies the options that DataSync can use to mount your NFS file * server. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("25a432ce7f1c75dc7f0fe7de40701517a3b87f70b0202663b66a2091262a75ad") override fun mountOptions(mountOptions: MountOptionsProperty.Builder.() -> Unit): Unit = mountOptions(MountOptionsProperty(mountOptions)) /** * Specifies the Amazon Resource Name (ARN) of the DataSync agent that want to connect to your * NFS file server. * * You can specify more than one agent. For more information, see [Using multiple agents for * transfers](https://docs.aws.amazon.com/datasync/latest/userguide/multiple-agents.html) . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-onpremconfig) * @param onPremConfig Specifies the Amazon Resource Name (ARN) of the DataSync agent that want * to connect to your NFS file server. */ override fun onPremConfig(onPremConfig: IResolvable) { cdkBuilder.onPremConfig(onPremConfig.let(IResolvable::unwrap)) } /** * Specifies the Amazon Resource Name (ARN) of the DataSync agent that want to connect to your * NFS file server. * * You can specify more than one agent. For more information, see [Using multiple agents for * transfers](https://docs.aws.amazon.com/datasync/latest/userguide/multiple-agents.html) . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-onpremconfig) * @param onPremConfig Specifies the Amazon Resource Name (ARN) of the DataSync agent that want * to connect to your NFS file server. */ override fun onPremConfig(onPremConfig: OnPremConfigProperty) { cdkBuilder.onPremConfig(onPremConfig.let(OnPremConfigProperty::unwrap)) } /** * Specifies the Amazon Resource Name (ARN) of the DataSync agent that want to connect to your * NFS file server. * * You can specify more than one agent. For more information, see [Using multiple agents for * transfers](https://docs.aws.amazon.com/datasync/latest/userguide/multiple-agents.html) . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-onpremconfig) * @param onPremConfig Specifies the Amazon Resource Name (ARN) of the DataSync agent that want * to connect to your NFS file server. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("2cd9f0ae144cf14221414b6db7af184a49d45996e7a95573bd995075ba3c701f") override fun onPremConfig(onPremConfig: OnPremConfigProperty.Builder.() -> Unit): Unit = onPremConfig(OnPremConfigProperty(onPremConfig)) /** * Specifies the Domain Name System (DNS) name or IP version 4 address of the NFS file server * that your DataSync agent connects to. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-serverhostname) * @param serverHostname Specifies the Domain Name System (DNS) name or IP version 4 address of * the NFS file server that your DataSync agent connects to. */ override fun serverHostname(serverHostname: String) { cdkBuilder.serverHostname(serverHostname) } /** * Specifies the export path in your NFS file server that you want DataSync to mount. * * This path (or a subdirectory of the path) is where DataSync transfers data to or from. For * information on configuring an export for DataSync, see [Accessing NFS file * servers](https://docs.aws.amazon.com/datasync/latest/userguide/create-nfs-location.html#accessing-nfs) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-subdirectory) * @param subdirectory Specifies the export path in your NFS file server that you want DataSync * to mount. */ override fun subdirectory(subdirectory: String) { cdkBuilder.subdirectory(subdirectory) } /** * Specifies labels that help you categorize, filter, and search for your AWS resources. * * We recommend creating at least a name tag for your location. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-tags) * @param tags Specifies labels that help you categorize, filter, and search for your AWS * resources. */ override fun tags(tags: List<CfnTag>) { cdkBuilder.tags(tags.map(CfnTag::unwrap)) } /** * Specifies labels that help you categorize, filter, and search for your AWS resources. * * We recommend creating at least a name tag for your location. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datasync-locationnfs.html#cfn-datasync-locationnfs-tags) * @param tags Specifies labels that help you categorize, filter, and search for your AWS * resources. */ override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList()) public fun build(): software.amazon.awscdk.services.datasync.CfnLocationNFS = cdkBuilder.build() } public companion object { public val CFN_RESOURCE_TYPE_NAME: String = software.amazon.awscdk.services.datasync.CfnLocationNFS.CFN_RESOURCE_TYPE_NAME public operator fun invoke( scope: CloudshiftdevConstructsConstruct, id: String, block: Builder.() -> Unit = {}, ): CfnLocationNFS { val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id) return CfnLocationNFS(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.datasync.CfnLocationNFS): CfnLocationNFS = CfnLocationNFS(cdkObject) internal fun unwrap(wrapped: CfnLocationNFS): software.amazon.awscdk.services.datasync.CfnLocationNFS = wrapped.cdkObject } /** * The AWS DataSync agents that are connecting to a Network File System (NFS) location. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.datasync.*; * OnPremConfigProperty onPremConfigProperty = OnPremConfigProperty.builder() * .agentArns(List.of("agentArns")) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datasync-locationnfs-onpremconfig.html) */ public interface OnPremConfigProperty { /** * The Amazon Resource Names (ARNs) of the agents connecting to a transfer location. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datasync-locationnfs-onpremconfig.html#cfn-datasync-locationnfs-onpremconfig-agentarns) */ public fun agentArns(): List<String> /** * A builder for [OnPremConfigProperty] */ @CdkDslMarker public interface Builder { /** * @param agentArns The Amazon Resource Names (ARNs) of the agents connecting to a transfer * location. */ public fun agentArns(agentArns: List<String>) /** * @param agentArns The Amazon Resource Names (ARNs) of the agents connecting to a transfer * location. */ public fun agentArns(vararg agentArns: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.datasync.CfnLocationNFS.OnPremConfigProperty.Builder = software.amazon.awscdk.services.datasync.CfnLocationNFS.OnPremConfigProperty.builder() /** * @param agentArns The Amazon Resource Names (ARNs) of the agents connecting to a transfer * location. */ override fun agentArns(agentArns: List<String>) { cdkBuilder.agentArns(agentArns) } /** * @param agentArns The Amazon Resource Names (ARNs) of the agents connecting to a transfer * location. */ override fun agentArns(vararg agentArns: String): Unit = agentArns(agentArns.toList()) public fun build(): software.amazon.awscdk.services.datasync.CfnLocationNFS.OnPremConfigProperty = cdkBuilder.build() } private class Wrapper( override val cdkObject: software.amazon.awscdk.services.datasync.CfnLocationNFS.OnPremConfigProperty, ) : CdkObject(cdkObject), OnPremConfigProperty { /** * The Amazon Resource Names (ARNs) of the agents connecting to a transfer location. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datasync-locationnfs-onpremconfig.html#cfn-datasync-locationnfs-onpremconfig-agentarns) */ override fun agentArns(): List<String> = unwrap(this).getAgentArns() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): OnPremConfigProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.datasync.CfnLocationNFS.OnPremConfigProperty): OnPremConfigProperty = Wrapper(cdkObject) internal fun unwrap(wrapped: OnPremConfigProperty): software.amazon.awscdk.services.datasync.CfnLocationNFS.OnPremConfigProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.datasync.CfnLocationNFS.OnPremConfigProperty } } /** * Specifies the options that DataSync can use to mount your NFS file server. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.datasync.*; * MountOptionsProperty mountOptionsProperty = MountOptionsProperty.builder() * .version("version") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datasync-locationnfs-mountoptions.html) */ public interface MountOptionsProperty { /** * Specifies the NFS version that you want DataSync to use when mounting your NFS share. * * If the server refuses to use the version specified, the task fails. * * You can specify the following options: * * * `AUTOMATIC` (default): DataSync chooses NFS version 4.1. * * `NFS3` : Stateless protocol version that allows for asynchronous writes on the server. * * `NFSv4_0` : Stateful, firewall-friendly protocol version that supports delegations and * pseudo file systems. * * `NFSv4_1` : Stateful protocol version that supports sessions, directory delegations, and * parallel data processing. NFS version 4.1 also includes all features available in version 4.0. * * * DataSync currently only supports NFS version 3 with Amazon FSx for NetApp ONTAP locations. * * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datasync-locationnfs-mountoptions.html#cfn-datasync-locationnfs-mountoptions-version) */ public fun version(): String? = unwrap(this).getVersion() /** * A builder for [MountOptionsProperty] */ @CdkDslMarker public interface Builder { /** * @param version Specifies the NFS version that you want DataSync to use when mounting your * NFS share. * If the server refuses to use the version specified, the task fails. * * You can specify the following options: * * * `AUTOMATIC` (default): DataSync chooses NFS version 4.1. * * `NFS3` : Stateless protocol version that allows for asynchronous writes on the server. * * `NFSv4_0` : Stateful, firewall-friendly protocol version that supports delegations and * pseudo file systems. * * `NFSv4_1` : Stateful protocol version that supports sessions, directory delegations, and * parallel data processing. NFS version 4.1 also includes all features available in version 4.0. * * * DataSync currently only supports NFS version 3 with Amazon FSx for NetApp ONTAP locations. */ public fun version(version: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.datasync.CfnLocationNFS.MountOptionsProperty.Builder = software.amazon.awscdk.services.datasync.CfnLocationNFS.MountOptionsProperty.builder() /** * @param version Specifies the NFS version that you want DataSync to use when mounting your * NFS share. * If the server refuses to use the version specified, the task fails. * * You can specify the following options: * * * `AUTOMATIC` (default): DataSync chooses NFS version 4.1. * * `NFS3` : Stateless protocol version that allows for asynchronous writes on the server. * * `NFSv4_0` : Stateful, firewall-friendly protocol version that supports delegations and * pseudo file systems. * * `NFSv4_1` : Stateful protocol version that supports sessions, directory delegations, and * parallel data processing. NFS version 4.1 also includes all features available in version 4.0. * * * DataSync currently only supports NFS version 3 with Amazon FSx for NetApp ONTAP locations. */ override fun version(version: String) { cdkBuilder.version(version) } public fun build(): software.amazon.awscdk.services.datasync.CfnLocationNFS.MountOptionsProperty = cdkBuilder.build() } private class Wrapper( override val cdkObject: software.amazon.awscdk.services.datasync.CfnLocationNFS.MountOptionsProperty, ) : CdkObject(cdkObject), MountOptionsProperty { /** * Specifies the NFS version that you want DataSync to use when mounting your NFS share. * * If the server refuses to use the version specified, the task fails. * * You can specify the following options: * * * `AUTOMATIC` (default): DataSync chooses NFS version 4.1. * * `NFS3` : Stateless protocol version that allows for asynchronous writes on the server. * * `NFSv4_0` : Stateful, firewall-friendly protocol version that supports delegations and * pseudo file systems. * * `NFSv4_1` : Stateful protocol version that supports sessions, directory delegations, and * parallel data processing. NFS version 4.1 also includes all features available in version 4.0. * * * DataSync currently only supports NFS version 3 with Amazon FSx for NetApp ONTAP locations. * * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datasync-locationnfs-mountoptions.html#cfn-datasync-locationnfs-mountoptions-version) */ override fun version(): String? = unwrap(this).getVersion() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): MountOptionsProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.datasync.CfnLocationNFS.MountOptionsProperty): MountOptionsProperty = Wrapper(cdkObject) internal fun unwrap(wrapped: MountOptionsProperty): software.amazon.awscdk.services.datasync.CfnLocationNFS.MountOptionsProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.datasync.CfnLocationNFS.MountOptionsProperty } } }
1
Kotlin
0
4
eb3eef728b34da593a3e55dc423d4f5fa3668e9c
30,413
kotlin-cdk-wrapper
Apache License 2.0
app/src/main/java/com/smd/surmaiya/ManagerClasses/FirebaseAuthManager.kt
AhmadHassan71
786,394,928
false
{"Kotlin": 408430, "Java": 347}
package com.smd.surmaiya.ManagerClasses import android.content.ContentValues import android.content.Intent import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.smd.surmaiya.itemClasses.User import com.google.firebase.messaging.FirebaseMessaging import com.smd.surmaiya.HelperClasses.CustomToastMaker import kotlinx.coroutines.flow.callbackFlow import java.security.MessageDigest class FirebaseAuthManager(private val activity: AppCompatActivity) { private var mAuth : FirebaseAuth = FirebaseAuth.getInstance() fun hashPassword(password: String): String { val bytes = password.toByteArray() val md = MessageDigest.getInstance("SHA-256") val digest = md.digest(bytes) return digest.fold("", { str, it -> str + "%02x".format(it) }) } fun saveUserAuthentication(user: User,Callback:(Boolean)->Unit) { mAuth.createUserWithEmailAndPassword(user.email, user.password) .addOnCompleteListener(activity) { task -> if (task.isSuccessful) { val user1 = mAuth.currentUser UserManager.setCurrentUser(user) FirebaseMessaging.getInstance().token.addOnCompleteListener { task -> if (!task.isSuccessful) { return@addOnCompleteListener } // Get new FCM registration token val token = task.result // Log and toast val msg = token Log.d("MyToken", msg) addFcmTokenToUser(UserManager.getCurrentUser()?.id.toString(), "users", token) UserManager.getCurrentUser()?.fcmToken = token.toString() CustomToastMaker().showToast(activity, "User created successfully") Callback(true) } } else { Log.e("Signing Up User", "Error creating user: ${task.exception?.message}") Callback(false) } } } fun loginUser(email: String,password1:String, Callback: (Boolean) -> Unit) { val password = <PASSWORD>) Log.d("Password",password) mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(activity) { task -> if (task.isSuccessful) { val user = mAuth.currentUser val userManager = UserManager.getInstance() userManager.fetchAndSetCurrentUser(user?.email.toString()) { FirebaseMessaging.getInstance().token.addOnCompleteListener { task -> if (!task.isSuccessful) { return@addOnCompleteListener } // Get new FCM registration token val token = task.result // Log and toast val msg = token Log.d("MyToken", msg) addFcmTokenToUser(UserManager.getCurrentUser()?.id.toString(), "users", token) UserManager.getCurrentUser()?.fcmToken = token.toString() Callback(true) } } } else { Log.w(ContentValues.TAG, "signInWithEmail:failure", task.exception) Callback(false) } } } fun checkEmailAvailability(email: String, completion: (Boolean) -> Unit) { val database = FirebaseDatabase.getInstance() val usersRef = database.getReference("users") usersRef.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val isAvailable = snapshot.childrenCount.toInt() == 0 completion(isAvailable) } override fun onCancelled(error: DatabaseError) { // Handle database error completion(false) } }) } fun checkPhoneAvailability(phone: String, completion: (Boolean) -> Unit) { val database = FirebaseDatabase.getInstance() val usersRef = database.getReference("users") usersRef.orderByChild("phone").equalTo(phone).addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val isAvailable = snapshot.childrenCount.toInt() == 0 completion(isAvailable) } override fun onCancelled(error: DatabaseError) { // Handle database error completion(false) } }) } fun addFcmTokenToUser( userId: String, userType: String, fcmToken: String ) { val database = FirebaseDatabase.getInstance() val fcmTokenRef = database.getReference(userType).child(userId).child("fcmToken") fcmTokenRef.setValue(fcmToken) .addOnSuccessListener { Log.d(ContentValues.TAG, "FCM token added successfully") } .addOnFailureListener { e -> Log.e(ContentValues.TAG, "Failed to add FCM token: ${e.message}") } } }
0
Kotlin
0
4
53bff924bffca89674c39c8ede66b62fb8318f00
5,835
Surmaiya
MIT License
app/src/main/java/com/dreamsoftware/fitflextv/data/remote/exception/RemoteDataSourceException.kt
sergio11
534,529,261
false
{"Kotlin": 615931}
package com.dreamsoftware.fitflextv.data.remote.exception open class RemoteDataSourceException(message: String? = null, cause: Throwable? = null): Exception(message, cause) // Auth Data Source class AuthRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class SignInRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class SignUpRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) // Categories class FetchCategoriesRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class FetchCategoryByIdRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) // Instructors class FetchInstructorsRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class FetchInstructorByIdRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) // Songs class FetchTrainingSongByIdRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) // Subscriptions class FetchSubscriptionsRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) // User Subscriptions class FetchUserSubscriptionRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class AddUserSubscriptionRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class RemoveUserSubscriptionRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class VerifyHasActiveSubscriptionRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) // Trainings class FetchTrainingsRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class FetchTrainingByIdRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class FetchTrainingByCategoryRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class FetchFeaturedTrainingsRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class FetchRecommendedTrainingsRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) // Profiles class FetchProfilesRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class UpdateProfileRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class DeleteProfileRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class CreateProfileRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class VerifyProfileRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class FetchProfileByIdRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) // Users class CreateUserDetailRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class UpdateUserDetailRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class FetchUserDetailRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class UpdateProfilesCountRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) // Favorites class AddToFavoritesRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class RemoveFromFavoritesRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class RemoveAllFavoritesRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class GetFavoritesByUserRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause) class HasTrainingInFavoritesRemoteException(message: String? = null, cause: Throwable? = null): RemoteDataSourceException(message, cause)
0
Kotlin
3
40
4452dcbcf3d4388144a949c65c216de5547c82a6
4,705
fitflextv_android
Apache License 2.0
data/src/main/java/com/gamapp/data/data_source/media_store/MediaStoreFetchDataSource.kt
aliHosseinNezhad
507,626,994
false
null
package com.gamapp.data.data_source.media_store import com.gamapp.domain.models.AlbumModel import com.gamapp.domain.models.ArtistModel import com.gamapp.domain.models.TrackModel import kotlinx.coroutines.flow.Flow interface MediaStoreFetchDataSource { fun getAllTracks(): Flow<List<TrackModel>> fun getAllAlbums(): Flow<List<AlbumModel>> fun getAllArtists(): Flow<List<ArtistModel>> fun getAlbumById(albumId: Long): Flow<AlbumModel> fun getArtistById(artistId: Long): Flow<ArtistModel> /** * @param ids list of tracks ids * */ fun getTracksByIds(ids: List<Long>): Flow<List<TrackModel>> fun getTrackById(id:Long):Flow<TrackModel?> }
0
Kotlin
0
2
8eddbdbcd5706072262ed7bd2cf6b2d0a6df6ada
684
DMPlayer_public
MIT License
server/src/main/kotlin/com/kazakago/cueue/database/entity/WorkspaceEntity.kt
KazaKago
329,953,173
false
{"Kotlin": 112293, "Dockerfile": 338}
package com.kazakago.cueue.database.entity import com.kazakago.cueue.database.table.MenusTable import com.kazakago.cueue.database.table.RecipesTable import com.kazakago.cueue.database.table.TagsTable import com.kazakago.cueue.database.table.UsersTable import com.kazakago.cueue.database.table.WorkspacesTable import org.jetbrains.exposed.dao.LongEntity import org.jetbrains.exposed.dao.LongEntityClass import org.jetbrains.exposed.dao.id.EntityID class WorkspaceEntity(id: EntityID<Long>) : LongEntity(id) { companion object : LongEntityClass<WorkspaceEntity>(WorkspacesTable) var createdAt by WorkspacesTable.createdAt var updatedAt by WorkspacesTable.updatedAt val recipes by RecipeEntity referrersOn RecipesTable.workspaceId val tags by TagEntity referrersOn TagsTable.workspaceId val menus by MenuEntity referrersOn MenusTable.workspaceId val users by UserEntity referrersOn UsersTable.workspaceId }
7
Kotlin
0
1
da6516826ec9d35ac046249bf146b2f8b23c9be7
935
cueue_server
Apache License 2.0
app/src/main/java/net/lll0/app/util/SingletonDemo.kt
aalj
152,862,620
false
null
package net.lll0.app.util /** * Created by liangjun on 2018/11/5 * */ class SingletonDemo private constructor() { companion object { // var instance: SingletonDemo? = null // get() { // if (field == null) { // field = SingletonDemo() // } // return field!! // } // // @Synchronized // fun get(): SingletonDemo { // return instance!! // } val instance: SingletonDemo by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { SingletonDemo() } } }
1
null
1
1
b09dc08534390b6609dadf73ebe76f8dcd03ad5c
607
ApplicationModel
Apache License 2.0
app/src/main/java/com/raheemjnr/jr_music/media/MediaPlaybackPreparer.kt
RaheemJnr
489,742,823
false
{"Kotlin": 153287}
package com.raheemjnr.jr_music.media import android.net.Uri import android.os.Bundle import android.os.ResultReceiver import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.PlaybackStateCompat import android.util.Log import com.google.android.exoplayer2.Player import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector import com.raheemjnr.jr_music.media.extentions.album import com.raheemjnr.jr_music.media.extentions.trackNumber import com.raheemjnr.jr_music.utils.TAG class MediaPlaybackPreparer( private val musicSource: MusicSource, private val playerPrepared: (MediaMetadataCompat) -> Unit ) : MediaSessionConnector.PlaybackPreparer { /** * UAMP supports preparing (and playing) from search, as well as media ID, so those * capabilities are declared here. * * TODO: Add support for ACTION_PREPARE and ACTION_PLAY, which mean "prepare/play something". */ override fun getSupportedPrepareActions(): Long = PlaybackStateCompat.ACTION_PREPARE_FROM_MEDIA_ID or PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID override fun onPrepare(playWhenReady: Boolean) { /* val recentSong = storage.loadRecentSong() ?: return onPrepareFromMediaId( recentSong.mediaId!!, playWhenReady, recentSong.description.extras ) */ musicSource.songs[0].description.mediaId?.let { mediaId -> onPrepareFromMediaId( mediaId, playWhenReady, musicSource.songs[0].bundle ) } } override fun onPrepareFromMediaId( mediaId: String, playWhenReady: Boolean, extras: Bundle? ) { musicSource.whenReady { val itemToPlay: MediaMetadataCompat? = musicSource.songs.find { item -> item.description.mediaId == mediaId } if (itemToPlay == null) { Log.w(TAG, "Content not found: MediaID=$mediaId") // TODO: Notify caller of the error. } else { playerPrepared(itemToPlay) // val playbackStartPositionMs = // extras?.getLong( // MEDIA_DESCRIPTION_EXTRAS_START_PLAYBACK_POSITION_MS, // C.TIME_UNSET // ) // ?: C.TIME_UNSET // // preparePlaylist( // buildPlaylist(itemToPlay), // itemToPlay, // playWhenReady, // playbackStartPositionMs // ) } // musicSource.whenReady { // val itemToPlay = musicSource.songs.find { mediaId == it.description.mediaId } // playerPrepared(itemToPlay) // } } } override fun onPrepareFromSearch(query: String, playWhenReady: Boolean, extras: Bundle?) = Unit override fun onPrepareFromUri(uri: Uri, playWhenReady: Boolean, extras: Bundle?) = Unit override fun onCommand( player: Player, command: String, extras: Bundle?, cb: ResultReceiver? ) = false /** * Builds a playlist based on a [MediaMetadataCompat]. * @param item Item to base the playlist on. * @return a [List] of [MediaMetadataCompat] objects representing a playlist. */ private fun buildPlaylist(item: MediaMetadataCompat): List<MediaMetadataCompat> = musicSource.songs.filter { it.album == item.album }.sortedBy { it.trackNumber } }
0
Kotlin
0
0
43a64f07137c6b3be5b5a381c31ee9a6a57a7be5
3,603
Jr-Music-Player
MIT License
core/src/jvmMain/kotlin/zakadabar/stack/backend/data/builtin/account/AccountPrivateDao.kt
kondorj
355,137,640
true
{"Kotlin": 577495, "HTML": 828, "JavaScript": 820, "Shell": 253}
/* * Copyright © 2020, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license. */ package zakadabar.stack.backend.data.builtin.account import org.jetbrains.exposed.dao.LongEntity import org.jetbrains.exposed.dao.LongEntityClass import org.jetbrains.exposed.dao.id.EntityID import zakadabar.stack.backend.data.builtin.principal.PrincipalDao import zakadabar.stack.data.builtin.account.AccountPrivateDto import zakadabar.stack.data.builtin.account.AccountPublicDto class AccountPrivateDao(id: EntityID<Long>) : LongEntity(id) { companion object : LongEntityClass<AccountPrivateDao>(AccountPrivateTable) var principal by PrincipalDao referencedOn AccountPrivateTable.principal var accountName by AccountPrivateTable.accountName var fullName by AccountPrivateTable.fullName var email by AccountPrivateTable.email var displayName by AccountPrivateTable.displayName var locale by AccountPrivateTable.locale var avatar by AccountImageDao optionalReferencedOn AccountPrivateTable.avatar var organizationName by AccountPrivateTable.organizationName var position by AccountPrivateTable.position var phone by AccountPrivateTable.phone fun toDto() = AccountPrivateDto( id = id.value, accountName = accountName, fullName = fullName, email = email, displayName = displayName, locale = locale, avatar = avatar?.id?.value, organizationName = organizationName, position = position, phone = phone ) fun toPublicDto(addEmail: Boolean) = AccountPublicDto( id = id.value, accountName = accountName, fullName = fullName, email = if (addEmail) email else null, displayName = displayName, locale = locale, organizationName = organizationName ) }
0
null
0
0
2379c0fb031f04a230e753a9afad6bd260f6a0b2
1,865
zakadabar-stack
Apache License 2.0
modules/kilua-bootstrap/src/commonMain/kotlin/dev/kilua/panel/Accordion.kt
rjaros
706,876,956
false
null
/* * Copyright (c) 2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.kilua.panel import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import dev.kilua.compose.ComponentNode import dev.kilua.core.ComponentBase import dev.kilua.core.DefaultRenderConfig import dev.kilua.core.RenderConfig import dev.kilua.html.CommentNode import dev.kilua.html.Div import dev.kilua.html.Tag import dev.kilua.html.button import dev.kilua.html.commentNode import dev.kilua.html.div import dev.kilua.html.h2 import dev.kilua.panel.Accordion.Companion.idCounter import dev.kilua.utils.rem import web.dom.HTMLDivElement internal data class AccordionItem( val label: String? = null, val icon: String? = null, val content: @Composable Div.() -> Unit ) public open class Accordion( className: String? = null, renderConfig: RenderConfig = DefaultRenderConfig() ) : Tag<HTMLDivElement>("div", className, renderConfig) { internal val items = mutableStateMapOf<Int, AccordionItem>() internal var itemsOrderList: List<Int> by mutableStateOf(emptyList()) /** * Adds an accordion item. * @param label the label of the item * @param icon the icon of the item * @param content the content of the item */ @Composable public fun item( label: String? = null, icon: String? = null, content: @Composable Div.() -> Unit ) { val itemId = remember { idCounter++ } commentNode("sid=$itemId") val item = AccordionItem(label, icon, content) if (items[itemId] != item) { items[itemId] = item } DisposableEffect(itemId) { refreshItemsOrderList() onDispose { refreshItemsOrderList() items.remove(itemId) } } } private fun refreshItemsOrderList() { itemsOrderList = this.children.filterIsInstance<CommentNode>().filter { it.data.startsWith("sid=") } .mapNotNull { it.data.drop("sid=".length).toIntOrNull() } } public companion object { internal var idCounter: Int = 0 } } @Composable private fun ComponentBase.accordion( className: String? = null, content: @Composable Accordion.() -> Unit, ): Accordion { val component = remember { Accordion(className, renderConfig) } ComponentNode(component, { set(className) { updateProperty(Accordion::className, it) } }, content) return component } /** * Creates an [Accordion] component. * * @param flush determines if the accordion has no rounded corners * @param alwaysOpen determines if the accordion items are automatically closing * @param openedIndex the index of the initially opened item * @param className the CSS class name * @param content the content of the accordion * @return the [Accordion] component */ @Composable public fun ComponentBase.accordion( flush: Boolean = false, alwaysOpen: Boolean = false, openedIndex: Int = 0, className: String? = null, content: @Composable Accordion.() -> Unit, ): Accordion { val accordionId = remember { "kilua_accordion_${idCounter++}" } return accordion("accordion" % if (flush) "accordion-flush" else null % className) { id = accordionId content() itemsOrderList.forEachIndexed { index, itemId -> this.items[itemId]?.let { item -> div("accordion-item") { h2("accordion-header") { button( item.label, item.icon, className = "accordion-button" % if (index != openedIndex) "collapsed" else null ) { setAttribute("data-bs-toggle", "collapse") setAttribute("data-bs-target", "#$accordionId-item-$index") setAttribute("aria-expanded", (index == openedIndex).toString()) setAttribute("aria-controls", "$accordionId-item-$index") } } div("accordion-collapse collapse" % if (index == openedIndex) "show" else null) { id = "$accordionId-item-$index" if (!alwaysOpen) { setAttribute("data-bs-parent", "#$accordionId") } div("accordion-body") { item.content(this) } } } } } } }
3
null
5
97
524a35c898fe84fa1773b53bf97e701cdc00155b
5,899
kilua
MIT License
app/src/main/java/com/example/gifter_single_module/profile/profile_add_edit/use_case/validation/ValidateNamedayDateUseCase.kt
chrming
490,583,267
false
null
package com.example.gifter_single_module.profile.profile_add_edit.use_case.validation import com.example.gifter_single_module.profile.util.MaxChars import com.example.gifter_single_module.util.TextError class ValidateNamedayDateUseCase { operator fun invoke(date: String): TextError { if (date.isBlank()) { return TextError(isError = true, errorMessage = "Date cannot be blank.") } if (date.length > MaxChars.namedayDate) { return TextError( isError = true, errorMessage = "Date can contain ${MaxChars.namedayDate} characters." ) } if (date.contains(regex = Regex("""([^\d])+"""))) { return TextError( isError = true, errorMessage = "Date can contain only digits" ) } return TextError(isError = false) } } //TODO validate day and month
0
Kotlin
0
0
1937d14a8eb35df1e750ed9fee128879dfd80781
925
GifterSingleModule
BSD Source Code Attribution
src/main/kotlin/dev/shtanko/algorithms/leetcode/AllPossibleFullBinaryTrees.kt
ashtanko
203,993,092
false
{"Kotlin": 5931500, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 894. All Possible Full Binary Trees * @see <a href="https://leetcode.com/problems/all-possible-full-binary-trees/">Source</a> */ fun interface AllPossibleFullBinaryTrees { operator fun invoke(n: Int): List<TreeNode?> } class AllPossibleFullBinaryTreesIterative : AllPossibleFullBinaryTrees { override fun invoke(n: Int): List<TreeNode?> { val ret: MutableList<TreeNode> = ArrayList() if (n % 2 == 0) { return ret } else if (1 == n) { ret.add(TreeNode(0)) return ret } // Build up a cache of a all possible FBT for the N - 2 levels // these levels will be linked together as a graph and should not // be returned val cache: MutableList<MutableList<TreeNode>> = ArrayList() cache.add(ArrayList<TreeNode>()) cache[0].add(TreeNode(0)) for (root in 1 until n / 2) { val newRoot: MutableList<TreeNode> = ArrayList() for (leftSize in 0 until root) { for (left in cache[leftSize]) { for (right in cache[root - leftSize - 1]) { val newTree = TreeNode(0) newTree.left = left newTree.right = right newRoot.add(newTree) } } } cache.add(newRoot) } // Cached values are linked together and must be cloned to be unlinked // trees before returning for (root in 0 until n / 2) { for (left in cache[root]) { for (right in cache[n / 2 - root - 1]) { val newTree = TreeNode(0) newTree.left = left.clone() newTree.right = right.clone() ret.add(newTree) } } } return ret } } class AllPossibleFullBinaryTreesRecursive : AllPossibleFullBinaryTrees { override fun invoke(n: Int): List<TreeNode?> { val ret: MutableList<TreeNode> = ArrayList() if (1 == n) { ret.add(TreeNode(0)) } else if (n % 2 != 0) { var i = 2 while (i <= n) { val leftBranch = invoke(i - 1) val rightBranch = invoke(n - i) val leftIter = leftBranch.iterator() while (leftIter.hasNext()) { val left = leftIter.next() val rightIter = rightBranch.iterator() while (rightIter.hasNext()) { val right = rightIter.next() val tree = TreeNode(0) // If we're using the last right branch, then this will be the last time this left branch is // used and can hence // be shallow copied, otherwise the tree will have to be cloned tree.left = if (rightIter.hasNext()) left.clone() else left // If we're using the last left branch, then this will be the last time this right branch is // used and can hence // be shallow copied, otherwise the tree will have to be cloned tree.right = if (leftIter.hasNext()) right.clone() else right ret.add(tree) } } i += 2 } } return ret } }
6
Kotlin
0
19
63877ed36cb5395797d4aad5e2d282b7c91a4174
4,126
kotlab
Apache License 2.0
mobile/src/main/java/com/podcreep/app/service/MediaServiceClient.kt
podcreep
131,102,789
false
null
package com.podcreep.app.service import android.content.ComponentName import android.content.Context import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaControllerCompat import android.support.v4.media.session.PlaybackStateCompat import com.podcreep.MainActivity import com.podcreep.model.store.Episode import com.podcreep.model.store.Podcast /** * MediaServiceClient is a helper class that uses the media browser/media session API to talk with the media service. * Doing it this way means we keep things nicely in sync with other playback state. */ class MediaServiceClient(private val context: Context) { abstract class Callbacks { open fun onPlaybackStateChanged(state: PlaybackStateCompat) {} open fun onMetadataChanged(metadata: MediaMetadataCompat) {} } companion object { val TAG = "MediaServiceClient" } private val mediaBrowser: MediaBrowserCompat private val callbacks: ArrayList<Callbacks> = ArrayList() private var mediaController: MediaControllerCompat? = null private var activity: MainActivity? = null private var lastPlaybackState: PlaybackStateCompat? = null private var lastMetadata: MediaMetadataCompat? = null init { mediaBrowser = MediaBrowserCompat( context, ComponentName(context, MediaService::class.java), MediaBrowserConnectionCallbacks(), null // optional Bundle ) mediaBrowser.connect() } fun attachActivity(activity: MainActivity) { val oldActivity = this.activity if (oldActivity != null) { // TODO: error? detachActivity(oldActivity) } this.activity = activity MediaControllerCompat.setMediaController(activity, mediaController) } fun detachActivity(activity: MainActivity) { if (this.activity != activity) { // TODO: error? return } this.activity = null } fun addCallback(callback: Callbacks) { if (callbacks.contains(callback)) { return } callbacks.add(callback) val playbackState = lastPlaybackState if (playbackState != null) { callback.onPlaybackStateChanged(playbackState) } val metadata = lastMetadata if (metadata != null) { callback.onMetadataChanged(metadata) } } fun removeCallback(callback: Callbacks) { callbacks.remove(callback) } fun play(podcast: Podcast, episode: Episode) { val mediaIdBuilder = MediaIdBuilder() mediaController?.transportControls?.playFromMediaId( mediaIdBuilder.getMediaId(podcast, episode), null) } fun play() { mediaController?.transportControls?.play() } fun pause() { mediaController?.transportControls?.pause() } fun skipForward() { // TODO: make these custom actions. mediaController?.transportControls?.skipToNext() } fun skipBack() { // TODO: make these custom actions. mediaController?.transportControls?.skipToPrevious() } private var controllerCallback = object : MediaControllerCompat.Callback() { override fun onMetadataChanged(metadata: MediaMetadataCompat?) { if (metadata == null) { return } lastMetadata = metadata callbacks.forEach { it.onMetadataChanged(metadata) } } override fun onPlaybackStateChanged(state: PlaybackStateCompat?) { if (state == null) { return } lastPlaybackState = state callbacks.forEach { it.onPlaybackStateChanged(state) } } } private inner class MediaBrowserConnectionCallbacks : MediaBrowserCompat.ConnectionCallback() { override fun onConnected() { // Get the token for the MediaSession mediaBrowser.sessionToken.also { token -> // Create a MediaControllerCompat. mediaController = MediaControllerCompat(context, token) // Get the current values of things. lastPlaybackState = mediaController?.playbackState lastMetadata = mediaController?.metadata controllerCallback.onPlaybackStateChanged(lastPlaybackState) controllerCallback.onMetadataChanged(lastMetadata) // Register a Callback to stay in sync mediaController?.registerCallback(controllerCallback) } } override fun onConnectionSuspended() { // The Service has crashed. Disable transport controls until it automatically reconnects } override fun onConnectionFailed() { // The Service has refused our connection } } }
0
Kotlin
0
0
a8e48d95500091a5b3a5a4b3877149567d9a53d9
4,523
android
Apache License 2.0
kandy-lets-plot/src/main/kotlin/org/jetbrains/kotlinx/kandy/letsplot/layers/context/aes/WithHeight.kt
Kotlin
502,039,936
false
{"Kotlin": 1556423}
/* * Copyright 2020-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package org.jetbrains.kotlinx.kandy.letsplot.layers.context.aes import org.jetbrains.kotlinx.dataframe.DataColumn import org.jetbrains.kotlinx.dataframe.columns.ColumnReference import org.jetbrains.kotlinx.kandy.dsl.internal.BindingContext import org.jetbrains.kotlinx.kandy.ir.bindings.NonPositionalMapping import org.jetbrains.kotlinx.kandy.ir.bindings.PositionalMapping import org.jetbrains.kotlinx.kandy.letsplot.internal.HEIGHT import kotlin.reflect.KProperty /** * Interface for configuring the `height` aesthetic specifically used for tile-like plot elements. * This interface provides methods for setting the aesthetic directly or through data mappings. * * Implementing this interface allows the aesthetic to be directly set as a [Double], or mapped to a data column. */ public interface WithHeight : BindingContext { /** * Sets the `height` for tile-like plot elements. * * @property height a [Double] value to set as the height. */ public var height: Double? get() = null set(value) { addNonPositionalSetting(HEIGHT, value) } /** * Maps the `height` aesthetic to a data column by [ColumnReference]. * * @param column the data column to map to the color. * @return a [NonPositionalMapping] object representing the mapping. */ public fun <T> height( column: ColumnReference<T>, ): NonPositionalMapping<T, Double> = addNonPositionalMapping<T, Double>(HEIGHT, column.name(), null) /** * Maps the `height` aesthetic to a data column by [KProperty]. * * @param column the data column to map to the color. * @return a [NonPositionalMapping] object representing the mapping. */ public fun <T> height( column: KProperty<T>, ): NonPositionalMapping<T, Double> = addNonPositionalMapping<T, Double>(HEIGHT, column.name, null) /** * Maps the `height` aesthetic to a data column by [String]. * * @param column the data column to map to the color. * @return a [NonPositionalMapping] object representing the mapping. */ public fun height(column: String): NonPositionalMapping<Any?, Double> = addNonPositionalMapping(HEIGHT, column, null) /** * Maps the `height` aesthetic to the iterable of values. * * @param values the iterable of values to be mapped. * @param name optional name for this aesthetic mapping. * @return a [NonPositionalMapping] object representing the mapping. */ public fun <T> height(values: Iterable<T>, name: String? = null): NonPositionalMapping<T, Double> = addNonPositionalMapping(HEIGHT, values.toList(), name, null) /** * Maps the `height` aesthetic to a data column. * * @param values the data column to map to the color. * @return a [NonPositionalMapping] object representing the mapping. */ public fun <T> height(values: DataColumn<T>): PositionalMapping<T> = addPositionalMapping(HEIGHT, values, null) }
123
Kotlin
11
522
2764bce7e9eec4888fdce71b306631cd4e0a208c
3,148
kandy
Apache License 2.0
test-suite-kotlin/src/test/kotlin/io/micronaut/docs/inject/intro/Engine.kt
patrickfav
227,128,310
true
{"Gradle": 47, "Shell": 6, "AsciiDoc": 212, "Java Properties": 3, "Markdown": 11, "Text": 3, "Ignore List": 1, "Batchfile": 1, "YAML": 6, "XML": 15, "Groovy": 980, "Java": 2496, "INI": 12, "JSON": 7, "Kotlin": 121, "HTML": 6, "SVG": 2, "CSS": 81, "JavaScript": 3}
package io.micronaut.docs.config.builder // tag::class[] internal interface Engine { // <1> val cylinders: Int fun start(): String } // end::class[]
0
Java
0
1
f80cbdd9250bf27fe96003c5360aef09c439ff3f
157
micronaut-core
Apache License 2.0
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/SearchLocation.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Bold.SearchLocation: ImageVector get() { if (_searchLocation != null) { return _searchLocation!! } _searchLocation = Builder(name = "SearchLocation", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(24.009f, 21.888f) lineToRelative(-5.939f, -5.939f) curveToRelative(1.226f, -1.66f, 1.952f, -3.71f, 1.952f, -5.927f) curveTo(20.021f, 4.508f, 15.535f, 0.021f, 10.021f, 0.021f) reflectiveCurveTo(0.021f, 4.508f, 0.021f, 10.021f) reflectiveCurveToRelative(4.486f, 10.0f, 10.0f, 10.0f) curveToRelative(2.217f, 0.0f, 4.267f, -0.726f, 5.927f, -1.952f) lineToRelative(5.939f, 5.939f) lineToRelative(2.121f, -2.121f) close() moveTo(10.022f, 17.022f) curveToRelative(-3.859f, 0.0f, -7.0f, -3.141f, -7.0f, -7.0f) reflectiveCurveTo(6.162f, 3.021f, 10.021f, 3.021f) reflectiveCurveToRelative(7.0f, 3.141f, 7.0f, 7.0f) reflectiveCurveToRelative(-3.141f, 7.0f, -7.0f, 7.0f) close() moveTo(10.001f, 5.001f) curveToRelative(-1.024f, 0.0f, -2.047f, 0.391f, -2.829f, 1.172f) curveToRelative(-1.562f, 1.562f, -1.562f, 4.095f, 0.0f, 5.657f) lineToRelative(2.828f, 2.766f) lineToRelative(2.828f, -2.766f) curveToRelative(1.562f, -1.562f, 1.562f, -4.095f, 0.0f, -5.657f) curveToRelative(-0.781f, -0.781f, -1.805f, -1.172f, -2.828f, -1.172f) close() moveTo(10.001f, 10.501f) curveToRelative(-0.828f, 0.0f, -1.5f, -0.672f, -1.5f, -1.5f) reflectiveCurveToRelative(0.672f, -1.5f, 1.5f, -1.5f) reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f) reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f) close() } } .build() return _searchLocation!! } private var _searchLocation: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,015
icons
MIT License
app/src/main/java/com/example/gamebuddy/presentation/main/community/CommunityEvent.kt
GameBuddyDevs
609,491,782
false
null
package com.example.gamebuddy.presentation.main.community sealed class CommunityEvent { object GetPosts: CommunityEvent() data class LikePost(val postId: String): CommunityEvent() object OnRemoveHeadFromQueue : CommunityEvent() }
0
Kotlin
1
3
0a767229f5505e6a68e167aece41c10abb282e1b
247
GameBuddy-Android
MIT License
app/src/main/java/br/com/movieapp/search_movie_feature/data/source/MovieSearchRemoteDataSourceImpl.kt
MoisesPJr
720,060,791
false
{"Kotlin": 84462}
package br.com.movieapp.search_movie_feature.data.source import br.com.movieapp.core.paging.MovieSearchPagingSource import br.com.movieapp.core.remote.MovieService import br.com.movieapp.core.remote.response.SearchResponse import br.com.movieapp.search_movie_feature.domain.source.MovieSearchRemoteDataSource import javax.inject.Inject class MovieSearchRemoteDataSourceImpl @Inject constructor( private val service: MovieService ) : MovieSearchRemoteDataSource { override fun getSearchMoviePagingSource(query: String): MovieSearchPagingSource { return MovieSearchPagingSource(query, remoteDataSource = this) } override suspend fun getSearchMovies(page: Int, query: String): SearchResponse { return service.searchMovie(page, query) } }
0
Kotlin
0
0
63653720cde369fb8bfe6c5f92a25135de68a885
773
MovieApp
MIT License
web/src/main/kotlin/no/nav/su/se/bakover/web/routes/person/PersonRoutes.kt
navikt
227,366,088
false
{"Kotlin": 8922060, "Shell": 3838, "TSQL": 1233, "Dockerfile": 800}
package no.nav.su.se.bakover.web.routes.person import arrow.core.Either import io.ktor.http.HttpStatusCode import io.ktor.server.application.call import io.ktor.server.routing.Route import io.ktor.server.routing.post import no.nav.su.se.bakover.common.objectMapper import no.nav.su.se.bakover.domain.Fnr import no.nav.su.se.bakover.domain.Person import no.nav.su.se.bakover.domain.person.KunneIkkeHentePerson.FantIkkePerson import no.nav.su.se.bakover.domain.person.KunneIkkeHentePerson.IkkeTilgangTilPerson import no.nav.su.se.bakover.domain.person.KunneIkkeHentePerson.Ukjent import no.nav.su.se.bakover.service.person.PersonService import no.nav.su.se.bakover.web.AuditLogEvent import no.nav.su.se.bakover.web.Resultat import no.nav.su.se.bakover.web.audit import no.nav.su.se.bakover.web.errorJson import no.nav.su.se.bakover.web.routes.Feilresponser import no.nav.su.se.bakover.web.routes.person.PersonResponseJson.Companion.toJson import no.nav.su.se.bakover.web.svar import no.nav.su.se.bakover.web.withBody import java.time.Clock import java.time.LocalDate internal const val personPath = "/person" internal fun Route.personRoutes( personService: PersonService, clock: Clock, ) { post("$personPath/søk") { data class Body( val fnr: String, ) call.withBody<Body> { body -> Either.catch { Fnr(body.fnr) }.fold( ifLeft = { call.svar( HttpStatusCode.BadRequest.errorJson( "Inneholder ikke et gyldig fødselsnummer", "ikke_gyldig_fødselsnummer", ), ) }, ifRight = { fnr -> call.svar( personService.hentPerson(fnr).fold( { call.audit(fnr, AuditLogEvent.Action.SEARCH, null) when (it) { FantIkkePerson -> Feilresponser.fantIkkePerson IkkeTilgangTilPerson -> Feilresponser.ikkeTilgangTilPerson Ukjent -> Feilresponser.feilVedOppslagPåPerson } }, { call.audit(fnr, AuditLogEvent.Action.ACCESS, null) Resultat.json(HttpStatusCode.OK, objectMapper.writeValueAsString(it.toJson(clock))) }, ), ) }, ) } } } data class PersonResponseJson( val fnr: String, val aktorId: String, val navn: NavnJson, val telefonnummer: TelefonnummerJson?, val adresse: List<AdresseJson>?, val statsborgerskap: String?, val sivilstand: SivilstandJson?, val kjønn: String?, val fødselsdato: LocalDate?, val alder: Number?, val adressebeskyttelse: String?, val skjermet: Boolean?, val kontaktinfo: KontaktinfoJson?, val vergemål: Boolean?, val fullmakt: Boolean?, val dødsdato: LocalDate?, ) { data class NavnJson( val fornavn: String, val mellomnavn: String?, val etternavn: String, ) data class TelefonnummerJson( val landskode: String, val nummer: String, ) data class AdresseJson( val adresselinje: String?, val postnummer: String?, val poststed: String?, val bruksenhet: String?, val kommunenummer: String?, val kommunenavn: String?, val adressetype: String, val adresseformat: String, ) data class KontaktinfoJson( val epostadresse: String?, val mobiltelefonnummer: String?, val reservert: Boolean, val kanVarsles: Boolean, val språk: String?, ) data class SivilstandJson( val type: String, val relatertVedSivilstand: String?, ) companion object { fun Person.toJson(clock: Clock) = PersonResponseJson( fnr = this.ident.fnr.toString(), aktorId = this.ident.aktørId.toString(), navn = NavnJson( fornavn = this.navn.fornavn, mellomnavn = this.navn.mellomnavn, etternavn = this.navn.etternavn, ), telefonnummer = this.telefonnummer?.let { t -> TelefonnummerJson( landskode = t.landskode, nummer = t.nummer, ) }, adresse = this.adresse?.map { AdresseJson( adresselinje = it.adresselinje, postnummer = it.poststed?.postnummer, poststed = it.poststed?.poststed, bruksenhet = it.bruksenhet, kommunenummer = it.kommune?.kommunenummer, kommunenavn = it.kommune?.kommunenavn, adressetype = it.adressetype, adresseformat = it.adresseformat, ) }, statsborgerskap = this.statsborgerskap, kjønn = this.kjønn, fødselsdato = this.fødselsdato, alder = this.getAlder(LocalDate.now(clock)), adressebeskyttelse = this.adressebeskyttelse, sivilstand = this.sivilstand?.let { sivilstand -> SivilstandJson( type = sivilstand.type.toString(), relatertVedSivilstand = sivilstand.relatertVedSivilstand?.toString(), ) }, skjermet = this.skjermet, kontaktinfo = this.kontaktinfo?.let { KontaktinfoJson( epostadresse = it.epostadresse, mobiltelefonnummer = it.mobiltelefonnummer, reservert = it.reservert, kanVarsles = it.kanVarsles, språk = it.språk, ) }, vergemål = this.vergemål, fullmakt = this.fullmakt, dødsdato = this.dødsdato, ) } }
9
Kotlin
1
1
d7157394e11b5b3c714a420a96211abb0a53ea45
6,213
su-se-bakover
MIT License
ok-marketplace-api-v2-kmp/src/commonTest/kotlin/SerializationRequestTest.kt
otuskotlin
462,372,364
false
null
package ru.otus.otuskotlin.marketplace.api.v1 import ru.otus.otuskotlin.marketplace.api.v1.models.* import kotlin.test.Test import kotlin.test.assertContains import kotlin.test.assertEquals class SerializationRequestTest { val createRequest = AdCreateRequest( ad = AdCreateObject( title = "Title", description = "Description", adType = DealSide.DEMAND, visibility = AdVisibility.PUBLIC ) ) @Test fun serializeTest() { val jsonString = apiV1RequestSerialize(createRequest) println(jsonString) assertContains(jsonString, """"title":"Title"""") assertContains(jsonString, """"requestType":"create"""") } @Test fun deserializeTest() { val jsonString = apiV1RequestSerialize(createRequest) val decoded = apiV1RequestDeserialize<AdCreateRequest>(jsonString) println(decoded) assertEquals("Title", decoded.ad?.title) assertEquals("Description", decoded.ad?.description) assertEquals(DealSide.DEMAND, decoded.ad?.adType) assertEquals(AdVisibility.PUBLIC, decoded.ad?.visibility) } @Test fun deserializeIRequestTest() { val jsonString = apiV1RequestSerialize(createRequest) val decoded = apiV1RequestDeserialize<IRequest>(jsonString) as AdCreateRequest println(decoded) assertEquals("Title", decoded.ad?.title) assertEquals("Description", decoded.ad?.description) assertEquals(DealSide.DEMAND, decoded.ad?.adType) assertEquals(AdVisibility.PUBLIC, decoded.ad?.visibility) } }
0
Kotlin
5
1
f0af66ea368c6d0908dc7dc8cd7a22bf6bb73228
1,624
202202-ok-marketplace
MIT License
JetStreamCompose/jetstream/src/main/java/com/google/jetstream/presentation/screens/home/HomeScreen.kt
android
192,011,831
false
null
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.jetstream.presentation.screens.home import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.unit.dp import androidx.tv.foundation.PivotOffsets import androidx.tv.foundation.lazy.list.TvLazyColumn import androidx.tv.foundation.lazy.list.rememberTvLazyListState import com.google.jetstream.data.entities.Movie import com.google.jetstream.data.util.StringConstants import com.google.jetstream.presentation.LocalMovieRepository import com.google.jetstream.presentation.common.MoviesRow import com.google.jetstream.presentation.screens.dashboard.rememberChildPadding @Composable fun HomeScreen( onMovieClick: (movie: Movie) -> Unit, goToVideoPlayer: () -> Unit, onScroll: (isTopBarVisible: Boolean) -> Unit, isTopBarVisible: Boolean ) { val childPadding = rememberChildPadding() val tvLazyListState = rememberTvLazyListState() val shouldShowTopBar by remember { derivedStateOf { tvLazyListState.firstVisibleItemIndex == 0 && tvLazyListState.firstVisibleItemScrollOffset < 300 } } val movieRepository = LocalMovieRepository.current!! val featuredMovies = remember { movieRepository.getFeaturedMovies() } val trendingMovies = remember { movieRepository.getTrendingMovies() } val top10Movies = remember { movieRepository.getTop10Movies() } val nowPlayingMovies = remember { movieRepository.getNowPlayingMovies() } LaunchedEffect(shouldShowTopBar) { onScroll(shouldShowTopBar) } LaunchedEffect(isTopBarVisible) { if (isTopBarVisible) tvLazyListState.animateScrollToItem(0) } val pivotOffset = remember { PivotOffsets() } val pivotOffsetForImmersiveList = remember { PivotOffsets(0f, 0f) } var immersiveListHasFocus by remember { mutableStateOf(false) } TvLazyColumn( modifier = Modifier.fillMaxSize(), pivotOffsets = if (immersiveListHasFocus) pivotOffsetForImmersiveList else pivotOffset, state = tvLazyListState ) { item { FeaturedMoviesCarousel( movies = featuredMovies, padding = childPadding, goToVideoPlayer = goToVideoPlayer ) } item { MoviesRow( modifier = Modifier.padding(top = 16.dp), movies = trendingMovies, title = StringConstants.Composable.HomeScreenTrendingTitle, onMovieClick = onMovieClick ) } item { Top10MoviesList( modifier = Modifier.onFocusChanged { immersiveListHasFocus = it.hasFocus }, moviesState = top10Movies, onMovieClick = onMovieClick ) } item { MoviesRow( modifier = Modifier.padding(top = 16.dp), movies = nowPlayingMovies, title = StringConstants.Composable.HomeScreenNowPlayingMoviesTitle, onMovieClick = onMovieClick ) } item { Spacer( modifier = Modifier.padding( bottom = LocalConfiguration.current.screenHeightDp.dp.times(0.19f) ) ) } } }
36
null
300
826
60cbe1b98554e111a5339b1a177f79bf27254c27
4,450
tv-samples
Apache License 2.0
designer/src/com/android/tools/idea/uibuilder/property/inspector/ConstraintLayoutFlowInspectorBuilder.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 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 com.android.tools.idea.uibuilder.property.inspector import com.android.AndroidXConstants import com.android.SdkConstants import com.android.tools.adtui.common.AdtSecondaryPanel import com.android.tools.idea.common.model.NlComponent import com.android.tools.idea.uibuilder.model.isOrHasSuperclass import com.android.tools.idea.uibuilder.property.NlPropertyItem import com.android.tools.idea.uibuilder.property.model.HorizontalEditorPanelModel import com.android.tools.idea.uibuilder.property.model.ToggleButtonPropertyEditorModel import com.android.tools.idea.uibuilder.property.ui.HorizontalEditorPanel import com.android.tools.idea.uibuilder.property.ui.ToggleButtonPropertyEditor import com.android.tools.property.panel.api.EditorProvider import com.android.tools.property.panel.api.InspectorLineModel import com.android.tools.property.panel.api.InspectorPanel import com.android.tools.property.panel.api.PropertiesTable import com.android.tools.property.panel.api.PropertyEditorModel import com.intellij.util.ui.JBUI import icons.StudioIcons import java.awt.BorderLayout import javax.swing.Icon import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JSeparator import javax.swing.SwingConstants import javax.swing.border.EmptyBorder /** Provides a custom set of editors for ConstraintLayout's flow in the Property Panel. */ class ConstraintLayoutFlowInspectorBuilder( private val editorProvider: EditorProvider<NlPropertyItem> ) { fun attachToInspector( inspector: InspectorPanel, properties: PropertiesTable<NlPropertyItem>, getTitleLine: () -> InspectorLineModel ) { if (!isApplicable(properties)) return var titleLine = getTitleLine() addEditor( inspector, properties[SdkConstants.ANDROID_URI, SdkConstants.ATTR_ORIENTATION], titleLine ) addEditor( inspector, properties[SdkConstants.AUTO_URI, SdkConstants.ATTR_FLOW_WRAP_MODE], titleLine ) addEditor( inspector, properties[SdkConstants.AUTO_URI, SdkConstants.ATTR_FLOW_MAX_ELEMENTS_WRAP], titleLine ) inspector.addComponent(MySeparator(), titleLine) addSubtitle(inspector, "Horizontal", titleLine) addHorizontalAlignment(inspector, properties, titleLine) addEditor( inspector, properties[SdkConstants.AUTO_URI, SdkConstants.ATTR_FLOW_HORIZONTAL_GAP], titleLine ) addEditor( inspector, properties[SdkConstants.AUTO_URI, SdkConstants.ATTR_FLOW_HORIZONTAL_BIAS], titleLine ) addHorizontalStyle(inspector, properties, titleLine) inspector.addComponent(MySeparator(), titleLine) addSubtitle(inspector, "Vertical", titleLine) addVerticalAlignment(inspector, properties, titleLine) addEditor( inspector, properties[SdkConstants.AUTO_URI, SdkConstants.ATTR_FLOW_VERTICAL_GAP], titleLine ) addEditor( inspector, properties[SdkConstants.AUTO_URI, SdkConstants.ATTR_FLOW_VERTICAL_BIAS], titleLine ) addVerticalStyle(inspector, properties, titleLine) inspector.addComponent(MySeparator(), titleLine) } private fun addSubtitle(inspector: InspectorPanel, s: String, titleLine: InspectorLineModel) { var component = JLabel(s) component.border = EmptyBorder(8, 8, 8, 8) inspector.addComponent(component, titleLine) } private fun addHorizontalAlignment( inspector: InspectorPanel, properties: PropertiesTable<NlPropertyItem>, group: InspectorLineModel ) { val alignment = properties.getOrNull(SdkConstants.AUTO_URI, SdkConstants.ATTR_FLOW_HORIZONTAL_ALIGN) ?: return val model = HorizontalEditorPanelModel(alignment) val panel = HorizontalEditorPanel(model) val line = inspector.addCustomEditor(model, panel, group) panel.add( createIconEditor( line, alignment, "Align Start", StudioIcons.LayoutEditor.Toolbar.LEFT_ALIGNED, SdkConstants.FlowAlignment.START ) ) panel.add( createIconEditor( line, alignment, "Align Start", StudioIcons.LayoutEditor.Toolbar.HORIZONTAL_CENTER_ALIGNED, SdkConstants.FlowAlignment.CENTER ) ) panel.add( createIconEditor( line, alignment, "Align End", StudioIcons.LayoutEditor.Toolbar.RIGHT_ALIGNED, SdkConstants.FlowAlignment.END ) ) } private fun addVerticalAlignment( inspector: InspectorPanel, properties: PropertiesTable<NlPropertyItem>, group: InspectorLineModel ) { val alignment = properties.getOrNull(SdkConstants.AUTO_URI, SdkConstants.ATTR_FLOW_VERTICAL_ALIGN) ?: return val model = HorizontalEditorPanelModel(alignment) val panel = HorizontalEditorPanel(model) val line = inspector.addCustomEditor(model, panel, group) panel.add( createIconEditor( line, alignment, "Align Top", StudioIcons.LayoutEditor.Toolbar.TOP_ALIGNED, SdkConstants.FlowAlignment.TOP ) ) panel.add( createIconEditor( line, alignment, "Align Center", StudioIcons.LayoutEditor.Toolbar.VERTICAL_CENTER_ALIGNED, SdkConstants.FlowAlignment.CENTER ) ) panel.add( createIconEditor( line, alignment, "Align Bottom", StudioIcons.LayoutEditor.Toolbar.BOTTOM_ALIGNED, SdkConstants.FlowAlignment.BOTTOM ) ) panel.add( createIconEditor( line, alignment, "Align Baseline", StudioIcons.LayoutEditor.Toolbar.BASELINE_ALIGNED, SdkConstants.FlowAlignment.BASELINE ) ) } private fun addHorizontalStyle( inspector: InspectorPanel, properties: PropertiesTable<NlPropertyItem>, group: InspectorLineModel ) { val alignment = properties.getOrNull(SdkConstants.AUTO_URI, SdkConstants.ATTR_FLOW_HORIZONTAL_STYLE) ?: return val model = HorizontalEditorPanelModel(alignment) val panel = HorizontalEditorPanel(model) val line = inspector.addCustomEditor(model, panel, group) panel.add( createIconEditor( line, alignment, "Spread", StudioIcons.LayoutEditor.Properties.SPREAD_HORIZONTAL, SdkConstants.FlowStyle.SPREAD ) ) panel.add( createIconEditor( line, alignment, "Spread Inside", StudioIcons.LayoutEditor.Properties.SPREAD_INSIDE_HORIZONTAL, SdkConstants.FlowStyle.SPREAD_INSIDE ) ) panel.add( createIconEditor( line, alignment, "Packed", StudioIcons.LayoutEditor.Properties.PACKED_HORIZONTAL, SdkConstants.FlowStyle.PACKED ) ) } private fun addVerticalStyle( inspector: InspectorPanel, properties: PropertiesTable<NlPropertyItem>, group: InspectorLineModel ) { val alignment = properties.getOrNull(SdkConstants.AUTO_URI, SdkConstants.ATTR_FLOW_VERTICAL_STYLE) ?: return val model = HorizontalEditorPanelModel(alignment) val panel = HorizontalEditorPanel(model) val line = inspector.addCustomEditor(model, panel, group) panel.add( createIconEditor( line, alignment, "Spread", StudioIcons.LayoutEditor.Properties.SPREAD_VERTICAL, SdkConstants.FlowStyle.SPREAD ) ) panel.add( createIconEditor( line, alignment, "Spread Inside", StudioIcons.LayoutEditor.Properties.SPREAD_INSIDE_VERTICAL, SdkConstants.FlowStyle.SPREAD_INSIDE ) ) panel.add( createIconEditor( line, alignment, "Packed", StudioIcons.LayoutEditor.Properties.PACKED_VERTICAL, SdkConstants.FlowStyle.PACKED ) ) } private fun createIconEditor( line: InspectorLineModel, property: NlPropertyItem, description: String, icon: Icon, trueValue: String, falseValue: String = "" ): Pair<PropertyEditorModel, JComponent> { val model = ToggleButtonPropertyEditorModel(description, icon, trueValue, falseValue, property) val editor = ToggleButtonPropertyEditor(model) model.lineModel = line return model to editor } private fun addEditor( inspector: InspectorPanel, property: NlPropertyItem, group: InspectorLineModel ): InspectorLineModel { return inspector.addEditor(editorProvider.createEditor(property), group) } private class MySeparator internal constructor() : AdtSecondaryPanel(BorderLayout()) { override fun updateUI() { super.updateUI() border = JBUI.Borders.empty(4) } init { add(JSeparator(SwingConstants.HORIZONTAL), BorderLayout.CENTER) } } companion object { fun isApplicable(properties: PropertiesTable<NlPropertyItem>): Boolean { var components: List<NlComponent>? = properties.first?.components ?: return false if (components!!.isEmpty()) return false var component: NlComponent? = components?.get(0) return component!!.isOrHasSuperclass(AndroidXConstants.CLASS_CONSTRAINT_LAYOUT_FLOW) } } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
9,788
android
Apache License 2.0
app/src/main/java/org/phcbest/neteasymusic/base/PAGE_STATE.kt
phcbest
471,621,513
false
null
package org.phcbest.neteasymusic.base enum class PAGE_STATE { SUCCESS, FAIL }
0
Kotlin
1
2
d94a834216d24f81ee5e2e35b0c54ef6da8b50af
82
KotlinNetEasyMusic
MIT License
src/main/kotlin/org/jetbrains/advocates/rider/plugins/dotnetwatch/run/DotNetWatchRunConfigurationOptions.kt
maartenba
418,503,336
false
{"Kotlin": 36559}
@file:Suppress("UnstableApiUsage") package org.jetbrains.advocates.rider.plugins.dotnetwatch.run import com.intellij.execution.configurations.RunConfigurationOptions import com.intellij.openapi.project.Project import com.intellij.workspaceModel.ide.WorkspaceModel import com.jetbrains.rider.projectView.workspace.getProjectModelEntities import com.jetbrains.rider.projectView.workspace.isUnloadedProject import java.nio.file.Path class DotNetWatchRunConfigurationOptions : RunConfigurationOptions() { private var projectFilePathOption = string("").provideDelegate(this, "projectFilePath") private var trackProjectExePathOption = property(true).provideDelegate(this, "trackProjectExePath") private var trackProjectWorkingDirectoryOption = property(true).provideDelegate(this, "trackProjectWorkingDirectory") private var projectTfmOption = string("").provideDelegate(this, "projectTfm") private var exePathOption = string("").provideDelegate(this, "exePath") private var programParametersOption = string("").provideDelegate(this, "programParameters") private var workingDirectoryOption = string("").provideDelegate(this, "workingDirectory") private var envsOption = map<String, String>().provideDelegate(this, "envs") private var isPassParentEnvsOption = property(true).provideDelegate(this, "isPassParentEnvs") private var useExternalConsoleOption = property(false).provideDelegate(this, "useExternalConsole") private var verbosityOption = string(DotNetWatchVerbosity.NORMAL.name).provideDelegate(this, "verbosity") private var isSuppressHotReloadOption = property(false).provideDelegate(this, "isSuppressHotReload") private var isRestartOnRudeEditEditorOption = property(false).provideDelegate(this, "isRestartOnRudeEditEditor") private var isUsePollingFileWatcherOption = property(false).provideDelegate(this, "isUsePollingFileWatcher") private var isSuppressBrowserLaunchOption = property(false).provideDelegate(this, "isSuppressBrowserLaunch") private var isSuppressBrowserRefreshOption = property(false).provideDelegate(this, "isSuppressBrowserRefresh") var projectFilePath: String get() = projectFilePathOption.getValue(this) ?: "" set(value) = projectFilePathOption.setValue(this, value) var trackProjectExePath: Boolean get() = trackProjectExePathOption.getValue(this) set(value) = trackProjectExePathOption.setValue(this, value) var trackProjectWorkingDirectory: Boolean get() = trackProjectWorkingDirectoryOption.getValue(this) set(value) = trackProjectWorkingDirectoryOption.setValue(this, value) var projectTfm: String get() = projectTfmOption.getValue(this) ?: "" set(value) = projectTfmOption.setValue(this, value) var exePath: String get() = exePathOption.getValue(this) ?: "" set(value) = exePathOption.setValue(this, value) var programParameters: String get() = programParametersOption.getValue(this) ?: "" set(value) = programParametersOption.setValue(this, value) var workingDirectory: String get() = workingDirectoryOption.getValue(this) ?: "" set(value) = workingDirectoryOption.setValue(this, value) var envs: Map<String, String> get() = envsOption.getValue(this) set(value) = envsOption.setValue(this, value.toMutableMap()) var isPassParentEnvs: Boolean get() = isPassParentEnvsOption.getValue(this) set(value) = isPassParentEnvsOption.setValue(this, value) var useExternalConsole: Boolean get() = useExternalConsoleOption.getValue(this) set(value) = useExternalConsoleOption.setValue(this, value) var verbosity: DotNetWatchVerbosity get() = DotNetWatchVerbosity.valueOf(verbosityOption.getValue(this) ?: DotNetWatchVerbosity.NORMAL.name) set(value) = verbosityOption.setValue(this, value.name) var isSuppressHotReload: Boolean get() = isSuppressHotReloadOption.getValue(this) set(value) = isSuppressHotReloadOption.setValue(this, value) var isRestartOnRudeEditEditor: Boolean get() = isRestartOnRudeEditEditorOption.getValue(this) set(value) = isRestartOnRudeEditEditorOption.setValue(this, value) var isUsePollingFileWatcher: Boolean get() = isUsePollingFileWatcherOption.getValue(this) set(value) = isUsePollingFileWatcherOption.setValue(this, value) var isSuppressBrowserLaunch: Boolean get() = isSuppressBrowserLaunchOption.getValue(this) set(value) = isSuppressBrowserLaunchOption.setValue(this, value) var isSuppressBrowserRefresh: Boolean get() = isSuppressBrowserRefreshOption.getValue(this) set(value) = isSuppressBrowserRefreshOption.setValue(this, value) fun isUnloadedProject(project: Project) = WorkspaceModel.getInstance(project) .getProjectModelEntities(Path.of(projectFilePath), project) .any { it.isUnloadedProject() } }
1
Kotlin
4
27
693c326753a6141bae07dbaf7fe5016727fa1240
4,985
DotNetWatch
MIT License
src/test/kotlin/com/yaroslavzghoba/utils/UserAuthentication.kt
papagei-service
855,958,312
false
{"Kotlin": 137594}
package com.yaroslavzghoba.utils import com.yaroslavzghoba.model.InputCredentials import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* object AuthUtils { suspend fun registerUser( client: HttpClient, inputCredentials: InputCredentials, token: String, ) { client.post("/v1/users/register") { contentType(ContentType.Application.Json) bearerAuth(token) setBody(inputCredentials) } } suspend fun loginUser( client: HttpClient, inputCredentials: InputCredentials, token: String, ): HttpResponse { return client.post("/v1/users/login") { contentType(ContentType.Application.Json) bearerAuth(token) setBody(inputCredentials) } } }
0
Kotlin
0
0
fda4a418997b25be36cca73038bad72d7afd09c0
862
backend
MIT License
libBottomDialog/src/main/java/com/tobery/libbottomdialog/BottomAlertDialog.kt
Tobeyr1
520,495,625
false
null
package com.tobery.libbottomdialog import android.app.Dialog import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.text.TextUtils import android.view.* import android.widget.TextView import androidx.annotation.StyleRes import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentManager class BottomAlertDialog : DialogFragment() { companion object { const val BASE_DIALOG_TAG = "BASE_DIALOG" private var mFragment: FragmentManager? = null private var mNegativeButtonMethod: ((Dialog?, View?) -> Unit)? = null private var mPositiveButtonMethod: ((Dialog?, View?) -> Unit)? = null } private lateinit var tvTitle: TextView private lateinit var tvContent: TextView private lateinit var tvOkButton: TextView private lateinit var tvCancelButton: TextView private lateinit var viewBg: View private var tvCancelColor: Int = 0 private var tvTitleColor: Int = 0 private var tvConfirmColor: Int = 0 private var confirmBg: Int = 0 private var cancelBg: Int = 0 private var viewBgColor: Int = 0 private var mWidth: Int = 0 private var mHeight: Int = 0 private var isOpenMask: Boolean = false private var maskColor: Int = 0 private var dimAmount: Float = 0.5f private var mAnimRes: Int = 0 private var gravityStyle: Int = Gravity.BOTTOM private var mCancelBtnVisibility: Boolean = false private var mTitle: String? = null private var mContent: String? = null private var mTvCancelMsg: String? = null private var mTvOkmMg: String? = null private var mNegativeToDismiss = true private var mCanceledOnTouchOutside = false private var mNegativeButtonMethodAdded = false private var mPositiveButtonMethodAdded = false init { arguments = Bundle() } private val mButtonClickListener = View.OnClickListener { view -> when (view.id) { R.id.tv_bt_ok -> { if (mPositiveButtonMethodAdded) { mPositiveButtonMethod?.invoke(dialog, view) } } R.id.tv_bt_cancel -> { if (mNegativeToDismiss) dismiss() if (mNegativeButtonMethodAdded) { mNegativeButtonMethod?.invoke(dialog, view) } } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.run { mWidth = getInt("mWidth") mHeight = getInt("mHeight") mTitle = getString("mTitle") mContent = getString("mContent") tvTitleColor = getInt("tvTitleColor") tvCancelColor = getInt("tvCancelColor") tvConfirmColor = getInt("tvConfirmColor") confirmBg = getInt("confirmBg") cancelBg = getInt("cancelBg") viewBgColor = getInt("viewBgColor") maskColor = getInt("maskColor") isOpenMask = getBoolean("isOpenMask") dimAmount = getFloat("alpha") mTvOkmMg = getString("mTvOkmMg") mTvCancelMsg = getString("mTvCancelMsg") gravityStyle = getInt("gravityStyle") mCancelBtnVisibility = getBoolean("mCancelBtnVisibility") mCanceledOnTouchOutside = getBoolean("mCanceledOnTouchOutside") mNegativeButtonMethodAdded = getBoolean("mNegativeButtonMethodAdded") mPositiveButtonMethodAdded = getBoolean("mPositiveButtonMethodAdded") } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.ui_common_bottom_alert, container, false) tvTitle = view.findViewById(R.id.tv_title) tvContent = view.findViewById(R.id.tv_content) tvCancelButton = view.findViewById(R.id.tv_bt_cancel) tvOkButton = view.findViewById(R.id.tv_bt_ok) viewBg = view.findViewById(R.id.view_bg) isCancelable = mCanceledOnTouchOutside return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (viewBgColor > 0) viewBg.background = ResourcesCompat.getDrawable(resources, viewBgColor, null) //修改背景 if (mHeight > 0) viewBg.layoutParams.height = mHeight val showTitle = !TextUtils.isEmpty(mTitle) val showContent = !TextUtils.isEmpty(mContent) if (showTitle) { tvTitle.text = mTitle } if (showContent) { tvContent.text = mContent tvTitle.visibility = if (showTitle) View.VISIBLE else View.GONE } tvContent.visibility = if (showContent) View.VISIBLE else View.GONE if (tvCancelColor > 0) tvCancelButton.setTextColor( ResourcesCompat.getColor( resources, tvCancelColor, null ) ) if (tvTitleColor > 0) { tvTitle.setTextColor(ResourcesCompat.getColor(resources, tvTitleColor, null)) tvContent.setTextColor(ResourcesCompat.getColor(resources, tvTitleColor, null)) } if (tvConfirmColor > 0) tvOkButton.setTextColor( ResourcesCompat.getColor( resources, tvConfirmColor, null ) ) if (cancelBg > 0) tvCancelButton.background = ResourcesCompat.getDrawable(resources, cancelBg, null) if (confirmBg > 0) tvOkButton.background = ResourcesCompat.getDrawable(resources, confirmBg, null) if (mTvOkmMg != null) tvOkButton.text = mTvOkmMg if (mTvCancelMsg != null) tvCancelButton.text = mTvCancelMsg if (mCancelBtnVisibility) { tvCancelButton.visibility = View.GONE val lp: ConstraintLayout.LayoutParams = tvOkButton.layoutParams as ConstraintLayout.LayoutParams lp.leftMargin = resources.getDimensionPixelSize(R.dimen.dp_24) lp.rightMargin = resources.getDimensionPixelSize(R.dimen.dp_24) tvOkButton.layoutParams = lp } tvOkButton.setOnClickListener(mButtonClickListener) tvCancelButton.setOnClickListener(mButtonClickListener) } override fun onStart() { super.onStart() dialog?.window?.apply { //set background transparent setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) if (maskColor > 0) setBackgroundDrawableResource(maskColor) //set anim if (mAnimRes > 0) setWindowAnimations(mAnimRes) val params = attributes params.width = if (mWidth > 0) mWidth else WindowManager.LayoutParams.MATCH_PARENT if (mHeight > 0) params.height = mHeight if (isOpenMask) params.height = WindowManager.LayoutParams.MATCH_PARENT //set transparent params.dimAmount = dimAmount params.gravity = gravityStyle attributes = params } } fun setFragmentManager(fragmentManager: FragmentManager) = apply { mFragment = fragmentManager } fun openFullScreenMask(isOpen: Boolean = false, maskColor: Int = 0, alpha: Float) = apply { //是否开启全屏显示遮罩 isOpenMask = isOpen this.maskColor = maskColor dimAmount = alpha arguments?.putInt("maskColor", maskColor) arguments?.putBoolean("isOpenMask", isOpenMask) arguments?.putFloat("alpha", dimAmount) } fun setWindowSize(width: Int, height: Int) = apply { setWidth(width) setHeight(height) } fun setWidth(width: Int) = apply { mWidth = width arguments?.putInt("mWidth", mWidth) } fun setCancelColor(color: Int) = apply { tvCancelColor = color arguments?.putInt("tvCancelColor", tvCancelColor) } fun setTitleColor(color: Int) = apply { tvTitleColor = color arguments?.putInt("tvTitleColor", tvTitleColor) } fun setConfirmBg(drawable: Int) = apply { confirmBg = drawable arguments?.putInt("confirmBg", confirmBg) } fun setCancelBg(drawable: Int) = apply { cancelBg = drawable arguments?.putInt("cancelBg",cancelBg) } fun setConfirmTextColor(color: Int) = apply { tvConfirmColor = color arguments?.putInt("tvConfirmColor", tvConfirmColor) } fun setCancelBtnGone() = apply { mCancelBtnVisibility = true arguments?.putBoolean("mCancelBtnVisibility", true) } fun setHeight(height: Int) = apply { mHeight = height arguments?.putInt("mHeight", mHeight) } fun setBackGroundColor(color: Int) = apply { viewBgColor = color arguments?.putInt("viewBgColor", viewBgColor) } fun setGravityStyle(gravity: Int) = apply { gravityStyle = gravity arguments?.putInt("gravityStyle", gravityStyle) } fun setAnimStyle(@StyleRes animStyle: Int) = apply { mAnimRes = animStyle arguments?.putInt("mAnimRes", mAnimRes) } fun setTitle(title: String) = apply { mTitle = title arguments?.putString("mTitle", mTitle) } fun setContent(content: String) = apply { mContent = content arguments?.putString("mContent", mContent) } fun setNegativeToDismiss(negativeToDismiss: Boolean) = apply { mNegativeToDismiss = negativeToDismiss arguments?.putBoolean("mNegativeToDismiss", mNegativeToDismiss) } fun setCanceledOnTouchOutside(canceledOnTouchOutside: Boolean) = apply { mCanceledOnTouchOutside = canceledOnTouchOutside arguments?.putBoolean("mCanceledOnTouchOutside", mCanceledOnTouchOutside) } fun setNegativeButtonMethod( msg: String?, tvColor: Int? = null, negativeButtonMethod: (Dialog?, View?) -> Unit ) = apply { mTvCancelMsg = msg msg?.let { arguments?.putString("mTvCancelMsg", it) } mNegativeButtonMethod = negativeButtonMethod tvColor?.let { tvCancelColor = it arguments?.putInt("tvCancelColor", tvCancelColor) } arguments?.putBoolean("mNegativeButtonMethodAdded", true) } fun setPositiveButtonMethod( msg: String?, tvColor: Int? = null, positiveButtonMethod: (Dialog?, View?) -> Unit ) = apply { mTvOkmMg = msg mPositiveButtonMethod = positiveButtonMethod msg?.let { arguments?.putString("mTvOkmMg", it) } tvColor?.let { tvConfirmColor = it arguments?.putInt("tvConfirmColor", tvConfirmColor) } arguments?.putBoolean("mPositiveButtonMethodAdded", true) } fun show() { mFragment?.let { val ft = it.beginTransaction() val prev = it.findFragmentByTag(BASE_DIALOG_TAG) if (prev != null) ft.remove(prev) ft.add(this, BASE_DIALOG_TAG) ft.commitAllowingStateLoss() } } }
0
Kotlin
0
0
b78ca811b259f6106813ea98d5a35c308c4661a2
11,425
libBottomDialog
Apache License 2.0
app/src/main/java/com/example/viewmodel/ui/MainActivity.kt
marosc
303,947,987
false
null
package com.example.viewmodel.ui import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.Navigation import androidx.navigation.ui.NavigationUI import com.example.viewmodel.R import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) NavigationUI.setupWithNavController( nav_view, Navigation.findNavController( this, R.id.nav_host_fragment ) ) } override fun onSupportNavigateUp(): Boolean { return Navigation.findNavController(this, R.id.nav_host_fragment).navigateUp() } }
0
Kotlin
2
1
bbe58d8974a442a5af53b4e6b60dc35a02216cf0
801
mobv2020.4
Apache License 2.0
src/test/enhetstester/kotlin/no/nav/familie/ks/sak/kjerne/behandling/steg/vedtak/vedtaksperiode/VedtaksperiodeUtilTest.kt
navikt
533,308,075
false
{"Kotlin": 2805873, "Shell": 1039, "Dockerfile": 141}
package no.nav.familie.ks.sak.kjerne.behandling.steg.vedtak.vedtaksperiode import io.mockk.every import io.mockk.junit5.MockKExtension import io.mockk.mockk import no.nav.familie.ks.sak.common.exception.FunksjonellFeil import no.nav.familie.ks.sak.kjerne.behandling.domene.Behandlingsresultat import no.nav.familie.ks.sak.kjerne.behandling.steg.vedtak.domene.Vedtak import no.nav.familie.ks.sak.kjerne.behandling.steg.vedtak.vedtaksperiode.domene.VedtaksperiodeMedBegrunnelser import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.EnumSource import org.hamcrest.CoreMatchers.`is` as Is @ExtendWith(MockKExtension::class) class VedtaksperiodeUtilTest { @ParameterizedTest @EnumSource( value = Vedtaksperiodetype::class, names = ["OPPHØR", "AVSLAG"], mode = EnumSource.Mode.INCLUDE ) fun `validerVedtaksperiodeMedBegrunnelser - skal kaste FunksjonellFeil dersom det er fritekst uten stanadard begrunnelser i opphør eller avslag`( vedtaksperiodetype: Vedtaksperiodetype ) { val vedtaksperiodeMedBegrunnelser = VedtaksperiodeMedBegrunnelser( vedtak = mockk(), type = vedtaksperiodetype, fritekster = mutableListOf(mockk()) ) val funksjonellFeil = assertThrows<FunksjonellFeil> { validerVedtaksperiodeMedBegrunnelser(vedtaksperiodeMedBegrunnelser) } assertThat( funksjonellFeil.message, Is("Fritekst kan kun brukes i kombinasjon med en eller flere begrunnelser. Legg først til en ny begrunnelse eller fjern friteksten(e).") ) } @Test fun `validerVedtaksperiodeMedBegrunnelser - skal kaste FunksjonellFeil dersom det eksisterer både fritekst og begrunnelser`() { val vedtaksperiodeMedBegrunnelser = VedtaksperiodeMedBegrunnelser( vedtak = mockk<Vedtak>().also { every { it.behandling.resultat } returns Behandlingsresultat.FORTSATT_INNVILGET }, type = Vedtaksperiodetype.FORTSATT_INNVILGET, fritekster = mutableListOf(mockk()), begrunnelser = mutableSetOf(mockk()) ) val funksjonellFeil = assertThrows<FunksjonellFeil> { validerVedtaksperiodeMedBegrunnelser(vedtaksperiodeMedBegrunnelser) } assertThat( funksjonellFeil.message, Is("Det ble sendt med både fritekst og begrunnelse. Vedtaket skal enten ha fritekst eller begrunnelse, men ikke begge deler.") ) } }
4
Kotlin
1
2
f798d3ec05f042b5648ffe04eae645866ca0e24b
2,692
familie-ks-sak
MIT License
app/src/main/java/com/example/android/politicalpreparedness/utils/BindingUtils.kt
tktschool
369,096,861
false
{"Java": 299595, "Kotlin": 64025}
package com.example.android.politicalpreparedness.utils import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.TextView import androidx.databinding.BindingAdapter import com.example.android.politicalpreparedness.network.models.Election import java.text.SimpleDateFormat import java.util.* @BindingAdapter("electionDateText") fun TextView.setElectionDate(item: Election) { item.let { text = item.electionDay.toFormatDateString() } } fun Date.toFormatDateString(): String { val format = SimpleDateFormat("EEE dd MMM yyyy", Locale.US) return format.format(this) } @BindingAdapter("setVisibilityBinding") fun setVisibility(view: View, isVisible: Boolean) { view.visibility = if (isVisible) View.VISIBLE else View.GONE } @BindingAdapter("viewVisibility") fun TextView.bindVisible(status: String?) { visibility = if (status.isNullOrEmpty()) View.GONE else View.VISIBLE } @BindingAdapter("buttonVisibility") fun Button.bindVisible(status: String?) { visibility = if (status.isNullOrEmpty()) View.GONE else View.VISIBLE }
0
Java
0
0
9039035da57c6841b954d60539946b50e46d7a99
1,108
Android-Political-Preparedness
Apache License 2.0
executor/invoker/src/commonMain/kotlin/io/github/charlietap/chasm/executor/invoker/instruction/table/TableSetExecutor.kt
CharlieTap
743,980,037
false
{"Kotlin": 2039170, "WebAssembly": 45714}
package io.github.charlietap.chasm.executor.invoker.instruction.table import com.github.michaelbull.result.Result import io.github.charlietap.chasm.ast.instruction.TableInstruction import io.github.charlietap.chasm.executor.runtime.Stack import io.github.charlietap.chasm.executor.runtime.error.InvocationError import io.github.charlietap.chasm.executor.runtime.store.Store internal typealias ElementDropExecutor = (Store, Stack, TableInstruction.ElemDrop) -> Result<Unit, InvocationError>
5
Kotlin
3
58
dbb72d7459491e15c2cc61ef6dc346e67eb371f5
492
chasm
Apache License 2.0
app/src/main/java/com/example/bookloverfinalapp/app/ui/admin_screens/screen_main_root/FragmentAdminMainRoot.kt
yusuf0405
484,801,816
false
{"Kotlin": 1421124}
package com.example.bookloverfinalapp.app.ui.admin_screens.screen_main_root import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.bookloverfinalapp.R import com.example.bookloverfinalapp.app.utils.extensions.setTabLayoutColor import com.example.bookloverfinalapp.databinding.FragmentAdminMainRootBinding import com.google.android.material.tabs.TabLayoutMediator class FragmentAdminMainRoot : Fragment() { private val binding: FragmentAdminMainRootBinding by lazy(LazyThreadSafetyMode.NONE) { FragmentAdminMainRootBinding.inflate(layoutInflater) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View = binding.root override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setTabLayoutColor(tabLayout = binding.tabLayout) setupTabLayout() } private fun setupTabLayout() { // binding.apply { // viewPager.isSaveEnabled = false // viewPager.adapter = // AdminViewPagerAdapter(fm = requireActivity().supportFragmentManager, // lifecycle = lifecycle) // TabLayoutMediator(tabLayout, viewPager) { tab, pos -> // when (pos) { // 0 -> tab.text = getString(R.string.admin_books) // 1 -> tab.text = getString(R.string.admin_classes) // } // }.attach() // } } }
1
Kotlin
1
3
e1ecdb14efbf7a25643ded1319841712f5e12a3b
1,644
BookLoverFinalApp
Apache License 1.1
ktor-utils/posix/src/io/ktor/util/StackFramesNative.kt
LloydFinch
166,520,021
true
{"Kotlin": 2419371, "Lua": 280, "HTML": 112}
package io.ktor.util @Suppress("UNUSED") internal actual interface CoroutineStackFrame { public actual val callerFrame: CoroutineStackFrame? public actual fun getStackTraceElement(): StackTraceElement? } @Suppress("ACTUAL_WITHOUT_EXPECT") internal actual typealias StackTraceElement = Any
0
Kotlin
0
2
9b9fc6c3b853c929a806c65cf6bf7c104b4c07fc
299
ktor
Apache License 2.0
domain/src/desktopMain/kotlin/ireader/domain/utils/extensions/withUIContext.kt
kazemcodes
540,829,865
true
{"Kotlin": 2179459}
package ireader.domain.utils.extensions import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext actual suspend fun <T> withUIContext(block: suspend CoroutineScope.() -> T){ withContext(Dispatchers.Default, block) }
0
Kotlin
0
6
b6b2414fa002cec2aa0d199871fcfb4c2e190a8f
282
IReader
Apache License 2.0
sdk/src/integrationTest/kotlin/com/kss/zoom/sdk/UsersTest.kt
Kotlin-server-squad
710,163,911
false
{"Kotlin": 92527}
package com.kss.zoom.sdk import com.kss.zoom.sdk.users.IUsers import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class UsersTest : ZoomTestBase() { private lateinit var users: IUsers @BeforeEach fun setUp() { users = users() } @Test fun `should load`() { } }
6
Kotlin
0
1
d9e9d8680448da04d6679f0b63dd31fe918f1806
323
zoomsdk
MIT License
scalechain-proto-codec/src/main/kotlin/io/scalechain/blockchain/proto/codec/primitive/FixedByteBufCodec.kt
ScaleChain
45,332,311
false
null
package io.scalechain.blockchain.proto.codec.primitive import io.netty.buffer.ByteBuf import io.scalechain.blockchain.proto.codec.Codec import io.scalechain.blockchain.proto.codec.CodecInputOutputStream import io.scalechain.io.InputOutputStream class FixedByteBufCodec(val length : Int) : Codec<ByteBuf> { override fun transcode(io : CodecInputOutputStream, obj : ByteBuf? ) : ByteBuf? { return io.fixedBytes(length, obj) } }
11
Kotlin
67
234
e39b789928256b75c18acee847ccc2c2dc2dec5a
443
scalechain
Intel Open Source License
kohii-core/src/main/java/kohii/v1/core/Playback.kt
loicsiret
232,360,662
true
{"Kotlin": 565036, "Java": 28428, "Prolog": 2839}
/* * Copyright (c) 2019 <NAME>, <EMAIL> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kohii.v1.core import android.graphics.Rect import android.view.ViewGroup import androidx.annotation.CallSuper import androidx.annotation.FloatRange import androidx.core.view.ViewCompat import androidx.lifecycle.Lifecycle.State import androidx.lifecycle.Lifecycle.State.STARTED import kohii.v1.BuildConfig import kohii.v1.core.Bucket.Companion.BOTH_AXIS import kohii.v1.core.Bucket.Companion.HORIZONTAL import kohii.v1.core.Bucket.Companion.NONE_AXIS import kohii.v1.core.Bucket.Companion.VERTICAL import kohii.v1.core.Common.STATE_BUFFERING import kohii.v1.core.Common.STATE_ENDED import kohii.v1.core.Common.STATE_IDLE import kohii.v1.core.Common.STATE_READY import kohii.v1.logDebug import kohii.v1.media.PlaybackInfo import kohii.v1.media.VolumeInfo import java.util.ArrayDeque import kotlin.LazyThreadSafetyMode.NONE import kotlin.math.max import kotlin.properties.Delegates abstract class Playback( internal val manager: Manager, internal val bucket: Bucket, val container: ViewGroup, val config: Config = Config() ) : PlayerEventListener, ErrorListener { companion object { @Suppress("unused") const val DELAY_INFINITE = -1L internal val CENTER_X: Comparator<Token> by lazy(NONE) { Comparator<Token> { o1, o2 -> compareValues(o1.containerRect.centerX(), o2.containerRect.centerX()) } } internal val CENTER_Y: Comparator<Token> by lazy(NONE) { Comparator<Token> { o1, o2 -> compareValues(o1.containerRect.centerY(), o2.containerRect.centerY()) } } internal val VERTICAL_COMPARATOR by lazy(NONE) { Comparator<Playback> { o1, o2 -> o1.compareWith(o2, VERTICAL) } } internal val HORIZONTAL_COMPARATOR by lazy(NONE) { Comparator<Playback> { o1, o2 -> o1.compareWith(o2, HORIZONTAL) } } internal val BOTH_AXIS_COMPARATOR by lazy(NONE) { Comparator<Playback> { o1, o2 -> o1.compareWith(o2, BOTH_AXIS) } } private const val STATE_CREATED = -1 private const val STATE_REMOVED = 0 private const val STATE_ADDED = 1 private const val STATE_DETACHED = 2 private const val STATE_ATTACHED = 3 private const val STATE_INACTIVE = 4 private const val STATE_ACTIVE = 5 } class Token( private val threshold: Float = 0.65F, @FloatRange(from = -1.0, to = 1.0) val areaOffset: Float, // -1 ~ < 0 : inactive or detached, 0 ~ 1: active val containerRect: Rect // Relative Rect to its Bucket's root View. ) { fun shouldPrepare(): Boolean { return areaOffset >= 0 } fun shouldPlay(): Boolean { return areaOffset >= threshold } } data class Config( val tag: Any = Master.NO_TAG, val delay: Int = 0, val threshold: Float = 0.65F, val preload: Boolean = false, val repeatMode: Int = Common.REPEAT_MODE_OFF, val controller: Controller? = null, val artworkHintListener: ArtworkHintListener? = null, val callbacks: Set<Callback> = emptySet() ) override fun toString(): String { return "${super.toString()}, [$playable], [${token.areaOffset}, ${token.containerRect}]" } protected open fun updateToken(): Token { "Playback#updateToken $this".logDebug() val containerRect = Rect() if (!lifecycleState.isAtLeast(STARTED)) return Token( config.threshold, -1F, containerRect ) if (!ViewCompat.isAttachedToWindow(container)) { return Token(config.threshold, -1F, containerRect) } val visible = container.getGlobalVisibleRect(containerRect) if (!visible) return Token( config.threshold, -1F, containerRect ) val drawArea = with(Rect()) { container.getDrawingRect(this) container.clipBounds?.let { this.intersect(it) } width() * height() } val offset: Float = if (drawArea > 0) (containerRect.width() * containerRect.height()) / drawArea.toFloat() else 0F return Token(config.threshold, offset, containerRect) } private val callbacks = ArrayDeque<Callback>() private val listeners = ArrayDeque<StateListener>() private var artworkHintListener: ArtworkHintListener? = null internal open fun acquireRenderer(): Any? { val playable = this.playable requireNotNull(playable) val provider: RendererProvider = manager.findRendererProvider(playable) return provider.acquireRenderer(this, playable.media) } internal open fun releaseRenderer( renderer: Any? ) { val playable = this.playable requireNotNull(playable) val provider: RendererProvider = manager.findRendererProvider(playable) return provider.releaseRenderer(this, playable.media, renderer) } internal fun attachRenderer(renderer: Any?): Boolean { "Playback#attachRenderer $renderer $this".logDebug() return onAttachRenderer(renderer) } internal fun detachRenderer(renderer: Any?): Boolean { "Playback#detachRenderer $renderer $this".logDebug() return onDetachRenderer(renderer) } // Return `true` to indicate that the Renderer is safely attached to container and // can be used by the Playable. protected abstract fun onAttachRenderer(renderer: Any?): Boolean // Return `true` to indicate that the Renderer is safely detached from container and // Playable should not use it any further. RendererProvider will then release the Renderer with // proper mechanism (eg: put it back to Pool for reuse). protected abstract fun onDetachRenderer(renderer: Any?): Boolean internal fun onAdded() { "Playback#onAdded $this".logDebug() playbackState = STATE_ADDED callbacks.forEach { it.onAdded(this) } artworkHintListener = config.artworkHintListener bucket.addContainer(this.container) } internal fun onRemoved() { "Playback#onRemoved $this".logDebug() playbackState = STATE_REMOVED bucket.removeContainer(this.container) artworkHintListener = null callbacks.onEach { it.onRemoved(this) } .clear() listeners.clear() } internal fun onAttached() { "Playback#onAttached $this".logDebug() playbackState = STATE_ATTACHED callbacks.forEach { it.onAttached(this) } } internal fun onDetached() { "Playback#onDetached $this".logDebug() playbackState = STATE_DETACHED callbacks.forEach { it.onDetached(this) } } @CallSuper internal open fun onActive() { "Playback#onActive $this".logDebug() playbackState = STATE_ACTIVE callbacks.forEach { it.onActive(this) } artworkHintListener?.onArtworkHint( playable?.isPlaying() == false, playbackInfo.resumePosition, playerState ) } @CallSuper internal open fun onInActive() { "Playback#onInActive $this".logDebug() playbackState = STATE_INACTIVE artworkHintListener?.onArtworkHint(true, playbackInfo.resumePosition, playerState) playable?.considerReleaseRenderer(this) callbacks.forEach { it.onInActive(this) } } @CallSuper internal open fun onPlay() { "Playback#onPlay $this".logDebug() container.keepScreenOn = true artworkHintListener?.onArtworkHint( playerState == STATE_ENDED, playbackInfo.resumePosition, playerState ) } @CallSuper internal open fun onPause() { container.keepScreenOn = false "Playback#onPause $this".logDebug() artworkHintListener?.onArtworkHint(true, playbackInfo.resumePosition, playerState) } // Will be updated everytime 'onRefresh' is called. private var _token: Token = Token(config.threshold, -1F, Rect()) internal val token: Token get() = _token internal fun onRefresh() { "Playback#onRefresh $this".logDebug() _token = updateToken() } private var playbackState: Int = STATE_CREATED internal val isAttached: Boolean get() = playbackState >= STATE_ATTACHED internal val isActive: Boolean get() = playbackState >= STATE_ACTIVE internal var lifecycleState: State = State.INITIALIZED // The smaller, the closer it is to be selected to Play. // Consider to prepare the underline Playable for low enough distance, and release it otherwise. // This value is updated by Group. In active Playback always has Int.MAX_VALUE distance. internal var distanceToPlay: Int by Delegates.observable( Int.MAX_VALUE, onChange = { _, from, to -> if (from == to) return@observable "Playback#distanceToPlay $from --> $to, $this".logDebug() playable?.onDistanceChanged(this, from, to) }) internal var volumeInfoUpdater: VolumeInfo by Delegates.observable( initialValue = bucket.volumeInfo, onChange = { _, from, to -> if (from == to) return@observable "Playback#volumeInfo $from --> $to, $this".logDebug() playable?.onVolumeInfoChanged(this, from, to) } ) init { volumeInfoUpdater = bucket.volumeInfo } internal var playable: Playable? = null internal fun compareWith( other: Playback, orientation: Int ): Int { "Playback#compareWith $this $other, $this".logDebug() val thisToken = this.token val thatToken = other.token val compareVertically by lazy(NONE) { CENTER_Y.compare(thisToken, thatToken) } val compareHorizontally by lazy(NONE) { CENTER_X.compare(thisToken, thatToken) } var result = when (orientation) { VERTICAL -> compareVertically HORIZONTAL -> compareHorizontally BOTH_AXIS -> max(compareVertically, compareHorizontally) NONE_AXIS -> max(compareVertically, compareHorizontally) else -> 0 } if (result == 0) result = compareValues(thisToken.areaOffset, thatToken.areaOffset) return result } // Public APIs val tag = config.tag private val playerState: Int get() = playable?.playerState ?: STATE_IDLE val volumeInfo: VolumeInfo get() = volumeInfoUpdater private val playbackInfo: PlaybackInfo get() = playable?.playbackInfo ?: PlaybackInfo() val containerRect: Rect get() = token.containerRect fun addCallback(callback: Callback) { "Playback#addCallback $callback, $this".logDebug() this.callbacks.push(callback) } fun removeCallback(callback: Callback?) { "Playback#removeCallback $callback, $this".logDebug() this.callbacks.remove(callback) } fun addStateListener(listener: StateListener) { "Playback#addStateListener $listener, $this".logDebug() this.listeners.add(listener) } fun removeStateListener(listener: StateListener?) { "Playback#removeStateListener $listener, $this".logDebug() this.listeners.remove(listener) } fun unbind() { "Playback#unbind, $this".logDebug() container.post { playable?.onUnbind(this) ?: manager.removePlayback(this) } } fun rewind(refresh: Boolean = true) { playable?.onReset() if (refresh) manager.refresh() } // PlayerEventListener override fun onPlayerStateChanged( playWhenReady: Boolean, playbackState: Int ) { "Playback#onPlayerStateChanged $playWhenReady - $playbackState, $this".logDebug() when (playbackState) { STATE_IDLE -> { } STATE_BUFFERING -> { listeners.forEach { it.onBuffering(this@Playback, playWhenReady) } } STATE_READY -> { listeners.forEach { if (playWhenReady) it.onPlaying(this@Playback) else it.onPaused(this@Playback) } } STATE_ENDED -> { listeners.forEach { it.onEnded(this@Playback) } } } artworkHintListener?.onArtworkHint( playerState == STATE_ENDED || playerState == STATE_IDLE, playbackInfo.resumePosition, playerState ) } override fun onVideoSizeChanged( width: Int, height: Int, unappliedRotationDegrees: Int, pixelWidthHeightRatio: Float ) { "Playback#onVideoSizeChanged $width × $height, $this".logDebug() listeners.forEach { it.onVideoSizeChanged(this, width, height, unappliedRotationDegrees, pixelWidthHeightRatio) } } override fun onRenderedFirstFrame() { "Playback#onRenderedFirstFrame, $this".logDebug() listeners.forEach { it.onRendered(this) } } // ErrorListener override fun onError(error: Exception) { "Playback#onError $error, $this".logDebug() listeners.forEach { it.onError(this, error) } if (BuildConfig.DEBUG) error.printStackTrace() } interface StateListener { /** Called when a Video is rendered on the Surface for the first time */ @JvmDefault fun onRendered(playback: Playback) { } /** * Called when buffering status of the playback is changed. * * @param playWhenReady true if the Video will start playing once buffered enough, false otherwise. */ @JvmDefault fun onBuffering( playback: Playback, playWhenReady: Boolean ) { } // ExoPlayer state: 2 /** Called when the Video starts playing */ @JvmDefault fun onPlaying(playback: Playback) { } // ExoPlayer state: 3, play flag: true /** Called when the Video is paused */ @JvmDefault fun onPaused(playback: Playback) { } // ExoPlayer state: 3, play flag: false /** Called when the Video finishes its playback */ @JvmDefault fun onEnded(playback: Playback) { } // ExoPlayer state: 4 @JvmDefault fun onVideoSizeChanged( playback: Playback, width: Int, height: Int, unAppliedRotationDegrees: Int, pixelWidthHeightRatio: Float ) { } @JvmDefault fun onError( playback: Playback, exception: Exception ) { } } interface Callback { @JvmDefault fun onActive(playback: Playback) { } @JvmDefault fun onInActive(playback: Playback) { } @JvmDefault fun onAdded(playback: Playback) { } @JvmDefault fun onRemoved(playback: Playback) { } @JvmDefault fun onAttached(playback: Playback) { } @JvmDefault fun onDetached(playback: Playback) { } } interface Controller { // false = full manual. // true = half manual. // When true: // - If user starts a Playback, it will not be paused until Playback is not visible enough // (controlled by Playback.Config), or user starts other Playback (priority overridden). // - If user pauses a Playback, it will not be played until user resumes it. // - If user scrolls a Playback so that a it is not visible enough, system will pause the Playback. // - If user scrolls a paused Playback so that it is visible enough, system will: play it if it was previously played by User, // or pause it if it was paused by User before (= do nothing). @JvmDefault fun kohiiCanPause(): Boolean = true // - Allow System to start a Playback. // When true: // - Kohii can start a Playback automatically. But once user pause it manually, Only user can resume it, // Kohii should never start/resume the Playback automatically. @JvmDefault fun kohiiCanStart(): Boolean = false } interface ArtworkHintListener { fun onArtworkHint( shouldShow: Boolean, position: Long, state: Int ) } }
0
null
0
0
96bfe46afb739302403fdbf4922d47ba12481e07
15,689
kohii
Apache License 2.0
src/main/java/com/tang/intellij/lua/editor/completion/LuaStringArgHistoryProvider.kt
Benjamin-Dobell
231,814,734
false
null
/* * Copyright (c) 2017. tangzx(<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.editor.completion import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.patterns.PlatformPatterns import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.Processor import com.tang.intellij.lua.lang.LuaIcons import com.tang.intellij.lua.psi.* import com.tang.intellij.lua.stubs.index.LuaStringArgIndex class LuaStringArgHistoryProvider : LuaCompletionProvider() { companion object { val STRING_ARG = PlatformPatterns.psiElement(LuaTypes.STRING) .withParent( PlatformPatterns.psiElement(LuaTypes.LITERAL_EXPR).withParent(LuaArgs::class.java) ) } override fun addCompletions(session: CompletionSession) { val argExpr = session.parameters.position.parent as? LuaExpr ?: return val callExpr = PsiTreeUtil.getParentOfType(session.parameters.position, LuaCallExpr::class.java) ?: return val fnName = callExpr.expr.name ?: return var index = callExpr.argList.indexOf(argExpr) index = if (callExpr.isMethodColonCall) index + 1 else index LuaStringArgIndex.processValues( fnName, GlobalSearchScope.projectScope(callExpr.project), Processor { arg -> if (arg.argIndex == index) { session.resultSet.addElement(LookupElementBuilder.create(arg.argString) .withIcon(LuaIcons.STRING_ARG_HISTORY) .withTypeText("History", true)) } true }) } }
61
Kotlin
9
83
68b0a63d3ddd5bc7be9ed304534b601fedcc8319
2,283
IntelliJ-Luanalysis
Apache License 2.0
src/main/kotlin/me/chill/embed/types/InputEventEmbeds.kt
woojiahao
145,920,296
false
null
package me.chill.embed.types import me.chill.framework.Command import me.chill.json.help.findCommand import me.chill.json.help.syntax import me.chill.settings.red import me.chill.settings.shock import me.chill.utility.embed fun invalidArgumentsEmbed(serverPrefix: String, command: Command, errMsg: String) = embed { title = "Invalid Arguments" description = "Invalid arguments passed to the command: **${command.name}**" color = red thumbnail = shock field { title = "Error" description = errMsg inline = false } field { title = "Syntax" description = command.syntax inline = false } field { title = "Learn more" description = "Use the `${serverPrefix}help ${command.name}` to learn more about the command" inline = false } } fun insufficientArgumentsEmbed(serverPrefix: String, commandName: String, expected: Array<Int>) = embed { title = "Insufficient Arguments" color = red thumbnail = shock description = "Command: **$commandName** requires **${expected.joinToString(" or ")}** arguments" field { title = "Syntax" description = "$serverPrefix${findCommand(commandName).syntax}" inline = false } field { title = "Example" description = "$serverPrefix${findCommand(commandName).example}" inline = false } }
10
null
12
19
f55e6dc4897096b40c77580b5a4f3417ca563b34
1,386
Taiga
MIT License
library/src/main/java/io/github/mayconcardoso/boilerplate/generator/templates/presentation/manifest/AndroidManifestTemplate.kt
MayconCardoso
224,556,754
false
null
package io.github.mayconcardoso.boilerplate.generator.templates.presentation.manifest import io.github.mayconcardoso.boilerplate.generator.generators.feature.context.FeatureContext import io.github.mayconcardoso.boilerplate.generator.core.generator.blankLine import io.github.mayconcardoso.boilerplate.generator.core.generator.printDoubleTabulate import io.github.mayconcardoso.boilerplate.generator.core.generator.printTabulate import io.github.mayconcardoso.boilerplate.generator.core.generator.writeFile import io.github.mayconcardoso.boilerplate.generator.core.path.ModuleFilePath import io.github.mayconcardoso.boilerplate.generator.core.settings.baseProjectPath import io.github.mayconcardoso.boilerplate.generator.core.settings.featureSegment import io.github.mayconcardoso.boilerplate.generator.templates.Template /** * @author <NAME> on 2019-12-02. */ open class AndroidManifestTemplate(private val moduleFilePath: ModuleFilePath) : Template() { override fun getPath(): String { return "${baseProjectPath}features/feature-${featureSegment()}/${moduleFilePath.type.getMainFolder()}AndroidManifest.xml" } override fun generate() = writeFile(this) { output -> val completedFeaturePackage = moduleFilePath.packageValue.value if (FeatureContext.featureGenerator.settings.presentationViewModel.hasActivity) { output.println("<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"") output.printTabulate("package=\"$completedFeaturePackage\">") output.blankLine() output.printTabulate("<application>") output.printDoubleTabulate("<activity android:name=\".${FeatureContext.featureGenerator.presentationActivity.className}\" />") output.printTabulate("</application>") output.blankLine() output.println("</manifest>") } else { output.println("<manifest package=\"$completedFeaturePackage\"/>") } } }
1
Kotlin
2
19
9c2b2ad6b34892d1c0b349ccd63a69fe935f57dd
1,907
ArchitectureBoilerplateGenerator
Apache License 2.0
library/springboot/springboot/src/test/kotlin/de/lise/fluxflow/springboot/activation/parameter/ValueTestBeanConfiguration.kt
lisegmbh
740,936,659
false
{"Kotlin": 732955}
package de.lise.fluxflow.springboot.activation.parameter import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import java.time.Clock import java.time.Instant import java.time.LocalDate import java.time.ZoneId @Configuration open class ValueTestBeanConfiguration { companion object { val TestInstant: Instant = LocalDate.of(2023, 10, 25).atStartOfDay(ZoneId.systemDefault()).toInstant() } @Bean open fun valueTestClock(): Clock { return mock<Clock> { on { instant() } doReturn TestInstant } } }
20
Kotlin
0
7
03a99c536434660fc2cde3df9e220991ff487599
677
fluxflow
Apache License 2.0
app/src/main/java/com/example/friendupp/MainActivity.kt
adampalkowski
650,671,766
false
null
package com.example.friendupp import android.content.ContentValues import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.os.Looper import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.compose.animation.* import androidx.compose.animation.core.* import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.graphics.* import androidx.compose.ui.platform.* import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.hilt.navigation.compose.hiltViewModel import com.example.friendupp.Categories.Category import com.example.friendupp.Home.HomeViewModel import com.example.friendupp.ui.theme.FriendUppTheme import com.example.friendupp.Navigation.NavigationComponent import com.example.friendupp.di.ActivityViewModel import com.example.friendupp.di.AuthViewModel import com.example.friendupp.di.ChatViewModel import com.example.friendupp.di.UserViewModel import com.example.friendupp.model.Response import com.example.friendupp.model.User import com.example.friendupp.model.UserData import com.google.android.gms.location.* import com.google.android.gms.maps.model.LatLng import com.google.firebase.dynamiclinks.PendingDynamicLinkData import com.google.firebase.dynamiclinks.ktx.dynamicLinks import com.google.firebase.ktx.Firebase import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.HiltAndroidApp import kotlinx.coroutines.flow.MutableStateFlow import java.io.File import java.util.concurrent.ExecutorService import java.util.concurrent.Executors @AndroidEntryPoint class MainActivity : ComponentActivity() { private lateinit var outputDirectory: File private lateinit var cameraExecutor: ExecutorService private var shouldShowCamera: MutableState<Boolean> = mutableStateOf(false) private val userViewModel by viewModels<UserViewModel>() private val chatViewModel by viewModels<ChatViewModel>() private val authViewModel by viewModels<AuthViewModel>() private val homeViewModel by viewModels<HomeViewModel>() private val activityViewModel by viewModels<ActivityViewModel>() private lateinit var photoUri: Uri private var shouldShowPhoto: MutableState<Boolean> = mutableStateOf(false) private var fusedLocationClient: FusedLocationProviderClient? = null private val _granted_permission = MutableStateFlow<Boolean>(false) private var locationCallback: LocationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { val locationList = locationResult.locations if (locationList.isNotEmpty()) { //The last location in the list is the newest Log.d("Mapfragment","location callback") val location = locationList.last() activityViewModel.setLocation(LatLng(location.latitude, location.longitude)) } } } override fun onPause() { super.onPause() stopLocationUpdates() } private fun stopLocationUpdates() { fusedLocationClient?.removeLocationUpdates(locationCallback) } private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted -> if (isGranted) { shouldShowCamera.value = true } else { } } override fun onRestart() { super.onRestart() } @OptIn(ExperimentalAnimationApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) UserData.user= User() if(authViewModel.isUserAuthenticated) { Log.d("MAINACTIVItyDebug","auth") userViewModel.currentUserState.value.let {response-> when(response){ is Response.Success->{ UserData.user=response.data Log.d("MAINACTIVItyDebug",response.data.toString()) } else->{} } } } requestCameraPermission() fusedLocationClient = LocationServices.getFusedLocationProviderClient(this.applicationContext!!) if (ActivityCompat.checkSelfPermission( this.applicationContext!!, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this.applicationContext!!, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { fusedLocationClient!!.requestLocationUpdates( LocationRequest(), locationCallback, Looper.getMainLooper() ) } val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { // Permission is granted. Continue the action or workflow in your // app.\ } else { // Explain to the user that the feature is unavailable because the // feature requires a permission that the user has denied. At the // same time, respect the user's decision. Don't link to system // settings in an effort to convince the user to change their // decision. } } when { ContextCompat.checkSelfPermission( this.applicationContext!!, android.Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED -> { _granted_permission.value=true } shouldShowRequestPermissionRationale(android.Manifest.permission.ACCESS_FINE_LOCATION) -> { // In an educational UI, explain to the user why your app requires this // permission for a specific feature to behave as expected, and what // features are disabled if it's declined. In this UI, include a // "cancel" or "no thanks" button that lets the user continue // using your app without granting the permission. } else -> { // You can directly ask for the permission. // The registered ActivityResultCallback gets the result of this request. requestPermissionLauncher.launch( android.Manifest.permission.ACCESS_FINE_LOCATION ) } } outputDirectory = getOutputDirectory() cameraExecutor = Executors.newSingleThreadExecutor() var deepLinkHasBeenSet = false // Flag variable to track if deep link has been set Firebase.dynamicLinks .getDynamicLink(intent) .addOnSuccessListener(this) { pendingDynamicLinkData: PendingDynamicLinkData? -> // Get deep link from result (may be null if no link is found) val deepLink: Uri? = pendingDynamicLinkData?.link if (deepLink != null && !deepLinkHasBeenSet) { homeViewModel.setDeepLink(deepLink) deepLinkHasBeenSet = true // Set the flag to indicate that deep link has been set } } .addOnFailureListener(this) { e -> Log.w(ContentValues.TAG, "getDynamicLink:onFailure", e) } setContent { FriendUppTheme { NavigationComponent(outputDirectory =outputDirectory, executor = cameraExecutor, authViewModel=authViewModel, chatViewModel = chatViewModel, userViewModel = userViewModel,homeViewModel=homeViewModel, activityViewModel = activityViewModel) } } } private fun requestCameraPermission() { when { ContextCompat.checkSelfPermission( this, android.Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED -> { shouldShowCamera.value = true } ActivityCompat.shouldShowRequestPermissionRationale( this, android.Manifest.permission.CAMERA ) -> {} else -> requestPermissionLauncher.launch( android.Manifest.permission.CAMERA ) } } private fun handleImageCapture(uri: Uri) { shouldShowCamera.value = false photoUri = uri shouldShowPhoto.value = true } private fun getOutputDirectory(): File { val mediaDir = externalMediaDirs.firstOrNull()?.let { File(it, resources.getString(R.string.app_name)).apply { mkdirs() } } return if (mediaDir != null && mediaDir.exists()) mediaDir else filesDir } override fun onDestroy() { super.onDestroy() cameraExecutor.shutdown() } }
0
Kotlin
0
0
21a401dd1845a4a6ba83508ab13311a368c75f22
9,401
FriendUpp
MIT License
src/main/kotlin/io/github/guttenbase/mapping/ColumnTypeResolver.kt
guttenbase
644,774,036
false
null
package io.github.guttenbase.mapping import io.github.guttenbase.meta.ColumnMetaData import io.github.guttenbase.meta.ColumnType /** * Map column types to Java types. Every data base has its own special types which have to be mapped to standard types somehow. * * &copy; 2012-2034 akquinet tech@spree * * * @author <NAME> */ fun interface ColumnTypeResolver { /** * Tries to map column to a known type. */ fun getColumnType(columnMetaData: ColumnMetaData): ColumnType }
0
null
0
1
48219dbf4e970248a5467f5b52988fea34c6b4e4
489
guttenbase
Apache License 2.0
feature/search/src/main/java/st/slex/csplashscreen/feature/search/ui/SearchViewModel.kt
stslex
413,161,718
false
null
package st.slex.csplashscreen.feature.search.ui import androidx.lifecycle.viewModelScope import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import st.slex.csplashscreen.core.navigation.navigator.Navigator import st.slex.csplashscreen.core.navigation.AppArguments import st.slex.csplashscreen.core.navigation.NavigationScreen import st.slex.csplashscreen.core.network.model.ui.ImageModel import st.slex.csplashscreen.core.photos.ui.model.PhotoModel import st.slex.csplashscreen.core.photos.ui.model.toPresentation import st.slex.csplashscreen.core.ui.base.BaseViewModel import st.slex.csplashscreen.core.ui.paging.PagingSource import st.slex.csplashscreen.feature.search.domain.interactor.SearchPhotosInteractor import st.slex.csplashscreen.feature.search.ui.model.SearchItem import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch class SearchViewModel( private val interactor: SearchPhotosInteractor, private val navigator: Navigator, args: AppArguments.SearchPhotosScreen, ) : BaseViewModel() { private val _querySearch = MutableStateFlow(args.checkedQuery) val querySearch: StateFlow<String> get() = _querySearch.asStateFlow() val searchHistory: StateFlow<PagingData<SearchItem>> get() = interactor.searchHistory .primaryPagingFlow val photosSearch: StateFlow<PagingData<PhotoModel>> get() = querySearch .map(::newPagerPhotosSearch) .mapState { it.toPresentation() } private fun newPagerPhotosSearch( query: String ): Pager<Int, ImageModel> = Pager(config) { PagingSource { page, pageSize -> if (query.isBlank()) { emptyList() } else { interactor.getPhotos(query, page, pageSize) } } } fun setQueryPhotosSearch(query: String) { _querySearch.tryEmit(query) } fun onProfileClick(username: String) { navigator.navigate(NavigationScreen.UserScreen(username)) } fun onImageClick(imageId: String) { navigator.navigate(NavigationScreen.ImageDetailScreen(imageId)) } fun clearHistory() { viewModelScope.launch { interactor.clearHistory() } } companion object { private val config = PagingConfig( pageSize = 3, enablePlaceholders = false ) } }
2
Kotlin
0
3
60a9a26b597d8d8a3a7749b1506bd7230f04cb06
2,564
CSplashScreen
Apache License 2.0
app/src/main/java/com/md/demo/MyApplication.kt
mohitdholakia
351,308,121
false
null
package com.md.demo import android.app.Application import com.md.demo.injection.module.localDataSourceModule import com.md.demo.injection.module.remoteDatasourceModule import com.md.demo.injection.module.repositoryModule import com.md.demo.injection.module.viewModelModule import org.koin.android.ext.android.startKoin import timber.log.Timber import timber.log.Timber.DebugTree class MyApplication : Application() { override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) { Timber.plant(DebugTree()) } startKoin(this, listOf( remoteDatasourceModule, localDataSourceModule, repositoryModule, viewModelModule)) } }
0
Kotlin
0
0
a0dd141a353c49e2dae785c2ccd941155d52f1d1
745
MVVM-Kotlin
Apache License 2.0
katarina-statistics/src/main/kotlin/com/hubtwork/katarina/statistics/matcherapi/service/SoloRankService.kt
adsad100
339,934,054
false
null
package com.hubtwork.katarina.statistics.matcherapi.service import com.hubtwork.katarina.statistics.matcherapi.domain.SoloRank import com.hubtwork.katarina.statistics.matcherapi.repository.SoloRankRepository import org.hibernate.mapping.Map import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service @Service class SoloRankService(val repository: SoloRankRepository) { fun create(match: SoloRank) = repository.save(match) fun getMatchByMatchId(matchId: Long): SoloRank? = repository.findByIdOrNull(matchId) fun getFirstMatchForTest(): SoloRank? = repository.getFirstMatch() fun getAllCount(): Int = repository.findAll().size fun update() { TODO("Not yet implemented") } fun delete() { TODO("Not yet implemented") } }
0
Kotlin
0
0
0db5e7d5c1b681a562392ded6182bffc72b91f7b
850
Katarina
MIT License
screen/hidden-notes/src/main/kotlin/ru/maksonic/beresta/screen/hidden_notes/core/HiddenNotesSandbox.kt
maksonic
580,058,579
false
{"Kotlin": 1587340, "Assembly": 374}
package ru.maksonic.beresta.screen.hidden_notes.core import ru.maksonic.beresta.feature.notes_list.ui.api.NoteUi import ru.maksonic.beresta.feature.ui.edit_note.api.EditNoteFabState import ru.maksonic.beresta.feature.ui.edit_note.api.isExpanded import ru.maksonic.beresta.feature.ui.search_bar.api.SearchBarState import ru.maksonic.beresta.platform.elm.core.ElmBaseModel.Companion.loadedFailure import ru.maksonic.beresta.platform.elm.core.ElmBaseModel.Companion.loadedSuccess import ru.maksonic.beresta.platform.elm.core.ElmUpdate import ru.maksonic.beresta.platform.elm.core.Sandbox import ru.maksonic.beresta.screen.hidden_notes.core.programs.HiddenNotesDataProgram import ru.maksonic.beresta.screen.hidden_notes.core.programs.HiddenNotesScreenCaptureProgram import ru.maksonic.beresta.screen.hidden_notes.core.programs.HiddenNotesSortProgram /** * @Author maksonic on 21.07.2023 */ private typealias Update = ElmUpdate<Model, Set<Cmd>, Set<Eff>> class HiddenNotesSandbox( hiddenNotesDataProgram: HiddenNotesDataProgram, hiddenNotesSortProgram: HiddenNotesSortProgram, hiddenNotesScreenCaptureProgram: HiddenNotesScreenCaptureProgram, ) : Sandbox<Model, Msg, Cmd, Eff>( initialModel = Model.Initial, initialCmd = setOf(Cmd.FetchNotesData, Cmd.FetchNotesSortState), subscriptions = listOf( hiddenNotesDataProgram, hiddenNotesSortProgram, hiddenNotesScreenCaptureProgram ) ) { companion object { private const val MINIMAL_FOR_LOADING_ITEMS_COUNT = 2000 } override fun update(msg: Msg, model: Model): Update = when (msg) { is Msg.Ui.OnTopBarBackPressed -> onTopBarBackPressed(model) // Notes is Msg.Inner.FetchedNotesSuccess -> fetchedNotesSuccess(model, msg) is Msg.Inner.FetchedNotesFail -> fetchedNotesFail(model, msg) is Msg.Inner.FetchedNotesSort -> fetchedNotesSort(model, msg) is Msg.Ui.OnNoteClicked -> onNoteClicked(model, msg) is Msg.Ui.OnNoteLongClicked -> onNoteLongClicked(model, msg) is Msg.Ui.CancelNotesSelection -> onCancelSelectionClicked(model) // Idle bottom bar actions is Msg.Ui.OnTopBarGridViewClicked -> onTopBarGridViewClicked(model, msg) is Msg.Ui.OnTopBarSortNotesClicked -> onTopBarSortNotesClicked(model) // Selected bottom bar actions is Msg.Ui.OnBottomBarUnhideSelectedNotesClicked -> onBottomBarUnhideSelectedClicked(model) is Msg.Ui.OnBottomBarPinSelectedNotesClicked -> onBottomBarPinSelectedClicked(model) is Msg.Ui.OnBottomBarRemoveSelectedNotesClicked -> onBottomBarRemoveSelectedClicked(model) // Modal sheet is Msg.Ui.OnHideModalBottomSheet -> onHideModalBottomSheet(model) is Msg.Inner.HiddenModalBottomSheet -> hiddenModalBottomSheet(model) // Search bar is Msg.Ui.OnCollapseSearchBar -> onCollapseSearchBar(model) is Msg.Ui.OnExpandSearchBar -> onExpandSearchBar(model) is Msg.Ui.OnCounterBarSelectAllClicked -> onCounterBarSelectAllClicked(model) is Msg.Ui.OnCounterBarShareClicked -> onCounterBarShareClicked(model) // Snack bar is Msg.Ui.OnSnackUndoRemoveNotesClicked -> onSnackBarUndoRemoveClicked(model) // Other is Msg.Inner.HiddenLoadingPlaceholder -> hiddenLoadingPlaceholder(model) is Msg.Inner.UpdatedEditNoteFabState -> updatedEditNoteFabState(model, msg) is Msg.Inner.UpdateStonewallVisibility -> updateStonewallVisibility(model, msg) } private fun onTopBarBackPressed(model: Model): Update = ElmUpdate( model, effects = setOf(Eff.NavigateBack), commands = setOf(Cmd.UpdateScreenCapturePermission(false)) ) private fun fetchedNotesSuccess(model: Model, msg: Msg.Inner.FetchedNotesSuccess): Update = ElmUpdate( model.copy( notes = model.notes.copy( state = model.notes.state.loadedSuccess, collection = msg.notes ), searchBarState = model.searchBarState.copy(searchList = msg.notes) ) ) private fun fetchedNotesFail(model: Model, msg: Msg.Inner.FetchedNotesFail): Update = ElmUpdate( model.copy( notes = model.notes.copy( state = model.notes.state.loadedFailure(msg.failInfo), collection = NoteUi.Collection.Empty ), searchBarState = model.searchBarState.copy(searchList = NoteUi.Collection.Empty) ) ) private fun fetchedNotesSort(model: Model, msg: Msg.Inner.FetchedNotesSort): Update = ElmUpdate(model.copy(sortState = msg.sort)) private fun onNoteClicked(model: Model, msg: Msg.Ui.OnNoteClicked): Update = if (model.notes.isSelection) baseOnNoteAction(model, msg.id) else ElmUpdate( model.copy( editNoteFabState = model.editNoteFabState.copy(state = EditNoteFabState.COLLAPSED) ), effects = setOf(Eff.NavigateToEditNote(msg.id)) ) private fun onNoteLongClicked(model: Model, msg: Msg.Ui.OnNoteLongClicked): Update = baseOnNoteAction(model, msg.id) private fun baseOnNoteAction(model: Model, noteId: Long): Update { val updatedNotes = model.notes.collection.copy(model.notes.collection.data.map { note -> val isSelected = if (note.id == noteId) !note.isSelected else note.isSelected note.copy(isSelected = isSelected) }) val selectedList = updatedNotes.data.filter { it.isSelected } val isVisibleUnpinButton = selectedList.isNotEmpty().run { if (this) !selectedList.map { it.style.isPinned }.contains(false) else false } return ElmUpdate( model.copy( notes = model.notes.copy( collection = updatedNotes, isSelection = true, isVisibleUnpinBottomBarIcon = isVisibleUnpinButton ), searchBarState = model.searchBarState.copy( barState = SearchBarState.Selected, counterValue = selectedList.count() ), editNoteFabState = model.editNoteFabState.copy( isVisible = false, state = EditNoteFabState.COLLAPSED ) ) ) } private fun onCancelSelectionClicked(model: Model): Update { val unselectedAll = model.notes.collection.copy( model.notes.collection.data.map { it.copy(isSelected = false) } ) return ElmUpdate( model.copy( notes = model.notes.copy(collection = unselectedAll, isSelection = false), searchBarState = model.searchBarState.copy(barState = SearchBarState.Collapsed), editNoteFabState = model.editNoteFabState.copy(isVisible = true), ) ) } private fun onTopBarGridViewClicked( model: Model, msg: Msg.Ui.OnTopBarGridViewClicked ): Update = ElmUpdate( model, commands = setOf(Cmd.UpdateNotesGrid(msg.count)), ) private fun onTopBarSortNotesClicked(model: Model): Update = ElmUpdate( model.copy( modalSheet = model.modalSheet.copy( isVisible = true, content = ModalSheetContent.SORT_HIDDEN_NOTES ) ), commands = setOf(Cmd.UpdateScreenCapturePermission(false)) ) private fun onBottomBarUnhideSelectedClicked(model: Model): Update { val unhidden = model.notes.collection.data.filter { it.isSelected } val isShowLoading = unhidden.count() >= MINIMAL_FOR_LOADING_ITEMS_COUNT return ElmUpdate( model = model.copy( notes = model.notes.copy( state = model.notes.state.copy(isLoading = isShowLoading), removedList = emptyList(), isSelection = false, ), searchBarState = model.searchBarState.copy(barState = SearchBarState.Collapsed), editNoteFabState = model.editNoteFabState.copy(isVisible = true), ), commands = setOf(Cmd.UnhideSelectedNotes(unhidden)), ) } private fun onBottomBarPinSelectedClicked(model: Model): Update { val unselectedAll = model.notes.collection.copy( model.notes.collection.data.map { it.copy(isSelected = false) } ) val selectedList = model.notes.collection.data.filter { it.isSelected } return ElmUpdate( model.copy(notes = model.notes.copy(collection = unselectedAll)), commands = setOf(Cmd.UpdatePinnedNotes(selectedList)) ) } private fun onBottomBarRemoveSelectedClicked(model: Model): Update { val unselectedAll = model.notes.collection.copy( model.notes.collection.data.map { it.copy(isSelected = false) } ) val selectedList = model.notes.collection.data.filter { it.isSelected } return ElmUpdate( model.copy( notes = model.notes.copy( state = model.notes.state.copy( isLoading = selectedList.count() >= MINIMAL_FOR_LOADING_ITEMS_COUNT ), collection = unselectedAll, removedList = selectedList, isSelection = false, ), searchBarState = model.searchBarState.copy(barState = SearchBarState.Collapsed), editNoteFabState = model.editNoteFabState.copy(isVisible = true) ), commands = setOf(Cmd.RemoveSelectedNotes(selectedList.toList())), effects = setOf( Eff.ShowSnackBar( SnackBarKey.REMOVED_NOTES, message = "${selectedList.count()}" ) ) ) } private fun onHideModalBottomSheet(model: Model): Update = ElmUpdate(model, effects = setOf(Eff.HideModalSheet)) private fun hiddenModalBottomSheet(model: Model): Update = ElmUpdate( model.copy( modalSheet = model.modalSheet.copy( isVisible = false, content = ModalSheetContent.NOTHING ) ) ) private fun onCollapseSearchBar(model: Model): Update = ElmUpdate( model.copy( searchBarState = model.searchBarState.copy(barState = SearchBarState.Collapsed), editNoteFabState = model.editNoteFabState.copy( isVisible = !model.notes.isSelection, state = EditNoteFabState.COLLAPSED ) ) ) private fun onExpandSearchBar(model: Model): Update = ElmUpdate( model.copy( searchBarState = model.searchBarState.copy(barState = SearchBarState.Expanded), editNoteFabState = model.editNoteFabState.copy( isVisible = false, state = EditNoteFabState.COLLAPSED ) ) ) private fun onCounterBarShareClicked(model: Model): Update = ElmUpdate(model) private fun onCounterBarSelectAllClicked(model: Model): Update { val notes = model.notes.collection.data.map { it.copy(isSelected = !model.notes.collection.data.all { item -> item.isSelected }) } val selectedList = notes.filter { it.isSelected } val isVisibleUnpinButton = selectedList.isNotEmpty().run { if (this) !selectedList.map { it.style.isPinned }.contains(false) else false } return ElmUpdate( model.copy( notes = model.notes.copy( collection = model.notes.collection.copy(notes), isVisibleUnpinBottomBarIcon = isVisibleUnpinButton ), searchBarState = model.searchBarState.copy( counterValue = notes.count { it.isSelected } ) ) ) } private fun onSnackBarUndoRemoveClicked(model: Model): Update { val restored = model.notes.removedList.map { note -> note.copy(isMovedToTrash = false) } val isShowLoading = restored.count() >= MINIMAL_FOR_LOADING_ITEMS_COUNT return ElmUpdate( model = model.copy( notes = model.notes.copy(state = model.notes.state.copy(isLoading = isShowLoading)) ), commands = setOf(Cmd.UndoRemoveNotes(restored)) ) } private fun hiddenLoadingPlaceholder(model: Model): Update = ElmUpdate( model = model.copy( notes = model.notes.copy(state = model.notes.state.copy(isLoading = false)) ) ) private fun updatedEditNoteFabState( model: Model, msg: Msg.Inner.UpdatedEditNoteFabState ): Update { val searchBarState = if (msg.state.isExpanded) model.searchBarState.copy(barState = SearchBarState.Collapsed) else model.searchBarState return ElmUpdate( model.copy( searchBarState = searchBarState, editNoteFabState = model.editNoteFabState.copy( isVisible = !model.notes.isSelection, state = msg.state ) ) ) } private fun updateStonewallVisibility( model: Model, msg: Msg.Inner.UpdateStonewallVisibility ): Update = ElmUpdate(model.copy(isVisibleStonewall = msg.isVisible)) }
0
Kotlin
0
0
863585ab17882e444060e5535401c728f9fc335d
13,456
Beresta
MIT License
sessionkotlin/lib/src/test/kotlin/dsl/enabled/EnabledBasicTest.kt
sessionkotlin
467,159,660
false
{"Kotlin": 365663, "Makefile": 1801}
package dsl.enabled import com.github.sessionkotlin.lib.dsl.SKRole import com.github.sessionkotlin.lib.dsl.exception.RoleNotEnabledException import com.github.sessionkotlin.lib.dsl.exception.UnfinishedRolesException import com.github.sessionkotlin.lib.dsl.globalProtocol import com.github.sessionkotlin.lib.dsl.globalProtocolInternal import com.github.sessionkotlin.lib.dsl.types.* import dsl.util.IntClass import dsl.util.LongClass import dsl.util.StringClass import org.junit.jupiter.api.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith class EnabledBasicTest { companion object { val a = SKRole("A") val b = SKRole("B") val c = SKRole("C") val d = SKRole("D") } @Test fun `role not enabled but is ignorable`() { val g = globalProtocolInternal { send<Int>(a, b) send<Int>(b, a) choice(b) { branch { // a not enabled send<String>(a, b) } } } val lA = LocalTypeSend( b, IntClass, LocalTypeReceive( b, IntClass, LocalTypeSend(b, StringClass, LEnd) ) ) assertEquals(g.project(a), lA) } @Test fun `role not enabled 2 branches mergeable`() { globalProtocol("Proto") { send<Int>(a, b) send<Int>(b, a) // mergeable for 'a' choice(b) { branch { send<String>(b, c, "b1") send<String>(a, b) } branch { send<String>(a, b) send<String>(b, c, "b2") } } } } @Test fun `role not enabled 2 branches not mergeable`() { assertFailsWith<RoleNotEnabledException> { globalProtocolInternal { choice(b) { branch { send<String>(b, c) // 'a' not enabled send<String>(a, b) } branch { send<Int>(a, b) send<Int>(b, c) } } } } } @Test fun `role not enabled 3 roles mergeable`() { val g = globalProtocolInternal { choice(b) { branch { send<String>(b, a, "b1") send<String>(d, a) } branch { send<Int>(b, a, "b2") send<String>(d, a) } } } val lD = LocalTypeSend(a, StringClass, LEnd) assertEquals(g.project(d), lD) } @Test fun `role not enabled 4 roles mergeable`() { val g = globalProtocolInternal { choice(b) { branch { send<String>(b, a, "b1") send<String>(c, d) send<String>(d, a) } branch { send<Int>(b, a, "b2") send<String>(c, d) send<String>(d, a) } } } val lC = LocalTypeSend(d, StringClass, LEnd) assertEquals(lC, g.project(c)) } @Test fun `role not enabled to send not mergeable`() { assertFailsWith<RoleNotEnabledException> { globalProtocolInternal { choice(b) { branch { send<String>(b, a) } branch { send<String>(b, a) send<String>(c, b) } } } } } @Test fun `role not enabled to choose not mergeable`() { assertFailsWith<UnfinishedRolesException> { globalProtocolInternal { choice(b) { branch { choice(a) { branch { send<Int>(a, b) } } } branch { send<Int>(b, a) } } } } } @Test fun `internal choice while ignoring external choice`() { val g = globalProtocolInternal { choice(b) { branch { choice(a) { branch { send<Int>(a, b) } } } } } val lA = LocalTypeInternalChoice( listOf(LocalTypeSend(b, IntClass, LEnd)) ) assertEquals(lA, g.project(a)) } @Test fun `role activated`() { globalProtocolInternal { choice(b) { branch { send<String>(b, a, "1") } branch { send<Int>(b, a, "2") send<Long>(a, b) } } } } @Test fun `role activated transitivity`() { globalProtocolInternal { choice(b) { branch { send<String>(b, c, "b1") send<String>(c, a, "b1") } branch { send<Int>(b, c, "b2") send<Int>(c, a, "b2") send<Int>(a, b) } } } } @Test fun `role activated transitivity 2`() { globalProtocolInternal { choice(a) { branch { send<Long>(a, b, "b1") send<Int>(b, c, "b1") send<String>(a, b) } branch { send<String>(a, b, "b2") send<Int>(b, c, "b2") send<Long>(a, b) } } } } @Test fun `erasable choice after activation`() { val g = globalProtocolInternal { choice(a) { branch { send<Long>(a, b, "1") // b does not participate, and can ignore the choice choice(a) { branch { send<Int>(a, c, "11") } branch { send<String>(a, c, "12") } } } branch { send<Int>(a, b, "2") send<Boolean>(a, c) } } } val lB = LocalTypeExternalChoice( a, listOf( LocalTypeReceive(a, LongClass, MsgLabel("1"), LEnd), LocalTypeReceive(a, IntClass, MsgLabel("2"), LEnd) ) ) assertEquals(g.project(b), lB) } @Test fun `external choice with input transitions`() { globalProtocol("Simple") { choice(a) { branch { send<String>(b, a) send<Int>(a, c, "_201", "_201 > 0") send<Int>(a, c, "_200") } branch { send<Int>(a, c, "_250") send<String>(b, a) } branch { send<Int>(a, c, "Quit") send<String>(b, a) } } } } }
0
Kotlin
0
1
558837e9525987c9196e00f796489c041928a50d
7,747
sessionkotlin
MIT License
src/commonMain/kotlin/com/adyen/model/checkout/DokuDetails.kt
tjerkw
733,432,442
false
{"Kotlin": 5043126, "Makefile": 6356}
/** * Adyen Checkout API * * Adyen Checkout API provides a simple and flexible way to initiate and authorise online payments. You can use the same integration for payments made with cards (including 3D Secure), mobile wallets, and local payment methods (for example, iDEAL and Sofort). This API reference provides information on available endpoints and how to interact with them. To learn more about the API, visit [online payments documentation](https://docs.adyen.com/online-payments). ## Authentication Each request to Checkout API must be signed with an API key. For this, [get your API key](https://docs.adyen.com/development-resources/api-credentials#generate-api-key) from your Customer Area, and set this key to the `X-API-Key` header value, for example: ``` curl -H \"Content-Type: application/json\" \\ -H \"X-API-Key: YOUR_API_KEY\" \\ ... ``` ## Versioning Checkout API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://checkout-test.adyen.com/v71/payments ``` ## Going live To access the live endpoints, you need an API key from your live Customer Area. The live endpoint URLs contain a prefix which is unique to your company account, for example: ``` https://{PREFIX}-checkout-live.adyenpayments.com/checkout/v71/payments ``` Get your `{PREFIX}` from your live Customer Area under **Developers** > **API URLs** > **Prefix**. When preparing to do live transactions with Checkout API, follow the [go-live checklist](https://docs.adyen.com/online-payments/go-live-checklist) to make sure you've got all the required configuration in place. ## Release notes Have a look at the [release notes](https://docs.adyen.com/online-payments/release-notes?integration_type=api&version=71) to find out what changed in this version! * * The version of the OpenAPI document: 71 * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package com.adyen.model.checkout import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* /** * * * @param firstName The shopper's first name. * @param lastName The shopper's last name. * @param shopperEmail The shopper's email. * @param type **doku** * @param checkoutAttemptId The checkout attempt identifier. */ @Serializable data class DokuDetails ( /* The shopper's first name. */ @SerialName(value = "firstName") @Required val firstName: kotlin.String, /* The shopper's last name. */ @SerialName(value = "lastName") @Required val lastName: kotlin.String, /* The shopper's email. */ @SerialName(value = "shopperEmail") @Required val shopperEmail: kotlin.String, /* **doku** */ @SerialName(value = "type") @Required val type: DokuDetails.Type, /* The checkout attempt identifier. */ @SerialName(value = "checkoutAttemptId") val checkoutAttemptId: kotlin.String? = null ) { /** * **doku** * * Values: MandiriVa,CimbVa,DanamonVa,BniVa,PermataLiteAtm,BriVa,BcaVa,Alfamart,Indomaret,Wallet,Ovo */ @Serializable enum class Type(val value: kotlin.String) { @SerialName(value = "doku_mandiri_va") MandiriVa("doku_mandiri_va"), @SerialName(value = "doku_cimb_va") CimbVa("doku_cimb_va"), @SerialName(value = "doku_danamon_va") DanamonVa("doku_danamon_va"), @SerialName(value = "doku_bni_va") BniVa("doku_bni_va"), @SerialName(value = "doku_permata_lite_atm") PermataLiteAtm("doku_permata_lite_atm"), @SerialName(value = "doku_bri_va") BriVa("doku_bri_va"), @SerialName(value = "doku_bca_va") BcaVa("doku_bca_va"), @SerialName(value = "doku_alfamart") Alfamart("doku_alfamart"), @SerialName(value = "doku_indomaret") Indomaret("doku_indomaret"), @SerialName(value = "doku_wallet") Wallet("doku_wallet"), @SerialName(value = "doku_ovo") Ovo("doku_ovo"); } }
0
Kotlin
0
0
2da5aea5519b2dfa84454fe1665e9699edc87507
4,229
adyen-kotlin-multiplatform-api-library
MIT License
domain/src/test/java/com/gauvain/seigneur/domain/mock/OutComeModelMock.kt
GauvainSeigneur
252,719,373
false
null
package com.gauvain.seigneur.domain.mock import com.gauvain.seigneur.domain.model.* import com.gauvain.seigneur.domain.utils.SERVER_DATE_FORMAT import com.gauvain.seigneur.domain.utils.SERVER_TIME_FORMAT import com.gauvain.seigneur.domain.utils.toDate object OutComeModelMock { fun createStatisticsModelListWithoutWorldAndAll(): List<StatisticsItemModel> = listOf( StatisticsItemModel( country = "China", day = "2020-04-08".toDate(SERVER_DATE_FORMAT), time = "2020-04-08T09:45:05+00:00".toDate(SERVER_TIME_FORMAT), casesModel = CasesModel( new = 1000, active = 70000, critical = 1000, recovered = 35000, total = 107000 ), deathsModel = DeathsModel( new = "+200", total = 1200 ) ), StatisticsItemModel( country = "France", day = "2020-04-08".toDate(SERVER_DATE_FORMAT), time = "2020-04-08T09:45:05+00:00".toDate(SERVER_TIME_FORMAT), casesModel = CasesModel( new = 1000, active = 70000, critical = 1000, recovered = 35000, total = 107000 ), deathsModel = DeathsModel( new = "+200", total = 1200 ) ), StatisticsItemModel( country = "Italy", day = "2020-04-08".toDate(SERVER_DATE_FORMAT), time = "2020-04-08T09:45:05+00:00".toDate(SERVER_TIME_FORMAT), casesModel = CasesModel( new = 800, active = 60000, critical = 200, recovered = 3500, total = 64500 ), deathsModel = DeathsModel( new = "+100", total = 900 ) ) ) fun CreateShortHistoryModel(): AllHistoryModel = AllHistoryModel( totalCases = 107000, totalNewCases = 1000, totalActiveCases = 70000, activeHistory = listOf( AllActiveHistoryItemModel( total = 70000, day = "2020-04-08".toDate(SERVER_DATE_FORMAT) ), AllActiveHistoryItemModel( total = 60000, day = "2020-04-07".toDate(SERVER_DATE_FORMAT) ) ) ) fun createCountryHistoryModel(): CountryHistoryModel = CountryHistoryModel( country = "France", history = listOf( CountryHistoryItemModel( date = "2020-04-08".toDate(SERVER_DATE_FORMAT), total = 107000, new = 1000, active = 70000, recovered = 35000, critical = 1000, dead = 1200 ), CountryHistoryItemModel( date = "2020-04-07".toDate(SERVER_DATE_FORMAT), total = 64500, new = 800, active = 60000, recovered = 3500, critical = 200, dead = 900 ) ) ) }
3
Kotlin
0
0
e983a2674d1729d2d6f8d7e0a34cee5a7354f27a
3,580
CovidUpdate
Apache License 2.0
framework/src/main/kotlin/br/com/zup/beagle/serialization/jackson/BeagleModule.kt
ZupIT
391,145,988
false
null
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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 br.com.zup.beagle.serialization.jackson import br.com.zup.beagle.analytics.ActionAnalyticsConfig import br.com.zup.beagle.widget.action.SetContext import br.com.zup.beagle.widget.context.Bind import br.com.zup.beagle.widget.context.Context import br.com.zup.beagle.widget.layout.ComposeComponent import br.com.zup.beagle.widget.layout.ScreenBuilder import com.fasterxml.jackson.databind.module.SimpleModule class BeagleModule( private val classLoader: ClassLoader = BeagleModule::class.java.classLoader ) : SimpleModule() { init { this.setSerializerModifier(BeagleSerializerModifier(this.classLoader)) this.addSerializer(Context::class.java, ContextObjectSerializer()) this.addSerializer(SetContext::class.java, SetContextObjectSerializer()) this.addSerializer(ScreenBuilder::class.java, ScreenBuilderSerializer()) this.setMixInAnnotation( getClass(ComposeComponent::class, this.classLoader), ComposeComponentMixin::class.java ) this.setMixInAnnotation( getClass(ScreenBuilder::class, this.classLoader), ScreenBuilderMixin::class.java ) this.setMixInAnnotation( getClass(Bind::class, this.classLoader), BindMixin::class.java ) this.setMixInAnnotation( getClass(ActionAnalyticsConfig::class, this.classLoader), ActionAnalyticsConfigMixin::class.java ) } }
5
null
11
5
e3f33bae4e209b3852c9a24182a109676166c3d9
2,098
beagle-backend-kotlin
Apache License 2.0
app/src/main/java/com/hillpark/hillpark/model/CameraUrl.kt
0adik0
437,355,255
false
{"Kotlin": 201941, "Java": 22343}
package com.hillpark.hillpark.model data class CameraUrl( var name: String, var url: String )
0
Kotlin
0
0
fb5519d9169a5d1185439df79a5da802e727fc87
102
Hillpark
Apache License 2.0
app/src/main/java/com/example/hiltdemo/MainActivity.kt
von-mon
315,506,144
false
null
package com.example.hiltdemo import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class MainActivity : AppCompatActivity() { @Inject lateinit var truck: Truck //不可以声明成private override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) truck.deliver() } }
0
Kotlin
0
0
c4d07766cd50a732bdecdda295c8eeb88f444a52
475
HiltDemo
Apache License 2.0
src/main/kotlin/com/amazon/opendistroforelasticsearch/indexmanagement/rollup/model/RollupFieldMapping.kt
opendistro-for-elasticsearch
174,581,847
false
null
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazon.opendistroforelasticsearch.indexmanagement.rollup.model import com.amazon.opendistroforelasticsearch.indexmanagement.rollup.model.Rollup.Companion.DIMENSIONS_FIELD import com.amazon.opendistroforelasticsearch.indexmanagement.rollup.model.Rollup.Companion.METRICS_FIELD data class RollupFieldMapping(val fieldType: FieldType, val fieldName: String, val mappingType: String, var sourceType: String? = null) { fun sourceType(type: String?) { this.sourceType = type } override fun toString(): String { return "$fieldName.$mappingType" } fun toIssue(isFieldMissing: Boolean = false): String { return if (isFieldMissing || mappingType == UNKNOWN_MAPPING) return "missing field $fieldName" else when (fieldType) { FieldType.METRIC -> "missing $mappingType aggregation on $fieldName" else -> "missing $mappingType grouping on $fieldName" } } companion object { const val UNKNOWN_MAPPING = "unknown" enum class FieldType(val type: String) { DIMENSION(DIMENSIONS_FIELD), METRIC(METRICS_FIELD); override fun toString(): String { return type } } } }
51
null
46
117
cda0eda35fc5da3816c407ad7a929d746edaf179
1,839
index-management
Apache License 2.0
app/src/main/java/com/vladgba/keyb/KeybView.kt
vladgba
508,309,235
false
null
package com.vladgba.keyb import kotlin.collections.* import android.annotation.SuppressLint import android.content.Context import android.content.res.Resources import android.graphics.* import android.util.AttributeSet import android.view.* import java.lang.* import java.util.* import kotlin.math.* class KeybView : View, View.OnClickListener { var keybCtl: KeybController? = null var buffer: Bitmap? = null private var bufferSh: Bitmap? = null private var res: Resources? = null var paint = Paint() var repMods = false constructor(c: KeybController) : super(c, null) { keybCtl = c initResources(c) } constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) fun reload() { buffer = null requestLayout() invalidate() } override fun onClick(v: View) {} public override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { if (keybCtl!!.keybLayout == null) return setMeasuredDimension(0, 0) var width = keybCtl!!.keybLayout!!.minWidth if (MeasureSpec.getSize(widthMeasureSpec) < width + 10) { width = MeasureSpec.getSize(widthMeasureSpec) } setMeasuredDimension(width, keybCtl!!.keybLayout!!.height) } public override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) repaintKeyb(w, h) } override fun onHoverEvent(event: MotionEvent): Boolean { return true } private fun initResources(context: Context) { res = context.resources } fun repMod() { if (buffer == null || bufferSh == null) return repMods = true keybPaint(buffer!!.width, buffer!!.height, buffer!!, false) keybPaint(bufferSh!!.width, bufferSh!!.height, bufferSh!!, true) repMods = false invalidate() } private fun repaintKeyb(w: Int, h: Int) { bufferSh = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565) buffer = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565) keybPaint(w, h, buffer!!, false) keybPaint(w, h, bufferSh!!, true) if (keybCtl!!.keybLayout!!.bitmap != null) return keybCtl!!.keybLayout!!.bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) keybCtl!!.keybLayout!!.bitmap?.eraseColor(Color.TRANSPARENT) keybCtl!!.keybLayout!!.canv = Canvas(keybCtl!!.keybLayout!!.bitmap!!) invalidate() } private fun keybPaint(w: Int, h: Int, b: Bitmap, sh: Boolean) { val canvas = Canvas(b) val paint = Paint() if (!repMods) { paint.color = getColor("keyboardBackground") val r = RectF(0f, 0f, w.toFloat(), h.toFloat()) canvas.drawRect(r, paint) } val keys = keybCtl!!.keybLayout!!.keys for (key in keys) { if (repMods && !key.getBool("mod")) continue if(key.getBool("mod")) { paint.color = getColor("keyboardBackground") val r = RectF(key.x.toFloat(), key.y.toFloat(), key.x.toFloat() + key.width.toFloat(), key.y.toFloat() + key.height.toFloat()) canvas.drawRect(r, paint) } canvas.save() // Positions for subsymbols val x1 = key.width / 5 val x2 = key.width / 2 val x3 = key.width - x1 val y1 = key.height / 5 val y2 = key.height / 2 val y3 = key.height - y1 val rect = Rect(key.x, key.y, key.x + key.width, key.y + key.height) canvas.clipRect(rect) paint.isAntiAlias = true paint.textAlign = Paint.Align.CENTER paint.color = getColor("keyBorder") val padding = key.height / 16 val radius = key.height / 6 val shadow = key.height / 36 val lpad = if (key.getStr("stylepos").contains("l")) -key.width else 0 val rpad = if (key.getStr("stylepos").contains("r")) key.width else 0 val tpad = if (key.getStr("stylepos").contains("t")) -key.height else 0 val bpad = if (key.getStr("stylepos").contains("b")) key.height else 0 var recty = RectF( (key.x + lpad + padding - shadow / 3).toFloat(), (key.y + tpad + padding).toFloat(), (key.x + rpad + key.width - padding + shadow / 3).toFloat(), (key.y + bpad + key.height - padding + shadow).toFloat() ) canvas.drawRoundRect(recty, radius.toFloat(), radius.toFloat(), paint) paint.color = if (key.getStr("bg").isEmpty()) getColor("keyBackground") else Color.parseColor("#" + key.getStr("bg")) if (key.getBool("mod") && (key.getInt("modmeta") and keybCtl!!.mod) > 0) paint.color = getColor("modBackground") recty = RectF( (key.x + lpad + padding).toFloat(), (key.y + tpad + padding).toFloat(), (key.x + rpad + key.width - padding).toFloat(), (key.y + bpad + key.height - padding).toFloat() ) canvas.drawRoundRect(recty, radius.toFloat(), radius.toFloat(), paint) paint.textSize = key.height / keybCtl!!.secondaryFont paint.color = getColor("primaryText") viewExtChars(key, canvas, paint, sh, x1, x2, x3, y1, y2, y3, false) paint.color = getColor("primaryText") paint.textSize = key.height / keybCtl!!.primaryFont if (key.label != null) { val lbl = if (sh && key.label!!.length < 2) keybCtl?.getShifted(key.label!![0].code,true)!!.toChar().toString() else key.label.toString() canvas.drawText( lbl, key.x + key.width / 2f, key.y + (key.height + paint.textSize - paint.descent()) / 2, paint) } canvas.restore() } } private fun randColor(): Int { val a = arrayOf(0xffff0000, 0xffffff00, 0xffffffff, 0xff00ff00, 0xffff00ff, 0xff00ffff, 0xff0000ff, 0xff000000) return (a[Random().nextInt(8)]).toInt() } private fun getColor(n: String): Int { if (keybCtl!!.sett.isEmpty()) return randColor() val clrSw = keybCtl!!.sett.containsKey("colorSwitch") && keybCtl!!.sett.getValue("colorSwitch") == "1" val curTheme = if (keybCtl!!.night && clrSw) "colorNight" else "colorDay" if (!keybCtl!!.sett.containsKey(curTheme)) return randColor() val theme = keybCtl!!.sett.getValue(curTheme) as Map<String, Any> return if (theme.containsKey(n)) (theme.getValue(n) as String).toLong(16).toInt() else randColor() } public override fun onDraw(canvas: Canvas) { try { if (buffer == null) repaintKeyb(width, height) canvas.drawBitmap((if (keybCtl!!.shiftPressed()) bufferSh else buffer)!!, 0f, 0f, null) if (keybCtl!!.getVal(keybCtl!!.sett, "debug", "") == "1") { if (keybCtl!!.keybLayout!!.bitmap != null) canvas.drawBitmap( keybCtl!!.keybLayout!!.bitmap!!, 0f, 0f, null ) paint.color = if (keybCtl!!.night) 0xffffffff.toInt() else 0xff000000.toInt() paint.textSize = 20.toFloat() canvas.drawText(keybCtl!!.mod.toString(2), 10f, 95f, paint) } canvas.drawText(keybCtl!!.erro, 40f, 20f, paint) if (keybCtl!!.recKey != null) canvas.drawText(keybCtl!!.recKey!!.record.size.toString(), 20f, 20f, paint) if (keybCtl!!.points[keybCtl!!.lastpid] == null) return val curkey = keybCtl!!.points[keybCtl!!.lastpid]!! drawKey(canvas, curkey) } catch (e: Exception) { keybCtl!!.prStack(e) } } fun drawKey(canvas: Canvas, curkey: Key) { canvas.save() if (!curkey.extCharsRaw.isNotEmpty() && !curkey.getBool("clipboard")) return val paint = Paint() paint.isAntiAlias = true paint.textAlign = Paint.Align.CENTER paint.textSize = curkey.height / keybCtl!!.primaryFont val rectShadow = RectF(0f, 0f, width.toFloat(), height.toFloat()) paint.color = getColor("shadowColor") canvas.drawRect(rectShadow, paint) paint.color = getColor("previewText") val x1 = curkey.width / 2 - curkey.width val x2 = curkey.width / 2 val x3 = curkey.width * 2 - curkey.width / 2 val y1 = curkey.height / 2 - curkey.height val y2 = curkey.height / 2 val y3 = curkey.height * 2 - curkey.height / 2 if (!curkey.getBool("clipboard") || curkey.charPos < 1 || curkey.extChars[curkey.charPos - 1] == null) { val rect = Rect( curkey.x - curkey.width, curkey.y - curkey.height, curkey.x + curkey.width * 2, curkey.y + curkey.height * 2) canvas.clipRect(rect) } val pd = curkey.height / 36 paint.color = getColor("keyBorder") var recty = RectF((curkey.x + x1 * 2).toFloat(), (curkey.y + y1 * 2).toFloat(), (curkey.x - x1 + x3).toFloat(), (curkey.y - y1 + y3).toFloat()) canvas.drawRoundRect(recty, 30f, 30f, paint) paint.color = getColor("keyBackground") recty = RectF((curkey.x + x1 * 2 + pd / 3).toFloat(), (curkey.y + y1 * 2).toFloat(), (curkey.x - x1 + x3 - pd / 3).toFloat(), (curkey.y - y1 + y3 - pd).toFloat()) canvas.drawRoundRect(recty, 30f, 30f, paint) paint.color = getColor("primaryText") val sh = keybCtl!!.shiftPressed() if (curkey.getBool("clipboard") && curkey.charPos > 0 && curkey.extChars[curkey.charPos - 1] != null) { paint.textSize = curkey.height / keybCtl!!.secondaryFont canvas.drawText( curkey.extChars[curkey.charPos - 1].toString(), width / 2f, curkey.height / 5 + (paint.textSize - paint.descent()) / 2, paint ) } viewExtChars(curkey, canvas, paint, sh, x1, x2, x3, y1, y2, y3, true) canvas.restore() } private fun viewExtChars(curkey: Key?, cv: Canvas, p: Paint, sh: Boolean, x1: Int, x2: Int, x3: Int, y1: Int, y2: Int, y3: Int, h: Boolean) { if (curkey == null || curkey.extCharsRaw == "") return val str = curkey.extChars val xi = intArrayOf(x1, x2, x3, x1, x3, x1, x2, x3) val yi = intArrayOf(y1, y1, y1, y2, y2, y3, y3, y3) for (i in 0..7) { p.color = getColor("previewSelected") if (h) { if (curkey.charPos == i + 1) cv.drawCircle((curkey.x + xi[i]).toFloat(), (curkey.y + yi[i]).toFloat(), min(curkey.width, curkey.height) * 0.6f, p) p.color = getColor("previewText") } else { p.color = getColor("secondaryText") } viewChar(str, i, xi[i], yi[i], cv, curkey, p, sh) } if (!h) return if (curkey.charPos == 0) { p.color = getColor("previewSelected") cv.drawCircle((curkey.x + x2).toFloat(), (curkey.y + y2).toFloat(), min(curkey.width, curkey.height) * 0.4f, p) } p.color = getColor("previewText") cv.drawText( if (sh && curkey.label!!.length < 2) keybCtl?.getShifted(curkey.label!![0].code, true)!!.toChar().toString() else curkey.label.toString(), (curkey.x + x2).toFloat(), curkey.y + y2 + (p.textSize - p.descent()) / 2, p ) } private fun viewChar(str: Array<CharSequence?>, pos: Int, ox: Int, oy: Int, canvas: Canvas, key: Key?, paint: Paint, sh: Boolean) { if (str.size <= pos || str[pos] == null || str[pos] == " ") return val lbl = if (str[pos]?.length == 1) { keybCtl?.getShifted(str[pos]!!.get(0).code, sh)!!.toChar().toString() } else { str[pos] } canvas.drawText( lbl.toString(), (key!!.x + ox).toFloat(), key.y + oy + (paint.textSize - paint.descent()) / 2, paint ) } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(me: MotionEvent): Boolean { invalidate() return keybCtl!!.onTouchEvent(me) } }
0
Kotlin
0
0
acb5d2cbb8758722522f55fdc1c93db0f9d67c3e
12,547
VKeyboard
MIT License
app/src/main/java/com/wa2c/android/medoly/plugin/action/tweet/activity/component/PreferenceExt.kt
wa2c
134,158,949
false
{"Kotlin": 74063}
package com.wa2c.android.medoly.plugin.action.tweet.activity.component import androidx.annotation.StringRes import androidx.preference.* import com.wa2c.android.medoly.plugin.action.tweet.R fun PreferenceFragmentCompat.setListener(@StringRes prefKeyRes: Int, listener: (() -> Unit)) { (findPreference(getString(prefKeyRes)) as? Preference)?.setOnPreferenceClickListener { listener.invoke() true } } fun <T : Preference> PreferenceFragmentCompat.preference(@StringRes prefKeyRes: Int): T? { return preference(getString(prefKeyRes)) } fun <T : Preference> PreferenceFragmentCompat.preference(prefKey: String): T? { return findPreference(prefKey) } fun PreferenceFragmentCompat.updatePrefSummary(@StringRes prefKeyRes: Int, force: Boolean = false) { this.updatePrefSummary(requireContext().getString(prefKeyRes), force) } /** * Initialize summary. * @param p target item. */ fun PreferenceFragmentCompat.initSummary(p: Preference) { // update summary when (p) { is PreferenceCategory -> { for (i in 0 until p.preferenceCount) { initSummary(p.getPreference(i)) } } is PreferenceScreen -> { for (i in 0 until p.preferenceCount) { initSummary(p.getPreference(i)) } } else -> updatePrefSummary(p.key) } } fun PreferenceFragmentCompat.updatePrefSummary(prefKey: String, force: Boolean = false) { val p = preference(prefKey) as? Preference ?: return // for instance type when (p) { is CheckBoxPreference -> { return } is ListPreference -> { // ListPreference p.value = p.sharedPreferences?.getString(p.key, "") p.setSummaryValue(p.entry) } is MultiSelectListPreference -> { // MultiSelectListPreference val stringSet = p.sharedPreferences?.getStringSet(p.key, null) var text = "" if (stringSet != null && stringSet.size > 0) { p.values = stringSet // update value once val builder = StringBuilder() (p.entries.indices) .filter { stringSet.contains(p.entryValues[it]) } .forEach { builder.append(p.entries[it]).append(",") } if (builder.isNotEmpty()) { text = builder.substring(0, builder.length - 1) // remove end comma } } p.setSummaryValue(text) } is EditTextPreference -> { // EditTextPreference val text = p.sharedPreferences?.getString(p.key, "") p.text = text // update once p.setSummaryValue(text) } else -> { if (force) { val text = p.sharedPreferences?.getString(p.key, "") p.setSummaryValue(text) } } } } /** * Add value on preference summary. */ private fun Preference.setSummaryValue(value: CharSequence?) { val mask = "********" val escapeMask = """\*\*\*\*\*\*\*\*""" val literal = (this.context.getString(R.string.settings_summary_current_value, mask)).let { val from = Regex("(?!\\\\)(\\W)").replace(it, "\\\\\$1") // NOTE: Escape regex characters from.replace(escapeMask, ".*") } val plainSummary = Regex("\n$literal$").replace(this.summary ?: "", "") val valueSummary = this.context.getString(R.string.settings_summary_current_value, value ?: "") this.summary = plainSummary + "\n" + valueSummary }
1
Kotlin
0
0
bd3b6591f0a427a8b327e18091a905e7b644e888
3,595
medoly-twitter-plugin
MIT License
src/test/kotlin/com/mattmik/rapira/console/ConsoleWriterTest.kt
rapira-book
519,693,099
true
{"Kotlin": 226030, "ANTLR": 7912}
package com.mattmik.rapira.console import com.mattmik.rapira.objects.Empty import com.mattmik.rapira.objects.Function import com.mattmik.rapira.objects.Logical import com.mattmik.rapira.objects.Procedure import com.mattmik.rapira.objects.RInteger import com.mattmik.rapira.objects.Real import com.mattmik.rapira.objects.Text import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.shouldBe class ConsoleWriterTest : WordSpec({ "formatObject" should { "return correct string representations" { ConsoleWriter.formatObject(Empty) shouldBe "empty" ConsoleWriter.formatObject(Procedure()) shouldBe "proc" ConsoleWriter.formatObject(Procedure("foo")) shouldBe "proc[\"foo\"]" ConsoleWriter.formatObject(Function()) shouldBe "fun" ConsoleWriter.formatObject(Function("foo")) shouldBe "fun[\"foo\"]" ConsoleWriter.formatObject(Logical(true)) shouldBe "yes" ConsoleWriter.formatObject(Logical(false)) shouldBe "no" ConsoleWriter.formatObject(RInteger(123)) shouldBe "123" ConsoleWriter.formatObject(Real(1.4)) shouldBe "1.4" ConsoleWriter.formatObject(Text("")) shouldBe "" ConsoleWriter.formatObject(Text("Hello!")) shouldBe "Hello!" ConsoleWriter.formatObject(Text("How about some \"double quotes\"?")) shouldBe "How about some \"double quotes\"?" } } })
0
null
0
0
46f294e59c67747e1c00b5acf32b3cbe44281831
1,430
rapture
Apache License 2.0
vector/src/main/java/varta/cdac/app/features/call/webrtc/PeerConnectionObserverAdapter.kt
ginnyTheCat
484,447,678
false
{"Gradle": 8, "Markdown": 16, "Java Properties": 2, "Shell": 19, "Text": 43, "Ignore List": 7, "Batchfile": 1, "EditorConfig": 1, "YAML": 2, "INI": 2, "Proguard": 5, "XML": 768, "Kotlin": 2184, "Java": 12, "JavaScript": 4, "JSON": 5, "HTML": 2, "Python": 2, "FreeMarker": 2, "Fluent": 7}
/* * Copyright (c) 2020 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.app.features.call.webrtc import org.webrtc.DataChannel import org.webrtc.IceCandidate import org.webrtc.MediaStream import org.webrtc.PeerConnection import org.webrtc.RtpReceiver import timber.log.Timber abstract class PeerConnectionObserverAdapter : PeerConnection.Observer { override fun onIceCandidate(p0: IceCandidate?) { Timber.v("## VOIP onIceCandidate $p0") } override fun onDataChannel(p0: DataChannel?) { Timber.v("## VOIP onDataChannel $p0") } override fun onIceConnectionReceivingChange(p0: Boolean) { Timber.v("## VOIP onIceConnectionReceivingChange $p0") } override fun onIceConnectionChange(p0: PeerConnection.IceConnectionState?) { Timber.v("## VOIP onIceConnectionChange $p0") } override fun onIceGatheringChange(p0: PeerConnection.IceGatheringState?) { Timber.v("## VOIP onIceConnectionChange $p0") } override fun onAddStream(mediaStream: MediaStream?) { Timber.v("## VOIP onAddStream $mediaStream") } override fun onSignalingChange(p0: PeerConnection.SignalingState?) { Timber.v("## VOIP onSignalingChange $p0") } override fun onIceCandidatesRemoved(p0: Array<out IceCandidate>?) { Timber.v("## VOIP onIceCandidatesRemoved $p0") } override fun onRemoveStream(mediaStream: MediaStream?) { Timber.v("## VOIP onRemoveStream $mediaStream") } override fun onRenegotiationNeeded() { Timber.v("## VOIP onRenegotiationNeeded") } override fun onAddTrack(p0: RtpReceiver?, p1: Array<out MediaStream>?) { Timber.v("## VOIP onAddTrack $p0 / out: $p1") } }
56
null
1
1
ef17804af2f134cfbeca5645579f2fbb4b685944
2,271
new_chat
Apache License 2.0
kt/godot-library/src/main/kotlin/godot/gen/godot/CSGCombiner.kt
ShalokShalom
343,354,086
true
{"Kotlin": 516486, "GDScript": 294955, "C++": 262753, "C#": 11670, "CMake": 2060, "Shell": 1628, "C": 959, "Python": 75}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName") package godot import godot.annotation.GodotBaseType import godot.core.TransferContext import godot.util.VoidPtr import kotlin.Suppress @GodotBaseType open class CSGCombiner : CSGShape() { override fun __new(): VoidPtr = TransferContext.invokeConstructor(ENGINECLASS_CSGCOMBINER) }
0
null
0
1
7b9b195de5be4a0b88b9831c3a02f9ca06aa399c
542
godot-jvm
MIT License
plugin/contract-models/src/main/java/studio/opends/OpenDesignSystem.kt
open-design-systems
810,431,148
false
{"Kotlin": 42547, "Shell": 2799, "Makefile": 121}
package studio.opends import kotlinx.serialization.Serializable @Serializable data class OpenDesignSystem( val meta: MetaInformation, val colors: Map<String, OpenColor>, val spacing: Map<String, Spacing>, // val surface: Map<String, Surface>, val typography: Map<String, Typography>, val shadows: Map<String, Shadows> )
1
Kotlin
0
0
7f969b713beb7d472504c68520e0482243f593a1
346
OpenDSAndroid
Creative Commons Zero v1.0 Universal
vapi4k-core/src/main/kotlin/com/vapi4k/dsl/model/PerplexityAIModelImpl.kt
vapi4k
867,257,277
false
{"Kotlin": 923800, "JavaScript": 12815, "CSS": 8320, "Mermaid": 1873, "Makefile": 623, "HTML": 51}
/* * Copyright © 2024 Matthew Ambrose * * 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.vapi4k.dsl.model import com.vapi4k.api.model.CustomLLMModel import com.vapi4k.dtos.model.CustomLLMModelDto internal class CustomLLMModelImpl( modelUnion: ModelUnion, modelDto: CustomLLMModelDto, ) : AbstractModelImpl(modelUnion, modelDto), CustomLLMModelProperties by modelDto, CustomLLMModel
0
Kotlin
0
0
da2eb5c23a0ad87a55d973e0610f4f8c4ccd6e7b
913
vapi4k
Apache License 2.0
sources/ui/src/main/kotlin/com/sedsoftware/blinktracker/ui/camera/core/VisionImageProcessor.kt
djkovrik
647,371,944
false
null
package com.sedsoftware.blinktracker.ui.camera.core import androidx.camera.core.ExperimentalGetImage import androidx.camera.core.ImageProxy import com.google.android.gms.tasks.TaskExecutors import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.face.Face import com.google.mlkit.vision.face.FaceDetection import com.google.mlkit.vision.face.FaceDetector import com.google.mlkit.vision.face.FaceDetectorOptions import com.sedsoftware.blinktracker.components.tracker.model.VisionFaceData import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import timber.log.Timber import kotlin.math.round interface VisionImageProcessor { val faceData: Flow<VisionFaceData> suspend fun process(image: ImageProxy) fun stop() } class FaceDetectorProcessor(detectorOptions: FaceDetectorOptions) : VisionImageProcessor { private val detector: FaceDetector = FaceDetection.getClient(detectorOptions) private val executor: ScopedExecutor = ScopedExecutor(TaskExecutors.MAIN_THREAD) private val emptyData: VisionFaceData = VisionFaceData() private val _faceData: MutableStateFlow<VisionFaceData> = MutableStateFlow(emptyData) private var isShutdown: Boolean = false override val faceData: Flow<VisionFaceData> get() = _faceData @ExperimentalGetImage override suspend fun process(image: ImageProxy) { if (isShutdown) { return } detector.process(InputImage.fromMediaImage(image.image!!, image.imageInfo.rotationDegrees)) .addOnSuccessListener(executor) { results: List<Face> -> if (results.isNotEmpty()) { val face = results.first() _faceData.value = VisionFaceData( leftEye = face.leftEyeOpenProbability.roundTo(PRECISION), rightEye = face.rightEyeOpenProbability.roundTo(PRECISION), faceAvailable = face.leftEyeOpenProbability != null && face.rightEyeOpenProbability != null, ) } else { _faceData.value = emptyData } } .addOnFailureListener(executor) { exception: Exception -> exception.printStackTrace() Timber.e("Face detection failed ${exception.message}") _faceData.value = emptyData } .addOnCompleteListener { image.close() } } override fun stop() { executor.shutdown() isShutdown = true detector.close() } @Suppress("MagicNumber") private fun Float?.roundTo(decimals: Int): Float? { if (this == null) return null var multiplier = 1.0f repeat(decimals) { multiplier *= 10f } return round(this * multiplier) / multiplier } private companion object { const val PRECISION = 4 } }
0
Kotlin
0
2
e21432314401f04c9c427af4178924b953653ddb
2,917
BlinkTracker
MIT License
sources/ui/src/main/kotlin/com/sedsoftware/blinktracker/ui/camera/core/VisionImageProcessor.kt
djkovrik
647,371,944
false
null
package com.sedsoftware.blinktracker.ui.camera.core import androidx.camera.core.ExperimentalGetImage import androidx.camera.core.ImageProxy import com.google.android.gms.tasks.TaskExecutors import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.face.Face import com.google.mlkit.vision.face.FaceDetection import com.google.mlkit.vision.face.FaceDetector import com.google.mlkit.vision.face.FaceDetectorOptions import com.sedsoftware.blinktracker.components.tracker.model.VisionFaceData import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import timber.log.Timber import kotlin.math.round interface VisionImageProcessor { val faceData: Flow<VisionFaceData> suspend fun process(image: ImageProxy) fun stop() } class FaceDetectorProcessor(detectorOptions: FaceDetectorOptions) : VisionImageProcessor { private val detector: FaceDetector = FaceDetection.getClient(detectorOptions) private val executor: ScopedExecutor = ScopedExecutor(TaskExecutors.MAIN_THREAD) private val emptyData: VisionFaceData = VisionFaceData() private val _faceData: MutableStateFlow<VisionFaceData> = MutableStateFlow(emptyData) private var isShutdown: Boolean = false override val faceData: Flow<VisionFaceData> get() = _faceData @ExperimentalGetImage override suspend fun process(image: ImageProxy) { if (isShutdown) { return } detector.process(InputImage.fromMediaImage(image.image!!, image.imageInfo.rotationDegrees)) .addOnSuccessListener(executor) { results: List<Face> -> if (results.isNotEmpty()) { val face = results.first() _faceData.value = VisionFaceData( leftEye = face.leftEyeOpenProbability.roundTo(PRECISION), rightEye = face.rightEyeOpenProbability.roundTo(PRECISION), faceAvailable = face.leftEyeOpenProbability != null && face.rightEyeOpenProbability != null, ) } else { _faceData.value = emptyData } } .addOnFailureListener(executor) { exception: Exception -> exception.printStackTrace() Timber.e("Face detection failed ${exception.message}") _faceData.value = emptyData } .addOnCompleteListener { image.close() } } override fun stop() { executor.shutdown() isShutdown = true detector.close() } @Suppress("MagicNumber") private fun Float?.roundTo(decimals: Int): Float? { if (this == null) return null var multiplier = 1.0f repeat(decimals) { multiplier *= 10f } return round(this * multiplier) / multiplier } private companion object { const val PRECISION = 4 } }
0
Kotlin
0
2
e21432314401f04c9c427af4178924b953653ddb
2,917
BlinkTracker
MIT License
app/src/main/java/com/fridaytech/dex/data/zrx/IZrxKitManager.kt
5daytech
198,758,400
false
null
package com.fridaytech.dex.data.zrx import com.fridaytech.dex.data.zrx.model.* import com.fridaytech.dex.presentation.orders.model.EOrderSide import com.fridaytech.zrxkit.ZrxKit import com.fridaytech.zrxkit.model.AssetItem import com.fridaytech.zrxkit.model.OrderInfo import com.fridaytech.zrxkit.model.SignedOrder import com.fridaytech.zrxkit.relayer.model.OrderRecord import io.reactivex.Flowable import io.reactivex.subjects.BehaviorSubject import java.math.BigDecimal interface IZrxKitManager { fun zrxKit(): ZrxKit fun unlink() } interface IAllowanceChecker { fun checkAndUnlockAssetPairForPost(assetPair: Pair<AssetItem, AssetItem>, side: EOrderSide): Flowable<Boolean> fun checkAndUnlockPairForFill(pair: Pair<String, String>, side: EOrderSide): Flowable<Boolean> } interface IExchangeInteractor { fun fill(orders: List<SignedOrder>, fillData: FillOrderData): Flowable<String> fun createOrder(feeRecipient: String, createData: CreateOrderData): Flowable<SignedOrder> fun cancelOrder(order: SignedOrder): Flowable<String> fun batchCancelOrders(orders: List<SignedOrder>): Flowable<String> fun ordersInfo(orders: List<SignedOrder>): Flowable<List<OrderInfo>> } interface IRelayerAdapterManager { val refreshInterval: Long var mainRelayer: IRelayerAdapter? val mainRelayerUpdatedSignal: BehaviorSubject<Unit> fun refresh() fun initRelayer() fun clearRelayers() } interface IRelayerAdapter { val refreshInterval: Long val relayerId: Int var myOrders: List<OrderRecord> var myOrdersInfo: List<OrderInfo> val myOrdersSyncSubject: BehaviorSubject<Unit> var buyOrders: RelayerOrdersList<OrderRecord> var sellOrders: RelayerOrdersList<OrderRecord> val allPairs: List<Pair<AssetItem, AssetItem>> val exchangePairs: List<ExchangePair> val pairsSyncSubject: BehaviorSubject<Unit> fun stop() fun calculateBasePrice(coinPair: Pair<String, String>, side: EOrderSide): BigDecimal fun calculateFillAmount( coinPair: Pair<String, String>, side: EOrderSide, amount: BigDecimal ): FillResult fun calculateSendAmount( coinPair: Pair<String, String>, side: EOrderSide, amount: BigDecimal ): FillResult fun fill(fillData: FillOrderData): Flowable<String> fun createOrder(createData: CreateOrderData): Flowable<SignedOrder> fun cancelOrder(order: SignedOrder): Flowable<String> fun batchCancelOrders(orders: List<SignedOrder>): Flowable<String> }
0
Kotlin
13
21
50200c97a9a7a456b588cf132fdb901141efb1d1
2,543
udex-app-android
MIT License
mage/src/main/java/mil/nga/giat/mage/cache/CacheUtils.kt
ngageoint
42,333,816
false
null
package mil.nga.giat.mage.cache import android.content.Context import android.net.Uri import android.os.Environment import mil.nga.geopackage.GeoPackageConstants import mil.nga.geopackage.io.GeoPackageIOUtils import mil.nga.geopackage.validate.GeoPackageValidate import mil.nga.giat.mage.map.cache.CacheProvider import mil.nga.giat.mage.sdk.utils.MediaUtility import java.io.File class CacheUtils( private val context: Context, private val cacheProvider: CacheProvider ) { /** * Copy the Uri to the cache directory in a background task * * @param uri * @param path */ suspend fun copyToCache(uri: Uri, path: String) { // Get a cache directory to write to val cacheDirectory = getApplicationCacheDirectory(context) // Get the Uri display name, which should be the file name with extension var name = MediaUtility.getDisplayName(context, uri, path) // If no extension, add a GeoPackage extension if (GeoPackageIOUtils.getFileExtension(File(name)) == null) { name += "." + GeoPackageConstants.EXTENSION } // Verify that the file is a cache file by its extension val cacheFile = File(cacheDirectory, name) if (isCacheFile(cacheFile)) { if (cacheFile.exists()) { cacheFile.delete() } val cacheName = MediaUtility.getFileNameWithoutExtension(cacheFile) cacheProvider.removeCacheOverlay(cacheName) copyCacheStream(uri, cacheFile, cacheName) } } /** * Determine if the file is a cache file based upon its extension * * @param file potential cache file * @return true if a cache file */ private fun isCacheFile(file: File?): Boolean { return GeoPackageValidate.hasGeoPackageExtension(file) } private suspend fun copyCacheStream(uri: Uri, cacheFile: File, cacheName: String) { context.contentResolver.openInputStream(uri)?.use { input -> cacheFile.outputStream().use { output -> input.copyTo(output) } } cacheProvider.enableAndRefreshTileOverlays(cacheName) } companion object { private var CACHE_DIRECTORY = "caches" /** * Get a writeable cache directory for saving cache files * * @param context * @return file directory or null */ fun getApplicationCacheDirectory(context: Context): File { var directory = context.filesDir val state = Environment.getExternalStorageState() if (Environment.MEDIA_MOUNTED == state) { val externalDirectory = context.getExternalFilesDir(null) if (externalDirectory != null) { directory = externalDirectory } } val cacheDirectory = File(directory, CACHE_DIRECTORY) if (!cacheDirectory.exists()) { cacheDirectory.mkdir() } return cacheDirectory } } }
5
null
21
39
81f71093b498692d99d350c702ea35a583930c68
2,941
mage-android
Apache License 2.0
ksmt-runner/src/main/kotlin/org/ksmt/solver/runner/KSolverState.kt
UnitTestBot
501,947,851
false
null
package org.ksmt.solver.runner import org.ksmt.decl.KConstDecl import org.ksmt.expr.KExpr import org.ksmt.runner.generated.models.SolverConfigurationParam import org.ksmt.sort.KBoolSort import java.util.concurrent.ConcurrentLinkedDeque import java.util.concurrent.ConcurrentLinkedQueue /** * State of an SMT solver. * Allows us to recover the state of the solver after failures. * * The state of the solver: * 1. Solver configuration * 2. Asserted expressions * 3. Assertion level (push commands) * * We don't consider last check-sat result as a solver state. * */ class KSolverState { private sealed interface AssertFrame private data class ExprAssertFrame(val expr: KExpr<KBoolSort>) : AssertFrame private data class AssertAndTrackFrame( val expr: KExpr<KBoolSort>, val trackVar: KConstDecl<KBoolSort> ) : AssertFrame private val configuration = ConcurrentLinkedQueue<SolverConfigurationParam>() /** * Asserted expressions. * Each nested queue contains expressions of the * corresponding assertion level. * */ private val assertFrames = ConcurrentLinkedDeque<ConcurrentLinkedQueue<AssertFrame>>() init { assertFrames.addLast(ConcurrentLinkedQueue()) } fun configure(config: List<SolverConfigurationParam>) { configuration.addAll(config) } fun assert(expr: KExpr<KBoolSort>) { assertFrames.last.add(ExprAssertFrame(expr)) } fun assertAndTrack(expr: KExpr<KBoolSort>, trackVar: KConstDecl<KBoolSort>) { assertFrames.last.add(AssertAndTrackFrame(expr, trackVar)) } fun push() { assertFrames.addLast(ConcurrentLinkedQueue()) } fun pop(n: UInt) { repeat(n.toInt()) { assertFrames.removeLast() } } /** * Recover the solver state via re-applying * all solver state modification operations. * */ suspend fun apply(executor: KSolverRunnerExecutor) { if (configuration.isNotEmpty()) { executor.configureAsync(configuration.toList()) } var firstFrame = true for (frame in assertFrames) { if (!firstFrame) { // Increase the solver assertion scope executor.pushAsync() } firstFrame = false for (assertion in frame) { when (assertion) { is ExprAssertFrame -> executor.assertAsync(assertion.expr) is AssertAndTrackFrame -> executor.assertAndTrackAsync(assertion.expr, assertion.trackVar) } } } } }
9
Kotlin
9
14
aa3c7b2c5db4588f774921e8f32eae25fd5baa3f
2,631
ksmt
Apache License 2.0
features/launches/src/main/java/com/sample/application/features/launches/FiltersInteractionObjects.kt
Raghuramchowdary-tech
363,732,877
false
null
package com.sample.application.features.launches import com.sample.application.base.ControllerEvent import com.sample.application.base.Navigation import com.sample.application.base.UiEvent import com.sample.application.base.UiState import com.sample.application.components.repository.launches.SortOrder import com.sample.application.features.launches.item.launch.AppliedFilters data class FiltersUiState( override val isLoading: Boolean, val showErrorView: Boolean, val filterYearsList: List<String>, val sortOrder: SortOrder, val selectedYearsList: List<String> ) : UiState sealed class FiltersUiEvent : UiEvent { data class OnSortButtonClicked(val appliedFilters: AppliedFilters) : FiltersUiEvent() } sealed class FiltersControllerEvent : ControllerEvent { data class OnCreated(val appliedFilters: AppliedFilters) : FiltersControllerEvent() } sealed class FiltersNavigation : Navigation { data class FilterSubmitted(val appliedFilters: AppliedFilters) : FiltersNavigation() }
0
Kotlin
0
0
76910ece9b3e3ec8627052d20f4c0b93514bbd1e
1,015
Task
Apache License 2.0
app/src/main/java/com/ramanie/rickmorty/presentation/components/CharacterListItem.kt
kennjr
808,172,016
false
{"Kotlin": 51887}
package com.ramanie.rickmorty.presentation.components import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.ramanie.rickmorty.domain.models.DataPoint import com.ramanie.rickmorty.network.domain.models.Character import com.ramanie.rickmorty.presentation.character_episodes.CharacterImageComponent import com.ramanie.rickmorty.presentation.charcter_details.DataPointComponent import com.ramanie.rickmorty.ui.theme.RickAction @Composable fun CharacterListItem(modifier: Modifier = Modifier, character: Character, characterDataPoints: List<DataPoint>, onClick: () -> Unit) { Row( // using the param modifier will allow parent styling to influence this composable modifier = modifier .border( width = 1.dp, brush = Brush.horizontalGradient(listOf(Color.Transparent, RickAction)), shape = RoundedCornerShape(12.dp) ) // we're adding this clip so that the ripple caused by the onclick is of the same shape as the element .clip(RoundedCornerShape(12.dp)) .clickable { onClick() }) { Box { CharacterImageComponent(imageUrl = character.imageUrl, modifier = Modifier.aspectRatio(1f) .clip(RoundedCornerShape(12.dp))) CharacterStatusCircle(characterStatus = character.status, modifier = Modifier.padding(start = 6.dp, top = 6.dp)) } LazyHorizontalGrid(rows = GridCells.Fixed(2), contentPadding = PaddingValues(start = 16.dp, end = 16.dp), content = { items(items = listOf(DataPoint(title = "Name", description = character.name)) + characterDataPoints, key = { it.hashCode() }){ Column(verticalArrangement = Arrangement.Center, modifier = Modifier.padding(end = 16.dp)) { DataPointComponent(dataPoint = it) } } }) } } private fun sanitizeDataPointForDisplay (dataPoint: DataPoint): DataPoint{ val newDescription = if(dataPoint.description.length > 14){ dataPoint.description.take(12) + "..." }else{ dataPoint.description } return dataPoint.copy(description = newDescription) }
0
Kotlin
0
0
54ed8ac6c0ca9a121891777690e4c4c7aeaa7085
3,153
rick-morty
MIT License
les/src/test/kotlin/org/apache/tuweni/les/LESSubProtocolHandlerTest.kt
apache
178,461,625
false
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.tuweni.les import kotlinx.coroutines.runBlocking import org.apache.tuweni.bytes.Bytes import org.apache.tuweni.bytes.Bytes32 import org.apache.tuweni.concurrent.AsyncCompletion import org.apache.tuweni.concurrent.coroutines.await import org.apache.tuweni.crypto.SECP256K1 import org.apache.tuweni.eth.Address import org.apache.tuweni.eth.Block import org.apache.tuweni.eth.BlockBody import org.apache.tuweni.eth.BlockHeader import org.apache.tuweni.eth.Hash import org.apache.tuweni.eth.Transaction import org.apache.tuweni.eth.repository.BlockchainIndex import org.apache.tuweni.eth.repository.BlockchainRepository import org.apache.tuweni.junit.BouncyCastleExtension import org.apache.tuweni.junit.LuceneIndexWriter import org.apache.tuweni.junit.LuceneIndexWriterExtension import org.apache.tuweni.junit.VertxExtension import org.apache.tuweni.kv.MapKeyValueStore import org.apache.tuweni.les.LESSubprotocol.Companion.LES_ID import org.apache.tuweni.rlpx.RLPxService import org.apache.tuweni.rlpx.WireConnectionRepository import org.apache.tuweni.rlpx.wire.DisconnectReason import org.apache.tuweni.rlpx.wire.SubProtocolIdentifier import org.apache.tuweni.units.bigints.UInt256 import org.apache.tuweni.units.ethereum.Gas import org.apache.tuweni.units.ethereum.Wei import org.apache.lucene.index.IndexWriter import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import java.io.IOException import java.net.InetSocketAddress import java.time.Instant import java.time.temporal.ChronoUnit @ExtendWith(BouncyCastleExtension::class, VertxExtension::class, LuceneIndexWriterExtension::class) internal class LESSubProtocolHandlerTest @Throws(IOException::class) constructor() { private val header = BlockHeader( Hash.fromBytes(Bytes32.random()), Hash.fromBytes(Bytes32.random()), Address.fromBytes(Bytes.random(20)), Hash.fromBytes(Bytes32.random()), Hash.fromBytes(Bytes32.random()), Hash.fromBytes(Bytes32.random()), Bytes32.random(), UInt256.fromBytes(Bytes32.random()), UInt256.fromBytes(Bytes32.random()), Gas.valueOf(3), Gas.valueOf(2), Instant.now().truncatedTo(ChronoUnit.SECONDS), Bytes.of(2, 3, 4), Hash.fromBytes(Bytes32.random()), Bytes32.random() ) private val body = BlockBody( listOf( Transaction( UInt256.valueOf(1), Wei.valueOf(2), Gas.valueOf(2), Address.fromBytes(Bytes.random(20)), Wei.valueOf(2), Bytes.random(12), SECP256K1.KeyPair.random() ) ), emptyList() ) private val block = Block(header, body) private class MyRLPxService : RLPxService { var message: Bytes? = null var disconnectReason: DisconnectReason? = null override fun connectTo(peerPublicKey: SECP256K1.PublicKey, peerAddress: InetSocketAddress): AsyncCompletion? { return null } override fun start(): AsyncCompletion? { return null } override fun stop(): AsyncCompletion? { return null } override fun send( subProtocolIdentifier: SubProtocolIdentifier, messageType: Int, connectionId: String, message: Bytes ) { this.message = message } override fun broadcast(subProtocolIdentifier: SubProtocolIdentifier, messageType: Int, message: Bytes) { } override fun disconnect(connectionId: String, reason: DisconnectReason) { this.disconnectReason = reason } override fun repository(): WireConnectionRepository? { return null } } @Test @Throws(Exception::class) fun sendStatusOnNewConnection(@LuceneIndexWriter writer: IndexWriter) = runBlocking { val service = MyRLPxService() val block = Block(header, body) val repo = BlockchainRepository .init( MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), BlockchainIndex(writer), block ) val handler = LESSubProtocolHandler( service, LES_ID, 1, false, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, repo ) handler.handleNewPeerConnection("abc").await() val message = StatusMessage.read(service.message!!) assertNotNull(message) assertEquals(2, message.protocolVersion) assertEquals(UInt256.ZERO, message.flowControlBufferLimit) assertEquals(block.getHeader().getHash(), message.genesisHash) } @Test @Throws(Exception::class) fun receiveStatusTwice(@LuceneIndexWriter writer: IndexWriter) = runBlocking { val status = StatusMessage( 2, 1, UInt256.valueOf(23), Bytes32.random(), UInt256.valueOf(3443), Bytes32.random(), null, UInt256.valueOf(333), UInt256.valueOf(453), true, UInt256.valueOf(3), UInt256.valueOf(4), UInt256.valueOf(5), 0 ).toBytes() val service = MyRLPxService() val repo = BlockchainRepository .init( MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), BlockchainIndex(writer), block ) val handler = LESSubProtocolHandler( service, LES_ID, 1, false, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, repo ) handler.handleNewPeerConnection("abc").await() handler.handle("abc", 0, status).await() assertThrows(IllegalStateException::class.java) { runBlocking { handler.handle("abc", 0, status).await() } } assertEquals(DisconnectReason.PROTOCOL_BREACH, service.disconnectReason) } @Test @Throws(Exception::class) fun receiveOtherMessageBeforeStatus(@LuceneIndexWriter writer: IndexWriter) = runBlocking { val service = MyRLPxService() val repo = BlockchainRepository( MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), BlockchainIndex(writer) ) val handler = LESSubProtocolHandler( service, LES_ID, 1, false, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, repo ) assertThrows(IllegalStateException::class.java) { runBlocking { handler.handle("abc", 2, Bytes.random(2)).await() } } assertEquals(DisconnectReason.PROTOCOL_BREACH, service.disconnectReason) } @Test @Throws(Exception::class) fun receivedGetBlockHeadersMessage(@LuceneIndexWriter writer: IndexWriter) = runBlocking { val service = MyRLPxService() val repo = BlockchainRepository .init( MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), BlockchainIndex(writer), block ) val handler = LESSubProtocolHandler( service, LES_ID, 1, false, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, repo ) val status = StatusMessage( 2, 1, UInt256.valueOf(23), Bytes32.random(), UInt256.valueOf(3443), Bytes32.random(), null, UInt256.valueOf(333), UInt256.valueOf(453), true, UInt256.valueOf(3), UInt256.valueOf(4), UInt256.valueOf(5), 0 ).toBytes() handler.handleNewPeerConnection("abc").await() handler.handle("abc", 0, status).await() handler.handle( "abc", 2, GetBlockHeadersMessage( 1, listOf( GetBlockHeadersMessage.BlockHeaderQuery( Bytes32.random(), UInt256.valueOf(3), UInt256.valueOf(0), GetBlockHeadersMessage.BlockHeaderQuery.Direction.BACKWARDS ) ) ).toBytes() ).await() val blockHeaders = BlockHeadersMessage.read(service.message!!) assertTrue(blockHeaders.blockHeaders.isEmpty()) } @Test @Throws(Exception::class) fun receivedBlockHeadersMessage(@LuceneIndexWriter writer: IndexWriter) = runBlocking { val service = MyRLPxService() val repo = BlockchainRepository .init( MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), BlockchainIndex(writer), block ) val handler = LESSubProtocolHandler( service, LES_ID, 1, false, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, repo ) val status = StatusMessage( 2, 1, UInt256.valueOf(23), Bytes32.random(), UInt256.valueOf(3443), Bytes32.random(), null, UInt256.valueOf(333), UInt256.valueOf(453), true, UInt256.valueOf(3), UInt256.valueOf(4), UInt256.valueOf(5), 0 ).toBytes() val header = BlockHeader( Hash.fromBytes(Bytes32.random()), Hash.fromBytes(Bytes32.random()), Address.fromBytes(Bytes.random(20)), Hash.fromBytes(Bytes32.random()), Hash.fromBytes(Bytes32.random()), Hash.fromBytes(Bytes32.random()), Bytes32.random(), UInt256.fromBytes(Bytes32.random()), UInt256.fromBytes(Bytes32.random()), Gas.valueOf(3), Gas.valueOf(2), Instant.now().truncatedTo(ChronoUnit.SECONDS), Bytes.of(2, 3, 4), Hash.fromBytes(Bytes32.random()), Bytes32.random() ) handler.handleNewPeerConnection("abc").await() handler.handle("abc", 0, status).await() handler.handle("abc", 3, BlockHeadersMessage(1, 2, listOf(header)).toBytes()).await() val retrieved = repo.retrieveBlockHeader(header.getHash()) assertEquals(header, retrieved) } @Test @Throws(Exception::class) fun receivedGetBlockBodiesMessage(@LuceneIndexWriter writer: IndexWriter) = runBlocking { val service = MyRLPxService() val repo = BlockchainRepository .init( MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), BlockchainIndex(writer), block ) val handler = LESSubProtocolHandler( service, LES_ID, 1, false, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, repo ) val status = StatusMessage( 2, 1, UInt256.valueOf(23), Bytes32.random(), UInt256.valueOf(3443), Bytes32.random(), null, UInt256.valueOf(333), UInt256.valueOf(453), true, UInt256.valueOf(3), UInt256.valueOf(4), UInt256.valueOf(5), 0 ).toBytes() handler.handleNewPeerConnection("abc").await() handler.handle("abc", 0, status).await() handler .handle("abc", 4, GetBlockBodiesMessage(1, listOf(Hash.fromBytes(Bytes32.random()))).toBytes()).await() val received = service.message val blockBodies = BlockBodiesMessage.read(received!!) assertTrue(blockBodies.blockBodies.isEmpty()) } @Test @Throws(Exception::class) fun receivedGetReceiptsMessage(@LuceneIndexWriter writer: IndexWriter) = runBlocking { val service = MyRLPxService() val repo = BlockchainRepository .init( MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), MapKeyValueStore(), BlockchainIndex(writer), block ) val handler = LESSubProtocolHandler( service, LES_ID, 1, false, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, UInt256.ZERO, repo ) val status = StatusMessage( 2, 1, UInt256.valueOf(23), Bytes32.random(), UInt256.valueOf(3443), Bytes32.random(), null, UInt256.valueOf(333), UInt256.valueOf(453), true, UInt256.valueOf(3), UInt256.valueOf(4), UInt256.valueOf(5), 0 ).toBytes() handler.handleNewPeerConnection("abc").await() handler.handle("abc", 0, status).await() handler .handle("abc", 4, GetReceiptsMessage(1, listOf(Hash.fromBytes(Bytes32.random()))).toBytes()).await() val received = service.message val receipts = ReceiptsMessage.read(received!!) assertTrue(receipts.receipts.isEmpty()) } }
6
null
78
171
0852e0b01ad126b47edae51b26e808cb73e294b1
13,890
incubator-tuweni
Apache License 2.0
features/feature_search_photo_shared/src/commonMain/kotlin/com/hoc081098/compose_multiplatform_kmpviewmodel_sample/search_photo/presentation/SearchPhotoUiState.kt
hoc081098
675,918,221
false
null
package com.hoc081098.compose_multiplatform_kmpviewmodel_sample.search_photo.presentation import androidx.compose.runtime.Immutable import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.search_photo.domain.SearchPhotoError import com.hoc081098.compose_multiplatform_kmpviewmodel_sample.stable_wrappers.ImmutableWrapper import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.datetime.Instant @Immutable data class SearchPhotoUiState( val photoUiItems: ImmutableList<PhotoUiItem>, val isLoading: Boolean, val error: SearchPhotoError?, val submittedTerm: String?, ) { @Immutable data class PhotoUiItem( val id: String, val slug: String, val createdAt: ImmutableWrapper<Instant>, val updatedAt: ImmutableWrapper<Instant>, val promotedAt: ImmutableWrapper<Instant?>, val width: Int, val height: Int, val thumbnailUrl: String, ) companion object { val INITIAL = SearchPhotoUiState( photoUiItems = persistentListOf(), isLoading = false, error = null, submittedTerm = null, ) } }
11
null
4
8
b5ab12979e96f40ade3b64324e3f8f9f18ea806a
1,147
Compose-Multiplatform-KmpViewModel-Unsplash-Sample
Apache License 2.0
app/src/main/java/com/ilgiz/kitsu/presentation/models/manga/ReviewsLinksUI.kt
ilgiz05
493,248,856
false
null
package com.ilgiz.kitsu.presentation.models.manga import com.ilgiz.kitsu.domain.models.manga.LinksXXXXXXModel data class LinksXXXXXXUI( val self: String, val related: String ) fun LinksXXXXXXModel.toUI() = LinksXXXXXXUI(self, related)
0
Kotlin
0
0
f9d4b4b9899bc2faa3fc992233c3187774d3d8d8
246
kitsuApi
MIT License
sample-compose/app/src/main/java/co/nimblehq/sample/compose/ui/AppDestination.kt
nimblehq
101,353,301
false
{"Kotlin": 379333, "Ruby": 5344, "XSLT": 1824}
package co.nimblehq.sample.compose.ui import androidx.navigation.NamedNavArgument import androidx.navigation.NavType import androidx.navigation.navArgument import co.nimblehq.sample.compose.ui.models.UiModel const val KeyId = "id" const val KeyModel = "model" sealed class AppDestination(val route: String = "") { open val arguments: List<NamedNavArgument> = emptyList() open var destination: String = route open var parcelableArgument: Pair<String, Any?> = "" to null object Up : AppDestination() object Home : AppDestination("home") object Second : AppDestination("second/{$KeyId}") { override val arguments = listOf( navArgument(KeyId) { type = NavType.StringType } ) fun createRoute(id: String) = apply { destination = "second/$id" } } object Third : AppDestination("third") { fun addParcel(value: UiModel) = apply { parcelableArgument = KeyModel to value } } }
33
Kotlin
21
81
df2fc0bbea2112f2aa8e23c625410e241644b57f
998
android-templates
MIT License
src/en/rizzcomic/src/eu/kanade/tachiyomi/extension/en/rizzcomic/RizzComic.kt
keiyoushi
740,710,728
false
null
package eu.kanade.tachiyomi.extension.en.rizzcomic import android.app.Application import androidx.preference.PreferenceScreen import eu.kanade.tachiyomi.lib.randomua.addRandomUAPreferenceToScreen import eu.kanade.tachiyomi.lib.randomua.getPrefCustomUA import eu.kanade.tachiyomi.lib.randomua.getPrefUAType import eu.kanade.tachiyomi.lib.randomua.setRandomUserAgent import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.network.interceptor.rateLimit import eu.kanade.tachiyomi.source.ConfigurableSource import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.util.asJsoup import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import okhttp3.FormBody import okhttp3.Request import okhttp3.Response import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import uy.kohesive.injekt.injectLazy import java.text.SimpleDateFormat import java.util.Locale class RizzComic : HttpSource(), ConfigurableSource { override val name = "Rizz Comic" override val lang = "en" override val baseUrl = "https://rizzcomic.com" override val supportsLatest = true private val json: Json by injectLazy() private val preferences by lazy { Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000) } override val client by lazy { network.cloudflareClient.newBuilder() .setRandomUserAgent( preferences.getPrefUAType(), preferences.getPrefCustomUA(), ) .rateLimit(1, 3) .build() } override fun headersBuilder() = super.headersBuilder() .set("Referer", "$baseUrl/") private val apiHeaders by lazy { headersBuilder() .set("X-Requested-With", "XMLHttpRequest") .build() } private var urlPrefix: String? = null private var genreCache: List<Pair<String, String>> = emptyList() private var attempts = 0 private fun updateCache() { if ((urlPrefix.isNullOrEmpty() || genreCache.isEmpty()) && attempts < 3) { runCatching { val document = client.newCall(GET("$baseUrl/series", headers)) .execute().use { it.asJsoup() } urlPrefix = document.selectFirst(".listupd a") ?.attr("href") ?.substringAfter("/series/") ?.substringBefore("-") genreCache = document.selectFirst(".filter .genrez") ?.select("li") .orEmpty() .map { val name = it.select("label").text() val id = it.select("input").attr("value") Pair(name, id) } } attempts++ } } private fun getUrlPrefix(): String { if (urlPrefix.isNullOrEmpty()) { updateCache() } return urlPrefix ?: throw Exception("Unable to update dynamic urls") } override fun popularMangaRequest(page: Int) = searchMangaRequest(page, "", SortFilter.POPULAR) override fun popularMangaParse(response: Response) = searchMangaParse(response) override fun latestUpdatesRequest(page: Int) = searchMangaRequest(page, "", SortFilter.LATEST) override fun latestUpdatesParse(response: Response) = searchMangaParse(response) override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { if (query.isNotEmpty()) { val form = FormBody.Builder() .add("search_value", query.trim()) .build() return POST("$baseUrl/Index/live_search", apiHeaders, form) } val form = FormBody.Builder().apply { filters.filterIsInstance<FormBodyFilter>().forEach { it.addFormParameter(this) } }.build() return POST("$baseUrl/Index/filter_series", apiHeaders, form) } override fun getFilterList(): FilterList { val filters: MutableList<Filter<*>> = mutableListOf( Filter.Header("Filters don't work with text search"), SortFilter(), StatusFilter(), TypeFilter(), ) filters += if (genreCache.isEmpty()) { listOf( Filter.Separator(), Filter.Header("Press reset to attempt to load genres"), ) } else { listOf( GenreFilter(genreCache), ) } return FilterList(filters) } override fun searchMangaParse(response: Response): MangasPage { updateCache() val result = response.parseAs<List<Comic>>() val entries = result.map { comic -> SManga.create().apply { url = "${comic.slug}#${comic.id}" title = comic.title description = comic.synopsis author = listOfNotNull(comic.author, comic.serialization).joinToString() artist = comic.artist status = comic.status.parseStatus() thumbnail_url = comic.cover?.let { "$baseUrl/assets/images/$it" } genre = buildList { add(comic.type?.capitalize()) comic.genreIds?.onEach { gId -> add(genreCache.firstOrNull { it.second == gId }?.first) } }.filterNotNull().joinToString() initialized = true } } return MangasPage(entries, false) } override fun fetchMangaDetails(manga: SManga): Observable<SManga> { return client.newCall(mangaDetailsRequest(manga)) .asObservableSuccess() .map { mangaDetailsParse(it, manga) } } override fun mangaDetailsRequest(manga: SManga): Request { val slug = manga.url.substringBefore("#") val randomPart = getUrlPrefix() return GET("$baseUrl/series/$randomPart-$slug", headers) } override fun getMangaUrl(manga: SManga): String { val slug = manga.url.substringBefore("#") val urlPart = urlPrefix?.let { "$it-" } ?: "" return "$baseUrl/series/$urlPart$slug" } private fun mangaDetailsParse(response: Response, manga: SManga) = manga.apply { val document = response.use { it.asJsoup() } title = document.selectFirst("h1.entry-title")?.text().orEmpty() artist = document.selectFirst(".tsinfo .imptdt:contains(artist) i")?.ownText() author = listOfNotNull( document.selectFirst(".tsinfo .imptdt:contains(author) i")?.ownText(), document.selectFirst(".tsinfo .imptdt:contains(serialization) i")?.ownText(), ).joinToString() genre = buildList { add( document.selectFirst(".tsinfo .imptdt:contains(type) a") ?.ownText() ?.capitalize(), ) document.select(".mgen a").eachText().onEach { add(it) } }.filterNotNull().joinToString() status = document.selectFirst(".tsinfo .imptdt:contains(status) i")?.text().parseStatus() thumbnail_url = document.selectFirst(".infomanga > div[itemprop=image] img, .thumb img")?.absUrl("src") } private fun String?.parseStatus(): Int = when { this == null -> SManga.UNKNOWN listOf("ongoing", "publishing").any { contains(it, ignoreCase = true) } -> SManga.ONGOING contains("hiatus", ignoreCase = true) -> SManga.ON_HIATUS contains("completed", ignoreCase = true) -> SManga.COMPLETED listOf("dropped", "cancelled").any { contains(it, ignoreCase = true) } -> SManga.CANCELLED else -> SManga.UNKNOWN } override fun chapterListRequest(manga: SManga): Request { val id = manga.url.substringAfter("#") val slug = manga.url.substringBefore("#") return GET("$baseUrl/index/search_chapters/$id#$slug", apiHeaders) } override fun chapterListParse(response: Response): List<SChapter> { val result = response.parseAs<List<Chapter>>() val slug = response.request.url.fragment!! return result.map { SChapter.create().apply { url = "$slug-chapter-${it.name}" name = "Chapter ${it.name}" date_upload = runCatching { dateFormat.parse(it.time!!)!!.time }.getOrDefault(0L) } } } override fun pageListRequest(chapter: SChapter): Request { return GET("$baseUrl/chapter/${getUrlPrefix()}-${chapter.url}", headers) } override fun pageListParse(response: Response): List<Page> { val document = response.use { it.asJsoup() } val chapterUrl = response.request.url.toString() return document.select("div#readerarea img") .mapIndexed { i, img -> Page(i, chapterUrl, img.absUrl("src")) } } override fun imageRequest(page: Page): Request { val newHeaders = headersBuilder() .set("Accept", "image/avif,image/webp,image/png,image/jpeg,*/*") .build() return GET(page.imageUrl!!, newHeaders) } override fun setupPreferenceScreen(screen: PreferenceScreen) { addRandomUAPreferenceToScreen(screen) } override fun mangaDetailsParse(response: Response): SManga { throw UnsupportedOperationException() } override fun imageUrlParse(response: Response): String { throw UnsupportedOperationException() } private inline fun <reified T> Response.parseAs(): T = use { it.body.string() }.let(json::decodeFromString) companion object { private fun String.capitalize() = replaceFirstChar { if (it.isLowerCase()) { it.titlecase(Locale.ROOT) } else { it.toString() } } private val dateFormat by lazy { SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH) } } }
178
null
245
1,027
19ae01034fea0874e76e4e266a040ab57d2af5d4
10,523
extensions-source
Apache License 2.0
data/remote/src/test/java/com/developersancho/remote/service/character/CharacterServiceTest.kt
developersancho
454,045,719
false
null
package com.example.remote.service.character import com.example.remote.service.mock.MockResponses import com.example.model.remote.base.Status import com.example.remote.service.CharacterService import com.example.testutils.BaseServiceTest import com.example.testutils.BuildConfig import kotlinx.coroutines.test.runTest import org.junit.Assert import org.junit.Test class CharacterServiceTest : BaseServiceTest<CharacterService>(CharacterService::class) { override val baseUrl: String get() = BuildConfig.BASE_URL /** * Get Character List */ @Test fun requestLiveGetCharacters() = runTest { val response = serviceLive.getCharacterList(page = 1, options = hashMapOf()) Assert.assertEquals(1, response.results?.first()?.id) Assert.assertEquals("<NAME>", response.results?.first()?.name) Assert.assertEquals(Status.Alive, response.results?.first()?.status) Assert.assertEquals("Male", response.results?.first()?.gender) } @Test fun requestGetCharacters() = runTest { enqueueResponse(MockResponses.GetCharacters.STATUS_200) serviceMock.getCharacterList(page = 1, options = hashMapOf()) val request = mockWebServer.takeRequest() Assert.assertEquals("GET", request.method) Assert.assertEquals("/character?page=1", request.path) } @Test fun responseGetCharacters() = runTest { enqueueResponse(MockResponses.GetCharacters.STATUS_200) val response = serviceMock.getCharacterList(page = 1, options = hashMapOf()) Assert.assertEquals(1, response.results?.first()?.id) Assert.assertEquals("<NAME>", response.results?.first()?.name) Assert.assertEquals(Status.Alive, response.results?.first()?.status) Assert.assertEquals("Male", response.results?.first()?.gender) } /** * Get Character List by Filter */ @Test fun requestLiveGetCharactersByFilter() = runTest { val response = serviceLive.getCharacterList( page = 1, options = hashMapOf( "name" to "rick", "status" to "alive" ) ) Assert.assertEquals(1, response.results?.first()?.id) Assert.assertEquals("<NAME>", response.results?.first()?.name) Assert.assertEquals(Status.Alive, response.results?.first()?.status) Assert.assertEquals("Male", response.results?.first()?.gender) } @Test fun requestGetCharactersByFilter() = runTest { enqueueResponse(MockResponses.GetCharactersByFilter.STATUS_200) serviceMock.getCharacterList( page = 1, options = hashMapOf( "name" to "rick", "status" to "alive" ) ) val request = mockWebServer.takeRequest() Assert.assertEquals("GET", request.method) Assert.assertEquals("/character?page=1&name=rick&status=alive", request.path) } @Test fun responseGetCharactersByFilter() = runTest { enqueueResponse(MockResponses.GetCharactersByFilter.STATUS_200) val response = serviceMock.getCharacterList( page = 1, options = hashMapOf( "name" to "rick", "status" to "alive" ) ) Assert.assertEquals(1, response.results?.first()?.id) Assert.assertEquals("<NAME>", response.results?.first()?.name) Assert.assertEquals(Status.Alive, response.results?.first()?.status) Assert.assertEquals("Male", response.results?.first()?.gender) } /** * Get Character */ @Test fun requestLiveGetCharacter() = runTest { val response = serviceLive.getCharacter(characterId = 1) Assert.assertEquals(1, response.id) Assert.assertEquals("<NAME>", response.name) Assert.assertEquals(Status.Alive, response.status) Assert.assertEquals("Male", response.gender) } @Test fun requestGetCharacter() = runTest { enqueueResponse(MockResponses.GetCharacter.STATUS_200) serviceMock.getCharacter(characterId = 1) val request = mockWebServer.takeRequest() Assert.assertEquals("GET", request.method) Assert.assertEquals("/character/1", request.path) } @Test fun responseGetCharacter() = runTest { enqueueResponse(MockResponses.GetCharacter.STATUS_200) val response = serviceMock.getCharacter(characterId = 1) Assert.assertEquals(1, response.id) Assert.assertEquals("<NAME>", response.name) Assert.assertEquals(Status.Alive, response.status) Assert.assertEquals("Male", response.gender) } }
3
null
33
236
53d96f038e70712387f26a0099949c26a2aa2311
4,696
JetRorty.Android
Apache License 2.0
app/src/main/java/com/masterplus/mesnevi/features/list/data/repo/ListRepoImpl.kt
Ramazan713
615,289,510
false
{"Kotlin": 443947}
package com.masterplus.mesnevi.features.list.data.repo import com.masterplus.mesnevi.features.list.data.mapper.toListEntity import com.masterplus.mesnevi.features.list.data.mapper.toListModel import com.masterplus.mesnevi.features.list.data.services.ListDao import com.masterplus.mesnevi.features.list.domain.model.ListModel import com.masterplus.mesnevi.features.list.domain.repo.ListRepo import javax.inject.Inject class ListRepoImpl @Inject constructor( private val listDao: ListDao ): ListRepo{ override suspend fun insertList(listModel: ListModel): Long { return listDao.insertList(listModel.toListEntity()) } override suspend fun updateList(listModel: ListModel) { listDao.updateList(listModel.toListEntity()) } override suspend fun deleteList(listModel: ListModel) { listDao.deleteList(listModel.toListEntity()) } override suspend fun getMaxPos(): Int { return listDao.getMaxPos() } override suspend fun getListById(listId: Int): ListModel? { return listDao.getListById(listId)?.toListModel() } }
0
Kotlin
0
0
7e29fcb261f1d4b3dc2d23d8ae27f7797da1a2c3
1,093
Mesnevi
Apache License 2.0
mulighetsrommet-api/src/main/kotlin/no/nav/mulighetsrommet/api/domain/dto/TiltaksgjennomforingAdminDto.kt
navikt
435,813,834
false
{"Kotlin": 1190339, "TypeScript": 1006342, "SCSS": 39876, "JavaScript": 24814, "PLpgSQL": 10327, "HTML": 1504, "Dockerfile": 683, "CSS": 437, "Shell": 95}
package no.nav.mulighetsrommet.api.domain.dto import kotlinx.serialization.Serializable import no.nav.mulighetsrommet.domain.constants.ArenaMigrering import no.nav.mulighetsrommet.domain.dbo.TiltaksgjennomforingOppstartstype import no.nav.mulighetsrommet.domain.dto.Faneinnhold import no.nav.mulighetsrommet.domain.dto.Tiltaksgjennomforingsstatus import no.nav.mulighetsrommet.domain.serializers.LocalDateSerializer import no.nav.mulighetsrommet.domain.serializers.LocalDateTimeSerializer import no.nav.mulighetsrommet.domain.serializers.UUIDSerializer import java.time.LocalDate import java.time.LocalDateTime import java.util.* @Serializable data class TiltaksgjennomforingAdminDto( @Serializable(with = UUIDSerializer::class) val id: UUID, val tiltakstype: Tiltakstype, val navn: String, val tiltaksnummer: String?, val arrangor: Arrangor, @Serializable(with = LocalDateSerializer::class) val startDato: LocalDate, @Serializable(with = LocalDateSerializer::class) val sluttDato: LocalDate?, val arenaAnsvarligEnhet: EmbeddedNavEnhet?, val status: Tiltaksgjennomforingsstatus, val apentForInnsok: Boolean, val antallPlasser: Int?, @Serializable(with = UUIDSerializer::class) val avtaleId: UUID?, val administratorer: List<Administrator>, val navEnheter: List<EmbeddedNavEnhet>, val navRegion: EmbeddedNavEnhet?, @Serializable(with = UUIDSerializer::class) val sanityId: UUID?, val oppstart: TiltaksgjennomforingOppstartstype, val opphav: ArenaMigrering.Opphav, @Serializable(with = LocalDateSerializer::class) val stengtFra: LocalDate?, @Serializable(with = LocalDateSerializer::class) val stengtTil: LocalDate?, val kontaktpersoner: List<TiltaksgjennomforingKontaktperson>, val stedForGjennomforing: String?, val faneinnhold: Faneinnhold?, val beskrivelse: String?, @Serializable(with = LocalDateTimeSerializer::class) val createdAt: LocalDateTime, @Serializable(with = LocalDateTimeSerializer::class) val updatedAt: LocalDateTime, val tilgjengeligForVeileder: Boolean, val visesForVeileder: Boolean, @Serializable(with = LocalDateTimeSerializer::class) val fremmoteTidspunkt: LocalDateTime?, val fremmoteSted: String?, ) { fun isAktiv(): Boolean = status in listOf( Tiltaksgjennomforingsstatus.PLANLAGT, Tiltaksgjennomforingsstatus.GJENNOMFORES, ) @Serializable data class Tiltakstype( @Serializable(with = UUIDSerializer::class) val id: UUID, val navn: String, val arenaKode: String, ) @Serializable data class Administrator( val navIdent: String, val navn: String, ) @Serializable data class Arrangor( val organisasjonsnummer: String, val navn: String?, val kontaktperson: VirksomhetKontaktperson?, val slettet: Boolean, ) }
6
Kotlin
1
6
fe8bff93ee98f28ac3f5027aa818cdd1d8093949
2,936
mulighetsrommet
MIT License
appcues/src/main/java/com/appcues/statemachine/states/EndingStepState.kt
appcues
413,524,565
false
{"Kotlin": 1152397, "Shell": 17991, "Ruby": 1503}
package com.appcues.statemachine.states import com.appcues.data.model.Experience import com.appcues.statemachine.Action import com.appcues.statemachine.Action.EndExperience import com.appcues.statemachine.Action.Reset import com.appcues.statemachine.Action.StartStep import com.appcues.statemachine.State import com.appcues.statemachine.Transition import com.appcues.statemachine.effects.AwaitDismissEffect import com.appcues.statemachine.effects.ContinuationEffect import com.appcues.statemachine.effects.PresentationEffect // AwaitDismissEffect works as a ContinuationSideEffect that AppcuesViewModel will // send to the state machine once it's done dismissing the current container // the presence of a non-null value is what tells the UI to dismiss the current container, // and it should be set to null if a dismiss is not requested (i.e. moving to next step in same container) // also when awaitDismissEffect is not null it means that ui/view presenter will remove the container from parentView internal data class EndingStepState( val experience: Experience, val flatStepIndex: Int, val markComplete: Boolean, val awaitDismissEffect: AwaitDismissEffect?, ) : State { override val currentExperience: Experience get() = experience override val currentStepIndex: Int get() = flatStepIndex override fun take(action: Action): Transition? { return when (action) { is EndExperience -> toEndingExperience(action) is StartStep -> toBeginningStep(action) else -> null } } private fun toEndingExperience(action: EndExperience): Transition { return next( state = EndingExperienceState(experience, flatStepIndex, action.markComplete, action.trackAnalytics), sideEffect = ContinuationEffect(Reset) ) } private fun toBeginningStep(action: StartStep): Transition { return next( state = BeginningStepState(experience, action.nextFlatStepIndex, false), sideEffect = PresentationEffect( experience = experience, flatStepIndex = action.nextFlatStepIndex, stepContainerIndex = action.nextStepContainerIndex, shouldPresent = awaitDismissEffect != null ) ) } }
16
Kotlin
3
9
53f1cc2c6c6d27085a39c50510783c1c32c62e58
2,323
appcues-android-sdk
MIT License
src/test/kotlin/g1301_1400/s1382_balance_a_binary_search_tree/SolutionTest.kt
javadev
190,711,550
false
{"Kotlin": 4901773, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1382_balance_a_binary_search_tree import com_github_leetcode.TreeNode import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test internal class SolutionTest { @Test fun balanceBST() { assertThat( Solution() .balanceBST( TreeNode.create(mutableListOf(1, null, 2, null, 3, null, 4, null, null)) ) .toString(), equalTo("2,1,3,null,4") ) } @Test fun balanceBST2() { assertThat( Solution().balanceBST(TreeNode.create(mutableListOf(2, 1, 3))).toString(), equalTo("2,1,3") ) } }
0
Kotlin
20
43
471d45c60f669ea1a2e103e6b4d8d54da55711df
728
LeetCode-in-Kotlin
MIT License
compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/ir/JvmIrBuilder.kt
krzema12
312,049,057
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.backend.jvm.ir import org.jetbrains.kotlin.backend.jvm.JvmBackendContext import org.jetbrains.kotlin.backend.jvm.JvmSymbols import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET import org.jetbrains.kotlin.ir.builders.IrBuilderWithScope import org.jetbrains.kotlin.ir.builders.IrGeneratorContextBase import org.jetbrains.kotlin.ir.builders.Scope import org.jetbrains.kotlin.ir.symbols.IrSymbol // An IR builder with a reference to the JvmBackendContext class JvmIrBuilder( val backendContext: JvmBackendContext, val symbol: IrSymbol, startOffset: Int = UNDEFINED_OFFSET, endOffset: Int = UNDEFINED_OFFSET, ) : IrBuilderWithScope( IrGeneratorContextBase(backendContext.irBuiltIns), Scope(symbol), startOffset, endOffset ) { val irSymbols: JvmSymbols get() = backendContext.ir.symbols } fun JvmBackendContext.createJvmIrBuilder( symbol: IrSymbol, startOffset: Int = UNDEFINED_OFFSET, endOffset: Int = UNDEFINED_OFFSET, ): JvmIrBuilder = JvmIrBuilder(this, symbol, startOffset, endOffset)
34
null
2
24
af0c7cfbacc9fa1cc9bec5c8e68847b3946dc33a
1,278
kotlin-python
Apache License 2.0
markdown/src/test/kotlin/com/appmattus/markdown/filter/SinglePathFilterTest.kt
appmattus
172,489,287
false
{"Kotlin": 248958, "XSLT": 7533}
package com.appmattus.markdown.filter import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatIllegalArgumentException import org.spekframework.spek2.Spek import org.spekframework.spek2.style.gherkin.Feature import java.nio.file.Path import java.nio.file.Paths object SinglePathFilterTest : Spek({ Feature("SinglePathFilter") { Scenario("invalid regex pattern throws an IllegalArgumentException") { lateinit var pattern: String Given("an invalid regex pattern") { pattern = "*." } Then("SinglePathFilter throws an IllegalArgumentException") { assertThatIllegalArgumentException().isThrownBy { SinglePathFilter(pattern) } } } Scenario("empty regex pattern throws an IllegalArgumentException") { lateinit var pattern: String Given("an empty pattern") { pattern = "" } Then("SinglePathFilter throws an IllegalArgumentException") { assertThatIllegalArgumentException().isThrownBy { SinglePathFilter(pattern) } } } Scenario("blank regex pattern throws an IllegalArgumentException") { lateinit var pattern: String Given("a blank pattern") { pattern = " " } Then("SinglePathFilter throws an IllegalArgumentException") { assertThatIllegalArgumentException().isThrownBy { SinglePathFilter(pattern) } } } Scenario("matches relative path") { lateinit var pattern: String lateinit var root: Path lateinit var path: Path Given("a single regex pattern on Unix systems") { pattern = ".*/build/.*" } And("a default root path") { root = Paths.get("").toAbsolutePath() } When("we have a relative path") { path = root.resolve("some/build/path/should/match") } Then("SinglePathFilter matches") { assertThat(SinglePathFilter(pattern).matches(path)).isTrue() } } Scenario("matches relative path with the filter in the beginning") { lateinit var pattern: String lateinit var root: Path lateinit var path: Path Given("a single regex pattern on Unix systems") { pattern = ".*/build/.*" } And("a default root path") { root = Paths.get("").toAbsolutePath() } When("we have a relative path with the filter in the beginning") { path = root.resolve("build/path/should/match") } Then("SinglePathFilter matches") { assertThat(SinglePathFilter(pattern).matches(path)).isTrue() } } Scenario("matches relative path with the filter in the beginning v2") { lateinit var pattern: String lateinit var root: Path lateinit var path: Path Given("a single regex pattern on Unix systems") { pattern = ".*/build/.*" } And("a default root path") { root = Paths.get("").toAbsolutePath() } When("we have a relative path with the filter in the beginning") { path = root.resolve("build/path/should/match") } Then("SinglePathFilter matches") { assertThat(SinglePathFilter(pattern).matches(path)).isTrue() } } Scenario("does not match an unrelated path") { lateinit var pattern: String lateinit var root: Path lateinit var path: Path Given("a single regex pattern on Unix systems") { pattern = ".*/build/.*" } And("a default root path") { root = Paths.get("").toAbsolutePath() } When("we have a path that should not match") { path = root.resolve("this/should/NOT/match") } Then("SinglePathFilter does not match") { assertThat(SinglePathFilter(pattern).matches(path)).isFalse() } } Scenario("does not match the pattern in the root path") { lateinit var pattern: String lateinit var root: Path lateinit var path: Path Given("a single regex pattern on Unix systems") { pattern = ".*/build/.*" } And("a root path with the pattern") { root = Paths.get("/tmp/build/detekt").toAbsolutePath() } When("we have a path that should not match") { path = root.resolve("should/not/match") } Then("SinglePathFilter does not match") { assertThat(SinglePathFilter(pattern, root).matches(path)).isFalse() } } Scenario("does not match the pattern in the absolute path with pattern but the relative path") { lateinit var pattern: String lateinit var root: Path lateinit var path: Path Given("a single regex pattern on Unix systems") { pattern = ".*/build/.*" } And("a root path with the pattern") { root = Paths.get("/tmp/build/detekt").toAbsolutePath() } When("we have a path that should match") { path = root.resolve("should/match/build/path") } Then("SinglePathFilter matches") { assertThat(SinglePathFilter(pattern, root).matches(path)).isTrue() } } Scenario("does not match the pattern in the absolute path without pattern but the relative path") { lateinit var pattern: String lateinit var root: Path lateinit var path: Path Given("a single regex pattern on Unix systems") { pattern = ".*/build/.*" } And("a root path with the pattern") { root = Paths.get("/tmp/detekt").toAbsolutePath() } When("we have a path that should match") { path = root.resolve("should/match/build/path") } Then("SinglePathFilter matches") { assertThat(SinglePathFilter(pattern, root).matches(path)).isTrue() } } } })
9
Kotlin
3
16
18e5bee66b7f38d1df18484e2f8f23a1f9190cf6
6,631
markdown-lint
Apache License 2.0
src/main/kotlin/com/vauthenticator/server/VAuthenticatorApplication.kt
VAuthenticator
191,632,792
false
null
package com.vauthenticator.server import com.vauthenticator.server.events.EventConsumerConfig import com.vauthenticator.server.mail.NoReplyMailConfiguration import com.vauthenticator.server.mfa.OtpConfigurationProperties import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.boot.runApplication import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ModelAttribute @SpringBootApplication @EnableConfigurationProperties( NoReplyMailConfiguration::class, OtpConfigurationProperties::class, EventConsumerConfig::class ) class VAuthenticatorApplication fun main(args: Array<String>) { runApplication<VAuthenticatorApplication>(*args) } @ControllerAdvice class BaseUiModelInjector(@Value("\${assetServer.baseUrl:http://localhost:3000/asset}") private val assetServerBaseUrl: String) { @ModelAttribute("assetServerBaseUrl") fun assetServerBaseUrl() = assetServerBaseUrl }
21
Kotlin
1
8
8847b3b0ed3d9530a85aa1124a8b2fdb634eba2b
1,132
vauthenticator
Apache License 2.0
app/src/main/kotlin/ru/sandello/binaryconverter/model/NumberSystem.kt
jedi1150
153,152,563
false
{"Kotlin": 195067, "Ruby": 3060}
package ru.sandello.binaryconverter.model import ru.sandello.binaryconverter.numsys.NumSys import ru.sandello.binaryconverter.numsys.model.Radix import ru.sandello.binaryconverter.numsys.model.groupLength data class NumberSystem( var value: String, var radix: Radix, var isError: Boolean = false, ) fun ru.sandello.binaryconverter.numsys.model.NumberSystem.asExternalModel() = NumberSystem( value = value, radix = radix, ) fun NumberSystem.asInternalModel() = ru.sandello.binaryconverter.numsys.model.NumberSystem( value, radix, ) fun NumberSystem.pretty(): String = value.split(NumSys.Constants.DELIMITER).joinToString(separator = NumSys.Constants.DELIMITER.toString()) { part -> part.reversed().chunked(asInternalModel().groupLength()).joinToString(NumSys.Constants.GROUP_SEPARATOR.toString()).reversed() }
5
Kotlin
3
14
f51857af84ddd2ecd2d36ebc5e2300fb55c88dff
846
number-systems
MIT License
src/main/java/org/github/otanikotani/workflow/GitHubWorkflowRunComponentFactory.kt
Otanikotani
235,634,673
false
null
package org.github.otanikotani.workflow import com.intellij.execution.impl.ConsoleViewImpl import com.intellij.ide.DataManager import com.intellij.ide.actions.RefreshAction import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actions.ToggleUseSoftWrapsToolbarAction import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.impl.ContextMenuPopupHandler import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Splitter import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.registry.Registry import com.intellij.ui.ListUtil import com.intellij.ui.OnePixelSplitter import com.intellij.ui.PopupHandler import com.intellij.ui.ScrollingUtil import com.intellij.ui.components.JBPanelWithEmptyText import com.intellij.util.ui.UIUtil import org.github.otanikotani.api.GitHubWorkflowRun import org.github.otanikotani.workflow.action.GitHubWorkflowRunActionKeys import org.github.otanikotani.workflow.data.GitHubWorkflowRunDataProvider import org.github.otanikotani.workflow.ui.GitHubWorkflowRunList import org.github.otanikotani.workflow.ui.GitHubWorkflowRunListLoaderPanel import org.github.otanikotani.workflow.ui.GitHubWorkflowRunLogConsole import org.jetbrains.annotations.CalledInAwt import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings import org.jetbrains.plugins.github.pullrequest.ui.GHCompletableFutureLoadingModel import org.jetbrains.plugins.github.pullrequest.ui.GHLoadingModel import org.jetbrains.plugins.github.pullrequest.ui.GHLoadingPanel import org.jetbrains.plugins.github.ui.util.SingleValueModel import org.jetbrains.plugins.github.util.GitRemoteUrlCoordinates import org.jetbrains.plugins.github.util.LazyCancellableBackgroundProcessValue import java.awt.BorderLayout import java.awt.event.ActionListener import java.awt.event.FocusEvent import java.awt.event.FocusListener import javax.swing.JComponent import javax.swing.event.ListDataEvent import javax.swing.event.ListDataListener import javax.swing.event.ListSelectionEvent @Service internal class GitHubWorkflowRunComponentFactory(private val project: Project) { private val progressManager = ProgressManager.getInstance() private val actionManager = ActionManager.getInstance() private val copyPasteManager = CopyPasteManager.getInstance() private val projectUiSettings = GithubPullRequestsProjectUISettings.getInstance(project) private val dataContextRepository = GitHubWorkflowDataContextRepository.getInstance(project) @CalledInAwt fun createComponent(remoteUrl: GitRemoteUrlCoordinates, account: GithubAccount, requestExecutor: GithubApiRequestExecutor, parentDisposable: Disposable): JComponent { val contextDisposable = Disposer.newDisposable() val contextValue = object : LazyCancellableBackgroundProcessValue<GitHubWorkflowRunDataContext>(progressManager) { override fun compute(indicator: ProgressIndicator) = dataContextRepository.getContext(account, requestExecutor, remoteUrl).also { Disposer.register(contextDisposable, it) } } Disposer.register(parentDisposable, contextDisposable) Disposer.register(parentDisposable, Disposable { contextValue.drop() }) val uiDisposable = Disposer.newDisposable() Disposer.register(parentDisposable, uiDisposable) val loadingModel = GHCompletableFutureLoadingModel<GitHubWorkflowRunDataContext>() val contentContainer = JBPanelWithEmptyText(null).apply { background = UIUtil.getListBackground() } loadingModel.addStateChangeListener(object : GHLoadingModel.StateChangeListener { override fun onLoadingCompleted() { val dataContext = loadingModel.result if (dataContext != null) { var content = createContent(dataContext, uiDisposable) if (Registry.`is`("show.log.as.editor.tab")) { content = patchContent(content) } with(contentContainer) { layout = BorderLayout() add(content, BorderLayout.CENTER) validate() repaint() } } } }) loadingModel.future = contextValue.value return GHLoadingPanel(loadingModel, contentContainer, uiDisposable, GHLoadingPanel.EmptyTextBundle.Simple("", "Can't load data from GitHub")).apply { resetHandler = ActionListener { contextValue.drop() loadingModel.future = contextValue.value } } } private fun patchContent(content: JComponent): JComponent { var patchedContent = content val onePixelSplitter = patchedContent as OnePixelSplitter val splitter = onePixelSplitter.secondComponent as Splitter patchedContent = splitter.secondComponent onePixelSplitter.secondComponent = splitter.firstComponent return patchedContent } private fun createContent(context: GitHubWorkflowRunDataContext, disposable: Disposable): JComponent { val listSelectionHolder = GitHubWorkflowRunListSelectionHolder() val workflowRunsList = createWorkflowRunsListComponent(context, listSelectionHolder, disposable) val dataProviderModel = createDataProviderModel(context, listSelectionHolder, disposable) val logLoadingModel = createLogLoadingModel(dataProviderModel, disposable) val logModel = createValueModel(logLoadingModel) val logPanel = createLogPanel(logModel, disposable) val logLoadingPanel = GHLoadingPanel(logLoadingModel, logPanel, disposable, GHLoadingPanel.EmptyTextBundle.Simple("Select workflow run to see the log", "Can't load log")).apply { // errorHandler = GHLoadingErrorHandlerImpl() { dataProviderModel.value?.reloadWorkflowRun() } } val selectionDataContext = GitHubWorkflowRunSelectionContext(context, listSelectionHolder) return OnePixelSplitter("GitHub.Workflows.Component", 0.5f).apply { background = UIUtil.getListBackground() isOpaque = true isFocusCycleRoot = true firstComponent = workflowRunsList secondComponent = logLoadingPanel // .also { // (actionManager.getAction("GitHub.Workflow.Details.Reload") as RefreshAction).registerCustomShortcutSet(it, disposable) // } }.also { // changesBrowser.diffAction.registerCustomShortcutSet(it, disposable) DataManager.registerDataProvider(it) { dataId -> if (Disposer.isDisposed(disposable)) null else when { GitHubWorkflowRunActionKeys.ACTION_DATA_CONTEXT.`is`(dataId) -> selectionDataContext else -> null } } } } private fun createLogPanel(logModel: SingleValueModel<String?>, disposable: Disposable): JBPanelWithEmptyText { val console = GitHubWorkflowRunLogConsole(project, logModel, disposable) val panel = JBPanelWithEmptyText(BorderLayout()).apply { isOpaque = false add(console.component, BorderLayout.CENTER) } installLogPopup(console) val editor = console.editor val consoleActionsGroup = DefaultActionGroup() val reloadAction = actionManager.getAction("Github.Workflow.Log.List.Reload") consoleActionsGroup.add(reloadAction) consoleActionsGroup.add(object : ToggleUseSoftWrapsToolbarAction(SoftWrapAppliancePlaces.CONSOLE) { override fun getEditor(e: AnActionEvent): Editor? { return editor } }) val toolbar = ActionManager.getInstance().createActionToolbar("WorkflowLogConsole", consoleActionsGroup, false) panel.add(toolbar.component, BorderLayout.EAST) logModel.addValueChangedListener { panel.validate() } return panel } private fun createWorkflowRunsListComponent(context: GitHubWorkflowRunDataContext, listSelectionHolder: GitHubWorkflowRunListSelectionHolder, disposable: Disposable): JComponent { val list = GitHubWorkflowRunList(context.listModel).apply { emptyText.clear() }.also { it.addFocusListener(object : FocusListener { override fun focusGained(e: FocusEvent?) { if (it.selectedIndex < 0 && !it.isEmpty) it.selectedIndex = 0 } override fun focusLost(e: FocusEvent?) {} }) installPopup(it) installWorkflowRunSelectionSaver(it, listSelectionHolder) } //Cannot seem to have context menu, when right click, why? val listReloadAction = actionManager.getAction("Github.Workflow.List.Reload") as RefreshAction return GitHubWorkflowRunListLoaderPanel(context.listLoader, listReloadAction, list).apply { errorHandler = GitHubLoadingErrorHandler { context.listLoader.reset() } }.also { listReloadAction.registerCustomShortcutSet(it, disposable) val logActionsGroup = DefaultActionGroup() logActionsGroup.add(listReloadAction) val toolbar = ActionManager.getInstance().createActionToolbar("WorkflowRuns", logActionsGroup, false) it.add(toolbar.component, BorderLayout.WEST) Disposer.register(disposable, Disposable { Disposer.dispose(it) }) } } private fun installWorkflowRunSelectionSaver(list: GitHubWorkflowRunList, listSelectionHolder: GitHubWorkflowRunListSelectionHolder) { var savedSelection: GitHubWorkflowRun? = null list.selectionModel.addListSelectionListener { e: ListSelectionEvent -> if (!e.valueIsAdjusting) { val selectedIndex = list.selectedIndex if (selectedIndex >= 0 && selectedIndex < list.model.size) { listSelectionHolder.selection = list.model.getElementAt(selectedIndex) savedSelection = null } } } list.model.addListDataListener(object : ListDataListener { override fun intervalAdded(e: ListDataEvent) { if (e.type == ListDataEvent.INTERVAL_ADDED) (e.index0..e.index1).find { list.model.getElementAt(it) == savedSelection } ?.run { ApplicationManager.getApplication().invokeLater { ScrollingUtil.selectItem(list, this) } } } override fun contentsChanged(e: ListDataEvent) {} override fun intervalRemoved(e: ListDataEvent) { if (e.type == ListDataEvent.INTERVAL_REMOVED) savedSelection = listSelectionHolder.selection } }) } private fun installPopup(list: GitHubWorkflowRunList) { val popupHandler = object : PopupHandler() { override fun invokePopup(comp: java.awt.Component, x: Int, y: Int) { val popupMenu: ActionPopupMenu = if (ListUtil.isPointOnSelection(list, x, y)) { actionManager .createActionPopupMenu("GithubWorkflowListPopupSelected", actionManager.getAction("Github.Workflow.ToolWindow.List.Popup.Selected") as ActionGroup) } else { actionManager .createActionPopupMenu("GithubWorkflowListPopup", actionManager.getAction("Github.Workflow.ToolWindow.List.Popup") as ActionGroup) } popupMenu.setTargetComponent(list) popupMenu.component.show(comp, x, y) } } list.addMouseListener(popupHandler) } private fun installLogPopup(console: ConsoleViewImpl) { val actionGroup = actionManager.getAction("Github.Workflow.Log.ToolWindow.List.Popup") as ActionGroup val contextMenuPopupHandler = ContextMenuPopupHandler.Simple(actionGroup) (console.editor as EditorEx).installPopupHandler(contextMenuPopupHandler) } private fun createDataProviderModel(context: GitHubWorkflowRunDataContext, listSelectionHolder: GitHubWorkflowRunListSelectionHolder, parentDisposable: Disposable): SingleValueModel<GitHubWorkflowRunDataProvider?> { val model: SingleValueModel<GitHubWorkflowRunDataProvider?> = SingleValueModel(null) fun setNewProvider(provider: GitHubWorkflowRunDataProvider?) { val oldValue = model.value if (oldValue != null && provider != null && oldValue.url != provider.url) { model.value = null } model.value = provider } Disposer.register(parentDisposable, Disposable { model.value = null }) listSelectionHolder.addSelectionChangeListener(parentDisposable) { val provider = listSelectionHolder.selection?.let { context.dataLoader.getDataProvider(it.logs_url) } setNewProvider(provider) } context.dataLoader.addInvalidationListener(parentDisposable) { val selection = listSelectionHolder.selection if (selection != null && selection.logs_url == it) { setNewProvider(context.dataLoader.getDataProvider(selection.logs_url)) } } return model } private fun createLogLoadingModel(dataProviderModel: SingleValueModel<GitHubWorkflowRunDataProvider?>, parentDisposable: Disposable): GHCompletableFutureLoadingModel<String> { val model = GHCompletableFutureLoadingModel<String>() var listenerDisposable: Disposable? = null dataProviderModel.addValueChangedListener { val provider = dataProviderModel.value model.future = provider?.logRequest listenerDisposable = listenerDisposable?.let { Disposer.dispose(it) null } if (provider != null) { val disposable = Disposer.newDisposable().apply { Disposer.register(parentDisposable, this) } provider.addRunChangesListener(disposable, object : GitHubWorkflowRunDataProvider.WorkflowRunChangedListener { override fun logChanged() { model.future = provider.logRequest } }) listenerDisposable = disposable } } return model } private fun <T> createValueModel(loadingModel: GHCompletableFutureLoadingModel<T>): SingleValueModel<T?> { val model = SingleValueModel<T?>(null) loadingModel.addStateChangeListener(object : GHLoadingModel.StateChangeListener { override fun onLoadingCompleted() { model.value = loadingModel.result } override fun onReset() { model.value = loadingModel.result } }) return model } }
12
Kotlin
7
23
f4383b6338eb6487355b4cc4951cafa8165af2ad
16,156
view-github-actions-idea-plugin
MIT License
app/src/main/java/com/lianshang/mvvm/ext/ViewKtx.kt
tangweihong
420,050,275
false
null
package com.lianshang.mvvm.ext import android.animation.Animator import android.animation.IntEvaluator import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.res.Resources import android.os.Build import android.text.method.HideReturnsTransformationMethod import android.text.method.PasswordTransformationMethod import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.Checkable import android.widget.EditText /** * @Author: QuYunShuo * @Time: 2020/9/1 * @Class: ViewKtx * @Remark: View相关的扩展方法 */ /*************************************** View可见性相关 ********************************************/ /** * 隐藏View */ fun View.gone() { visibility = View.GONE } /** * 显示View * @receiver View */ fun View.visible() { visibility = View.VISIBLE } /** * View不可见但存在原位置 */ fun View.invisible() { visibility = View.INVISIBLE } /** * 判断View是不是[View.VISIBLE]状态 */ val View.isVisible: Boolean get() { return visibility == View.VISIBLE } /** * 判断View是不是[View.INVISIBLE]状态 */ val View.isInvisible: Boolean get() { return visibility == View.INVISIBLE } /** * 判断View是不是[View.GONE]状态 */ val View.isGone: Boolean get() { return visibility == View.GONE } val Number.dp: Int get() = (this.toFloat() * Resources.getSystem().displayMetrics.density).toInt() /** * px to dp */ val Number.px: Int get() = (this.toFloat() / Resources.getSystem().displayMetrics.density).toInt() /*************************************** View宽高相关 ********************************************/ /** * 设置View的高度 */ fun View.height(height: Int): View { val params = layoutParams ?: ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) params.height = height layoutParams = params return this } /** * 设置View的宽度 */ fun View.width(width: Int): View { val params = layoutParams ?: ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) params.width = width layoutParams = params return this } /** * 设置View的宽度和高度 * @param width 要设置的宽度 * @param height 要设置的高度 */ fun View.widthAndHeight(width: Int, height: Int): View { val params = layoutParams ?: ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) params.width = width params.height = height layoutParams = params return this } /** * 设置宽度,带有过渡动画 * @param targetValue 目标宽度 * @param duration 时长 * @param action 可选行为 * @return 动画 */ fun View.animateWidth( targetValue: Int, duration: Long = 400, listener: Animator.AnimatorListener? = null, action: ((Float) -> Unit)? = null ): ValueAnimator? { var animator: ValueAnimator? = null post { animator = ValueAnimator.ofInt(width, targetValue).apply { addUpdateListener { width(it.animatedValue as Int) action?.invoke((it.animatedFraction)) } if (listener != null) addListener(listener) setDuration(duration) start() } } return animator } /** * 设置高度,带有过渡动画 * @param targetValue 目标高度 * @param duration 时长 * @param action 可选行为 * @return 动画 */ fun View.animateHeight( targetValue: Int, duration: Long = 400, listener: Animator.AnimatorListener? = null, action: ((Float) -> Unit)? = null ): ValueAnimator? { var animator: ValueAnimator? = null post { animator = ValueAnimator.ofInt(height, targetValue).apply { addUpdateListener { height(it.animatedValue as Int) action?.invoke((it.animatedFraction)) } if (listener != null) addListener(listener) setDuration(duration) start() } } return animator } /** * 设置宽度和高度,带有过渡动画 * @param targetWidth 目标宽度 * @param targetHeight 目标高度 * @param duration 时长 * @param action 可选行为 * @return 动画 */ fun View.animateWidthAndHeight( targetWidth: Int, targetHeight: Int, duration: Long = 400, listener: Animator.AnimatorListener? = null, action: ((Float) -> Unit)? = null ): ValueAnimator? { var animator: ValueAnimator? = null post { val startHeight = height val evaluator = IntEvaluator() animator = ValueAnimator.ofInt(width, targetWidth).apply { addUpdateListener { widthAndHeight( it.animatedValue as Int, evaluator.evaluate(it.animatedFraction, startHeight, targetHeight) ) action?.invoke((it.animatedFraction)) } if (listener != null) addListener(listener) setDuration(duration) start() } } return animator } /*************************************** View其他 ********************************************/ /** * 获取View id,如果没有id:SDK>17, 使用[View.generateViewId];否则使用[View.hashCode] */ @SuppressLint("ObsoleteSdkInt") fun View.getViewId(): Int { var id = id if (id == View.NO_ID) { id = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { View.generateViewId() } else { this.hashCode() } } return id } fun EditText.passwordShowHide(isShow: Boolean) { this.transformationMethod = if (isShow) HideReturnsTransformationMethod.getInstance() else PasswordTransformationMethod.getInstance() //光标会自动到行头,所以重新设置光标位置 this.isFocusable = true this.isFocusableInTouchMode = true this.requestFocus() this.setSelection(this.text.length) }
0
null
0
1
3f259a2b8fe183a7578c626418edd0dc8025fe74
5,758
BaseKotlinMVVM
Apache License 2.0
Base/src/main/java/xy/xy/base/widget/voice/VoiceImageView.kt
xiuone
291,512,847
false
{"Kotlin": 696966, "Java": 245782}
package xy.xy.base.widget.voice import android.content.Context import android.graphics.drawable.AnimationDrawable import android.util.AttributeSet import androidx.appcompat.widget.AppCompatImageView import xy.xy.base.utils.audio.OnPlayListener class VoiceImageView@JvmOverloads constructor(context: Context, attrs: AttributeSet?=null, defStyleAttr:Int = 0) : AppCompatImageView(context, attrs, defStyleAttr) ,OnPlayListener{ override fun onPrepared() { getAnimDrawable()?.start() } override fun onCompletion() { getAnimDrawable()?.stop() } override fun onInterrupt() { getAnimDrawable()?.stop() } override fun onError(error: String?) { getAnimDrawable()?.stop() } override fun onPlaying(curPosition: Long) { getAnimDrawable()?.stop() } private fun getAnimDrawable():AnimationDrawable?{ val animDrawable = background if (animDrawable is AnimationDrawable){ return animDrawable } return null } }
0
Kotlin
1
2
dc9f035dae4c876c6acb3e2e96742d5eb5cebe18
1,039
ajinlib
Apache License 2.0
src/test/kotlin/OneOf.kt
papsign
186,148,881
false
null
import TestServer.setupBaseTestServer import com.fasterxml.jackson.annotation.JsonTypeInfo import com.fasterxml.jackson.annotation.JsonTypeName import com.papsign.ktor.openapigen.annotations.type.`object`.example.ExampleProvider import com.papsign.ktor.openapigen.annotations.type.`object`.example.WithExample import com.papsign.ktor.openapigen.annotations.type.number.integer.clamp.Clamp import com.papsign.ktor.openapigen.annotations.type.number.integer.max.Max import com.papsign.ktor.openapigen.annotations.type.number.integer.min.Min import com.papsign.ktor.openapigen.annotations.type.string.example.DiscriminatorAnnotation import com.papsign.ktor.openapigen.route.apiRouting import com.papsign.ktor.openapigen.route.info import com.papsign.ktor.openapigen.route.path.normal.NormalOpenAPIRoute import com.papsign.ktor.openapigen.route.path.normal.post import com.papsign.ktor.openapigen.route.response.respond import com.papsign.ktor.openapigen.route.route import io.ktor.http.* import io.ktor.server.testing.* import org.junit.Assert import org.junit.jupiter.api.Test fun NormalOpenAPIRoute.SealedRoute() { route("sealed") { post<Unit, Base, Base>( info("Sealed class Endpoint", "This is a Sealed class Endpoint"), exampleRequest = Base.A("Hi"), exampleResponse = Base.A("Hi") ) { params, base -> respond(base) } } } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME) @DiscriminatorAnnotation() sealed class Base { @JsonTypeName("A") @DiscriminatorAnnotation() class A(val str: String) : Base() @JsonTypeName("B") @DiscriminatorAnnotation() class B(@Min(0) @Max(2) val i: Int) : Base() @WithExample @JsonTypeName("C") @DiscriminatorAnnotation() class C(@Clamp(0, 10) val l: Long) : Base() { companion object : ExampleProvider<C> { override val example: C = C(5) } } } val ref = "\$ref" internal class OneOfLegacyGenerationTests { @Test fun willDiscriminatorsBePresent() = withTestApplication({ setupBaseTestServer() apiRouting { SealedRoute() } }) { with(handleRequest(HttpMethod.Get, "//openapi.json")) { Assert.assertEquals(HttpStatusCode.OK, response.status()) Assert.assertTrue( response.content!!.contains( """"Base" : { "discriminator" : { "propertyName" : "type" }, "oneOf" : [ { "$ref" : "#/components/schemas/A" }, { "$ref" : "#/components/schemas/B" }, { "$ref" : "#/components/schemas/C" } ], "properties" : { "type" : { "format" : "string", "nullable" : false, "type" : "string" } }""" ) ) Assert.assertTrue( response.content!!.contains( """"A" : { "discriminator" : { "propertyName" : "type" }, "nullable" : false, "properties" : { "str" : { "nullable" : false, "type" : "string" }, "type" : { "format" : "string", "nullable" : false, "type" : "string" } }, "required" : [ "str" ], "type" : "object" }""" ) ) } } }
24
null
35
172
8362dafa8a8b701983ad7d0119a15a12b863953f
3,448
Ktor-OpenAPI-Generator
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsciagcareersinductionapi/entity/AchievedFunctionalLevel.kt
ministryofjustice
620,258,376
false
null
package uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.entity import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.FunctionalAssessment import uk.gov.justice.digital.hmpps.hmppsciagcareersinductionapi.data.common.FunctionalAssessmentLevel import java.time.LocalDateTime import javax.persistence.Embeddable @Embeddable data class AchievedFunctionalLevel( var functionalAssessment: FunctionalAssessment?, var functionalAssessmentLevel: FunctionalAssessmentLevel?, var achievedDate: LocalDateTime?, )
0
Kotlin
0
0
b42545a6d27e61a51525d266e3ccc91f39afb2e7
541
hmpps-ciag-careers-induction-api
MIT License
modules/feature/bars/impl/src/main/kotlin/kekmech/ru/feature_bars_impl/launcher/BarsFeatureLauncherImpl.kt
tonykolomeytsev
203,239,594
false
{"Kotlin": 972736, "JavaScript": 9100, "Python": 2365, "Shell": 46}
package kekmech.ru.feature_bars_impl.launcher import kekmech.ru.feature_bars_api.BarsFeatureLauncher import kekmech.ru.feature_bars_impl.presentation.screen.main.BarsFragment internal class BarsFeatureLauncherImpl : BarsFeatureLauncher { override fun launchMain() = BarsFragment() }
19
Kotlin
4
41
15c3c17e33d0ffffc0e269ad0cd6fe47b0bc971a
290
mpeiapp
MIT License
src/test/kotlin/no/skatteetaten/aurora/boober/feature/BuildFeatureTest.kt
furode
395,321,155
true
{"Kotlin": 1004371, "Shell": 424}
package no.skatteetaten.aurora.boober.feature import org.apache.commons.lang3.RandomStringUtils import org.junit.jupiter.api.Test import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isNull import io.fabric8.openshift.api.model.DeploymentConfig import io.fabric8.openshift.api.model.ImageStream import no.skatteetaten.aurora.boober.utils.AbstractFeatureTest import no.skatteetaten.aurora.boober.utils.singleApplicationError class BuildFeatureTest : AbstractFeatureTest() { override val feature: Feature get() = BuildFeature("test.docker.com") @Test fun `should disable feature if deploy type`() { val adc = createAuroraDeploymentContext() assertThat(adc.features.isEmpty()) } @Test fun `should get error if groupId is missing`() { assertThat { createAuroraDeploymentContext( """{ "type": "development", "version" : "1" }""" ) }.singleApplicationError("GroupId must be set and be shorter then 200 characters.") } @Test fun `should get error if groupId is too long`() { val groupId = RandomStringUtils.randomAlphanumeric(201) assertThat { createAuroraDeploymentContext( """{ "type": "development", "version" : "1", "groupId" : "$groupId" }""" ) }.singleApplicationError("GroupId must be set and be shorter then 200 characters.") } @Test fun `should get error if version is not set`() { assertThat { createAuroraDeploymentContext( """{ "type": "development", "groupId" : "org.test" }""" ) }.singleApplicationError("Version must be a 128 characters or less, alphanumeric and can contain dots and dashes.") } @Test fun `should generate build and modify imageStream with default values`() { val (dcResources, isResource, bcResource) = generateResources( """{ "type": "development", "groupId": "org.test", "version" : "1" }""", createEmptyDeploymentConfig(), createEmptyImageStream() ) assertThat(bcResource).auroraResourceCreatedByThisFeature() .auroraResourceMatchesFile("bc.json") val deploymentConfig = dcResources.resource as DeploymentConfig val trigger = deploymentConfig.spec.triggers.first() assertThat(dcResources).auroraResourceModifiedByThisFeatureWithComment("Change imageChangeTrigger to follow latest") assertThat(trigger.type).isEqualTo("ImageChange") assertThat(trigger.imageChangeParams.from.name).isEqualTo("simple:latest") assertThat(isResource).auroraResourceModifiedByThisFeatureWithComment("Remove spec from imagestream") val imageStream = isResource.resource as ImageStream assertThat(imageStream.spec).isNull() } @Test fun `test render spec for minimal build`() { val spec = createAuroraDeploymentSpecForFeature( """{ "type": "development", "groupId": "org.test", "version" : "1" }""" ) assertThat(spec).auroraDeploymentSpecMatches("spec-default.json") } }
0
null
0
0
ccd89bc227d44f2fe3ad8a64224ac8dd19175289
3,341
boober
Apache License 2.0
tmp/results/JVM-Xnew-inference/BACKEND_csrbf.kt
mandelshtamd
346,008,310
false
{"Markdown": 122, "Gradle": 762, "Gradle Kotlin DSL": 649, "Java Properties": 23, "Shell": 49, "Ignore List": 20, "Batchfile": 26, "Git Attributes": 8, "Kotlin": 82508, "Protocol Buffer": 12, "Java": 6674, "Proguard": 12, "XML": 1698, "Text": 13298, "INI": 221, "JavaScript": 294, "JAR Manifest": 2, "Roff": 217, "Roff Manpage": 38, "JSON": 199, "HTML": 2429, "AsciiDoc": 1, "YAML": 21, "EditorConfig": 1, "OpenStep Property List": 19, "C": 79, "Objective-C": 68, "C++": 169, "Swift": 68, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 12, "Groovy": 45, "Dockerfile": 3, "Diff": 1, "EJS": 1, "CSS": 6, "Ruby": 6, "SVG": 50, "JFlex": 3, "Maven POM": 107, "JSON with Comments": 9, "Ant Build System": 53, "Graphviz (DOT)": 78, "Scala": 1}
interface T val t = object : T { val foo by foo }
1
null
1
1
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
67
kotlinWithFuzzer
Apache License 2.0
analysis/analysis-test-framework/tests/org/jetbrains/kotlin/analysis/test/framework/project/structure/KtModuleFactory.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.test.framework.project.structure import com.intellij.openapi.project.Project import org.jetbrains.kotlin.analysis.api.standalone.base.project.structure.KtModuleWithFiles import org.jetbrains.kotlin.test.model.TestModule import org.jetbrains.kotlin.test.services.TestService import org.jetbrains.kotlin.test.services.TestServices fun interface KtModuleFactory : TestService { fun createModule(testModule: TestModule, testServices: TestServices, project: Project): KtModuleWithFiles } val TestServices.ktModuleFactory: KtModuleFactory by TestServices.testServiceAccessor()
162
null
5729
46,436
c902e5f56504e8572f9bc13f424de8bfb7f86d39
825
kotlin
Apache License 2.0
game/core/src/com/lyeeedar/AI/Tasks/TaskInterrupt.kt
Lyeeedar
257,323,195
false
null
package com.lyeeedar.AI.Tasks import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.utils.Pool import com.lyeeedar.Components.* import com.lyeeedar.Systems.World import com.lyeeedar.Util.AssetManager import com.lyeeedar.Util.Colour import com.lyeeedar.Util.Localisation import squidpony.squidmath.LightRNG class TaskInterrupt : AbstractTask() { override fun execute(e: Entity, world: World<*>, rng: LightRNG) { var interrupted = false val activeAbility = e.actionSequence() if (activeAbility != null && activeAbility.actionSequence.cancellable) { activeAbility.actionSequence.cancel(activeAbility.actionSequenceState) e.removeComponent(ComponentType.ActionSequence) interrupted = true } val combo = e.combo() if (combo?.currentStep != null) { combo.currentStep = null combo.lastTarget = null combo.fixedDirection = null interrupted = true } val stunParticle = AssetManager.loadParticleEffect("StatusAndEffects/Stunned").getParticleEffect() stunParticle.addToWorld(world, e.position()!!.position, Vector2(0f, 0.8f), isBlocking = false) val message = if (interrupted) Localisation.getText("interrupted", "UI") else Localisation.getText("stunned", "UI") e.statistics()?.addMessage(message, Colour.YELLOW, 0.4f) } var obtained: Boolean = false companion object { private val pool: Pool<TaskInterrupt> = object : Pool<TaskInterrupt>() { override fun newObject(): TaskInterrupt { return TaskInterrupt() } } @JvmStatic fun obtain(): TaskInterrupt { val anim = pool.obtain() if (anim.obtained) throw RuntimeException() anim.obtained = true return anim } } override fun free() { if (obtained) { pool.free(this); obtained = false } } }
0
Kotlin
0
0
5068af2489fa6ff52a99016bceafca5690864754
1,733
PortalClosers
Apache License 2.0
app/src/main/java/com/ukuapps/comidastati/presentation/login/signIn/SignInPresenter.kt
joansilva86
221,337,054
false
null
package com.ukuapps.comidastati.presentation.login.signIn import com.ukuapps.comidastati.domain.login.LoginInteractorI import com.ukuapps.comidastati.domain.login.SignInException import com.ukuapps.comidastati.presentation.base.BasePresenter import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import javax.inject.Inject import kotlin.coroutines.CoroutineContext class SignInPresenter @Inject constructor(private var interactor: LoginInteractorI) : BasePresenter(), CoroutineScope { private val job = Job() override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job private var view: SignInView? = null override fun attach(view: Any) { this.view = view as SignInView } override fun detach() { view = null } fun signIn(model: SignInModel) { if (validate(model)) return launch { try { view?.showProgressBar() interactor.signIn(model) view?.goToMain() } catch (ex: SignInException) { view?.cleanPassword() view?.showError(ex.toString()) view?.cleanPassword() view?.hideProgressBar() } } } fun validate(model: SignInModel): Boolean { if (model.email.isEmpty()) { view?.mailEmpty() } if (!model.emailIsValid) { view?.emailNoMatch() } if (model.password.isEmpty()) { view?.passwordEmpty() } if (!model.isValid) return true return false } }
0
Kotlin
0
0
880f43773c18471c670d835c149e409a850b7905
1,723
comidasTati
MIT License
app/src/main/java/com/qingmei2/sample/common/loadings/CommonLoadingViewModel.kt
msdgwzhy6
157,537,516
true
{"Kotlin": 112168}
package com.qingmei2.sample.common.loadings import android.arch.lifecycle.LifecycleOwner import android.arch.lifecycle.MutableLiveData import com.qingmei2.rhine.ext.viewmodel.addLifecycle import com.qingmei2.sample.base.BaseViewModel @Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") class CommonLoadingViewModel private constructor() : BaseViewModel(), ILoadingDelegate { private val state: MutableLiveData<CommonLoadingState> = MutableLiveData() override fun loadingState(): MutableLiveData<CommonLoadingState> = state override fun applyState(state: CommonLoadingState) { this.state.postValue(state) } companion object { fun instance(lifecycleOwner: LifecycleOwner) = CommonLoadingViewModel().apply { addLifecycle(lifecycleOwner) } } }
0
Kotlin
0
1
ac829cbef19a105ce34589cda89c6c397386b60d
829
MVVM-Rhine
Apache License 2.0