path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app-kit/src/main/java/media/pixi/appkit/ui/signup/SignUpActivity.kt
|
NateWickstrom
| 166,901,841
| false
| null |
package media.pixi.appkit.ui.signup
import android.os.Bundle
import dagger.android.support.DaggerAppCompatActivity
import kotlinx.android.synthetic.main.appkit__appbar.*
import media.pixi.appkit.R
import media.pixi.appkit.utils.ActivityUtils
import javax.inject.Inject
class SignUpActivity : DaggerAppCompatActivity() {
lateinit var fragment: SignUpFragment
@Inject set
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.appkit__activity)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
ActivityUtils.addFragmentToActivity(
supportFragmentManager, fragment, R.id.contentFrame
)
}
}
| 0
|
Kotlin
|
0
| 0
|
67e3f5cb6e1d0d7ed12002408325823ce1772492
| 759
|
android-rx-firebase-app-kit
|
Apache License 2.0
|
tmp/arrays/youTrackTests/7099.kt
|
DaniilStepanov
| 228,623,440
| false
| null |
// Original bug: KT-28421
interface A {
fun foo() {}
}
interface B {
fun foo() {}
}
fun some(ab: Any) {
if (ab is A && ab is B) {
ab.foo() // Why it's not an ambiguity?
}
}
| 1
| null |
1
| 1
|
602285ec60b01eee473dcb0b08ce497b1c254983
| 200
|
bbfgradle
|
Apache License 2.0
|
idea/testData/multiModuleQuickFix/importCommonFunInJvm/common/a.kt
|
JakeWharton
| 99,388,807
| false
| null |
package foo
fun foo() {
}
| 0
| null |
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 28
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/alarm/alARm_you_need/ArPreviewActivity.kt
|
tofhddl9
| 276,293,107
| false
|
{"Java": 152319, "Kotlin": 85353, "GLSL": 23811}
|
package com.alarm.alARm_you_need
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.google.ar.core.AugmentedImage
import com.google.ar.core.TrackingState
import com.google.ar.core.examples.java.common.helpers.CameraPermissionHelper
import com.google.ar.core.examples.java.common.helpers.SnackbarHelper
import com.google.ar.sceneform.FrameTime
import kotlinx.android.synthetic.main.activity_augmented_image.*
import java.util.HashMap
class ArPreviewActivity : AppCompatActivity() {
private var arFragment: AugmentedImageFragment? = null
private val augmentedImageMap: MutableMap<AugmentedImage, AugmentedImageNode> = HashMap()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d("DEBUGGING LOG", "ArPreview::onCreate is called")
setContentView(R.layout.activity_augmented_image)
val targetImageUri = intent.getStringExtra("IMAGE_URI")
arFragment = supportFragmentManager.findFragmentById(R.id.ux_fragment) as AugmentedImageFragment
arFragment!!.setAugmentedTargetImage(Uri.parse(targetImageUri))
arFragment!!.arSceneView.scene.addOnUpdateListener { frameTime: FrameTime ->
onUpdateFrame(frameTime)
}
init_btn.visibility = View.GONE
}
override fun onDestroy() {
super.onDestroy()
SnackbarHelper.getInstance().hide(this)
}
override fun onResume() {
super.onResume()
Log.d("DEBUGGING LOG", "ArPreviewActivity::onResume is called")
if (!CameraPermissionHelper.hasCameraPermission(this)) {
CameraPermissionHelper.requestCameraPermission(this)
}
if (augmentedImageMap.isEmpty()) {
image_view_fit_to_scan?.visibility = View.VISIBLE
}
}
private fun onUpdateFrame(frameTime: FrameTime) {
val frame = arFragment!!.arSceneView.arFrame
if (frame == null || frame.camera.trackingState != TrackingState.TRACKING) {
return
}
val updatedAugmentedImages =
frame.getUpdatedTrackables(AugmentedImage::class.java)
for (augmentedImage in updatedAugmentedImages) {
when (augmentedImage.trackingState) {
TrackingState.PAUSED -> {
val text = "곧 미로가 생성됩니다. 이 이미지는 사용할 수 있습니다."
SnackbarHelper.getInstance().showMessage(this, text)
}
TrackingState.TRACKING -> {
image_view_fit_to_scan.visibility = View.GONE
if (!augmentedImageMap.containsKey(augmentedImage)) {
val node = AugmentedImageNode(this)
node.setImage(augmentedImage, true)
augmentedImageMap[augmentedImage] = node
arFragment!!.arSceneView.scene.addChild(node)
}
}
}
}
}
}
| 2
| null |
1
| 1
|
bf4f93bda388d4f19c2c3201c783cefdf1aaa4de
| 3,033
|
alARm-you-need
|
Apache License 2.0
|
Kotlin/Code/Kotlin-Coroutines/src/main/kotlin/core/select/01_SelectingFromChannels.kt
|
hiloWang
| 203,300,702
| false
| null |
package core.select
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.selects.select
/*
select 表达式可以同时等待多个挂起函数,并选择 第一个可用的。(这个有点类似于 NIO 中的 Selector)
在通道中 select,使用 receive 挂起函数,我们可以从两个通道接收 其中一个 的数据。 但是 select 表达式允许我们使用其 onReceive 子句 同时 从两者接收
*/
private fun CoroutineScope.fizz() = produce<String> {
while (true) { // sends "Fizz" every 300 ms
delay(300)
send("Fizz")
}
}
private fun CoroutineScope.buzz() = produce<String> {
while (true) { // sends "Buzz!" every 500 ms
delay(500)
send("Buzz!")
}
}
private suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) {
select<Unit> {
// <Unit> means that this select expression does not produce any result
fizz.onReceive { value ->
// this is the first select clause
println("fizz -> '$value'")
}
buzz.onReceive { value ->
// this is the second select clause
println("buzz -> '$value'")
}
}
}
fun main() = runBlocking<Unit> {
//sampleStart
val fizz = fizz()
val buzz = buzz()
repeat(7) {
selectFizzBuzz(fizz, buzz)
}
coroutineContext.cancelChildren() // cancel fizz & buzz coroutines
//sampleEnd
}
| 0
| null |
15
| 4
|
64a637a86f734e4e80975f4aa93ab47e8d7e8b64
| 1,477
|
notes
|
Apache License 2.0
|
Code/Shared/src/commonMain/kotlin/org/chrishatton/example/model/UUID.kt
|
chris-hatton
| 196,953,459
| false
| null |
package org.chrishatton.example.model
expect class UUID
| 1
|
Kotlin
|
3
| 18
|
26dc1b5b1df888167f0b4af7fd74b039a4a574c3
| 57
|
kotlin-multiplatform-template
|
MIT License
|
idea/testData/copyPaste/conversion/ConversionInCorrectContext.dependency.kt
|
JakeWharton
| 99,388,807
| true
| null |
class Dependency {
fun getInt(): Int = 1
}
| 0
|
Kotlin
|
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 46
|
kotlin
|
Apache License 2.0
|
analysis/analysis-api/testData/components/resolver/singleByPsi/withErrors/variableWithInvokeFunctionCall_extensionReceiver.kt
|
JetBrains
| 3,432,266
| false
| null |
operator fun Int.invoke() {}
class A {
fun test() {
<expr>f()</expr>
}
}
val A.f: Int = 1
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 107
|
kotlin
|
Apache License 2.0
|
proto/src/main/java/com/hik/proto/utils/thread/pool/DefaultThreadPool.kt
|
DeveloperLinus
| 538,288,229
| false
|
{"Java": 343699, "Kotlin": 118261}
|
/*
* Copyright 2020-present hikvision
*
* 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.hik.proto.utils.thread.pool
import java.util.concurrent.*
/**
* Created by linzijian on 2021/2/21.
* 指定数量的核心线程和工作线程5秒存活时间
* 可用于一般异步任务处理
*/
class DefaultThreadPool(private val mCoreSize: Int, private val mMaximumSize: Int) {
@Volatile
private var mExecutor: ThreadPoolExecutor? = null
private fun initThreadPoolExecutor() {
if (mExecutor == null || mExecutor!!.isShutdown || mExecutor!!.isTerminated) {
synchronized(DefaultThreadPool::class.java) {
if (mExecutor == null || mExecutor!!.isShutdown || mExecutor!!.isTerminated) {
val keepAliveTime: Long = 5000
val unit = TimeUnit.MILLISECONDS
val blockingQueue: BlockingQueue<Runnable> = LinkedBlockingDeque()
val threadFactory = Executors.defaultThreadFactory()
val handler: RejectedExecutionHandler = ThreadPoolExecutor.DiscardPolicy()
mExecutor = ThreadPoolExecutor(
mCoreSize,
mMaximumSize, keepAliveTime,
unit, blockingQueue, threadFactory, handler
)
}
}
}
}
fun execute(task: Runnable?) {
initThreadPoolExecutor()
mExecutor!!.execute(task)
}
fun submit(task: Runnable?): Future<*> {
initThreadPoolExecutor()
return mExecutor!!.submit(task)
}
fun remove(task: Runnable?) {
initThreadPoolExecutor()
mExecutor!!.remove(task)
}
}
| 1
| null |
1
| 1
|
abc54ce42e65acb9f135006a5ac1f297b555f132
| 2,173
|
HEOP_DEMO_V3.1.0_personSource
|
MIT License
|
spring-data-requery-kotlin/src/test/kotlin/org/springframework/data/requery/kotlin/QueryElementExtensionsTest.kt
|
debop
| 188,192,108
| false
|
{"Java": 915808, "Kotlin": 629888}
|
/*
* Copyright 2018 Coupang 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 org.springframework.data.requery.kotlin
import io.requery.query.Limit
import io.requery.query.Offset
import io.requery.query.Order
import io.requery.query.OrderingExpression
import io.requery.query.element.QueryElement
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.data.requery.kotlin.domain.AbstractDomainTest
import org.springframework.data.requery.kotlin.domain.sample.User
/**
* org.springframework.data.requery.QueryElementExtensionsTest
*
* @author debop
*/
@SuppressWarnings("UNCHECKED_CAST")
class QueryElementExtensionsTest : AbstractDomainTest() {
@Test
fun `apply sort to QueryElement`() {
val sort = Sort.by(Sort.Order.desc("firstname"), Sort.Order.asc("lastname"))
val query = kotlinDataStore.select(User::class).applySort(User::class.java, sort)
assertThat(query.orderByExpressions).hasSize(2)
assertThat(query.orderByExpressions.map { it.name }).containsOnly("firstname", "lastname")
assertThat(query.orderByExpressions.map { it as OrderingExpression<*> }.map { it.order }).containsExactly(Order.DESC, Order.ASC)
}
@Test
fun `apply pageable to QueryElement`() {
val pageable = PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "firstname", "lastname"))
val query = kotlinDataStore.select(User::class).applyPageable(User::class.java, pageable)
assertThat(query).isInstanceOf(QueryElement::class.java)
assertThat(query).isInstanceOf(Limit::class.java)
assertThat(query).isInstanceOf(Offset::class.java)
assertThat(query.offset).isEqualTo(pageable.offset)
assertThat(query.limit).isEqualTo(pageable.pageSize)
assertThat(query.orderByExpressions).hasSize(2)
assertThat(query.orderByExpressions.map { it.name }).containsOnly("firstname", "lastname")
assertThat(query.orderByExpressions.map { it as OrderingExpression<*> }.map { it.order }).containsOnly(Order.DESC)
}
@Test
fun `get OrderingExpression from Entity`() {
val sort = Sort.by(Sort.Order.desc("firstname"), Sort.Order.asc("lastname"))
val orderExprs = User::class.java.getOrderingExpressions(sort)
assertThat(orderExprs).hasSize(2)
assertThat(orderExprs[0].name).isEqualTo("firstname")
assertThat(orderExprs[0].order).isEqualTo(Order.DESC)
assertThat(orderExprs[1].name).isEqualTo("lastname")
assertThat(orderExprs[1].order).isEqualTo(Order.ASC)
}
}
| 1
|
Java
|
1
| 5
|
80ff3671fccfe98cee8aa22418923237f2e9ce2f
| 3,206
|
spring-data-requery
|
Apache License 2.0
|
app/src/main/java/com/bounhackers/wowservice/profileedit/ProfileEditContract.kt
|
BounHackers
| 159,948,954
| false
|
{"Gradle": 3, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "Kotlin": 40, "XML": 28, "Java": 1}
|
package com.bounhackers.wowservice.profileedit
import com.bounhackers.wowservice.base.BaseContract
class ProfileEditContract {
interface View: BaseContract.View {
}
interface Presenter: BaseContract.Presenter<View> {
}
}
| 1
| null |
1
| 1
|
f68332a5aa5dfb95ab9b446b4d0839f70dc5951a
| 241
|
servisim-app
|
MIT License
|
app/src/main/java/com/dujiajun/courseblock/constant/PreferenceKey.kt
|
dujiajun
| 178,798,441
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "YAML": 1, "Proguard": 2, "XML": 58, "Kotlin": 43, "INI": 1, "Java": 6}
|
package com.dujiajun.courseblock.constant
class PreferenceKey {
companion object {
const val FIRST_MONDAY = "first_monday"
const val LAST_SUNDAY = "last_sunday"
const val REFERER = "referer"
const val CURRENT_TERM = "cur_term"
const val CURRENT_YEAR = "cur_year"
const val STATUS = "status"
const val SHOW_WEEKEND = "show_weekend"
const val SHOW_NOT_CUR_WEEK = "show_not_cur_week"
const val SHOW_COURSE_TIME = "show_course_time"
const val USE_CHI_ICON = "use_chi_icon"
}
}
| 6
|
Kotlin
|
2
| 24
|
c79597cdd69cf788f06e12643f616e51fbf0bb4e
| 563
|
CourseBlock
|
MIT License
|
src/test/java/nl/jovmit/lyrics/domain/search/SearchServiceShould.kt
|
mitrejcevski
| 274,624,763
| false
| null |
package nl.jovmit.lyrics.domain.search
import nl.jovmit.lyrics.domain.songs.SongRepository
import nl.jovmit.lyrics.domain.users.UnknownUserException
import nl.jovmit.lyrics.domain.users.UserRepository
import nl.jovmit.lyrics.infrastructure.builder.SongBuilder.Companion.aSong
import nl.jovmit.lyrics.infrastructure.builder.UserBuilder.Companion.aUser
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.BDDMockito.given
import org.mockito.Mock
import org.mockito.junit.jupiter.MockitoExtension
@ExtendWith(MockitoExtension::class)
class SearchServiceShould {
private val tom = aUser().build()
private val keyword = "ye"
private val titleMatchingSong = aSong().withTitle("Yesterday").build()
private val performerMatchingSong = aSong().withPerformer("Billye").build()
private val lyricsMatchingSong = aSong().withLyrics("Lyrics bye bye").build()
private val anotherSong = aSong().build()
private val allSongs = listOf(
titleMatchingSong,
lyricsMatchingSong,
performerMatchingSong,
anotherSong
)
@Mock
private lateinit var songRepository: SongRepository
@Mock
private lateinit var userRepository: UserRepository
private lateinit var searchService: SearchService
@BeforeEach
fun setUp() {
searchService = SearchService(songRepository, userRepository)
}
@Test
fun return_a_list_of_songs_containing_search_keyword() {
given(userRepository.hasUserWithId(tom.id)).willReturn(true)
given(songRepository.songsFor(tom.id)).willReturn(allSongs)
val result = searchService.searchSongs(tom.id, keyword)
assertThat(result).containsExactlyInAnyOrder(titleMatchingSong, performerMatchingSong, lyricsMatchingSong)
}
@Test
fun throw_exception_when_unknown_user_performs_a_search() {
given(userRepository.hasUserWithId(tom.id)).willReturn(false)
assertThrows<UnknownUserException> {
searchService.searchSongs(tom.id, keyword)
}
}
}
| 1
| null |
1
| 1
|
32bccdc270f5a6e4351f9aa2d03d1c73aab08498
| 2,202
|
lyrics-backend
|
Apache License 2.0
|
kotlin/src/test/kotlin/api/ColorSpec.kt
|
fossabot
| 191,747,173
| true
|
{"YAML": 1, "Gradle": 11, "Shell": 2, "EditorConfig": 1, "Markdown": 1, "Git Attributes": 1, "Batchfile": 1, "Text": 30, "Ignore List": 1, "Python": 26, "INI": 2, "AsciiDoc": 10, "C++": 8, "C": 20, "Kotlin": 36, "Groovy": 139, "Java": 306}
|
package api
import com.google.common.truth.Truth.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.context
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
object ColorSpec : Spek({
describe("Color Enum") {
context("'valueOf' String") {
it("should 'valueOf' should handle colors") {
assertThat(Color.valueOf("BLUE")).isEqualTo(Color.BLUE)
}
}
context("'values' size") {
it("should only have 3 colors") {
assertThat(Color.values().size).isEqualTo(3)
}
}
}
})
| 0
|
Java
|
0
| 0
|
96809893c7d7448c382d3f94ada1af92042089ac
| 642
|
cs-interview-questions
|
Apache License 2.0
|
core/src/main/kotlin/com/justai/jaicf/activator/StateMapActivator.kt
|
klits111
| 282,262,247
| true
|
{"Kotlin": 195973, "Java": 11791}
|
package com.justai.jaicf.activator
import com.justai.jaicf.context.BotContext
import com.justai.jaicf.model.activation.ActivationRuleType
import com.justai.jaicf.model.scenario.ScenarioModel
import com.justai.jaicf.model.state.StatePath
/**
* A helper abstraction for every [Activator] that should activate a state if it contains a particular rule like event or intent.
*
* @see com.justai.jaicf.activator.event.BaseEventActivator
* @see com.justai.jaicf.activator.intent.BaseIntentActivator
*/
abstract class StateMapActivator(
ruleType: ActivationRuleType,
model: ScenarioModel
): Activator {
private val transitions = model.activations
.filter { a -> a.type == ruleType }
.map { a -> Pair(a.fromState, Pair(a.rule, a.toState)) }
.groupBy {a -> a.first}
.mapValues { l -> l.value.map { v -> v.second } }
fun findState(rule: String?, botContext: BotContext): String? = rule?.let {
val path = StatePath.parse(botContext.dialogContext.currentContext)
return checkWithParents(path, rule)
}
private fun checkWithParents(path: StatePath, rule: String): String? {
var p = path
while (true) {
val res = findState(p.toString(), rule)
if (res != null) {
return res
}
if (p.toString() == "/") {
break
}
p = p.stepUp()
}
return null
}
private fun findState(path: String, rule: String): String? =
transitions[path]?.firstOrNull { it.first == rule }?.second
}
| 1
| null |
1
| 1
|
35a778503744df742fd22a7a178a0befbbb422f5
| 1,582
|
jaicf-kotlin
|
Apache License 2.0
|
mobile/src/main/java/com/siliconlabs/bledemo/home_screen/menu_items/MatterDemo.kt
|
SiliconLabs
| 85,345,875
| false
| null |
package com.siliconlabs.bledemo.home_screen.menu_items
import androidx.annotation.DrawableRes
import com.siliconlabs.bledemo.bluetooth.services.BluetoothService
class MatterDemo(
@DrawableRes imageResId: Int,
title: String,
description: String
) : DemoMenuItem(imageResId, title, description) {
override val connectType = BluetoothService.GattConnectType.MATTER_DEMO
}
| 21
| null |
76
| 154
|
b5bf71aadb39d48f5612de8c4aed3bf12c9896cb
| 386
|
SimplicityConnect-android
|
Apache License 2.0
|
src/main/kotlin/net/megavex/redikt/protocol/RedisTypeWriter.kt
|
MegavexNetwork
| 666,473,616
| false
| null |
package net.megavex.redikt.protocol
import net.megavex.redikt.buffer.ByteWriter
internal object RedisTypeWriter {
suspend fun write(writer: ByteWriter, type: RedisType.Array<String, RedisType.BulkString>) {
writer.writeAsciiChar(ProtocolConstants.ARRAY)
writeInteger(writer, type.elements.size)
writeCrlf(writer)
for (element in type.elements) {
writeBulkString(writer, element.value)
}
}
private suspend fun writeInteger(writer: ByteWriter, value: Int) {
value.toString().forEach { writer.writeAsciiChar(it) }
}
private suspend fun writeBulkString(writer: ByteWriter, value: ByteArray) {
writer.writeAsciiChar(ProtocolConstants.BULK_STRING)
writeInteger(writer, value.size)
writeCrlf(writer)
writer.writeBytes(value)
writeCrlf(writer)
}
private suspend fun writeCrlf(writer: ByteWriter) {
writer.writeAsciiChar('\r')
writer.writeAsciiChar('\n')
}
}
| 0
|
Kotlin
|
0
| 0
|
a35976ed5dd96727a8cfe28c3d26dff4f033fcad
| 1,006
|
redikt
|
MIT License
|
server/src/main/java/com/pyamsoft/tetherfi/server/proxy/session/tcp/socks/four/SOCKS4Implementation.kt
|
pyamsoft
| 475,225,784
| false
|
{"Kotlin": 933742, "Shell": 2212}
|
/*
* Copyright 2024 pyamsoft
*
* 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.pyamsoft.tetherfi.server.proxy.session.tcp.socks.four
import android.annotation.SuppressLint
import com.pyamsoft.pydroid.core.cast
import com.pyamsoft.tetherfi.core.Timber
import com.pyamsoft.tetherfi.server.broadcast.BroadcastNetworkStatus
import com.pyamsoft.tetherfi.server.clients.ByteTransferReport
import com.pyamsoft.tetherfi.server.clients.TetherClient
import com.pyamsoft.tetherfi.server.network.SocketBinder
import com.pyamsoft.tetherfi.server.proxy.ServerDispatcher
import com.pyamsoft.tetherfi.server.proxy.SocketTagger
import com.pyamsoft.tetherfi.server.proxy.SocketTracker
import com.pyamsoft.tetherfi.server.proxy.session.tcp.socks.AbstractSOCKSImplementation
import com.pyamsoft.tetherfi.server.proxy.session.tcp.socks.AbstractSOCKSImplementation.Responder.Companion.INVALID_IP
import com.pyamsoft.tetherfi.server.proxy.session.tcp.socks.AbstractSOCKSImplementation.Responder.Companion.INVALID_PORT
import com.pyamsoft.tetherfi.server.proxy.session.tcp.socks.SOCKSCommand
import com.pyamsoft.tetherfi.server.proxy.session.tcp.socks.readUntilNullTerminator
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.ByteWriteChannel
import io.ktor.utils.io.core.writeFully
import io.ktor.utils.io.readByte
import io.ktor.utils.io.readPacket
import io.ktor.utils.io.readShort
import io.ktor.utils.io.writePacket
import java.net.Inet4Address
import java.net.InetAddress
import java.net.UnknownHostException
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.withContext
import kotlinx.io.Buffer
import kotlinx.io.Sink
import kotlinx.io.readByteArray
/** https://www.openssh.com/txt/socks4.protocol */
@Singleton
internal class SOCKS4Implementation
@Inject
internal constructor(
socketTagger: SocketTagger,
) :
AbstractSOCKSImplementation<SOCKS4AddressType, SOCKS4Implementation.Responder>(
socketTagger = socketTagger) {
@SuppressLint("CheckResult")
private suspend fun ignoreUserId(proxyInput: ByteReadChannel) {
proxyInput.readUntilNullTerminator()
}
override suspend fun usingResponder(
proxyOutput: ByteWriteChannel,
block: suspend Responder.() -> Unit
) {
Responder(proxyOutput).also { block(it) }
}
override suspend fun udpAssociate(
scope: CoroutineScope,
serverDispatcher: ServerDispatcher,
socketTracker: SocketTracker,
connectionInfo: BroadcastNetworkStatus.ConnectionInfo.Connected,
proxyInput: ByteReadChannel,
proxyOutput: ByteWriteChannel,
client: TetherClient,
destinationAddress: InetAddress,
destinationPort: Short,
addressType: SOCKS4AddressType,
responder: Responder,
onReport: suspend (ByteTransferReport) -> Unit
) {
Timber.w { "SOCKS4 implementation does not support UDP_ASSOCIATE" }
usingResponder(proxyOutput) { sendRefusal() }
}
override suspend fun handleSocksCommand(
scope: CoroutineScope,
serverDispatcher: ServerDispatcher,
socketTracker: SocketTracker,
networkBinder: SocketBinder.NetworkBinder,
proxyInput: ByteReadChannel,
proxyOutput: ByteWriteChannel,
connectionInfo: BroadcastNetworkStatus.ConnectionInfo.Connected,
client: TetherClient,
onReport: suspend (ByteTransferReport) -> Unit
) =
withContext(context = serverDispatcher.primary) {
/**
* +----+----+----+----+----+----+----+----+----+....+----+ | CD | DSTPORT | DSTIP | USERID
* |NULL| +----+----+----+----+----+----+----+----+----+....+----+
*
* # of bytes: 1 2 4 variable 1
*/
// We've already consumed the first byte of this and determined it was a SOCKS4 request
// First byte command
val commandByte = proxyInput.readByte()
val command = SOCKSCommand.fromByte(commandByte)
if (command == null) {
Timber.w {
"Invalid command byte: $commandByte, expected CONNECT, BIND, or UDP_ASSOCIATE"
}
usingResponder(proxyOutput) { sendRefusal() }
return@withContext
}
// 2 bytes for port
val destinationPort = proxyInput.readShort()
if (destinationPort <= 0) {
Timber.w { "Invalid destination port $destinationPort" }
usingResponder(proxyOutput) { sendError() }
return@withContext
}
// 4 bytes IP
val destinationPacket = proxyInput.readPacket(4)
val destinationIPBytes = destinationPacket.readByteArray()
val versionLessDestinationAddress =
try {
InetAddress.getByAddress(destinationIPBytes)
} catch (e: UnknownHostException) {
Timber.e(e) { "Unable to parse IPv4 address $destinationIPBytes" }
usingResponder(proxyOutput) { sendError() }
return@withContext
}
// If this is null, its not an IPv4 address
val ipv4DestinationAddress = versionLessDestinationAddress.cast<Inet4Address>()
if (ipv4DestinationAddress == null) {
Timber.w { "Destination address is not an IPv4 address: $versionLessDestinationAddress" }
usingResponder(proxyOutput) { sendError() }
return@withContext
}
// Ignore the user ID, we don't implement this
// And strip off the final NULL byte
ignoreUserId(proxyInput)
// If this is a SOCKS4 address (3 zero bytes, read AGAIN and this up until a null byte is
// the hostname
val finalDestinationAddress: InetAddress
if (ipv4DestinationAddress.isSOCKS4A()) {
val hostname = proxyInput.readUntilNullTerminator()
val versionLessHostname =
try {
InetAddress.getByName(hostname)
} catch (e: UnknownHostException) {
Timber.e(e) { "Unable to parse SOCKS4A IPv4 hostname $hostname" }
usingResponder(proxyOutput) { sendError() }
return@withContext
}
finalDestinationAddress = versionLessHostname
} else {
finalDestinationAddress = ipv4DestinationAddress
}
val responder = Responder(proxyOutput)
return@withContext performSOCKSCommand(
addressType = SOCKS4AddressType,
scope = scope,
socketTracker = socketTracker,
networkBinder = networkBinder,
serverDispatcher = serverDispatcher,
proxyInput = proxyInput,
proxyOutput = proxyOutput,
responder = responder,
client = client,
destinationAddress = finalDestinationAddress,
destinationPort = destinationPort,
command = command,
connectionInfo = connectionInfo,
onReport = onReport,
)
}
@JvmInline
internal value class Responder
internal constructor(
private val proxyOutput: ByteWriteChannel,
) : AbstractSOCKSImplementation.Responder<SOCKS4AddressType> {
private suspend inline fun sendPacket(builder: Sink.() -> Unit) {
val packet =
Buffer().apply {
// VN
writeByte(SOCKS_VERSION_BYTE)
// Builder
builder()
}
proxyOutput.apply {
writePacket(packet)
flush()
}
}
/**
* +----+----+----+----+----+----+----+----+ | VN | CD | DSTPORT | DSTIP |
* +----+----+----+----+----+----+----+----+
*
* # of bytes: 1 1 2 4
*/
private suspend fun sendPacket(replyCode: Byte, port: Short, address: InetAddress) {
sendPacket {
// CD
writeByte(replyCode)
// DSTPORT
writeShort(port)
// DSTIP
writeFully(address.address)
}
}
override suspend fun sendConnectSuccess(addressType: SOCKS4AddressType) {
return sendPacket(
replyCode = SUCCESS_CODE,
port = INVALID_PORT,
address = INVALID_IP,
)
}
override suspend fun sendBindInitialized(
addressType: SOCKS4AddressType,
port: Short,
address: InetAddress
) {
return sendPacket(
replyCode = SUCCESS_CODE,
port = port,
address = address,
)
}
override suspend fun sendRefusal() {
return sendPacket(
replyCode = ERROR_CODE,
port = INVALID_PORT,
address = INVALID_IP,
)
}
override suspend fun sendError() {
// SOCKS4 does not differentiate between "something went wrong" and "no"
return sendRefusal()
}
companion object {
private const val SOCKS_VERSION_BYTE: Byte = 0
// Granted
private const val SUCCESS_CODE: Byte = 90
// SOCKS4 does not differentiate between "something went wrong" and "no"
private const val ERROR_CODE: Byte = 91
}
}
}
| 10
|
Kotlin
|
31
| 401
|
aebdfc88e59a967d2c343d68d5dccb49dfa4ac06
| 9,504
|
tetherfi
|
Apache License 2.0
|
library/src/main/kotlin/delta/codecharacter/dtos/CreateMapRevisionRequestDto.kt
|
delta
| 731,776,389
| false
|
{"Kotlin": 563450, "Dockerfile": 618, "Shell": 299}
|
package delta.codecharacter.dtos
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonValue
import delta.codecharacter.dtos.GameMapTypeDto
import jakarta.validation.constraints.DecimalMax
import jakarta.validation.constraints.DecimalMin
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.Max
import jakarta.validation.constraints.Min
import jakarta.validation.constraints.NotNull
import jakarta.validation.constraints.Pattern
import jakarta.validation.constraints.Size
import jakarta.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
* Create map revision request
* @param map
* @param mapImage
* @param message
* @param mapType
*/
data class CreateMapRevisionRequestDto(
@Schema(example = "0000\n0010\n0100\n1000\n", required = true, description = "")
@get:JsonProperty("map", required = true) val map: kotlin.String,
@Schema(example = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIAQMAAAD+wSzIAAAABlBMVEX///+/v7+jQ3Y5AAAADklEQVQI12P4AIX8EAgALgAD/aNpbtEAAAAASUVORK5CYII", required = true, description = "")
@get:JsonProperty("mapImage", required = true) val mapImage: kotlin.String,
@Schema(example = "message", required = true, description = "")
@get:JsonProperty("message", required = true) val message: kotlin.String,
@field:Valid
@Schema(example = "null", description = "")
@get:JsonProperty("mapType") val mapType: GameMapTypeDto? = GameMapTypeDto.NORMAL
) {
}
| 0
|
Kotlin
|
0
| 0
|
4b7add531880e3fa00a8471c4248f18e8268d862
| 1,551
|
codecharacter-server
|
MIT License
|
library/plugins/base/base-publisher/src/main/java/io/github/cdsap/talaiot/publisher/timeline/TimelinePublisher.kt
|
cdsap
| 157,973,716
| false
| null |
package io.github.cdsap.talaiot.publisher.timeline
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import io.github.cdsap.talaiot.entities.ExecutionReport
import io.github.cdsap.talaiot.publisher.Publisher
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.InputStream
class TimelinePublisher(private val path: File) : Publisher {
override fun publish(report: ExecutionReport) {
val measures = report.tasks
?.filter { !it.rootNode }
?.groupBy { it.workerId }
val timelineMeasures = measures?.map {
Measure(
it.key,
it.value.map { task ->
TimelineTaskMeasurement(
task.taskPath,
task.state,
task.critical,
task.startMs,
task.workerId,
task.stopMs
)
}
)
} ?: emptyList()
val executionResult = ExecutionResult(timelineMeasures)
val gson: Gson = GsonBuilder().setPrettyPrinting().create()
val html = File(path, "reports/talaiot/timeline/index.html")
.apply {
mkdirs()
delete()
createNewFile()
}
BufferedWriter(FileWriter(html)).use {
var reader = inputStreamFromResources("timeline/index_0.html").bufferedReader()
it.append(reader.readText())
reader.close()
gson.toJson(executionResult, it)
reader = inputStreamFromResources("timeline/index_2.html").bufferedReader()
it.append(reader.readText())
reader.close()
it.flush()
}
inputStreamFromResources("timeline/chart.css").use {
it.copyTo(
File(
path,
"reports/talaiot/timeline/chart.css"
).outputStream()
)
}
inputStreamFromResources("timeline/chart.js").use {
it.copyTo(
File(
path,
"reports/talaiot/timeline/chart.js"
).outputStream()
)
}
}
private fun inputStreamFromResources(path: String): InputStream =
TimelinePublisher::class.java.classLoader.getResourceAsStream(path)
}
| 27
|
Kotlin
|
36
| 550
|
3b352fea5355448450c9ffb96946788212b40099
| 2,446
|
Talaiot
|
MIT License
|
app/src/main/java/com/jnj/vaccinetracker/sync/domain/usecases/masterdata/SyncLocalizationUseCase.kt
|
johnsonandjohnson
| 503,902,626
| false
|
{"Kotlin": 1690434}
|
package com.jnj.vaccinetracker.sync.domain.usecases.masterdata
import com.jnj.vaccinetracker.common.data.models.api.response.LocalizationMapDto
import com.jnj.vaccinetracker.common.data.repositories.MasterDataRepository
import com.jnj.vaccinetracker.common.domain.entities.MasterDataFile
import com.jnj.vaccinetracker.sync.data.network.VaccineTrackerSyncApiDataSource
import com.jnj.vaccinetracker.sync.domain.helpers.SyncLogger
import com.jnj.vaccinetracker.sync.domain.usecases.masterdata.base.SyncMasterDataUseCaseBase
import javax.inject.Inject
class SyncLocalizationUseCase @Inject constructor(
private val api: VaccineTrackerSyncApiDataSource,
override val masterDataRepository: MasterDataRepository, override val syncLogger: SyncLogger,
) : SyncMasterDataUseCaseBase<LocalizationMapDto>() {
override suspend fun getMasterDataRemote(): LocalizationMapDto {
return api.getLocalization()
}
override suspend fun storeMasterData(masterData: LocalizationMapDto) {
masterDataRepository.writeLocalizationMap(masterData)
}
override val masterDataFile: MasterDataFile
get() = MasterDataFile.LOCALIZATION
}
| 2
|
Kotlin
|
1
| 1
|
dbf657c7fb7cb1233ed5c26bc554a1032afda3e0
| 1,158
|
vxnaid
|
Apache License 2.0
|
src/main/kotlin/org/stvad/kask/model/constants.kt
|
Stvad
| 144,476,230
| false
| null |
package org.stvad.kask.model
const val amazonPrefix = "AMAZON."
| 1
|
Kotlin
|
0
| 5
|
cd86ed9d07c9233c484001f771171dd0587d2344
| 64
|
kask
|
Apache License 2.0
|
edge-agent-sdk/src/commonMain/kotlin/org/hyperledger/identus/walletsdk/edgeagent/protocols/outOfBand/InvitationType.kt
|
hyperledger
| 564,174,099
| false
|
{"Kotlin": 1701521, "Gherkin": 4030, "JavaScript": 375}
|
package org.hyperledger.identus.walletsdk.edgeagent.protocols.outOfBand
import kotlinx.serialization.Serializable
/**
* Represents a sealed class for different types of invitations.
*/
@Serializable
sealed class InvitationType
| 2
|
Kotlin
|
4
| 9
|
0437927de1d21b9acaaaf257d24e7c9a30de657c
| 231
|
identus-edge-agent-sdk-kmp
|
Apache License 2.0
|
sources-jvm/model/MValueParameterIndex.kt
|
fluidsonic
| 168,738,824
| false
| null |
package io.fluidsonic.meta
public inline class MValueParameterIndex(public val value: Int) {
override fun toString(): String = value.toString()
public companion object
}
| 0
|
Kotlin
|
1
| 11
|
edfa3f0a4484d4a6f03e359e69ad131ec5208cef
| 177
|
fluid-meta
|
Apache License 2.0
|
api-owm/src/main/java/com/kennyc/dashweather/api_owm/response/OWMResponse.kt
|
Kennyc1012
| 105,380,988
| false
| null |
package com.kennyc.dashweather.api_owm.response
import com.google.gson.annotations.SerializedName
import com.kennyc.dashweather.api_owm.model.OWMCurrent
import com.kennyc.dashweather.api_owm.model.OWMDaily
data class OWMResponse(@SerializedName("lat") val lat: Double,
@SerializedName("lon") val lon: Double,
@SerializedName("current") val current: OWMCurrent,
@SerializedName("daily") val daily: List<OWMDaily>) {
init {
require(daily.isNotEmpty())
}
}
| 0
|
Kotlin
|
2
| 0
|
212ce9f0dc434a537530b3904b1763684f7f6915
| 540
|
DashWeatherExtension
|
Apache License 2.0
|
ksiren-okhttp3-plugin/src/main/java/com/brightspace/ksiren/okhttp3_plugin/KSirenOkhttp3RequestBuilder.kt
|
Brightspace
| 98,900,973
| false
| null |
package com.brightspace.ksiren.okhttp3_request_builder
import com.brightspace.ksiren.Action
import com.brightspace.ksiren.ContentType
import com.brightspace.ksiren.KSirenJsonWriter
import com.brightspace.ksiren.KSirenRequestBuilder
import okhttp3.*
/**
* Copyright 2017 D2L Corporation
*
* 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.
*/
class KSirenOkhttp3RequestBuilder(wrappedAction: Action, private val writer: KSirenJsonWriter) : KSirenRequestBuilder<Request>(wrappedAction) {
override fun build(): Request {
val requestBuilder: Request.Builder = Request.Builder()
val urlBuilder: HttpUrl.Builder = HttpUrl.parse(action.href)?.newBuilder()
?: throw Exception("Action href could not be parsed")
if (action.fields.isNotEmpty()) {
when (action.method) {
"GET" -> {
action.fields.forEach {
if (it.value != null ) {
urlBuilder.addQueryParameter(it.name, it.value)
}
}
requestBuilder.get()
}
"POST" -> {
requestBuilder.post(getBody())
}
}
}
requestBuilder.url(urlBuilder.build())
return requestBuilder.build()
}
private fun getBody(): RequestBody {
when (action.type) {
ContentType.JSON -> {
val mediaType = MediaType.parse(action.type.value)
val jsonBody = action.toJsonRequestBody(writer)
return RequestBody.create(mediaType, jsonBody)
}
ContentType.FORM -> {
val requestBodyBuilder: MultipartBody.Builder = MultipartBody.Builder()
.setType(MultipartBody.FORM)
action.fields
.mapNotNull { field -> field.value?.let { value -> field.name to value } }
.forEach() { pair -> requestBodyBuilder.addFormDataPart(pair.first, pair.second) }
return requestBodyBuilder.build()
}
}
}
}
| 1
|
Kotlin
|
2
| 2
|
82300a4c223be1529465bba23853bd4789d4b39e
| 2,228
|
ksiren
|
Apache License 2.0
|
src/lib/kotlin/slatekit-workers/src/main/kotlin/slatekit/workers/status/RunState.kt
|
TrendingTechnology
| 157,646,990
| true
|
{"Kotlin": 1826115, "Scala": 1124254, "Batchfile": 17450, "Shell": 8834, "Java": 2251, "Swift": 1555, "HTML": 303, "CSS": 35, "JavaScript": 28}
|
/**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.workers.status
interface RunState {
val mode: String
val value: Int
}
// STATES:
// 1. non-started : not-started
// 2. executing : currently executing
// 3. waiting : waiting for work
// 4. paused : paused for x amount of time before going back to executing
// 5. stopped : stopped indefinitely
// 6. complete : completed
// 7. failed : failed ( opposite of completed )
object RunStateNotStarted : RunState {
override val value: Int = 1
override val mode: String = "not-started"
}
object RunStateInitializing : RunState {
override val value: Int = 2
override val mode: String = "initializing"
}
object RunStateRunning : RunState {
override val value: Int = 3
override val mode: String = "running"
}
object RunStateIdle : RunState {
override val value: Int = 4
override val mode: String = "idle"
}
object RunStatePaused : RunState {
override val value: Int = 5
override val mode: String = "paused"
}
object RunStateStopped : RunState {
override val value: Int = 6
override val mode: String = "stopped"
}
object RunStateComplete : RunState {
override val value: Int = 7
override val mode: String = "complete"
}
object RunStateFailed : RunState {
override val value: Int = 8
override val mode: String = "failed"
}
| 0
|
Kotlin
|
0
| 0
|
03b468db9dd69a80ff3d9bb01141c65bd0e21456
| 1,678
|
slatekit
|
Apache License 2.0
|
src/main/kotlin/org/example/detekt/rules/arch/mappers/SeparateDataModelPerLayerRule.kt
|
Keslerdk
| 863,145,840
| false
|
{"Kotlin": 58750, "Shell": 738}
|
package org.example.detekt.rules.arch.mappers
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.hasAnnotation
import org.example.detekt.rules.arch.ModuleType
import org.example.detekt.rules.getCurrentLayer
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
//todo: mutex
private val dataClasses: MutableSet<KtClass> = mutableSetOf()
class SeparateDataModelPerLayerRule(config: Config) : Rule(config) {
private companion object {
const val RULE_DESCRIPTION =
"Проверяет, что каждый слой имеет свою собственную модель данных и они не используются в других слоях."
const val REPORT_MESSAGE_DATA = "Domain модель не должна использоваться для получения данных"
const val REPORT_MESSAGE_DOMAIN = "Domain модель не должна использоваться для отображения данных"
}
override val issue: Issue
get() = Issue(javaClass.simpleName, Severity.Defect, RULE_DESCRIPTION, Debt.TEN_MINS)
override fun visitClass(klass: KtClass) {
super.visitClass(klass)
val type = getCurrentLayer(klass.containingFile.name)
if (!klass.isData() || type != ModuleType.DOMAIN) return
dataClasses.add(klass)
//todo: как проверить что не используется в дата-слое, если используется не serialization?
if (klass.hasAnnotation("Serializable")) {
report(CodeSmell(issue, Entity.Companion.from(klass), REPORT_MESSAGE_DATA))
}
}
override fun visitNamedFunction(function: KtNamedFunction) {
super.visitNamedFunction(function)
if (function.hasAnnotation("Composable")) {
val hasDomainImport =
function.getParentOfType<KtFile>(true)?.importList?.imports?.any { import ->
val importPath = import.importPath?.pathStr ?: return@any false
dataClasses.any { klass ->
val packageName = klass.fqName?.parent()?.asString() ?: return@any false
val className = klass.name ?: return@any false
importPath.endsWith(".$className") && importPath.startsWith(packageName)
}
}
if (hasDomainImport == true) {
report(CodeSmell(issue, Entity.Companion.from(function), REPORT_MESSAGE_DOMAIN))
}
}
}
/**
private class MyVisitor : DetektVisitor() {
val dataClasses: MutableSet<KtClass> = mutableSetOf()
val funParamTypes: MutableSet<String> = mutableSetOf()
fun getDomainModels(): List<KtClass> {
return dataClasses.filter { getCurrentLayer(it.name.orEmpty()) == ModuleType.DOMAIN }
.filter { funParamTypes.contains(it.name) }
}
override fun visitClass(klass: KtClass) {
super.visitClass(klass)
if (klass.isData()) {
dataClasses.add(klass)
}
}
override fun visitNamedFunction(function: KtNamedFunction) {
super.visitNamedFunction(function)
if (function.hasAnnotation("Composable")) {
function.valueParameters.forEach { param ->
param.typeReference?.name?.let { funParamTypes.add(it) }
}
}
}
}
**/
}
| 1
|
Kotlin
|
0
| 0
|
614c19c88d61c41f6a9af7e6d49d677945965509
| 3,561
|
fluffy-octo-meme
|
Apache License 2.0
|
design/src/main/java/com/ingresse/design/ui/dialog/DSConfirmDialog.kt
|
ingresse
| 203,441,687
| false
| null |
package com.ingresse.design.ui.dialog
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.ViewGroup
import com.ingresse.design.R
import com.ingresse.design.helper.setVisible
import kotlinx.android.synthetic.main.ds_confirm_dialog.*
class DSConfirmDialog(context: Context): DSBaseDialog(R.layout.ds_confirm_dialog, context) {
private var defaultPositiveBtn = context.getString(R.string.confirm_dialog_default_positive_btn)
private var defaultNegativeBtn = context.getString(R.string.confirm_dialog_default_negative_btn)
fun setInfos(title: String = "",
message: String = "",
positiveTitle: String = defaultPositiveBtn,
negativeTitle: String = defaultNegativeBtn,
onPositiveClick: (() -> Unit),
onNegativeClick: (() -> Unit)) {
lbl_dialog_title.text = title
lbl_dialog_message.text = message
btn_confirm.text = positiveTitle
btn_cancel.text = negativeTitle
btn_confirm.setOnClickListener { onPositiveClick() }
btn_cancel.setOnClickListener { onNegativeClick() }
}
fun setEvent(eventName: String = "", dialogPoster: Drawable? = null) {
lbl_event_name.setVisible(true)
lbl_event_name.text = eventName
val topMargin = context.resources.getDimensionPixelSize(R.dimen.spacing_x2)
val params = lbl_dialog_title.layoutParams as ViewGroup.MarginLayoutParams
params.setMargins(params.leftMargin, topMargin, params.rightMargin, params.bottomMargin)
val poster = dialogPoster ?: return
iv_dialog_poster.setImageDrawable(poster)
iv_dialog_poster.setVisible(true)
}
}
| 3
|
Kotlin
|
0
| 1
|
381d7b36d8ad693cf13c7a5ba02127bcb6278019
| 1,723
|
design-systems-android
|
MIT License
|
app/src/main/java/com/berkaykurtoglu/recipequest/domain/model/recipedetailmodel/RecipeDetailModel.kt
|
BerkayyKurtoglu
| 789,163,245
| false
|
{"Kotlin": 144729}
|
package com.berkaykurtoglu.recipequest.domain.model.recipedetailmodel
data class RecipeDetailModel(
val analyzedInstructionModels: List<AnalyzedInstructionModel>,
val allergenList: List<AllergenModel>,
val dishTypes: List<String>,
val extendedIngredientModels: List<ExtendedIngredientModel>,
val id: Int,
val image: String,
val instructions: String,
val readyInMinutes: Int,
val servings: Int,
val sourceName: String,
val sourceUrl: String,
val spoonacularScore: Double,
val summary: String,
val title: String,
val veryPopular: Boolean,
)
| 0
|
Kotlin
|
0
| 0
|
152b6d0b6e1faf31de89ff613e2e5a5541f14c11
| 600
|
Papara-Final-Project
|
MIT License
|
src/test/kotlin/com/romankagan/pyramid/PyramidControllerTestsHebrew.kt
|
romankagan
| 244,289,596
| false
| null |
package com.romankagan.pyramid
import org.hamcrest.CoreMatchers
import org.junit.Assert
import org.springframework.http.HttpStatus
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class PyramidControllerTestsHebrew {
@Autowired
lateinit var testRestTemplate: TestRestTemplate
@Test
fun testWordIsPyramid() {
val word="באנאנא"
val result = testRestTemplate.getForEntity("/api/v1/pyramid?word=$word", String::class.java)
Assert.assertThat(result.body, CoreMatchers.`is`("Success. The word:$word is a `pyramid word`."))
Assert.assertThat(result.statusCode, CoreMatchers.`is`(HttpStatus.OK))
}
@Test
fun testWordIsBlank() {
val word="ביר לוגא"
val result = testRestTemplate.getForEntity("/api/v1/pyramid?word=$word", String::class.java)
Assert.assertThat(result.body, CoreMatchers.`is`("Failed. The word:$word has blank character(s)."))
Assert.assertThat(result.statusCode, CoreMatchers.`is`(HttpStatus.NOT_FOUND))
}
@Test
fun testWordHasDups() {
val word="בעער"
val result = testRestTemplate.getForEntity("/api/v1/pyramid?word=$word", String::class.java)
Assert.assertThat(result.body, CoreMatchers.`is`("Failed. The word:$word has duplicates."))
Assert.assertThat(result.statusCode, CoreMatchers.`is`(HttpStatus.NOT_FOUND))
}
@Test
fun testWordNotPyramid() {
val word="בער"
val result = testRestTemplate.getForEntity("/api/v1/pyramid?word=$word", String::class.java)
Assert.assertThat(result.body, CoreMatchers.`is`("Failed. The word:$word is not a `pyramid word`."))
Assert.assertThat(result.statusCode, CoreMatchers.`is`(HttpStatus.NOT_FOUND))
}
@Test
fun testNotPyramidSingleCharAbsent() {
val word="בעבעב"
val result = testRestTemplate.getForEntity("/api/v1/pyramid?word=$word", String::class.java)
Assert.assertThat(result.body, CoreMatchers.`is`("Failed. The word:$word is not a `pyramid word`."))
Assert.assertThat(result.statusCode, CoreMatchers.`is`(HttpStatus.NOT_FOUND))
}
}
| 0
|
Kotlin
|
0
| 0
|
c66f11d07c2a56a3df531b976d1e2d57897089c9
| 2,306
|
pyramid
|
Apache License 2.0
|
edicion/Dashboard_V2/app/src/main/java/com/example/dashboard_v2/components/OnBoardingData.kt
|
maurodri
| 678,590,413
| false
| null |
package com.example.dashboard_v2.components
import androidx.compose.ui.graphics.Color
import com.example.dashboard_v2.ui.theme.ColorBlue
data class OnBoardingData(
val image: Int, val title: String,
val desc: String,
val backgroundColor:Color,
val mainColor:Color = ColorBlue
)
| 0
|
Kotlin
|
0
| 0
|
6122d3e2a4a89794b05985bde11f8f58949ec648
| 295
|
Trabajos-Kotlin
|
MIT License
|
src/main/kotlin/org/awong/koans/KollectionKoans.kt
|
alanktwong
| 245,327,983
| false
| null |
package org.awong.koans
// https://play.kotlinlang.org/koans/Collections/Introduction/Task.kt
fun Shop.getSetOfCustomers(): Set<Customer> = customers.toSet()
// https://play.kotlinlang.org/koans/Collections/Filter%20map/Task.kt
// Return the set of cities the customers are from
fun Shop.getCitiesCustomersAreFrom(): Set<City> = getSetOfCustomers().map { customer -> customer.city }.toSet()
// Return a list of the customers who live in the given city
val isInCity: (Customer, City) -> Boolean = { customer, city -> city == customer.city }
fun Shop.getCustomersFrom(city: City): List<Customer> = getSetOfCustomers()
.filter { customer -> isInCity(customer, city) }
// https://play.kotlinlang.org/koans/Collections/All%20Any%20and%20other%20predicates/Task.kt
// Return true if all customers are from the given city
fun Shop.checkAllCustomersAreFrom(city: City): Boolean = getSetOfCustomers()
.all { customer -> isInCity(customer, city) }
// Return true if there is at least one customer from the given city
fun Shop.hasCustomerFrom(city: City): Boolean = getSetOfCustomers()
.any { customer -> isInCity(customer, city) }
// Return the number of customers from the given city
fun Shop.countCustomersFrom(city: City): Int = getSetOfCustomers()
.count { customer -> isInCity(customer, city) }
// Return a customer who lives in the given city, or null if there is none
fun Shop.findAnyCustomerFrom(city: City): Customer? = getSetOfCustomers()
.firstOrNull { customer -> isInCity(customer, city) }
// https://play.kotlinlang.org/koans/Collections/FlatMap/Task.kt
// Return all products this customer has ordered
val Customer.orderedProducts: Set<Product> get() {
return orders.flatMap { order -> order.products }.toSet()
}
// Return all products that were ordered by at least one customer
val Shop.allOrderedProducts: Set<Product> get() {
return customers.flatMap { customer -> customer.orderedProducts }.toSet()
}
// https://play.kotlinlang.org/koans/Collections/Max%20min/Task.kt
// Return a customer whose order count is the highest among all customers
fun Shop.getCustomerWithMaximumNumberOfOrders(): Customer? = customers.maxBy { customer -> customer.orders.size }
// Return the most expensive product which has been ordered
fun Customer.getMostExpensiveOrderedProduct(): Product? = orders.flatMap { order -> order.products }
.maxBy { product -> product.price }
// https://play.kotlinlang.org/koans/Collections/Sort/Task.kt
// Return a list of customers, sorted by the ascending number of orders they made
fun Shop.getCustomersSortedByNumberOfOrders(): List<Customer> = customers.sortedBy { customer -> customer.orders.size }
// https://play.kotlinlang.org/koans/Collections/Sum/Task.kt
// Return the sum of prices of all products that a customer has ordered.
// Note: the customer may order the same product for several times.
fun Customer.getTotalOrderPrice(): Double = orders.flatMap { order -> order.products }
.sumByDouble { product -> product.price }
// https://play.kotlinlang.org/koans/Collections/GroupBy/Task.kt
// Return a map of the customers living in each city
fun Shop.groupCustomersByCity(): Map<City, List<Customer>> = customers.groupBy( { customer -> customer.city })
// https://play.kotlinlang.org/koans/Collections/Partition/Task.kt
// Return customers who have more undelivered orders than delivered
fun Customer.getNumberOfUndeliveredOrders(): Int = orders.count { !it.isDelivered }
fun Customer.getNumberOfDeliveredOrders(): Int = orders.count { it.isDelivered }
fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> = customers.partition { customer ->
customer.getNumberOfUndeliveredOrders() > customer.getNumberOfDeliveredOrders()
}.first.toSet()
// https://play.kotlinlang.org/koans/Collections/Fold/Task.kt
// Return the set of products that were ordered by every customer
fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> {
val allProducts = customers.flatMap { it.orders.flatMap { it.products }}.toSet()
return customers.fold(allProducts, {
orderedByAll, customer ->
orderedByAll.intersect(customer.orders.flatMap { it.products }.toSet())
})
}
// https://play.kotlinlang.org/koans/Collections/Compound%20tasks/Task.kt
// Return the most expensive product among all delivered products
// (use the Order.isDelivered flag)
fun Customer.getMostExpensiveDeliveredProduct(): Product? {
val deliveredProducts = orders.filter { it.isDelivered }.flatMap { it.products }
return deliveredProducts.maxBy { it.price }
}
// Return how many times the given product was ordered.
// Note: a customer may order the same product for several times.
fun Shop.getNumberOfTimesProductWasOrdered(product: Product): Int = customers.flatMap { it.getOrderedProductsList() }.count { it == product }
fun Customer.getOrderedProductsList(): List<Product> {
return orders.flatMap { it.products }
}
// https://play.kotlinlang.org/koans/Collections/Get%20used%20to%20new%20style/Task.kt
fun doSomethingStrangeWithCollection(collection: Collection<String>): Collection<String>? {
val groupsByLength = collection.groupBy { it.length }
val maximumSizeOfGroup = groupsByLength.values.map { group -> group.size }.max()
return groupsByLength.values.firstOrNull { group -> group.size == maximumSizeOfGroup }
}
| 0
|
Kotlin
|
0
| 0
|
cdf2483bfdfb824b3c8dc51d387012cbebb45ec5
| 5,392
|
learning-kotlin
|
MIT License
|
src/main/kotlin/dermomedic/ai/service/DermoAnalyser.kt
|
fbrunacci
| 303,677,842
| false
|
{"Jupyter Notebook": 1708775, "Kotlin": 22785, "Python": 8530, "CSS": 94}
|
package dermomedic.ai.service
import dermomedic.ai.Config
import kotlinx.coroutines.*
import dermomedic.ai.service.ktor.Analyse
import org.datavec.image.loader.NativeImageLoader
import org.deeplearning4j.nn.graph.ComputationGraph
import org.deeplearning4j.util.ModelSerializer
import org.nd4j.linalg.api.ndarray.INDArray
import org.nd4j.linalg.dataset.api.preprocessor.VGG16ImagePreProcessor
import java.io.File
object DermoAnalyser {
val height = 224L
val width = 224L
val channels = 3L
val imageLoader = NativeImageLoader(height, width, channels)
val modelContext = newSingleThreadContext("ModelContext")
val preTrainedModel: ComputationGraph
fun initPreTrainedModel() {
}
init {
preTrainedModel = ModelSerializer.restoreComputationGraph("${Config.preTrainedModel}")
}
fun analyse(database: Database, analyse: Analyse, uploadDir: File): Job {
val file = File(uploadDir, analyse.storedFileName())
val job = GlobalScope.launch {
var image = imageLoader.asMatrix(file)
// println("image:$image")
VGG16ImagePreProcessor().transform(image)
withContext(modelContext) {
val output: Array<INDArray> = preTrainedModel.output(false, image)
println("output: $output")
analyse.malingantEvaluation = output[0].getFloat(0)
// analyse.benignEvaluation = output[0].getFloat(1)
database.saveAnalyse(analyse)
}
}
return job
}
}
| 0
|
Jupyter Notebook
|
0
| 0
|
361f1f0a52c457d27e2bc648f0888bdf71cb0f32
| 1,544
|
dermomedic.ai
|
Apache License 2.0
|
feature/products/src/main/java/co/ke/xently/products/di/RepositoryModule.kt
|
ajharry69
| 391,476,966
| false
| null |
package co.ke.xently.products.di
import co.ke.xently.products.repository.IProductsRepository
import co.ke.xently.products.repository.ProductsRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
internal abstract class RepositoryModule {
@Binds
abstract fun bindProductsRepository(repository: ProductsRepository): IProductsRepository
}
| 8
|
Kotlin
|
0
| 0
|
591f88f92313c1e57422dac61774533dfc52a2df
| 467
|
xently-archived
|
MIT License
|
app/src/main/java/com/julianczaja/esp_monitoring_app/data/remote/RetrofitEspMonitoringApi.kt
|
julianczaja
| 575,978,649
| false
|
{"Kotlin": 588227}
|
package com.julianczaja.esp_monitoring_app.data.remote
import com.julianczaja.esp_monitoring_app.domain.model.DeviceInfo
import com.julianczaja.esp_monitoring_app.domain.model.DeviceServerSettings
import com.julianczaja.esp_monitoring_app.domain.model.Photo
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
interface RetrofitEspMonitoringApi {
@GET(value = "/dates/{deviceId}")
suspend fun getDeviceDates(
@Path("deviceId") deviceId: Long
): Result<List<String>>
@GET(value = "/photos/{deviceId}/{date}")
suspend fun getDevicePhotosByDate(
@Path("deviceId") deviceId: Long,
@Path("date") date: String
): Result<List<Photo>>
@GET(value = "/last_photo/{deviceId}")
suspend fun getDeviceLastPhoto(
@Path("deviceId") deviceId: Long
): Result<Photo>
@DELETE(value = "/photos/{fileName}")
suspend fun removePhoto(
@Path("fileName") fileName: String,
): Result<Unit>
@POST(value = "/photos/remove")
suspend fun removePhotos(
@Body params: List<String>
): Result<Unit>
@GET(value = "/device/{deviceId}")
suspend fun getDeviceInfo(
@Path("deviceId") deviceId: Long
): Result<DeviceInfo>
@GET(value = "/device/{deviceId}/settings")
suspend fun getDeviceServerSettings(
@Path("deviceId") deviceId: Long
): Result<DeviceServerSettings>
@POST(value = "/device/{deviceId}/settings")
suspend fun updateDeviceServerSettings(
@Path("deviceId") deviceId: Long,
@Body settings: DeviceServerSettings
): Result<DeviceServerSettings>
}
| 0
|
Kotlin
|
0
| 2
|
0a062d07b9429de22d33811d50fddc7291234fa0
| 1,687
|
esp_monitoring_app
|
MIT License
|
core/presentation/flow/src/main/java/com/krossovochkin/core/presentation/flow/FlowUtils.kt
|
krossovochkin
| 221,648,261
| false
|
{"Kotlin": 493412, "Python": 2433, "Shell": 369}
|
package com.krossovochkin.core.presentation.flow
import androidx.fragment.app.Fragment
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
inline fun <reified T> Flow<T>.collect(
fragment: Fragment,
noinline collector: suspend (T) -> Unit
) {
this.flowWithLifecycle(fragment.lifecycle)
.onEach { collector(it) }
.launchIn(fragment.lifecycleScope)
}
| 0
|
Kotlin
|
0
| 15
|
3568c445d83bdf332f1c6b96d9c137440c01cc25
| 526
|
FiberyUnofficial
|
Apache License 2.0
|
src/main/kotlin/com/grappenmaker/snake/Data.kt
|
770grappenmaker
| 505,066,875
| false
|
{"Kotlin": 20208}
|
package com.grappenmaker.snake
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class BotInfo(
@SerialName("apiversion") val apiVersion: String = "1",
val author: String,
val color: String,
val head: String,
val tail: String,
val version: String
)
@Serializable
data class StartRequest(
val game: Game,
val turn: Int,
val board: Board,
val you: BattleSnake
)
typealias MoveRequest = StartRequest
@Serializable
data class MoveResponse(
val shout: String?,
val move: Direction
)
typealias EndRequest = StartRequest
@Serializable
data class Game(
val id: String,
val ruleset: Ruleset,
val map: String? = null,
val timeout: Long,
val source: GameSource
)
@Serializable
data class Ruleset(
val name: String,
val version: String,
val settings: RulesetSettings
)
@Serializable
data class RulesetSettings(
val foodSpawnChance: Int,
val minimumFood: Int,
val hazardDamagePerTurn: Int,
val royale: RoyaleSettings?,
val squad: SquadSettings?
)
@Serializable
data class SquadSettings(
val allowBodyCollisions: Boolean,
val sharedElimination: Boolean,
val sharedHealth: Boolean,
val sharedLength: Boolean
)
@Serializable
data class RoyaleSettings(val shrinkEveryNTurns: Int)
@Serializable
enum class GameSource {
@SerialName("tournament") TOURNAMENT,
@SerialName("league") LEAGUE,
@SerialName("arena") ARENA,
@SerialName("challenge") CHALLENGE,
@SerialName("custom") CUSTOM,
@SerialName("ladder") LADDER
}
@Serializable
data class Board(
val height: Int,
val width: Int,
val food: List<Position>,
val hazards: List<Position>,
val snakes: List<BattleSnake>
)
@Serializable
data class BattleSnake(
val id: String,
val name: String,
val health: Int,
val body: List<Position>,
val latency: String,
val head: Position,
val length: Int,
val shout: String,
val squad: String,
val customizations: SnakeCustomization
)
val BattleSnake.tail get() = body.last()
@Serializable
data class SnakeCustomization(
val color: String,
val head: String,
val tail: String
)
| 0
|
Kotlin
|
0
| 1
|
a3de714cb876edf0e2da5374678e3a9784f3b7d7
| 2,218
|
snek-bro
|
The Unlicense
|
src/test/unit/kotlin/com/kilchichakov/fiveletters/MongoTestSuiteExternal.kt
|
augur
| 194,393,890
| false
|
{"Kotlin": 306716, "JavaScript": 3426, "Dockerfile": 135, "HTML": 9}
|
package com.kilchichakov.fiveletters
import com.kilchichakov.fiveletters.config.MongoConfig
import com.kilchichakov.fiveletters.service.TransactionWrapper
import com.mongodb.BasicDBObject
import com.mongodb.MongoClient
import com.mongodb.client.MongoDatabase
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.bson.BsonDocument
open class MongoTestSuiteExternal {
lateinit var db: MongoDatabase
lateinit var transactionWrapper: TransactionWrapper
private val initScript = MongoTestSuiteExternal::class.java.classLoader.getResource("mongo-init.js").readText()
companion object {
private val mongoConfig = MongoConfig()
lateinit var client: MongoClient
@BeforeAll
@JvmStatic
fun setUp() {
client = mongoConfig.mongoClient(
login = "fiveletters",
password = "111",
host = "111",
port = 27018,
srvMode = true
)
}
@AfterAll
@JvmStatic
fun tearDown() {
client.close()
}
}
@BeforeEach
open fun setUpEach() {
transactionWrapper = TransactionWrapper(client)
db = client.getDatabase("test-db")
val script = BasicDBObject()
script["eval"] = initScript
db.runCommand(BsonDocument())
}
@AfterEach
fun tearDownEach() {
client.dropDatabase("test-db")
}
}
| 0
|
Kotlin
|
0
| 0
|
64734f93bef1c36309caaece5b04fe8852872498
| 1,576
|
five-letters
|
MIT License
|
src/main/kotlin/com/uca/bigdreamscoders/bigcinema/services/ProvinceService.kt
|
BigDreamsCoders
| 192,656,497
| false
|
{"JavaScript": 129854, "HTML": 104338, "Kotlin": 55736}
|
package com.uca.bigdreamscoders.bigcinema.services
import com.uca.bigdreamscoders.bigcinema.repositories.ProvinceRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class ProvinceService{
@Autowired
lateinit var provinceRepository: ProvinceRepository
fun findAll() = provinceRepository.findAll()
fun findByProId(proId:String) = provinceRepository.findByProId(proId)
}
| 0
|
JavaScript
|
0
| 0
|
f416244db46c6fe06fccc993a7a050103833d2a1
| 462
|
bigcinema
|
MIT License
|
app/src/main/java/com/craiovadata/android/sunshine/ui/models/WebcamEntry.kt
|
alboteanud
| 141,880,564
| false
|
{"Java": 178703, "Kotlin": 149743}
|
package com.craiovadata.android.sunshine.ui.models
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import java.util.*
@Entity(tableName = "webcams", indices = [Index(value = ["id"], unique = true)])
class WebcamEntry(
@PrimaryKey var id: String,
var title: String,
var updateDate: Date,
var previewUrl: String
) {
}
/*
@Entity(tableName = "webcams", indices = [Index(value = ["id"], unique = true)])
class WebcamEntry {
// @PrimaryKey(autoGenerate = true)
@PrimaryKey
var id = "0"
var title = ""
var updateDate: Date = Date()
var previewUrl = ""
// @Ignore
// constructor()
constructor(id: String, title: String, updateDate: Date, previewUrl: String) {
this.id = id
this.title = title
this.updateDate = updateDate
this.previewUrl = previewUrl
}
}
*/
| 0
|
Java
|
0
| 0
|
ba5a32e3454c7f6a9825375d4088b7a44f9a66b7
| 885
|
Sunshine---my-weather-app
|
Apache License 2.0
|
tests/integration-tests/src/test/kotlin/steps/did/UpdateDidSteps.kt
|
hyperledger
| 512,835,706
| false
|
{"Scala": 2680210, "Kotlin": 166165, "TypeScript": 50664, "Shell": 30427, "Python": 13723, "Gherkin": 10879, "Smarty": 2922, "JavaScript": 1204}
|
package steps.did
import common.TestConstants
import interactions.Get
import interactions.Post
import io.cucumber.java.en.Then
import io.cucumber.java.en.When
import io.iohk.atala.automation.extensions.get
import io.iohk.atala.automation.serenity.ensure.Ensure
import io.iohk.atala.automation.utils.Wait
import net.serenitybdd.rest.SerenityRest
import net.serenitybdd.screenplay.Actor
import org.apache.http.HttpStatus
import org.hyperledger.identus.client.models.*
import java.util.UUID
class UpdateDidSteps {
@When("{actor} updates PRISM DID by adding new key with {curve} curve and {purpose} purpose")
fun actorUpdatesPrismDidByAddingNewKeys(actor: Actor, curve: Curve, purpose: Purpose) {
val newDidKeyId = UUID.randomUUID().toString()
val didKey = ManagedDIDKeyTemplate(
id = newDidKeyId,
purpose = purpose,
curve = curve,
)
val updatePrismDidAction = UpdateManagedDIDRequestAction(
actionType = ActionType.ADD_KEY,
addKey = didKey,
)
actor.remember("newDidKeyId", newDidKeyId)
actor.remember("updatePrismDidAction", updatePrismDidAction)
}
@When("{actor} updates PRISM DID by removing keys")
fun actorUpdatesPrismDidByRemovingKeys(actor: Actor) {
val updatePrismDidAction = UpdateManagedDIDRequestAction(
actionType = ActionType.REMOVE_KEY,
removeKey = RemoveEntryById(TestConstants.PRISM_DID_AUTH_KEY.id),
)
actor.remember("updatePrismDidAction", updatePrismDidAction)
}
@When("{actor} updates PRISM DID with new services")
fun actorUpdatesPrismDidWithNewServices(actor: Actor) {
val updatePrismDidAction = UpdateManagedDIDRequestAction(
actionType = ActionType.ADD_SERVICE,
addService = TestConstants.PRISM_DID_UPDATE_NEW_SERVICE,
)
actor.remember("updatePrismDidAction", updatePrismDidAction)
}
@When("{actor} updates PRISM DID by removing services")
fun actorUpdatesPrismDidByRemovingServices(actor: Actor) {
val updatePrismDidAction = UpdateManagedDIDRequestAction(
actionType = ActionType.REMOVE_SERVICE,
removeService = RemoveEntryById(TestConstants.PRISM_DID_UPDATE_NEW_SERVICE.id),
)
actor.remember("updatePrismDidAction", updatePrismDidAction)
}
@When("{actor} updates PRISM DID by updating services")
fun actorUpdatesPrismDidByUpdatingServices(actor: Actor) {
val newService = UpdateManagedDIDServiceAction(
id = TestConstants.PRISM_DID_SERVICE_FOR_UPDATE.id,
type = TestConstants.PRISM_DID_SERVICE_FOR_UPDATE.type,
serviceEndpoint = Json(
TestConstants.PRISM_DID_UPDATE_NEW_SERVICE_URL,
),
)
val updatePrismDidAction = UpdateManagedDIDRequestAction(
actionType = ActionType.UPDATE_SERVICE,
updateService = newService,
)
actor.remember("updatePrismDidAction", updatePrismDidAction)
}
@When("{actor} submits PRISM DID update operation")
fun actorSubmitsPrismDidUpdateOperation(actor: Actor) {
actor.attemptsTo(
Post.to("/did-registrar/dids/${actor.recall<String>("shortFormDid")}/updates")
.with {
it.body(UpdateManagedDIDRequest(listOf(actor.recall("updatePrismDidAction"))))
},
)
val didOperationResponse = SerenityRest.lastResponse().get<DIDOperationResponse>()
actor.attemptsTo(
Ensure.thatTheLastResponse().statusCode().isEqualTo(HttpStatus.SC_ACCEPTED),
Ensure.that(didOperationResponse.scheduledOperation.didRef).isNotEmpty(),
Ensure.that(didOperationResponse.scheduledOperation.id).isNotEmpty(),
)
}
@Then("{actor} sees PRISM DID was successfully updated with new keys of {purpose} purpose")
fun actorSeesDidSuccessfullyUpdatedWithNewKeys(actor: Actor, purpose: Purpose) {
val newDidKeyId = actor.recall<String>("newDidKeyId")
var i = 0
Wait.until(
errorMessage = "ERROR: DID UPDATE operation did not succeed on the ledger!",
) {
actor.attemptsTo(
Get.resource("/dids/${actor.recall<String>("shortFormDid")}"),
)
val didKey = "${actor.recall<String>("shortFormDid")}#$newDidKeyId"
val didDocument = SerenityRest.lastResponse().get<DIDResolutionResult>().didDocument!!
val foundVerificationMethod = didDocument.verificationMethod!!.map { it.id }.any { it == didKey }
foundVerificationMethod && when (purpose) {
Purpose.ASSERTION_METHOD -> didDocument.assertionMethod!!.any { it == didKey }
Purpose.AUTHENTICATION -> didDocument.authentication!!.any { it == didKey }
Purpose.CAPABILITY_DELEGATION -> didDocument.capabilityDelegation!!.any { it == didKey }
Purpose.CAPABILITY_INVOCATION -> didDocument.capabilityInvocation!!.any { it == didKey }
Purpose.KEY_AGREEMENT -> didDocument.keyAgreement!!.any { it == didKey }
}
}
}
@Then("{actor} sees PRISM DID was successfully updated and keys removed")
fun actorSeesDidSuccessfullyUpdatedAndKeysRemoved(actor: Actor) {
Wait.until(
errorMessage = "ERROR: DID UPDATE operation did not succeed on the ledger!",
) {
actor.attemptsTo(
Get.resource("/dids/${actor.recall<String>("shortFormDid")}"),
)
val authUris = SerenityRest.lastResponse().get<DIDResolutionResult>().didDocument!!.authentication!!
val verificationMethods = SerenityRest.lastResponse()
.get<DIDResolutionResult>().didDocument!!.verificationMethod!!.map { it.id }
authUris.none {
it == "${actor.recall<String>("shortFormDid")}#${TestConstants.PRISM_DID_AUTH_KEY.id}"
} && verificationMethods.none {
it == "${actor.recall<String>("shortFormDid")}#${TestConstants.PRISM_DID_AUTH_KEY.id}"
}
}
}
@Then("{actor} sees PRISM DID was successfully updated with new services")
fun actorSeesDidSuccessfullyUpdatedWithNewServices(actor: Actor) {
Wait.until(
errorMessage = "ERROR: DID UPDATE operation did not succeed on the ledger!",
) {
actor.attemptsTo(
Get.resource("/dids/${actor.recall<String>("shortFormDid")}"),
)
val serviceIds =
SerenityRest.lastResponse().get<DIDResolutionResult>().didDocument!!.service!!.map { it.id }
serviceIds.any {
it == "${actor.recall<String>("shortFormDid")}#${TestConstants.PRISM_DID_UPDATE_NEW_SERVICE.id}"
}
}
}
@Then("{actor} sees PRISM DID was successfully updated by removing services")
fun actorSeesDidSuccessfullyUpdatedByRemovingServices(actor: Actor) {
Wait.until(
errorMessage = "ERROR: DID UPDATE operation did not succeed on the ledger!",
) {
actor.attemptsTo(
Get.resource("/dids/${actor.recall<String>("shortFormDid")}"),
)
val serviceIds =
SerenityRest.lastResponse().get<DIDResolutionResult>().didDocument!!.service!!.map { it.id }
serviceIds.none {
it == "${actor.recall<String>("shortFormDid")}#${TestConstants.PRISM_DID_UPDATE_NEW_SERVICE.id}"
}
}
}
@Then("{actor} sees PRISM DID was successfully updated by updating services")
fun actorSeesDidSuccessfullyUpdatedByUpdatingServices(actor: Actor) {
Wait.until(
errorMessage = "ERROR: DID UPDATE operation did not succeed on the ledger!",
) {
actor.attemptsTo(
Get.resource("/dids/${actor.recall<String>("shortFormDid")}"),
)
val service = SerenityRest.lastResponse().get<DIDResolutionResult>().didDocument!!.service!!
service.any { it.serviceEndpoint.value.contains(TestConstants.PRISM_DID_UPDATE_NEW_SERVICE_URL) }
}
}
}
| 26
|
Scala
|
18
| 72
|
5398a75cfde7ee922588bd84608223abf389d5c1
| 8,224
|
identus-cloud-agent
|
Apache License 2.0
|
kmp/features/appSettings/src/commonMain/kotlin/com/egoriku/grodnoroads/appsettings/domain/util/UrlLauncher.kt
|
BehindWheel
| 485,026,420
| false
|
{"Kotlin": 1196733, "Swift": 86939, "Ruby": 5951, "Shell": 830}
|
package com.egoriku.grodnoroads.appsettings.domain.util
import androidx.compose.runtime.Composable
interface UrlLauncher {
fun openUrl(url: String)
}
@Composable
expect fun rememberUrlLauncher(): UrlLauncher
| 20
|
Kotlin
|
1
| 18
|
d7c3250ff2b360c61398425b7b2c28bf021b175c
| 215
|
BehindWheelKMP
|
Apache License 2.0
|
src/main/kotlin/svg/attributes.kt
|
xfeldman
| 153,592,601
| false
| null |
package svg
import kotlinx.html.attributes.Attribute
import kotlinx.html.attributes.StringAttribute
internal val attributeStringString : Attribute<String> = StringAttribute()
| 0
|
Kotlin
|
1
| 0
|
78e97e0ac5bdbf05159a71096b4d5aecf9e101af
| 177
|
kotlin-d3-sample
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/mongodb/dublinmug_kmm/Expects.kt
|
mongodb-developer
| 546,175,862
| false
|
{"Kotlin": 12017, "Ruby": 1722, "Swift": 1338}
|
package com.mongodb.dublinmug_kmm
expect class RandomUUID(){
val randomId : String
}
expect class Platform(){
val getPlatform : String
}
| 0
|
Kotlin
|
2
| 8
|
e0a0939c9d134e29137e919e6391e74627280b04
| 146
|
Conference-Queries-App
|
Apache License 2.0
|
AndroidApp/domain/src/main/java/me/nya_n/notificationnotifier/domain/usecase/LoadAppUseCase.kt
|
ptkNktq
| 50,931,408
| false
| null |
package me.nya_n.notificationnotifier.domain.usecase
import android.content.pm.PackageManager
import androidx.annotation.VisibleForTesting
import me.nya_n.notificationnotifier.data.repository.AppRepository
import me.nya_n.notificationnotifier.data.repository.UserSettingRepository
import me.nya_n.notificationnotifier.model.AppException
import me.nya_n.notificationnotifier.model.InstalledApp
class LoadAppUseCase(
private val userSettingRepository: UserSettingRepository,
private val appRepository: AppRepository
) {
suspend operator fun invoke(pm: PackageManager): Result<Outputs> {
val apps = loadInstalledAppList(pm).getOrElse {
return Result.failure(it)
}
val targets = loadTargetList()
return Result.success(Outputs(apps, targets))
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
fun loadInstalledAppList(pm: PackageManager): Result<List<InstalledApp>> {
val setting = userSettingRepository.getUserSetting()
return if (!setting.isPackageVisibilityGranted) {
Result.failure(AppException.PermissionDeniedException())
} else {
Result.success(appRepository.loadInstalledAppList(pm))
}
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
suspend fun loadTargetList(): List<InstalledApp> {
return appRepository.getTargetAppList()
}
data class Outputs(
val installs: List<InstalledApp>,
val targets: List<InstalledApp>,
)
}
| 12
|
Kotlin
|
0
| 2
|
412261d4c9b0ec8f05e3cbc0d7a1c5b716190405
| 1,519
|
AndroidNotificationNotifier
|
MIT License
|
common/src/main/kotlin/ru/art/platform/common/emitter/Emitter.kt
|
art-community
| 284,500,366
| false
| null |
package ru.art.platform.common.emitter
import java.lang.Runtime.*
import java.util.concurrent.atomic.*
fun <T> simpleEmitter(emitter: (T) -> Unit = {}) = Emitter(emitter, {}, {})
fun <T> emitterWithErrors(emitter: (T) -> Unit = {}, errorEmitter: (Throwable) -> Unit = {}) = Emitter(emitter, errorEmitter, {})
fun <T> emitter(emitter: (T) -> Unit = {}, errorEmitter: (Throwable) -> Unit = {}, completer: () -> Unit = {}) = Emitter(emitter, errorEmitter, completer)
class Emitter<T>(private val emitter: (T) -> Unit, private val errorEmitter: (Throwable) -> Unit, private val completer: () -> Unit = {}) {
private var completed = AtomicBoolean()
fun emit(value: T) {
emitter(value)
}
fun emitWithError(value: T, throwable: Throwable) {
emit(value)
emitError(throwable)
completer()
}
fun emitWithCompletion(value: T) {
emit(value)
complete()
}
fun emitError(throwable: Throwable) {
errorEmitter(throwable)
}
fun complete() {
if (!completed.get()) {
completer()
getRuntime().gc()
completed.set(true)
}
}
fun completeWithError(throwable: Throwable) {
emitError(throwable)
complete()
}
}
| 1
|
TypeScript
|
0
| 1
|
80051409f70eec2abb66afb7d72359a975198a2b
| 1,266
|
art-platform
|
Apache License 2.0
|
fontawesome/src/de/msrd0/fontawesome/icons/FA_MARS_STROKE_UP.kt
|
msrd0
| 363,665,023
| false
| null |
/* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* 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 de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
/** Mars stroke up */
object FA_MARS_STROKE_UP: Icon {
override val name get() = "Mars stroke up"
override val unicode get() = "f22a"
override val styles get() = setOf(SOLID)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path d="M224 163V144h24c4.418 0 8-3.578 8-7.1V120c0-4.418-3.582-7.1-8-7.1H224V96h24.63c16.41 0 24.62-19.84 13.02-31.44l-60.97-60.97c-4.795-4.793-12.57-4.793-17.36 0L122.3 64.56c-11.6 11.6-3.383 31.44 13.02 31.44H160v15.1H136c-4.418 0-8 3.582-8 7.1v15.1c0 4.422 3.582 7.1 8 7.1H160v19.05c-84.9 15.62-148.5 92.01-143.7 182.5c4.783 90.69 82.34 165.1 173.2 166.5C287.8 513.4 368 434.1 368 336C368 249.7 305.9 178.1 224 163zM192 431.1c-52.94 0-96-43.06-96-95.1s43.06-95.1 96-95.1c52.93 0 96 43.06 96 95.1S244.9 431.1 192 431.1z"/></svg>"""
else -> null
}
}
/** Alias for [FA_MARS_STROKE_UP]. */
val FA_MARS_STROKE_V = FA_MARS_STROKE_UP
| 0
|
Kotlin
|
0
| 0
|
1358935395f9254cab27852457e2aa6c58902e16
| 1,827
|
fontawesome-kt
|
Apache License 2.0
|
app/src/main/java/no/mhl/kotdoc/repository/DocRepository.kt
|
maxhvesser
| 332,813,944
| false
| null |
package no.mhl.kotdoc.repository
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import no.mhl.kotdoc.data.remote.DocService
import javax.inject.Inject
class DocRepository @Inject constructor(
private val docService: DocService
) {
suspend fun getRemoteFile(fileName: String): Flow<List<String>> = callbackFlow {
val document = docService.getMarkdownForFile(fileName)
trySend(document.charStream().readLines().toList())
awaitClose { document.close() }
}
}
| 1
|
Kotlin
|
2
| 4
|
e644ead28ff30410838815c16b308093bc4a3fea
| 573
|
kotdoc-android
|
Apache License 2.0
|
src/main/kotlin/no/nav/syfo/consumer/syfosmregister/sykmeldingModel/SporsmalSvarDTO.kt
|
navikt
| 303,972,532
| false
|
{"Kotlin": 385324, "Dockerfile": 148}
|
package no.nav.syfo.consumer.syfosmregister.sykmeldingModel
data class SporsmalSvarDTO(
val sporsmal: String?,
val svar: String,
val restriksjoner: List<SvarRestriksjonDTO>
)
| 4
|
Kotlin
|
2
| 0
|
40826147d9ea77aaa58a3aa7660203c38e5b77ba
| 188
|
esyfovarsel
|
MIT License
|
gerbera-main/src/main/kotlin/process/Process.kt
|
kotpot
| 672,754,643
| false
|
{"Kotlin": 22941, "HTML": 82}
|
package org.kotpot.gerbera.process
sealed class Process {
abstract val block: suspend () -> Unit
abstract val next: ProcessSwitcher
}
class ProcessBuilder {
private class ProcessImpl : Process() {
override var block: suspend () -> Unit = {}
override var next: ProcessSwitcher = ProcessSwitcher.NEXT
}
fun build(): Process = this
}
| 0
|
Kotlin
|
0
| 4
|
9648fd588fb72affeedaed2a8122575082d712c1
| 372
|
gerbera
|
MIT License
|
src/main/kotlin/kotlinmud/action/contextBuilder/EquippedItemContextBuilder.kt
|
brandonlamb
| 275,313,206
| true
|
{"Kotlin": 435931, "Dockerfile": 133, "Shell": 126}
|
package kotlinmud.action.contextBuilder
import kotlinmud.action.model.Context
import kotlinmud.action.type.Status
import kotlinmud.io.type.Syntax
import kotlinmud.mob.model.Mob
class EquippedItemContextBuilder(private val mob: Mob) : ContextBuilder {
override fun build(syntax: Syntax, word: String): Context<Any> {
return mob.equipped.find { kotlinmud.helper.string.matches(it.name, word) }?.let {
Context<Any>(syntax, Status.OK, it)
} ?: return Context<Any>(
syntax,
Status.ERROR,
"you're not wearing that."
)
}
}
| 0
| null |
0
| 0
|
fc03c6230b9b3b66cd63994e74ddd7897732d527
| 598
|
kotlinmud
|
MIT License
|
features/feature-translate/src/main/java/com/worldturtlemedia/whalesay/features/translate/ui/error/state/ErrorBindingState.kt
|
worldturtlemedia
| 167,640,908
| false
| null |
package com.worldturtlemedia.whalesay.features.translate.ui.error.state
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import com.etiennelenhart.eiffel.binding.BindableMapping1
import com.etiennelenhart.eiffel.binding.BindableState
import com.etiennelenhart.eiffel.binding.bindableMapping
import com.worldturtlemedia.whalesay.features.translate.R
import com.worldturtlemedia.whalesay.features.translate.ui.error.model.ErrorType
typealias LiveErrorBindingState = LiveData<ErrorBindingState>
data class ErrorBindingState(
@StringRes val titleID: Int = R.string.error_generic,
@StringRes val subTitleID: Int = R.string.empty,
val showSubTitle: Boolean = true
) : BindableState {
companion object {
val mapping: BindableMapping1<ErrorState, ErrorBindingState>
get() = bindableMapping { state ->
val id = when (state.type) {
ErrorType.Network -> R.string.error_network
ErrorType.Google -> R.string.error_google
ErrorType.SpeechToText -> R.string.error_speech_to_text
ErrorType.TextToSpeech -> R.string.error_text_to_speech
ErrorType.AudioPlayer -> R.string.error_audio_player
else -> R.string.empty
}
copy(subTitleID = id, showSubTitle = id != R.string.empty)
}
}
}
| 12
|
Kotlin
|
0
| 0
|
fbe09a3c0d5a332b090710626e2f75ca521d8384
| 1,412
|
whalesay
|
MIT License
|
src/main/kotlin/co/csadev/advent2022/Day20.kt
|
gtcompscientist
| 577,439,489
| false
|
{"Kotlin": 252918}
|
/**
* Copyright (c) 2022 by <NAME>
* Advent of Code 2022, Day 20
* Problem Description: http://adventofcode.com/2021/day/20
*/
package co.csadev.advent2022
import co.csadev.adventOfCode.BaseDay
import co.csadev.adventOfCode.Resources.resourceAsList
import co.csadev.adventOfCode.circular
class Day20(override val input: List<String> = resourceAsList("22day20.txt")) :
BaseDay<List<String>, Long, Long> {
private val decryptionKey = 811589153
override fun solvePart1() = mix()
override fun solvePart2() = mix(decryptionKey, 10)
private fun mix(decryptKey: Int = 1, mix: Int = 1): Long {
val base = input.mapIndexed { index, i -> index to i.toLong() * decryptKey }
val mixing = base.toMutableList().circular()
repeat(mix) {
base.forEach { p -> mixing.move(mixing.indexOf(p), p.second) }
}
val output = mixing.map { it.second }
val zero = output.indexOf(0L)
return output.run { this[(zero + 1000) % size] + this[(zero + 2000) % size] + this[(zero + 3000) % size] }
}
}
| 0
|
Kotlin
|
0
| 1
|
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
| 1,068
|
advent-of-kotlin
|
Apache License 2.0
|
libraries/scripting/dependencies-maven/src/kotlin/script/experimental/dependencies/maven/MavenDependenciesResolver.kt
|
BradOselo
| 367,097,840
| true
| null |
/*
* Copyright 2010-2019 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 kotlin.script.experimental.dependencies.maven
import org.eclipse.aether.artifact.DefaultArtifact
import org.eclipse.aether.repository.RemoteRepository
import org.eclipse.aether.resolution.DependencyResolutionException
import org.eclipse.aether.util.artifact.JavaScopes
import org.eclipse.aether.util.repository.AuthenticationBuilder
import java.io.File
import java.util.*
import kotlin.script.experimental.api.ResultWithDiagnostics
import kotlin.script.experimental.api.SourceCode
import kotlin.script.experimental.api.asSuccess
import kotlin.script.experimental.dependencies.ExternalDependenciesResolver
import kotlin.script.experimental.dependencies.RepositoryCoordinates
import kotlin.script.experimental.dependencies.impl.makeResolveFailureResult
import kotlin.script.experimental.dependencies.impl.toRepositoryUrlOrNull
import kotlin.script.experimental.dependencies.maven.impl.AetherResolveSession
import kotlin.script.experimental.dependencies.maven.impl.mavenCentral
import kotlin.script.experimental.dependencies.impl.dependencyScopes
class MavenRepositoryCoordinates(
url: String,
val username: String?,
val password: String?,
val privateKeyFile: String?,
val passPhrase: String?
) : RepositoryCoordinates(url)
class MavenDependenciesResolver : ExternalDependenciesResolver {
override fun acceptsArtifact(artifactCoordinates: String): Boolean =
artifactCoordinates.toMavenArtifact() != null
override fun acceptsRepository(repositoryCoordinates: RepositoryCoordinates): Boolean {
return repositoryCoordinates.toRepositoryUrlOrNull() != null
}
// TODO: make robust
val localRepo = File(File(System.getProperty("user.home")!!, ".m2"), "repository")
val repos: ArrayList<RemoteRepository> = arrayListOf()
private fun remoteRepositories() = if (repos.isEmpty()) arrayListOf(mavenCentral) else repos
private fun allRepositories() = remoteRepositories() + localRepo
private fun String.toMavenArtifact(): DefaultArtifact? =
if (this.isNotBlank() && this.count { it == ':' } >= 2) DefaultArtifact(this)
else null
override suspend fun resolve(
artifactCoordinates: String,
options: ExternalDependenciesResolver.Options,
sourceCodeLocation: SourceCode.LocationWithId?
): ResultWithDiagnostics<List<File>> {
val artifactId = artifactCoordinates.toMavenArtifact()!!
try {
val dependencyScopes = options.dependencyScopes ?: listOf(JavaScopes.COMPILE, JavaScopes.RUNTIME)
val deps = AetherResolveSession(
localRepo, remoteRepositories()
).resolve(
artifactId, dependencyScopes.joinToString(",")
)
if (deps != null)
return ResultWithDiagnostics.Success(deps.map { it.file })
} catch (e: DependencyResolutionException) {
return makeResolveFailureResult(e.message ?: "unknown error", sourceCodeLocation)
}
return makeResolveFailureResult(allRepositories().map { "$it: $artifactId not found" }, sourceCodeLocation)
}
private fun tryResolveEnvironmentVariable(str: String) =
if (str.startsWith("$")) System.getenv(str.substring(1)) ?: str
else str
override fun addRepository(
repositoryCoordinates: RepositoryCoordinates,
options: ExternalDependenciesResolver.Options,
sourceCodeLocation: SourceCode.LocationWithId?
): ResultWithDiagnostics<Boolean> {
val url = repositoryCoordinates.toRepositoryUrlOrNull()
?: return false.asSuccess()
val repoId = repositoryCoordinates.string.replace(FORBIDDEN_CHARS, "_")
val repo = RemoteRepository.Builder(repoId, "default", url.toString())
if (repositoryCoordinates is MavenRepositoryCoordinates) {
val username = repositoryCoordinates.username?.let(::tryResolveEnvironmentVariable)
val password = repositoryCoordinates.password?.let(::tryResolveEnvironmentVariable)
if (username != null) {
val auth = AuthenticationBuilder().apply {
addUsername(username)
if (password != null) {
addPassword(password)
}
}
repo.setAuthentication(auth.build())
}
}
repos.add(repo.build())
return true.asSuccess()
}
companion object {
/**
* These characters are forbidden in Windows, Linux or Mac file names.
* As the repository ID is used in metadata filename generation
* (see [org.eclipse.aether.internal.impl.SimpleLocalRepositoryManager.getRepositoryKey]),
* they should be replaced with an allowed character.
*/
private val FORBIDDEN_CHARS = Regex("[/\\\\:<>\"|?*]")
}
}
| 0
| null |
0
| 3
|
58c7aa9937334b7f3a70acca84a9ce59c35ab9d1
| 5,078
|
kotlin
|
Apache License 2.0
|
model/src/main/kotlin/me/ogq/ocp/sample/model/publicityright/PublicityRight.kt
|
mj-at-ogq
| 605,355,876
| false
| null |
package me.ogq.ocp.sample.model.publicityright
import me.ogq.ocp.sample.model.image.Image
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.OneToMany
@Entity
class PublicityRight(
@Id
var id: Long,
@OneToMany(mappedBy = "publicityRight")
val salesMarkets: MutableSet<Market> = mutableSetOf(),
) {
fun attach(markets: Set<Market>) {
markets.forEach {
it.publicityRight = this
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Image
return id == other.id
}
override fun hashCode(): Int {
return id.hashCode()
}
override fun toString(): String {
return "PublicityRight(id='$id')"
}
}
| 0
|
Kotlin
|
1
| 0
|
43ab8aa22afd010120bdbbe2a5268f33d77f968b
| 834
|
image-platform-api
|
MIT License
|
lib/basic/src/main/java/com/dinesh/basic/app/network/api/util/ApiUtil.kt
|
Dinesh2811
| 745,880,179
| false
|
{"Kotlin": 1200547, "Java": 206284, "JavaScript": 20260}
|
package com.dinesh.basic.app.network.api.util
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Response
fun <T> Response<T?>.relativeUrl(): String {
return try {
val pathSegments = raw().request.url.pathSegments.takeLast(2)
pathSegments.joinToString("/")
} catch (e: Exception) {
raw().request.url.toString()
}
}
//inline fun <reified T> handleError(statusCode: Int?, errorBody: String?): ApiState<T> {
// val errorMessage = extractMessageFromJson(errorBody) ?: "Unknown error"
// Log.e("log_handleError", "Message: $errorMessage, StatusCode: $statusCode")
// return ApiState.Error(message = errorMessage, data = null)
//}
fun extractMessageFromJson(json: String?): String? {
return try {
JSONObject(json.orEmpty()).optString("message")
} catch (e: JSONException) {
null
}
}
| 0
|
Kotlin
|
0
| 1
|
d5b4b55728848196c71c351c186df7e57ad4e8c2
| 877
|
Android101
|
Apache License 2.0
|
app/src/main/java/com/example/androidonkotlin/view/history/HistoryFragment.kt
|
zurbaevi
| 354,132,653
| false
| null |
package com.example.androidonkotlin.view.history
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.androidonkotlin.R
import com.example.androidonkotlin.databinding.FragmentHistoryBinding
import com.example.androidonkotlin.utils.showSnackBar
import com.example.androidonkotlin.viewmodel.AppState
import com.example.androidonkotlin.viewmodel.HistoryViewModel
import kotlinx.android.synthetic.main.fragment_history.*
class HistoryFragment : Fragment() {
private var _binding: FragmentHistoryBinding? = null
private val binding get() = _binding!!
private val viewModel: HistoryViewModel by lazy {
ViewModelProvider(this).get(HistoryViewModel::class.java)
}
private val adapter: HistoryAdapter by lazy { HistoryAdapter() }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
_binding = FragmentHistoryBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
historyFragmentRecyclerView.adapter = adapter
viewModel.historyLiveData.observe(viewLifecycleOwner, Observer { renderData(it) })
viewModel.getAllHistory()
}
private fun renderData(appState: AppState) {
when (appState) {
is AppState.Success -> {
binding.historyFragmentRecyclerView.visibility = View.VISIBLE
binding.includedLoadingLayout.loadingLayout.visibility = View.GONE
adapter.setData(appState.weatherData)
}
is AppState.Loading -> {
binding.historyFragmentRecyclerView.visibility = View.GONE
binding.includedLoadingLayout.loadingLayout.visibility = View.VISIBLE
}
is AppState.Error -> {
binding.historyFragmentRecyclerView.visibility = View.VISIBLE
binding.includedLoadingLayout.loadingLayout.visibility = View.GONE
binding.historyFragmentRecyclerView.showSnackBar(
getString(R.string.error),
getString(R.string.reload),
{ viewModel.getAllHistory() }
)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
@JvmStatic
fun newInstance() = HistoryFragment()
}
}
| 0
|
Kotlin
|
0
| 0
|
a007a4817bcadf9e6d71084bd307ea6e5cea4719
| 2,708
|
android-on-kotlin
|
MIT License
|
src/me/camdenorrb/opencast/commands/sub/IntervalCmd.kt
|
camdenorrb
| 77,727,425
| false
| null |
package me.camdenorrb.opencast.commands.sub
import me.camdenorrb.opencast.OpenCast
import me.camdenorrb.opencast.commands.SubCmd
import org.bukkit.ChatColor.*
import org.bukkit.command.CommandSender
/**
* Created by camdenorrb on 12/27/16.
*/
class IntervalCmd(val openCast: OpenCast) : SubCmd("interval", 1, "$RED/Interval <Seconds>") {
override fun execute(sender: CommandSender, args: MutableList<String>): Boolean {
val delay: Long = try { args[0].toLong() } catch(e: Exception) { return false }
if (delay < 0) return false
openCast.castHandler.messages.delay = delay
openCast.castHandler.disable()
openCast.castHandler.enable()
sender.sendMessage("${DARK_GREEN}Set the delay to $LIGHT_PURPLE$delay ${DARK_GREEN}Seconds!")
return true
}
}
| 0
|
Kotlin
|
0
| 2
|
c7f1d43d1a0eb8a3d7648d8170aecdfecf4e9c6b
| 819
|
OpenCast
|
MIT License
|
stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/call/stats/model/RtcOutboundRtpAudioStreamStats.kt
|
GetStream
| 505,572,267
| false
|
{"Kotlin": 2549850, "MDX": 279508, "Python": 18285, "Shell": 4455, "JavaScript": 1112, "PureBasic": 107}
|
/*
* Copyright (c) 2014-2023 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-video-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getstream.video.android.core.call.stats.model
import java.math.BigInteger
data class RtcOutboundRtpAudioStreamStats(
override val id: String?,
override val type: String?,
override val timestampUs: Double?,
override val ssrc: Long?,
override val kind: String?,
override val transportId: String?,
override val codecId: String?,
override val packetsSent: BigInteger?,
override val bytesSent: BigInteger?,
override val mid: String?,
override val mediaSourceId: String?,
override val remoteId: String?,
override val headerBytesSent: BigInteger?,
override val retransmittedPacketsSent: BigInteger?,
override val retransmittedBytesSent: BigInteger?,
override val rtxSsrc: Long?,
override val targetBitrate: Double?,
override val totalEncodedBytesTarget: BigInteger?,
override val totalEncodeTime: Double?,
override val totalPacketSendDelay: Double?,
override val active: Boolean?,
) : RtcOutboundRtpStreamStats {
companion object {
const val SSRC = RtcSentRtpStreamStats.SSRC
const val KIND = RtcSentRtpStreamStats.KIND
const val TRANSPORT_ID = RtcSentRtpStreamStats.TRANSPORT_ID
const val CODEC_ID = RtcSentRtpStreamStats.CODEC_ID
const val PACKETS_SENT = RtcSentRtpStreamStats.PACKETS_SENT
const val BYTES_SENT = RtcSentRtpStreamStats.BYTES_SENT
const val MID = RtcOutboundRtpStreamStats.MID
const val MEDIA_SOURCE_ID = RtcOutboundRtpStreamStats.MEDIA_SOURCE_ID
const val REMOTE_ID = RtcOutboundRtpStreamStats.REMOTE_ID
const val HEADER_BYTES_SENT = RtcOutboundRtpStreamStats.HEADER_BYTES_SENT
const val RETRANSMITTED_PACKETS_SENT = RtcOutboundRtpStreamStats.RETRANSMITTED_PACKETS_SENT
const val RETRANSMITTED_BYTES_SENT = RtcOutboundRtpStreamStats.RETRANSMITTED_BYTES_SENT
const val RTX_SSRC = RtcOutboundRtpStreamStats.RTX_SSRC
const val TARGET_BITRATE = RtcOutboundRtpStreamStats.TARGET_BITRATE
const val TOTAL_ENCODED_BYTES_TARGET = RtcOutboundRtpStreamStats.TOTAL_ENCODED_BYTES_TARGET
const val TOTAL_ENCODE_TIME = RtcOutboundRtpStreamStats.TOTAL_ENCODE_TIME
const val TOTAL_PACKET_SEND_DELAY = RtcOutboundRtpStreamStats.TOTAL_PACKET_SEND_DELAY
const val ACTIVE = RtcOutboundRtpStreamStats.ACTIVE
}
}
| 3
|
Kotlin
|
30
| 308
|
1c67906e4c01e480ab180f30b39f341675bc147e
| 2,975
|
stream-video-android
|
FSF All Permissive License
|
example/android/app/src/main/kotlin/com/example/client_information_example/MainActivity.kt
|
Tsagaanbayr1
| 387,647,276
| true
|
{"Dart": 24132, "Kotlin": 3583, "Swift": 2884, "Ruby": 2312, "HTML": 1573, "Objective-C": 763}
|
package kent.chien.client_information_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
| null |
0
| 1
|
ad2715b955d09249b531296ec5020a71b11e6d9c
| 142
|
client_information
|
MIT License
|
libraries/api/src/main/java/com/simplecrud/api/interceptors/HelloWorldHeaderInterceptor.kt
|
keppra
| 510,439,516
| false
|
{"Kotlin": 122424, "Java": 33124}
|
package com.simplecrud.api.interceptors
import okhttp3.Interceptor
import okhttp3.Response
import org.koin.core.component.KoinComponent
class HelloWorldHeaderInterceptor: Interceptor, KoinComponent {
override fun intercept(chain: Interceptor.Chain): Response = chain.run {
proceed(
request()
.newBuilder()
.addHeader(name = "Content-Type", value = "application/json")
.addHeader(name = "Accept", value = "application/json")
.build()
)
}
}
| 0
|
Kotlin
|
0
| 0
|
67a6468860c57593e219f3942e1341198023b6e1
| 541
|
simple-crud
|
MIT License
|
app/src/main/java/com/joshuacerdenia/android/nicefeed/ui/viewmodel/EntryViewModel.kt
|
kitlith
| 297,803,241
| true
|
{"Kotlin": 207296}
|
package com.joshuacerdenia.android.nicefeed.ui.viewmodel
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import com.joshuacerdenia.android.nicefeed.data.NiceFeedRepository
import com.joshuacerdenia.android.nicefeed.data.model.Entry
import com.joshuacerdenia.android.nicefeed.data.model.EntryMinimal
import com.joshuacerdenia.android.nicefeed.data.remote.FeedParser
import com.joshuacerdenia.android.nicefeed.utils.EntryToHtmlFormatter
class EntryViewModel : ViewModel() {
private val repo = NiceFeedRepository.get()
private val entryIdLiveData = MutableLiveData<String>()
private val entryLiveData = Transformations.switchMap(entryIdLiveData) { entryId ->
repo.getEntry(entryId)
}
val htmlLiveData = MediatorLiveData<String?>()
var lastPosition: Pair<Int, Int> = Pair(0, 0)
var textSize = 0
private set
var font = 0
var bannerIsEnabled = true
var isInitialLoading = true
var entry: Entry? = null
private set
var isExcerpt = false
private set
init {
htmlLiveData.addSource(entryLiveData) { source ->
if (source != null) {
entry = source
isExcerpt = source.content?.startsWith(FeedParser.FLAG_EXCERPT) ?: false
drawHtml(source)
} else htmlLiveData.value = null
}
}
fun getEntryById(entryId: String) {
entryIdLiveData.value = entryId
}
fun setTextSize(textSize: Int) {
this.textSize = textSize
entryLiveData.value?.let { entry -> drawHtml(entry) }
}
private fun drawHtml(entry: Entry) {
EntryMinimal(
title = entry.title,
date = entry.date,
author = entry.author,
content = entry.content?.removePrefix(FeedParser.FLAG_EXCERPT) ?: ""
).let {
htmlLiveData.value = EntryToHtmlFormatter(textSize, font, !bannerIsEnabled).getHtml(it)
}
}
fun saveChanges() {
entry?.let { entry ->
repo.updateEntryAndFeedUnreadCount(entry.url, true, entry.isStarred)
}
}
}
| 0
| null |
0
| 0
|
8a81efe5886b27efbce15b817d2eab9704543550
| 2,216
|
NiceFeed
|
MIT License
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/ec2/CfnEgressOnlyInternetGatewayPropsDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.ec2
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.ec2.CfnEgressOnlyInternetGatewayProps
@Generated
public fun buildCfnEgressOnlyInternetGatewayProps(initializer: @AwsCdkDsl
CfnEgressOnlyInternetGatewayProps.Builder.() -> Unit): CfnEgressOnlyInternetGatewayProps =
CfnEgressOnlyInternetGatewayProps.Builder().apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
b22e397ff37c5fce365a5430790e5d83f0dd5a64
| 479
|
aws-cdk-kt
|
Apache License 2.0
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/ec2/CfnEgressOnlyInternetGatewayPropsDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.ec2
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.ec2.CfnEgressOnlyInternetGatewayProps
@Generated
public fun buildCfnEgressOnlyInternetGatewayProps(initializer: @AwsCdkDsl
CfnEgressOnlyInternetGatewayProps.Builder.() -> Unit): CfnEgressOnlyInternetGatewayProps =
CfnEgressOnlyInternetGatewayProps.Builder().apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
b22e397ff37c5fce365a5430790e5d83f0dd5a64
| 479
|
aws-cdk-kt
|
Apache License 2.0
|
app/src/main/java/android/project/auction/presentation/updateprofile/UpdateProfileEvent.kt
|
RavanSA
| 515,232,661
| false
|
{"Kotlin": 429676}
|
package android.project.auction.presentation.updateprofile
import android.net.Uri
sealed class UpdateProfileEvent {
data class OnFullNameChange(val value: String) : UpdateProfileEvent()
data class OnTitleChange(val value: String) : UpdateProfileEvent()
data class OnEmailChange(val value: String) : UpdateProfileEvent()
data class OnPhoneNumberChange(val value: String) : UpdateProfileEvent()
data class OnBirthdayChange(val value: String) : UpdateProfileEvent()
data class OnCountryChange(val value: String) : UpdateProfileEvent()
data class OnPostCodeChange(val value: String) : UpdateProfileEvent()
data class OnCityChange(val value: String) : UpdateProfileEvent()
data class OnAddressChange(val value: String) : UpdateProfileEvent()
data class OnProfilePictureChange(val value: Uri) : UpdateProfileEvent()
object OnUpdateButtonClicked : UpdateProfileEvent()
}
| 0
|
Kotlin
|
1
| 3
|
c5914b4870d6b004152c45d6d41d7bd6c99eb9e6
| 909
|
AuctionProject
|
MIT License
|
plugin/src/main/kotlin/io/wttech/gradle/config/InputMode.kt
|
wttech
| 542,640,409
| false
| null |
package io.wttech.gradle.config
enum class InputMode {
DEFAULTS,
GUI,
CLI,
FILE;
companion object {
fun of(name: String) = values().firstOrNull { it.name.equals(name, true) }
?: throw ConfigException("Config input mode '$name' is not supported!")
}
}
| 0
|
Kotlin
|
0
| 1
|
077f5140fab6faa026003c7a602612ee7663061c
| 297
|
gradle-config-plugin
|
Apache License 2.0
|
app/src/main/java/com/example/androiddevchallenge/ui/view/WeatherScreen.kt
|
ked4ma
| 349,264,309
| false
| null |
/*
* Copyright 2021 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
*
* 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.example.androiddevchallenge.ui.view
import android.content.res.Configuration
import androidx.annotation.VisibleForTesting
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Cached
import androidx.compose.material.icons.filled.Error
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.example.androiddevchallenge.R
import com.example.androiddevchallenge.model.CurrentWeather
import com.example.androiddevchallenge.model.Temperature
import com.example.androiddevchallenge.model.WeatherInfo
import com.example.androiddevchallenge.model.Wind
import com.example.androiddevchallenge.ui.theme.MyTheme
import com.example.androiddevchallenge.util.Const
import com.example.androiddevchallenge.util.LoadState
import com.example.androiddevchallenge.util.ShowState
import com.example.androiddevchallenge.vm.AppViewModel
import dev.chrisbanes.accompanist.insets.navigationBarsPadding
import dev.chrisbanes.accompanist.insets.statusBarsPadding
import java.time.LocalDateTime
import kotlin.math.pow
@Composable
fun WeatherScreen() {
val viewModel = AppViewModel.weather
val state by viewModel.weatherInfoState.collectAsState()
WeatherScreen(state = state, now = viewModel.currentTime) {
viewModel.refreshRepository()
}
}
@VisibleForTesting
@Composable
fun WeatherScreen(state: LoadState<WeatherInfo>, now: LocalDateTime, onClickRefresh: () -> Unit) {
Crossfade(
state,
) { loadState ->
Box(
modifier = Modifier
.fillMaxSize()
.statusBarsPadding()
.navigationBarsPadding()
) {
when (loadState) {
is LoadState.Loading -> LoadingScreen(
modifier = Modifier
.align(Alignment.Center)
.semantics {
testTag = "Loading"
}
)
is LoadState.Error -> ErrorScreen(
modifier = Modifier
.align(Alignment.Center)
.semantics {
testTag = "Error"
}
) {
onClickRefresh()
}
is LoadState.Loaded -> ContentScreen(
weatherInfo = loadState.value,
now = now,
modifier = Modifier.semantics {
testTag = "Loaded"
}
)
}
}
}
}
@Composable
private fun LoadingScreen(modifier: Modifier = Modifier) {
val infiniteTransition = rememberInfiniteTransition()
val loadDotNum by infiniteTransition.animateFloat(
initialValue = 0F,
targetValue = 199F,
animationSpec = infiniteRepeatable(
animation = tween(2000, easing = LinearEasing),
repeatMode = RepeatMode.Restart
)
)
when (loadDotNum.toInt() / 50) {
1 -> Text(
text = stringResource(R.string.loading1),
modifier = modifier,
style = MyTheme.typography.body1
)
2 -> Text(
text = stringResource(R.string.loading2),
modifier = modifier,
style = MyTheme.typography.body1
)
3 -> Text(
text = stringResource(R.string.loading3),
modifier = modifier,
style = MyTheme.typography.body1
)
else -> Text(
text = stringResource(R.string.loading0),
modifier = modifier,
style = MyTheme.typography.body1
)
}
}
@VisibleForTesting
@Composable
fun ErrorScreen(modifier: Modifier = Modifier, onClickRefresh: () -> Unit) {
Column(modifier = modifier) {
Icon(
imageVector = Icons.Default.Error,
contentDescription = null,
modifier = Modifier
.size(80.dp)
.align(Alignment.CenterHorizontally)
)
Text(
text = "Failed to load Weather Info.",
style = MyTheme.typography.body1,
modifier = Modifier.paddingFromBaseline(
top = 20.dp,
bottom = 8.dp
)
)
IconButton(
modifier = Modifier
.size(60.dp)
.align(Alignment.CenterHorizontally)
.semantics {
testTag = "Refresh Button"
},
onClick = {
onClickRefresh()
}
) {
Icon(
imageVector = Icons.Default.Cached,
contentDescription = null,
modifier = Modifier
.size(60.dp)
)
}
}
}
@Composable
private fun ContentScreen(
modifier: Modifier = Modifier,
weatherInfo: WeatherInfo,
now: LocalDateTime
) {
if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) {
Column(modifier = modifier) {
ContentScreenPortrait(
data = weatherInfo.current,
now = now,
modifier = Modifier.weight(1F)
)
WeatherForecast(
forecast = weatherInfo.forecast,
modifier = Modifier.weight(1F)
)
}
} else {
Box(modifier = modifier) {
WeatherForecast(
forecast = weatherInfo.forecast,
modifier = Modifier.fillMaxSize()
)
ContentScreenLandscape(
data = weatherInfo.current,
now = now,
modifier = Modifier.fillMaxSize()
)
}
}
}
@Composable
private fun ContentScreenPortrait(
modifier: Modifier = Modifier,
data: CurrentWeather,
now: LocalDateTime
) {
ConstraintLayout(modifier = modifier.fillMaxWidth()) {
val transitionState = remember { MutableTransitionState(ShowState.Hidden) }
transitionState.targetState = ShowState.Show
val transition = updateTransition(transitionState)
val iconTransition by transition.animateFloat(
transitionSpec = {
tween(durationMillis = 500)
}
) { state ->
when (state) {
ShowState.Hidden -> 0F
ShowState.Show -> 1F
}
}
val iconGuide = createGuidelineFromStart(iconTransition / 2)
val (icon, info) = createRefs()
WeatherIcon(
weather = data.weather,
dateTime = now,
modifier = Modifier
.constrainAs(icon) {
centerVerticallyTo(parent)
end.linkTo(iconGuide)
width = Dimension.percent(0.5F)
}
.alpha(iconTransition)
)
val infoTransition by transition.animateFloat(
transitionSpec = {
tween(durationMillis = 500, delayMillis = 300)
}
) { state ->
when (state) {
ShowState.Hidden -> 0F
ShowState.Show -> 1F
}
}
WeatherInfo(
title = data.desc, temperature = data.temp, wind = data.wind,
modifier = Modifier
.constrainAs(info) {
centerVerticallyTo(parent)
end.linkTo(parent.end)
width = Dimension.percent(0.5F)
}
.alpha(infoTransition)
)
}
}
@Composable
private fun ContentScreenLandscape(
modifier: Modifier = Modifier,
data: CurrentWeather,
now: LocalDateTime
) {
ConstraintLayout(modifier = modifier.fillMaxWidth()) {
val transitionState = remember { MutableTransitionState(ShowState.Hidden) }
transitionState.targetState = ShowState.Show
val transition = updateTransition(transitionState)
val iconTransition by transition.animateFloat(
transitionSpec = {
tween(durationMillis = 500)
}
) { state ->
when (state) {
ShowState.Hidden -> 0F
ShowState.Show -> 1F
}
}
val iconGuide = createGuidelineFromStart(iconTransition / 2)
val (icon, info) = createRefs()
Box(
modifier = Modifier
.constrainAs(icon) {
top.linkTo(parent.top)
end.linkTo(iconGuide)
width = Dimension.percent(0.5F)
height = Dimension.percent(0.6F)
}
.alpha(iconTransition)
) {
WeatherIcon(
weather = data.weather,
dateTime = now,
modifier = Modifier
.fillMaxHeight()
.align(Alignment.Center)
)
}
val infoTransition by transition.animateFloat(
transitionSpec = {
tween(durationMillis = 500, delayMillis = 300)
}
) { state ->
when (state) {
ShowState.Hidden -> 0F
ShowState.Show -> 1F
}
}
WeatherInfo(
title = data.desc, temperature = data.temp, wind = data.wind,
modifier = Modifier
.padding(top = 20.dp)
.constrainAs(info) {
top.linkTo(parent.top)
end.linkTo(parent.end)
width = Dimension.percent(0.5F)
}
.alpha(infoTransition)
)
}
}
@Composable
private fun WeatherInfo(
modifier: Modifier = Modifier,
title: String,
temperature: Temperature,
wind: Wind,
) {
Column(modifier = modifier) {
Text(
text = title,
style = MyTheme.typography.h3,
)
/**
* calc temperature color roughly
*/
fun temperatureColor(value: Float): Color {
val v = value.coerceIn(-10F, 30F) + 10 // 0..40
val r = (1F / 10) * (v - 30).coerceAtLeast(0F)
val (g, b) = if (v >= 30) {
1F - (1F / 10) * (v - 30) to 0F
} else {
val k = (v / 30F).pow(2)
k to 1F - k
}
return Color(r, g, b)
}
Text(
text = stringResource(R.string.temperature, (temperature.value - Const.Kelvin).toInt()),
color = temperatureColor(temperature.value - Const.Kelvin),
style = MyTheme.typography.h1,
modifier = Modifier.align(Alignment.CenterHorizontally),
)
Text(
text = stringResource(
R.string.temperature_range,
(temperature.max - Const.Kelvin).toInt(),
(temperature.min - Const.Kelvin).toInt()
),
style = MyTheme.typography.body1,
modifier = Modifier.align(Alignment.CenterHorizontally),
)
Row(
modifier = Modifier
.align(Alignment.CenterHorizontally)
) {
Icon(
painter = painterResource(id = R.drawable.ic_strong_wind),
contentDescription = "",
modifier = Modifier
.size(18.dp)
.align(Alignment.CenterVertically),
)
Text(
text = stringResource(R.string.wind_speed, wind.speed),
style = MyTheme.typography.body1,
modifier = Modifier
.align(Alignment.CenterVertically),
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
440dd9a070b329fc6aeb237878e6a2665bcacf4d
| 14,105
|
AndroidDevChallengeJetpackComposeWeek4
|
Apache License 2.0
|
app/src/main/java/me/proton/reactiveui/ui/MessagesListScreen.kt
|
4face-studi0
| 508,248,835
| false
| null |
package me.proton.reactiveui.ui
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import me.proton.reactiveui.model.MessageInfo
import me.proton.reactiveui.sampledata.Data
import me.proton.reactiveui.ui.theme.ProtonReactiveUiTheme
object MessagesListScreen {
@get:Composable
private val contentPadding get() = PaddingValues(vertical = 8.dp)
@Composable
operator fun invoke(
messages: List<MessageInfo>,
onMessageClick: (MessageInfo) -> Unit,
modifier: Modifier = Modifier
) {
LazyColumn(modifier = modifier, contentPadding = contentPadding) {
items(messages) {
MessageListItem(messageInfo = it, onClick = onMessageClick)
}
}
}
@Composable
fun Selectable(
messages: List<MessageInfo>,
initialSelected: MessageInfo?,
onMessageClick: (MessageInfo) -> Unit,
modifier: Modifier = Modifier
) {
var selected by remember { mutableStateOf(initialSelected) }
LazyColumn(modifier = modifier, contentPadding = contentPadding) {
items(messages) { messageInfo ->
MessageListItem.Selectable(
messageInfo = messageInfo,
isSelected = selected == messageInfo,
onClick = { selectedMessageInfo ->
selected = selectedMessageInfo
onMessageClick(selectedMessageInfo)
}
)
}
}
}
}
@Composable
@Preview(showBackground = true)
private fun MessagesListScreenPreview() {
val messages = Data.Messages.all().map { it.info }
ProtonReactiveUiTheme {
MessagesListScreen(messages, onMessageClick = {})
}
}
@Composable
@Preview(showBackground = true)
private fun SelectedMessagesListScreenPreview() {
val messages = Data.Messages.all().map { it.info }
val initialSelected = Data.Messages.Birthday.info
ProtonReactiveUiTheme {
MessagesListScreen.Selectable(messages, initialSelected = initialSelected, onMessageClick = {})
}
}
| 0
|
Kotlin
|
1
| 0
|
3bcd2cda818f22ef259f8d36512f52e8f966a4c8
| 2,539
|
ProtonReactiveUI
|
Apache License 2.0
|
containers/src/commonTest/kotlin/IteratorTests.kt
|
aeckar
| 834,956,853
| false
|
{"Kotlin": 123024, "ANTLR": 18047}
|
import io.github.aeckar.parsing.containers.PivotIterator
import io.github.aeckar.parsing.containers.RevertibleIterator
import io.github.aeckar.parsing.containers.pivotIterator
import io.github.aeckar.parsing.containers.revertibleIterator
import kotlinx.io.buffered
import kotlinx.io.files.Path
import kotlinx.io.files.SystemFileSystem
import kotlinx.io.readString
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
private const val SOURCE_TXT = "A3Z8q9B5C2"
private val LIST = listOf("first", 2, 3.0)
class IteratorTests {
private fun RevertibleIterator<*, *>.testReverting(elements: List<*>) {
assertFailsWith<IllegalStateException> { revert() }
save()
save()
next()
removeSave()
assertEquals(elements[1], next())
revert()
assertEquals(elements[0], next())
}
private fun PivotIterator<*, *, Array<Int>>.testPivoting() {
save()
save()
next()
removeSave()
next()
here()[0] = 16
revert()
advance(2)
assertEquals(16, here()[0])
advance(2)
assertFailsWith<NoSuchElementException> { next() }
}
@Test
fun `revertible list iterator`() {
assertContentEquals(LIST, LIST.revertibleIterator().asSequence().toList())
LIST.revertibleIterator().testReverting(LIST)
}
@Test
fun `revertible string iterator`() {
SOURCE_TXT.revertibleIterator().testReverting(SOURCE_TXT.toList())
}
@Test
fun `revertible source iterator`() {
val source = SystemFileSystem.source(Path("src/commonTest/resources/source.txt"))
source.revertibleIterator().testReverting(SOURCE_TXT.toList())
// play with SECTION_SIZE, too
}
@Test
fun `pivoting list iterator`() {
assertContentEquals(LIST, LIST.pivotIterator { arrayOf(0) }.asSequence().toList())
LIST.pivotIterator { arrayOf(0) }.testReverting(LIST)
LIST.pivotIterator { arrayOf(0) }.testPivoting()
}
@Test
fun `pivoting string iterator`() {
SOURCE_TXT.pivotIterator { arrayOf(0) }.testReverting(SOURCE_TXT.toList())
SOURCE_TXT.pivotIterator { arrayOf(0) }.testPivoting()
}
@Test
fun `pivoting source iterator`() {
fun getSource() = SystemFileSystem.source(Path("src/commonTest/resources/source.txt"))
assertEquals(
expected = getSource().buffered().readString(),
actual = getSource().pivotIterator { arrayOf(0) }.asSequence().joinToString(separator = "")
)
getSource().pivotIterator { arrayOf(0) }.testReverting(SOURCE_TXT.toList())
getSource().pivotIterator { arrayOf(0) }.testPivoting()
// play with SECTION_SIZE, too
}
}
| 0
|
Kotlin
|
0
| 1
|
1682778adfd33ba3d38d0f967d80a0277b96216c
| 2,826
|
modular-parsers
|
MIT License
|
app/src/main/java/com/example/currency_converter_plus/model/remote/RetrofitClient.kt
|
AntonyLajes
| 575,114,247
| false
|
{"Kotlin": 19508}
|
package com.example.currency_converter_plus.model.remote
import com.example.currency_converter_plus.util.constants.RetrofitConstants
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class RetrofitClient private constructor() {
companion object{
private lateinit var INSTANCE: Retrofit
private val client = OkHttpClient.Builder().apply {
addInterceptor(CurrencyConverterInterceptor())
}.build()
fun getRetrofit(): Retrofit{
if(!::INSTANCE.isInitialized){
INSTANCE = Retrofit.Builder()
.baseUrl(RetrofitConstants.BASE_URL_CC)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return INSTANCE
}
}
}
| 0
|
Kotlin
|
0
| 0
|
089dc6c8b97512f2ebbf2b17da3f57eb78feccc0
| 879
|
currency-converter-plus
|
MIT License
|
app/src/main/java/coder/seventy/two/ecommerce/SingleCategoryProducts.kt
|
waiferkolar
| 178,734,222
| false
| null |
package coder.seventy.two.ecommerce
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.view.MenuItemCompat
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import coder.seventy.two.ecommerce.adapters.ProductAdapter
import coder.seventy.two.ecommerce.libby.H
import coder.seventy.two.ecommerce.libby.H.Companion.USER_TOKEN
import coder.seventy.two.ecommerce.libby.H.Companion.l
import coder.seventy.two.ecommerce.modals.Products
import coder.seventy.two.ecommerce.services.ServiceBuilder
import coder.seventy.two.ecommerce.services.WebService
import kotlinx.android.synthetic.main.activity_single_category_products.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class SingleCategoryProducts : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single_category_products)
if (H.checkUserAuth()) {
val intent = Intent(this, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
}
var bundle: Bundle = intent.extras
var catId = bundle.getString("cat_id")
singCategoryProductRecycler.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
loadAllProductOfACategory(catId)
}
private fun loadAllProductOfACategory(catId: String) {
val services: WebService = ServiceBuilder.buildService(WebService::class.java)
val responseProduct: Call<Products> = services.getProductsOfACategory("Bearer $USER_TOKEN", catId)
responseProduct.enqueue(object : Callback<Products> {
override fun onFailure(call: Call<Products>, t: Throwable) {
l(t.message!!)
}
override fun onResponse(call: Call<Products>, response: Response<Products>) {
if (response.isSuccessful) {
val prod: Products = response.body()!!
val products = prod.products
singCategoryProductRecycler.adapter = ProductAdapter(this@SingleCategoryProducts, products)
} else {
l("Something not right")
}
}
})
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
val item: MenuItem = menu.findItem(R.id.cart)
MenuItemCompat.setActionView(item, R.layout.my_cart_layout)
return super.onCreateOptionsMenu(menu)
}
}
| 0
|
Kotlin
|
0
| 1
|
0cb3ac52ab2c0ac18635a85827b9a81d91a94fa5
| 2,736
|
72Android-Ecommerce
|
Freetype Project License
|
common/src/main/java/net/sistr/flexibleguns/resource/DataDrivenModelLoader.kt
|
SistrScarlet
| 437,250,021
| false
|
{"Kotlin": 239434, "Java": 36089}
|
package net.sistr.flexibleguns.resource
import com.google.common.collect.Lists
import net.minecraft.resource.ResourceManager
import net.minecraft.util.Identifier
import net.sistr.flexibleguns.FlexibleGunsMod
class DataDrivenModelLoader {
companion object {
val INSTANCE = DataDrivenModelLoader()
}
val ids = Lists.newArrayList<Identifier>()
fun load(manager: ResourceManager) {
FlexibleGunsMod.LOGGER.info("now loading DataDrivenModelLoader..")
ids.clear()
for (id in manager.findResources(
"models/item/non_item"
) { path: String -> path.endsWith(".json") }) {
val length = "models/item".length
val path = id.path.substring(length + 1)
val loadId = Identifier(id.namespace, path.substring(0, path.lastIndexOf(".")))
ids.add(loadId)
FlexibleGunsMod.LOGGER.info("$id : $loadId")
}
}
}
| 0
|
Kotlin
|
0
| 2
|
c00fbbfbd98a253f971cb9f5c87a4cf3eef9b6a2
| 926
|
FlexibleGuns
|
MIT License
|
src/test/kotlin/eZmaxApi/models/FieldEEzsigntemplateelementdependencyOperatorTest.kt
|
eZmaxinc
| 271,950,932
| false
|
{"Kotlin": 6909939}
|
/**
*
* 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 eZmaxApi.models
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import eZmaxApi.models.FieldEEzsigntemplateelementdependencyOperator
class FieldEEzsigntemplateelementdependencyOperatorTest : ShouldSpec() {
init {
// uncomment below to create an instance of FieldEEzsigntemplateelementdependencyOperator
//val modelInstance = FieldEEzsigntemplateelementdependencyOperator()
}
}
| 0
|
Kotlin
|
0
| 0
|
961c97a9f13f3df7986ea7ba55052874183047ab
| 705
|
eZmax-SDK-kotlin
|
MIT License
|
src/test/kotlin/org/jetbrains/kotlinx/jupyter/test/embeddingTest.kt
|
Snowgrass
| 363,977,155
| true
|
{"Kotlin": 492519, "HTML": 54181, "JavaScript": 38779, "CSS": 16140, "Python": 6245, "Shell": 73}
|
package org.jetbrains.kotlinx.jupyter.test
import org.jetbrains.kotlinx.jupyter.ReplForJupyterImpl
import org.jetbrains.kotlinx.jupyter.api.MimeTypedResult
import org.jetbrains.kotlinx.jupyter.api.ResultHandlerCodeExecution
import org.jetbrains.kotlinx.jupyter.api.SubtypeRendererTypeHandler
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryDefinitionImpl
import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryResource
import org.jetbrains.kotlinx.jupyter.api.libraries.ResourceFallbacksBundle
import org.jetbrains.kotlinx.jupyter.api.libraries.ResourceLocation
import org.jetbrains.kotlinx.jupyter.api.libraries.ResourcePathType
import org.jetbrains.kotlinx.jupyter.api.libraries.ResourceType
import org.jetbrains.kotlinx.jupyter.execute
import org.jetbrains.kotlinx.jupyter.test.repl.AbstractReplTest
import org.junit.jupiter.api.Test
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class SomeSingleton {
companion object {
var initialized: Boolean = false
}
}
/**
* Used for [EmbedReplTest.testSubtypeRenderer]
*/
@Suppress("unused")
class TestSum(val a: Int, val b: Int)
/**
* Used for [EmbedReplTest.testSubtypeRenderer]
*/
class TestFunList<T>(private val head: T, private val tail: TestFunList<T>?) {
@Suppress("unused")
fun render(): String {
return generateSequence(this) {
it.tail
}.joinToString(", ", "[", "]") {
it.head.toString()
}
}
}
/**
* Used for [EmbedReplTest.testSubtypeRenderer]
*/
@Suppress("unused")
val testLibraryDefinition1 = LibraryDefinitionImpl(
renderers = listOf(
SubtypeRendererTypeHandler(
TestSum::class,
ResultHandlerCodeExecution("\$it.a + \$it.b")
),
SubtypeRendererTypeHandler(
TestFunList::class,
ResultHandlerCodeExecution("\$it.render()")
)
)
)
/**
* Used for [EmbedReplTest.testJsResources]
*/
@Suppress("unused")
val testLibraryDefinition2 = LibraryDefinitionImpl(
resources = listOf(
LibraryResource(
listOf(
ResourceFallbacksBundle(
ResourceLocation(
"https://cdn.plot.ly/plotly-latest.min.js",
ResourcePathType.URL
)
),
ResourceFallbacksBundle(
ResourceLocation(
"src/test/testData/js-lib.js",
ResourcePathType.LOCAL_PATH
)
),
),
ResourceType.JS,
"testLib2"
)
)
)
class EmbedReplTest : AbstractReplTest() {
private val repl = run {
val embeddedClasspath: List<File> = System.getProperty("java.class.path").split(File.pathSeparator).map(::File)
ReplForJupyterImpl(resolutionInfoProvider, embeddedClasspath, isEmbedded = true)
}
@Test
fun testSharedStaticVariables() {
var res = repl.eval("org.jetbrains.kotlinx.jupyter.test.SomeSingleton.initialized")
assertEquals(false, res.resultValue)
SomeSingleton.initialized = true
res = repl.eval("org.jetbrains.kotlinx.jupyter.test.SomeSingleton.initialized")
assertEquals(true, res.resultValue)
}
@Test
fun testCustomClasses() {
repl.eval("class Point(val x: Int, val y: Int)")
repl.eval("val p = Point(1,1)")
val res = repl.eval("p.x")
assertEquals(1, res.resultValue)
}
@Test
fun testSubtypeRenderer() {
repl.execute {
addLibrary(testLibraryDefinition1)
}
val result1 = repl.eval("org.jetbrains.kotlinx.jupyter.test.TestSum(5, 8)")
assertEquals(13, result1.resultValue)
val result2 = repl.eval(
"""
import org.jetbrains.kotlinx.jupyter.test.TestFunList
TestFunList(12, TestFunList(13, TestFunList(14, null)))
""".trimIndent()
)
assertEquals("[12, 13, 14]", result2.resultValue)
}
@Test
fun testJsResources() {
val displayHandler = TestDisplayHandler()
val res = repl.eval(
"USE(org.jetbrains.kotlinx.jupyter.test.testLibraryDefinition2)",
displayHandler
)
assertTrue(res.resultValue is Unit)
assertEquals(1, displayHandler.list.size)
val typedResult = displayHandler.list[0] as MimeTypedResult
val content = typedResult["text/html"]!!
assertTrue(content.contains("""id="kotlin_out_0""""))
assertTrue(content.contains("""function test_fun(x)"""))
}
}
| 8
| null |
0
| 0
|
ce0bf03f5423c1861e8cd777874a00f71ec144cb
| 4,641
|
kotlin-jupyter
|
Apache License 2.0
|
src/main/kotlin/org/teamvoided/dusk_debris/block/voided/sign/VoidSignBlock.kt
|
TeamVoided
| 814,767,803
| false
|
{"Kotlin": 153037, "Java": 3724}
|
package org.teamvoided.dusk_debris.block.voided.sign
import net.minecraft.block.sign.SignBlock
import net.minecraft.block.sign.SignType
import net.minecraft.util.Identifier
class VoidSignBlock(override val texture: Identifier, woodType: SignType, settings: Settings) :
SignBlock(woodType, settings.solid()), VoidSign
| 0
|
Kotlin
|
0
| 0
|
7973b474b08276fc01cb6222ceadf235004c29f3
| 324
|
Dusk-Debris
|
MIT License
|
domain-recipes/src/main/java/pl/smcebi/recipeme/domain/recipes/GetQuickAnswerUseCase.kt
|
Seba0855
| 616,026,534
| false
|
{"Kotlin": 89067}
|
package pl.smcebi.recipeme.domain.recipes
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import pl.smcebi.recipeme.domain.common.dispatchers.DispatcherIO
import pl.smcebi.recipeme.domain.common.utils.DomainResult
import pl.smcebi.recipeme.domain.common.utils.getErrorMessage
import pl.smcebi.recipeme.domain.recipes.model.QuickAnswerUI
import pl.smcebi.recipeme.recipes.QuickAnswerResponse
import pl.smcebi.recipeme.recipes.RecipesDataSource
import javax.inject.Inject
class GetQuickAnswerUseCase @Inject internal constructor(
private val dataSource: RecipesDataSource,
@DispatcherIO private val dispatcher: CoroutineDispatcher
) {
suspend operator fun invoke(query: String): DomainResult<QuickAnswerUI, String?> =
withContext(dispatcher) {
dataSource.getQuickAnswer(query).map(
onSuccess = { response ->
DomainResult.Success(response.mapUI())
},
onError = { _, errorBody ->
DomainResult.Failure(errorBody.getErrorMessage())
}
)
}
private fun QuickAnswerResponse.mapUI(): QuickAnswerUI =
QuickAnswerUI(
answer = this.answer,
image = this.image
)
}
| 0
|
Kotlin
|
0
| 0
|
04a9966a50929063f3f85c2c270c91ce3133575e
| 1,288
|
recipe.me
|
Apache License 2.0
|
src/main/kotlin/mindustry_plugin_utils/Templates.kt
|
jakubDoka
| 366,089,363
| false
| null |
package mindustry_plugin_utils
import java.lang.Integer.max
import java.lang.Integer.min
import java.lang.StringBuilder
object Templates {
fun page(title: String, lines: Array<String>, cap: Int, index: Int, color :String = "orange", comment: String = ""): String {
val count = lines.size / cap
val max = if(count * cap < lines.size) count else count + 1
val id = max(min(max, index - 1), 0)
val sb = StringBuilder()
if(comment.isNotEmpty()) sb.append(comment).append("\n\n")
for(i in cap * id until min(cap*(id+1), lines.size)) {
sb.append(lines[i]).append("\n")
}
return info(title, sb.toString(), color)
}
fun info(title: String, body: String, color: String = "orange"): String {
return "[$color]==$title==[]\n\n$body"
}
fun clean(string: String, begin: String?, end: String?): String {
var string = string
var fromBegin = 0
var fromEnd = 0
while (string.contains(begin!!)) {
val first = string.indexOf(begin, fromBegin)
val last = string.indexOf(end!!, fromEnd)
if (first == -1 || last == -1) break
if (first > last) {
fromBegin = first + 1
fromEnd = last + 1
}
string = string.substring(0, first) + string.substring(last + 1)
}
return string
}
fun cleanEmotes(string: String): String {
return clean(string, "<", ">")
}
fun cleanColors(string: String): String {
return clean(string, "[", "]")
}
fun cleanName(name: String): String? {
return cleanEmotes(cleanColors(name)).replace(" ", "_")
}
fun Long.time(): String {
val sec = this / 1000
val min = sec / 60
val hour = min / 60
val days = hour / 24
return String.format("%d:%02d:%02d:%02d", days % 365, hour % 24, min % 60, sec % 60)
}
}
| 0
|
Kotlin
|
0
| 0
|
8c05670e12a18072e35654750df20d47deb1e21f
| 1,957
|
mindustry-plugin-utils
|
MIT License
|
src/main/kotlin/dev/emad/framework/data/remote/response/mapper/AudioResponseMapper.kt
|
razavioo
| 541,187,073
| false
| null |
package dev.emad.framework.data.remote.response.mapper
import dev.emad.business.model.Audio
import dev.emad.framework.data.local.mapper.Mapper
import dev.emad.framework.data.remote.response.model.AudioResponse
class AudioResponseMapper : Mapper<Audio, AudioResponse>() {
override fun from(value: Audio): AudioResponse {
val websiteUrl = System.getenv("API_URL") ?: "http://0.0.0.0:8080"
val downloadUrl = "$websiteUrl/audio/${value.redirectionId}"
return AudioResponse(
id = value.id,
pageUrl = value.pageUrl,
downloadUrl = downloadUrl
)
}
}
| 0
|
Kotlin
|
0
| 3
|
089d88eb806226e907976f0e631c1cf19710ea7b
| 619
|
any-audio-finder
|
MIT License
|
app/src/androidTest/java/com/example/movieapp/detail/DetailFragmentTest.kt
|
Ahnset
| 539,038,324
| false
|
{"Kotlin": 138435}
|
package com.example.movieapp.detail
import androidx.core.os.bundleOf
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.Visibility.VISIBLE
import androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import com.example.movieapp.common.MockWebServerHelper.serverIsDone
import com.example.movieapp.common.MockWebServerHelper.setSuccessMockedResponse
import com.example.movieapp.common.TestHelper.NestedScrollTo
import com.example.movieapp.common.launchFragmentInHiltContainer
import com.example.movieapp.detail.ui.DetailFragment
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockWebServer
import org.awaitility.kotlin.await
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import javax.inject.Inject
@HiltAndroidTest
@ExperimentalCoroutinesApi
class DetailFragmentTest {
@get:Rule(order = 0)
var hiltRule = HiltAndroidRule(this)
@Inject
lateinit var client: OkHttpClient
private val mockWebServer = MockWebServer()
@Before
fun setup() {
hiltRule.inject()
mockWebServer.start(8080)
}
@Test
fun shouldLaunchFragmentInContainer() = runTest {
// Arrange
val movieId = 0
val args = bundleOf("movieId" to movieId)
setSuccessMockedResponse(mockWebServer, movieId)
// Act
launchFragmentInHiltContainer<DetailFragment>(args)
}
@Test
fun shouldShowCorrectContentWhenDetailIsFetched() = runTest {
// Arrange
val movieId = 0
val args = bundleOf("movieId" to movieId)
val expectedTitle = "Orphan: First Kill"
setSuccessMockedResponse(mockWebServer, movieId)
// Act
launchFragmentInHiltContainer<DetailFragment>(args)
await.until(serverIsDone(client))
// Assert
onView(withId(R.id.detailContent))
.check(matches(withEffectiveVisibility(VISIBLE)))
onView(withId(R.id.movieTitle))
.check(matches(withText(expectedTitle)))
}
@Test
fun shouldShowSnackMessageWhenBookmarkButtonIsClicked() = runTest {
// Arrange
val movieId = 0
val args = bundleOf("movieId" to movieId)
val expectedText = "TODO:// Add Bookmark feature."
setSuccessMockedResponse(mockWebServer, movieId)
// Act
launchFragmentInHiltContainer<DetailFragment>(args)
await.until(serverIsDone(client))
onView(withId(R.id.detailBookmarkButton))
.perform(NestedScrollTo(), click())
// Assert
onView(withText(expectedText))
.check(matches(withEffectiveVisibility(VISIBLE)))
}
@After
fun teardown() {
mockWebServer.shutdown()
}
}
| 0
|
Kotlin
|
2
| 3
|
a5ddc921f8f4df80cc13f17284015086fe6112b0
| 3,199
|
movieapp
|
Apache License 2.0
|
features/chart/src/commonMain/kotlin/com/mathroda/chart/common/model/MultiChartDataSet.kt
|
MathRoda
| 507,060,394
| false
|
{"Kotlin": 446115, "Swift": 4323, "Ruby": 2379, "Java": 624}
|
package com.mathroda.chart.common.model
import com.mathroda.chart.common.internal.common.model.ChartDataItem
import com.mathroda.chart.common.internal.common.model.MultiChartData
import com.mathroda.chart.common.internal.common.model.toChartData
/**
* A class that represents a data set for a chart.
*
* @property data The data item that represents the data set.
* @constructor Creates a new ChartDataSet with the provided items, title, prefix, and postfix.
*
* @param items The list of data items.
* @param title The title of the data set.
* @param prefix The prefix to be added to each data item. Defaults to an empty string.
* @param postfix The postfix to be added to each data item. Defaults to an empty string.
*/
class MultiChartDataSet(
items: List<Pair<String, List<Float>>>,
categories: List<String> = emptyList(),
title: String,
prefix: String = "",
postfix: String = ""
) {
internal val data: MultiChartData
init {
val dataItems = items.map {
ChartDataItem(
label = it.first,
item = it.second.toChartData(prefix = prefix, postfix = postfix)
)
}
data = MultiChartData(
items = dataItems,
title = title,
categories = categories
)
}
}
| 0
|
Kotlin
|
41
| 297
|
cf303ba50bad35a816253bee5b27beee5ea364b8
| 1,314
|
DashCoin
|
Apache License 2.0
|
android/app/src/main/kotlin/com/example/hashcode/MainActivity.kt
|
savagecarol
| 324,532,127
| true
|
{"Dart": 20752, "HTML": 1505, "Swift": 404, "Kotlin": 125, "Objective-C": 38}
|
package com.example.hashcode
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
| null |
0
| 0
|
de8c57b594fef8a98b0ac2f046ce94b244b3bb5e
| 125
|
hashcode_app
|
MIT License
|
app/src/main/java/teka/android/chamaaapp/presentation/home/HomeScreenViewModel.kt
|
samAricha
| 759,726,734
| false
|
{"Kotlin": 368851}
|
package teka.android.chamaaapp.presentation.home
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import teka.android.chamaaapp.data.local.repository.DbRepository
import teka.android.chamaaapp.data.room_remote_sync.RemoteDataUpdater
import teka.android.chamaaapp.presentation.members.EntityCountResult
import javax.inject.Inject
@HiltViewModel
class HomeScreenViewModel @Inject constructor(
private val repository: DbRepository,
private val remoteDataUpdater: RemoteDataUpdater
): ViewModel() {
private val _memberCount = MutableStateFlow<EntityCountResult<Int>>(EntityCountResult.Success(0))
val memberCount: StateFlow<EntityCountResult<Int>> get() = _memberCount
private val _chamaaAccountsCount = MutableStateFlow<EntityCountResult<Int>>(EntityCountResult.Success(0))
val chamaaAccountsCount: StateFlow<EntityCountResult<Int>> get() = _chamaaAccountsCount
fun getMemberCount() {
viewModelScope.launch {
_memberCount.value = repository.getTotalMembers()
_chamaaAccountsCount.value = repository.getTotalChamaaAccounts()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
72c9892e0bec64f082d0c237da58be9cc6822194
| 1,305
|
ChamaYetu
|
The Unlicense
|
zoomimage-core/src/main/java/com/github/panpf/zoomimage/core/internal/CoreOtherUtils.kt
|
panpf
| 647,222,866
| false
| null |
package com.github.panpf.zoomimage.core.internal
import java.math.BigDecimal
import java.math.RoundingMode
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.roundToLong
internal fun Any.toHexString(): String = Integer.toHexString(this.hashCode())
internal fun Float.format(newScale: Int): Float {
return if (this.isNaN()) {
this
} else {
BigDecimal(toDouble()).setScale(newScale, RoundingMode.HALF_UP).toFloat()
}
}
// File of internal utility methods used for the geometry library
internal fun Float.toStringAsFixed(digits: Int): String {
val clampedDigits: Int = kotlin.math.max(digits, 0) // Accept positive numbers and 0 only
val pow = 10f.pow(clampedDigits)
val shifted = this * pow // shift the given value by the corresponding power of 10
val decimal = shifted - shifted.toInt() // obtain the decimal of the shifted value
// Manually round up if the decimal value is greater than or equal to 0.5f.
// because kotlin.math.round(0.5f) rounds down
val roundedShifted = if (decimal >= 0.5f) {
shifted.toInt() + 1
} else {
shifted.toInt()
}
val rounded = roundedShifted / pow // divide off the corresponding power of 10 to shift back
return if (clampedDigits > 0) {
// If we have any decimal points, convert the float to a string
rounded.toString()
} else {
// If we do not have any decimal points, return the int
// based string representation
rounded.toInt().toString()
}
}
/**
* Linearly interpolate between [start] and [stop] with [fraction] fraction between them.
*/
internal fun lerp(start: Float, stop: Float, fraction: Float): Float {
return (1 - fraction) * start + fraction * stop
}
/**
* Linearly interpolate between [start] and [stop] with [fraction] fraction between them.
*/
internal fun lerp(start: Int, stop: Int, fraction: Float): Int {
return start + ((stop - start) * fraction.toDouble()).roundToInt()
}
/**
* Linearly interpolate between [start] and [stop] with [fraction] fraction between them.
*/
internal fun lerp(start: Long, stop: Long, fraction: Float): Long {
return start + ((stop - start) * fraction.toDouble()).roundToLong()
}
| 0
|
Kotlin
|
0
| 3
|
a6814e1fc8a84946d8bad0cf41406519197784eb
| 2,244
|
zoomimage
|
Apache License 2.0
|
api/src/main/kotlin/kontrol/api/Monitorable.kt
|
neilellis
| 15,782,049
| false
| null |
/*
* Copyright 2014 Cazcade Limited (http://cazcade.com)
*
* 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 kontrol.api
/**
* @todo document.
* @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a>
*/
public trait Monitorable<E : Enum<E>> {
var disableAction: ((in Monitorable<E>) -> Unit)?;
var enableAction: ((in Monitorable<E>) -> Unit)?;
fun state(): E?
fun transition(state: E?)
var enabled: Boolean
fun name(): String
fun id(): String
fun groupName(): String
fun disabled(): Boolean {
return !enabled
}
fun enabled(): Boolean {
return enabled
}
fun disable() {
enabled = false;
if (disableAction != null) {
disableAction!!(this)
};
}
fun enable() {
enabled = true;
if (enableAction != null) {
enableAction!!(this)
};
}
}
| 0
|
Kotlin
|
0
| 0
|
38d115785e33b1383d389815e039f5f09f6ccec1
| 1,421
|
kontrol
|
Apache License 2.0
|
whetstone/src/main/java/com/deliveryhero/whetstone/fragment/MultibindingFragmentFactory.kt
|
deliveryhero
| 402,753,721
| false
|
{"Kotlin": 77197}
|
package com.deliveryhero.whetstone.fragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentFactory
import com.deliveryhero.whetstone.activity.ActivityScope
import com.squareup.anvil.annotations.ContributesBinding
import dagger.Reusable
import javax.inject.Inject
import javax.inject.Provider
/**
* A [FragmentFactory] that can hold onto multiple other FragmentFactory [Provider]'s.
*/
@Reusable
@ContributesBinding(ActivityScope::class)
public class MultibindingFragmentFactory @Inject constructor(
private val fragmentComponentFactory: FragmentComponent.Factory
) : FragmentFactory() {
override fun instantiate(classLoader: ClassLoader, className: String): Fragment {
val fragmentComponent = fragmentComponentFactory.create()
val fragmentClass = loadFragmentClass(classLoader, className)
val fragmentMap = fragmentComponent.fragmentMap
val fragmentProvider = fragmentMap[fragmentClass]
return try {
fragmentProvider?.get() ?: super.instantiate(classLoader, className)
} catch (throwable: Throwable) {
throw if (fragmentProvider == null)
IllegalStateException(
"${fragmentClass.name} could not be instantiated. Did you forget to contribute it? Ensure the " +
"fragment class is annotated with '${ContributesFragment::class.java.name}' " +
"and has an '@Inject constructor'",
throwable
)
else throwable
}
}
}
| 5
|
Kotlin
|
5
| 211
|
34d67b2c03f8110eb8c71b21678207677928b704
| 1,573
|
whetstone
|
Apache License 2.0
|
src/main/kotlin/com/leetcode/top100LikedQuestions/easy/move_zeroes/Main.kt
|
frikit
| 254,842,734
| false
| null |
package com.leetcode.top100LikedQuestions.easy.move_zeroes
fun main() {
println("Test case 1:")
println(Solution().moveZeroes(intArrayOf(0, 1, 0, 3, 12)))
println()
println("Test case 2:")
println(Solution().moveZeroes(intArrayOf(0)))
println()
}
class Solution {
fun moveZeroes(nums: IntArray): Unit {
val final = mutableListOf<Int>()
val zeroes = mutableListOf<Int>()
nums.forEach { number ->
if (number == 0) {
zeroes.add(0)
} else {
final.add(number)
}
}
(final + zeroes).forEachIndexed { i, e ->
nums[i] = e
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ba08fd191a0d1224f3ad3e949c77e9dce1abf34c
| 684
|
leet-code-problems
|
Apache License 2.0
|
app/src/main/java/com/tsu/firstlab/database/Word.kt
|
astyd256
| 609,680,319
| false
| null |
package com.tsu.firstlab.database
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity()
data class Word(
@PrimaryKey(autoGenerate = false) val word: String,
val phonetic: String,
val partOfSpeech: String,
val soundURL: String,
@ColumnInfo(defaultValue = "0") val learningProgress: Int
)
| 0
|
Kotlin
|
0
| 0
|
ef4281bcec96d5fa7bff489c889e3789d5e92dcd
| 357
|
English-Vocabulary-Android-App
|
MIT License
|
data/src/main/java/com/semicolon/data/remote/request/users/UpdateProfileRequest.kt
|
Walkhub
| 443,006,389
| false
| null |
package com.semicolon.data.remote.request.users
import com.google.gson.annotations.SerializedName
data class UpdateProfileRequest(
@SerializedName("name") val name: String,
@SerializedName("profile_image_url") val profileImageUrl: String,
@SerializedName("sex") val sex: String
)
| 30
|
Kotlin
|
1
| 15
|
c2d85ebb9ae8b200be22e9029dcfdcbfed19e473
| 293
|
walkhub_android
|
MIT License
|
src/commonMain/kotlin/com/bkahlert/kommons/builder/EnumSetBuilder.kt
|
bkahlert
| 323,048,013
| false
| null |
@file:Suppress("PropertyName")
package com.bkahlert.kommons.builder
import com.bkahlert.kommons.asString
import com.bkahlert.kommons.builder.context.ListBuildingContext
import kotlin.contracts.InvocationKind.EXACTLY_ONCE
import kotlin.contracts.contract
/**
* Builder of an [Enum] [Set] of any enum type [E].
*
* @see EnumSetBuilderSamples.directUse
* @see EnumSetBuilderSamples.indirectUse
*/
public open class EnumSetBuilder<E : Enum<E>> : Builder<Init<ListBuildingContext<E>>, Set<E>> {
/**
* A context to collect all elements added by means
* of the [ListBuildingContext].
*/
protected class BackedListBuildingContext<E>(
/**
* The mutable list to which all context operations should be delegated.
*/
public val list: MutableList<E> = mutableListOf(),
) : ListBuildingContext<E> {
override fun add(element: E) {
list += element
}
}
override fun invoke(init: Init<ListBuildingContext<E>>): Set<E> {
return BackedListBuildingContext<E>().apply(init).list.toSet()
}
override fun toString(): String = asString()
public companion object {
public operator fun <E : Enum<E>> invoke(@BuilderInference init: Init<ListBuildingContext<E>>): Set<E> = EnumSetBuilder<E>().invoke(init)
}
}
/**
* Builds an enum set of enum type [E] as specified by [init].
*/
public fun <E : Enum<E>> buildEnumSet(@BuilderInference init: Init<ListBuildingContext<E>>): Set<E> {
contract { callsInPlace(init, EXACTLY_ONCE) }
return EnumSetBuilder(init)
}
@Suppress("UNUSED_VARIABLE", "unused")
private object EnumSetBuilderSamples {
enum class Features {
FeatureA, FeatureB, FeatureC
}
fun directUse() {
val features = EnumSetBuilder {
+Features.FeatureA + Features.FeatureC
}
}
fun indirectUse() {
fun builderAcceptingFunction(init: Init<ListBuildingContext<Features>>) {
val enumSet = EnumSetBuilder(init)
println("Et voilà, $enumSet")
}
val enumSet = builderAcceptingFunction { +Features.FeatureA + Features.FeatureC }
}
}
| 7
|
Kotlin
|
0
| 9
|
35e2ac1c4246decdf7e7a1160bfdd5c9e28fd066
| 2,166
|
kommons
|
MIT License
|
app/src/main/java/com/example/busschedule/data/AppContainer.kt
|
JimmyAlele
| 702,268,926
| false
|
{"Kotlin": 29026}
|
package com.example.busschedule.data
import android.content.Context
/**
* App container for Dependency injection.
*/
interface AppContainer {
val busScheduleRepository: BusScheduleRepository
}
/**
* [AppContainer] implementation that provides instance of [OfflineBusScheduleRepository]
*/
class AppDataContainer(private val context: Context) : AppContainer {
/**
* Implementation for [BusScheduleRepository]
*/
override val busScheduleRepository: BusScheduleRepository by lazy {
OfflineBusScheduleRepository(BusScheduleDatabase.getDatabase(context).busScheduleDao())
}
}
| 0
|
Kotlin
|
0
| 0
|
375cb7bf9a44b3ecb2eb159c3e36e0cf7663c0ad
| 613
|
BusSchedule
|
Apache License 2.0
|
src/main/kotlin/io/cutebot/memegenmanage/bot/commands/ManageBotCommand.kt
|
asundukov
| 280,483,551
| false
| null |
package io.cutebot.memegenmanage.bot.commands
import io.cutebot.memegenmanage.bot.blocks.StartBlock
import io.cutebot.memegenmanage.bot.blocks.managebot.ManageMenuBlock
import io.cutebot.memegenmanage.bot.blocks.managebot.tools.ManageTools
import io.cutebot.memegenmanage.bot.blocks.managebot.tools.ManageToolsFactory
import io.cutebot.memegenmanage.botclient.BotClient
import io.cutebot.telegram.bot.block.BotBlock
import io.cutebot.telegram.bot.command.Command
import io.cutebot.telegram.bot.model.RawMessage
import org.springframework.stereotype.Service
@Service
class ManageBotCommand(
private val botClient: BotClient,
private val manageToolsFactory: ManageToolsFactory
): Command {
override fun getCommand(): String {
return "/manage"
}
override fun getCommandDescription(): String {
return ""
}
override fun handleCommand(query: String, message: RawMessage): BotBlock {
val userId = message.from!!.id
val botId = try{
query.toInt()
} catch (e: NumberFormatException) {
return StartBlock(botClient, userId)
}
val bot = botClient.getBot(botId)
if (bot.adminUsrId != userId) {
return StartBlock(botClient, userId)
}
return ManageMenuBlock(manageToolsFactory.getTools(userId, botId, StartBlock(botClient, userId)))
}
override fun isSystemCommand(): Boolean {
return false
}
}
| 7
|
Kotlin
|
0
| 0
|
358dd371a66a77968c646020ecd3dd555bebef3b
| 1,459
|
meme-gen-manage-bot
|
Apache License 2.0
|
app/src/main/java/com/dew/aihua/infolist/adapter/InfoItemDialog.kt
|
ed828a
| 172,828,123
| false
| null |
package com.dew.aihua.infolist.adapter
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.view.View
import android.widget.TextView
import com.dew.aihua.R
import org.schabi.newpipe.extractor.stream.StreamInfoItem
/**
* Created by Edward on 3/2/2019.
*/
class InfoItemDialog(activity: Activity,
commands: Array<String>,
actions: DialogInterface.OnClickListener,
title: String,
additionalDetails: String?) {
private val dialog: AlertDialog
constructor(activity: Activity,
info: StreamInfoItem,
commands: Array<String>,
actions: DialogInterface.OnClickListener) : this(activity, commands, actions, info.name, info.uploaderName)
init {
val bannerView = View.inflate(activity, R.layout.dialog_title, null)
bannerView.isSelected = true
val titleView = bannerView.findViewById<TextView>(R.id.itemTitleView)
titleView.text = title
val detailsView = bannerView.findViewById<TextView>(R.id.itemAdditionalDetails)
if (additionalDetails != null) {
detailsView.text = additionalDetails
detailsView.visibility = View.VISIBLE
} else {
detailsView.visibility = View.GONE
}
dialog = AlertDialog.Builder(activity)
.setCustomTitle(bannerView)
.setItems(commands, actions)
.create()
}
fun show() {
dialog.show()
}
}
| 0
|
Kotlin
|
0
| 1
|
1896f46888b5a954b367e83f40b845ce174a2328
| 1,577
|
Aihua
|
Apache License 2.0
|
richeditor-compose/src/commonMain/kotlin/com/mohamedrejeb/richeditor/parser/markdown/MarkdownAnnotation.kt
|
MohamedRejeb
| 630,584,174
| false
| null |
package com.mohamedrejeb.richeditor.parser.markdown
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.em
import com.mohamedrejeb.richeditor.model.RichParagraph
import com.mohamedrejeb.richeditor.model.RichSpan
import com.mohamedrejeb.richeditor.model.RichSpanStyle
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.ast.ASTNode
import org.intellij.markdown.ast.findChildOfType
import org.intellij.markdown.ast.getTextInNode
import org.intellij.markdown.flavours.gfm.GFMElementTypes
import org.intellij.markdown.flavours.gfm.GFMTokenTypes
internal object MarkdownSpanStyles {
val linkSpanStyle = SpanStyle(textDecoration = TextDecoration.Underline, fontWeight = FontWeight.Bold)
val italic = SpanStyle(fontStyle = FontStyle.Italic)
val bold = SpanStyle(fontWeight = FontWeight.Bold)
val lineThrough = SpanStyle(textDecoration = TextDecoration.LineThrough)
val H1SPanStyle = SpanStyle(fontSize = 2.em, fontWeight = FontWeight.Bold)
val H2SPanStyle = SpanStyle(fontSize = 1.5.em, fontWeight = FontWeight.Bold)
val H3SPanStyle = SpanStyle(fontSize = 1.17.em, fontWeight = FontWeight.Bold)
val H4SPanStyle = SpanStyle(fontSize = 1.12.em, fontWeight = FontWeight.Bold)
val H5SPanStyle = SpanStyle(fontSize = 0.83.em, fontWeight = FontWeight.Bold)
val H6SPanStyle = SpanStyle(fontSize = 0.75.em, fontWeight = FontWeight.Bold)
}
/**
* Appends Styles for all the children nodes of the [parent]
*/
internal fun Parser.buildSpans(content: String, parent : RichParagraph, node: ASTNode): MutableList<RichSpan> {
return buildSpans(content, parent,node.children)
}
//val TESTMARKDOWN = """# My first heading
//
//## My second heading
//
//### My third heading
//
//#### My fourth heading
//
//##### My fifth heading
//
//###### My sixth heading
//
//## My *italic* heading with [link]()
//
//This is my normal text
//
//This text will contain **bold** and *italic* items.
//
//A line through ~~something~~ and
//
//You can also make the text ***italicandbold***
//
//The link can be [normal]() [*italic*]() , [**bold**]() or [***bold and italic***]()
//A normal link [link](http://example.com)
//
//Here's an auto link http://a.b
//Auto link italic *http://a.b*
//Auto link bold **http://a.b**
//Auto link italicandbold ***http://a.b***
//
//Here's some text that get's added fast
//'"()[]<>:!something`"""
/**
* Appends styles for [node] and its children
*/
internal fun Parser.buildSpans(
content: String,
parent : RichParagraph,
children: List<ASTNode>
): MutableList<RichSpan> {
val list = mutableListOf<RichSpan>()
for (child in children) {
// print("CHILD(${child.type})->")
when (child.type) {
MarkdownElementTypes.PARAGRAPH -> {
// this paragraph is triggered when a list item is being written , right after the list bullet
list.add(
RichSpan(
children = buildSpans(content,parent, child),
paragraph = parent,
)
)
}
MarkdownElementTypes.IMAGE -> {
// TODO
// child.findChildOfTypeRecursive(MarkdownElementTypes.LINK_DESTINATION)
// ?.let {
// appendInlineContent(TAG_IMAGE_URL, it.getTextInNode(content).toString())
// }
}
MarkdownElementTypes.EMPH -> {
// print("IN EMPH->")
list.add(
RichSpan(
paragraph = parent,
children = buildSpans(content,parent, child),
spanStyle = MarkdownSpanStyles.italic
)
)
// print("OUT EMPH->")
}
MarkdownElementTypes.STRONG -> {
list.add(
RichSpan(
paragraph = parent,
children = buildSpans(content,parent, child),
spanStyle = MarkdownSpanStyles.bold
)
)
}
MarkdownElementTypes.CODE_SPAN -> {
list.add(
RichSpan(
paragraph = parent,
children = buildSpans(content,parent, child.children.innerList()),
style = RichSpanStyle.Code()
)
)
}
MarkdownTokenTypes.LIST_BULLET -> {
// list.getLastOrNewDefaultRichSpan(parent).text += '*'
}
MarkdownElementTypes.AUTOLINK -> list.add(appendAutoLink(content, parent,child))
MarkdownElementTypes.INLINE_LINK -> appendMarkdownLink(content,parent, child)?.let { list.add(it) }
MarkdownElementTypes.SHORT_REFERENCE_LINK -> appendMarkdownLink(content,parent, child)?.let { list.add(it) }
MarkdownElementTypes.FULL_REFERENCE_LINK -> appendMarkdownLink(content,parent, child)?.let { list.add(it) }
GFMElementTypes.STRIKETHROUGH -> {
list.add(
RichSpan(
paragraph = parent,
children = buildSpans(content,parent, child.children),
spanStyle = MarkdownSpanStyles.lineThrough
)
)
}
MarkdownTokenTypes.ATX_HEADER -> {
// TODO
}
MarkdownTokenTypes.ATX_CONTENT -> {
list.addAll(buildSpans(content,parent,child))
}
MarkdownTokenTypes.TEXT -> {
list.getLastOrNewDefaultRichSpan(parent).text += (child.getTextInNode(content).toString())
}
// TODO handling html tags as text
MarkdownTokenTypes.HTML_TAG -> list.getLastOrNewDefaultRichSpan(parent).text += (child.getTextInNode(content).toString())
GFMTokenTypes.GFM_AUTOLINK -> if (child.parent == MarkdownElementTypes.LINK_TEXT) {
list.getLastOrNewDefaultRichSpan(parent).text += (child.getTextInNode(content).toString())
} else list.add(appendAutoLink(content, parent,child))
MarkdownTokenTypes.SINGLE_QUOTE -> list.getLastOrNewDefaultRichSpan(parent).text += '\''
MarkdownTokenTypes.DOUBLE_QUOTE -> list.getLastOrNewDefaultRichSpan(parent).text += ('\"')
MarkdownTokenTypes.LPAREN -> list.getLastOrNewDefaultRichSpan(parent).text += ('(')
MarkdownTokenTypes.RPAREN -> list.getLastOrNewDefaultRichSpan(parent).text += (')')
MarkdownTokenTypes.LBRACKET -> list.getLastOrNewDefaultRichSpan(parent).text += ('[')
MarkdownTokenTypes.RBRACKET -> list.getLastOrNewDefaultRichSpan(parent).text += (']')
MarkdownTokenTypes.LT -> list.getLastOrNewDefaultRichSpan(parent).text += ('<')
MarkdownTokenTypes.GT -> list.getLastOrNewDefaultRichSpan(parent).text += ('>')
MarkdownTokenTypes.COLON -> list.getLastOrNewDefaultRichSpan(parent).text += (':')
MarkdownTokenTypes.EXCLAMATION_MARK -> list.getLastOrNewDefaultRichSpan(parent).text += ('!')
MarkdownTokenTypes.BACKTICK -> list.getLastOrNewDefaultRichSpan(parent).text += ('`')
MarkdownTokenTypes.HARD_LINE_BREAK -> list.getLastOrNewDefaultRichSpan(parent).text += ("\n\n")
MarkdownTokenTypes.EOL -> list.getLastOrNewDefaultRichSpan(parent).text += ('\n')
MarkdownTokenTypes.WHITE_SPACE -> list.getLastOrNewDefaultRichSpan(parent).text += (' ')
// else -> println("Missed on ${child.type}")
}
}
return list
}
internal fun Parser.appendAutoLink(content: String, parent : RichParagraph, node: ASTNode): RichSpan {
val destination = node.getTextInNode(content).toString()
return RichSpan(
paragraph = parent,
spanStyle = MarkdownSpanStyles.linkSpanStyle,
style = RichSpanStyle.Link(url = destination),
text = node.getTextInNode(content).toString(),
)
}
internal fun Parser.appendMarkdownLink(content: String, parent : RichParagraph, node: ASTNode): RichSpan? {
val linkText = node.findChildOfType(MarkdownElementTypes.LINK_TEXT)?.children?.innerList() ?: return null
val destination =
node.findChildOfType(MarkdownElementTypes.LINK_DESTINATION)?.getTextInNode(content)?.toString()
val linkLabel = node.findChildOfType(MarkdownElementTypes.LINK_LABEL)?.getTextInNode(content)?.toString()
return RichSpan(
paragraph = getLastOrNewParagraph(),
spanStyle = MarkdownSpanStyles.linkSpanStyle,
style = RichSpanStyle.Link(url = destination ?: ""),
text = linkLabel ?: "",
children = buildSpans(content, parent,linkText)
)
}
| 12
|
Kotlin
|
17
| 484
|
4dac74b8cce711dee0a2191d332ee6824c0a3761
| 9,053
|
Compose-Rich-Editor
|
Apache License 2.0
|
LeetCode/Remove All Occurrences of a Substring/main.kt
|
Code-With-Aagam
| 455,843,406
| true
|
{"C++": 2823238, "Kotlin": 190162, "Swift": 170085, "Java": 56114, "Python": 14574, "C": 3440, "Shell": 732, "JavaScript": 719}
|
class Solution {
fun removeOccurrences(s: String, part: String): String {
var ans = s
while (ans.contains(part)) {
ans = ans.replaceFirst(part, "")
}
return ans
}
}
| 0
| null |
0
| 2
|
610520cc396fb13a03c606b5fb6739cfd68cc444
| 216
|
competitive-programming
|
MIT License
|
src/Day09.kt
|
Misano9699
| 572,108,457
| false
| null |
fun main() {
val head = 0
var tail = 1
var knots = MutableList(tail + 1) { Point(0, 0) }
var tailPoints = mutableSetOf(knots[tail])
fun reset() {
knots = MutableList(tail + 1) { Point(0, 0) }
tailPoints = mutableSetOf(knots[tail])
}
fun moveTailY(knot: Int) = when (knots[knot - 1].y - knots[knot].y) {
1, 2 -> knots[knot].up()
-1, -2 -> knots[knot].down()
else -> knots[knot]
}
fun moveTailX(knot: Int) = when (knots[knot - 1].x - knots[knot].x) {
1, 2 -> knots[knot].right()
-1, -2 -> knots[knot].left()
else -> knots[knot]
}
fun moveTail(knot: Int): Point {
var point = when (knots[knot - 1].x - knots[knot].x) {
2 -> moveTailY(knot).right()
-2 -> moveTailY(knot).left()
else -> knots[knot]
}
point = when (knots[knot - 1].y - knots[knot].y) {
2 -> moveTailX(knot).up()
-2 -> moveTailX(knot).down()
else -> point
}
return point
}
fun moveHead(direction: String) = when (direction) {
"R" -> knots[head].right()
"L" -> knots[head].left()
"U" -> knots[head].up()
"D" -> knots[head].down()
else -> knots[head]
}
fun moveKnots(direction: String, knot: Int) {
(1..knot).forEach { _ ->
knots[head] = moveHead(direction)
(1..tail).forEach {
knots[it] = moveTail(it)
}
tailPoints.add(knots[tail])
}
}
fun part1(input: List<String>): Int {
tail = 1
reset()
input.forEach { line ->
val move = line.split(" ")
moveKnots(move[0], move[1].toInt())
}
return tailPoints.count()
}
fun part2(input: List<String>): Int {
tail = 9
reset()
input.forEach { line ->
val move = line.split(" ")
moveKnots(move[0], move[1].toInt())
}
return tailPoints.count()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
val input = readInput("Day09")
println("---- PART 1 ----")
check(part1(testInput).also { println("Answer test input part1: $it") } == 13)
println("Answer part1: " + part1(input))
println("---- PART 2 ----")
check(part2(testInput).also { println("Answer test input part2: $it") } == 1)
println("Answer part2: " + part2(input))
}
data class Point(val x: Int, val y: Int) {
fun left(): Point = Point(this.x - 1, this.y)
fun right(): Point = Point(this.x + 1, this.y)
fun up(): Point = Point(this.x, this.y + 1)
fun down(): Point = Point(this.x, this.y - 1)
}
| 0
|
Kotlin
|
0
| 0
|
adb8c5e5098fde01a4438eb2a437840922fb8ae6
| 2,774
|
advent-of-code-2022
|
Apache License 2.0
|
app/src/main/java/ton/coin/wallet/feature/send/amount/SendAmountViewModel.kt
|
protoshadowmaker
| 643,940,461
| false
| null |
package ton.coin.wallet.feature.send.amount
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import org.koin.core.component.inject
import ton.coin.wallet.common.lifecycle.ConductorViewModel
import ton.coin.wallet.data.DraftTransaction
import ton.coin.wallet.data.TonCoins
import ton.coin.wallet.repository.TonRepository
import java.math.BigDecimal
class SendAmountViewModel : ConductorViewModel() {
private val tonRepository: TonRepository by inject()
private val _stateFlow: MutableStateFlow<ScreenData> = MutableStateFlow(ScreenData())
val stateFlow: StateFlow<ScreenData> = _stateFlow.asStateFlow()
val state: ScreenData get() = stateFlow.value
init {
loadData()
}
fun loadData() {
if (state.status == ScreenState.Loading) {
return
}
onScreenDataChanged(state.copy(status = ScreenState.Loading))
lifecycleScope.launch {
var transaction = tonRepository.getDraftTransaction().getOrNull()
if (transaction == null) {
transaction = DraftTransaction()
tonRepository.saveDraftTransaction(transaction)
}
val cachedBalance = tonRepository.getCachedBalance().getOrNull() ?: TonCoins()
onScreenDataChanged(
state.copy(
status = ScreenState.Successful,
draftTransaction = transaction,
availableBalance = cachedBalance
)
)
val availableBalance = tonRepository.getBalance().getOrNull() ?: cachedBalance
onScreenDataChanged(
state.copy(
status = ScreenState.Successful,
draftTransaction = transaction,
availableBalance = availableBalance
)
)
}
}
fun onAmountChanged(amount: String) {
val value = try {
TonCoins(BigDecimal(amount).multiply(BigDecimal.valueOf(1_000_000_000)).toBigInteger())
} catch (e: Throwable) {
null
}
val transaction = state.draftTransaction.copy(amount = value)
lifecycleScope.launch {
tonRepository.saveDraftTransaction(transaction)
}
onScreenDataChanged(state.copy(draftTransaction = transaction))
}
fun onContinuePressed() {
if (state.status == ScreenState.Loading) {
return
}
onScreenDataChanged(state.copy(status = ScreenState.Loading))
lifecycleScope.launch {
onScreenDataChanged(state.copy(status = ScreenState.Redirection("comment")))
}
}
fun consumeRedirection() {
onScreenDataChanged(state.copy(status = ScreenState.Successful))
}
private fun onScreenDataChanged(newData: ScreenData) {
_stateFlow.tryEmit(newData)
}
}
data class ScreenData(
val draftTransaction: DraftTransaction = DraftTransaction(),
val availableBalance: TonCoins = TonCoins(),
val status: ScreenState = ScreenState.Pure
)
sealed class ScreenState {
object Pure : ScreenState()
object Loading : ScreenState()
object Successful : ScreenState()
data class Error(val error: Throwable) : ScreenState()
data class Redirection(val target: String) : ScreenState()
}
| 0
|
Kotlin
|
0
| 0
|
adf8eb798a8e044427b7295136913869bf264e7e
| 3,431
|
tonwallet
|
MIT License
|
vb-prebuilt/src/main/java/live/hms/vb_prebuilt/VirtualBackgroundOptions.kt
|
100mslive
| 330,654,934
| false
|
{"Kotlin": 1217116, "Java": 63283}
|
package live.hms.vb_prebuilt
import android.graphics.Bitmap
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.bumptech.glide.Glide
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
import com.bumptech.glide.integration.compose.placeholder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import live.hms.prebuilt_themes.Variables
import live.hms.prebuilt_themes.Variables.Companion.Spacing1
import live.hms.prebuilt_themes.Variables.Companion.Spacing2
@Preview
@Composable
private fun Preview() {
VirtualBackgroundOptions(close = {},
allBackgrounds = listOf("a","b","c","d","d"),
defaultBackground = "a",
removeEffects = {},
blur = {},
backgroundSelected = {a,b ->},
onBlurPercentageChanged = {},
initialBlurPercentage = 30f,
currentlySelectedVbMode = SelectedEffect.NO_EFFECT)
}
@Composable
fun VirtualBackgroundOptions(
videoView: @Composable (modifier: Modifier) -> Unit = { modifier ->
Box(
modifier = modifier.then(
Modifier.Companion
.clip(RectangleShape)
.background(Color.Gray)
)
)
},
allBackgrounds: List<String> = emptyList(),
defaultBackground: String? = null,
currentlySelectedVbMode : SelectedEffect,
close: () -> Unit,
removeEffects: () -> Unit,
backgroundSelected: (String, Bitmap) -> Unit,
blur: (Float) -> Unit,
onBlurPercentageChanged: (Float) -> Unit,
initialBlurPercentage: Float,
) {
Column(
modifier = Modifier
.fillMaxSize()
.background(
color = Variables.SurfaceDim,
shape = RoundedCornerShape(
topStart = Variables.Spacing2,
topEnd = Variables.Spacing2
)
)
.padding(
start = Variables.Spacing3,
end = Variables.Spacing3,
top = Variables.Spacing3,
bottom = Variables.Spacing4
)
,
verticalArrangement = Arrangement.spacedBy(Variables.Spacing2, Alignment.Top),
// horizontalAlignment = Alignment.CenterHorizontally,
) {
BottomSheetHeader(close)
Box(modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center) {
videoView(
Modifier
.width(166.dp)
.height(280.dp))
}
Text(
text = "Effects", style = TextStyle(
fontSize = 14.sp,
lineHeight = 24.sp,
fontFamily = FontFamily(Font(live.hms.prebuilt_themes.R.font.inter_regular)),
fontWeight = FontWeight(600),
color = Variables.OnSecondaryHigh,
letterSpacing = 0.15.sp,
)
)
var currentBackground by remember { mutableStateOf(defaultBackground) }
var currentBlurPercentage by remember { mutableFloatStateOf(initialBlurPercentage) }
var selectedEffect by remember { mutableStateOf(currentlySelectedVbMode) }
Row(horizontalArrangement = Arrangement.spacedBy(Spacing2)) {
VbOptionButton(drawable = live.hms.vb_prebuilt.R.drawable.vb_cross_circle,
"No effect", selectedEffect == SelectedEffect.NO_EFFECT) {
selectedEffect = SelectedEffect.NO_EFFECT
currentBackground = null
removeEffects()
}
VbOptionButton(drawable = live.hms.vb_prebuilt.R.drawable.vb_blur_background,
"Blur",selectedEffect == SelectedEffect.BLUR) {
selectedEffect = SelectedEffect.BLUR
currentBackground = null
blur(currentBlurPercentage)
}
}
if(selectedEffect == SelectedEffect.BLUR) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(Spacing1)
) {
Image(
painter = painterResource(id = live.hms.vb_prebuilt.R.drawable.vb_slider_blur_people),
contentDescription = "effect slider"
)
Slider(
modifier = Modifier.weight(1f),
value = currentBlurPercentage,
onValueChange = {
currentBlurPercentage = it
onBlurPercentageChanged.invoke(it)
},
valueRange = 0f..100f,
steps = 100,
colors = SliderDefaults.colors(
thumbColor = Variables.PrimaryDefault,
activeTrackColor = Variables.PrimaryDefault,
inactiveTrackColor = Variables.SecondaryDefault,
)
)
Image(
painter = painterResource(id = live.hms.vb_prebuilt.R.drawable.vb_slider_blur_people_max),
contentDescription = "effect slider"
)
}
}
if(allBackgrounds.isNotEmpty()) {
Spacer(modifier = Modifier.height(Variables.Spacing2))
Text(
text = "Backgrounds",
style = TextStyle(
fontSize = 14.sp,
lineHeight = 20.sp,
fontFamily = FontFamily(Font(live.hms.prebuilt_themes.R.font.inter_bold)),
fontWeight = FontWeight(600),
color = Variables.OnSurfaceHigh,
letterSpacing = 0.1.sp,
)
)
val coroutineScope = rememberCoroutineScope()
val context = LocalContext.current
BackgroundListing(allBackgrounds, currentBackground) { selectedBackground ->
currentBackground = selectedBackground
selectedEffect = SelectedEffect.BACKGROUND
// Running here instead of launched effect because it shouldn't run
// the very first time we set current background to something.
coroutineScope.launch {
launch(Dispatchers.IO) {
backgroundSelected(
selectedBackground,
Glide.with(context).asBitmap().load(selectedBackground).submit().get()
)
}
}
}
}
}
}
@Preview
@Composable
private fun BackgroundGallery() {
BackgroundListing(
backgrounds = listOf("https://img-vb.100ms.live/layouts/defaults/vb-1.jpg",
"https://img-vb.100ms.live/layouts/defaults/vb-2.jpg"),
currentBackground = "https://img-vb.100ms.live/layouts/defaults/vb-1.jpg"
) {
}
}
/**
* Takes a list of background images
* Notifies when one of them is selected.
*/
@OptIn(ExperimentalGlideComposeApi::class)
@Composable
fun BackgroundListing(backgrounds : List<String>,
currentBackground : String?,
onBackgroundSelected : (String) -> Unit) {
LazyVerticalGrid(
horizontalArrangement = Arrangement.spacedBy(Spacing2),
verticalArrangement = Arrangement.spacedBy(Spacing2),
columns = GridCells.Fixed(3)
) {
itemsIndexed(backgrounds) { _, photoUrl ->
val m = Modifier.clickable { onBackgroundSelected(photoUrl) }
.clip(RoundedCornerShape(8.dp))
val modifier = if(currentBackground == photoUrl) {
m.then(Modifier.border(
2.dp, Variables.PrimaryDefault,
shape = RoundedCornerShape(8.dp)
))
} else {
m
}
GlideImage(
modifier = modifier,
model = photoUrl,
contentDescription = "background",
// using the composable placeholder causes a lot of re-rendering
// loading = placeholder(R.drawable.gray_round_stroked_drawable)
)
}
}
}
@Composable
fun BottomSheetHeader(close : () -> Unit,) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.Start),
verticalAlignment = Alignment.Top,
) {
Text(
modifier = Modifier.weight(1f),
text = "Virtual Background", style = TextStyle(
fontSize = 16.sp,
lineHeight = 24.sp,
fontFamily = FontFamily(Font(live.hms.prebuilt_themes.R.font.inter_bold)),
fontWeight = FontWeight(600),
color = Variables.OnSecondaryHigh,
letterSpacing = 0.15.sp,
)
)
Image(
modifier = Modifier
.padding(1.dp)
.size(24.dp)
.clickable { close() },
painter = painterResource(id = live.hms.prebuilt_themes.R.drawable.outline_cross),
contentDescription = "Close",
contentScale = ContentScale.None
)
}
}
enum class SelectedEffect {
NO_EFFECT,
BLUR,
BACKGROUND
}
@Composable
fun VbOptionButton(@DrawableRes drawable : Int,
description : String,
selected : Boolean,
onClick : () -> Unit) {
Column(
Modifier
.width(103.33334.dp)
.height(86.dp)
.clickable { onClick() }
.background(
shape = RoundedCornerShape(16.dp),
color = Variables.SurfaceBright
)
.border(
2.dp, if (selected) Variables.PrimaryDefault else (Variables.SurfaceBright),
shape = RoundedCornerShape(16.dp)
)
.padding(start = 10.dp, top = 10.dp, end = 10.dp, bottom = 10.dp),
verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Image(painter = painterResource(id = drawable), contentDescription = "background")
Text(description,
style = TextStyle(
fontSize = 12.sp,
lineHeight = 16.sp,
fontFamily = FontFamily(Font(live.hms.prebuilt_themes.R.font.inter_regular)),
fontWeight = FontWeight(400),
color = Variables.OnSurfaceMedium,
letterSpacing = 0.4.sp,
))
}
}
| 29
|
Kotlin
|
39
| 87
|
ca00e87c14b81319118b60d52c22038ca9bb7e22
| 12,711
|
100ms-android
|
MIT License
|
interactors/src/main/java/app/tivi/interactors/UpdateShowSeasons.kt
|
kumamon-git
| 143,403,157
| true
|
{"Kotlin": 535436, "Shell": 2064, "Java": 737}
|
/*
* Copyright 2018 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 app.tivi.interactors
import app.tivi.data.repositories.episodes.SeasonsEpisodesRepository
import app.tivi.data.resultentities.SeasonWithEpisodesAndWatches
import app.tivi.util.AppCoroutineDispatchers
import app.tivi.util.AppRxSchedulers
import io.reactivex.Flowable
import kotlinx.coroutines.experimental.CoroutineDispatcher
import javax.inject.Inject
class UpdateShowSeasons @Inject constructor(
private val seasonsEpisodesRepository: SeasonsEpisodesRepository,
dispatchers: AppCoroutineDispatchers,
private val schedulers: AppRxSchedulers
) : SubjectInteractor<UpdateShowSeasons.Params, List<SeasonWithEpisodesAndWatches>>() {
override val dispatcher: CoroutineDispatcher = dispatchers.io
override fun createObservable(param: Params): Flowable<List<SeasonWithEpisodesAndWatches>> {
return seasonsEpisodesRepository.observeSeasonsForShow(param.showId)
.subscribeOn(schedulers.io)
}
override suspend fun execute(param: Params) {
seasonsEpisodesRepository.updateSeasonsEpisodes(param.showId)
}
data class Params(val showId: Long, val forceLoad: Boolean)
}
| 0
|
Kotlin
|
0
| 0
|
576ce71a830303f3a78bf0ed20ef4dd9e6f93b1d
| 1,732
|
tivi
|
Apache License 2.0
|
src/main/kotlin/io/github/platan/tests_execution_chart/reporters/json/JsonReporter.kt
|
platan
| 549,810,072
| false
| null |
package io.github.platan.tests_execution_chart.reporters.json
import groovy.json.JsonOutput
import io.github.platan.tests_execution_chart.config.Json
import io.github.platan.tests_execution_chart.report.TestExecutionScheduleReport
import io.github.platan.tests_execution_chart.reporters.GanttDiagramReporter
import io.github.platan.tests_execution_chart.reporters.Logger
import java.io.File
class JsonReporter(private val config: Json, private val logger: Logger) : GanttDiagramReporter() {
override fun report(
report: TestExecutionScheduleReport,
baseDir: File,
taskName: String
) {
val jsonReport = JsonOutput.prettyPrint(JsonOutput.toJson(report))
val reportFile = save(jsonReport, taskName, baseDir, config.outputLocation.get(), "json")
logger.lifecycle("Tests execution schedule report saved to ${reportFile.absolutePath} file.")
}
}
| 0
|
Kotlin
|
3
| 9
|
16069d8cf9d6661246f7e9438b73a99c3cc4bf62
| 903
|
tests-execution-chart
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.