path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/theendercore/packed/data/PakItemTags.kt
|
theendercore
| 674,191,573
| false
|
{"Kotlin": 35748}
|
package com.theendercore.packed.data
import com.theendercore.packed.Packed.id
import com.theendercore.packed.util.tag
import net.minecraft.item.Item
import net.minecraft.registry.RegistryKeys
import net.minecraft.registry.tag.TagKey
import net.minecraft.util.Identifier
object PakItemTags {
val ITEM_TAGS = mutableSetOf<TagKey<Item>>()
val BACKPACKS = create("backpacks")
fun create(id: String): TagKey<Item> {
val regTag = itemTag(id(id))
ITEM_TAGS.add(regTag)
return regTag
}
fun itemTag(id: Identifier) = RegistryKeys.ITEM.tag(id)
}
| 0
|
Kotlin
|
0
| 0
|
0b3e4373b64ae2a0bdb6275468c8d81807ccef48
| 585
|
Packed
|
MIT License
|
app/src/main/java/com/hover/stax/ussd_library/LibraryFragment.kt
|
UseHover
| 286,494,631
| false
|
{"Kotlin": 1033610, "Java": 88968, "Shell": 274, "Ruby": 235}
|
/*
* Copyright 2022 Stax
*
* 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.hover.stax.ussd_library
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.View.VISIBLE
import android.view.ViewGroup
import androidx.core.text.HtmlCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.hover.stax.R
import com.hover.stax.addChannels.ChannelsViewModel
import com.hover.stax.countries.CountryAdapter
import com.hover.stax.database.models.Channel
import com.hover.stax.databinding.FragmentLibraryBinding
import com.hover.stax.presentation.home.components.TopBar
import com.hover.stax.views.theme.StaxTheme
import com.hover.stax.utils.UIHelper
import com.hover.stax.views.RequestServiceDialog
import timber.log.Timber
class LibraryFragment :
Fragment(),
CountryAdapter.SelectListener,
LibraryChannelsAdapter.FavoriteClickInterface {
private val viewModel: ChannelsViewModel by viewModels()
private var _binding: FragmentLibraryBinding? = null
private val binding get() = _binding!!
private val libraryAdapter = LibraryChannelsAdapter(this)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentLibraryBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
com.hover.stax.utils.AnalyticsUtil.logAnalyticsEvent(
getString(
R.string.visit_screen,
LibraryFragment::class.java.simpleName
),
requireActivity()
)
initToolbar()
binding.countryCard.showProgressIndicator()
binding.countryDropdown.setListener(this)
binding.shortcodes.apply {
layoutManager = UIHelper.setMainLinearManagers(requireActivity())
adapter = libraryAdapter
}
setupEmptyState()
setSearchInputWatcher()
setObservers()
}
private fun initToolbar() {
binding.toolbar.setContent {
StaxTheme { TopBar(title = R.string.library_cardhead) { dest -> navigateTo(dest) } }
}
}
private fun navigateTo(dest: Int) = findNavController().navigate(dest)
private fun setObservers() {
with(viewModel) {
channelCountryList.observe(viewLifecycleOwner) {
it?.let {
binding.countryDropdown.updateChoices(
it,
countryChoice.value
)
}
}
sims.observe(viewLifecycleOwner) { Timber.e("${this@LibraryFragment.javaClass.simpleName} Loaded ${it?.size} sims") }
simCountryList.observe(viewLifecycleOwner) { Timber.e("${this@LibraryFragment.javaClass.simpleName} Loaded ${it?.size} hnis") }
filteredChannels.observe(viewLifecycleOwner) { it?.let { updateList(it) } }
countryChoice.observe(viewLifecycleOwner) {
it?.let {
binding.countryDropdown.setDropdownValue(
it
)
}
}
}
}
private fun setupEmptyState() {
binding.emptyState.root.visibility = View.GONE
binding.emptyState.informUs.setOnClickListener {
RequestServiceDialog(requireActivity()).showIt()
}
}
private fun setSearchInputWatcher() {
val searchInputWatcher: TextWatcher = object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun afterTextChanged(editable: Editable) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
viewModel.updateSearch(charSequence.toString())
}
}
binding.searchInput.addTextChangedListener(searchInputWatcher)
}
private fun updateList(channels: List<Channel>) {
binding.countryCard.hideProgressIndicator()
if (channels.isNotEmpty()) showList(channels)
else showEmptyState()
}
private fun showList(channels: List<Channel>) {
libraryAdapter.submitList(channels)
binding.emptyState.root.visibility = View.GONE
binding.shortcodesParent.visibility = VISIBLE
}
private fun showEmptyState() {
val content = resources.getString(
R.string.no_accounts_found_desc,
viewModel.filterQuery.value ?: getString(R.string.empty_channel_placeholder)
)
binding.emptyState.noAccountFoundDesc.apply {
text = HtmlCompat.fromHtml(content, HtmlCompat.FROM_HTML_MODE_LEGACY)
movementMethod = LinkMovementMethod.getInstance()
}
binding.emptyState.root.visibility = VISIBLE
binding.shortcodesParent.visibility = View.GONE
}
override fun countrySelect(countryCode: String) {
viewModel.updateCountry(countryCode)
}
override fun onFavoriteIconClicked(channel: Channel) {
viewModel.updateChannel(channel)
}
}
| 106
|
Kotlin
|
72
| 79
|
5b735dc215b63533420fe899c579a42a44f598ea
| 5,963
|
Stax
|
Apache License 2.0
|
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-23.kt
|
ferinagy
| 432,170,488
| false
| null |
package com.github.ferinagy.adventOfCode.aoc2022
import com.github.ferinagy.adventOfCode.Coord2D
fun main() {
println("Part1:")
println(part1(testInput1))
println(part1(input))
println()
println("Part2:")
println(part2(testInput1))
println(part2(input))
}
private fun part1(input: String): Int {
val elves = solve(input, 10).first
val minX = elves.minOf { it.x }
val minY = elves.minOf { it.y }
val maxX = elves.maxOf { it.x }
val maxY = elves.maxOf { it.y }
return (maxX - minX + 1) * (maxY - minY + 1) - elves.size
}
private fun part2(input: String): Int {
return solve(input, null).second
}
private fun solve(input: String, max: Int?): Pair<MutableSet<Coord2D>, Int> {
val elves = mutableSetOf<Coord2D>()
input.lines().forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
if (c == '#') elves += Coord2D(x, y)
}
}
val dirs = listOf(Coord2D(0, -1), Coord2D(0, 1), Coord2D(-1, 0), Coord2D(1, 0)).map {
listOf(it, Coord2D(it.x + it.y, it.y + it.x), Coord2D(it.x - it.y, it.y - it.x))
}
var iteration = 0
while (true) {
val map = mutableMapOf<Coord2D, MutableList<Coord2D>>()
elves.forEach { e ->
if (e.adjacent(includeDiagonals = true).any { it in elves }) {
for (d in 0..3) {
val dir = dirs[(d + iteration) % 4]
if (dir.none { e + it in elves }) {
val next = e + dir.first()
map.getOrPut(next) { mutableListOf() }.add(e)
break
}
}
}
}
var moved = false
map.forEach { (dest, src) ->
if (src.size == 1) {
elves -= src.single()
elves += dest
moved = true
}
}
iteration++
if (iteration == max) break
if (!moved) break
}
return elves to iteration
}
private const val testInput1 = """....#..
..###.#
#...#.#
.#...##
#.###..
##.#.##
.#..#.."""
private const val input = """#.##.##...####..#.##.##....###....##...#..#####..#.##.##.#...###.##..#.##
.#....#..#.##..#.#.#...#..#..####..#.#.##.#.#..#.#..#.#..##.#..........#.
##.#####.###.#...######..###.#.#..##.#.##.#......#..##.....###.#.##.##.##
..#######.####.#..###...####..####....#.####.#.#..#.#.###.##.###.##..#...
.#..#.##...#...####.....##.#.#..#...###.....##..#.##..#.#.#.##.##.#.#.#..
####.#...#.#..##..###.####.#######.....#.##.#..#.#...#.##.#....#.........
..#.#.####...###.##.#..#.....#.##...#.#.####.....#..##....#..#####...##..
#####..##.....#.##..#.####....#.#....#.##....#.#....##.#####.#...####..##
#.#..#####.###..####..#.##..#######....##..#.###.#.#....##.#..##.##..#..#
..##.#.##.....###..#..#..#.####....#..####..##.###...#..#..#...##..##..##
#.###.##.#...##.##.#.##..####.##.#.#.###...##.#....#.#.#.##.##...#.##.#.#
.#####..###.#.###.###....#..#..#....#.##.#.###.#.####..###.#####.#.#####.
...#..##.##.#.#.###.#######.##.#...##..##...#......#..####.#.#...#.#####.
.#..###..######..#.#.##.##.#.##....##.#...#...#..#.#.##.#...#.#..#...#.##
##..#.#...#.###.#..#..#.###.###..###.#.......#####.##.####..#...#..#....#
...#..###...#...###.#.....#.###.##.###.####.##.....##..##.#.##.#.#...#.##
####.#......#..###..#.#...##.#.##..#...#.###...#..##.#..#.....####.##.###
##....#..#####..#####....##.#####.##.###..#.#####..###.##..#.#..###.#.###
##.##...##.###.#.#..#####...#..#...#....#..#.#.#.......##..#...#..######.
......#.###.#.##..####..#..##..##.###.#..##...#...#...#...#.###.#.#.##.##
....##..#...##.##.#.#.#..#..#.#...####.#.....#.#.#.##.#.....##.#...#.#.##
..#..###.#..###.####..#.#....#..##.#.##..###...#.##.#.####.##.#.#.#.#...#
...###.....####.######...####.....#.#.#.#...#..##.##...#.###..###.#.#####
#.##..#.##.#......#####..#...####.#...###...###.##...##.##...###.###.##.#
###....#..#.###..#.####.##.#...##..#..#..#....###...#......#..#..##.#.###
.####.#.###..#########...#.##############.##...#.##.##.#..#.#.##.#.#.###.
.#.##...#...###..#..#.#.#..#.#.#.#.##........#.##.#.#.##.##.#.#.##.######
##.#.#.###..###.###.#.#.....#.###..####.#.#..##.#.##..#.####..#.......##.
.#.#####.#..###..##.#..#...#.#.##..#..#..#..##.####.##.#..###.#......#...
.##..##..#..#.#..###...#.#.##.###..#..#...#.##.#.##..#.#.##..#....#...#..
..#......###..###..##...##.###..##.#.....#.###...##.##..#...#..#.#..#....
.#.#.#.#.#...###.#######..#..###...#.###.#.###.##....#...#.##......####..
#...#.##.#...#.#.#.###.#..#.#..##.###.######.#.#....###.##...#....#....#.
.###....#..####.#..#....##.#..##..#..#.#####.#.#...##.##...####.###.##..#
#...#.#...#...##.#####.#.#...##..#..##.#...#...###....##.######.#..#.##.#
#...##...##..#......####.#.#.##.##.#.......####...####...#..#..#.#..#.##.
.###....#.####..##.###..#....#...##.###..#...#.##.#...#####.###..#..#..##
##.#..##..###.#..#..####...#.##.##..#......####....#....#.###..##......##
##.##....#####.##.###.######..#..####..##.#.####.#..####.##...##....#####
.##.#..##..#.##..###.....#..#.##..####...#.##...#.#.#.#..##.###.....##...
.##.#...#...####..##.#....##...#..###.#.#..#....##.######.#...##.###..##.
##.##.###..#.##.#..#....#.##.#.##..#...#..##.#.####..##.##...#..##.##..##
.#..###.#.#.##..#..#.####.#.##.#..##.#....#.###.##..#.###...#..#....###..
####..#.#..###..#...##.##.###.##...#.##.##...##..#.##.##...#.#..#.#.#.#..
..###...#..#...........#.###.##..#..###..##.#.##.#...#.#..#.....##..#####
.....##....###..###.###..#..#...##..#......#.##..#.#.#..##..#.###.....#.#
..####.#......#...#.#.#.#..#..##....##..#.#...##.##.##.###.###...###...#.
##..#.#.#.##.###########.#.###....####.##.#.#...####..#.##.#...##...#....
##...#..#...####.#.####....#.########.######..###....###..##..#...#.###..
##.###.####..#.##.#.#####.##.###..#.#.#.##.##.##.####.##.#...#..#..##....
.#..#.#.##..##...#....#.#....#....###..#..##..###.##.####.##.####.##.#...
##.#.##.##...#.#..#.#...##...#...#..#......#.###......###.....#.#.#####.#
..#.##.##.###....#.#..###..#..##.####.###.##..##.##....#...##.#..#..##.##
#####.#...#..##..##.#.#.....##..#..##.##.##.####..#####.#..###..#.##..##.
####.##..........###.###.#####.#.#..##...##.....#..###..##..#.####..#.##.
#.....##.####...#..##.##..#..#....##..#...#..#.#.....#..#...#.###.##.#..#
#.#.##..###.#...##.#...###.#......#....##..##.##.###.#.#.#..#.##.####..##
##..###.#.#......##.##.##.#.#####.#.#.###...###.##.#......#.##########..#
.####....#..#...###.#..##.#.####..#.#..######.#.####..##....###..##..#..#
#..##.#.#...##.#.#.########.....#.##...#....#.####.###.########.#.##.#...
#.#######..#.##.#.#.#..####..##.#..###.####.#..#########....####....###..
..##.#...##...#..###.#..##.#..#...##.####.######.####.#..##.#...#.#..###.
.#..##.#.##..#......##.#.#.##.#####.#.###....#...###...#....#.###.....###
#......#.#..##....##.########.#..#..##.##......#.#..######..##.##..##.###
..##...#...#.#..#.#########..##..#####..#..#..##.#....##...#.#....##.#.#.
.##..###.####.#..#####.###..###..#......##...#.....####..###..#..##.#.##.
......###.#..#...#..#.#.##.#.###...##.#.#....####.#..#.######.#.#...####.
...#.##.####....##..##.#.###.###.....#..###...####..##..######.#..##.....
.....####.....###.#.#.......#####.#.#....##...#####..#..#.#..#.#.#..##.##
##..##.#..##..#..#.#####..##.####.#...#.#..#..###..#..#....#...#.###.##..
#.#..#.#########.####..#####..####.#.#####....#.#..##...#..####.#..###.#.
#..##.###.##..#....#...#..#.##..#..###..#####..#######.#####....#.##.....
####.####.########.#.###....#.#..#..#.#.#.#..#....#..#.....#..##..#.##.#."""
| 0
|
Kotlin
|
0
| 1
|
ab1e894995c7a40b3c1ce244f842fc5fe3658ead
| 7,549
|
advent-of-code
|
MIT License
|
app/src/main/java/com/bett/androidkotlinanimationimagealongpath/MainActivity.kt
|
betranthanh
| 101,761,528
| false
| null |
package com.bett.androidkotlinanimationimagealongpath
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var animationView = findViewById<AnimationView>(R.id.animationView)
val avatars = hashSetOf(
"https://raw.githubusercontent.com/betranthanh/android-kotlin-animation-move-image-along-path/master/avatar_demo/avatar1.png",
"https://raw.githubusercontent.com/betranthanh/android-kotlin-animation-move-image-along-path/master/avatar_demo/avatar2.png",
"https://raw.githubusercontent.com/betranthanh/android-kotlin-animation-move-image-along-path/master/avatar_demo/avatar3.png",
"https://raw.githubusercontent.com/betranthanh/android-kotlin-animation-move-image-along-path/master/avatar_demo/avatar4.png",
"https://raw.githubusercontent.com/betranthanh/android-kotlin-animation-move-image-along-path/master/avatar_demo/avatar5.png",
"https://raw.githubusercontent.com/betranthanh/android-kotlin-animation-move-image-along-path/master/avatar_demo/avatar6.png",
"https://raw.githubusercontent.com/betranthanh/android-kotlin-animation-move-image-along-path/master/avatar_demo/avatar7.png",
"https://raw.githubusercontent.com/betranthanh/android-kotlin-animation-move-image-along-path/master/avatar_demo/avatar8.png"
)
var players = ArrayList<PlayerDto>()
for (i in 0..7) {
var playerDto = PlayerDto()
playerDto.image = avatars.elementAt(i)
playerDto.distance = Constants.PLAYER_DISTANT * i + Constants.PLAYER_SIZE
playerDto.offsetX = Constants.PLAYER_SIZE / 2
playerDto.offsetY = Constants.PLAYER_SIZE / 2
players.add(playerDto)
}
animationView.setPlayers(players)
}
}
| 0
|
Kotlin
|
5
| 9
|
14d2a849e75895f97776d60ff82b6c8ba230f239
| 2,045
|
android-kotlin-animation-move-image-along-path
|
MIT License
|
underlayk/src/main/java/com/mozhimen/underlayk/logk/annors/ALogKType.kt
|
mozhimen
| 353,952,154
| false
| null |
package com.mozhimen.underlayk.logk.annors
import androidx.annotation.IntDef
import com.mozhimen.basick.elemk.cons.CLogPriority
/**
* @ClassName LogKType
* @Description TODO
* @Author <NAME> / Mozhimen
* @Date 2021/12/20 16:59
* @Version 1.0
*/
@IntDef(value = [CLogPriority.V, CLogPriority.D, CLogPriority.I, CLogPriority.W, CLogPriority.E, CLogPriority.A])
@Retention(AnnotationRetention.SOURCE)
annotation class ALogKType
| 0
|
Kotlin
|
6
| 112
|
efbc55d940b169511106a9b813513fc3f86df1fb
| 433
|
SwiftKit
|
Apache License 2.0
|
app/src/main/java/com/example/moviescourseapp/presentation/detail/MovieDetailsViewModel.kt
|
adolfo1295
| 755,302,290
| false
|
{"Kotlin": 42090}
|
package com.example.moviescourseapp.presentation.detail
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.moviescourseapp.data.MoviesRepository
import com.example.moviescourseapp.presentation.home.ErrorMessage
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.net.ConnectException
import javax.inject.Inject
import kotlin.time.Duration.Companion.seconds
@HiltViewModel
class MovieDetailsViewModel @Inject constructor(
private val movieRepository: MoviesRepository
) : ViewModel() {
private val _movieDetailsUiState = MutableStateFlow(MovieDetailsUiState())
val movieDetailsUiState = _movieDetailsUiState.asStateFlow()
fun getMovieDetails(movieId: String) {
Log.d("adolfo", "getMovieDetails: paso por aqui")
viewModelScope.launch {
_movieDetailsUiState.update {
it.copy(isLoading = true, error = null)
}
delay(1.seconds)
try {
val movieDetail = movieRepository.getMovieDetails(movieId = movieId)
_movieDetailsUiState.update {
it.copy(isLoading = false, movieDetailsModel = movieDetail)
}
} catch (e: Exception) {
val error = when (e) {
is ConnectException -> ErrorMessage.INTERNET_CONNECTION
else -> ErrorMessage.DEFAULT
}
_movieDetailsUiState.update {
it.copy(isLoading = false, error = error)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b1951466830fed652f04df384dcb5b309b5f0bd5
| 1,695
|
MoviesCourseApp
|
Apache License 2.0
|
buildSrc/src/test/kotlin/ch/acanda/gradle/fabrikt/build/generator/FilePropertyGeneratorTest.kt
|
acanda
| 687,155,869
| false
|
{"Kotlin": 104277}
|
package ch.acanda.gradle.fabrikt.build.generator
import ch.acanda.gradle.fabrikt.build.ExtensionGeneratorTest.Companion.writeToString
import com.squareup.kotlinpoet.TypeSpec
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
class FilePropertyGeneratorTest : StringSpec({
"fileProperty(name) should create property and syntactic sugar" {
val typeSpec = TypeSpec.classBuilder("Dog")
.fileProperty("healthRecord")
.build()
typeSpec.writeToString() shouldBe """
|package ch.acanda
|
|import java.io.File
|import java.nio.`file`.Path
|import kotlin.CharSequence
|import kotlin.jvm.JvmName
|import org.gradle.api.`file`.RegularFile
|import org.gradle.api.`file`.RegularFileProperty
|import org.gradle.api.provider.Provider
|
|public class Dog {
| public val healthRecord: RegularFileProperty = objects.fileProperty()
|
| public fun healthRecord(healthRecord: File) {
| this.healthRecord.set(healthRecord)
| }
|
| @JvmName("healthRecordFromFileProvider")
| public fun healthRecord(healthRecord: Provider<File>) {
| this.healthRecord.set(objects.fileProperty().fileProvider(healthRecord))
| }
|
| public fun healthRecord(healthRecord: Path) {
| this.healthRecord.set(healthRecord.toFile())
| }
|
| @JvmName("healthRecordFromPathProvider")
| public fun healthRecord(healthRecord: Provider<out Path>) {
| this.healthRecord.set(objects.fileProperty().fileProvider(healthRecord.map { it.toFile() }))
| }
|
| public fun healthRecord(healthRecord: CharSequence) {
| this.healthRecord.set(File(healthRecord.toString()))
| }
|
| @JvmName("healthRecordFromCharSequenceProvider")
| public fun healthRecord(healthRecord: Provider<out CharSequence>) {
| val provider = objects.fileProperty().fileProvider(healthRecord.map { File(it.toString()) })
| this.healthRecord.set(provider)
| }
|
| public fun healthRecord(healthRecord: RegularFile) {
| this.healthRecord.set(healthRecord)
| }
|
| @JvmName("healthRecordFromRegularFileProvider")
| public fun healthRecord(healthRecord: Provider<out RegularFile>) {
| this.healthRecord.set(healthRecord)
| }
|}
|
""".trimMargin()
}
})
| 2
|
Kotlin
|
0
| 2
|
138b8acccf5f4f255ab42f25dae00d4bd889c3b5
| 2,803
|
fabrikt-gradle-plugin
|
Apache License 2.0
|
src/main/kotlin/us/sodiumlabs/electorate/ranked/RankedApproval.kt
|
napentathol
| 130,545,021
| false
| null |
package us.sodiumlabs.electorate.ranked
import com.google.common.collect.HashBasedTable
import us.sodiumlabs.electorate.sim.Candidate
import us.sodiumlabs.electorate.sim.ElectoralSystem
import us.sodiumlabs.electorate.sim.ElectoralSystemName
import us.sodiumlabs.electorate.sim.Electorate
import us.sodiumlabs.electorate.sim.VotingStrategy
import java.util.Optional
class RankedApproval(private val strategy: RankedApprovalStrategy) : ElectoralSystem {
override fun electCandidate(electorate: Electorate): Optional<Candidate> {
val ballots = electorate.poll(strategy)
val candidateTable = HashBasedTable.create<Candidate, Candidate, Int>()
var candidates = electorate.candidates
// Tally
ballots.forEach {
val missingCandidates = candidates - it.candidates
for (i in 0 until it.candidates.size - 1) {
val c1 = it.candidates[i]
for (j in i + 1 until it.candidates.size) {
val c2 = it.candidates[j]
val n = Optional.ofNullable(candidateTable.get(c1, c2)).orElse(0)
candidateTable.put(c1, c2, n + 1)
}
for(c2 in missingCandidates) {
}
}
}
var condorcetWinner = Optional.empty<Candidate>()
while(condorcetWinner.isEmpty) {
// find the condorcet winner and return if it is present
condorcetWinner = findCondorcetWinner(candidates, candidateTable)
if(condorcetWinner.isPresent) break
// remove the least approved candidate(s);
candidates = removeLeastApprovedCandidates(candidates, candidateTable)
if(candidates.isEmpty()) return Optional.empty()
}
return condorcetWinner
}
override fun getSystemName(): ElectoralSystemName = strategy.getSystemName()
}
interface RankedApprovalStrategy : VotingStrategy<RankedBallot> {
fun getSystemName(): ElectoralSystemName
}
| 0
|
Kotlin
|
0
| 1
|
ad82e05775861030c40e0c39384016de34e69275
| 2,008
|
electorate
|
MIT License
|
src/main/java/dev/zprotect/obfuscator/api/TransformerPriority.kt
|
JessSystemV
| 599,200,266
| false
| null |
/**
* Copyright (C) 2022 zProtect
*
* This software is NOT free software.
* You may NOT distribute it or modify it without explicit permission.
*
* This software has been created in the hope that it will be useful,
* but WITHOUT ANY WARRANTY. zProtect is NOT liable for ANY damages caused by unlawful distribution
* or usage of any zProtect source code or products.
*
* You should have received a copy of the zProtect PU (Prohibited Usage) License along with this program.
*/
package dev.zprotect.obfuscator.api
enum class TransformerPriority {
HIGHEST, HIGH, NORMAL, LOW, LOWEST
}
| 0
| null |
2
| 8
|
ffb39ed146380b6a9ef50b10a0e51cee01aad4ef
| 598
|
zProtect
|
MIT License
|
memkched-client/src/main/kotlin/com/raycoarana/memkched/internal/ProtocolAbstractFactory.kt
|
raycoarana
| 597,846,682
| false
| null |
package com.raycoarana.memkched.internal
import com.raycoarana.memkched.api.Protocol
import com.raycoarana.memkched.api.Protocol.BINARY
import com.raycoarana.memkched.api.Protocol.TEXT
import com.raycoarana.memkched.internal.text.TextProtocolAbstractFactory
import kotlinx.coroutines.channels.Channel
import java.net.InetSocketAddress
internal interface ProtocolAbstractFactory<out T : SocketChannelWrapper> {
fun createOperationFactory(): OperationFactory<out T>
fun createNodeWorkerFactory(socketConfig: SocketConfig): NodeWorkerFactory<T>
fun createCluster(
queueSize: Int,
socketConfig: SocketConfig,
addresses: Array<InetSocketAddress>
): Cluster<out T> = Cluster(
nodeWorkerFactory = createNodeWorkerFactory(socketConfig),
channel = Channel(queueSize),
addresses = addresses,
threadPoolInitialSize = socketConfig.nioThreadPoolInitialSize
)
companion object {
fun create(protocol: Protocol): ProtocolAbstractFactory<SocketChannelWrapper> =
when (protocol) {
TEXT -> TextProtocolAbstractFactory()
BINARY -> TODO("Binary protocol not implemented")
}
}
}
| 2
|
Kotlin
|
0
| 0
|
0e851d420910b654be04feef81d4a26c8abdd708
| 1,209
|
memkched
|
MIT License
|
src/main/kotlin/br/com/zup/casadocodigo/book/BookDetailResponse.kt
|
walisonpereirazup
| 313,660,618
| true
|
{"Kotlin": 42214, "Dockerfile": 995}
|
package br.com.zup.casadocodigo.book
import br.com.zup.casadocodigo.author.Author
import java.math.BigDecimal
import java.time.LocalDate
class BookDetailResponse(
val title: String,
val abstract: String,
val summary: String,
val price: BigDecimal,
val pages: Int,
val isbn: String,
val publishedAt: LocalDate,
val author: BookAuthorResponse
) {
constructor(book: Book) : this(
book.title,
book.abstract,
book.summary,
book.price,
book.pages,
book.isbn,
book.publishedAt,
BookAuthorResponse(book.author)
)
class BookAuthorResponse(val name: String, val description: String) {
constructor(author: Author) : this(author.name, author.description)
}
}
| 0
|
Kotlin
|
1
| 1
|
e2f7053cca10cbe11f0588aafebb640198a47d6a
| 836
|
bootcamp-02-template-casa-do-codigo
|
Apache License 2.0
|
app/src/main/java/com/github/libliboom/epubviewer/base/BaseView.kt
|
libliboom
| 258,487,396
| false
| null |
package com.github.libliboom.epubviewer.base
interface BaseView {
fun getLayoutId(): Int
}
| 2
|
Kotlin
|
0
| 3
|
71f1d99af902a82784819a672bb3e27fa306f005
| 96
|
Epub-Viewer-Android
|
MIT License
|
feature/signup/src/main/java/com/erkindilekci/signup/SignUpViewModel.kt
|
erkindilekci
| 668,684,107
| false
| null |
package com.erkindilekci.signup
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.erkindilekci.domain.usecase.auth.SignUpUseCase
import com.erkindilekci.util.Response
import com.google.firebase.auth.AuthResult
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SignUpViewModel @Inject constructor(
private val signUpUseCase: SignUpUseCase,
) : ViewModel() {
private var _signUpFlow = MutableSharedFlow<Response<AuthResult>>()
val signUpFlow = _signUpFlow
var nameState by mutableStateOf("")
private set
var emailState by mutableStateOf("")
private set
var passwordState by mutableStateOf("")
private set
fun signUp() {
viewModelScope.launch {
signUpUseCase.invoke(nameState, emailState, passwordState).collect {
_signUpFlow.emit(it)
}
}
}
fun updateNameState(str: String) {
nameState = str
}
fun updateEmailState(str: String) {
emailState = str
}
fun updatePasswordState(str: String) {
passwordState = str
}
}
| 0
|
Kotlin
|
0
| 0
|
2c862d0d868f229e7458da39dd4f32efaf8e6d11
| 1,419
|
CryptoBalanceTracker
|
Apache License 2.0
|
examples/nft/create/createAnNft/main.kt
|
GWT-M3O-TEST
| 485,009,715
| false
| null |
package examples.nft.create
import com.m3o.m3okotlin.M3O
import com.m3o.m3okotlin.services.nft
suspend fun main() {
M3O.initialize(System.getenv("M3O_API_TOKEN"))
val req = NftCreateRequest(Name = "<NAME>",
Description = "The epic monkey island character",)
try {
val response = NftServ.create(req)
println(response)
} catch (e: Exception) {
println(e)
}
}
| 1
|
Kotlin
|
1
| 0
|
54158b584ba47bd7323a484804dcd78c55ef7f69
| 392
|
m3o-kotlin
|
Apache License 2.0
|
waypoints/src/main/kotlin/de/md5lukas/waypoints/gui/pages/ListingPage.kt
|
Sytm
| 211,378,928
| false
| null |
package de.md5lukas.waypoints.gui.pages
import de.md5lukas.commons.collections.PaginationList
import de.md5lukas.kinvs.items.GUIContent
import de.md5lukas.waypoints.gui.WaypointsGUI
import org.bukkit.inventory.ItemStack
open class ListingPage<T>(
wpGUI: WaypointsGUI,
background: ItemStack,
private val contentGetter: () -> PaginationList<T>,
private val displayableConverter: (T) -> GUIContent
) : BasePage(wpGUI, background) {
companion object Constants {
const val PAGINATION_LIST_PAGE_SIZE = 4 * 9
}
protected var listingContent: PaginationList<T> = contentGetter()
protected var listingPage = 0
protected fun checkListingPageBounds() {
if (listingPage < 0) {
listingPage = 0
} else if (listingPage >= listingContent.pages()) {
listingPage = listingContent.pages() - 1
}
}
protected fun isValidListingPage(page: Int) = page >= 0 && page < listingContent.pages()
protected fun updateListingContent() {
listingContent = contentGetter()
checkListingPageBounds()
updateListingInInventory()
}
protected fun updateListingInInventory() {
val pageContent = listingContent.page(listingPage)
for (row in 0..3) {
for (column in 0..8) {
val content = pageContent.getOrNull(row * 8 + column)
if (content == null) {
grid[row][column] = GUIContent.AIR
} else {
grid[row][column] = displayableConverter(content)
}
}
}
wpGUI.gui.update()
}
protected fun previousPage() {
if (!isValidListingPage(listingPage - 1))
return
listingPage--
updateListingInInventory()
}
protected fun nextPage() {
if (!isValidListingPage(listingPage + 1))
return
listingPage++
updateListingInInventory()
}
}
| 3
|
Kotlin
|
3
| 12
|
9a69b00457a7308507dea14a54199abb181a6b90
| 1,970
|
waypoints
|
MIT License
|
2017/src/test/kotlin/Day04Test.kt
|
dlew
| 498,498,097
| false
|
{"Kotlin": 273159, "TypeScript": 60083, "JavaScript": 262}
|
import answer.Answer
import answer.answerEquals
import org.junit.Assert.*
import org.junit.Test
import utils.getResourceAsString
import utils.splitNewlines
class Day04Test {
@Test
fun part1() {
answerEquals(Answer.DAY04_PART1, Day04.part1(getResourceAsString("day04.txt")))
}
@Test
fun part2() {
answerEquals(Answer.DAY04_PART2, Day04.part2(getResourceAsString("day04.txt")))
}
}
| 0
|
Kotlin
|
0
| 0
|
bb7494aa33da1d63de8c382e858fee51e609b703
| 403
|
advent-of-code
|
MIT License
|
src/main/kotlin/no/nav/permitteringsskjemaapi/util/TokenUtil.kt
|
navikt
| 247,277,988
| false
|
{"Kotlin": 151424, "Dockerfile": 81}
|
package no.nav.permitteringsskjemaapi.util
import no.nav.permitteringsskjemaapi.config.TOKENX_ISSUER
import no.nav.security.token.support.core.context.TokenValidationContextHolder
import no.nav.security.token.support.core.exceptions.JwtTokenValidatorException
import no.nav.security.token.support.core.jwt.JwtTokenClaims
import org.springframework.stereotype.Component
import java.util.*
@Component
class TokenUtil(private val ctxHolder: TokenValidationContextHolder) {
private val claimSet: JwtTokenClaims
get() = ctxHolder.getTokenValidationContext().getClaims(TOKENX_ISSUER)
val expiryDate: Date?
get() = claimSet.expirationTime
val fnrFraToken: String?
get() = claimSet.getStringClaim("pid")
fun autentisertBruker(): String {
return fnrFraToken ?: throw JwtTokenValidatorException("Fant ikke fødselsnummer i token")
}
}
| 0
|
Kotlin
|
0
| 0
|
d12b8276702b2cc1163f7e8da0c1d757738686e1
| 880
|
permitteringsskjema-api
|
MIT License
|
app/src/main/java/com/padcmyanmar/kunyi/network/JobDataAgent.kt
|
NweNiAung90
| 142,923,305
| false
| null |
package com.padcmyanmar.kunyi.network
interface JobDataAgent {
fun loadJobInfo( accessToken: String , mpage: Int )
}
| 0
|
Kotlin
|
0
| 0
|
d51d1a6081a9dbaafb7cf4526cbc815121be854c
| 122
|
MM-KuNyi-NNA
|
MIT License
|
src/Day01.kt
|
strindberg
| 572,685,170
| false
|
{"Kotlin": 15804}
|
import java.lang.Integer.max
fun main() {
fun part1(input: List<String>): Int =
input.fold(Pair(0, 0)) { (max, total), line ->
if (line.isEmpty())
Pair(max(total, max), 0)
else
Pair(max, total + line.toInt())
}.first
fun part2(input: List<String>): Int =
input.fold(Pair(listOf(0, 0, 0), 0)) { (maxThree, total), line ->
if (line.isEmpty())
Pair((maxThree + total).sortedDescending().take(3), 0)
else
Pair(maxThree, total + line.toInt())
}.first.sum()
val input = readInput("Day01")
val part1 = part1(input)
println(part1)
check(part1 == 69693)
val part2 = part2(input)
println(part2)
check(part2 == 200945)
}
| 0
|
Kotlin
|
0
| 0
|
c5d26b5bdc320ca2aeb39eba8c776fcfc50ea6c8
| 843
|
aoc-2022
|
Apache License 2.0
|
src/test/kotlin/mbo/dev/springnative/domain/user/UserServiceTest.kt
|
mbogner
| 559,374,643
| false
|
{"Kotlin": 19977, "PLpgSQL": 1753}
|
package mbo.dev.springnative.domain.user
import jakarta.persistence.EntityManager
import jakarta.transaction.Transactional
import mbo.dev.springnative.AbstractCrudServiceTest
import org.springframework.beans.factory.annotation.Autowired
@Transactional
internal class UserServiceTest @Autowired constructor(
repo: UserRepository,
em: EntityManager,
) : AbstractCrudServiceTest<User>(UserService(repo), em) { // workaround because repo isn't initialised in autowiring
override fun validInstance(): User {
return UserGen.validInstance()
}
}
| 0
|
Kotlin
|
0
| 0
|
4e635e0f211c76015bbf03de817469bbe60f4d39
| 566
|
spring-native-sample
|
Apache License 2.0
|
fireko-codegen/src/main/java/de/musichin/fireko/processor/TargetParameter.kt
|
musichin
| 272,263,347
| false
| null |
package de.musichin.fireko.processor
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.metadata.KotlinPoetMetadataPreview
import de.musichin.fireko.annotations.Embedded
import de.musichin.fireko.annotations.FirekoAdapter
import de.musichin.fireko.annotations.NullValues
import javax.lang.model.type.DeclaredType
internal class TargetParameter(
classElement: ClassElement,
parameterSpec: ParameterSpec,
) {
val name = parameterSpec.name
val type = parameterSpec.type
val annotations: List<AnnotationSpec> =
parameterSpec.propertyAnnotations(classElement.typeSpec)
val exclude: Boolean = hasAnnotation(FIREBASE_EXCLUDE)
val include = !exclude
val propertyName: String = annotations.propertyName() ?: name
val hasDefaultValue: Boolean = parameterSpec.defaultValue != null
val usingAdapter = annotations
.get(FirekoAdapter::class.asClassName())
?.value("using")
?.let { it as DeclaredType }
?.asElement()
private val targetNullValues: NullValues? =
classElement.element.getAnnotation(NullValues::class.java)
private val propertyNullValues: NullValues? by lazy {
val nullValues = annotations.get(NullValues::class.asClassName())
if (nullValues == null) {
null
} else {
val omit = nullValues.value("omit") as Boolean? ?: false
val preset = nullValues.value("preset") as Boolean? ?: false
val constructor = NullValues::class.constructors.first()
constructor.call(omit, preset)
}
}
val omitNullValue = type.isNullable &&
(propertyNullValues ?: targetNullValues)?.omit == true
val presetNullValue = hasDefaultValue &&
(propertyNullValues ?: targetNullValues)?.preset == true
val embedded: Boolean = hasAnnotation(Embedded::class.asClassName())
val documentId: Boolean = hasAnnotation(FIREBASE_DOCUMENT_ID)
val serverTimestamp: Boolean = hasAnnotation(FIREBASE_SERVER_TIMESTAMP)
fun hasAnnotation(typeName: TypeName): Boolean = annotation(typeName) != null
fun annotation(typeName: TypeName): AnnotationSpec? = annotations.get(typeName)
companion object {
private fun ParameterSpec.propertyAnnotations(typeSpec: TypeSpec): List<AnnotationSpec> {
val fieldAnnotations = typeSpec.propertySpecs
.filter { it.name == this.name }
.flatMap { it.annotations }
return annotations + fieldAnnotations
}
internal fun List<AnnotationSpec>.propertyName(): String? =
annotationValue(FIREBASE_PROPERTY_NAME, "value")?.toString()
internal fun List<AnnotationSpec>.annotationValue(
annotation: TypeName,
property: String
): Any? = get(annotation)?.value(property)
@KotlinPoetMetadataPreview
fun create(element: ClassElement, parameter: ParameterSpec): TargetParameter {
return TargetParameter(element, parameter)
}
}
}
| 5
|
Kotlin
|
0
| 2
|
8c36bf692ec037b63fffd3d0b3f3db986a965a7a
| 3,221
|
fireko
|
MIT License
|
meccano-core/src/main/kotlin/com/gastonlagaf/meccano/annotation/RequestParam.kt
|
gastonlagaf
| 241,596,102
| true
|
{"Kotlin": 164175, "FreeMarker": 528}
|
package com.gastonlagaf.meccano.annotation
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class RequestParam(
val value: String = ""
)
| 0
|
Kotlin
|
0
| 0
|
40be8e3ba49fa67867c768cf64dc4c1b56ebfd8c
| 185
|
meccano
|
Apache License 2.0
|
gateway/src/main/kotlin/me/ogq/ocp/sample/gateway/elasticsearch/EsParser.kt
|
mj-at-ogq
| 605,355,876
| false
| null |
package me.ogq.ocp.sample.gateway.elasticsearch
import me.ogq.ocp.sample.model.event.ImageEventData
import me.ogq.ocp.sample.model.image.StringSetConverter
import org.elasticsearch.action.search.SearchResponse
import org.elasticsearch.search.SearchHit
import org.springframework.stereotype.Component
@Component
class EsParser(
private val tagConverter: StringSetConverter,
) {
fun toDocumentFrom(image: ImageEventData): Map<String, Any?> {
return mapOf(
"image_id" to image.id.toString(),
"title" to image.title,
"description" to image.description,
"imagePath" to image.imagePath,
"tags" to tagConverter.convertToDatabaseColumn(image.tags),
"creator_id" to image.authorId.toString(),
"publicity_id" to image.publicityRightId.toString(),
)
}
fun toImageListFrom(searchResponse: SearchResponse): List<ImageEventData> {
val images = mutableListOf<ImageEventData>()
val hits = searchResponse.hits.hits
for (hit in hits) {
val image = toImageFrom(hit)
images.add(image)
}
return images
}
private fun toImageFrom(source: SearchHit): ImageEventData {
val sourceMap = source.sourceAsMap
val id = sourceMap["image_id"]?.toString()?.toLong()
val title = sourceMap["title"] as String
val description = sourceMap["description"] as String?
val tags = tagConverter.convertToEntityAttribute(sourceMap["tags"] as String)
val creatorId = sourceMap["creator_id"]?.toString()?.toLong()
val imagePath = sourceMap["imagePath"] as String
val publicityRightId = sourceMap["publicity_id"]?.toString()?.toLongOrNull()
return ImageEventData(
id = id ?: throw IllegalArgumentException("id should not be null"),
title = title,
description = description,
tags = tags,
publicityRightId = publicityRightId,
authorId = creatorId ?: throw IllegalArgumentException("creatorId should not be null"),
imagePath = imagePath
)
}
}
| 0
|
Kotlin
|
1
| 0
|
43ab8aa22afd010120bdbbe2a5268f33d77f968b
| 2,155
|
image-platform-api
|
MIT License
|
src/test/kotlin/dev/itv/itv_proyecto/services/storages/CsvTrabajadoresStorageTest.kt
|
AlvaroDVA
| 641,823,911
| false
| null |
package dev.itv.itv_proyecto.services.storages
import dev.itv.itv_proyecto.config.AppConfig
import dev.itv.itv_proyecto.di.moduloTest
import dev.itv.itv_proyecto.enums.Especialidad
import dev.itv.itv_proyecto.models.Trabajador
import dev.itv.itv_proyecto.repositories.TrabajadorRepositoryImpl
import dev.itv.itv_proyecto.utils.UtilsForTest
import mu.KotlinLogging
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.test.KoinTest
import org.koin.test.inject
import java.io.File
import java.io.FileInputStream
import java.sql.Connection
import java.sql.DriverManager
import java.time.LocalDate
import java.util.*
class CsvTrabajadoresStorageTest : KoinTest {
private val logger = KotlinLogging.logger { }
lateinit var database : Connection
val utilsForTest = UtilsForTest()
val appConfig : AppConfig by inject()
lateinit var trabajadoresRepository : TrabajadorRepositoryImpl
val csvTrabajadoresStorage = CsvTrabajadoresStorage()
val trabajadores = mutableListOf<Trabajador>()
@BeforeEach
fun iniciarTest() {
cambiarValores()
database = DriverManager.getConnection("jdbc:mariadb://127.0.0.1:3306/TestbbITV", "root", "")
trabajadoresRepository = TrabajadorRepositoryImpl().apply {
database = DriverManager.getConnection("jdbc:mariadb://127.0.0.1:3306/TestbbITV", "root", "")
}
trabajadores.addAll(
listOf(
Trabajador(
nombreTrabajador = "<NAME>",
telefonoTrabajador = 123456789,
email = "<EMAIL>",
username = "juancito",
password = "<PASSWORD>",
fechaContratacion = LocalDate.parse("2017-12-01"),
especialidad = Especialidad.MOTOR,
isResponsable = false
),
Trabajador(
nombreTrabajador = "<NAME>",
telefonoTrabajador = 987654321,
email = "<EMAIL>",
username = "marialo",
password = "<PASSWORD>",
fechaContratacion = LocalDate.parse("2022-08-12"),
especialidad = Especialidad.ADMINISTRACION,
isResponsable = true
),
Trabajador(
nombreTrabajador = "<NAME>",
telefonoTrabajador = 555555555,
email = "<EMAIL>",
username = "pedror",
password = "<PASSWORD>",
fechaContratacion = LocalDate.parse("2021-05-10"),
especialidad = Especialidad.ELECTRICIDAD,
isResponsable = false
)
)
)
}
private fun cambiarValores() {
val properties = Properties()
val fileInputStream = FileInputStream("src/test/resources/config.properties")
properties.load(fileInputStream)
appConfig.loadProperties()
appConfig.bdPath = properties.getProperty("bd.path") ?: "127.0.0.1"
appConfig.dataPath = properties.getProperty("data.path") ?: "data"
appConfig.bdName = properties.getProperty("bd.name") ?: "Testbbitv"
appConfig.initDataFolder()
}
@AfterEach
fun closeBaseDatos () {
database.close()
}
@Test
fun csvTrabajadorTest() {
val fileName = System.getProperty("user.dir") + File.separator + appConfig.dataPath + File.separator + "FicheroTest.csv"
csvTrabajadoresStorage.saveFile(trabajadores, fileName)
val res = csvTrabajadoresStorage.loadFile(fileName)
assertEquals(trabajadores, res.component1())
}
companion object {
@JvmStatic
@BeforeAll
fun startup() {
startKoin {
this.modules(moduloTest)
}
}
@JvmStatic
@AfterAll
fun cerrarKoin () {
stopKoin()
}
}
}
| 0
|
Kotlin
|
1
| 1
|
c63907fde55a46c2d54bf04a985b1cab41c45a35
| 4,135
|
Proyecto_ITV
|
Creative Commons Zero v1.0 Universal
|
src/test/kotlin/dev/itv/itv_proyecto/services/storages/CsvTrabajadoresStorageTest.kt
|
AlvaroDVA
| 641,823,911
| false
| null |
package dev.itv.itv_proyecto.services.storages
import dev.itv.itv_proyecto.config.AppConfig
import dev.itv.itv_proyecto.di.moduloTest
import dev.itv.itv_proyecto.enums.Especialidad
import dev.itv.itv_proyecto.models.Trabajador
import dev.itv.itv_proyecto.repositories.TrabajadorRepositoryImpl
import dev.itv.itv_proyecto.utils.UtilsForTest
import mu.KotlinLogging
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.test.KoinTest
import org.koin.test.inject
import java.io.File
import java.io.FileInputStream
import java.sql.Connection
import java.sql.DriverManager
import java.time.LocalDate
import java.util.*
class CsvTrabajadoresStorageTest : KoinTest {
private val logger = KotlinLogging.logger { }
lateinit var database : Connection
val utilsForTest = UtilsForTest()
val appConfig : AppConfig by inject()
lateinit var trabajadoresRepository : TrabajadorRepositoryImpl
val csvTrabajadoresStorage = CsvTrabajadoresStorage()
val trabajadores = mutableListOf<Trabajador>()
@BeforeEach
fun iniciarTest() {
cambiarValores()
database = DriverManager.getConnection("jdbc:mariadb://127.0.0.1:3306/TestbbITV", "root", "")
trabajadoresRepository = TrabajadorRepositoryImpl().apply {
database = DriverManager.getConnection("jdbc:mariadb://127.0.0.1:3306/TestbbITV", "root", "")
}
trabajadores.addAll(
listOf(
Trabajador(
nombreTrabajador = "<NAME>",
telefonoTrabajador = 123456789,
email = "<EMAIL>",
username = "juancito",
password = "<PASSWORD>",
fechaContratacion = LocalDate.parse("2017-12-01"),
especialidad = Especialidad.MOTOR,
isResponsable = false
),
Trabajador(
nombreTrabajador = "<NAME>",
telefonoTrabajador = 987654321,
email = "<EMAIL>",
username = "marialo",
password = "<PASSWORD>",
fechaContratacion = LocalDate.parse("2022-08-12"),
especialidad = Especialidad.ADMINISTRACION,
isResponsable = true
),
Trabajador(
nombreTrabajador = "<NAME>",
telefonoTrabajador = 555555555,
email = "<EMAIL>",
username = "pedror",
password = "<PASSWORD>",
fechaContratacion = LocalDate.parse("2021-05-10"),
especialidad = Especialidad.ELECTRICIDAD,
isResponsable = false
)
)
)
}
private fun cambiarValores() {
val properties = Properties()
val fileInputStream = FileInputStream("src/test/resources/config.properties")
properties.load(fileInputStream)
appConfig.loadProperties()
appConfig.bdPath = properties.getProperty("bd.path") ?: "127.0.0.1"
appConfig.dataPath = properties.getProperty("data.path") ?: "data"
appConfig.bdName = properties.getProperty("bd.name") ?: "Testbbitv"
appConfig.initDataFolder()
}
@AfterEach
fun closeBaseDatos () {
database.close()
}
@Test
fun csvTrabajadorTest() {
val fileName = System.getProperty("user.dir") + File.separator + appConfig.dataPath + File.separator + "FicheroTest.csv"
csvTrabajadoresStorage.saveFile(trabajadores, fileName)
val res = csvTrabajadoresStorage.loadFile(fileName)
assertEquals(trabajadores, res.component1())
}
companion object {
@JvmStatic
@BeforeAll
fun startup() {
startKoin {
this.modules(moduloTest)
}
}
@JvmStatic
@AfterAll
fun cerrarKoin () {
stopKoin()
}
}
}
| 0
|
Kotlin
|
1
| 1
|
c63907fde55a46c2d54bf04a985b1cab41c45a35
| 4,135
|
Proyecto_ITV
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/br/com/zup/edu/servicosexternos/ContasDeClientesNoItauClient.kt
|
caiorodrigueszup
| 385,247,255
| true
|
{"Kotlin": 70251}
|
package br.com.zup.edu.servicosexternos
import br.com.zup.edu.TipoConta
import br.com.zup.edu.pix.novachave.DadosDaContaResponse
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.PathVariable
import io.micronaut.http.annotation.QueryValue
import io.micronaut.http.client.annotation.Client
@Client("http://localhost:9091/api/v1")
interface ContasDeClientesNoItauClient {
@Get("/clientes/{id}/contas{?tipo}")
fun buscarContaPorTipo(@PathVariable id: String, @QueryValue tipo: TipoConta): HttpResponse<DadosDaContaResponse>
}
| 0
|
Kotlin
|
0
| 0
|
b5adb6b86b19cd7347b91f7cdc231e3961e48f64
| 599
|
orange-talents-05-template-pix-keymanager-grpc
|
Apache License 2.0
|
effit-cqrs-backend/src/test/kotlin/be/swsb/effit/domain/core/competition/CompetitionCreatorTest.kt
|
SoftwareSandbox
| 179,507,167
| false
| null |
package be.swsb.effit.domain.core.competition
import be.swsb.effit.domain.command.competition.CreateCompetition
import be.swsb.effit.domain.core.exceptions.DomainValidationRuntimeException
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.junit.jupiter.api.Test
import java.time.LocalDate
class CompetitionCreatorTest {
@Test
fun `without startDate, creates Competition with default startDate`() {
val endDate = LocalDate.now().plusDays(5)
val actual = CompetitionCreator().from(CreateCompetition("unimportant", null, endDate))
assertThat(actual.startDate).isNotNull()
}
@Test
fun `without endDate, creates Competition with default endDate`() {
val startDate = LocalDate.now().minusDays(8)
val actual = CompetitionCreator().from(CreateCompetition("unimportant", startDate, null))
assertThat(actual.endDate).isNotNull()
}
@Test
fun `with both start and endDate, creates Competition with default start and end dates`() {
val startDate = LocalDate.now().minusDays(8)
val endDate = LocalDate.now().plusDays(8)
val actual = CompetitionCreator().from(CreateCompetition("unimportant", startDate, endDate))
assertThat(actual.startDate).isNotNull()
assertThat(actual.endDate).isNotNull()
}
@Test
fun `Cannot create a Competition without both a start and end date`() {
assertThatExceptionOfType(DomainValidationRuntimeException::class.java)
.isThrownBy {
CompetitionCreator().from(CreateCompetition("unimportant", null, null))
}
.withMessage("Cannot create a Competition without both a start and end date")
}
@Test
fun `name is null, cannot create a Competition without a name`() {
val startDate = LocalDate.now().minusDays(8)
val endDate = LocalDate.now().plusDays(8)
assertThatExceptionOfType(DomainValidationRuntimeException::class.java)
.isThrownBy {
CompetitionCreator().from(CreateCompetition(null, startDate, endDate))
}
.withMessage("Cannot create a Competition without a name")
}
@Test
fun `name is blank, cannot create a Competition without a name`() {
val startDate = LocalDate.now().minusDays(8)
val endDate = LocalDate.now().plusDays(8)
assertThatExceptionOfType(DomainValidationRuntimeException::class.java)
.isThrownBy {
CompetitionCreator().from(CreateCompetition(" ", startDate, endDate))
}
.withMessage("Cannot create a Competition without a name")
}
@Test
fun `name contains more than 25 characters, should throw exception`() {
val startDate = LocalDate.now().minusDays(8)
val endDate = LocalDate.now().plusDays(8)
assertThatExceptionOfType(DomainValidationRuntimeException::class.java)
.isThrownBy {
CompetitionCreator().from(CreateCompetition("a".repeat(26), startDate, endDate))
}
.withMessage("Cannot create a Competition with a name longer than 25 characters")
}
@Test
fun `name contains exactly 25 characters, should not throw exception`() {
val startDate = LocalDate.now().minusDays(8)
val endDate = LocalDate.now().plusDays(8)
val nameOfExactly25Characters = "a".repeat(25)
val createdCompetition = CompetitionCreator().from(CreateCompetition(nameOfExactly25Characters, startDate, endDate))
assertThat(createdCompetition.name).isEqualTo(nameOfExactly25Characters)
}
}
| 34
|
Kotlin
|
2
| 6
|
4b2f86c13e46c5561f7e675bf8c153025969e223
| 3,747
|
effit-challenge
|
MIT License
|
DelegationSample/src/main/kotlin/Sample06Main.kt
|
LeoAndo
| 331,229,609
| false
| null |
fun main() {
val user = User2(mapOf(
"name" to "<NAME>",
"age" to 25))
println(user.name)
println(user.age)
}
class User2(val map: Map<String, Any?>) {
val name: String by map
val age: Int by map
}
| 50
|
Kotlin
|
0
| 0
|
7efe78235b019354e934cb99563e9bfc3a33d69d
| 239
|
kotlin-training
|
Apache License 2.0
|
DelegationSample/src/main/kotlin/Sample06Main.kt
|
LeoAndo
| 331,229,609
| false
| null |
fun main() {
val user = User2(mapOf(
"name" to "<NAME>",
"age" to 25))
println(user.name)
println(user.age)
}
class User2(val map: Map<String, Any?>) {
val name: String by map
val age: Int by map
}
| 50
|
Kotlin
|
0
| 0
|
7efe78235b019354e934cb99563e9bfc3a33d69d
| 239
|
kotlin-training
|
Apache License 2.0
|
app/src/main/java/com/example/ca2_circle/MainActivity.kt
|
Garvitjoshi1
| 858,722,635
| false
|
{"Kotlin": 4707}
|
package com.example.ca2_circle
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(CustomCanvas(this))
}
inner class CustomCanvas(context: Context) : View(context) {
private var circleRadius = 150f
private var circle1X = 0f
private var circle2X = 0f
private var circleY = 0f
private var centerX = 0f
private var isMovingToCenter = false
private val paint1 = Paint().apply {
color = Color.RED
}
private val paint2 = Paint().apply {
color = Color.BLUE
}
init {
setBackgroundColor(Color.YELLOW)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
circle1X = w * 0.25f
circle2X = w * 0.75f
circleY = h / 2f
centerX = w / 2f
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawCircle(circle1X, circleY, circleRadius, paint1)
canvas.drawCircle(circle2X, circleY, circleRadius, paint2)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
if (!isMovingToCenter) {
isMovingToCenter = true
animateCircles()
} else {
isMovingToCenter = false
resetCircles()
}
}
}
return true
}
private fun animateCircles() {
val animator1 = ValueAnimator.ofFloat(circle1X, centerX - circleRadius)
animator1.addUpdateListener { animation ->
circle1X = animation.animatedValue as Float
invalidate()
}
val animator2 = ValueAnimator.ofFloat(circle2X, centerX + circleRadius)
animator2.addUpdateListener { animation ->
circle2X = animation.animatedValue as Float
invalidate()
}
animator1.duration = 1000
animator2.duration = 1000
animator1.interpolator = AccelerateDecelerateInterpolator()
animator2.interpolator = AccelerateDecelerateInterpolator()
animator1.start()
animator2.start()
}
private fun resetCircles() {
val animator1 = ValueAnimator.ofFloat(circle1X, width * 0.25f)
animator1.addUpdateListener { animation ->
circle1X = animation.animatedValue as Float
invalidate()
}
val animator2 = ValueAnimator.ofFloat(circle2X, width * 0.75f)
animator2.addUpdateListener { animation ->
circle2X = animation.animatedValue as Float
invalidate()
}
animator1.duration = 1000
animator2.duration = 1000
animator1.interpolator = AccelerateDecelerateInterpolator()
animator2.interpolator = AccelerateDecelerateInterpolator()
animator1.start()
animator2.start()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
52dc88e34906cb04ca61b213c0fa43af3b361162
| 3,690
|
CA2_circle
|
MIT License
|
HIGOODS-Api/src/main/kotlin/com/higoods/api/orderform/controller/OrderFormController.kt
|
higoods-hongik
| 663,934,695
| false
|
{"Kotlin": 324199, "Dockerfile": 291}
|
package com.higoods.api.orderform.controller
import com.higoods.api.orderform.dto.request.OrderFormCreateRequest
import com.higoods.api.orderform.usecase.OrderFormCreateUseCase
import com.higoods.api.orderform.usecase.OrderFormReadUseCase
import com.higoods.domain.orderform.domain.OrderFormVo
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/v1/project/{project_id}/order-form")
class OrderFormController(
private val orderFormCreateUseCase: OrderFormCreateUseCase,
private val orderFormReadUseCase: OrderFormReadUseCase
) {
@PostMapping
fun create(
@PathVariable("project_id") projectId: Long,
@Validated @RequestBody
orderFormCreateRequests: List<OrderFormCreateRequest>
): OrderFormVo {
return orderFormCreateUseCase.execute(projectId, orderFormCreateRequests)
}
/**
* 주문폼은 한개만 관리합니다.
*/
@GetMapping
fun getOrderForm(
@PathVariable("project_id") projectId: Long
): OrderFormVo {
return orderFormReadUseCase.execute(projectId)
}
}
| 4
|
Kotlin
|
0
| 1
|
0726bc2a44e9eb4e4c630814a9d010d33c1a7018
| 1,444
|
HIGOODS-Backend
|
MIT License
|
src/main/kotlin/com/careem/gradle/dependencies/denylist/denylist.kt
|
careem
| 309,438,205
| false
|
{"Kotlin": 30344}
|
/*
* Copyright Careem, an Uber Technologies Inc. company
*
* 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.careem.gradle.dependencies.denylist
import com.careem.gradle.dependencies.common.filterMatches
import com.careem.gradle.dependencies.common.parser.Dependency
import com.careem.gradle.dependencies.common.parser.parseDependencyTree
fun illegalDependencies(dependencies: String, illegalDependencies: List<String>): Map<Dependency, List<Dependency>> {
return if (illegalDependencies.isEmpty()) {
emptyMap()
} else {
val tree = parseDependencyTree(dependencies)
val denyListDependencies = illegalDependencies.map { it.asDependency() }
denyListDependencies
.map { illegal ->
val result = tree.mapNotNull { treeDependency ->
treeDependency.filterMatches { it.matches(illegal) }
}
illegal to result
}
.filter { (_, matches) -> matches.isNotEmpty() }
.associateBy(
keySelector = { it.first },
valueTransform = { it.second }
)
}
}
internal fun Dependency.matches(target: Dependency) =
artifact == target.artifact && requestedVersion == target.resolvedVersion
private fun String.asDependency(): Dependency {
val pieces = this.split(":")
val group = pieces[0]
val artifact = pieces[1]
val version = pieces[2]
return Dependency(group, artifact, version, version)
}
| 1
|
Kotlin
|
3
| 43
|
eed681fec0069a30e853ed996b8d4b09bbac1987
| 1,888
|
dependency-diff-tldr
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/darrenthiores/ecoswap/presentation/profile/ProfileState.kt
|
darrenthiores
| 688,372,873
| false
|
{"Kotlin": 770054, "Swift": 362583}
|
package com.darrenthiores.ecoswap.presentation.profile
import com.darrenthiores.ecoswap.domain.item.model.Item
import com.darrenthiores.ecoswap.domain.reviews.model.Review
import com.darrenthiores.ecoswap.domain.user.model.User
import com.darrenthiores.ecoswap.presentation.utils.PagingState
data class ProfileState(
val user: User? = null,
val isUserLoading: Boolean = false,
val userError: String? = null,
val items: PagingState<Item> = PagingState(),
val reviews: PagingState<Review> = PagingState()
)
| 0
|
Kotlin
|
0
| 0
|
792b3293b4e378b7482f948ce4de622cb88f3cf1
| 527
|
EcoSwap
|
MIT License
|
backend/src/main/kotlin/top/kanetah/planhv2/backend/repository/SubjectRepository.kt
|
kanetah
| 118,541,878
| false
|
{"JavaScript": 104696, "Kotlin": 96766, "HTML": 5613, "CSS": 1941, "Dockerfile": 207}
|
package top.kanetah.planhv2.backend.repository
import top.kanetah.planhv2.backend.annotation.DataAccess
import top.kanetah.planhv2.backend.entity.Subject
/**
* created by kane on 2018/1/24
*/
@DataAccess
interface SubjectRepository {
fun save(subject: Subject): Int
fun delete(id: Int): Int
fun update(subject: Subject): Int
fun findAll(): ArrayList<Subject>?
fun find(id: Int): Subject?
fun findBySubjectName(subjectName: String): Subject?
}
| 44
|
JavaScript
|
0
| 2
|
f386b724d08a6fe9afdc8119ddccf7f57a717301
| 477
|
planhv2
|
MIT License
|
app/src/main/java/com/vicgcode/dialectica/domain/usecases/GetOwnPersonUseCase.kt
|
vicgcode
| 634,342,124
| false
|
{"Kotlin": 107302}
|
package com.vicgcode.dialectica.domain.usecases
import com.vicgcode.dialectica.database.room.AppRoomRepository
class GetOwnPersonUseCase(
private val appRoomRepository: AppRoomRepository
) {
suspend operator fun invoke(isOwner: Boolean?) =
appRoomRepository.getOwnerPerson(isOwner)
}
| 0
|
Kotlin
|
0
| 0
|
87e7046c67b2ddf125c88dca57b24c117bcbea91
| 302
|
Dialectica
|
Apache License 2.0
|
GrowthBook/src/commonMain/kotlin/com/sdk/growthbook/features/FeatureURLBuilder.kt
|
growthbook
| 445,362,249
| false
|
{"Kotlin": 208616}
|
package com.sdk.growthbook.features
internal class FeatureURLBuilder {
companion object {
/**
* Context Path for Fetching Feature Details - Web Service
*/
private const val featurePath = "api/features"
}
fun buildUrl(baseUrl: String, apiKey: String): String {
val baseUrlWithFeaturePath = if (baseUrl.endsWith('/'))
"$baseUrl$featurePath"
else
"$baseUrl/$featurePath"
return "$baseUrlWithFeaturePath/$apiKey"
}
}
| 7
|
Kotlin
|
14
| 15
|
a15859757e96114f84d595beeb0d78055408e271
| 515
|
growthbook-kotlin
|
MIT License
|
util/autodoc-core/src/main/kotlin/top/bettercode/autodoc/core/model/CombineCollection.kt
|
top-bettercode
| 387,652,015
| false
| null |
package top.bettercode.autodoc.core.model
import com.fasterxml.jackson.annotation.JsonIgnore
import top.bettercode.autodoc.core.operation.DocOperation
data class CombineCollection(private val rootCollection: DocCollection, var projectCollection: DocCollection?) : ICollection {
override val name: String = rootCollection.name
override val operations: List<DocOperation>
@JsonIgnore
get() {
return if (projectCollection != null) {
val operations = mutableListOf<DocOperation>()
operations.addAll(rootCollection.operations.filter { !projectCollection!!.operations.contains(it) })
operations.addAll(projectCollection!!.operations)
operations
} else rootCollection.operations
}
}
| 0
|
Kotlin
|
0
| 1
|
6fe2f1eb2e5db2c3b24eef3dd01a1cadbd2a3d17
| 802
|
summer
|
Apache License 2.0
|
adaptive-ui/adaptive-ui-common/src/commonTest/kotlin/hu/simplexion/adaptive/ui/common/support/RowTest.kt
|
spxbhuhb
| 788,711,010
| false
|
{"Kotlin": 1463989, "Java": 17672, "HTML": 2540, "JavaScript": 970}
|
/*
* Copyright © 2020-2024, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package hu.simplexion.adaptive.ui.common.support
import hu.simplexion.adaptive.ui.common.fragment.row
import hu.simplexion.adaptive.ui.common.fragment.text
import hu.simplexion.adaptive.ui.common.testing.uiTest
import hu.simplexion.adaptive.ui.common.testing.assertEquals
import kotlin.test.Test
class RowTest {
@Test
fun basicRowAsRoot() {
uiTest(0, 0, 400, 400) {
row(Row1) {
text("almafa", Text1) // 6 char = 120f
text("barakcfa", Text2) // 8 char = 160f
}
}.also { adapter ->
adapter.assertEquals<Row1>(0, 0, 400, 400)
adapter.assertEquals<Text1>(0, 0, 120, 20)
adapter.assertEquals<Text2>(0, 120, 160, 20)
}
}
}
| 13
|
Kotlin
|
0
| 0
|
2f97d34731f19163e62da8c578802c2915a48572
| 876
|
adaptive
|
Apache License 2.0
|
app/src/main/java/com/catnip/layoutingexample/model/Category.kt
|
devalrohit
| 774,423,612
| false
|
{"Kotlin": 21023}
|
package com.example.layoutexaple.model
import androidx.annotation.DrawableRes
import java.util.UUID
data class Category (
var id: String = UUID.randomUUID().toString(),
@DrawableRes
var image: Int,
var name: String,
)
| 0
|
Kotlin
|
0
| 1
|
a7d236fbf1b1400ea9acda048a5fd5a3c7a23a76
| 235
|
24001084-km6-izr-FoodApps-ch3
|
MIT License
|
src/main/kotlin/dev/hybridlabs/aquatic/world/gen/feature/FeatureBiomeModifications.kt
|
hybridlabs
| 661,391,321
| false
|
{"Kotlin": 892890, "Java": 69899}
|
package dev.hybridlabs.aquatic.world.gen.feature
import dev.hybridlabs.aquatic.tag.HybridAquaticBiomeTags
import net.fabricmc.fabric.api.biome.v1.BiomeModifications
import net.fabricmc.fabric.api.biome.v1.BiomeSelectors
import net.minecraft.world.gen.GenerationStep
/**
* Applies biome modifications to features when initialised.
*/
object FeatureBiomeModifications {
init {
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.ANEMONE_SPAWN_BIOMES),
GenerationStep.Feature.VEGETAL_DECORATION,
HybridAquaticPlacedFeatures.ANEMONE_PATCH
)
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.GIANT_CLAM_SPAWN_BIOMES),
GenerationStep.Feature.VEGETAL_DECORATION,
HybridAquaticPlacedFeatures.GIANT_CLAM_PATCH
)
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.TUBE_SPONGE_SPAWN_BIOMES),
GenerationStep.Feature.VEGETAL_DECORATION,
HybridAquaticPlacedFeatures.TUBE_SPONGE_PATCH
)
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.MESSAGE_IN_A_BOTTLE_SPAWN_BIOMES),
GenerationStep.Feature.TOP_LAYER_MODIFICATION,
HybridAquaticPlacedFeatures.MESSAGE_IN_A_BOTTLE
)
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.SARGASSUM_SPAWN_BIOMES),
GenerationStep.Feature.VEGETAL_DECORATION,
HybridAquaticPlacedFeatures.SARGASSUM
)
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.DENSE_SARGASSUM_SPAWN_BIOMES),
GenerationStep.Feature.VEGETAL_DECORATION,
HybridAquaticPlacedFeatures.DENSE_SARGASSUM
)
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.FLOATING_SARGASSUM_SPAWN_BIOMES),
GenerationStep.Feature.VEGETAL_DECORATION,
HybridAquaticPlacedFeatures.FLOATING_SARGASSUM
)
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.RED_ALGAE_SPAWN_BIOMES),
GenerationStep.Feature.VEGETAL_DECORATION,
HybridAquaticPlacedFeatures.RED_ALGAE
)
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.RED_ALGAE_MEADOW_SPAWN_BIOMES),
GenerationStep.Feature.VEGETAL_DECORATION,
HybridAquaticPlacedFeatures.RED_ALGAE_MEADOW
)
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.GLOWING_PLANKTON_SPAWN_BIOMES),
GenerationStep.Feature.VEGETAL_DECORATION,
HybridAquaticPlacedFeatures.GLOWING_PLANKTON
)
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.DENSE_KELP_WARM_SPAWN_BIOMES),
GenerationStep.Feature.VEGETAL_DECORATION,
HybridAquaticPlacedFeatures.DENSE_KELP_WARM
)
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.DENSE_KELP_COLD_SPAWN_BIOMES),
GenerationStep.Feature.VEGETAL_DECORATION,
HybridAquaticPlacedFeatures.DENSE_KELP_COLD
)
BiomeModifications.addFeature(
BiomeSelectors.tag(HybridAquaticBiomeTags.THERMAL_VENT_SPAWN_BIOMES),
GenerationStep.Feature.VEGETAL_DECORATION,
HybridAquaticPlacedFeatures.THERMAL_VENT
)
}
}
| 6
|
Kotlin
|
0
| 4
|
82c3b26d6697d2e5666b173101ade38505a3fe4c
| 3,564
|
hybrid-aquatic
|
MIT License
|
src/main/kotlin/com/wrike/sprinter/RunTestsInExistingJvmAction.kt
|
wrike
| 632,906,511
| false
|
{"Kotlin": 94058}
|
package com.wrike.sprinter
import com.intellij.execution.JavaTestConfigurationBase
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
open class RunTestsInExistingJvmAction : AnAction({ "Run in Launched JVM" }, AllIcons.RunConfigurations.TestState.Run_run) {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val context = ConfigurationContext.getFromContext(e.dataContext, e.place)
val sharedJvmExecutorService = project.getService(SharedJvmExecutorService::class.java) ?: return
val testsConfiguration = getConfigurationToRun(context, sharedJvmExecutorService)
if (testsConfiguration != null
&& testsConfiguration is JavaTestConfigurationBase
&& sharedJvmExecutorService.isSupported(testsConfiguration)
) {
sharedJvmExecutorService.executeConfiguration(testsConfiguration, context)
}
}
protected open fun getConfigurationToRun(
context: ConfigurationContext,
sharedJvmExecutorService: SharedJvmExecutorService
): RunConfiguration? {
return when (context.place) {
ActionPlaces.EDITOR_GUTTER_POPUP,
ActionPlaces.EDITOR_POPUP,
ActionPlaces.KEYBOARD_SHORTCUT,
ActionPlaces.MOUSE_SHORTCUT -> context.configuration?.configuration
else -> null
}
}
override fun update(e: AnActionEvent) {
val project = e.project ?: return
val sharedJvmExecutorService = project.getService(SharedJvmExecutorService::class.java) ?: return
val context = ConfigurationContext.getFromContext(e.dataContext, e.place)
val configurationToRun = getConfigurationToRun(context, sharedJvmExecutorService)
val isVisible = configurationToRun != null
&& configurationToRun is JavaTestConfigurationBase
&& sharedJvmExecutorService.isSupported(configurationToRun)
e.presentation.isVisible = isVisible
}
}
| 1
|
Kotlin
|
1
| 9
|
6b8d09afa18b1ef568339b7d872419437b7d4af4
| 2,426
|
sprinter-idea-plugin
|
Apache License 2.0
|
src/main/kotlin/org/freekode/cryptobot/indicatorservice/rest/alert/AlertDTO.kt
|
cryptocurrency-robot
| 327,736,056
| false
| null |
package org.freekode.cryptobot.indicatorservice.rest.alert
import org.freekode.cryptobot.indicatorservice.domain.MarketPair
import org.freekode.cryptobot.indicatorservice.domain.alert.Alert
import org.freekode.cryptobot.indicatorservice.domain.alert.AlertType
import org.freekode.cryptobot.indicatorservice.domain.indicator.IndicatorId
import java.math.BigDecimal
data class AlertDTO(
val id: Int,
val indicatorId: IndicatorId,
val pair: MarketPair,
val type: AlertType,
val value: BigDecimal,
) {
constructor(alert: Alert) : this(alert.id, alert.indicatorId, alert.pair, alert.type, alert.value)
}
| 0
|
Kotlin
|
0
| 0
|
14d98556b56078fac94ed397a159624aa64ced05
| 626
|
indicator-service
|
MIT License
|
shared/src/androidMain/kotlin/com/architect/kmpessentials/connectivity/KmpConnectivity.kt
|
TheArchitect123
| 801,452,364
| false
|
{"Kotlin": 335554, "Ruby": 2253, "Swift": 342}
|
package com.architect.kmpessentials.connectivity
import com.architect.kmpessentials.internal.ActionBoolParams
import dev.tmapps.konnection.Konnection
actual class KmpConnectivity {
actual companion object {
private val konnection = Konnection.instance
actual fun isConnected(): Boolean {
return konnection.isConnected()
}
actual fun getCurrentNetworkName(): String? {
return konnection.getCurrentNetworkConnection()?.name
}
actual suspend fun listenToConnectionChange(connectionState: ActionBoolParams) {
konnection.observeHasConnection().collect { hasConnection ->
connectionState(hasConnection)
}
}
}
}
| 0
|
Kotlin
|
0
| 96
|
3f1e7e14bf7e3da6b20c1d4bf2924ac4571a75b6
| 736
|
KmpEssentials
|
MIT License
|
httpmanager/src/main/java/com/base/library/rxRetrofit/http/httpList/HttpListObserver.kt
|
wkxjc
| 246,898,873
| false
|
{"Java": 100590, "Kotlin": 58568}
|
package com.base.library.rxRetrofit.http.httpList
import android.app.ProgressDialog
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.base.library.rxRetrofit.RxRetrofitApp
import com.base.library.rxRetrofit.http.api.BaseApi
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
/**
* Description:
* HttpList请求结果观察者
*
* @author <NAME>
* Date: 2019-04-25
*/
class HttpListObserver(
private val activity: AppCompatActivity?,
private val fragment: Fragment?,
private val context: Context,
private val resultMap: HashMap<BaseApi, Any>,
private val config: HttpListConfig,
private val listener: HttpListListener
) : Observer<List<Unit>>, DefaultLifecycleObserver {
var loading: ProgressDialog? = null
private var disposable: Disposable? = null
override fun onSubscribe(d: Disposable) {
disposable = d
activity?.lifecycle?.addObserver(this)
fragment?.lifecycle?.addObserver(this)
listener.onSubscribe(d)
showLoadingIfNeed()
}
private fun showLoadingIfNeed() {
if (!config.showLoading || context == RxRetrofitApp.application.applicationContext) return
if (loading == null) {
loading =
ProgressDialog.show(context, null, "Loading", false, config.loadingCancelable) {
disposable?.dispose()
listener.onError(Throwable("request cancel"))
}
} else {
loading?.show()
}
}
override fun onNext(ignore: List<Unit>) {
listener.onNext(resultMap)
}
override fun onError(error: Throwable) {
loading?.dismiss()
listener.onError(error)
}
override fun onComplete() {
loading?.dismiss()
listener.onComplete()
}
override fun onDestroy(owner: LifecycleOwner) {
disposable?.dispose()
super.onDestroy(owner)
}
}
| 1
| null |
1
| 1
|
ccb6e3be80ba985e3c6dff789b2093b6dbe80ee2
| 2,093
|
WanAndroid
|
DOC License
|
src/main/kotlin/de/mackeprm/herdable/Message.kt
|
mackeprm
| 304,402,446
| false
| null |
package de.mackeprm.herdable
interface Message {
}
| 0
|
Kotlin
|
0
| 0
|
5803d4721c062c6d073c6fa056d9dd626bb348b2
| 51
|
herdable
|
MIT License
|
app/src/main/java/com/febrian/whatsappclone/ui/otp/OtpVerifyActivity.kt
|
AndroidProjectCollection
| 490,940,446
| false
| null |
package com.febrian.whatsappclone.ui.otp
import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.febrian.whatsappclone.MainActivity
import com.febrian.whatsappclone.databinding.ActivityOtpVerifyBinding
import com.google.firebase.FirebaseException
import com.google.firebase.FirebaseTooManyRequestsException
import com.google.firebase.auth.*
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import java.util.concurrent.TimeUnit
class OtpVerifyActivity : AppCompatActivity() {
private lateinit var binding: ActivityOtpVerifyBinding
private var verificationId: String? = null
private lateinit var auth: FirebaseAuth
private lateinit var resendToken: PhoneAuthProvider.ForceResendingToken
private lateinit var callbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks
private lateinit var phoneText: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityOtpVerifyBinding.inflate(layoutInflater)
setContentView(binding.root)
auth = FirebaseAuth.getInstance()
phoneText = String.format(
"+62-%s", intent.getStringExtra("phone").toString()
)
binding.tvMobile.text = phoneText
verificationId = intent.getStringExtra("verificationId")
binding.tvResendBtn.setOnClickListener {
resendVerificationCode()
Toast.makeText(this@OtpVerifyActivity, "OTP Send Successfully.", Toast.LENGTH_SHORT)
.show()
}
callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
Log.d(TAG, "onVerificationCompleted:$credential")
}
override fun onVerificationFailed(e: FirebaseException) {
Log.w(TAG, "onVerificationFailed", e)
if (e is FirebaseAuthInvalidCredentialsException) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_SHORT).show()
// Invalid request
} else if (e is FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
Toast.makeText(applicationContext, e.message, Toast.LENGTH_SHORT).show()
}
// Show a message and update the UI
}
override fun onCodeSent(
newVerificationId: String,
token: PhoneAuthProvider.ForceResendingToken
) {
// The SMS verification code has been sent to the provided phone number, we
// now need to ask the user to enter the code and then construct a credential
// by combining the code with a verification ID.
Log.d(TAG, "onCodeSent:$newVerificationId")
// Save verification ID and resending token so we can use them later
verificationId = newVerificationId
resendToken = token
}
}
binding.btnVerify.setOnClickListener {
binding.progressBarVerify.visibility = View.VISIBLE
binding.btnVerify.visibility = View.INVISIBLE
if (binding.code.text.toString().trim().isEmpty()) {
Toast.makeText(applicationContext, "OTP is not Valid!", Toast.LENGTH_SHORT).show()
} else {
if (verificationId != null) {
val code = binding.code.text.toString().trim()
val credential = PhoneAuthProvider.getCredential(verificationId!!, code)
auth
.signInWithCredential(credential)
.addOnCompleteListener {
if (it.isSuccessful) {
binding.progressBarVerify.visibility = View.VISIBLE
binding.btnVerify.visibility = View.INVISIBLE
registerUser()
Toast.makeText(
this@OtpVerifyActivity,
"Welcome...",
Toast.LENGTH_SHORT
).show()
val intent =
Intent(this@OtpVerifyActivity, MainActivity::class.java)
intent.flags =
Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
} else {
binding.progressBarVerify.visibility = View.GONE
binding.btnVerify.visibility = View.VISIBLE
Toast.makeText(
this@OtpVerifyActivity,
"OTP is not Valid!",
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
}
private fun registerUser(){
val user = FirebaseAuth.getInstance().currentUser
if (user != null) {
val mUserDB = FirebaseDatabase.getInstance().reference.child("user").child(user.uid)
mUserDB.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (!dataSnapshot.exists()) {
val userMap: MutableMap<String, Any?> = HashMap()
userMap["phone"] = user.phoneNumber
userMap["name"] = user.phoneNumber
mUserDB.updateChildren(userMap)
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
}
private fun resendVerificationCode(
) {
val optionsBuilder = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(
phoneText
) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
optionsBuilder.setForceResendingToken(resendToken)
PhoneAuthProvider.verifyPhoneNumber(optionsBuilder.build())
}
}
| 0
|
Kotlin
|
0
| 0
|
495bda945ab70338ca0ba4c730dc0845d6198530
| 6,935
|
WhatsAppClone
|
MIT License
|
FundametalAndroid24/app/src/main/java/com/byandev/fundametalandroid24/MainActivity.kt
|
byansanur
| 259,883,301
| false
| null |
package com.byandev.fundametalandroid24
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.byandev.fundametalandroid24.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var adapter: WeatherAdapter
private lateinit var binding: ActivityMainBinding
private lateinit var mainViewModel: ActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// viewBinding use
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.getRoot())
// Menghubungkan viewModel dengan activity
mainViewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory())
.get(ActivityViewModel::class.java)
// penghubung class adapter dengan activity untuk interaksi dengan recyclerView
adapter = WeatherAdapter()
adapter.notifyDataSetChanged()
// pemanggilan id dengan viewBinding
listener()
}
private fun listener() {
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = adapter
binding.btnCity.setOnClickListener{
// validasi isian editText
val city = binding.editCity.text.toString()
if (city.isEmpty()) return@setOnClickListener
// setelah validasi show progressBar
showLoading(true)
// interaksi dengan function pada viewModel
mainViewModel.setWeather(city)
}
// Subscribe untuk mendapatkan value dari LiveData yang ada pada kelas viewModel
mainViewModel.getWeathers()
.observe(this, Observer {
if (it != null) {
adapter.setData(it)
showLoading(false)
}
})
}
private fun showLoading(state: Boolean) {
if (state) binding.progressBar.visibility = View.VISIBLE
else binding.progressBar.visibility = View.GONE
}
// sebelum menggunakan viewModel
/*
private fun setWeather(city: String) {
val listItems = ArrayList<WeatherItems>()
val apiKey = getString(R.string.APP_ID)
val url = "https://api.openweathermap.org/data/2.5/group?id=$city&units=metric&appid=${apiKey}"
val client = AsyncHttpClient()
client.get(url, object : AsyncHttpResponseHandler() {
override fun onSuccess(
statusCode: Int,
headers: Array<out Header>,
responseBody: ByteArray
) {
try {
//parsing json
val result = String(responseBody)
val responseObject = JSONObject(result)
val list = responseObject.getJSONArray("list")
for (i in 0 until list.length()) {
val weather = list.getJSONObject(i)
weatherItems.id = weather.getInt("id")
weatherItems.name = weather.getString("name")
weatherItems.currentWeather = weather.getJSONArray("weather").getJSONObject(0).getString("main")
weatherItems.description = weather.getJSONArray("weather").getJSONObject(0).getString("description")
val tempInKelvin = weather.getJSONObject("main").getDouble("temp")
val tempInCelsius = tempInKelvin - 273
weatherItems.temperature = DecimalFormat("##.##").format(tempInCelsius)
listItems.add(weatherItems)
}
//set data ke adapter
adapter.setData(listItems)
showLoading(false)
} catch (e: Exception) {
Log.d("Exception", e.message.toString())
}
}
override fun onFailure(
statusCode: Int,
headers: Array<out Header>,
responseBody: ByteArray,
error: Throwable
) {
Log.d("onFailure", error.message.toString())
}
})
}
*/
}
| 0
|
Kotlin
|
0
| 1
|
b678e1bbeab400e25aafced5c65abffd139e249d
| 4,415
|
Android-Fundamental
|
MIT License
|
app/src/main/kotlin/com/fernandocejas/sample/core/di/ApplicationModule.kt
|
mohamedmenasy
| 199,511,290
| true
|
{"Kotlin": 98100}
|
/**
* Copyright (C) 2019 <NAME> Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fernandocejas.sample.core.di
import com.fernandocejas.sample.BuildConfig
import com.fernandocejas.sample.core.navigation.Navigator
import com.fernandocejas.sample.core.platform.NetworkHandler
import com.fernandocejas.sample.features.login.Authenticator
import com.fernandocejas.sample.features.movies.data.remote.MoviesRepository
import com.fernandocejas.sample.features.movies.data.remote.MoviesService
import com.fernandocejas.sample.features.movies.usecase.GetMovieDetails
import com.fernandocejas.sample.features.movies.usecase.GetMovies
import com.fernandocejas.sample.features.movies.usecase.PlayMovie
import com.fernandocejas.sample.features.movies.view.MovieDetailsAnimator
import com.fernandocejas.sample.features.movies.view.MoviesAdapter
import com.fernandocejas.sample.features.movies.viewmodel.MovieDetailsViewModel
import com.fernandocejas.sample.features.movies.viewmodel.MoviesViewModel
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
val applicationModule = module {
single {
Retrofit.Builder()
.baseUrl(
"https://raw.githubusercontent.com/android10/Sample-Data/master/Android-CleanArchitecture-Kotlin/"
)
.client(get())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
single {
val okHttpClientBuilder: OkHttpClient.Builder = OkHttpClient.Builder()
if (BuildConfig.DEBUG) {
val loggingInterceptor = HttpLoggingInterceptor().setLevel(
HttpLoggingInterceptor.Level.BASIC
)
okHttpClientBuilder.addInterceptor(loggingInterceptor)
}
okHttpClientBuilder.build() as OkHttpClient
}
factory { NetworkHandler(get()) }
factory { MoviesService(get()) }
single { Navigator(get()) }
}
val loginModule = module {
single { Authenticator() }
}
val moviesModule = module {
single { MoviesRepository.Network(get(), get()) as MoviesRepository }
single { GetMovieDetails(get()) }
single { GetMovies(get()) }
single { PlayMovie(get(), get()) }
single { MoviesAdapter() }
factory { MovieDetailsAnimator() }
viewModel { MovieDetailsViewModel(get(), get()) }
viewModel { MoviesViewModel(get()) }
}
| 0
|
Kotlin
|
0
| 5
|
6a7479a0c30436e223568a9964775bb21bc466a8
| 2,953
|
Android-CleanArchitecture-Kotlin
|
Apache License 2.0
|
app/src/main/java/arira/co/id/mesinatrian/helper/HelperToast.kt
|
ramcona
| 295,104,924
| false
| null |
package arira.co.id.mesinatrian.helper
import android.content.Context
import android.widget.Toast
open class HelperToast {
fun show(msg: String, context: Context){
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
}
}
| 0
|
Kotlin
|
0
| 0
|
ed95c8b13f6e2aa2a64087b08719ca16b7cdb08c
| 241
|
mesin-antrian
|
Apache License 2.0
|
aquasketch-frontend/src/main/java/com/github/perseacado/aquasketch/frontend/user/CustomUserDetails.kt
|
perseacado
| 62,453,004
| false
|
{"HTML": 23565, "JavaScript": 22138, "Kotlin": 18589}
|
package com.github.perseacado.aquasketch.frontend.user
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.User
/**
* @author <NAME>, 09.07.16.
*/
class CustomUserDetails(
val id: String,
username: String?,
authorities: MutableCollection<out GrantedAuthority>?) : User(username, "N/A", authorities)
| 5
|
HTML
|
0
| 1
|
9c171078a8619f9019b675c382442f1f63b273be
| 373
|
aquasketch
|
MIT License
|
app/src/main/java/ru/ilyasekunov/officeapp/data/datasource/PostsDataSource.kt
|
IlyaSekunov
| 744,587,168
| false
|
{"Kotlin": 671010}
|
package ru.ilyasekunov.officeapp.data.datasource
import androidx.annotation.IntRange
import ru.ilyasekunov.officeapp.data.dto.EditPostDto
import ru.ilyasekunov.officeapp.data.dto.PublishPostDto
import ru.ilyasekunov.officeapp.data.dto.SearchPostsDto
import ru.ilyasekunov.officeapp.data.model.Filters
import ru.ilyasekunov.officeapp.data.model.IdeaPost
interface PostsDataSource {
suspend fun publishPost(post: PublishPostDto): Result<Unit>
suspend fun findPostById(postId: Long): Result<IdeaPost>
suspend fun posts(
searchPostsDto: SearchPostsDto,
@IntRange(from = 1)
page: Int,
@IntRange(from = 1)
pageSize: Int
): Result<List<IdeaPost>>
suspend fun favouritePosts(
searchPostsDto: SearchPostsDto,
@IntRange(from = 1)
page: Int,
@IntRange(from = 1)
pageSize: Int
): Result<List<IdeaPost>>
suspend fun postsByAuthorId(
authorId: Long,
@IntRange(from = 1)
page: Int,
@IntRange(from = 1)
pageSize: Int
): Result<List<IdeaPost>>
suspend fun suggestedIdeas(
@IntRange(from = 1)
page: Int,
@IntRange(from = 1)
pageSize: Int
): Result<List<IdeaPost>>
suspend fun ideasInProgress(
@IntRange(from = 1)
page: Int,
@IntRange(from = 1)
pageSize: Int
): Result<List<IdeaPost>>
suspend fun implementedIdeas(
@IntRange(from = 1)
page: Int,
@IntRange(from = 1)
pageSize: Int
): Result<List<IdeaPost>>
suspend fun myIdeas(
@IntRange(from = 1) page: Int,
@IntRange(from = 1) pageSize: Int
): Result<List<IdeaPost>>
suspend fun editPostById(
postId: Long,
editedPost: EditPostDto
): Result<Unit>
suspend fun deletePostById(postId: Long): Result<Unit>
suspend fun pressLike(postId: Long): Result<Unit>
suspend fun removeLike(postId: Long): Result<Unit>
suspend fun pressDislike(postId: Long): Result<Unit>
suspend fun removeDislike(postId: Long): Result<Unit>
suspend fun filters(): Result<Filters>
suspend fun suggestIdeaToMyOffice(postId: Long): Result<Unit>
}
| 0
|
Kotlin
|
0
| 2
|
31175ebc80c04b0ccb40644229a2ea3cd223ee3c
| 2,202
|
office-app
|
Apache License 2.0
|
reflekt-plugin/src/test/resources/org/jetbrains/reflekt/plugin/compiler/code-gen/general-standalone-project-calling/reflekt/functions/functions-1.kt
|
JetBrains-Research
| 293,503,377
| false
|
{"Kotlin": 397259, "Java": 35379}
|
// FILE: TestCase.kt
import org.jetbrains.reflekt.Reflekt
import org.jetbrains.reflekt.test.helpers.checkFunctionsCallResult
fun box(): String = checkFunctionsCallResult(
{ Reflekt.functions().withAnnotations<() -> Unit>().toList() },
listOf("fun foo1(): kotlin.Unit", "fun foo2(): kotlin.Unit", "fun foo4(): kotlin.Unit")
)
| 13
|
Kotlin
|
9
| 325
|
ae53618880e5eb610ddeb2792d63208eade951a8
| 334
|
reflekt
|
Apache License 2.0
|
src/test/kotlin/com/tyro/oss/rabbit_amazon_bridge/logging/LogbackStructuredLogLayoutTest.kt
|
rajeshgpai
| 159,911,792
| true
|
{"Kotlin": 140497, "Shell": 4213, "Makefile": 816}
|
/*
* Copyright [2018] Tyro Payments Limited.
*
* 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.tyro.oss.rabbit_amazon_bridge.logging
import ch.qos.logback.classic.Level
import ch.qos.logback.classic.LoggerContext
import ch.qos.logback.classic.spi.LoggingEvent
import com.google.gson.Gson
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import java.lang.RuntimeException
class LogbackStructuredLogLayoutTest {
private lateinit var layout: LogbackStructuredLogLayout
@Before
fun setUp() {
layout = LogbackStructuredLogLayout()
layout.artifactId = "rabbit-amazon-bridge"
layout.artifactVersion = "1.0.0"
}
@Test
fun shouldLayoutMessagesAsJson() {
val logger = LoggerContext().getLogger("test-logger")
val event = LoggingEvent(null, logger, Level.INFO, "test", null, null)
val message = layout.doLayout(event)
val logEvent = Gson().fromJson(message, LogbackStructuredLogLayout.LogEventEnvelope::class.java)
assertThat(logEvent.artifactId).isEqualTo(layout.artifactId)
assertThat(logEvent.artifactVersion).isEqualTo(layout.artifactVersion)
assertThat(logEvent.logType).isEqualTo("moneyswitch")
assertThat(logEvent.syslogFormat).isEqualTo("tyro-app-scrubbed")
assertThat(logEvent.timestamp).isNotBlank()
assertThat(logEvent.event).isEqualTo("test")
assertThat(logEvent.logLevel).isEqualTo(Level.INFO.levelStr)
}
@Test
fun shouldLayoutMessagesWithExceptionsAsJson() {
val logger = LoggerContext().getLogger("test-logger")
val runtimeException = RuntimeException("message")
val event = LoggingEvent(null, logger, Level.ERROR, "test", runtimeException, null)
val message = layout.doLayout(event)
val logEvent = Gson().fromJson(message, LogbackStructuredLogLayout.LogErrorEventEnvelope::class.java)
assertThat(logEvent.artifactId).isEqualTo(layout.artifactId)
assertThat(logEvent.artifactVersion).isEqualTo(layout.artifactVersion)
assertThat(logEvent.logType).isEqualTo("moneyswitch")
assertThat(logEvent.syslogFormat).isEqualTo("tyro-app-scrubbed")
assertThat(logEvent.timestamp).isNotBlank()
assertThat(logEvent.event).isEqualTo("test")
assertThat(logEvent.logLevel).isEqualTo(Level.ERROR.levelStr)
assertThat(logEvent.exception.exception_message).isEqualTo("message")
assertThat(logEvent.exception.exception_class).isEqualTo(RuntimeException::class.java.name)
assertThat(logEvent.exception.stacktrace).isEqualTo(runtimeException.stackTrace.joinToString { it.toString() + "\n" })
}
}
| 0
|
Kotlin
|
0
| 0
|
bbe687d144f298800d4cc6a9da8618d2bfdbf419
| 3,240
|
rabbit-amazon-bridge
|
Apache License 2.0
|
UIKit/src/main/java/com/nativeboys/uikit/fragments/FragmentDialogListener.kt
|
EvangelosBoudis
| 347,924,640
| false
| null |
package com.nativeboys.uikit.fragments
import android.view.View
import androidx.fragment.app.DialogFragment
interface FragmentDialogListener {
fun onClick(dialogFragment: DialogFragment, view: View)
}
| 0
|
Kotlin
|
0
| 0
|
b392cf151d1967b6dc5d56fef6f5f0bfaaa7fb07
| 206
|
digital-bit-security
|
Apache License 2.0
|
src/behaivorDesignPattern/chainOfResponsibility/main.kt
|
dja1369
| 807,056,411
| false
|
{"Kotlin": 5894}
|
package src.behaivorDesignPattern.chainOfResponsibility
fun main() {
val devHandler = DevHandler()
val pmHandler = PmHandler()
val designHandler = DesignHandler()
var query = "Design"
devHandler.setNext(pmHandler).setNext(designHandler)
println(devHandler.handle(query))
println("=====================================")
query = "PM"
println(devHandler.handle(query))
println("=====================================")
query = "Missing"
println(devHandler.handle(query))
}
| 0
|
Kotlin
|
0
| 0
|
a04c9adc8ba8dd362e6220a4abff7c8db3e11a7b
| 518
|
aboutDesignPattern
|
MIT License
|
p2m-core/src/main/java/com/p2m/core/module/task/TaskUnit.kt
|
wangdaqi77
| 367,279,479
| false
| null |
package com.p2m.core.module.task
/**
* Task unit of a task, can add some dependency.
*/
interface TaskUnit {
fun getOwnerClass(): Class<out Task<*, *>>
/**
* Add the given dependency to this task.
*
* @param taskClass The dependency to add to this task.
*/
fun dependOn(taskClass: Class<out Task<*, *>>): TaskUnit
/**
* Adds the given dependencies to this task.
*
* @param taskClass The dependencies to add to this task.
*/
fun dependOn(vararg taskClass: Class<out Task<*, *>>): TaskUnit
fun getDependencies(): Set<Class<out Task<*, *>>>
}
| 0
|
Kotlin
|
6
| 34
|
6263c1c5a2dedda773eb7c6745b86ac2ff8f00d9
| 620
|
P2M
|
Apache License 2.0
|
mockzilla-management-ui/src/commonMain/kotlin/com/apadmi/mockzilla/desktop/ui/widgets/deviceconnection/DeviceConnectionWidget.kt
|
Apadmi-Engineering
| 570,496,992
| false
|
{"Kotlin": 481322, "Dart": 132393, "Swift": 47059, "Ruby": 12855, "Objective-C": 76}
|
package com.apadmi.mockzilla.desktop.ui.widgets.deviceconnection
import androidx.compose.animation.AnimatedContent
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
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.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.apadmi.mockzilla.desktop.di.utils.getViewModel
import com.apadmi.mockzilla.desktop.engine.connection.DetectedDevice
import com.apadmi.mockzilla.desktop.i18n.LocalStrings
import com.apadmi.mockzilla.desktop.i18n.Strings
import com.apadmi.mockzilla.desktop.ui.components.StandardTextTooltip
import com.apadmi.mockzilla.desktop.ui.theme.alternatingBackground
import com.apadmi.mockzilla.desktop.ui.widgets.deviceconnection.DeviceConnectionViewModel.State
import com.apadmi.mockzilla.desktop.utils.Platform
import com.apadmi.mockzilla_management_ui.generated.resources.Res
import com.apadmi.mockzilla_management_ui.generated.resources.mockzilla_logo
import org.jetbrains.compose.resources.painterResource
private fun DetectedDevice.State.toolTipText(strings: Strings) = when (this) {
DetectedDevice.State.NotYourSimulator -> strings.widgets.deviceConnection.tooltips.notYourSimulator
DetectedDevice.State.ReadyToConnect -> strings.widgets.deviceConnection.tooltips.readyToConnect
DetectedDevice.State.Removed -> strings.widgets.deviceConnection.tooltips.removed
DetectedDevice.State.Resolving -> strings.widgets.deviceConnection.tooltips.resolving
}
private fun DetectedDevice.State.color() = when (this) {
DetectedDevice.State.ReadyToConnect -> Color.Green
DetectedDevice.State.Removed,
DetectedDevice.State.NotYourSimulator -> Color.Red
DetectedDevice.State.Resolving -> Color.Gray
}
@Composable
fun DeviceConnectionWidget() {
val viewModel = getViewModel<DeviceConnectionViewModel>()
val state by viewModel.state.collectAsState()
DeviceConnectionContent(state, viewModel::onIpAndPortChanged, viewModel::connectToDevice)
}
@Composable
fun DeviceConnectionContent(
state: State,
onIpAndPortChanged: (String) -> Unit,
onTapDevice: (DetectedDevice) -> Unit,
strings: Strings = LocalStrings.current,
) = Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(
modifier = Modifier
.widthIn(max = 500.dp)
.padding(top = 100.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Image(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(vertical = 16.dp)
.height(100.dp),
painter = painterResource(Res.drawable.mockzilla_logo),
contentDescription = null
)
Text(
text = strings.widgets.deviceConnection.heading,
style = MaterialTheme.typography.headlineLarge
)
TextField(
modifier = Modifier.fillMaxWidth(),
value = state.ipAndPort,
onValueChange = onIpAndPortChanged,
singleLine = true,
label = { Text(strings.widgets.deviceConnection.ipInputLabel) }
)
Spacer(Modifier.height(4.dp))
if (Platform.current == Platform.Android) {
Button(onClick = { onIpAndPortChanged("127.0.0.1:8080") }) {
Text(strings.widgets.deviceConnection.androidDevConnectButton)
}
}
AnimatedContent(
targetState = state.hasDevices
) {
if (it) {
DevicesList(
devices = state.devices,
onTapDevice = onTapDevice
)
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun DevicesList(
devices: List<DetectedDevice>,
onTapDevice: (DetectedDevice) -> Unit,
strings: Strings = LocalStrings.current,
) = LazyColumn {
item {
Column(
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = strings.widgets.deviceConnection.autoConnectHeading,
style = MaterialTheme.typography.headlineLarge
)
Text(
text = strings.widgets.deviceConnection.autoConnectSubHeading,
style = MaterialTheme.typography.bodySmall
)
Spacer(Modifier.height(8.dp))
}
}
itemsIndexed(devices, key = { _, device -> device.connectionName }) { index, device ->
Row(
modifier = Modifier.animateItemPlacement().alternatingBackground(index).fillMaxWidth()
.padding(start = 16.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
StandardTextTooltip(text = device.state.toolTipText(strings)) {
Canvas(
modifier = Modifier.padding(end = 16.dp).size(12.dp),
onDraw = { drawCircle(color = device.state.color()) })
}
Column(
verticalArrangement = Arrangement.spacedBy(2.dp),
modifier = Modifier.weight(1f).padding(end = 8.dp)
) {
Text(device.prettyName(), maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
modifier = Modifier.alpha(0.5f),
text = buildString {
device.metaData?.appName?.also {
append(device.metaData.appName)
append(" | ")
}
append("${device.hostAddress}:${device.port}")
},
style = MaterialTheme.typography.bodySmall,
)
}
if (device.state == DetectedDevice.State.Resolving) {
CircularProgressIndicator(Modifier.padding(end = 8.dp).size(20.dp))
} else {
Button(onClick = { onTapDevice(device) }) {
Text(strings.widgets.deviceConnection.autoConnectButton)
}
}
}
}
}
| 18
|
Kotlin
|
8
| 29
|
89c3ba7b6a4f4eed2c0866c917ca8b6d7e8596ae
| 6,835
|
Mockzilla
|
MIT License
|
src/main/kotlin/no/nav/tema_tiltak/tiltak_auditlogger/App.kt
|
navikt
| 680,103,929
| false
| null |
package no.nav.tema_tiltak.tiltak_auditlogger
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import mu.KotlinLogging
import no.nav.tema_tiltak.tiltak_auditlogger.kafka.AuditHendelseConsumer
import no.nav.tema_tiltak.tiltak_auditlogger.kafka.consumerConfig
import org.apache.kafka.clients.consumer.Consumer
import org.apache.kafka.clients.consumer.KafkaConsumer
import java.io.Closeable
class App(private val auditHendelseConsumer: AuditHendelseConsumer) : Closeable {
private val logger = KotlinLogging.logger {}
private val server = embeddedServer(Netty, port = 8092) {
routing {
get("/internal/isAlive") { call.respond(HttpStatusCode.OK) }
get("/internal/isReady") { call.respond(HttpStatusCode.OK) }
}
}
fun start() {
logger.info("Starter applikasjon :)")
server.start()
auditHendelseConsumer.start()
}
override fun close() {
logger.info("Stopper app")
server.stop(0, 0)
}
}
fun main() {
// Setup kafka and database
val consumer: Consumer<String, String> = KafkaConsumer(consumerConfig())
val auditHendelseConsumer = AuditHendelseConsumer(consumer)
App(auditHendelseConsumer).start()
}
| 0
|
Kotlin
|
0
| 0
|
580b8cf882362dc87ad86831cf30decb089a0033
| 1,356
|
tiltak-auditlogger
|
MIT License
|
src/main/kotlin/de/tweerlei/plumber/worker/impl/csv/CsvWriteWorker.kt
|
tweerlei
| 450,150,451
| false
|
{"Kotlin": 908232, "Shell": 2267, "Dockerfile": 639}
|
/*
* Copyright 2022 <NAME> + Buchmeier GbR - http://www.tweerlei.de/
*
* 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 de.tweerlei.plumber.worker.impl.csv
import com.fasterxml.jackson.databind.SequenceWriter
import com.fasterxml.jackson.dataformat.csv.CsvMapper
import com.fasterxml.jackson.dataformat.csv.CsvSchema
import de.tweerlei.plumber.worker.OutputStreamProvider
import de.tweerlei.plumber.worker.WorkItem
import de.tweerlei.plumber.worker.Worker
import de.tweerlei.plumber.worker.impl.DelegatingWorker
import de.tweerlei.plumber.worker.impl.WellKnownKeys
import de.tweerlei.plumber.worker.types.Record
import java.io.Closeable
import java.io.OutputStream
class CsvWriteWorker(
private val outputStreamProvider: OutputStreamProvider,
private val csvMapper: CsvMapper,
private val separator: Char,
private val header: Boolean,
worker: Worker
): DelegatingWorker(worker) {
private lateinit var stream: OutputStream
private var writer: RecordWriter<Record, out Any>? = null
override fun onOpen() {
stream = outputStreamProvider.open()
}
override fun doProcess(item: WorkItem): Boolean =
item.getFirst(WellKnownKeys.RECORD)
.toRecord()
.let { obj ->
writerFor(obj).write(obj)
}.let { true }
private fun writerFor(rec: Record) =
when (val w = writer) {
null -> createWriter(rec).also { writer = it }
else -> w
}
private fun createWriter(rec: Record) =
when (header) {
true -> writerWithHeader(rec)
false -> writerWithoutHeader(rec)
}
override fun onClose() {
when (writer) {
null -> stream.close()
else -> writer?.close()
}
}
private fun writerWithHeader(rec: Record) =
RecordWriter<Record, Iterable<Any>>(csvMapper
.writerFor(Iterable::class.java)
// See https://github.com/FasterXML/jackson-dataformats-text/issues/10
// withNullValue() does not apply to arrays and collections
.with(rec.toFormatSchema().withColumnSeparator(separator).withHeader())
.writeValues(stream)) {
it.toAny().values.mapNullTo("null")
}
private fun writerWithoutHeader(rec: Record) =
RecordWriter<Record, Iterable<Any>>(csvMapper
.writerFor(Iterable::class.java)
// See https://github.com/FasterXML/jackson-dataformats-text/issues/10
// withNullValue() does not apply to arrays and collections
.with(rec.toFormatSchema().withColumnSeparator(separator))
.writeValues(stream)) {
it.toAny().values.mapNullTo("null")
}
private fun Record.toFormatSchema() =
CsvSchema.Builder().also { builder ->
toAny().forEach { (k, _) -> builder.addColumn(k) }
}.build()
private class RecordWriter<T, U>(
val writer: SequenceWriter,
val mapper: (T) -> U
) : Closeable {
fun write(value: T) {
writer.write(mapper(value))
}
override fun close() {
writer.close()
}
}
}
| 0
|
Kotlin
|
0
| 2
|
ea5ec4d291f6a4a17dc507378e368d6216605926
| 3,745
|
plumber
|
Apache License 2.0
|
app/src/main/java/com/transfers/transfertracker/view/dashboard/TeamsComponent.kt
|
Josephhowerton
| 527,618,192
| false
| null |
package com.transfers.transfertracker.view.components
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ChainStyle
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.skydoves.landscapist.glide.GlideImage
import com.transfers.transfertracker.R
import com.transfers.transfertracker.model.teams.Team
import com.transfers.transfertracker.view.dashboard.DashboardViewModel
import com.transfers.transfertracker.view.dashboard.GetStartedItem
import com.transfers.transfertracker.view.theme.CardBackgroundColor
import com.transfers.transfertracker.view.theme.HyperLinkBlue
import com.transfers.transfertracker.view.theme.TransferTrackerTheme
@Preview(showBackground = true)
@Composable
fun TeamsComponentScreenPreview() {
TeamsComponentScreen(Modifier)
}
@Composable
fun TeamsComponentScreen(modifier: Modifier) = TransferTrackerTheme {
Card(shape = RoundedCornerShape(2),
modifier = modifier
.fillMaxWidth()
.height(450.dp)
) {
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (descriptionText,
addATeamText,
selectedTeam,
selectedTeamImage,
secondTeam,
thirdTeam,
fourthTeam,
fifthTeam
) = createRefs()
Image(painter = painterResource(id = R.drawable.ic_baseline_sports_soccer_24),
contentDescription = "",
modifier = Modifier
.size(36.dp)
.padding(end = 2.dp)
.constrainAs(selectedTeamImage) {
start.linkTo(parent.start)
top.linkTo(selectedTeam.top)
bottom.linkTo(selectedTeam.bottom)
end.linkTo(selectedTeam.start)
}
)
Text(text = "PlaceHolderText",
fontSize = 32.sp,
modifier = Modifier
.padding(start = 2.dp)
.constrainAs(selectedTeam) {
top.linkTo(parent.top, 5.dp)
end.linkTo(parent.end)
start.linkTo(selectedTeamImage.end)
}
)
createHorizontalChain(selectedTeamImage, selectedTeam, chainStyle = ChainStyle.Packed)
Text(text = "Select a team below to change data.",
modifier = Modifier.constrainAs(descriptionText) {
end.linkTo(parent.end)
start.linkTo(parent.start)
top.linkTo(selectedTeam.bottom, 5.dp)
}
)
TeamItem(
teamName = "Team 1",
crestUrl = "",
modifier = Modifier
.padding(10.dp)
.wrapContentSize()
.constrainAs(secondTeam) {
top.linkTo(descriptionText.bottom)
bottom.linkTo(thirdTeam.top)
}
)
TeamItem(
teamName = "Team 2",
crestUrl = "",
modifier = Modifier
.padding(10.dp)
.wrapContentSize()
.constrainAs(thirdTeam) {
top.linkTo(secondTeam.bottom)
bottom.linkTo(fourthTeam.top)
}
)
TeamItem(
teamName = "Team 3",
crestUrl = "",
modifier = Modifier
.padding(10.dp)
.wrapContentSize()
.constrainAs(fourthTeam) {
top.linkTo(thirdTeam.bottom)
bottom.linkTo(fifthTeam.top)
}
)
TeamItem(
teamName = "Team 4",
crestUrl = "",
modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
.constrainAs(fifthTeam) {
top.linkTo(fourthTeam.bottom)
bottom.linkTo(addATeamText.top)
}
)
ClickableText(onClick = {}, text = AnnotatedString("Add Team"),
style = TextStyle(
color = Color.Blue,
fontSize = 20.sp
),
modifier = Modifier
.padding(15.dp)
.constrainAs(addATeamText) {
end.linkTo(parent.end)
bottom.linkTo(parent.bottom)
}
)
}
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun TeamsComponent(viewModel: DashboardViewModel, modifier: Modifier) = TransferTrackerTheme {
Card(shape = RoundedCornerShape(2),
modifier = modifier
.fillMaxWidth()
.height(450.dp)
) {
val currentTeam = remember {
viewModel.selectedTeam
}
val teams = remember {
viewModel.usersTeams
}
val addTeamVisibility = remember {
viewModel.shouldShowAddTeamButton
}
val currentTeamBitmap = currentTeam.value?.logo
val logo = if(currentTeamBitmap.isNullOrEmpty())
R.drawable.ic_baseline_sports_soccer_24
else
currentTeamBitmap
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (
descriptionText,
addATeamText,
selectedTeam,
selectedTeamImage,
teamsList,
) = createRefs()
GlideImage(imageModel = logo,
contentDescription = "",
modifier = Modifier
.size(36.dp)
.padding(end = 2.dp)
.constrainAs(selectedTeamImage) {
start.linkTo(parent.start)
top.linkTo(selectedTeam.top)
bottom.linkTo(selectedTeam.bottom)
end.linkTo(selectedTeam.start)
}
)
val currentTeamName = currentTeam?.value?.name ?: "Not Provided"
Text(text = currentTeamName,
fontSize = 32.sp,
modifier = Modifier
.padding(start = 2.dp)
.constrainAs(selectedTeam) {
top.linkTo(parent.top, 5.dp)
end.linkTo(parent.end)
start.linkTo(selectedTeamImage.end)
}
)
createHorizontalChain(selectedTeamImage, selectedTeam, chainStyle = ChainStyle.Packed)
Text(text = "Select a team below to change data.",
modifier = Modifier.constrainAs(descriptionText) {
end.linkTo(parent.end)
start.linkTo(parent.start)
top.linkTo(selectedTeam.bottom, 5.dp)
}
)
if(teams.isEmpty()){
GetStartedItem("Select A Team\n\nTo Get Started", Modifier
.padding(top = 20.dp, bottom = 40.dp)
.constrainAs(teamsList) {
top.linkTo(descriptionText.bottom)
bottom.linkTo(parent.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
})
}else {
LazyColumn(verticalArrangement = Arrangement.spacedBy(15.dp),
modifier = Modifier
.padding(top = 20.dp, bottom = 20.dp)
.constrainAs(teamsList) {
height = Dimension.fillToConstraints
top.linkTo(descriptionText.bottom)
bottom.linkTo(parent.bottom)
}) {
items(teams) { team ->
val dismissState = rememberDismissState(
confirmStateChange = {
if (it == DismissValue.DismissedToEnd || it == DismissValue.DismissedToStart) {
viewModel.removeSelectedTeam(team)
}
true
}
)
SwipeToDismiss(
state = dismissState,
directions = setOf(DismissDirection.EndToStart),
dismissThresholds = { FractionalThreshold(0.2f) },
background = {
val alignment = Alignment.CenterEnd
val color by animateColorAsState(targetValue = Color.Red)
val icon = Icons.Default.Delete
val scale by animateFloatAsState(
targetValue =
if (dismissState.targetValue == DismissValue.Default)
0.8f
else
1.2f
)
Card(
shape = RoundedCornerShape(5.dp),
modifier = Modifier.fillMaxWidth()
.fillParentMaxHeight()
) {
Box(
contentAlignment = alignment,
modifier = Modifier.fillMaxWidth()
.background(color)
.padding(start = 12.dp, end = 12.dp)
) {
Icon(
icon,
contentDescription = "Icon",
modifier = Modifier.scale(scale)
)
}
}
},
dismissContent = {
TeamItem(
viewModel = viewModel,
dismissState = dismissState,
team = team,
modifier = Modifier
.wrapContentSize()
)
}
)
}
}
}
AddMoreClickableText(viewModel, isVisible = addTeamVisibility.value,
Modifier.constrainAs(addATeamText) {
end.linkTo(parent.end)
bottom.linkTo(parent.bottom)
}
)
}
}
}
@Composable
fun AddMoreClickableText(viewModel: DashboardViewModel, isVisible: Boolean, modifier: Modifier) {
if (isVisible) {
ClickableText(
onClick = { viewModel.navigateToAddTeam() }, text = AnnotatedString("Add Team"),
style = TextStyle(
color = HyperLinkBlue,
fontSize = 20.sp
),
modifier = modifier
.padding(15.dp)
)
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun TeamItem(
viewModel: DashboardViewModel,
team: Team,
dismissState: DismissState,
modifier: Modifier
) =
Card(backgroundColor = CardBackgroundColor,
elevation = animateDpAsState(
targetValue =
if (dismissState.dismissDirection != null)
5.dp
else
0.dp
).value,
modifier = modifier,
onClick = { viewModel.updateCurrentTeam(team) }) {
ConstraintLayout(
modifier = Modifier
.fillMaxWidth()
) {
val (crest, name) = createRefs()
GlideImage(imageModel = team.logo,
contentScale = ContentScale.Fit,
contentDescription = "",
modifier = Modifier
.padding(start = 5.dp)
.size(36.dp)
.constrainAs(crest) {
start.linkTo(parent.start)
top.linkTo(name.top)
bottom.linkTo(name.bottom)
}
)
val teamName = team.name ?: "Not Provided"
Text(text = teamName,
fontSize = 24.sp,
modifier = Modifier
.padding(end = 5.dp, start = 7.dp, top = 15.dp, bottom = 15.dp)
.constrainAs(name) {
start.linkTo(crest.end)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
}
)
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun TeamItem(teamName: String, crestUrl: String, modifier: Modifier) =
Card(elevation = 0.dp, modifier = modifier, onClick = { }) {
ConstraintLayout(
modifier = Modifier
.fillMaxWidth()
) {
val (crest, name) = createRefs()
Image(painter = painterResource(id = R.drawable.ic_baseline_sports_soccer_24),
contentDescription = "",
modifier = Modifier
.padding(end = 5.dp, start = 5.dp, top = 15.dp, bottom = 15.dp)
.constrainAs(crest) {
start.linkTo(parent.start)
top.linkTo(name.top)
bottom.linkTo(name.bottom)
}
)
Text(text = teamName,
fontSize = 24.sp,
modifier = Modifier
.padding(end = 5.dp, start = 5.dp, top = 15.dp, bottom = 15.dp)
.constrainAs(name) {
top.linkTo(parent.top)
start.linkTo(crest.end)
}
)
}
}
| 0
|
Kotlin
|
0
| 0
|
3f81d1bb6b2e36587f5b599ba4b1c4a0a415d7d7
| 15,638
|
transfer-app
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/com/example/bleapplication/utils/BluetoothUtils.kt
|
ChandanJana
| 556,605,890
| false
| null |
package com.example.bleapplication.utils
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothGattService
import com.example.bleapplication.Constants.CHARACTERISTIC_ECHO_STRING
import com.example.bleapplication.Constants.CHARACTERISTIC_TIME_STRING
import com.example.bleapplication.Constants.CLIENT_CONFIGURATION_DESCRIPTOR_SHORT_ID
import com.example.bleapplication.Constants.SERVICE_STRING
object BluetoothUtils {
// Characteristics
fun findCharacteristics(bluetoothGatt: BluetoothGatt): List<BluetoothGattCharacteristic> =
findService(bluetoothGatt.services)?.characteristics?.filter { isMatchingCharacteristic(it) }
?: listOf()
fun findEchoCharacteristic(bluetoothGatt: BluetoothGatt): BluetoothGattCharacteristic? =
findCharacteristic(bluetoothGatt, CHARACTERISTIC_ECHO_STRING)
fun findTimeCharacteristic(bluetoothGatt: BluetoothGatt): BluetoothGattCharacteristic? =
findCharacteristic(bluetoothGatt, CHARACTERISTIC_TIME_STRING)
private fun findCharacteristic(bluetoothGatt: BluetoothGatt, uuidString: String) =
findService(bluetoothGatt.services)?.characteristics?.find {
characteristicMatches(
it,
uuidString
)
}
fun isEchoCharacteristic(characteristic: BluetoothGattCharacteristic?) =
characteristicMatches(characteristic, CHARACTERISTIC_ECHO_STRING)
fun isTimeCharacteristic(characteristic: BluetoothGattCharacteristic?) =
characteristicMatches(characteristic, CHARACTERISTIC_TIME_STRING)
private fun characteristicMatches(
characteristic: BluetoothGattCharacteristic?,
uuidString: String
) =
characteristic?.let {
uuidMatches(it.uuid.toString(), uuidString)
} ?: false
private fun isMatchingCharacteristic(characteristic: BluetoothGattCharacteristic?) =
characteristic?.let {
matchesCharacteristicUuidString(it.uuid.toString())
} ?: false
private fun matchesCharacteristicUuidString(characteristicIdString: String) =
uuidMatches(characteristicIdString, CHARACTERISTIC_ECHO_STRING, CHARACTERISTIC_TIME_STRING)
fun requiresResponse(characteristic: BluetoothGattCharacteristic) =
characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE != BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE
fun requiresConfirmation(characteristic: BluetoothGattCharacteristic) =
characteristic.properties and BluetoothGattCharacteristic.PROPERTY_INDICATE == BluetoothGattCharacteristic.PROPERTY_INDICATE
// Descriptor
fun findClientConfigurationDescriptor(descriptorList: List<BluetoothGattDescriptor?>): BluetoothGattDescriptor? =
descriptorList.find { isClientConfigurationDescriptor(it) }
private fun isClientConfigurationDescriptor(descriptor: BluetoothGattDescriptor?) =
descriptor?.let {
uuidMatches(
descriptor.uuid.toString().substring(4, 8),
CLIENT_CONFIGURATION_DESCRIPTOR_SHORT_ID
)
} ?: false
// Service
private fun findService(serviceList: List<BluetoothGattService>): BluetoothGattService? =
serviceList.find { uuidMatches(it.uuid.toString(), SERVICE_STRING) }
// String matching
// If manually filtering, substring to match:
// 0000XXXX-0000-0000-0000-000000000000
private fun uuidMatches(uuidString: String, vararg matches: String): Boolean =
matches.any { uuidString.equals(it, ignoreCase = true) }
}
| 0
|
Kotlin
|
0
| 1
|
2885e3ad58f33a87fcb618116eb99a09d45a8faa
| 3,683
|
android-BLEApplication
|
Apache License 2.0
|
app/src/main/java/soup/gdg/darktheme/sample/elevation/ElevationNoOverlayActivity.kt
|
fornewid
| 190,510,615
| false
| null |
package soup.gdg.darktheme.sample.elevation
class ElevationNoOverlayActivity : ElevationOverlayActivity()
| 0
|
Kotlin
|
0
| 0
|
7642c940072a7d69ab4845f8af78f23b246c6f4f
| 107
|
GDGAndroid-atPangyo-2019-DarkTheme-Sample
|
Apache License 2.0
|
aws-dynamo/src/iosMain/kotlin/com/estivensh4/dynamo/mappers/AttributeMapper.kt
|
estivensh
| 716,450,518
| false
|
{"Kotlin": 155379, "Shell": 2027}
|
/*
* Copyright 2023 estiven. Use of this source code is governed by the Apache 2.0 license.
*/
package com.estivensh4.dynamo.mappers
import cocoapods.AWSDynamoDB.AWSDynamoDBAttributeAction
import cocoapods.AWSDynamoDB.AWSDynamoDBAttributeDefinition
import cocoapods.AWSDynamoDB.AWSDynamoDBAttributeValue
import cocoapods.AWSDynamoDB.AWSDynamoDBAttributeValueUpdate
import cocoapods.AWSDynamoDB.AWSDynamoDBScalarAttributeType
import com.estivensh4.dynamo.AttributeDefinition
import com.estivensh4.dynamo.AttributeValue
import com.estivensh4.dynamo.AttributeValueUpdate
import com.estivensh4.dynamo.ScalarAttributeType
import kotlinx.cinterop.ExperimentalForeignApi
@OptIn(ExperimentalForeignApi::class)
fun AttributeValue.toAttributeValue(): AWSDynamoDBAttributeValue {
return AWSDynamoDBAttributeValue().apply {
setS(s)
setSS(sS)
setN(n)
setNS(ns)
setM(m?.mapValues { it.value.toAttributeValue() })
setL(l?.map { it.toAttributeValue() })
}
}
@OptIn(ExperimentalForeignApi::class)
fun AttributeDefinition.toAttribute(): AWSDynamoDBAttributeDefinition {
return AWSDynamoDBAttributeDefinition()
.apply {
setAttributeType(this@toAttribute.attributeType.toType())
setAttributeName(this@toAttribute.attributeName)
}
}
@OptIn(ExperimentalForeignApi::class)
fun AttributeValueUpdate.toAttributeValueUpdate(): AWSDynamoDBAttributeValueUpdate {
val builder = AWSDynamoDBAttributeValueUpdate()
action?.let { builder.setAction(AWSDynamoDBAttributeAction.valueOf(it)) }
value?.let { builder.setValue(it.toAttributeValue()) }
return builder
}
@OptIn(ExperimentalForeignApi::class)
fun ScalarAttributeType.toType(): AWSDynamoDBScalarAttributeType {
return when (this) {
ScalarAttributeType.S -> AWSDynamoDBScalarAttributeType.AWSDynamoDBScalarAttributeTypeS
ScalarAttributeType.N -> AWSDynamoDBScalarAttributeType.AWSDynamoDBScalarAttributeTypeN
ScalarAttributeType.B -> AWSDynamoDBScalarAttributeType.AWSDynamoDBScalarAttributeTypeB
}
}
| 2
|
Kotlin
|
1
| 7
|
72f9a9ccedeed893c2b35e44a6ee6b8ea708e611
| 2,079
|
aws-kmp
|
Apache License 2.0
|
core/droidMain/framework/AndroidFramework.kt
|
shibasis0801
| 669,270,289
| false
|
{"Kotlin": 51865, "C++": 47981, "Objective-C++": 11829, "Ruby": 6473, "Swift": 5718, "Objective-C": 4286, "CMake": 1744, "TypeScript": 941, "JavaScript": 328, "C": 123}
|
package app.mehmaan.core.framework
import java.lang.ref.WeakReference
import java.util.concurrent.atomic.AtomicInteger
// replace this from pragati
actual val __PLATFORM = PlatformType.ANDROID
actual class WeakRef<T> actual constructor(referred: T) {
private val ref = WeakReference(referred)
actual fun get() = ref.get()
}
actual class AtomicInt actual constructor(value: Int){
private val data = AtomicInteger(value)
actual fun getAndIncrement() = data.getAndIncrement()
}
| 0
|
Kotlin
|
0
| 0
|
4c28775f036392357683a2e9e98255fef1256854
| 494
|
Reaktor
|
Apache License 2.0
|
spark/src/main/java/io/github/tonnyl/spark/Spark.kt
|
hyl87
| 126,146,323
| true
|
{"Kotlin": 3240}
|
package io.github.tonnyl.spark
import android.graphics.drawable.AnimationDrawable
import android.view.View
/**
* Created by lizhaotailang on 26/08/2017.
*
* Create a background animation like instagram.
*/
class Spark private constructor(
private val mDuration: Int,
private val mView: View?,
private val mAnimList: Int
) {
companion object {
@JvmField
val ANIM_GREEN_PURPLE = R.drawable.anim_green_purple
@JvmField
val ANIM_BLUE_PURPLE = R.drawable.anim_blue_purple
@JvmField
val ANIM_RED_PURPLE = R.drawable.anim_red_purple
}
private constructor(builder: Builder) :
this(builder.duration, builder.view, builder.animList)
private var mBackgroundAnimationDrawable: AnimationDrawable? = null
fun startAnimation() {
mView?.let {
it.setBackgroundResource(mAnimList)
mBackgroundAnimationDrawable = it.background as AnimationDrawable
mBackgroundAnimationDrawable?.setEnterFadeDuration(mDuration)
mBackgroundAnimationDrawable?.setExitFadeDuration(mDuration)
it.background = mBackgroundAnimationDrawable
it.post {
mBackgroundAnimationDrawable?.start()
}
} ?: run {
throw IllegalStateException("view must be initialized")
}
}
fun stopAnimation() {
if (mView != null && mBackgroundAnimationDrawable?.isRunning == true) {
mBackgroundAnimationDrawable?.stop()
}
}
class Builder {
var duration: Int = 4000
private set
var view: View? = null
private set
var animList: Int = ANIM_GREEN_PURPLE
private set
fun setDuration(duration: Int): Builder {
this.duration = duration
return this
}
fun setView(view: View): Builder {
this.view = view
return this
}
fun setAnimList(animList: Int): Builder {
this.animList = animList
return this
}
fun build() = Spark(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
e6dbb003a77fd99e819f72b7cd89f4e9b5834664
| 2,150
|
Spark-1
|
MIT License
|
src/main/kotlin/net/casualuhc/uhcmod/uhc/UHCEvent.kt
|
CasualUHC
| 334,382,250
| false
| null |
package net.casualuhc.uhcmod.uhc
import net.casualuhc.uhcmod.uhc.handlers.LobbyHandler
import net.casualuhc.uhcmod.uhc.handlers.ResourceHandler
interface UHCEvent {
fun getTeamSize(): Int
fun getLobbyHandler(): LobbyHandler
fun getResourcePackHandler(): ResourceHandler
fun load()
}
| 0
|
Kotlin
|
0
| 3
|
4dfc539c3cf7f261c911f45a47206f64faaa37e9
| 303
|
UHC-Mod
|
MIT License
|
src/main/kotlin/watch/dependency/config.kt
|
JakeWharton
| 281,296,048
| false
|
{"Kotlin": 58388, "Shell": 2975, "Dockerfile": 1119}
|
package watch.dependency
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.tomlj.Toml
import org.tomlj.TomlTable
import watch.dependency.RepositoryConfig.Companion.GOOGLE_MAVEN_HOST
import watch.dependency.RepositoryConfig.Companion.GOOGLE_MAVEN_ID
import watch.dependency.RepositoryConfig.Companion.GOOGLE_MAVEN_NAME
import watch.dependency.RepositoryConfig.Companion.MAVEN_CENTRAL_HOST
import watch.dependency.RepositoryConfig.Companion.MAVEN_CENTRAL_ID
import watch.dependency.RepositoryConfig.Companion.MAVEN_CENTRAL_NAME
import watch.dependency.RepositoryType.Maven2
fun MavenRepository.Factory.parseWellKnownIdOrUrl(value: String): MavenRepository {
return when (value) {
MAVEN_CENTRAL_ID -> maven2(MAVEN_CENTRAL_NAME, MAVEN_CENTRAL_HOST)
GOOGLE_MAVEN_ID -> maven2(GOOGLE_MAVEN_NAME, GOOGLE_MAVEN_HOST)
else -> maven2("Maven Repository", value.toHttpUrl())
}
}
data class RepositoryConfig(
val name: String,
val host: HttpUrl,
val type: RepositoryType = Maven2,
val coordinates: List<MavenCoordinate>,
) {
companion object {
const val MAVEN_CENTRAL_ID = "MavenCentral"
const val MAVEN_CENTRAL_NAME = "Maven Central"
val MAVEN_CENTRAL_HOST = "https://repo1.maven.org/maven2/".toHttpUrl()
const val GOOGLE_MAVEN_ID = "GoogleMaven"
const val GOOGLE_MAVEN_NAME = "Google Maven"
val GOOGLE_MAVEN_HOST = "https://maven.google.com/".toHttpUrl()
private const val TOML_KEY_NAME = "name"
private const val TOML_KEY_HOST = "host"
private const val TOML_KEY_TYPE = "type"
private const val TOML_KEY_COORDINATES = "coordinates"
private fun TomlTable.getCoordinates(key: String): List<MavenCoordinate> {
val coordinateArray = getArray(key)!!
return (0 until coordinateArray.size())
.map(coordinateArray::getString)
.map(MavenCoordinate::parse)
}
private fun TomlTable.tryParseWellKnown(self: String, name: String, host: HttpUrl): RepositoryConfig {
var coordinates: List<MavenCoordinate>? = null
for (key in keySet()) {
when (key) {
TOML_KEY_COORDINATES -> coordinates = getCoordinates(key)
TOML_KEY_NAME, TOML_KEY_HOST, TOML_KEY_TYPE -> {
throw IllegalArgumentException("'$self' table must not define a '$key' key")
}
else -> throw IllegalArgumentException("'$self' table contains unknown '$key' key")
}
}
requireNotNull(coordinates) { "'$self' table missing required '$TOML_KEY_COORDINATES' key" }
return RepositoryConfig(name, host, Maven2, coordinates)
}
private fun TomlTable.tryParseCustom(self: String): RepositoryConfig {
var name = self
var host: HttpUrl? = null
var type: RepositoryType = Maven2
var coordinates: List<MavenCoordinate>? = null
for (key in keySet()) {
when (key) {
TOML_KEY_NAME -> name = getString(key)!!
TOML_KEY_HOST -> host = getString(key)!!.toHttpUrl()
TOML_KEY_TYPE -> type = RepositoryType.valueOf(getString(key)!!)
TOML_KEY_COORDINATES -> coordinates = getCoordinates(key)
else -> throw IllegalArgumentException("'$self' table contains unknown key '$key'")
}
}
requireNotNull(host) { "'$self' table missing required '$TOML_KEY_HOST' key" }
requireNotNull(coordinates) { "'$self' table missing required '$TOML_KEY_COORDINATES' key" }
return RepositoryConfig(name, host, type, coordinates)
}
fun parseConfigsFromToml(toml: String): List<RepositoryConfig> = buildList {
val parseResult = Toml.parse(toml)
require(!parseResult.hasErrors()) {
"Unable to parse TOML config:\n\n * " + parseResult.errors().joinToString("\n *")
}
for (key in parseResult.keySet()) {
val table = parseResult.getTable(key)!!
this += when (key) {
MAVEN_CENTRAL_ID -> table.tryParseWellKnown(MAVEN_CENTRAL_ID, MAVEN_CENTRAL_NAME, MAVEN_CENTRAL_HOST)
GOOGLE_MAVEN_ID -> table.tryParseWellKnown(GOOGLE_MAVEN_ID, GOOGLE_MAVEN_NAME, GOOGLE_MAVEN_HOST)
else -> table.tryParseCustom(key)
}
}
}
}
}
enum class RepositoryType {
Maven2,
}
| 3
|
Kotlin
|
8
| 282
|
5b29764d78c7644c47d0cf9e129e6041ee922f2c
| 3,983
|
dependency-watch
|
Apache License 2.0
|
logs/src/main/java/vip/mystery0/logs/LogsConfig.kt
|
Mystery0Tools
| 126,463,085
| false
| null |
package vip.mystery0.logs
import vip.mystery0.logs.languageConstants.StringInterfaceContext
class LogsConfig {
var isShowLog = true//是否显示日志
var isShowDate = true//是否显示日期
var isShowHead = true//是否显示头部信息
var isShowBorder = true//是否显示边框
var isShowThread = true//是否显示当前的所在线程
var isShowInfoTag = true//是否显示信息的tag
var commonTag = ""//全局的tag
enum class NumberGravity { NONE, LEFT, RIGHT }
var showNumber = NumberGravity.RIGHT//是否显示编号
var indexWidth = 3//多条信息输出时,编号所占的宽度
var stackOffset = -1//需要输出的栈深度,-1表示自动计算
var dividerLength = 60//分割线的宽度
var language = StringInterfaceContext.Language.EN//提示信息的语言
fun setShowLog(isShowLog: Boolean): LogsConfig {
this.isShowLog = isShowLog
return this
}
fun setShowDate(isShowDate: Boolean): LogsConfig {
this.isShowDate = isShowDate
return this
}
fun setShowHead(isShowHead: Boolean): LogsConfig {
this.isShowHead = isShowHead
return this
}
fun setShowBorder(isShowBorder: Boolean): LogsConfig {
this.isShowBorder = isShowBorder
return this
}
fun setShowThread(isShowThread: Boolean): LogsConfig {
this.isShowThread = isShowThread
return this
}
fun setShowInfoTag(isShowInfoTag: Boolean): LogsConfig {
this.isShowInfoTag = isShowInfoTag
return this
}
fun setShowNumber(gravity: NumberGravity): LogsConfig {
this.showNumber = gravity
return this
}
fun setIndexWidth(indexWidth: Int): LogsConfig {
this.indexWidth = indexWidth
return this
}
fun setStackOffset(stackOffset: Int): LogsConfig {
this.stackOffset = stackOffset
return this
}
fun setDividerLength(dividerLength: Int): LogsConfig {
this.dividerLength = dividerLength
return this
}
fun setCommonTag(commonTag: String): LogsConfig {
this.commonTag = commonTag
return this
}
}
| 0
|
Kotlin
|
0
| 1
|
22f0daa037c5adfea9b33a7131b0765237431065
| 1,756
|
Logs
|
Apache License 2.0
|
settings-core/src/main/java/com/michaelflisar/settings/core/internal/fragments/SettingsFragment.kt
|
MFlisar
| 256,263,996
| false
| null |
package com.michaelflisar.settings.core.internal.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.michaelflisar.settings.core.Settings
import com.michaelflisar.settings.core.SettingsManager
import com.michaelflisar.settings.core.classes.SettingsDefinition
import com.michaelflisar.settings.core.classes.SettingsDependency
import com.michaelflisar.settings.core.classes.SettingsDisplaySetup
import com.michaelflisar.settings.core.classes.SettingsState
import com.michaelflisar.settings.core.databinding.SettingsFragmentSettingsBinding
import com.michaelflisar.settings.core.enums.ChangeType
import com.michaelflisar.settings.core.interfaces.ISetting
import com.michaelflisar.settings.core.interfaces.ISettingsData
import com.michaelflisar.settings.core.internal.SettingsPayload
import com.michaelflisar.settings.core.internal.Test
import com.michaelflisar.settings.core.settings.SettingsGroup
internal class SettingsFragment : Fragment() {
companion object {
fun create(settingsData: ISettingsData, group: SettingsGroup, dependencies: List<SettingsDependency<*>>, setup: SettingsDisplaySetup, state: SettingsState): SettingsFragment {
val f = SettingsFragment()
val args = Bundle().apply {
putParcelable("settingsData", settingsData)
if (SettingsManager.settingsProvider == null)
putParcelableArrayList("items", ArrayList(group.getItems()))
else
putLongArray("itemIds", group.getItems().map { it.id }.toLongArray())
putParcelableArrayList("dependencies", ArrayList(dependencies))
putParcelable("setup", setup)
putParcelable("state", state)
}
f.arguments = args
return f
}
}
private var binding: SettingsFragmentSettingsBinding? = null
private lateinit var settingsData: ISettingsData
private lateinit var items: ArrayList<ISetting<*>>
private lateinit var dependencies: ArrayList<SettingsDependency<*>>
private lateinit var setup: SettingsDisplaySetup
private var state: SettingsState = SettingsState()
private lateinit var settings: Settings
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments!!.let {
settingsData = it.getParcelable("settingsData")!!
if (SettingsManager.settingsProvider == null)
items = it.getParcelableArrayList("items")!!
else
items = ArrayList(it.getLongArray("itemIds")!!.map { SettingsManager.settingsProvider!!.invoke(it) })
dependencies = it.getParcelableArrayList("dependencies")!!
setup = it.getParcelable("setup")!!
state = it.getParcelable("state")!!
}
savedInstanceState?.let {
it.getParcelable<SettingsState>("state")?.let {
state = it
}
// Log.d("SettingsFragment", "state restored: $state")
}
settings = Settings(SettingsDefinition(items, dependencies, false), settingsData, setup)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = SettingsFragmentSettingsBinding.inflate(inflater)
setup.noDataFoundIcon?.takeIf { it > 0 }?.let {
binding!!.vEmpty.ivEmpty.setImageResource(it)
}
setup.noSearchResults.takeIf { it > 0 }?.let {
binding!!.vEmpty.tvEmpty.setText(it)
}
// bind settings to recyclerview
val start = Test.measureTimeStart()
settings.bind(Settings.ViewContext.Fragment(this), state, binding!!.rv, binding!!.vEmpty.root)
Test.measureTimeStop(start, "settings.bind")
if (state.filter.isNotEmpty()) {
updateFilter(state.filter)
}
return binding!!.root
}
override fun onDestroyView() {
settings.unbind()
super.onDestroyView()
}
fun updateFilter(text: String) {
settings.filter(text)
}
// fun getExistingIds(): List<Long> {
// return SettingsUtils.getAllIds(items)
// }
fun getViewState(): SettingsState? {
return settings.getViewState()
}
fun onDependencyChanged(dependency: SettingsDependency<*>, payload: SettingsPayload) {
settings.onDependencyChanged(dependency, payload)
}
// ------------------------
// state saving/restoring
// ------------------------
override fun onSaveInstanceState(outState: Bundle) {
val state = settings.getViewState()
outState.putParcelable("state", state)
super.onSaveInstanceState(outState)
}
// ---------------
// ISettingsChangedCallback - forwards events
// ---------------
fun onSettingChanged(changeType: ChangeType, setting: ISetting<*>, settingsData: ISettingsData, oldValue: Any?, newValue: Any?) {
settings.onSettingChanged(changeType, setting, settingsData, oldValue, newValue)
}
}
| 0
|
Kotlin
|
0
| 2
|
5fc5264a9b2bfc108aab03e8925244d665c6a9d4
| 5,182
|
Settings
|
Apache License 2.0
|
library/src/main/java/jp/co/soramitsu/map/presentation/places/add/schedule/ScheduleSectionView.kt
|
soramitsu
| 255,592,548
| false
| null |
package jp.co.soramitsu.map.presentation.places.add.schedule
import android.animation.LayoutTransition
import android.app.TimePickerDialog
import android.content.Context
import android.text.format.DateFormat.is24HourFormat
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import androidx.constraintlayout.widget.ConstraintLayout
import jp.co.soramitsu.map.databinding.SmAddScheduleSectionViewBinding
import jp.co.soramitsu.map.model.Time
import jp.co.soramitsu.map.model.WorkDay
import java.time.DayOfWeek
import java.time.temporal.WeekFields
import java.util.*
internal class ScheduleSectionView @JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyleRes: Int = 0
) : ConstraintLayout(context, attributeSet, defStyleRes) {
private val weekdaysChips by lazy {
with(binding) {
listOf(weekday1, weekday2, weekday3, weekday4, weekday5, weekday6, weekday7)
}
}
private val binding = SmAddScheduleSectionViewBinding.inflate(LayoutInflater.from(context), this)
private var onRemoveButtonClickListener: () -> Unit = {}
private var onWorkingDaysSelected: () -> Unit = { }
@Suppress("MagicNumber")
val selectedDays: List<WorkDay>
get() {
val is24Hours = binding.open24HoursSwitch.isChecked
val from = if (is24Hours) {
Time(0, 0)
} else {
TimeUtils.parseTime(binding.openFromEditText.text.toString())
}
val to = if (is24Hours) {
Time(23, 59)
} else {
TimeUtils.parseTime(binding.closeAtEditText.text.toString())
}
val lunchTimeFrom = TimeUtils.parseTime(binding.lunchFromEditText.text.toString())
val lunchTimeTo = TimeUtils.parseTime(binding.lunchToEditText.text.toString())
return weekdaysChips.filter { it.isChecked }.map { chip ->
val dayOfWeek = chip.tag as DayOfWeek
WorkDay(
weekDay = dayOfWeek.asJavaCalendarValue(),
from = from,
to = to,
lunchTimeFrom = lunchTimeFrom,
lunchTimeTo = lunchTimeTo,
)
}
}
var editable: Boolean = true
set(value) {
field = value
weekdaysChips.forEach { it.isCheckable = value }
binding.open24HoursSwitch.isEnabled = value
binding.openFromTextInputLayout.isEnabled = value
binding.closeAtTextInputLayout.isEnabled = value
binding.lunchTimeSwitch.isEnabled = value
binding.lunchFromTextInputLayout.isEnabled = value
binding.lunchToTextInputLayout.isEnabled = value
}
var removeButtonVisibility: Boolean = false
set(value) {
field = value
binding.deleteButton.visibility = if (value) View.VISIBLE else View.GONE
binding.topSeparator.visibility = if (value) View.VISIBLE else View.GONE
}
init {
layoutTransition = LayoutTransition()
displayLocalisedWeekdays()
binding.open24HoursSwitch.setOnCheckedChangeListener { _, isChecked ->
binding.openHoursFlow.visibility = if (isChecked) View.GONE else View.VISIBLE
}
binding.lunchTimeSwitch.setOnCheckedChangeListener { _, isChecked ->
binding.lunchHoursFlow.visibility = if (isChecked) View.VISIBLE else View.GONE
}
weekdaysChips.forEach { chip ->
chip.setOnCheckedChangeListener { _, _ -> onWorkingDaysSelected.invoke() }
}
binding.deleteButton.setOnClickListener { onRemoveButtonClickListener.invoke() }
initTimeField(binding.openFromEditText)
initTimeField(binding.closeAtEditText)
initTimeField(binding.lunchFromEditText)
initTimeField(binding.lunchToEditText)
}
fun setOnRemoveButtonClickListener(onRemoveButtonClickListener: () -> Unit) {
this.onRemoveButtonClickListener = onRemoveButtonClickListener
}
fun setOnWorkingDaysSelected(onWorkingDaysSelected: () -> Unit) {
this.onWorkingDaysSelected = onWorkingDaysSelected
}
@Suppress("MagicNumber")
fun getSectionData(): SectionData {
val is24Hours = binding.open24HoursSwitch.isChecked
val from = if (is24Hours) {
Time(0, 0)
} else {
TimeUtils.parseTime(binding.openFromEditText.text.toString())
}
val to = if (is24Hours) {
Time(23, 59)
} else {
TimeUtils.parseTime(binding.closeAtEditText.text.toString())
}
val lunchTimeFrom = TimeUtils.parseTime(binding.lunchFromEditText.text.toString())
val lunchTimeTo = TimeUtils.parseTime(binding.lunchToEditText.text.toString())
val daysMap = mutableMapOf<DayOfWeek, SelectionState>()
weekdaysChips
.filter { it.isChecked }
.map { it.tag as DayOfWeek }
.forEach { dayOfWeek -> daysMap[dayOfWeek] = SelectionState.Selected }
weekdaysChips
.filter { it.isEnabled && !it.isChecked }
.map { it.tag as DayOfWeek }
.forEach { dayOfWeek -> daysMap[dayOfWeek] = SelectionState.NotSelected }
weekdaysChips
.filter { !it.isEnabled }
.map { it.tag as DayOfWeek }
.forEach { dayOfWeek -> daysMap[dayOfWeek] = SelectionState.SelectedInOtherSection }
return SectionData(
id = tag as Int,
daysMap = daysMap,
fromTime = from,
toTime = to,
lunchFromTime = lunchTimeFrom,
lunchToTime = lunchTimeTo
)
}
fun bindWithSectionData(sectionData: SectionData) = with(sectionData) {
tag = sectionData.id
if (fromTime != Time.NOT_SET) {
binding.openFromEditText.setText(TimeUtils.formatTime(fromTime.hour, fromTime.minute))
}
if (toTime != Time.NOT_SET) {
binding.closeAtEditText.setText(TimeUtils.formatTime(toTime.hour, toTime.minute))
}
if (lunchFromTime != Time.NOT_SET) {
binding.lunchFromEditText.setText(TimeUtils.formatTime(lunchFromTime.hour, lunchFromTime.minute))
}
if (lunchToTime != Time.NOT_SET) {
binding.lunchToEditText.setText(TimeUtils.formatTime(lunchToTime.hour, lunchToTime.minute))
}
daysMap
.filterValues { state -> state == SelectionState.Selected }
.map { it.key }
.forEach { dayOfWeek ->
weekdaysChips.find { it.tag == dayOfWeek }?.let { chip ->
chip.isCheckable = true
chip.isEnabled = true
chip.isChecked = true
}
}
daysMap
.filterValues { state -> state == SelectionState.NotSelected }
.map { it.key }
.forEach { dayOfWeek ->
weekdaysChips.find { it.tag == dayOfWeek }?.let { chip ->
chip.isCheckable = true
chip.isEnabled = true
chip.isChecked = false
}
}
daysMap
.filterValues { state -> state == SelectionState.SelectedInOtherSection }
.map { it.key }
.forEach { dayOfWeek ->
weekdaysChips.find { it.tag == dayOfWeek }?.let { chip ->
chip.isCheckable = false
chip.isEnabled = false
chip.isChecked = false
}
}
}
@Suppress("MagicNumber")
private fun displayLocalisedWeekdays() {
val firstDayOfWeek = WeekFields.of(Locale.getDefault()).firstDayOfWeek
IntRange(0, 6).map { firstDayOfWeek.plus(it.toLong()) }.forEachIndexed { index, dayOfWeek ->
weekdaysChips[index].text = dayOfWeek.shortLocalisedName(resources)
weekdaysChips[index].tag = dayOfWeek
}
}
private fun initTimeField(editText: EditText) {
editText.setOnFocusChangeListener { v, hasFocus ->
v.clearFocus()
if (hasFocus) {
val onTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
editText.setText(TimeUtils.formatTime(hourOfDay, minute))
}
TimePickerDialog(context, onTimeSetListener, 0, 0, is24HourFormat(context)).show()
}
}
}
}
| 1
|
Kotlin
|
0
| 3
|
545b5f56b84a2df438407dc53358c03e1ed69e82
| 8,632
|
magellan-android
|
Apache License 2.0
|
logging-test/src/main/java/com/fsryan/tools/logging/test/FSTestLoggingConfig.kt
|
ryansgot
| 212,757,848
| false
| null |
package com.fsryan.tools.logging.test
import com.fsryan.tools.logging.FSLoggingConfig
import java.util.concurrent.Executor
class FSTestLoggingConfig : FSLoggingConfig {
override fun createExecutor() = Executor { r -> r.run() }
override fun isTestEnvironment(): Boolean = true
}
| 2
|
Kotlin
|
2
| 1
|
ddf9d66edbda1b81d7fec2a41593ecc2ecc72dfc
| 287
|
logging
|
Apache License 2.0
|
play-media/src/main/java/io/agora/play_media_manager/PlayMediaManager.kt
|
AgoraIO
| 623,043,738
| false
|
{"Kotlin": 141696}
|
package io.agora.play_media_manager
import android.content.Context
import android.view.SurfaceView
import io.agora.authentication_manager.AuthenticationManager
import io.agora.mediaplayer.Constants.*
import io.agora.mediaplayer.IMediaPlayer
import io.agora.mediaplayer.IMediaPlayerObserver
import io.agora.mediaplayer.data.PlayerUpdatedInfo
import io.agora.mediaplayer.data.SrcInfo
import io.agora.rtc2.ChannelMediaOptions
import io.agora.rtc2.Constants
import io.agora.rtc2.video.VideoCanvas
class PlayMediaManager(context: Context?) : AuthenticationManager(context) {
private var mediaPlayer: IMediaPlayer? = null // Instance of the media player
private var mediaDuration: Long = 0
private lateinit var mediaPlayerListener: MediaPlayerListener
// Interface to forward media player events to the UI
interface MediaPlayerListener {
fun onPlayerStateChanged(state: MediaPlayerState, error: MediaPlayerError)
fun onProgress(percent: Int)
}
fun setupMediaPlayer(listener: MediaPlayerListener){
if (mediaPlayer == null) {
// Create an instance of the media player
mediaPlayer = agoraEngine?.createMediaPlayer()
// Set the mediaPlayerObserver to receive callbacks
mediaPlayer?.registerPlayerObserver(mediaPlayerObserver)
// A listener to notify the UI
mediaPlayerListener = listener
}
}
fun mediaPlayerState(): MediaPlayerState? {
// Returns the current state of the media player
return mediaPlayer?.state
}
fun openMediaFile(mediaLocation: String) {
// Opens the media file at mediaLocation url
// Supports URI files starting with content://
if (mediaPlayer != null) {
// Open the media file
mediaPlayer?.open(mediaLocation, 0)
}
}
fun destroyMediaPlayer(){
// Destroy the media player instance and clean up
if (mediaPlayer != null) {
mediaPlayer?.stop()
mediaPlayer?.unRegisterPlayerObserver(mediaPlayerObserver)
mediaPlayer?.destroy()
mediaPlayer = null
}
}
fun playMedia() {
// Start publishing the media player video
updateChannelPublishOptions(true)
mediaPlayer?.play()
}
fun pauseMedia() {
mediaPlayer?.pause()
}
fun resumeMedia() {
mediaPlayer?.resume()
}
fun updateChannelPublishOptions(publishMediaPlayer: Boolean) {
val channelOptions = ChannelMediaOptions()
// Start or stop publishing the media player tracks
channelOptions.publishMediaPlayerAudioTrack = publishMediaPlayer
channelOptions.publishMediaPlayerVideoTrack = publishMediaPlayer
// Stop or start publishing the microphone and camera tracks
channelOptions.publishMicrophoneTrack = !publishMediaPlayer
channelOptions.publishCameraTrack = !publishMediaPlayer
// Specify the media player Id for publishing
if (publishMediaPlayer) channelOptions.publishMediaPlayerId = mediaPlayer?.mediaPlayerId
// Implement the settings
agoraEngine?.updateChannelMediaOptions(channelOptions)
}
fun mediaPlayerSurfaceView(): SurfaceView {
// Sets up and returns a SurfaceView to display the media player output
// Instantiate a SurfaceView
val videoSurfaceView = SurfaceView(mContext)
// Create a VideoCanvas using the SurfaceView
val videoCanvas = VideoCanvas(
videoSurfaceView,
Constants.RENDER_MODE_HIDDEN,
0
)
// Set the source type and media player Id
videoCanvas.sourceType = Constants.VIDEO_SOURCE_MEDIA_PLAYER
videoCanvas.mediaPlayerId = mediaPlayer?.mediaPlayerId ?: 0
// Setup the SurfaceView
agoraEngine?.setupLocalVideo(videoCanvas)
return videoSurfaceView
}
private val mediaPlayerObserver: IMediaPlayerObserver = object : IMediaPlayerObserver {
override fun onPlayerStateChanged(state: MediaPlayerState, error: MediaPlayerError) {
// Reports changes in playback state
if (state == MediaPlayerState.PLAYER_STATE_OPEN_COMPLETED) {
// Read media duration for updating play progress
mediaDuration = mediaPlayer?.duration ?: 0
}
// Notify the UI
mediaPlayerListener.onPlayerStateChanged(state, error)
}
override fun onPositionChanged(position: Long) {
if (mediaDuration > 0) {
// Calculate the progress percentage
val result = (position.toFloat() / mediaDuration.toFloat() * 100).toInt()
// Notify the UI of the progress
mediaPlayerListener.onProgress(result)
}
}
override fun onPlayerEvent(eventCode: MediaPlayerEvent, elapsedTime: Long, message: String) {
// Required to implement IMediaPlayerObserver
}
override fun onMetaData(type: MediaPlayerMetadataType, data: ByteArray) {
// Occurs when the media metadata is received
}
override fun onPlayBufferUpdated(playCachedBuffer: Long) {
// Reports the playback duration that the buffered data can support
}
override fun onPreloadEvent(src: String, event: MediaPlayerPreloadEvent) {
// Reports the events of preloaded media resources
}
override fun onPlayerSrcInfoChanged(from: SrcInfo, to: SrcInfo) {
// Occurs when the video bitrate of the media resource changes
}
override fun onPlayerInfoUpdated(info: PlayerUpdatedInfo) {
// Occurs when information related to the media player changes
}
override fun onAudioVolumeIndication(volume: Int) {
// Reports the volume of the media player
}
override fun onAgoraCDNTokenWillExpire() {
// Required to implement IMediaPlayerObserver
}
}
}
| 0
|
Kotlin
|
3
| 5
|
75e53677ee7f1febbb8278d391d5632abecb3b0b
| 6,061
|
video-sdk-samples-android
|
MIT License
|
app/src/main/java/dev/devunion/skillsnap/viewmodels/storage/DummyStorageViewModel.kt
|
abdelillahbel
| 845,821,547
| false
|
{"Kotlin": 211690}
|
/*
* Copyright (c) 2024. DevUnion Foundation.
* GitHub: https://github.com/devunionorg
* All rights reserved.
*
* This project was conceptualized and developed by @abdelillahbel.
* GitHub: https://github.com/abdelillahbel
*/
package dev.devunion.skillsnap.viewmodels.storage
import android.graphics.Bitmap
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import java.lang.Exception
class DummyStorageViewModel : ViewModel(), StorageViewModelInterface {
override fun uploadImage(
image: Bitmap,
onSuccess: (String) -> Unit,
onFailure: (Exception) -> Unit
) {
viewModelScope.launch {
try {
onSuccess("https://dummyimage.com/600x400/000/fff.jpg")
} catch (e: Exception) {
onFailure(e)
}
}
}
override fun deleteImage(
imageUrl: String,
onSuccess: () -> Unit,
onFailure: (Exception) -> Unit
) {
viewModelScope.launch {
try {
onSuccess()
} catch (e: Exception) {
onFailure(e)
}
}
}
}
| 0
|
Kotlin
|
0
| 8
|
0bbc0a442ba33e606e573381922c5b7493d0c0c8
| 1,190
|
SkillSnapAndroid
|
MIT License
|
navigation/src/commonMain/kotlin/com/hoc081098/solivagant/navigation/internal/StackEntryViewModelStoreOwner.kt
|
hoc081098
| 736,617,487
| false
|
{"Kotlin": 195727, "Shell": 377}
|
package com.hoc081098.solivagant.navigation.internal
import com.hoc081098.kmp.viewmodel.ViewModelStore
import com.hoc081098.kmp.viewmodel.ViewModelStoreOwner
import kotlin.LazyThreadSafetyMode.NONE
internal expect fun createViewModelStore(): ViewModelStore
internal class StackEntryViewModelStoreOwner : ViewModelStoreOwner {
private val viewModelStoreLazy = lazy(NONE) { createViewModelStore() }
fun clearIfInitialized() {
if (viewModelStoreLazy.isInitialized()) {
viewModelStoreLazy.value.clear()
}
}
override val viewModelStore: ViewModelStore by viewModelStoreLazy
}
| 6
|
Kotlin
|
3
| 5
|
9977b0e2365ef1dc484aa6069b73cf9c4f78e5ae
| 598
|
solivagant
|
Apache License 2.0
|
OnlinePK-Android/app/src/main/java/com/netease/yunxin/nertc/demo/feedback/expand/QuestionGroup.kt
|
netease-george
| 377,830,443
| true
|
{"Objective-C": 1325069, "Kotlin": 611041, "Java": 270376, "Swift": 124836, "C": 6974, "Python": 2874, "Ruby": 797}
|
/*
* Copyright (c) 2021 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be found in the LICENSE file
*/
package com.netease.yunxin.nertc.demo.feedback.expand
import java.util.*
/**
* Created by luc on 2020/11/17.
*/
class QuestionGroup(val title: String, items: List<QuestionItem>?) {
val items: List<QuestionItem>
init {
this.items = ArrayList(items)
}
}
| 0
|
Objective-C
|
0
| 0
|
9ba2e45734d24bcc287a08288e25b6d27856744d
| 438
|
OnlinePK
|
MIT License
|
app/src/main/java/com/citra/keyhub/Result.kt
|
Jul699
| 715,573,580
| false
|
{"Kotlin": 31263}
|
package com.citra.keyhub
sealed class Result<out R> private constructor() {
data class Success<out T>(val data: T) : Result<T>()
data class Error<out T>(val error: String) : Result<T>()
object Loading : Result<Nothing>()
}
| 0
|
Kotlin
|
0
| 0
|
5c1ba999547743223fc7f13a303033007573c4cf
| 236
|
Key-Hub
|
MIT License
|
app/src/main/java/com/vlad1m1r/kotlintest/presentation/utils/CoroutineContextProvider.kt
|
VladimirWrites
| 86,824,178
| false
| null |
package com.vlad1m1r.kotlintest.presentation.utils
import kotlinx.coroutines.experimental.Dispatchers
import kotlin.coroutines.experimental.CoroutineContext
open class CoroutineContextProvider() {
open val Main: CoroutineContext by lazy { Dispatchers.Main }
open val IO: CoroutineContext by lazy { Dispatchers.IO }
}
| 0
|
Kotlin
|
6
| 25
|
7bb76c69b41c2769b49e4f4f445452839f3cd5c2
| 326
|
KotlinSample
|
Apache License 2.0
|
src/main/kotlin/entry/Util.kt
|
wilinz
| 289,951,161
| true
|
{"Kotlin": 8181, "Java": 3444}
|
package entry
fun String.underscoreToCamel(): String {
val names = this.split("_")
val sb = StringBuilder()
for (n in names) {
sb.append(n.firstToUpper())
}
return sb.toString()
}
//这里还是不把id改了吧,今天发现我的 VideoUrl 变成 VIDeoUrl,难受
fun String.fmtName(to: String): String {
var name = this.clearName()
if (name.contains("_")) name = name.underscoreToCamel()
if (to == "json") name = name.firstToLower()
else if (to == "go") name = name.firstToUpper()
return name
}
fun String.clearName() =
this.replace("`".toRegex(), "").replace("'".toRegex(), "").replace("\"".toRegex(), "")
fun String.firstToUpper(): String {
if (this.isEmpty()) return ""
val ch = this.toCharArray()
ch[0] = ch[0].toUpperCase()
return String(ch)
}
fun String.firstToLower(): String {
if (this.isEmpty()) return ""
val ch = this.toCharArray()
ch[0] = ch[0].toLowerCase()
return String(ch)
}
| 0
|
Kotlin
|
0
| 0
|
2077eb751e1c8aff82579e6d60fc8e460eefaadd
| 942
|
convent-json-sql-to-go-struct
|
Apache License 2.0
|
apps/utgang-pdl/src/main/kotlin/no/nav/paw/arbeidssoekerregisteret/utgang/pdl/kafka/processors/HendelseLoggProcessor.kt
|
navikt
| 794,874,233
| false
|
{"Kotlin": 510676, "Dockerfile": 143}
|
package no.nav.paw.arbeidssoekerregisteret.utgang.pdl.kafka.processors
import no.nav.paw.arbeidssoekerregisteret.utgang.pdl.kafka.scheduleCleanup
import no.nav.paw.arbeidssoekerregisteret.utgang.pdl.kafka.serdes.HendelseState
import no.nav.paw.arbeidssokerregisteret.intern.v1.Startet
import org.apache.kafka.streams.kstream.KStream
import org.apache.kafka.streams.kstream.Named
import org.apache.kafka.streams.processor.api.Processor
import org.apache.kafka.streams.processor.api.ProcessorContext
import org.apache.kafka.streams.processor.api.Record
import org.apache.kafka.streams.state.KeyValueStore
import java.util.*
fun KStream<Long, Startet>.oppdaterHendelseState(
hendelseStateStoreName: String,
): KStream<Long, Startet> {
val processor = {
HendelseLoggProcessor(hendelseStateStoreName)
}
return process(processor, Named.`as`("hendelseLoggProsessor"), hendelseStateStoreName)
}
class HendelseLoggProcessor(
private val hendelseStateStoreName: String,
) : Processor<Long, Startet, Long, Startet> {
private var hendelseStateStore: KeyValueStore<UUID, HendelseState>? = null
private var context: ProcessorContext<Long, Startet>? = null
override fun init(context: ProcessorContext<Long, Startet>?) {
super.init(context)
this.context = context
hendelseStateStore = context?.getStateStore(hendelseStateStoreName)
scheduleCleanup(
requireNotNull(context) { "Context is not initialized" },
requireNotNull(hendelseStateStore) { "State store is not initialized" }
)
}
override fun process(record: Record<Long, Startet>?) {
if (record == null) return
val store = requireNotNull(hendelseStateStore) { "State store is not initialized" }
val startetHendelse = record.value()
val eksisterendeHendelseState = store.get(startetHendelse.hendelseId)
store.put(startetHendelse.hendelseId, HendelseState(
brukerId = startetHendelse.id,
periodeId = startetHendelse.hendelseId,
recordKey = record.key(),
identitetsnummer = startetHendelse.identitetsnummer,
opplysninger = startetHendelse.opplysninger,
startetTidspunkt = eksisterendeHendelseState?.startetTidspunkt ?: startetHendelse.metadata.tidspunkt,
harTilhoerendePeriode = eksisterendeHendelseState?.harTilhoerendePeriode ?: false
))
}
}
| 0
|
Kotlin
|
0
| 1
|
66d40ab0f27c4af892997006f1f6c318cec77470
| 2,472
|
paw-arbeidssoekerregisteret-monorepo-intern
|
MIT License
|
server/src/main/kotlin/org/kryptonmc/krypton/entity/ai/goal/KryptonGoalSelector.kt
|
KryptonMC
| 255,582,002
| false
| null |
/*
* This file is part of the Krypton project, licensed under the Apache License v2.0
*
* Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kryptonmc.krypton.entity.ai.goal
import org.kryptonmc.api.entity.Entity
import org.kryptonmc.api.entity.ai.goal.Goal
import org.kryptonmc.api.entity.ai.goal.GoalSelector
import org.kryptonmc.api.entity.ai.goal.TargetFinder
import java.util.Collections
import java.util.TreeSet
class KryptonGoalSelector : GoalSelector {
private val goals = TreeSet<PrioritizedGoal>(Comparator.comparingInt { it.priority })
private val finders = TreeSet<PrioritizedTargetFinder>(Comparator.comparingInt { it.priority })
override val availableGoals: Collection<Goal>
get() = Collections.unmodifiableCollection(goals)
override val targetFinders: Collection<TargetFinder>
get() = Collections.unmodifiableCollection(finders)
override fun addGoal(priority: Int, goal: Goal) {
goals.add(PrioritizedGoal(goal, priority))
}
override fun removeGoal(goal: Goal) {
goals.forEach {
if (it.goal !== goal || !it.isRunning()) return@forEach
it.stop()
}
goals.removeIf { it.goal === goal }
}
override fun addTargetFinder(priority: Int, finder: TargetFinder) {
finders.add(PrioritizedTargetFinder(finder, priority))
}
override fun removeTargetFinder(finder: TargetFinder) {
finders.removeIf { it.finder === finder }
}
override fun findTarget(): Entity? {
if (finders.isEmpty()) return null
for (finder in finders) {
if (!finder.isInUse()) continue
val target = finder.findTarget()
if (target != null) return target
}
return null
}
fun tick(time: Long) {
for (goal in goals) {
if (!goal.isRunning()) {
// If the goal isn't running, try to see if we can start it
if (goal.canUse()) goal.start()
continue
}
if (goal.shouldStop()) {
// If the goal should be stopped, stop it
goal.stop()
} else {
// Update the goal
goal.tick(time)
}
}
for (finder in finders) {
if (!finder.isInUse()) {
// If the finder isn't being used, try to see if we can start using it
if (finder.canUse()) finder.startUsing()
continue
}
if (finder.shouldRemove()) {
finder.remove()
}
}
}
private class PrioritizedGoal(val goal: Goal, val priority: Int) : Goal {
private var running = false
override fun canUse(): Boolean = goal.canUse()
override fun start() {
if (running) return
running = true
goal.start()
}
override fun shouldStop(): Boolean = goal.shouldStop()
override fun stop() {
if (!running) return
running = false
goal.stop()
}
override fun tick(time: Long) {
goal.tick(time)
}
fun isRunning(): Boolean = running
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
return goal == (other as PrioritizedGoal).goal
}
override fun hashCode(): Int = goal.hashCode()
}
private class PrioritizedTargetFinder(val finder: TargetFinder, val priority: Int) : TargetFinder {
private var inUse = false
override fun findTarget(): Entity? = finder.findTarget()
override fun canUse(): Boolean = finder.canUse()
fun isInUse(): Boolean = inUse
fun startUsing() {
if (inUse) return
inUse = true
onStartUsing()
}
override fun onStartUsing() {
finder.onStartUsing()
}
override fun shouldRemove(): Boolean = finder.shouldRemove()
fun remove() {
if (!inUse) return
inUse = false
onRemove()
}
override fun onRemove() {
finder.onRemove()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
return finder == (other as PrioritizedTargetFinder).finder
}
override fun hashCode(): Int = finder.hashCode()
}
}
| 27
|
Kotlin
|
11
| 233
|
a9eff5463328f34072cdaf37aae3e77b14fcac93
| 5,213
|
Krypton
|
Apache License 2.0
|
app/src/test/java/com/privateinternetaccess/android/pia/migration/mocks/HasWireguardMigrationNotBeenDoneMock.kt
|
pia-foss
| 229,341,983
| false
|
{"Git Config": 1, "Gradle": 4, "Go": 3, "Markdown": 3, "CODEOWNERS": 1, "Java Properties": 2, "Shell": 15, "Text": 2, "Ignore List": 9, "reStructuredText": 1, "Java": 213, "Kotlin": 123, "YAML": 7, "INI": 1, "XML": 462, "JSON": 2, "HTML": 3, "CMake": 1, "C": 60, "Roff Manpage": 2, "desktop": 1, "QMake": 1, "C++": 1, "OpenStep Property List": 1, "JavaScript": 1, "Haskell": 3, "Python": 1, "TOML": 1, "Rust": 1, "Go Checksums": 1, "Diff": 1, "Makefile": 1, "Go Module": 1, "Gradle Kotlin DSL": 1}
|
package com.privateinternetaccess.android.pia.migration.mocks
import com.privateinternetaccess.android.ui.connection.controller.WireguardMigrationControllerError
import com.privateinternetaccess.android.ui.connection.controller.WireguardMigrationControllerErrorCode
import com.privateinternetaccess.android.ui.connection.controller.domain.usecases.IHasWireguardMigrationNotBeenDone
class HasWireguardMigrationNotBeenDoneMock(
private val shouldSucceed: Boolean
): IHasWireguardMigrationNotBeenDone {
// region IHasWireguardMigrationNotBeenDone
override fun invoke(): Result<Unit> {
return if (shouldSucceed) {
Result.success(Unit)
} else {
Result.failure(WireguardMigrationControllerError(
code = WireguardMigrationControllerErrorCode.WIREGUARD_MIGRATION_HAS_BEEN_DONE
))
}
}
// endregion
}
| 6
|
Java
|
16
| 35
|
8c380f875a1a3328f95a1e9ff460588041175f3d
| 889
|
mobile-android-legacy
|
MIT License
|
app/src/main/kotlin/com/akagiyui/drive/model/request/AddRoleRequest.kt
|
AkagiYui
| 647,653,830
| false
|
{"Kotlin": 227183, "Java": 87795, "HTML": 812, "Dockerfile": 658}
|
package com.akagiyui.drive.model.request
import jakarta.validation.constraints.NotNull
/**
* 添加角色 请求
*
* @author AkagiYui
*/
class AddRoleRequest {
/**
* 角色名
*/
@NotNull(message = "{name is missing}")
lateinit var name: String
/**
* 角色描述
*/
lateinit var description: String
/**
* 角色权限
*/
lateinit var permissions: Set<String>
/**
* 是否是默认角色
*/
var isDefault: Boolean = false
}
| 4
|
Kotlin
|
2
| 9
|
6ff345645dfa83944ca4d36c02f9fa7b2162697f
| 461
|
KenkoDrive
|
MIT License
|
app/src/main/java/dev/lengua/ui/components/EntryDescription.kt
|
mgmu
| 802,992,375
| false
|
{"Kotlin": 81639}
|
package dev.lengua.ui.components
import android.content.res.Configuration
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Divider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import dev.lengua.R
import dev.lengua.ui.theme.LenguaTheme
@Composable
fun EditableEntryWithButtonPortrait(
title: String,
term: String,
onTermValueChange: (String) -> Unit,
definition: String,
onDefinitionValueChange: (String) -> Unit,
onClick: () -> Unit,
buttonText: String,
placeholderTerm: String,
placeholderDef: String
) {
Surface(modifier = Modifier.fillMaxSize()) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
EntryDescriptionWithFlag(
false,
title,
term,
onTermValueChange,
definition,
onDefinitionValueChange,
placeholderTerm,
placeholderDef
)
val buttonModifier = Modifier.padding(32.dp)
SimpleButton(onClick, buttonModifier, buttonText)
}
}
}
@Composable
fun EditableEntryWithButtonLandscape(
title: String,
term: String,
onTermValueChange: (String) -> Unit,
definition: String,
onDefinitionValueChange: (String) -> Unit,
onClick: () -> Unit,
buttonText: String,
placeholderTerm: String,
placeholderDef: String
) {
Surface(modifier = Modifier.fillMaxSize()) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
EntryDescriptionWithFlag(
false,
title,
term,
onTermValueChange,
definition,
onDefinitionValueChange,
placeholderTerm,
placeholderDef
)
}
val buttonModifier = Modifier.padding(32.dp)
SimpleButton(onClick, buttonModifier, buttonText)
}
}
}
@Composable
private fun EntryDescriptionWithFlag(
readOnly: Boolean,
title: String,
term: String,
onTermValueChange: (String) -> Unit,
definition: String,
onDefinitionValueChange: (String) -> Unit,
placeholderTerm: String,
placeholderDef: String
) {
Text(text = title, style = MaterialTheme.typography.headlineSmall)
Divider(modifier = Modifier
.padding(8.dp)
.width(316.dp))
OutlinedTextField(
value = term,
onValueChange = onTermValueChange,
placeholder = { Text(placeholderTerm) },
label = @Composable { Text(stringResource(R.string.term)) },
modifier = Modifier
.height(65.dp)
.width(300.dp),
readOnly = readOnly
)
OutlinedTextField(
value = definition,
onValueChange = onDefinitionValueChange,
placeholder = { Text(placeholderDef) },
label = @Composable { Text(stringResource(R.string.definition)) },
modifier = Modifier
.height(200.dp)
.width(300.dp),
readOnly = readOnly
)
}
@Composable
fun EntryDescription(
title: String,
term: String,
definition: String,
placeholderTerm: String,
placeholderDef: String
) {
Surface(modifier = Modifier.fillMaxSize()) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
EntryDescriptionWithFlag(
true,
title,
term,
{},
definition,
{},
placeholderTerm,
placeholderDef
)
}
}
}
@Preview(
showSystemUi = true,
uiMode = Configuration.UI_MODE_NIGHT_YES,
name = "DefaultPreviewDark"
)
@Preview(
showSystemUi = true,
uiMode = Configuration.UI_MODE_NIGHT_NO,
name = "DefaultPreviewLight"
)
@Composable
fun PreviewEntryDescription() {
LenguaTheme {
EntryDescription(
"Entry",
"the term",
"the definition",
"placeholder term",
"placeholder definition"
)
}
}
@Preview(
showSystemUi = true,
uiMode = Configuration.UI_MODE_NIGHT_YES,
name = "DefaultPreviewDarkPortrait"
)
@Preview(
showSystemUi = true,
uiMode = Configuration.UI_MODE_NIGHT_NO,
name = "DefaultPreviewLightPortrait"
)
@Composable
fun PreviewEditableEntryWithButtonPortrait() {
LenguaTheme {
EditableEntryWithButtonPortrait(
"Entry",
"the term",
{},
"the definition",
{},
{},
"Button",
"placeholder term",
"placeholder definition"
)
}
}
@Preview(
showSystemUi = true,
uiMode = Configuration.UI_MODE_NIGHT_YES,
name = "DefaultPreviewDarkLandscape",
device = "spec:orientation=landscape,width=411dp,height=891dp"
)
@Preview(
showSystemUi = true,
uiMode = Configuration.UI_MODE_NIGHT_NO,
name = "DefaultPreviewLightLandscape",
device = "spec:orientation=landscape,width=411dp,height=891dp"
)
@Composable
fun PreviewEditableEntryWithButtonLandscape() {
LenguaTheme {
EditableEntryWithButtonLandscape(
"Entry",
"the term",
{},
"the definition",
{},
{},
"Button",
"placeholder term",
"placeholder definition"
)
}
}
| 0
|
Kotlin
|
0
| 0
|
1b579b40922e9f2a3f509cf49c040396578957c3
| 6,554
|
lengua
|
MIT License
|
dcache/src/main/java/dora/db/exception/ConstraintException.kt
|
dora4
| 378,306,065
| false
|
{"Kotlin": 180368}
|
package dora.db.exception
/**
* Please check the constraint configuration.
* 简体中文:请检查约束配置。
*/
class ConstraintException(message: String) : RuntimeException(message)
| 2
|
Kotlin
|
3
| 30
|
782a37c8ff4464329a1d5cfc6aeb04550f4c5d2a
| 168
|
dcache-android
|
MIT License
|
src/test/kotlin/it/skrape/selects/html5/TextContentElementPickersKtTest.kt
|
djcass44
| 215,034,200
| true
|
{"Kotlin": 136261, "HTML": 1597}
|
package it.skrape.selects.html5
import it.skrape.aValidDocument
import it.skrape.selects.lastOccurrence
import org.junit.jupiter.api.Test
import strikt.api.expectThat
import strikt.assertions.isEqualTo
internal class TextContentElementPickersKtTest {
@Test
fun `can parse blockquote-tag`() {
val result = aValidDocument()
result.blockquote {
expectThat(text()).isEqualTo("i'm a quote")
}
}
@Test
fun `can parse dd-tag`() {
val result = aValidDocument()
result.dd {
expectThat(size).isEqualTo(2)
}
}
@Test
fun `can parse dir-tag`() {
val result = aValidDocument()
result.dir {
expectThat(size).isEqualTo(1)
}
}
@Test
fun `can parse dl-tag`() {
val result = aValidDocument()
result.dl {
expectThat(size).isEqualTo(1)
}
}
@Test
fun `can parse dt-tag`() {
val result = aValidDocument()
result.dt {
expectThat(size).isEqualTo(2)
}
}
@Test
fun `can parse figcaption-tag`() {
val result = aValidDocument()
result.figcaption {
expectThat(size).isEqualTo(1)
}
}
@Test
fun `can parse figure-tag`() {
val result = aValidDocument()
result.figure {
expectThat(size).isEqualTo(1)
}
}
@Test
fun `can parse hr-tag`() {
val result = aValidDocument()
result.hr {
expectThat(size).isEqualTo(2)
}
}
@Test
fun `can parse li-tag`() {
val result = aValidDocument()
result.li {
expectThat(size).isEqualTo(11)
}
}
@Test
fun `can parse ol-tag`() {
val result = aValidDocument()
result.ol {
expectThat(size).isEqualTo(1)
}
}
@Test
fun `can parse ul-tag`() {
val result = aValidDocument()
result.ul {
expectThat(size).isEqualTo(1)
}
}
@Test
fun `can parse p-tag`() {
val result = aValidDocument()
result.p {
lastOccurrence {
expectThat(text()).isEqualTo("i'm the last paragraph")
}
}
}
@Test
fun `can parse pre-tag`() {
val result = aValidDocument()
result.pre {
expectThat(text()).isEqualTo("i'm a pre")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
800935472219082c5cdf41e6070fa4b62c078447
| 2,449
|
skrape.it
|
MIT License
|
core/src/main/kotlin/com/hhs/koto/app/screen/BlankScreen.kt
|
XiaoGeNintendo
| 402,344,979
| true
|
{"Kotlin": 639984, "GLSL": 3181}
|
/*
* MIT License
*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.hhs.koto.app.screen
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.scenes.scene2d.actions.Actions.delay
import com.badlogic.gdx.scenes.scene2d.actions.Actions.sequence
import com.hhs.koto.util.SystemFlag
import com.hhs.koto.util.app
import com.hhs.koto.util.getRegion
class BlankScreen : BasicScreen(null, getRegion("ui/blank.png")) {
init {
background.color = Color.BLACK
}
override fun fadeIn(oldScreen: KotoScreen?, duration: Float) {
app.input.addProcessor(input)
blocker.isBlocking = false
state = ScreenState.FADING_IN
show()
st.root.clearActions()
st.root.color.a = 1f
st.root.addAction(sequence(delay(duration), Actions.run {
state = ScreenState.SHOWN
if (SystemFlag.redirect != null) {
if (SystemFlag.redirectDuration != null) {
app.setScreen(SystemFlag.redirect!!, SystemFlag.redirectDuration!!)
SystemFlag.redirectDuration = null
} else {
app.setScreen(SystemFlag.redirect!!)
}
SystemFlag.redirect = null
}
}))
}
override fun onQuit() = Unit
}
| 0
|
Kotlin
|
0
| 1
|
8be3871cdf6cd83cc32ed6d5c82cc2cc40c94ce7
| 2,428
|
TestSTG5
|
Creative Commons Zero v1.0 Universal
|
list/src/main/java/com/vip/list/adapter/MAdapter.kt
|
AbnerMing888
| 581,379,171
| false
|
{"Kotlin": 171916}
|
package com.vip.list.adapter
import com.vip.list.base.BaseMultipleItemAdapter
import com.vip.list.base.BaseViewHolder
import com.vip.list.data.BaseMultipleItem
import com.vip.list.listener.OnHeadOrFootConvertListener
import com.vip.list.listener.OnMultipleConvertListener
/**
*AUTHOR:AbnerMing
*DATE:2022/8/19
*INTRODUCE:多布局
*/
open class MAdapter : BaseMultipleItemAdapter() {
/**
* AUTHOR:AbnerMing
* INTRODUCE:数据操作
*/
override fun bindOperation(holder: BaseViewHolder, t: BaseMultipleItem?, position: Int) {
if (mOnMultipleConvertListener != null) {
mOnMultipleConvertListener?.bind(holder, t!!)
}
}
override fun dataOperationHead(holder: BaseViewHolder, position: Int) {
super.dataOperationHead(holder, position)
convertListener(holder, position)
}
override fun dataOperationFoot(holder: BaseViewHolder, position: Int) {
super.dataOperationFoot(holder, position)
convertListener(holder, position)
}
private fun convertListener(holder: BaseViewHolder, position: Int) {
if (mOnHeadOrFootConvertListener != null) {
mOnHeadOrFootConvertListener?.bind(holder, position)
}
}
/**
* AUTHOR:AbnerMing
* INTRODUCE:绑定头部或者尾部
*/
fun bindHeadOrFoot(block: BaseViewHolder.(position: Int) -> Unit) {
setHeadOrFootConvert(object : OnHeadOrFootConvertListener {
override fun bind(holder: BaseViewHolder, position: Int) {
block(holder, position)
}
})
}
/**
* AUTHOR:AbnerMing
* INTRODUCE:绑定数据
*/
fun bindData(block: BaseViewHolder.(t: BaseMultipleItem) -> Unit) {
setConvert(object : OnMultipleConvertListener {
override fun bind(holder: BaseViewHolder, t: BaseMultipleItem) {
block(holder, t)
}
})
}
/**
* AUTHOR:AbnerMing
* INTRODUCE:错误信息
*/
private var mException: ((Exception) -> Unit?)? = null
fun bindError(exception: (e: Exception) -> Unit) {
mException = exception
}
override fun bindViewHolderError(e: Exception) {
super.bindViewHolderError(e)
mException?.invoke(e)
}
private var mOnMultipleConvertListener: OnMultipleConvertListener? = null
private fun setConvert(mOnMultipleConvertListener: OnMultipleConvertListener) {
this.mOnMultipleConvertListener = mOnMultipleConvertListener
}
private var mOnHeadOrFootConvertListener: OnHeadOrFootConvertListener? = null
private fun setHeadOrFootConvert(mOnHeadOrFootConvertListener: OnHeadOrFootConvertListener) {
this.mOnHeadOrFootConvertListener = mOnHeadOrFootConvertListener
}
}
| 2
|
Kotlin
|
3
| 42
|
a91377c5b4ceb9cca29521ecc39413cb6324c2c5
| 2,746
|
VipList
|
Apache License 2.0
|
feature-crowdloan-impl/src/main/java/jp/co/soramitsu/feature_crowdloan_impl/di/customCrowdloan/moonbeam/MoonbeamContributionModule.kt
|
soramitsu
| 278,060,397
| false
| null |
package jp.co.soramitsu.feature_crowdloan_impl.di.customCrowdloan.moonbeam
import com.google.gson.FieldNamingPolicy
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoSet
import jp.co.soramitsu.common.data.network.HttpExceptionHandler
import jp.co.soramitsu.common.data.network.NetworkApiCreator
import jp.co.soramitsu.common.di.scope.FeatureScope
import jp.co.soramitsu.common.resources.ResourceManager
import jp.co.soramitsu.feature_account_api.data.extrinsic.ExtrinsicService
import jp.co.soramitsu.feature_account_api.domain.interfaces.AccountRepository
import jp.co.soramitsu.feature_account_api.domain.interfaces.SelectedAccountUseCase
import jp.co.soramitsu.feature_crowdloan_api.data.repository.CrowdloanRepository
import jp.co.soramitsu.feature_crowdloan_impl.data.network.api.moonbeam.MoonbeamApi
import jp.co.soramitsu.feature_crowdloan_impl.di.customCrowdloan.CustomContributeFactory
import jp.co.soramitsu.feature_crowdloan_impl.domain.contribute.custom.moonbeam.MoonbeamContributeInteractor
import jp.co.soramitsu.feature_crowdloan_impl.presentation.contribute.custom.moonbeam.MoonbeamContributeSubmitter
import jp.co.soramitsu.runtime.multiNetwork.ChainRegistry
@Module
class MoonbeamContributionModule {
@Provides
@FeatureScope
fun provideMoonbeamApi(networkApiCreator: NetworkApiCreator): MoonbeamApi = networkApiCreator.create(
service = MoonbeamApi::class.java,
customFieldNamingPolicy = FieldNamingPolicy.LOWER_CASE_WITH_DASHES
)
@Provides
@FeatureScope
fun provideMoonbeamInteractor(
moonbeamApi: MoonbeamApi,
httpExceptionHandler: HttpExceptionHandler,
resourceManager: ResourceManager,
accountRepository: AccountRepository,
crowdloanRepository: CrowdloanRepository,
service: ExtrinsicService,
chainRegistry: ChainRegistry
) = MoonbeamContributeInteractor(
moonbeamApi,
httpExceptionHandler,
resourceManager,
accountRepository,
crowdloanRepository,
service,
chainRegistry
)
@Provides
@FeatureScope
fun provideMoonbeamSubmitter(
interactor: MoonbeamContributeInteractor
) = MoonbeamContributeSubmitter(interactor)
@Provides
@FeatureScope
@IntoSet
fun provideMoonbeamFactory(
submitter: MoonbeamContributeSubmitter,
moonbeamInteractor: MoonbeamContributeInteractor,
resourceManager: ResourceManager,
accountUseCase: SelectedAccountUseCase
): CustomContributeFactory = MoonbeamContributeFactory(
submitter,
moonbeamInteractor,
resourceManager,
accountUseCase
)
}
| 4
|
Kotlin
|
14
| 55
|
d555e9cf4bd5f0abf8091781c237b6af9e1da850
| 2,689
|
fearless-Android
|
Apache License 2.0
|
Application/core/core-logger/src/main/java/com/istudio/core_logger/domain/LoggerFeature.kt
|
devrath
| 570,594,617
| false
|
{"Kotlin": 238294}
|
package com.istudio.core_logger.domain
interface LoggerFeature {
fun d(featureName: String?, msg: String?)
fun e(featureName: String?, msg: String?)
fun w(featureName: String?, msg: String?)
fun v(featureName: String?, msg: String?)
fun i(featureName: String?, msg: String?)
}
| 0
|
Kotlin
|
3
| 6
|
17d03b535e2ced992b97cc1e3a6d40c5393afded
| 298
|
Distance-Tracker
|
Apache License 2.0
|
app/src/main/java/com/starkbank/cocoatouch/foundation/NSArray.kt
|
starkbank
| 542,751,615
| false
|
{"Kotlin": 45758}
|
package com.starkbank.cocoatouch.foundation
open class NSArray<NSObject> : Iterable<NSObject> {
protected var array = ArrayList<NSObject>()
fun count(): Int {
return array.size
}
fun objectAtIndex(index: Int): NSObject {
return array[index]
}
override fun iterator(): Iterator<NSObject> {
return array.iterator()
}
fun lastObject(): NSObject? {
return if (array.isEmpty()) null else array[array.size - 1]
}
}
| 0
|
Kotlin
|
0
| 0
|
f857b1c8e97342024f12959cebd6b9182f903f29
| 483
|
cocoatouch-for-android
|
MIT License
|
app/src/main/kotlin/com/ashish/movieguide/ui/review/ReviewPresenter.kt
|
AshishKayastha
| 82,365,723
| false
| null |
package com.ashish.movieguide.ui.review
import com.ashish.movieguide.data.interactors.MovieInteractor
import com.ashish.movieguide.data.models.Review
import com.ashish.movieguide.ui.base.recyclerview.BaseRecyclerViewMvpView
import com.ashish.movieguide.ui.base.recyclerview.BaseRecyclerViewPresenter
import com.ashish.movieguide.utils.schedulers.BaseSchedulerProvider
import javax.inject.Inject
class ReviewPresenter @Inject constructor(
private val movieInteractor: MovieInteractor,
schedulerProvider: BaseSchedulerProvider
) : BaseRecyclerViewPresenter<Review, BaseRecyclerViewMvpView<Review>>(schedulerProvider) {
private var movieId: Long = 0L
fun setMovieId(movieId: Long) {
this.movieId = movieId
}
override fun getResultsObservable(type: String?, page: Int) = movieInteractor.getMovieReviews(movieId, page)
}
| 5
|
Kotlin
|
5
| 16
|
f455e468b917491fd1e35b07f70e9e9e2d00649d
| 860
|
Movie-Guide
|
Apache License 2.0
|
app/src/main/java/br/com/fiap/locawebmailapp/database/dao/AgendaConvidadoDao.kt
|
pedroferrarezzo
| 800,793,379
| false
|
{"Kotlin": 656574}
|
package br.com.fiap.locawebmailapp.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import br.com.fiap.locawebmailapp.model.AgendaConvidado
import br.com.fiap.locawebmailapp.model.AgendaCor
import br.com.fiap.locawebmailapp.model.IdConvidado
@Dao
interface AgendaConvidadoDao {
@Insert
fun criarAgendaConvidado(agendaConvidado: AgendaConvidado): Long
@Query("SELECT id_convidado FROM T_LCW_AGENDA_CONVIDADO WHERE id_agenda = :id_agenda")
fun listarIdConvidadoPorAgenda(id_agenda: Long): List<IdConvidado>
@Query("DELETE FROM T_LCW_AGENDA_CONVIDADO WHERE grupo_repeticao = :grupo_repeticao AND id_agenda != :id_agenda")
fun excluirPorGrupoRepeticaoExcetoIdAgenda(grupo_repeticao: Int, id_agenda: Long): Int
@Query("DELETE FROM T_LCW_AGENDA_CONVIDADO WHERE id_agenda = :id_agenda")
fun excluirPorIdAgenda(id_agenda: Long): Int
@Query("DELETE FROM T_LCW_AGENDA_CONVIDADO WHERE id_agenda = :id_agenda AND id_convidado = :id_convidado")
fun excluirPorIdAgendaEIdConvidado(id_agenda: Long, id_convidado: Long): Int
}
| 0
|
Kotlin
|
0
| 0
|
1c160310c5578ffdd386052788bb6774cef4f79f
| 1,101
|
LocaWeb-LocaMail-Kotlin-Compose-Challenge-Fiap
|
MIT License
|
app/src/main/java/com/kl3jvi/animity/ui/fragments/notifications/NotificationViewModel.kt
|
kl3jvi
| 286,457,139
| false
| null |
package com.kl3jvi.animity.ui.fragments.notifications
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.kl3jvi.animity.domain.repositories.NotificationsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
@HiltViewModel
class NotificationViewModel @Inject constructor(
notificationsRepository: NotificationsRepository
) : ViewModel() {
val notifications = notificationsRepository
.getNotifications()
.cachedIn(viewModelScope)
.stateIn(
viewModelScope,
SharingStarted.WhileSubscribed(5_000),
PagingData.empty()
)
}
| 2
|
Kotlin
|
30
| 671
|
bca166eb23b148eaff25caa770f03c908502ed35
| 817
|
animity
|
MIT License
|
plugin/src/main/kotlin/com/firsttimeinforever/intellij/pdf/viewer/settings/PdfViewerInvertColorsListener.kt
|
FirstTimeInForever
| 245,457,194
| false
|
{"Kotlin": 174520, "HTML": 794, "CSS": 460, "JavaScript": 29}
|
package com.firsttimeinforever.intellij.pdf.viewer.settings
import com.intellij.openapi.editor.colors.EditorColorsListener
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.ui.ColorUtil
class PdfViewerInvertColorsListener : EditorColorsListener {
override fun globalSchemeChange(scheme: EditorColorsScheme?) {
if (PdfViewerSettings.instance.invertColorsWithTheme) {
val backGround = scheme?.defaultBackground ?: return
PdfViewerSettings.instance.invertDocumentColors = ColorUtil.isDark(backGround)
PdfViewerSettings.instance.notifyListeners()
}
}
}
| 12
|
Kotlin
|
18
| 85
|
6c7c3b43371404aa0089429076567c83f133124e
| 612
|
intellij-pdf-viewer
|
MIT License
|
app/src/test/java/com/abdoul/felinelove/utils/BaseUnitTest.kt
|
Abdoul02
| 372,765,904
| false
| null |
package com.abdoul.felinelove.utils
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.Rule
@ExperimentalCoroutinesApi
open class BaseUnitTest {
@get:Rule
var coroutinesTestRule = MainCoroutineScopeRule()
@get:Rule
val instantTaskExecutorRule =
InstantTaskExecutorRule() //Allows execution of LiveData to happen instantly
}
| 0
| null |
0
| 0
|
3ea63eb8e6b804db47190961d9a2007572812029
| 436
|
FelineLove
|
Apache License 2.0
|
src/main/kotlin/walkmc/serializer/common/Files.kt
|
rona-tombo
| 463,865,654
| false
| null |
/*
MIT License
Copyright (c) 2021 uin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
@file:Suppress("NOTHING_TO_INLINE")
package walkmc.serializer.common
import walkmc.serializer.*
import walkmc.serializer.tag.*
import java.io.*
/**
* Converts this file to a yaml serial file.
*/
inline fun <reified T : Any> File.asYaml() = createYamlFile(this, T::class)
/**
* Converts this file to a json serial file.
*/
inline fun <reified T : Any> File.asJson() = createJsonFile(this, T::class)
/**
* Converts this file to a protobuf serial file.
*/
inline fun <reified T : Any> File.asProtobuf() = createProtobufFile(this, T::class)
/**
* Converts this file to a nbt serial file.
*/
inline fun <reified T : Any> File.asNBT() = createNBTFile(this, T::class)
/**
* Converts this file to a yaml folder.
*/
inline fun <reified T : Any> File.asYamlFolder() = createYamlFolder(this, T::class)
/**
* Converts this file to a json folder.
*/
inline fun <reified T : Any> File.asJsonFolder() = createJsonFolder(this, T::class)
/**
* Converts this file to a protobuf folder.
*/
inline fun <reified T : Any> File.asProtobufFolder() = createProtobufFolder(this, T::class)
/**
* Converts this file to a NBT folder.
*/
inline fun <reified T : Any> File.asNBTFolder() = createNBTFolder(this, T::class)
/**
* Converts this file to a mark file.
*/
inline fun File.toMark() = TaggedFile(this)
/**
* List all files from this file directory.
*/
fun File.files(): List<File> = listFiles()?.toList() ?: emptyList()
/**
* List all files from this file directory filtered by the given [filter].
*/
fun File.files(filter: File.() -> Boolean): List<File> = listFiles(filter)?.toList() ?: emptyList()
/**
* List all directories from this file directory.
*/
fun File.directories(): List<File> = files { isDirectory }
/**
* List all directories from this file directory filtered by the given [filter].
*/
fun File.directories(filter: File.() -> Boolean): List<File> = files { isDirectory && filter() }
| 0
| null |
0
| 0
|
1580bc39a19a43741e76f598c97521fc9491b96b
| 3,037
|
serializer-framework
|
MIT License
|
library/src/main/java/com/chrynan/chords/parcel/UnexpectedParcelValueException.kt
|
bakhbk
| 236,358,693
| true
|
{"Kotlin": 51046}
|
package com.chrynan.chords.parcel
class UnexpectedParcelValueException(private val value: Any?) : RuntimeException("Unexpected parcel value. value = $value")
| 0
| null |
0
| 0
|
6fa018378e5905c44ed09bfe368558cc650cb532
| 158
|
chords
|
Apache License 2.0
|
android/src/main/java/io/github/ackeecz/extensions/android/DrawableExtensions.kt
|
AckeeCZ
| 130,711,681
| false
| null |
package io.github.ackeecz.extensions.android
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.RippleDrawable
import android.graphics.drawable.StateListDrawable
import androidx.annotation.ColorInt
import androidx.core.graphics.ColorUtils
// Extensions for creating drawables and other drawable-related helpers
/**
* Create a drawable programmatically with optional properties. When [isButton] defined as
* true result is a drawable with ripple effect.
*
* @param color - color of a drawable
* @param isButton - wheter drawable should respond to pressed state
* @param checkedColor - color of checked state
* @param pressedColor - color of pressed state
* @param focusedColor - color of focused state
* @param disabledColor - color of a disabled state
* @param mask - mask drawable applied on a result ripple drawable.
* @param radius - corner radius in px
* @param strokeColor - color of a stroke effect
* @param strokeWidth - width of a stroke effect
* @param topLeftRadius - top left corner radius
* @param topRightRadius - top right corner radius
* @param bottomLeftRadius - bottom left corner radius
* @param bottomRightRadius - bottom right corner radius
*/
fun backgroundDrawable(
@ColorInt color: Int,
isButton: Boolean = false,
@ColorInt checkedColor: Int = color,
@ColorInt pressedColor: Int = color.toPressedColor(),
@ColorInt focusedColor: Int = color,
@ColorInt disabledColor: Int = color,
mask: Drawable? = null,
radius: Number = 0f,
strokeColor: Int = Color.TRANSPARENT,
strokeWidth: Int = 0,
topLeftRadius: Number = 0f,
topRightRadius: Number = 0f,
bottomLeftRadius: Number = 0f,
bottomRightRadius: Number = 0f
): Drawable {
val baseDrawable = StateListDrawable().apply {
addState(intArrayOf(-android.R.attr.state_enabled), GradientDrawable().apply {
setCornerRadius(radius, topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius)
setColor(disabledColor)
setStroke(strokeWidth, strokeColor)
})
addState(intArrayOf(android.R.attr.state_focused), GradientDrawable().apply {
setCornerRadius(radius, topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius)
setColor(focusedColor)
setStroke(strokeWidth, strokeColor)
})
addState(intArrayOf(android.R.attr.state_checked), GradientDrawable().apply {
setCornerRadius(radius, topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius)
setColor(checkedColor)
setStroke(strokeWidth, strokeColor)
})
addState(intArrayOf(), GradientDrawable().apply {
setCornerRadius(radius, topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius)
setColor(color)
setStroke(strokeWidth, strokeColor)
})
}
if (!isButton) return baseDrawable
// set pressed state only if isButton = true
return RippleDrawable(ColorStateList.valueOf(pressedColor), baseDrawable, mask)
}
private fun Int.toPressedColor(): Int {
return if (isDarkColor(this)) {
toLighterColor()
} else {
toDarkerColor()
}
}
private fun isDarkColor(color: Int): Boolean {
return ColorUtils.calculateLuminance(color) < 0.15
}
/**
* Convert color to lighter shade
*/
fun Int.toLighterColor(): Int {
val hsv = floatArrayOf(0f, 0f, 0f)
Color.colorToHSV(this, hsv)
hsv[2] = 0.2f + 0.8f * hsv[2];
return Color.HSVToColor(hsv)
}
/**
* Convert color to darker shade
*/
fun Int.toDarkerColor(): Int {
val hsv = floatArrayOf(0f, 0f, 0f)
Color.colorToHSV(this, hsv)
hsv[2] *= 0.8f
return Color.HSVToColor(hsv)
}
private fun GradientDrawable.setCornerRadius(
radius: Number,
topLeftRadius: Number = 0f,
topRightRadius: Number = 0f,
bottomLeftRadius: Number = 0f,
bottomRightRadius: Number = 0f
) {
if (radius != 0f) {
cornerRadius = radius.toFloat()
} else {
cornerRadii = floatArrayOf(
topLeftRadius.toFloat(), topLeftRadius.toFloat(),
topRightRadius.toFloat(), topRightRadius.toFloat(),
bottomRightRadius.toFloat(), bottomRightRadius.toFloat(),
bottomLeftRadius.toFloat(), bottomLeftRadius.toFloat()
)
}
}
/**
* Create a [ColorStateList] programmatically
*/
fun colorStateList(
@ColorInt normalColor: Int,
@ColorInt checkedColor: Int? = null,
@ColorInt selectedColor: Int? = null,
@ColorInt disabledColor: Int? = null,
@ColorInt pressedColor: Int? = null,
@ColorInt focusedColor: Int? = null
): ColorStateList {
val states = mapOf(
intArrayOf(-android.R.attr.state_enabled) to disabledColor,
intArrayOf(android.R.attr.state_pressed) to pressedColor,
intArrayOf(android.R.attr.state_checked) to checkedColor,
intArrayOf(android.R.attr.state_selected) to selectedColor,
intArrayOf(android.R.attr.state_focused) to focusedColor,
intArrayOf() to normalColor
).filterValues { it != null }
return ColorStateList(states.keys.toTypedArray(), states.values.map { it!!.toInt() }.toIntArray())
}
| 1
|
Kotlin
|
0
| 13
|
fc56c5c9aba5582f203334a6ab09b198cdc9596c
| 5,330
|
kotlin-extensions
|
Apache License 2.0
|
restrikt-compiler-plugin/src/main/kotlin/com/zwendo/restrikt/plugin/backend/RestriktClassBuilder.kt
|
ZwenDo
| 516,460,376
| false
| null |
package com.zwendo.restrikt.plugin.backend
import com.zwendo.restrikt.plugin.backend.symbol.RestriktClassBuildingContext
import com.zwendo.restrikt.plugin.backend.visitor.RestriktClassVisitor
import com.zwendo.restrikt.plugin.backend.visitor.RestriktClassVisitorProxy
import com.zwendo.restrikt.plugin.backend.visitor.RestriktFieldVisitor
import com.zwendo.restrikt.plugin.backend.visitor.RestriktMetadataVisitor
import com.zwendo.restrikt.plugin.backend.visitor.RestriktMethodVisitor
import com.zwendo.restrikt.plugin.backend.visitor.RestriktRecordComponentVisitor
import org.jetbrains.kotlin.codegen.ClassBuilder
import org.jetbrains.kotlin.codegen.DelegatingClassBuilder
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.org.objectweb.asm.AnnotationVisitor
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.FieldVisitor
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.RecordComponentVisitor
internal class RestriktClassBuilder(private val original: ClassBuilder) : DelegatingClassBuilder() {
override fun getDelegate(): ClassBuilder = original
override fun getVisitor(): ClassVisitor {
val classData = RestriktClassBuildingContext.currentClassData
// the following if aims to avoid infinite queueing, in the case of the RestriktClassVisitor tries to call
// methods from the original visitor (e.g. avoid infinite annotation queueing)
return if (classData.isWritten) { // most common case, class containing at least 1 symbol
RestriktClassVisitorProxy(classData, original.visitor)
} else { // empty interface/annotation class
RestriktClassVisitor(classData)
}
}
override fun newMethod(
origin: JvmDeclarationOrigin,
access: Int,
name: String,
desc: String,
signature: String?,
exceptions: Array<out String>?,
): MethodVisitor {
val data = RestriktClassBuildingContext.methodData(origin.descriptor, access) {
super.newMethod(origin, it, name, desc, signature, exceptions)
}
return RestriktMethodVisitor(data)
}
override fun newField(
origin: JvmDeclarationOrigin,
access: Int,
name: String,
desc: String,
signature: String?,
value: Any?,
): FieldVisitor {
val data = RestriktClassBuildingContext.fieldData(origin.descriptor, access) {
super.newField(origin, it, name, desc, signature, value)
}
return RestriktFieldVisitor(data)
}
override fun visitInnerClass(name: String, outerName: String?, innerName: String?, access: Int) {
RestriktClassBuildingContext.onStartWritingPartWithoutData()
val actualAccess = RestriktClassBuildingContext.classAccess(name, access)
super.visitInnerClass(name, outerName, innerName, actualAccess)
}
override fun defineClass(
origin: PsiElement?,
version: Int,
access: Int,
name: String,
signature: String?,
superName: String,
interfaces: Array<out String>,
) = RestriktClassBuildingContext.createClassData(original, name, access) {
super.defineClass(origin, version, it, name, signature, superName, interfaces)
original.visitor
}
override fun newRecordComponent(name: String, desc: String, signature: String?): RecordComponentVisitor {
val data = RestriktClassBuildingContext.recordComponentData {
super.newRecordComponent(name, desc, signature)
}
return RestriktRecordComponentVisitor(data)
}
override fun newAnnotation(desc: String, visible: Boolean): AnnotationVisitor {
// most common case, class containing at least 1 symbol and has already been written, so we do not need to
// parse the metadata
if (RestriktClassBuildingContext.currentClassData.isWritten) {
return super.newAnnotation(desc, visible)
}
// we must parse the metadata to gather the information about the class, as it has an empty body, meaning that
// we did not have the possibility to retrieve its descriptor
val data = RestriktClassBuildingContext.metadataProxyData {
super.newAnnotation(desc, visible)
}
return RestriktMetadataVisitor(RestriktClassBuildingContext.currentClassData, data)
}
override fun done() = RestriktClassBuildingContext.done()
}
| 0
|
Kotlin
|
0
| 21
|
13010dd4733eb385062ca260849d2e0ee52a3c65
| 4,599
|
Restrikt
|
MIT License
|
app/src/main/java/com/sunkitto/news/NewsApp.kt
|
sunkitto
| 663,131,959
| false
| null |
package com.sunkitto.news
import android.app.Application
import android.content.Context
import android.os.StrictMode
import androidx.fragment.app.strictmode.FragmentStrictMode
import com.sunkitto.news.all_news.di.AllNewsDependencyStore
import com.sunkitto.news.di.AppComponent
import com.sunkitto.news.di.DaggerAppComponent
import com.sunkitto.news.feature.settings.di.SettingsDependencyStore
import com.sunkitto.news.feature.top_headlines.di.TopHeadlinesDependencyStore
class NewsApp : Application() {
val appComponent: AppComponent by lazy {
DaggerAppComponent.builder()
.applicationContext(this.applicationContext)
.apiKey(BuildConfig.API_KEY)
.build()
}
override fun onCreate() {
TopHeadlinesDependencyStore.dependencies = appComponent
AllNewsDependencyStore.dependencies = appComponent
SettingsDependencyStore.dependencies = appComponent
if (BuildConfig.DEVELOPER_MODE) {
FragmentStrictMode.defaultPolicy =
FragmentStrictMode.Policy.Builder()
.detectFragmentReuse()
.detectFragmentTagUsage()
.detectRetainInstanceUsage()
.detectSetUserVisibleHint()
.detectTargetFragmentUsage()
.detectWrongFragmentContainer()
.build()
StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.detectCustomSlowCalls()
.build(),
)
StrictMode.setVmPolicy(
StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build(),
)
}
super.onCreate()
}
}
val Context.appComponent: AppComponent
get() = when (this) {
is NewsApp -> appComponent
else -> applicationContext.appComponent
}
| 0
|
Kotlin
|
0
| 0
|
dc8f6e99b95aae50b3013f19bc36b75b110f7e3f
| 2,176
|
News
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.