path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
โ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/luizcampos/downloadimage/repository/AndroidDownloadService.kt | luizcamposmc | 592,121,832 | false | null | package com.luizcampos.downloadimage.repository
import android.app.DownloadManager
import android.content.Context
import android.os.Environment
import androidx.core.net.toUri
class AndroidDownloadService (
private val context: Context
) : DownloaderRepository {
private val downloadManager = context
.getSystemService(DownloadManager::class.java)
override fun downloadFile(url: String): Long {
val request = DownloadManager.Request(url.toUri())
.setMimeType("image/jpeg")
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setTitle("image.jpg")
.addRequestHeader("Authorization", "Bearer <token>")
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "image.jpg")
return downloadManager.enqueue(request)
}
} | 0 | Kotlin | 0 | 0 | 27bfa264c5770109d01d3ca65f5588cd7f30f3c2 | 940 | DownloadImage | Apache License 2.0 |
app/src/main/java/com/davion/github/paging/ui/repo/ReposFragment.kt | dragonddavion | 291,616,804 | false | null | package com.davion.github.paging.ui.repo
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.DividerItemDecoration
import com.davion.github.paging.R
import com.davion.github.paging.databinding.FragmentReposBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
@AndroidEntryPoint
class ReposFragment : Fragment() {
private lateinit var binding: FragmentReposBinding
private val viewModel: RepoViewModel by viewModels()
private var repoJob: Job? = null
private val adapter: ReposAdapter by lazy { ReposAdapter() }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_repos, container, false)
initRecyclerView()
initData()
return binding.root
}
private fun initData() {
repoJob?.cancel()
repoJob = lifecycleScope.launch {
viewModel.getRepositories().collectLatest {
adapter.submitData(it)
}
}
lifecycleScope.launch {
adapter.loadStateFlow
.distinctUntilChangedBy {
it.refresh
}.filter {
it.refresh is LoadState.NotLoading
}.collect {
binding.repositoryList.scrollToPosition(0)
}
}
binding.retryButton.setOnClickListener {
adapter.retry()
}
}
private fun initRecyclerView() {
binding.repositoryList.adapter = adapter.withLoadStateHeaderAndFooter(
header = ReposLoadStateAdapter { adapter.retry() },
footer = ReposLoadStateAdapter { adapter.retry() }
)
adapter.addLoadStateListener { loadState ->
binding.repositoryList.isVisible = loadState.source.refresh is LoadState.NotLoading
binding.progressBar.isVisible = loadState.source.refresh is LoadState.Loading
binding.retryButton.isVisible = loadState.source.refresh is LoadState.Error
val errorState = loadState.source.append as? LoadState.Error
?: loadState.source.prepend as? LoadState.Error
?: loadState.append as? LoadState.Error
?: loadState.prepend as? LoadState.Error
errorState?.let {
Toast.makeText(requireContext(), "\uD83D\uDE28 Wooops ${it.error}", Toast.LENGTH_LONG).show()
}
}
lifecycleScope.launch {
adapter.loadStateFlow
.distinctUntilChangedBy { it.refresh }
.filter { it.refresh is LoadState.NotLoading }
.collect { binding.repositoryList.scrollToPosition(0) }
}
val decoration =
DividerItemDecoration(this.requireContext(), DividerItemDecoration.VERTICAL)
binding.repositoryList.addItemDecoration(decoration)
}
override fun onDestroyView() {
super.onDestroyView()
repoJob?.cancel()
}
}
| 0 | Kotlin | 0 | 0 | f7ffe65edbbc7ab76b8995c98ab01c08f93dcb87 | 3,654 | github-paging | Apache License 2.0 |
src/main/kotlin/br/com/zup/osmarjunior/clients/response/CreatePixKeyResponse.kt | osmar-jr | 409,735,103 | true | {"Kotlin": 85153} | package br.com.zup.osmarjunior.clients.response
data class CreatePixKeyResponse(
val keyType: String,
val key: String,
val bankAccount: BankAccountResponse,
val owner: OwnerResponse,
val createdAt: String
)
| 0 | Kotlin | 0 | 0 | 7f9afdcd60f7f329c590e1cbf3cd1980243fdb27 | 228 | orange-talents-07-template-pix-keymanager-grpc | Apache License 2.0 |
botalka/src/main/kotlin/ru/vityaman/lms/botalka/core/security/auth/TokenGuard.kt | vityaman-edu | 762,733,310 | false | {"Kotlin": 222074, "Shell": 4101, "Python": 1261, "Dockerfile": 66} | package ru.vityaman.lms.botalka.core.security.auth
import ru.vityaman.lms.botalka.core.exception.AuthenticationException
import ru.vityaman.lms.botalka.core.exception.orNotFound
import ru.vityaman.lms.botalka.core.logic.UserService
import ru.vityaman.lms.botalka.core.model.User
sealed class Authentication {
data object Monitoring : Authentication()
data class Fuzzer(val user: User) : Authentication()
data class Client(val user: User) : Authentication()
}
interface TokenGuard {
suspend fun authenticate(token: AccessToken): Authentication?
}
class MonitoringTokenGuard(private val reference: String) : TokenGuard {
override suspend fun authenticate(token: AccessToken): Authentication? =
if (token.text == reference) {
Authentication.Monitoring
} else {
null
}
}
class FuzzerTokenGuard(
private val reference: String,
private val users: Collection<User>,
) : TokenGuard {
override suspend fun authenticate(token: AccessToken): Authentication? =
if (token.text == reference) {
Authentication.Fuzzer(users.random())
} else {
null
}
}
class JwtClientTokenGuard(
private val tokens: TokenService,
private val users: UserService,
) : TokenGuard {
override suspend fun authenticate(token: AccessToken): Authentication {
val payload = tokens.decode(token)
val user = users.getById(payload.userId)
.orNotFound("user with id ${payload.userId}")
return Authentication.Client(user)
}
}
class CombinedTokenGuard(vararg guards: TokenGuard) : TokenGuard {
private val guards = guards.toList()
override suspend fun authenticate(token: AccessToken): Authentication {
for (guard in guards) {
val auth = guard.authenticate(token)
if (auth != null) {
return auth
}
}
throw AuthenticationException("Unknown authentication token kind")
}
}
| 28 | Kotlin | 0 | 3 | 116a85bd8576e679a02598a92749f2f23c8be20e | 1,999 | lms | Apache License 2.0 |
app/src/main/java/com/aayushpuranik/todolist/data/repository/RegistrationRepository.kt | dev-aayushpuranik | 871,340,204 | false | {"Kotlin": 9913} | package com.aayushpuranik.todolist.data.repository
import com.aayushpuranik.todolist.data.db.RegistrationDatabase
import com.aayushpuranik.todolist.domain.model.Person
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
class RegistrationRepository @Inject constructor(val registrationDatabase: RegistrationDatabase) {
fun savePersonDetails(person: Person) {
CoroutineScope(Dispatchers.IO).launch {
registrationDatabase.registrationDao().insert(person)
Result.success(Unit)
}
}
fun getPersonFromDB(callback: (Person) -> Unit) {
CoroutineScope(Dispatchers.IO).launch {
registrationDatabase.registrationDao().getPersons()?.let { callback(it) }
}
}
} | 0 | Kotlin | 0 | 0 | a01a6b79e533ad68c7d83b82bcf89fc080da700b | 860 | ToDoList | Apache License 2.0 |
api/src/main/kotlin/nebulosa/api/sequencer/SequenceJobExecutor.kt | tiagohm | 568,578,345 | false | {"Kotlin": 1439041, "TypeScript": 246001, "HTML": 125856, "SCSS": 4922, "JavaScript": 1164} | package nebulosa.api.sequencer
import nebulosa.indi.device.Device
interface SequenceJobExecutor<in T, J : SequenceJob> : Iterable<J> {
fun execute(request: T): J
fun sequenceJobFor(vararg devices: Device): J? {
fun find(task: J): Boolean {
for (i in devices.indices) {
if (i >= task.devices.size || task.devices[i].name != devices[i].name) {
return false
}
}
return true
}
return findLast(::find)
}
fun sequenceJobWithId(jobId: Long): J? {
return find { it.jobId == jobId }
}
}
| 0 | Kotlin | 0 | 1 | 8a281b5e158104ad93a1aa19a5a584fbead57f73 | 625 | nebulosa | MIT License |
bones/src/main/java/pro/horovodovodo4ka/bones/ui/ScreenInterface.kt | horovodovodo4ka | 123,154,278 | false | null | package pro.horovodovodo4ka.bones.ui
import pro.horovodovodo4ka.bones.Phalanx
/**
* Semantic alias for fragments. Describes fragments which represents view that takes whole page/screen.
*/
interface ScreenInterface<T : Phalanx> : FragmentSibling<T> | 0 | Kotlin | 2 | 12 | dcf5e6349ecb11871e3706c3087113c85b49d402 | 252 | bones | The Unlicense |
app/src/main/java/com/inging/notis/data/room/entity/NotiInfo.kt | prdotk | 372,680,673 | false | null | package com.inging.notis.data.room.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* Created by annasu on 2021/04/26.
* https://developer.android.com/reference/android/app/Notification
*/
@Entity(ignoredColumns = ["isChecked"])
data class NotiInfo(
@PrimaryKey(autoGenerate = true)
val notiId: Long = 0,
// StatusBarNotification key
var key: String = "",
// ์นดํ
๊ณ ๋ฆฌ
var category: String = "",
// ํจํค์ง ๋ค์
var pkgName: String = "",
// ์ ์ฅ ์๊ฐ
var timestamp: Long = -1,
// ํ์ดํ, ์นดํก์ ๊ฒฝ์ฐ ๋ณด๋ธ ์ฌ๋
var title: String = "",
// ๋ด์ฉ
var text: String = "",
// ์๋ธ ํ
์คํธ, ์นดํก์ ๊ฒฝ์ฐ ๊ทธ๋ฃน๋ช
var subText: String = "",
// ๋
ธํฐ ๊ทธ๋ฃน ๊ด๋ จ ์ ๋ณด, ์นดํก์ ๊ฒฝ์ฐ ๊ทธ๋ฃน๋ช
var summaryText: String = "",
// ์์ด์ฝ, ํ์ฌ ์ฌ์ฉ ์ํจ
var icon: Int = 0,
// ๋ผ์ง ์์ด์ฝ ํ์ผ ๊ฒฝ๋ก, ์บ์์ ํ์ผ๋ก ์ ์ฅ๋จ
var largeIcon: String = "",
// ํฝ์ณ ํ์ผ ๊ฒฝ๋ก, ์บ์์ ํ์ผ๋ก ์ ์ฅ๋จ
var picture: String = "",
// ๋ฐฑ๊ทธ๋ผ์ด๋ ์ด๋ฏธ์ง ํ์ผ ๊ฒฝ๋ก, ์บ์์ ํ์ผ๋ก ์ ์ฅ๋จ
var bgImage: String = "",
// 0: ๋ฐ์ ๋ฉ์์ง, 1: ๋ณด๋ธ ๋ฉ์์ง, 90: ํค๋
val senderType: Int,
// ์์ฝ์ ๋
ธํฐ ๊ตฌ๋ถ, ๋ฉ์์ง ์๋ ๋
ธํฐ๋ง ์ฌ์ฉ
// true: ์์ฝ์, false: ์ฝ์
var unread: Boolean = true,
// undo ๊ตฌํ์ํด ์ฌ์ฉ
var deleted: Boolean = false
) : IgnoreInfo() | 0 | Kotlin | 0 | 0 | 15101b8f1a844adc892c2b4ce04a39790b41738d | 1,212 | notis | MIT License |
corelib/src/main/java/dk/mustache/corelib/utils/PixelUtil.kt | mustachedk | 181,449,514 | false | null | package dk.mustache.corelib.utils
import android.content.res.Resources
/**
* Convert Pixels (px) to Density Pixels (dp)
*/
fun Int.toDp(): Int = (this / Resources.getSystem().displayMetrics.density).toInt()
/**
* Convert Density Pixels (dp) to Pixels (px)
*/
fun Int.toPx(): Int = (this * Resources.getSystem().displayMetrics.density).toInt()
/**
* Convert Pixels (px) to Density Pixels (dp)
*/
fun Float.toDp(): Float = (this / Resources.getSystem().displayMetrics.density)
/**
* Convert Density Pixels (dp) to Pixels (px)
*/
fun Float.toPx(): Float = (this * Resources.getSystem().displayMetrics.density)
| 0 | Kotlin | 1 | 1 | e87d3452ef8e456960ce3624a3b0dd4d650c6d06 | 620 | core-lib-an | MIT License |
src/main/kotlin/Day03.kt | Vampire | 572,990,104 | false | {"Kotlin": 57326} | fun main() {
val priorities = ('a'..'z') + ('A'..'Z')
fun part1(input: List<String>) = input
.flatMap {
it
.chunkedSequence(it.length / 2)
.map(String::toCharArray)
.reduce { a, b -> a.intersect(b.asIterable().toSet()).toCharArray() }
.map(priorities::indexOf)
.map(Int::inc)
}
.sum()
fun part2(input: List<String>) = input
.asSequence()
.chunked(3)
.flatMap {
it
.asSequence()
.map(String::toCharArray)
.reduce { a, b -> a.intersect(b.asIterable().toSet()).toCharArray() }
.map(priorities::indexOf)
.map(Int::inc)
}
.sum()
val testInput = readStrings("Day03_test")
check(part1(testInput) == 157)
val input = readStrings("Day03")
println(part1(input))
check(part2(testInput) == 70)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f | 995 | aoc-2022 | Apache License 2.0 |
core/src/main/kotlin/spp/jetbrains/status/SourceStatus.kt | sourceplusplus | 173,253,271 | false | null | /*
* Source++, the continuous feedback platform for developers.
* Copyright (C) 2022-2024 CodeBrig, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package spp.jetbrains.status
import spp.jetbrains.icons.PluginIcons
import javax.swing.Icon
/**
* Represents the current status of the Source++ plugin.
*
* @author [<NAME>](mailto:<EMAIL>)
*/
enum class SourceStatus(val ephemeral: Boolean = false) {
Enabled,
Disabled,
Pending,
PluginsLoaded(true),
Connected,
ConnectionError,
WaitingForService,
ServiceEstablished;
val icon: Icon
get() {
return when {
isReady -> PluginIcons.statusEnabled
isDisabled -> PluginIcons.statusDisabled
isFailed -> PluginIcons.statusFailed
else -> PluginIcons.statusPending
}
}
val presentableText: String
get() {
return when (this) {
Disabled -> "Click to enable Source++"
Pending -> "Booting Source++"
Connected -> "Connection established"
WaitingForService -> "Waiting for active service"
ConnectionError -> "Connection error"
PluginsLoaded -> "Plugins loaded"
else -> "Click to disable Source++"
}
}
val disposedPlugin: Boolean
get() = this in DISPOSED_STATUSES
val isFailed: Boolean
get() = this in FAILED_STATUSES
val isConnected: Boolean
get() = this in CONNECTED_STATUSES
val isEnabled: Boolean
get() = !isDisabled
val isDisabled: Boolean
get() = this == Disabled
val isReady: Boolean
get() = this in READY_STATUSES
companion object {
val READY_STATUSES = setOf(ServiceEstablished)
val CONNECTED_STATUSES = READY_STATUSES + setOf(PluginsLoaded, Pending, Connected, WaitingForService)
val DISPOSED_STATUSES = setOf(Disabled, ConnectionError)
val FAILED_STATUSES = setOf(ConnectionError)
}
}
| 14 | null | 13 | 87 | 199006a410529d961dc184f0740a5d845bd87899 | 2,567 | interface-jetbrains | Apache License 2.0 |
jpa2.0-rxjava2/src/test/kotlin/hibernate/RxPersistenceSpec.kt | eraga | 132,671,655 | false | {"Gradle": 4, "Shell": 2, "Text": 1, "Ignore List": 1, "Batchfile": 1, "AsciiDoc": 1, "YAML": 1, "INI": 3, "XML": 5, "Kotlin": 73, "Java Properties": 1, "Java": 1} | package hibernate
import TestSubject
import net.eraga.jpa.async.RxPersistence
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.subject.SubjectSpek
import java.util.*
import javax.persistence.EntityManagerFactory
import javax.persistence.PersistenceUtil
import kotlin.test.assertFails
import kotlin.test.assertTrue
/**
* Date: 08/05/2018
* Time: 18:16
*/
object RxPersistenceSpec : SubjectSpek<TestSubject>({
subject { TestSubject("H2 Hibernate") }
given("$subject persistence unit") {
on("createEntityManagerFactory ") {
it("should create with with persistenceUnitName") {
val emf = RxPersistence
.createEntityManagerFactory(subject.persistenceUnit)
.blockingGet()
val success = emf is EntityManagerFactory
if (success) emf.close()
assertTrue { success }
}
it("should create with with persistenceUnitName and properties") {
val properties = Properties()
properties.setProperty("javax.persistence.jdbc.url", "jdbc:h2:mem:test")
val emf = RxPersistence
.createEntityManagerFactory(
subject.persistenceUnit,
properties
)
.blockingGet()
val success = emf is EntityManagerFactory
if (success) emf.close()
assertTrue { success }
}
it("should fail with with wrong url in properties") {
if (!(subject.persistenceUnit.contains("eclipselink", true)
|| subject.persistenceUnit.contains("openjpa", true))) {
// Skip old EclipseLink // OpenJpa as they fail this test.
// Fuck legacy standards anyway.
assertFails {
val properties = Properties()
properties.setProperty("javax.persistence.jdbc.url", "test_url")
RxPersistence
.createEntityManagerFactory(
subject.persistenceUnit,
properties
)
.blockingGet()
}
}
}
}
on("getPersistenceUtil") {
it("should return PersistenceUtil") {
assertTrue {
// This can't break, but we live in the world full of magic ^_^
// ะะถัั
ะธ ะฟะธะทะดะตั...
@Suppress("USELESS_IS_CHECK")
RxPersistence.getPersistenceUtil() is PersistenceUtil
}
}
}
}
afterGroup {
// System.exit(0)
}
})
| 0 | Kotlin | 1 | 3 | a515723d7023393d3438006bd44ac83b4296de00 | 3,022 | async-jpa | Apache License 2.0 |
data/src/main/java/com/bstudio/data/service/GitHubService.kt | binhbk230 | 511,929,225 | false | {"Kotlin": 21549} | package com.bstudio.data.service
import com.bstudio.data.response.UserInfoResponse
import retrofit2.http.GET
import retrofit2.http.Path
interface GitHubService {
@GET("users/{user}")
suspend fun getUserInfo(@Path(value = "user", encoded = true) user: String): UserInfoResponse
} | 0 | Kotlin | 0 | 2 | 90b929738ebb1bfa8beb5994f81b6faae6402bd7 | 288 | MVVM-Clean-Architecture | MIT License |
src/test/kotlin/me/fornever/todosaurus/toDoItemTests/IsReadyTests.kt | ForNeVeR | 762,819,625 | false | {"Kotlin": 25841} | package me.fornever.todosaurus.toDoItemTests
import me.fornever.todosaurus.services.ToDoItem
import me.fornever.todosaurus.testFramework.FakeRangeMarker
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
@RunWith(Parameterized::class)
class IsReportedTests(private val readyItem: String) {
companion object {
@JvmStatic
@Parameters
fun readyItems()
= arrayOf(
"TODO[#2342]:",
"Todo[#2123]")
}
@Test
fun `ToDo item should be reported`() {
// Arrange
val sut = ToDoItem(FakeRangeMarker(readyItem))
// Act & Assert
Assert.assertFalse(sut.isNew)
}
}
| 6 | Kotlin | 2 | 8 | 4f61aedbf9e7be9062f5d7a85434244f54213aef | 780 | Todosaurus | MIT License |
shared/src/commonMain/kotlin/ui/mainUI/textToImage/TextToImageViewModel.kt | erenalpaslan | 697,706,268 | false | {"Kotlin": 118364, "Swift": 1139, "Shell": 228} | package ui.mainUI.textToImage
import common.BaseViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
/**
* Created by erenalpaslan on 2.10.2023
*/
class TextToImageViewModel: BaseViewModel() {
private val _text: MutableStateFlow<TextToImageUiState> = MutableStateFlow(
TextToImageUiState()
)
val text = _text.asStateFlow()
fun onSend(prompt: String?) {
viewModelScope.launch {
_text.update { it.copy(prompt = prompt) }
}
}
} | 0 | Kotlin | 0 | 1 | a48ee1be024a80d3ffa4e476bf4ca237f969a0e1 | 605 | Fusion | Apache License 2.0 |
src/main/kotlin/org/geepawhill/jltkv/ui/TestResultCell.kt | GeePawHill | 661,747,103 | false | null | package za.co.wethinkcode.viewer.app.ui
import javafx.scene.control.ListCell
import javafx.scene.layout.Background
import javafx.scene.layout.BackgroundFill
import javafx.scene.text.Font
import za.co.wethinkcode.viewer.app.parse.TestResult
class TestResultCell : ListCell<TestResult>() {
override fun updateItem(result: TestResult?, p1: Boolean) {
super.updateItem(result, p1)
if (isEmpty || result == null) {
text = ""
} else {
text = result.name
textFill = result.textColor
background = chooseBackground(result)
font = Font.font(20.0)
}
}
private fun chooseBackground(result: TestResult): Background {
return Background(BackgroundFill(result.color, null, null))
}
} | 0 | Kotlin | 0 | 0 | fcd6ce06c7d223d82506a0567083187100ea3e70 | 786 | jltk-viewer | MIT License |
app/src/main/java/com/anshtya/weatherapp/presentation/screens/weather/WeatherScreen.kt | anshtya | 607,466,913 | false | {"Kotlin": 174591} | package com.anshtya.weatherapp.presentation.screens.weather
import androidx.activity.compose.BackHandler
import androidx.compose.material3.DrawerState
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import com.anshtya.weatherapp.presentation.components.WeatherDrawer
import kotlinx.coroutines.launch
@Composable
fun WeatherScreen(
uiState: WeatherUiState,
weatherId: String?,
onManageLocationsClick: () -> Unit,
onSettingsClick: () -> Unit,
onErrorShown: () -> Unit,
onUpdateClick: () -> Unit,
drawerState: DrawerState = rememberDrawerState(DrawerValue.Closed)
) {
val scope = rememberCoroutineScope()
val weatherLocations = uiState.userWeather.weather
var selectedWeatherLocationId by rememberSaveable { mutableStateOf("") }
var weatherDisplayed by rememberSaveable { mutableStateOf(false) }
BackHandler(drawerState.isOpen) {
scope.launch {
drawerState.close()
}
}
WeatherDrawer(
weatherLocations = weatherLocations,
drawerState = drawerState,
onDrawerClose = {
scope.launch {
drawerState.close()
}
},
onChangeSelectedId = {
selectedWeatherLocationId = it
},
onSettingsClick = onSettingsClick,
onManageLocationsClick = onManageLocationsClick,
) {
weatherLocations.takeIf { it.isNotEmpty() }?.let { locations ->
weatherId?.let {
if (selectedWeatherLocationId != weatherId && !weatherDisplayed) {
selectedWeatherLocationId = it
weatherDisplayed = true
}
}
locations.find { it.weatherLocation.id == selectedWeatherLocationId }?.let {
WeatherDetails(
weather = it,
isLoading = uiState.isLoading,
errorMessage = uiState.errorMessage,
showCelsius = uiState.userWeather.showCelsius,
onErrorShown = onErrorShown,
onMenuClick = {
scope.launch {
drawerState.open()
}
},
onUpdateClick = onUpdateClick
)
} ?: WeatherDetails(
weather = locations.first(),
isLoading = uiState.isLoading,
errorMessage = uiState.errorMessage,
showCelsius = uiState.userWeather.showCelsius,
onErrorShown = onErrorShown,
onMenuClick = {
scope.launch {
drawerState.open()
}
},
onUpdateClick = onUpdateClick
)
}
}
} | 0 | Kotlin | 0 | 3 | b883a724ad528a03686ef015be346487fbe214d3 | 3,140 | weather-app | MIT License |
app/src/main/java/com/example/android/codelabs/navigation/ShoppingFragment.kt | arohim | 200,835,538 | false | null | package com.example.android.codelabs.navigation
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Activities that contain this fragment must implement the
* [ShoppingFragment.OnFragmentInteractionListener] interface
* to handle interaction events.
* Use the [ShoppingFragment.newInstance] factory method to
* create an instance of this fragment.
*
*/
class ShoppingFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_shopping, container, false)
}
}
| 0 | Kotlin | 0 | 0 | b130d679bbb2379cabed1196b7f833c4d1468961 | 1,384 | google-navigation-component-codelab | Apache License 2.0 |
src/main/kotlin/com/lvla/rxjava/interopkt/RxJavaInteropKt.kt | MoyuruAizawa | 82,516,067 | false | null | package com.lvla.rxjava.interopkt
import hu.akarnokd.rxjava.interop.RxJavaInterop
import io.reactivex.BackpressureStrategy
import io.reactivex.CompletableSource
import io.reactivex.CompletableTransformer
import io.reactivex.FlowableOperator
import io.reactivex.FlowableTransformer
import io.reactivex.MaybeSource
import io.reactivex.ObservableSource
import io.reactivex.SingleSource
import io.reactivex.SingleTransformer
import io.reactivex.processors.FlowableProcessor
import io.reactivex.subjects.Subject
import org.reactivestreams.Publisher
fun <T> rx.Observable<T>.toV2Flowable() = RxJavaInterop.toV2Flowable(this)!!
fun <T> rx.Observable<T>.toV2Observable() = RxJavaInterop.toV2Observable(this)!!
fun <T> rx.Single<T>.toV2Single() = RxJavaInterop.toV2Single(this)!!
fun rx.Completable.toV2Completable() = RxJavaInterop.toV2Completable(this)!!
fun <T> rx.Single<T>.toV2Maybe() = RxJavaInterop.toV2Maybe(this)!!
fun <T> rx.Completable.toV2Maybe() = RxJavaInterop.toV2Maybe<T>(this)!!
fun <T> Publisher<T>.toV1Observable() = RxJavaInterop.toV1Observable(this)!!
fun <T> ObservableSource<T>.toV1Observable(strategy: BackpressureStrategy)
= RxJavaInterop.toV1Observable(this, strategy)!!
fun <T> SingleSource<T>.toV1Single() = RxJavaInterop.toV1Single(this)!!
fun CompletableSource.toV1Completable() = RxJavaInterop.toV1Completable(this)!!
fun <T> MaybeSource<T>.toV1Single() = RxJavaInterop.toV1Single(this)!!
fun <T> MaybeSource<T>.toCompletable() = RxJavaInterop.toV1Completable(this)!!
fun <T> rx.subjects.Subject<T, T>.toV2Subject() = RxJavaInterop.toV2Subject(this)!!
fun <T> rx.subjects.Subject<T, T>.toV2Processor() = RxJavaInterop.toV2Processor(this)!!
fun <T> Subject<T>.toV1Subject() = RxJavaInterop.toV1Subject(this)!!
fun <T> FlowableProcessor<T>.toV1Subject() = RxJavaInterop.toV1Subject(this)!!
fun <T, R> rx.Observable.Transformer<T, R>.toV2Transformer() = RxJavaInterop.toV2Transformer(this)!!
fun <T, R> rx.Single.Transformer<T, R>.toV2Transformer() = RxJavaInterop.toV2Transformer(this)!!
fun rx.Completable.Transformer.toV2Transformer() = RxJavaInterop.toV2Transformer(this)!!
fun <T, R> FlowableTransformer<T, R>.toV1Transformer() = RxJavaInterop.toV1Transformer(this)!!
fun <T, R> SingleTransformer<T, R>.toV1Transformer() = RxJavaInterop.toV1Transformer(this)!!
fun CompletableTransformer.toV1Transformer() = RxJavaInterop.toV1Transformer(this)!!
fun <T, R> rx.Observable.Operator<R, T>.toV2Operator() = RxJavaInterop.toV2Operator(this)!!
fun <T, R> FlowableOperator<R, T>.toV1Operator() = RxJavaInterop.toV1Operator(this)!! | 0 | Kotlin | 0 | 10 | 4e4451bc134ba44df6907fc2a5d655ab513ca1ed | 2,562 | RxJava2InteropKt | Apache License 2.0 |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/controllers/Arm.kt | Superman132 | 239,211,214 | false | null | package org.firstinspires.ftc.teamcode.controllers
import com.qualcomm.robotcore.hardware.DcMotor
import org.firstinspires.ftc.teamcode.hardware.general.Motor
import org.firstinspires.ftc.teamcode.hardware.general.ServoNormal
import java.lang.Thread.sleep
import kotlin.math.PI
class Arm(val startAngle: Double, val arm_motor: Motor, val grabber: ServoNormal?) {
private val reduction = 0.30
private val autoSpeed = 0.90
init {
arm_motor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER)
arm_motor.setMode(DcMotor.RunMode.RUN_USING_ENCODER)
arm_motor.setZeroBehavior(DcMotor.ZeroPowerBehavior.BRAKE)
arm_motor.device.setVelocityPIDFCoefficients(5.0, 0.0, 0.0, 12.4)
arm_motor.device.setPositionPIDFCoefficients(5.0)
arm_motor.device.targetPositionTolerance = 10
}
fun toAngle(targetAngle: Double) {
val revToTurn = (targetAngle - startAngle) / (2 * PI)
arm_motor.device.targetPosition = (revToTurn * arm_motor.adjusted_tpr).toInt()
arm_motor.setMode(DcMotor.RunMode.RUN_TO_POSITION)
arm_motor.start(autoSpeed)
}
fun grabAuto() {
grabber?.start(1.0)
sleep(400)
}
fun dropAuto() {
run(-autoSpeed)
sleep(700)
run(0.0)
grabber?.start(0.05)
sleep(300)
}
fun grabTele() {
grabber?.start(0.75)
}
fun dropTele() {
grabber?.start(0.05)
}
fun run(raw_speed: Double) {
val adjustedSpeed = raw_speed * reduction
arm_motor.start(adjustedSpeed)
}
} | 0 | Kotlin | 0 | 1 | 1806b92cafaf774c944966e5c2c68557930d6432 | 1,584 | StaticDischargeCode | MIT License |
server-sample/src/main/kotlin/com/github/biancacristina/server/data/User.kt | biahyonce | 377,495,152 | false | {"Batchfile": 13214, "Kotlin": 12824} | package com.github.biancacristina.server.data
import io.micronaut.core.annotation.Introspected
@Introspected
data class User (val username: String) | 0 | Batchfile | 0 | 0 | 2fa83887362025888cd480fdd6a1f202bbb34fda | 149 | kotlin-micronaut-overview | MIT License |
intelligame/intelligame/src/main/kotlin/com/glycin/intelligame/codehero/osu/OsuFileSection.kt | glycin | 780,474,941 | false | {"Kotlin": 209198} | package com.glycin.intelligame.codehero.osu
class OsuFileSection(
val name: String,
var content: MutableList<String> = mutableListOf(),
) | 0 | Kotlin | 0 | 5 | 903e33f6eba6cf0781fe8f9afe2188f3ef4237be | 146 | intelligame | MIT License |
oppgave-endret/src/test/kotlin/no/nav/helse/sparkel/oppgaveendret/GosysOppgaveEndretProducerTest.kt | navikt | 341,650,641 | false | null | package no.nav.helse.sparkel.oppgaveendret
import com.fasterxml.jackson.databind.JsonNode
import no.nav.helse.rapids_rivers.testsupport.TestRapid
import no.nav.helse.sparkel.oppgaveendret.oppgave.Identtype.FOLKEREGISTERIDENT
import no.nav.helse.sparkel.oppgaveendret.oppgave.Oppgave
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
internal class GosysOppgaveEndretProducerTest {
private val rapid = TestRapid()
private val oppgaveEndretProducer: GosysOppgaveEndretProducer = GosysOppgaveEndretProducer(rapid)
@Test
fun `kรธer opp meldinger og sender dem nรฅr det er klart`() {
val oppgave = Oppgave(1, "SYK", "12345678910", FOLKEREGISTERIDENT)
oppgaveEndretProducer.onPacket(oppgave)
oppgaveEndretProducer.shipIt()
assertMeldingsinnhold(forventetMelding, rapid.inspektรธr.message(0))
}
@Test
fun `dedupliserer fรธdselsnumre`() {
val oppgave = Oppgave(1, "SYK", "12345678910", FOLKEREGISTERIDENT)
val enOppgaveTil = Oppgave(2, "SYK", "12345678910", FOLKEREGISTERIDENT)
val enUrelatertOppgave = Oppgave(3, "SYK", "10987654321", FOLKEREGISTERIDENT)
val endaEnOppgave = Oppgave(4, "SYK", "12345678910", FOLKEREGISTERIDENT)
oppgaveEndretProducer.onPacket(oppgave)
oppgaveEndretProducer.onPacket(enOppgaveTil)
oppgaveEndretProducer.onPacket(enUrelatertOppgave)
oppgaveEndretProducer.onPacket(endaEnOppgave)
oppgaveEndretProducer.shipIt()
assertEquals(2, rapid.inspektรธr.size)
}
@Test
fun `tรธmmer duplikatene etter hver sending`() {
val oppgave = Oppgave(1, "SYK", "fรธdselsnummer", FOLKEREGISTERIDENT)
oppgaveEndretProducer.onPacket(oppgave)
oppgaveEndretProducer.shipIt()
assertEquals(1, rapid.inspektรธr.size)
oppgaveEndretProducer.shipIt()
assertEquals(1, rapid.inspektรธr.size)
oppgaveEndretProducer.onPacket(oppgave)
oppgaveEndretProducer.shipIt()
assertEquals(2, rapid.inspektรธr.size)
}
private fun assertMeldingsinnhold(forventet: String, faktisk: JsonNode) {
val forventetNode = objectMapper.readTree(forventet)
setOf("@event_name", "fรธdselsnummer").forEach {
assertEquals(forventetNode[it], faktisk[it])
}
setOf("@id", "@opprettet").forEach {
assertTrue(faktisk[it].isValueNode)
}
}
private val forventetMelding = """
{
"@event_name": "gosys_oppgave_endret",
"fรธdselsnummer": "12345678910"
}
""".trimIndent()
}
| 1 | Kotlin | 1 | 2 | 7a4704c6c15e0699ef49be291a483bd8965350ab | 2,654 | helse-sparkelapper | MIT License |
app/src/androidTest/java/com/telenav/osv/ui/fragment/settings/ResolutionViewModelTest.kt | kartaview | 63,806,526 | false | null | package com.telenav.osv.ui.fragment.settings
import android.Manifest
import android.content.Context
import android.view.View
import android.widget.RadioGroup
import androidx.preference.PreferenceViewHolder
import androidx.test.InstrumentationRegistry
import androidx.test.annotation.UiThreadTest
import androidx.test.rule.GrantPermissionRule
import com.telenav.osv.R
import com.telenav.osv.application.ApplicationPreferences
import com.telenav.osv.application.KVApplication
import com.telenav.osv.application.PreferenceTypes
import com.telenav.osv.ui.fragment.settings.custom.RadioGroupPreference
import com.telenav.osv.ui.fragment.settings.viewmodel.ResolutionViewModel
import com.telenav.osv.utils.Size
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.mockito.MockitoAnnotations
class ResolutionViewModelTest {
private lateinit var viewModel: ResolutionViewModel
private lateinit var context: Context
private lateinit var appPrefs: ApplicationPreferences
@Before
fun setUp() {
GrantPermissionRule.grant(Manifest.permission.CAMERA)
context = InstrumentationRegistry.getTargetContext()
val app = InstrumentationRegistry.getTargetContext().applicationContext as KVApplication
MockitoAnnotations.initMocks(this)
appPrefs = ApplicationPreferences(app)
viewModel = ResolutionViewModel(app, appPrefs)
}
@Test
@UiThreadTest
fun testResolutionClick() {
val preference = getGroupPreference()
val checkedChangeListener = preference.onCheckedChangeListener
var preferenceChanged = false
preference.onCheckedChangeListener = (RadioGroup.OnCheckedChangeListener { radioGroup, i ->
preferenceChanged = true
checkedChangeListener.onCheckedChanged(radioGroup, i)
})
preference.onBindViewHolder(PreferenceViewHolder.createInstanceForTests(View.inflate(context, R.layout.settings_item_radio_group, null)))
preference.radioButtonList[0].isChecked = false
preference.radioButtonList[0].isChecked = true
Assert.assertTrue(preferenceChanged)
val size = preference.radioButtonList[0].tag as Size
Assert.assertEquals(size.width, appPrefs.getIntPreference(PreferenceTypes.K_RESOLUTION_WIDTH))
Assert.assertEquals(size.height, appPrefs.getIntPreference(PreferenceTypes.K_RESOLUTION_HEIGHT))
}
@Test
@UiThreadTest
fun testStoredResolutionCheckedWhenDisplayingTheList() {
val preference = getGroupPreference()
for (radioButton in preference.radioButtonList) {
if (radioButton.isChecked) {
val size = radioButton.tag as Size
Assert.assertEquals(size.width, appPrefs.getIntPreference(PreferenceTypes.K_RESOLUTION_WIDTH))
Assert.assertEquals(size.height, appPrefs.getIntPreference(PreferenceTypes.K_RESOLUTION_HEIGHT))
return
}
}
Assert.assertTrue(false)
}
private fun getGroupPreference(): RadioGroupPreference {
viewModel.settingsDataObservable
viewModel.start()
val settingsGroups = viewModel.settingsDataObservable.value!!
return settingsGroups[0].getPreference(context) as RadioGroupPreference
}
} | 76 | null | 30 | 130 | 66eb0ee1ab093562e2867087084b26803fe58174 | 3,295 | android | MIT License |
src/test/kotlin/uitests/IntroductionScreenTest.kt | mataframework | 770,318,523 | false | {"Kotlin": 19637} | package uitests
import app.App
import app.AppLauncher
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import uitests.ui.IntroductionPage
import uitests.ui.PlusAdsPage
import kotlin.test.assertEquals
class IntroductionScreenTest {
@Test
fun checkIntroductionPages() {
val introductionPage = IntroductionPage(app)
assertEquals("ะกะผะพััะธัะต ัััััะธ\nัะธะปัะผะพะฒ\nะธ ัะตัะธะฐะปะพะฒ", introductionPage.getDescription())
introductionPage.clickNext()
introductionPage.reload()
assertEquals("ะกะบะฐัะธะฒะฐะนัะต\nะฒ ะดะพัะพะณั", introductionPage.getDescription())
introductionPage.clickNext()
val plusAdsPage = PlusAdsPage(app)
assertEquals("ะกะผะพััะธัะต ะบะธะฝะพ\n30 ะดะฝะตะน ะฑะตัะฟะปะฐัะฝะพ", plusAdsPage.getPrimaryOfferText())
assertEquals("ะะพะดะฟะธัะบะฐ ะะปัั ะะพะปััะต ะบะธะฝะพ", plusAdsPage.getSecondaryOfferText())
plusAdsPage.clickSkip()
}
companion object {
private lateinit var app: App
@JvmStatic
@BeforeAll
fun setUp() {
app = AppLauncher().launch()
}
@JvmStatic
@AfterAll
fun tearDown() {
app.close()
}
}
} | 2 | Kotlin | 0 | 0 | 3b20fc8b3da850899e33cb2af8ccc4d61c2f066a | 1,224 | mataframework | MIT License |
tmp/arrays/youTrackTests/1273.kt | DaniilStepanov | 228,623,440 | false | null | // Original bug: KT-16445
interface SomeInterface<T>
object Container {
private inline fun <reified T> someMethod() = object : SomeInterface<T> { }
class SomeClass : SomeInterface<SomeClass> by someMethod()
}
fun main(args: Array<String>) {
Container.SomeClass()
}
| 1 | null | 8 | 1 | 602285ec60b01eee473dcb0b08ce497b1c254983 | 280 | bbfgradle | Apache License 2.0 |
core/src/com/gbjam6/city/Input.kt | crazynavi | 693,746,502 | false | null | package com.gbjam6.city
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.gbjam6.city.general.Util
/**
* Manages inputs.
*
* DPAD is mapped to WASD / ZQSD / Arrows
* A is mapped to O / SPACE
* B is mapped to K / ESC
* START is mapped to B / ENTER
* SELECT is mapped to V / TAB
*/
interface Input {
fun processInputs() {
if (Util.inputFreeze > 0) {
Util.inputFreeze--
} else {
if (Gdx.input.isKeyPressed(Input.Keys.DPAD_UP) || Gdx.input.isKeyPressed(Input.Keys.Z) || Gdx.input.isKeyPressed(Input.Keys.W)) {
Util.inputFreeze = 16; up() ; Util.wasPressed = true
} else if (Gdx.input.isKeyPressed(Input.Keys.DPAD_DOWN) || Gdx.input.isKeyPressed(Input.Keys.S)) {
Util.inputFreeze = 16; down() ; Util.wasPressed = true
} else if (Gdx.input.isKeyPressed(Input.Keys.DPAD_LEFT) || Gdx.input.isKeyPressed(Input.Keys.Q) || Gdx.input.isKeyPressed(Input.Keys.A)) {
Util.inputFreeze = 16; left() ; Util.wasPressed = true
} else if (Gdx.input.isKeyPressed(Input.Keys.DPAD_RIGHT) || Gdx.input.isKeyPressed(Input.Keys.D)) {
Util.inputFreeze = 16; right() ; Util.wasPressed = true
} else if (Gdx.input.isKeyPressed(Input.Keys.O) || Gdx.input.isKeyPressed(Input.Keys.SPACE)) {
Util.inputFreeze = 16; a() ; Util.wasPressed = true
} else if (Gdx.input.isKeyPressed(Input.Keys.K) || Gdx.input.isKeyPressed(Input.Keys.ESCAPE)) {
Util.inputFreeze = 16; b() ; Util.wasPressed = true
} else if (Gdx.input.isKeyPressed(Input.Keys.B) || Gdx.input.isKeyPressed(Input.Keys.ENTER)) {
Util.inputFreeze = 16; start() ; Util.wasPressed = true
} else if (Gdx.input.isKeyPressed(Input.Keys.V) || Gdx.input.isKeyPressed(Input.Keys.TAB)) {
Util.inputFreeze = 16; select() ; Util.wasPressed = true
} else if (Gdx.input.isKeyPressed(Input.Keys.P)) {
Util.inputFreeze = 16; p() ; Util.wasPressed = true
} else {
Util.wasPressed = false
}
}
}
fun up() {}
fun down() {}
fun left() {}
fun right() {}
fun a() {}
fun b() {}
fun start() {}
fun select() {}
fun p() {}
}
| 0 | null | 0 | 5 | cb75c85ce851c0c498202bcf414af46ddd3896aa | 2,334 | kotlin-city-builder | Creative Commons Zero v1.0 Universal |
app/src/main/java/be/hogent/faith/faith/library/eventList/EventListFragment.kt | hydrolythe | 353,694,404 | false | null | package be.hogent.faith.faith.library.eventList
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.content.res.AppCompatResources
import androidx.databinding.DataBindingUtil.inflate
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import be.hogent.faith.R
import be.hogent.faith.databinding.FragmentLibraryEventlistBinding
import be.hogent.faith.faith.UserViewModel
import be.hogent.faith.faith.di.KoinModules
import be.hogent.faith.faith.models.Event
import com.google.android.material.datepicker.CalendarConstraints
import com.google.android.material.datepicker.MaterialDatePicker
import kotlinx.android.synthetic.main.fragment_library_eventlist.*
import org.koin.android.ext.android.getKoin
import org.koin.android.viewmodel.ext.android.sharedViewModel
import org.koin.core.parameter.parametersOf
import java.util.UUID
class EventListFragment : Fragment() {
private var navigation: EventsListNavigationListener? = null
private lateinit var binding: FragmentLibraryEventlistBinding
/**
* Adapter for the recyclerview showing the events
*/
private lateinit var eventsAdapter: EventsAdapter
/**
* Listener used to track items clicked in the Adapter.
*/
private lateinit var eventListener: EventListener
private val userViewModel: UserViewModel = getKoin().getScope(KoinModules.USER_SCOPE_ID).get()
private val eventListViewModel: EventListViewModel by sharedViewModel {
parametersOf(
userViewModel.user.value
)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = inflate(inflater, R.layout.fragment_library_eventlist, container, false)
binding.eventlistViewModel = eventListViewModel
setupRecyclerView(binding.recyclerViewLibraryEventlist)
startListeners()
return binding.root
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is EventsListNavigationListener) {
navigation = context
}
}
private fun setupRecyclerView(recyclerView: RecyclerView) {
eventListener = object : EventListener {
override fun onEventClicked(eventUUID: UUID) {
navigation?.startEventDetailsFragment(eventUUID)
}
override fun onEventDeleteClicked(event: Event) {
showDeleteAlert(event)
}
}
eventsAdapter = EventsAdapter(eventListener)
recyclerView.apply {
layoutManager = GridLayoutManager(context, 3)
addItemDecoration(GridSpacingItemDecoration(3, 10, true, 0))
this.adapter = eventsAdapter
}
}
private fun startListeners() {
eventListViewModel.dateRangeString.observe(viewLifecycleOwner, Observer { range ->
btn_library_eventlist_chooseDate.text = range
})
eventListViewModel.filteredEvents.observe(viewLifecycleOwner, Observer { list ->
eventsAdapter.updateEventsList(list, eventListViewModel.deleteEnabled.value!!)
})
eventListViewModel.audioFilterEnabled.observe(viewLifecycleOwner, Observer { enabled ->
setDrawable(
enabled,
btn_library_eventlist_searchAudio,
R.drawable.ic_filterknop_audio,
R.drawable.ic_filterknop_audio_selected
)
})
eventListViewModel.textFilterEnabled.observe(viewLifecycleOwner, Observer { enabled ->
setDrawable(
enabled,
btn_library_eventlist_searchText,
R.drawable.ic_filterknop_teksten,
R.drawable.ic_filterknop_teksten_selected
)
})
eventListViewModel.photoFilterEnabled.observe(viewLifecycleOwner, Observer { enabled ->
setDrawable(
enabled,
btn_library_eventlist_searchPhotos,
R.drawable.ic_filterknop_foto,
R.drawable.ic_filterknop_foto_selected
)
})
eventListViewModel.drawingFilterEnabled.observe(viewLifecycleOwner, Observer { enabled ->
setDrawable(
enabled,
btn_library_eventlist_searchDrawing,
R.drawable.ic_filterknop_tekeningen,
R.drawable.ic_filterknop_tekeningen_selected
)
})
eventListViewModel.startDateClicked.observe(viewLifecycleOwner, Observer {
showDateRangePicker()
})
eventListViewModel.endDateClicked.observe(viewLifecycleOwner, Observer {
showDateRangePicker()
})
eventListViewModel.cancelButtonClicked.observe(viewLifecycleOwner, Observer {
requireActivity().onBackPressed()
})
eventListViewModel.deleteEnabled.observe(viewLifecycleOwner, Observer { enabled ->
eventsAdapter.updateEventsList(eventListViewModel.filteredEvents.value!!, enabled)
})
}
/**
* show Material DatePicker. Sets the latest month that can be selected
*/
private fun showDateRangePicker() {
val builder = MaterialDatePicker.Builder.dateRangePicker()
val picker: MaterialDatePicker<*>
builder
.setTitleText(R.string.datumVan)
.setCalendarConstraints(
CalendarConstraints.Builder()
.setEnd(MaterialDatePicker.thisMonthInUtcMilliseconds())
.build()
)
picker = builder.build()
picker.show(requireActivity().supportFragmentManager, picker.toString())
picker.addOnPositiveButtonClickListener {
eventListViewModel.setDateRange(it.first, it.second)
}
}
private fun showDeleteAlert(event: Event) {
val alertDialog: AlertDialog = this.run {
val builder = AlertDialog.Builder(this.requireContext()).apply {
setTitle(getString(R.string.library_verwijder_event_title))
setMessage(getString(R.string.library_verwijder_event_message))
setPositiveButton(R.string.ok) { _, _ ->
eventListViewModel.deleteEvent(event)
}
setNegativeButton(R.string.cancel) { dialog, _ ->
dialog.cancel()
}
}
builder.create()
}
alertDialog.show()
}
private fun setDrawable(enabled: Boolean, button: ImageButton, image: Int, imageSelected: Int) {
button.setImageDrawable(
AppCompatResources.getDrawable(
this.requireContext(),
if (enabled) imageSelected else image
)
)
}
interface EventsListNavigationListener {
fun startEventDetailsFragment(eventUuid: UUID)
}
companion object {
fun newInstance(): EventListFragment {
return EventListFragment()
}
}
} | 0 | Kotlin | 0 | 0 | 14c6aec4b3c0a42bc73a7f779964d166fffeea20 | 7,349 | FAITHAndroid | The Unlicense |
chat/repository/src/main/java/com/devfalah/repository/ChatRemoteDataSource.kt | Salmon-family | 569,890,321 | false | {"Kotlin": 837143} | package com.devfalah.repository
import com.devfalah.repository.models.*
interface ChatRemoteDataSource {
suspend fun getChats(userID: Int,page: Int): ConversationDTO
suspend fun getMessagesWithFriend(userID: Int, friendID: Int, page: Int): ConversationDTO
suspend fun sendMessage(from: Int, to: Int, message: String): ChatDTO
suspend fun postNotification(notification: NotificationDto): Boolean
suspend fun getUserDetails(userID: Int): UserDTO
suspend fun getAllFriends(userID: Int, page: Int): FriendsResponse
} | 11 | Kotlin | 19 | 24 | 7589d73a400c78ecfa94b24d87189b4f5e01de9b | 544 | Clubs | Apache License 2.0 |
app/src/main/java/eu/kanade/tachiyomi/data/database/tables/CategoryTable.kt | AntsyLich | 378,910,163 | true | {"Kotlin": 2124469} | package eu.kanade.tachiyomi.data.database.tables
object CategoryTable {
const val TABLE = "categories"
const val COL_ID = "_id"
const val COL_NAME = "name"
const val COL_ORDER = "sort"
const val COL_FLAGS = "flags"
}
| 0 | Kotlin | 1 | 4 | 3c40010afffa807017f0b56634d8c5323154b4e4 | 243 | tachiyomi | Apache License 2.0 |
GallerySelector/src/main/java/com/jms/galleryselector/manager/API29MediaContentManager.kt | minsuk-jang | 762,162,064 | false | {"Kotlin": 40762} | package com.jms.galleryselector.manager
import android.content.ContentResolver
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.annotation.RequiresApi
import androidx.core.os.bundleOf
@RequiresApi(Build.VERSION_CODES.R)
internal class API29MediaContentManager(
private val context: Context
) : MediaContentManager() {
override fun getCursor(
uri: Uri,
projection: Array<String>,
albumId: String?,
offset: Int,
limit: Int
): Cursor? {
val selection = baseSelectionClause + " AND ${MediaStore.MediaColumns.IS_PENDING} = ?" +
if (albumId != null) " AND ${MediaStore.MediaColumns.BUCKET_ID} = ?" else ""
val selectionArgs = baseSelectionArgs.toMutableList().apply {
add("0")
albumId?.let { add(it) } //when album id is not null
}.toTypedArray()
val selectionBundle = bundleOf(
ContentResolver.QUERY_ARG_OFFSET to offset,
ContentResolver.QUERY_ARG_LIMIT to limit,
ContentResolver.QUERY_ARG_SORT_COLUMNS to arrayOf(
MediaStore.Files.FileColumns.DATE_MODIFIED
),
ContentResolver.QUERY_ARG_SORT_DIRECTION to ContentResolver.QUERY_SORT_DIRECTION_DESCENDING,
ContentResolver.QUERY_ARG_SQL_SELECTION to selection,
ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS to selectionArgs
)
return context.contentResolver.query(
uri,
projection,
selectionBundle,
null
)
}
} | 0 | Kotlin | 0 | 7 | 3bec304a70a709cd57d202d792c1c32d305c5cac | 1,665 | GallerySelector | The Unlicense |
rubik/rubik_publish/src/main/java/com/rubik/publish/extra/Injector.kt | baidu | 504,447,693 | false | {"Kotlin": 607049, "Java": 37304} | package com.rubik.publish.extra
import com.ktnail.gradle.maven.MavenDependency
import com.rubik.context.extra.Context
import com.rubik.context.extra.rubikMainProject
import com.rubik.context.utility.Module
import com.rubik.context.utility.ModuleInjector
import com.rubik.publish.record.PublicationRecords
import com.rubik.publish.task.PublishContextTasksContainer
import com.rubik.publish.task.name.PublishTaskName
import com.rubik.publish.task.target.ContextTaskTarget
import com.rubik.publish.task.target.TaskTargetContainer
import org.gradle.api.Project
interface PublishModuleInjector : ModuleInjector {
val publicationRecords: PublicationRecords
val publishTasksContainer: PublishContextTasksContainer
val taskTargetContainer: TaskTargetContainer
fun contextToDependLibMavenDependencies(
context: Context, version: String, dev: Boolean?
): List<Pair<String, MavenDependency>>
}
object PublishModule : Module<PublishModuleInjector>()
val publicationRecords: PublicationRecords
get() = PublishModule.content.publicationRecords
val publishTasksContainer: PublishContextTasksContainer
get() = PublishModule.content.publishTasksContainer
val Project.targetTaskName: PublishTaskName?
get() = PublishModule.content.taskTargetContainer.let { container->
container.projectTargetTaskName(this)?: container.projectTargetTaskName(this.rubikMainProject)
}
var Context.target: ContextTaskTarget
set(value) { PublishModule.content.taskTargetContainer.taskTargets[uri] = value }
get() = PublishModule.content.taskTargetContainer.taskTargets[uri] ?: ContextTaskTarget.doNotPublish(this)
fun Context.toDependLibMavenDependencies(
version: String,
dev: Boolean?
): List<Pair<String, MavenDependency>> = PublishModule.content.contextToDependLibMavenDependencies(this, version, dev) | 1 | Kotlin | 7 | 153 | 065ba8f4652b39ff558a5e3f18b9893e2cf9bd25 | 1,844 | Rubik | Apache License 2.0 |
app/src/main/java/com/myetherwallet/mewconnect/core/ui/dialog/SimpleTextDialogFragment.kt | MyEtherWallet | 152,647,742 | false | null | package com.myetherwallet.mewconnect.core.ui.dialog
import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
/**
* Created by BArtWell on 15.07.2018.
*/
private const val TAG = "SimpleTextDialogFragment"
private const val EXTRA_TITLE = "title"
private const val EXTRA_TEXT = "text"
class SimpleTextDialogFragment : BaseDialogFragment() {
companion object {
fun newInstance(text: String, title: String? = null): SimpleTextDialogFragment {
val fragment = SimpleTextDialogFragment()
val arguments = Bundle()
if (title != null) {
arguments.putString(EXTRA_TITLE, title)
}
arguments.putString(EXTRA_TEXT, text)
fragment.arguments = arguments
return fragment
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(requireContext())
builder.setTitle(arguments?.getString(EXTRA_TITLE))
builder.setMessage(arguments?.getString(EXTRA_TEXT))
builder.setPositiveButton(android.R.string.ok, null)
return builder.create()
}
override fun getFragmentTag() = TAG
} | 7 | Kotlin | 37 | 49 | b55589ed7729c5afd0f81ff4c1177c92df651e45 | 1,218 | MEWconnect-Android | MIT License |
bitcoincore/src/main/kotlin/io/definenulls/bitcoincore/transactions/PendingTransactionProcessor.kt | toEther | 677,363,684 | false | null | package io.definenulls.bitcoincore.transactions
import io.definenulls.bitcoincore.WatchedTransactionManager
import io.definenulls.bitcoincore.blocks.IBlockchainDataListener
import io.definenulls.bitcoincore.core.IPublicKeyManager
import io.definenulls.bitcoincore.core.IStorage
import io.definenulls.bitcoincore.core.inTopologicalOrder
import io.definenulls.bitcoincore.extensions.toReversedHex
import io.definenulls.bitcoincore.managers.BloomFilterManager
import io.definenulls.bitcoincore.managers.IIrregularOutputFinder
import io.definenulls.bitcoincore.managers.PublicKeyManager
import io.definenulls.bitcoincore.models.Transaction
import io.definenulls.bitcoincore.storage.FullTransaction
import io.definenulls.bitcoincore.transactions.extractors.TransactionExtractor
class PendingTransactionProcessor(
private val storage: IStorage,
private val extractor: TransactionExtractor,
private val publicKeyManager: IPublicKeyManager,
private val irregularOutputFinder: IIrregularOutputFinder,
private val dataListener: IBlockchainDataListener,
private val conflictsResolver: TransactionConflictsResolver) {
private val notMineTransactions = HashSet<ByteArray>()
var transactionListener: WatchedTransactionManager? = null
fun processCreated(transaction: FullTransaction) {
if (storage.getTransaction(transaction.header.hash) != null) {
throw TransactionCreator.TransactionAlreadyExists("hash = ${transaction.header.hash.toReversedHex()}")
}
extractor.extract(transaction)
storage.addTransaction(transaction)
try {
dataListener.onTransactionsUpdate(listOf(transaction.header), listOf(), null)
} catch (e: Exception) {
// ignore any exception since the tx is inserted to the db
}
if (irregularOutputFinder.hasIrregularOutput(transaction.outputs)) {
throw BloomFilterManager.BloomFilterExpired
}
}
@Throws(BloomFilterManager.BloomFilterExpired::class)
fun processReceived(transactions: List<FullTransaction>, skipCheckBloomFilter: Boolean) {
var needToUpdateBloomFilter = false
val inserted = mutableListOf<Transaction>()
val updated = mutableListOf<Transaction>()
// when the same transaction came in merkle block and from another peer's mempool we need to process it serial
synchronized(this) {
for ((index, transaction) in transactions.inTopologicalOrder().withIndex()) {
if (notMineTransactions.any { it.contentEquals(transaction.header.hash) }) {
// already processed this transaction with same state
continue
}
val invalidTransaction = storage.getInvalidTransaction(transaction.header.hash)
if (invalidTransaction != null) {
// if some peer send us transaction after it's invalidated, we must ignore it
continue
}
val existingTransaction = storage.getTransaction(transaction.header.hash)
if (existingTransaction != null) {
if (existingTransaction.status == Transaction.Status.RELAYED) {
// if comes again from memPool we don't need to update it
continue
}
relay(existingTransaction, index)
storage.updateTransaction(existingTransaction)
updated.add(existingTransaction)
continue
}
relay(transaction.header, index)
extractor.extract(transaction)
transactionListener?.onTransactionReceived(transaction)
if (!transaction.header.isMine) {
notMineTransactions.add(transaction.header.hash)
conflictsResolver.getIncomingPendingTransactionsConflictingWith(transaction).forEach { tx ->
// Former incoming transaction is conflicting with current transaction
tx.conflictingTxHash = transaction.header.hash
storage.updateTransaction(tx)
updated.add(tx)
}
continue
}
val conflictingTransactions = conflictsResolver.getTransactionsConflictingWithPendingTransaction(transaction)
if (conflictingTransactions.isNotEmpty()) {
// Ignore current transaction and mark former transactions as conflicting with current transaction
conflictingTransactions.forEach { tx ->
tx.conflictingTxHash = transaction.header.hash
storage.updateTransaction(tx)
updated.add(tx)
}
} else {
storage.addTransaction(transaction)
inserted.add(transaction.header)
}
if (!skipCheckBloomFilter) {
val checkDoubleSpend = !transaction.header.isOutgoing
needToUpdateBloomFilter = needToUpdateBloomFilter ||
checkDoubleSpend ||
publicKeyManager.gapShifts() ||
irregularOutputFinder.hasIrregularOutput(transaction.outputs)
}
}
}
if (inserted.isNotEmpty() || updated.isNotEmpty()) {
dataListener.onTransactionsUpdate(inserted, updated, null)
}
if (needToUpdateBloomFilter) {
throw BloomFilterManager.BloomFilterExpired
}
}
private fun relay(transaction: Transaction, order: Int) {
transaction.status = Transaction.Status.RELAYED
transaction.order = order
}
}
| 0 | Kotlin | 0 | 0 | bbd7c809a027dd33c1fd393f6a53684d84dcbe14 | 5,883 | bitcoin-kit-android_s | MIT License |
app/src/main/java/com/classic/assistant/car/ui/add/AddActivity.kt | qyxxjd | 59,408,384 | false | null | package com.classic.assistant.car.ui.add
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.FragmentManager
import com.amap.api.location.AMapLocationListener
import com.classic.assistant.car.R
import com.classic.assistant.car.data.manager.BackupManager
import com.classic.assistant.car.data.manager.DataManager
import com.classic.assistant.car.data.manager.LocationManager
import com.classic.assistant.car.data.source.DataSource
import com.classic.assistant.car.data.source.local.db.ConsumptionInfo
import com.classic.assistant.car.databinding.ActivityAddBinding
import com.classic.assistant.car.extension.*
import com.classic.assistant.car.ui.base.AppViewBindingActivity
import com.classic.assistant.car.util.CarLog
import com.classic.assistant.car.util.CharFilter
import com.classic.assistant.car.util.DatePickerUtil
/**
* - ๅ ๆฒนใไฟๅ
ปๆถ๏ผ้่ฆๅกซๅ: ้็จ่กจ
* - ้่ฆๅจๆ่ฎพ็ฝฎๆ ็ญพ็็ฑปๅ: ๆฑฝ่ฝฆไฟ้ฉใๆฑฝ่ฝฆ้
ไปถใๆฑฝ่ฝฆ่ดญไนฐใ่ฃ
ๆฝข้ฅฐๅ
* - ๆๅฎไฝๆ้ใๅนถไธๅฎไฝๆๅๆถ๏ผๅฑ็คบไฝ็ฝฎไฟกๆฏใๆทปๅ ๆฐๆฎๅใๅ
ณ้ญ้กต้ขๆถ้ๆฏ่ตๆบ
*/
class AddActivity : AppViewBindingActivity<ActivityAddBinding>(), Toolbar.OnMenuItemClickListener {
private val textChooseColumnCount = 2
private var isModify = false
private var target: ConsumptionInfo = ConsumptionInfo()
private var tagHintResId = 0
private var dataSource: DataSource? = null
private var fm: FragmentManager? = null
private val locationListener = AMapLocationListener {
if (isFinishing) return@AMapLocationListener
val address = it.address
CarLog.d("ๅฎไฝๆๅ๏ผ$address")
uiTask {
viewBinding?.includeAddContent?.addConsumptionLocation?.let { v ->
target.location = address
setupText(v, address)
v.applyFocus()
showToast(appContext, R.string.hint_location_success)
}
}
}
private val location: LocationManager by lazy { LocationManager.get() }
override fun createViewBinding() {
viewBinding = ActivityAddBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
dataSource = DataSource.get(appContext)
toolbar?.setOnMenuItemClickListener(this)
if (intent.hasExtra(KEY_CONSUMPTION)) {
target = intent.getSerializableExtra(KEY_CONSUMPTION) as ConsumptionInfo
isModify = true
setTitle(R.string.modify)
} else {
isModify = false
target.time = System.currentTimeMillis()
setTitle(R.string.add)
}
viewBinding?.includeAddContent?.apply {
addConsumptionTimeLayout.setOnClickListener { showDatePicker() }
addConsumptionTypeLayout.setOnClickListener { showTypeChoose() }
contentOilLayout.setOnClickListener { showOilTypeChoose() }
applyFilter(addConsumptionTag, addConsumptionLocation, addConsumptionRemark)
}
setupUI(target)
fm = supportFragmentManager
location.init(appContext)
}
override fun onDestroy() {
location.stop()
location.destroy()
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(if (isModify) R.menu.modify_menu else R.menu.add_menu, menu)
return true
}
override fun onMenuItemClick(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.action_location -> {
task { location.start(locationListener) }
return true
}
R.id.action_add -> {
if (checkParams()) {
onAdd()
return true
}
}
R.id.action_modify -> {
if (checkParams()) {
onModify()
return true
}
}
}
return false
}
private fun showDatePicker() {
DatePickerUtil.create(this, target.time, { date, _ ->
val time = date.time
target.time = time
setupTime(time)
}).show()
}
private fun showTypeChoose() {
if (null != fm) {
TextChooseFragment()
.title(string(R.string.hint_add_consumption_type))
.columnCount(textChooseColumnCount)
.items(ConsumptionInfo.TYPE_LABELS)
.listener(object : TextChooseListener {
override fun onChoose(index: Int, text: String) {
CarLog.d("ๆถ่ดน็ฑปๅ้ๆฉ๏ผindex=$index, text=$text")
onTypeChanged(index, text)
}
})
.show(fm!!)
}
}
private fun showOilTypeChoose() {
fm?.apply {
TextChooseFragment()
.title(string(R.string.hint_add_consumption_oil_type))
.columnCount(textChooseColumnCount)
.items(ConsumptionInfo.FUEL_LABELS)
.listener(object : TextChooseListener {
override fun onChoose(index: Int, text: String) {
CarLog.d("ๅ ๆฒน็ฑปๅ้ๆฉ๏ผindex=$index, text=$text")
onOilTypeChanged(index, text)
}
})
.show(fm!!)
}
}
private fun onTypeChanged(newType: Int, value: String) {
target.type = newType
setupTypeValue(value)
visibleTagLayout(newType)
visibleOilLayout(target)
visibleMileageLayout(newType)
}
private fun onOilTypeChanged(newType: Int, value: String) {
target.oilType = newType
viewBinding?.includeAddContent?.contentOilTypeValue?.text = value
}
private fun checkParams(): Boolean {
viewBinding?.includeAddContent?.apply {
if (addConsumptionAmount.text().isEmpty()) {
hintToast(R.string.hint_add_consumption_amount)
addConsumptionAmount.applyFocus()
return false
}
if (tagHintResId != 0 && addConsumptionTag.text().isEmpty()) {
hintToast(tagHintResId)
addConsumptionTag.applyFocus()
return false
}
if (useFuel(target.type) && contentOilPrice.text().isEmpty()) {
hintToast(R.string.hint_add_consumption_oil_price)
contentOilPrice.applyFocus()
return false
}
if (useMileage(target.type) && addConsumptionMileage.text().isEmpty()) {
hintToast(R.string.hint_add_consumption_mileage)
addConsumptionMileage.applyFocus()
return false
}
}
return true
}
private fun hintToast(resId: Int) {
toast(string(resId) + string(R.string.hint_empty_suffix))
}
private fun setupUI(info: ConsumptionInfo) {
val type = info.type
setupTime(info.time)
setupTypeValue(UIManager.label(info.type))
viewBinding?.includeAddContent?.apply {
setupNumber(addConsumptionAmount, info.amount)
if (useTag(type)) setupText(addConsumptionTag, info.tag)
if (info.mileage > 0L) setupText(addConsumptionMileage, info.mileage.toString())
if (info.location.isNotEmpty()) setupText(addConsumptionLocation, info.location)
if (info.remark.isNotEmpty()) setupText(addConsumptionRemark, info.remark)
visibleTagLayout(type)
visibleOilLayout(info)
visibleMileageLayout(type)
addConsumptionAmount.applyFocus()
}
}
private fun setupTypeValue(text: String) {
viewBinding?.includeAddContent?.addConsumptionTypeValue?.text = text
}
private fun setupText(view: EditText, text: String) {
view.setText(text)
}
private fun setupNumber(view: EditText, number: Float) {
view.setText(if (number > 0F) number.replace() else "")
}
private fun setupTime(time: Long) {
viewBinding?.includeAddContent?.addConsumptionTime?.text = time.format()
}
/**
* ๅ ๆฒนไฟกๆฏ
*/
private fun visibleOilLayout(info: ConsumptionInfo) {
viewBinding?.includeAddContent?.apply {
if (useFuel(info.type)) {
contentOilLayout.visible()
contentOilTypeValue.text = ConsumptionInfo.FUEL_LABELS[info.oilType]
setupNumber(contentOilPrice, info.oilPrice)
} else {
contentOilLayout.gone()
}
}
}
/**
* ๅ ๆฒนใไฟๅ
ปๆถ๏ผๆพ็คบ้็จไฟกๆฏ
*/
private fun visibleMileageLayout(type: Int) {
viewBinding?.includeAddContent?.addConsumptionMileage?.apply {
if (useMileage(type)) visible() else gone()
}
}
/**
* ๆฑฝ่ฝฆไฟ้ฉใๆฑฝ่ฝฆ้
ไปถใๆฑฝ่ฝฆ่ดญไนฐใ่ฃ
ๆฝข้ฅฐๅๆถ๏ผๆพ็คบๆ ็ญพไฟกๆฏ
*/
private fun visibleTagLayout(type: Int) {
tagHintResId = when (type) {
// ๆฑฝ่ฝฆไฟ้ฉ
ConsumptionInfo.TYPE_PREMIUM -> R.string.hint_tag_premium
// ๆฑฝ่ฝฆ้
ไปถ
ConsumptionInfo.TYPE_ACCESSORIES -> R.string.hint_tag_accessories
// ๆฑฝ่ฝฆ่ดญไนฐ
ConsumptionInfo.TYPE_CAR_PURCHASE -> R.string.hint_tag_car_purchase
// ่ฃ
ๆฝข้ฅฐๅ
ConsumptionInfo.TYPE_DECORATION -> R.string.hint_tag_decoration
// ๅๆไปๆฌพ
ConsumptionInfo.TYPE_INSTALLMENT -> R.string.hint_tag_installment
else -> 0
}
viewBinding?.includeAddContent?.addConsumptionTag?.apply {
if (tagHintResId != 0) {
visible()
hint = string(tagHintResId)
} else gone()
}
}
private fun useTag(type: Int): Boolean {
return when (type) {
ConsumptionInfo.TYPE_PREMIUM, ConsumptionInfo.TYPE_ACCESSORIES,
ConsumptionInfo.TYPE_CAR_PURCHASE, ConsumptionInfo.TYPE_DECORATION,
ConsumptionInfo.TYPE_INSTALLMENT -> true
else -> false
}
}
private fun useMileage(type: Int): Boolean {
return when (type) {
ConsumptionInfo.TYPE_FUEL, ConsumptionInfo.TYPE_MAINTENANCE -> true
else -> false
}
}
private fun useFuel(type: Int): Boolean {
return when (type) {
ConsumptionInfo.TYPE_FUEL -> true
else -> false
}
}
private fun onSaveBefore() {
viewBinding?.includeAddContent?.apply {
target.amount = addConsumptionAmount.float()
if (tagHintResId != 0) target.tag = addConsumptionTag.text()
if (useFuel(target.type)) target.oilPrice = contentOilPrice.float()
if (useMileage(target.type)) target.mileage = addConsumptionMileage.long()
target.location = addConsumptionLocation.text()
target.remark = addConsumptionRemark.text()
}
}
private fun onAdd() {
onSaveBefore()
val time = System.currentTimeMillis()
target.createTime = time
target.lastUpdateTime = time
async {
try {
dataSource?.add(target)
} catch (e: Exception) {
e.printStackTrace()
null
}
} ui {
if (null != it && it > 0L) {
target.id = it
// ๆฐๆฎๅคไปฝ
onBackupItem(target)
DataManager.get().dispatchAdd(target)
toast(R.string.hint_add_success)
finish()
} else {
toast(R.string.hint_add_failure)
}
}
}
private fun onModify() {
onSaveBefore()
target.lastUpdateTime = System.currentTimeMillis()
async {
try {
dataSource?.modify(target)
} catch (e: Exception) {
e.printStackTrace()
null
}
} ui {
if (null != it && it > 0) {
// ๆฐๆฎๅคไปฝ
onBackupItem(target)
DataManager.get().dispatchUpdate(target)
toast(R.string.hint_modify_success)
finish()
} else {
toast(R.string.hint_modify_failure)
}
}
}
private fun onBackupItem(item: ConsumptionInfo) {
ioTask { BackupManager.append(item) }
}
private fun applyFilter(vararg views: EditText) {
val filters = arrayOf(CharFilter.defaultFilter())
views.forEach { it.filters = filters }
}
companion object {
private const val KEY_CONSUMPTION = "consumption"
fun start(context: Context, data: ConsumptionInfo? = null) {
val intent = Intent(context, AddActivity::class.java)
if (null != data) intent.putExtra(KEY_CONSUMPTION, data)
context.startActivity(intent)
}
}
}
| 4 | Kotlin | 100 | 423 | d1bf52291e288e3c1d1d1fd79f7cf3896dbb272d | 13,033 | CarAssistant | The Unlicense |
Kawa/src/main/kotlin/sibwaf/kawa/analysis/CtReturnAnalyzer.kt | dya-tel | 332,540,419 | false | null | package sibwaf.kawa.analysis
import sibwaf.kawa.AnalyzerState
import sibwaf.kawa.DataFrame
import sibwaf.kawa.ReachableFrame
import sibwaf.kawa.UnreachableFrame
import spoon.reflect.code.CtReturn
import spoon.reflect.code.CtStatement
class CtReturnAnalyzer : StatementAnalyzer {
override fun supports(statement: CtStatement) = statement is CtReturn<*>
override suspend fun analyze(state: AnalyzerState, statement: CtStatement): DataFrame {
statement as CtReturn<*>
val frame = if (statement.returnedExpression != null) {
state.getValue(statement.returnedExpression).first
} else {
state.frame
}
return if (frame is ReachableFrame) {
state.jumpPoints += statement to frame
UnreachableFrame.after(frame)
} else {
state.jumpPoints += statement to (frame as UnreachableFrame).previous
frame
}
}
} | 0 | Kotlin | 0 | 0 | f3ff039c6204a659e67554617178a78dc695d1f9 | 938 | Kawa | MIT License |
src/main/kotlin/me/clip/voteparty/conf/objects/CumulativeVoteRewards.kt | darbyjack | 194,936,662 | false | {"Kotlin": 101929, "Java": 835} | package me.clip.voteparty.conf.objects
internal data class CumulativeVoteRewards(
var enabled: Boolean = false,
var entries: List<CumulativeVoteCommands> = listOf(CumulativeVoteCommands(5, listOf("eco give %player_name% 500")))
) | 20 | Kotlin | 13 | 17 | 456c4c7565bfdaa1f917c7259486126e1f0abd2c | 232 | VoteParty | MIT License |
plugins/kotlin/idea/tests/testData/intentions/convertVariableAssignmentToExpression/complexRhs.kt | ingokegel | 72,937,917 | false | null | // WITH_STDLIB
object X {
var string = "foo"
}
var target = "baz"
fun main() {
target <caret>= X.string
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 115 | intellij-community | Apache License 2.0 |
features/fixtures/mazerunner/jvm-scenarios/src/main/java/com/bugsnag/android/mazerunner/scenarios/JvmMarkLaunchCompletedScenario.kt | bugsnag | 2,406,783 | false | null | package com.bugsnag.android.mazerunner.scenarios
import android.content.Context
import com.bugsnag.android.Bugsnag
import com.bugsnag.android.Configuration
/**
* Sends a JVM error to Bugsnag after markLaunchCompleted() is invoked.
*/
internal class JvmMarkLaunchCompletedScenario(
config: Configuration,
context: Context,
eventMetadata: String?
) : Scenario(config, context, eventMetadata) {
init {
config.launchDurationMillis = 0
}
override fun startScenario() {
super.startScenario()
Bugsnag.notify(RuntimeException("first error"))
Bugsnag.markLaunchCompleted()
Bugsnag.notify(generateException())
}
}
| 17 | null | 205 | 1,188 | f5fd26b3cdeda9c4d4e221f55feb982a3fd97197 | 678 | bugsnag-android | MIT License |
app/src/main/java/com/github/android/example/feature/main/domain/AppConfigRepository.kt | hammernetwork | 387,936,460 | false | {"Kotlin": 31929} | package com.github.android.example.feature.main.domain
interface AppConfigRepository {
suspend fun syncSomethings()
} | 0 | Kotlin | 0 | 0 | 35694b926aefa9e0d741e607621b4bc5e53c6f9e | 122 | android-mvvm-clean-architecture-hilt | Apache License 2.0 |
src/main/kotlin/features/texturepack/OrPredicate.kt | nea89o | 637,563,904 | false | {"Kotlin": 600801, "Java": 131606, "Nix": 1217} |
package moe.nea.firmament.features.texturepack
import com.google.gson.JsonArray
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import net.minecraft.item.ItemStack
class OrPredicate(val children: Array<FirmamentModelPredicate>) : FirmamentModelPredicate {
override fun test(stack: ItemStack): Boolean {
return children.any { it.test(stack) }
}
object Parser : FirmamentModelPredicateParser {
override fun parse(jsonElement: JsonElement): FirmamentModelPredicate {
val children =
(jsonElement as JsonArray)
.flatMap {
CustomModelOverrideParser.parsePredicates(it as JsonObject)
}
.toTypedArray()
return OrPredicate(children)
}
}
}
| 25 | Kotlin | 6 | 37 | 9cdc30e024fac9fe04eeeccb15dfd46f4aa648cb | 820 | Firmament | Apache License 2.0 |
src/jvmMain/kotlin/dev/jjerrell/kenvironment/ktor/DefaultLogger.kt | jjerrell | 696,076,681 | false | {"Kotlin": 12648} | package dev.jjerrell.kenvironment.ktor
import io.ktor.util.logging.*
import org.slf4j.Marker
object DefaultLogger : Logger {
var level: Level = Level.INFO
override fun getName(): String = "Default"
override fun isTraceEnabled(): Boolean = level == Level.TRACE
override fun isTraceEnabled(marker: Marker?): Boolean = isTraceEnabled()
override fun isDebugEnabled(): Boolean = level == Level.DEBUG
override fun isDebugEnabled(marker: Marker?): Boolean = isDebugEnabled()
override fun isInfoEnabled(): Boolean = level == Level.INFO
override fun isInfoEnabled(marker: Marker?): Boolean = isInfoEnabled()
override fun isWarnEnabled(): Boolean = level == Level.WARN
override fun isWarnEnabled(marker: Marker?): Boolean = isWarnEnabled()
override fun isErrorEnabled(): Boolean = level == Level.ERROR
override fun isErrorEnabled(marker: Marker?): Boolean = isErrorEnabled()
//region TRACE
override fun trace(msg: String?) {
logRecord(msg)
}
override fun trace(format: String?, arg: Any?) {
logRecord(format, arg)
}
override fun trace(format: String?, arg1: Any?, arg2: Any?) {
logRecord(format, arg1, arg2)
}
override fun trace(format: String?, vararg arguments: Any?) {
logRecord(format, *arguments)
}
override fun trace(msg: String?, t: Throwable?) {
logRecord(msg, t)
}
override fun trace(marker: Marker?, msg: String?) {
logRecord(marker, msg)
}
override fun trace(marker: Marker?, format: String?, arg: Any?) {
logRecord(marker, format, arg)
}
override fun trace(marker: Marker?, format: String?, arg1: Any?, arg2: Any?) {
logRecord(marker, format, arg1, arg2)
}
override fun trace(marker: Marker?, format: String?, vararg argArray: Any?) {
logRecord(marker, format, *argArray)
}
override fun trace(marker: Marker?, msg: String?, t: Throwable?) {
logRecord(marker, msg, t)
}
//endregion
//region DEBUG
override fun debug(msg: String?) {
logRecord(msg)
}
override fun debug(format: String?, arg: Any?) {
logRecord(format, arg)
}
override fun debug(format: String?, arg1: Any?, arg2: Any?) {
logRecord(format, arg1, arg2)
}
override fun debug(format: String?, vararg arguments: Any?) {
logRecord(format, *arguments)
}
override fun debug(msg: String?, t: Throwable?) {
logRecord(msg, t)
}
override fun debug(marker: Marker?, msg: String?) {
logRecord(marker, msg)
}
override fun debug(marker: Marker?, format: String?, arg: Any?) {
logRecord(marker, format, arg)
}
override fun debug(marker: Marker?, format: String?, arg1: Any?, arg2: Any?) {
logRecord(marker, format, arg1, arg2)
}
override fun debug(marker: Marker?, format: String?, vararg arguments: Any?) {
logRecord(marker, format, *arguments)
}
override fun debug(marker: Marker?, msg: String?, t: Throwable?) {
logRecord(marker, msg, t)
}
//endregion
//region INFO
override fun info(msg: String?) {
logRecord(msg)
}
override fun info(format: String?, arg: Any?) {
logRecord(format, arg)
}
override fun info(format: String?, arg1: Any?, arg2: Any?) {
logRecord(format, arg1, arg2)
}
override fun info(format: String?, vararg arguments: Any?) {
logRecord(format, *arguments)
}
override fun info(msg: String?, t: Throwable?) {
logRecord(msg, t)
}
override fun info(marker: Marker?, msg: String?) {
logRecord(marker, msg)
}
override fun info(marker: Marker?, format: String?, arg: Any?) {
logRecord(marker, format, arg)
}
override fun info(marker: Marker?, format: String?, arg1: Any?, arg2: Any?) {
logRecord(marker, format, arg1, arg2)
}
override fun info(marker: Marker?, format: String?, vararg arguments: Any?) {
logRecord(marker, format, *arguments)
}
override fun info(marker: Marker?, msg: String?, t: Throwable?) {
logRecord(marker, msg, t)
}
//endregion
//region WARN
override fun warn(msg: String?) {
logRecord(msg)
}
override fun warn(format: String?, arg: Any?) {
logRecord(format, arg)
}
override fun warn(format: String?, vararg arguments: Any?) {
logRecord(format, *arguments)
}
override fun warn(format: String?, arg1: Any?, arg2: Any?) {
logRecord(format, arg1, arg2)
}
override fun warn(msg: String?, t: Throwable?) {
logRecord(msg, t)
}
override fun warn(marker: Marker?, msg: String?) {
logRecord(marker, msg)
}
override fun warn(marker: Marker?, format: String?, arg: Any?) {
logRecord(marker, format, arg)
}
override fun warn(marker: Marker?, format: String?, arg1: Any?, arg2: Any?) {
logRecord(marker, format, arg1, arg2)
}
override fun warn(marker: Marker?, format: String?, vararg arguments: Any?) {
logRecord(marker, format, *arguments)
}
override fun warn(marker: Marker?, msg: String?, t: Throwable?) {
logRecord(marker, msg, t)
}
//endregion
//region ERROR
override fun error(msg: String?) {
logRecord(msg)
}
override fun error(format: String?, arg: Any?) {
logRecord(format, arg)
}
override fun error(format: String?, arg1: Any?, arg2: Any?) {
logRecord(format, arg1, arg2)
}
override fun error(format: String?, vararg arguments: Any?) {
logRecord(format, *arguments)
}
override fun error(msg: String?, t: Throwable?) {
logRecord(msg, t)
}
override fun error(marker: Marker?, msg: String?) {
logRecord(marker, msg)
}
override fun error(marker: Marker?, format: String?, arg: Any?) {
logRecord(marker, format, arg)
}
override fun error(marker: Marker?, format: String?, arg1: Any?, arg2: Any?) {
logRecord(marker, format, arg1, arg2)
}
override fun error(marker: Marker?, format: String?, vararg arguments: Any?) {
logRecord(marker, format, *arguments)
}
override fun error(marker: Marker?, msg: String?, t: Throwable?) {
logRecord(marker, msg, t)
}
//endregion
//region Base logging methods
private fun logRecord(msg: String?) {
if (level.isEnabled && msg != null) {
println(msg)
}
}
private fun logRecord(format: String?, arg: Any?) {
if (level.isEnabled && format != null) {
println(String.format(format, arg))
}
}
private fun logRecord(format: String?, arg1: Any?, arg2: Any?) {
if (level.isEnabled && format != null) {
println(String.format(format, arg1, arg2))
}
}
private fun logRecord(format: String?, vararg arguments: Any?) {
if (level.isEnabled && format != null) {
println(String.format(format, arguments))
}
}
private fun logRecord(msg: String?, t: Throwable?) {
if (level.isEnabled) {
buildString {
msg?.let { message ->
appendLine("Primary message: $message")
}
t?.let { exception ->
exception.message?.let { message ->
appendLine("Thrown message: $message")
}
appendLine("Stack trace: ${exception.stackTraceToString()}")
}
}.takeUnless { it.isBlank() }?.let { traceString ->
print(traceString)
}
}
}
private fun logRecord(marker: Marker?, msg: String?) {
if (level.isEnabled) {
marker?.let { println("Marker: $it") }
logRecord(msg)
}
}
private fun logRecord(marker: Marker?, format: String?, arg: Any?) {
if (level.isEnabled) {
marker?.let { println("Marker: $it") }
logRecord(format, arg)
}
}
private fun logRecord(marker: Marker?, format: String?, arg1: Any?, arg2: Any?) {
if (level.isEnabled) {
marker?.let { println("Marker: $it") }
logRecord(format, arg1, arg2)
}
}
private fun logRecord(marker: Marker?, format: String?, vararg arguments: Any?) {
if (level.isEnabled) {
marker?.let { println("Marker: $it") }
logRecord(format, *arguments)
}
}
private fun logRecord(marker: Marker?, msg: String?, t: Throwable?) {
if (level.isEnabled) {
marker?.let { println("Marker: $it") }
logRecord(msg, t)
}
}
//endregion
enum class Level {
TRACE, DEBUG, INFO, WARN, ERROR;
val isEnabled: Boolean
get() = when (this) {
TRACE -> isTraceEnabled()
DEBUG -> isDebugEnabled()
INFO -> isInfoEnabled()
WARN -> isWarnEnabled()
ERROR -> isErrorEnabled()
}
}
} | 5 | Kotlin | 0 | 0 | 75c51514206939dbe6314ce3781147c602004668 | 9,156 | Kenvironment | MIT License |
plugins/kotlin/code-insight/inspections-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/inspections/ImplicitThisInspection.kt | jinsihou19 | 192,350,885 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.k2.codeinsight.inspections
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.components.KtImplicitReceiver
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.analysis.api.types.KtFunctionalType
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.*
import org.jetbrains.kotlin.idea.codeinsight.api.applicable.inspections.AbstractKotlinApplicableInspectionWithContext
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicabilityRange
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.renderer.render
internal class ImplicitThisInspection :
AbstractKotlinApplicableInspectionWithContext<KtExpression, ImplicitThisInspection.ImplicitReceiverInfo>(KtExpression::class) {
data class ImplicitReceiverInfo(
val receiverLabel: Name?,
val isUnambiguousLabel: Boolean
)
override fun getProblemDescription(element: KtExpression, context: ImplicitReceiverInfo): String =
KotlinBundle.message("inspection.implicit.this.display.name")
override fun getActionFamilyName(): String = KotlinBundle.message("inspection.implicit.this.action.name")
override fun getApplicabilityRange(): KotlinApplicabilityRange<KtExpression> = ApplicabilityRanges.SELF
override fun isApplicableByPsi(element: KtExpression): Boolean {
return when (element) {
is KtSimpleNameExpression -> {
if (element !is KtNameReferenceExpression) return false
if (element.parent is KtThisExpression) return false
if (element.parent is KtCallableReferenceExpression) return false
if (element.isSelectorOfDotQualifiedExpression()) return false
val parent = element.parent
if (parent is KtCallExpression && parent.isSelectorOfDotQualifiedExpression()) return false
true
}
is KtCallableReferenceExpression -> element.receiverExpression == null
else -> false
}
}
context(KtAnalysisSession)
override fun prepareContext(element: KtExpression): ImplicitReceiverInfo? {
val reference = if (element is KtCallableReferenceExpression) element.callableReference else element
val declarationSymbol = reference.mainReference?.resolveToSymbol() ?: return null
// Get associated class symbol on declaration-site
val declarationAssociatedClass = getAssociatedClass(declarationSymbol) ?: return null
// Getting the implicit receiver
val allImplicitReceivers = reference.containingKtFile.getScopeContextForPosition(reference).implicitReceivers
return getImplicitReceiverInfoOfClass(allImplicitReceivers, declarationAssociatedClass)
}
override fun apply(element: KtExpression, context: ImplicitReceiverInfo, project: Project, editor: Editor?) {
element.addImplicitThis(context)
}
}
context(KtAnalysisSession)
private fun getAssociatedClass(symbol: KtSymbol): KtClassOrObjectSymbol? {
// both variables and functions are callable and only they can be referenced by "this"
if (symbol !is KtCallableSymbol) return null
return when (symbol) {
is KtFunctionSymbol, is KtPropertySymbol ->
if (symbol.isExtension) symbol.receiverType?.expandedClassSymbol else symbol.getContainingSymbol() as? KtClassOrObjectSymbol
is KtVariableLikeSymbol -> {
val variableType = symbol.returnType as? KtFunctionalType
variableType?.receiverType?.expandedClassSymbol
}
else -> null
}
}
context(KtAnalysisSession)
private fun getImplicitReceiverInfoOfClass(
implicitReceivers: List<KtImplicitReceiver>, associatedClass: KtClassOrObjectSymbol
): ImplicitThisInspection.ImplicitReceiverInfo? {
// We can't use "this" with label if the label is already taken
val alreadyReservedLabels = mutableListOf<Name>()
var isInnermostReceiver = true
for (receiver in implicitReceivers) {
val (receiverClass, receiverLabel) = getImplicitReceiverClassAndTag(receiver) ?: return null
if (receiverClass == associatedClass) {
if (receiverLabel in alreadyReservedLabels) return null
return if (isInnermostReceiver || receiverLabel != null) ImplicitThisInspection.ImplicitReceiverInfo(
receiverLabel,
isInnermostReceiver
) else null
}
receiverLabel?.let { alreadyReservedLabels.add(it) }
isInnermostReceiver = false
}
return null
}
context(KtAnalysisSession)
private fun getImplicitReceiverClassAndTag(receiver: KtImplicitReceiver): Pair<KtClassOrObjectSymbol, Name?>? {
val associatedClass = receiver.type.expandedClassSymbol ?: return null
val associatedTag: Name? = when (val receiverSymbol = receiver.ownerSymbol) {
is KtClassOrObjectSymbol -> receiverSymbol.name
is KtAnonymousFunctionSymbol -> {
val receiverPsi = receiverSymbol.psi
val potentialLabeledPsi = receiverPsi?.parent?.parent
if (potentialLabeledPsi is KtLabeledExpression) potentialLabeledPsi.getLabelNameAsName()
else {
val potentialCallExpression = potentialLabeledPsi?.parent as? KtCallExpression
val potentialCallNameReference = (potentialCallExpression?.calleeExpression as? KtNameReferenceExpression)
potentialCallNameReference?.getReferencedNameAsName()
}
}
is KtFunctionSymbol -> receiverSymbol.name
else -> null
}
return Pair(associatedClass, associatedTag)
}
private fun KtExpression.isSelectorOfDotQualifiedExpression(): Boolean {
val parent = parent
return parent is KtDotQualifiedExpression && parent.selectorExpression == this
}
private fun KtExpression.addImplicitThis(input: ImplicitThisInspection.ImplicitReceiverInfo) {
val reference = if (this is KtCallableReferenceExpression) callableReference else this
val thisExpressionText = if (input.isUnambiguousLabel) "this" else "this@${input.receiverLabel?.render()}"
val factory = KtPsiFactory(project)
with(reference) {
when (parent) {
is KtCallExpression -> parent.replace(factory.createExpressionByPattern("$0.$1", thisExpressionText, parent))
is KtCallableReferenceExpression -> parent.replace(
factory.createExpressionByPattern(
"$0::$1", thisExpressionText, this
)
)
else -> this.replace(factory.createExpressionByPattern("$0.$1", thisExpressionText, this))
}
}
}
| 1 | null | 1 | 1 | 55cb0396e166a3f4e114a59e9357d2e390a6dd96 | 7,152 | intellij-community | Apache License 2.0 |
src/main/kotlin/org.danilopianini.gradle.mavencentral/Configuration.kt | DanySK | 175,677,936 | false | null | package org.danilopianini.gradle.mavencentral
import org.gradle.api.Project
import org.gradle.api.provider.Property
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.publish.maven.tasks.PublishToMavenRepository
import org.gradle.api.publish.plugins.PublishingPlugin
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.create
import org.gradle.kotlin.dsl.the
import org.gradle.kotlin.dsl.withType
import java.net.URI
internal inline fun <reified T> Project.propertyWithDefault(default: T?): Property<T> =
objects.property(T::class.java).apply { convention(default) }
internal inline fun <reified T> Project.propertyWithDefaultProvider(noinline default: () -> T?): Property<T> =
objects.property(T::class.java).apply { convention(provider(default)) }
/**
* Configures the pom.xml file of a [MavenPublication] with the information specified in this configuration.
*/
fun MavenPublication.configurePomForMavenCentral(extension: PublishOnCentralExtension) {
pom { pom ->
with(pom) {
name.set(extension.projectLongName)
description.set(extension.projectDescription)
packaging = "jar"
url.set(extension.projectUrl)
licenses {
it.license { license ->
license.name.set(extension.licenseName)
license.url.set(extension.licenseUrl)
}
}
scm { scm ->
scm.url.set(extension.projectUrl)
scm.connection.set(extension.scmConnection)
scm.developerConnection.set(extension.scmConnection)
}
}
}
}
/**
* Reifies this repository setup onto every [PublishingExtension] configuration of the provided [project].
*/
fun Project.configureRepository(repoToConfigure: Repository) {
extensions.configure(PublishingExtension::class) { publishing ->
publishing.repositories { repository ->
repository.maven { mavenArtifactRepository ->
mavenArtifactRepository.name = repoToConfigure.name
mavenArtifactRepository.url = URI(repoToConfigure.url)
mavenArtifactRepository.credentials { credentials ->
credentials.username = repoToConfigure.user.orNull
credentials.password = <PASSWORD>orNull
}
tasks.withType(PublishToMavenRepository::class) {
if (it.repository == mavenArtifactRepository) {
it.doFirst {
warnIfCredentialsAreMissing(repoToConfigure)
}
}
}
}
}
}
if (repoToConfigure.nexusUrl != null) {
configureNexusRepository(repoToConfigure, repoToConfigure.nexusUrl)
}
}
private fun Project.configureNexusRepository(repoToConfigure: Repository, nexusUrl: String) {
the<PublishingExtension>().publications.withType<MavenPublication>().forEach { publication ->
val nexus = NexusStatefulOperation(
project = project,
nexusUrl = nexusUrl,
group = project.group.toString(),
user = repoToConfigure.user,
password = <PASSWORD>,
timeOut = repoToConfigure.nexusTimeOut,
connectionTimeOut = repoToConfigure.nexusConnectTimeOut,
)
val publicationName = publication.name.replaceFirstChar(Char::titlecase)
val uploadArtifacts = project.tasks.create(
"upload${publicationName}To${repoToConfigure.name}Nexus",
PublishToMavenRepository::class,
) { publishTask ->
publishTask.repository = project.repositories.maven { repo ->
repo.name = repoToConfigure.name
repo.url = project.uri(repoToConfigure.url)
repo.credentials {
it.username = repoToConfigure.user.orNull
it.password = <PASSWORD>
}
}
publishTask.doFirst {
warnIfCredentialsAreMissing(repoToConfigure)
publishTask.repository.url = nexus.repoUrl
}
publishTask.publication = publication
publishTask.group = PublishingPlugin.PUBLISH_TASK_GROUP
publishTask.description = "Initializes a new Nexus repository on ${repoToConfigure.name} " +
"and uploads the $publicationName publication."
}
val closeRepository = tasks.create("close${publicationName}On${repoToConfigure.name}Nexus") {
it.doLast { nexus.close() }
it.dependsOn(uploadArtifacts)
it.group = PublishingPlugin.PUBLISH_TASK_GROUP
it.description = "Closes the Nexus repository on ${repoToConfigure.name} with the " +
"$publicationName publication."
}
tasks.create("release${publicationName}On${repoToConfigure.name}Nexus") {
it.doLast { nexus.release() }
it.dependsOn(closeRepository)
it.group = PublishingPlugin.PUBLISH_TASK_GROUP
it.description = "Releases the Nexus repo on ${repoToConfigure.name} " +
"with the $publicationName publication."
}
}
}
private fun Project.warnIfCredentialsAreMissing(repository: Repository) {
if (repository.user.orNull == null) {
logger.warn(
"No username configured for repository {} at {}.",
repository.name,
repository.url,
)
}
if (repository.password.orNull == null) {
logger.warn(
"No password configured for user {} on repository {} at {}.",
repository.user.orNull,
repository.name,
repository.url,
)
}
}
| 1 | Kotlin | 1 | 13 | 1ac2f0fc7ddb2eb15b6fab6341cc94fdf3547d7c | 5,862 | maven-central-gradle-plugin | Apache License 2.0 |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/quicksight/CfnAnalysisParameterSelectableValuesPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION")
package cloudshift.awscdk.dsl.services.quicksight
import cloudshift.awscdk.common.CdkDslMarker
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.quicksight.CfnAnalysis
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.MutableList
/**
* A list of selectable values that are used in a control.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.quicksight.*;
* ParameterSelectableValuesProperty parameterSelectableValuesProperty =
* ParameterSelectableValuesProperty.builder()
* .linkToDataSetColumn(ColumnIdentifierProperty.builder()
* .columnName("columnName")
* .dataSetIdentifier("dataSetIdentifier")
* .build())
* .values(List.of("values"))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-analysis-parameterselectablevalues.html)
*/
@CdkDslMarker
public class CfnAnalysisParameterSelectableValuesPropertyDsl {
private val cdkBuilder: CfnAnalysis.ParameterSelectableValuesProperty.Builder =
CfnAnalysis.ParameterSelectableValuesProperty.builder()
private val _values: MutableList<String> = mutableListOf()
/**
* @param linkToDataSetColumn The column identifier that fetches values from the data set.
*/
public fun linkToDataSetColumn(linkToDataSetColumn: IResolvable) {
cdkBuilder.linkToDataSetColumn(linkToDataSetColumn)
}
/**
* @param linkToDataSetColumn The column identifier that fetches values from the data set.
*/
public fun linkToDataSetColumn(linkToDataSetColumn: CfnAnalysis.ColumnIdentifierProperty) {
cdkBuilder.linkToDataSetColumn(linkToDataSetColumn)
}
/**
* @param values The values that are used in `ParameterSelectableValues` .
*/
public fun values(vararg values: String) {
_values.addAll(listOf(*values))
}
/**
* @param values The values that are used in `ParameterSelectableValues` .
*/
public fun values(values: Collection<String>) {
_values.addAll(values)
}
public fun build(): CfnAnalysis.ParameterSelectableValuesProperty {
if (_values.isNotEmpty()) cdkBuilder.values(_values)
return cdkBuilder.build()
}
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 2,580 | awscdk-dsl-kotlin | Apache License 2.0 |
hazelnet-community/src/main/kotlin/io/hazelnet/community/persistence/DiscordPaymentRepository.kt | nilscodes | 446,203,879 | false | {"TypeScript": 1045486, "Kotlin": 810416, "Dockerfile": 4476, "Shell": 1830, "JavaScript": 1384} | package io.hazelnet.community.persistence
import io.hazelnet.community.data.premium.DiscordPayment
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.CrudRepository
import org.springframework.data.repository.query.Param
import org.springframework.stereotype.Repository
import java.util.*
@Repository
interface DiscordPaymentRepository: CrudRepository<DiscordPayment, Int> {
@Query(value = "SELECT SUM(payment_amount) FROM discord_payments WHERE discord_server_id=:discordServerId", nativeQuery = true)
fun getCurrentBalance(@Param("discordServerId") discordServerId: Int): Optional<Long>
} | 0 | TypeScript | 4 | 13 | 79f8b096f599255acb03cc809464d0570a51d82c | 645 | hazelnet | Apache License 2.0 |
app/src/main/java/com/dominate/caravan/ui/home/HomeFragment.kt | NoorAlnajjar1993 | 720,250,705 | false | {"Gradle": 5, "Java Properties": 7, "Shell": 1, "Text": 20, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 155, "XML": 709, "JSON": 154, "Java": 501, "Motorola 68K Assembly": 12, "SQL": 6, "INI": 4, "Ignore List": 1} | package com.dominate.caravan.ui.home
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.viewpager.widget.ViewPager
import com.caravan.R
import com.caravan.databinding.FragmentHomeBinding
import com.dominate.caravan.core.base.BaseFragment
import com.dominate.caravan.core.showLoginDialog
import com.dominate.caravan.medule.home.Banner
import com.dominate.caravan.medule.home.CommercialAd
import com.dominate.caravan.medule.home.CommercialEstate
import com.dominate.caravan.medule.home.HousingAd
import com.dominate.caravan.medule.home.RealEstateAd
import com.dominate.caravan.ui.estatedetails.EstateDetailsFragment
import com.dominate.caravan.ui.home.adapter.CommercialAdsAdapter
import com.dominate.caravan.ui.home.adapter.CommercialEstatesAdapter
import com.dominate.caravan.ui.home.adapter.HousingAdsAdapter
import com.dominate.caravan.ui.home.adapter.RealEstateAdsAdapter
import com.dominate.caravan.utils.Resource
import dagger.hilt.android.AndroidEntryPoint
import java.util.Timer
import java.util.TimerTask
@AndroidEntryPoint
class HomeFragment : BaseFragment() {
lateinit var binding: FragmentHomeBinding
private val viewModel: HomeViewModel by viewModels()
lateinit var housingAdsAdapter: HousingAdsAdapter
lateinit var realEstateAdsAdapter: RealEstateAdsAdapter
lateinit var commercialEstatesAdapter: CommercialEstatesAdapter
lateinit var commercialAdsAdapter: CommercialAdsAdapter
lateinit var bannerAdapter: BannerAdapter
var maxCount = 2
var token: String? = ""
var currentPage = 0
var NUM_PAGES = 5
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setData()
setRecycleView()
}
private fun setData() {
try {
token = prefs.getCurrentUser().token.toString()
} catch (_: Exception) {
}
val slideUpAnimation: Animation = AnimationUtils.loadAnimation(
requireContext(),
R.anim.slide_up
)
binding.constraintLayout01.startAnimation(slideUpAnimation)
binding.viewPager.startAnimation(slideUpAnimation)
binding.tabLayout.startAnimation(slideUpAnimation)
binding.tvHousingAds.startAnimation(slideUpAnimation)
binding.tvMoreHousingAds.startAnimation(slideUpAnimation)
binding.rvHousingAds.startAnimation(slideUpAnimation)
binding.tvMoreRealEstateAds.startAnimation(slideUpAnimation)
binding.tvRealEstateAds.startAnimation(slideUpAnimation)
binding.rvRealEstateAds.startAnimation(slideUpAnimation)
binding.constraintLayout02.startAnimation(slideUpAnimation)
binding.tvMoreCommercialEstates.startAnimation(slideUpAnimation)
binding.tvCommercialEstates.startAnimation(slideUpAnimation)
binding.rvCommercialEstates.startAnimation(slideUpAnimation)
binding.tvMoreCommercialAds.startAnimation(slideUpAnimation)
binding.tvCommercialAds.startAnimation(slideUpAnimation)
binding.rvCommercialAds.startAnimation(slideUpAnimation)
binding.rvCommercialAds.startAnimation(slideUpAnimation)
Handler().postDelayed({
binding.loading.visibility = View.GONE
}, 2000)
// binding.viewPager.setPageTransformer(true, ZoomOutPageTransformer())
val handler = Handler()
val update = Runnable {
if (currentPage == NUM_PAGES) {
currentPage = 0
}
binding.viewPager.setCurrentItem(currentPage++, true)
}
Timer().schedule(object : TimerTask() {
override fun run() {
handler.post(update)
}
}, 400, 10000)
binding.btnSearchNow.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_searchFragment)
}
binding.tvMoreHousingAds.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_housingAdsFragment)
}
binding.tvMoreCommercialEstates.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_commercialEstateFragment)
}
binding.tvMoreRealEstateAds.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_realEstateAdsFragment2)
}
binding.tvMoreCommercialAds.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_commercialAdsFragment)
}
binding.btnPostAdNow.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_addAdsFragment)
}
observeHome()
}
fun observeHome() {
viewModel.getHome()
viewModel.getHomeResponse.observe(viewLifecycleOwner, Observer {
if (it.status == Resource.Status.SUCCESS) {
if (it.data?.status?.code == 200) {
it.data!!.let { it ->
bannerSetData(it.results.banners)
if (it.results.housing_ads.size > maxCount) {
binding.tvMoreHousingAds.visibility = View.VISIBLE
val housing_ads_list: MutableList<HousingAd> = mutableListOf()
for (i in 0..maxCount) {
housing_ads_list.add(it.results.housing_ads[i])
}
housingAdsData(housing_ads_list)
} else {
binding.tvMoreHousingAds.visibility = View.INVISIBLE
housingAdsData(it.results.housing_ads)
}
if (it.results.real_estate_ads.size > maxCount) {
binding.tvMoreRealEstateAds.visibility = View.VISIBLE
val real_estate_ads_list: MutableList<RealEstateAd> = mutableListOf()
for (i in 0..maxCount) {
real_estate_ads_list.add(it.results.real_estate_ads[i])
}
realEstateAdsData(real_estate_ads_list)
} else {
binding.tvMoreRealEstateAds.visibility = View.INVISIBLE
realEstateAdsData(it.results.real_estate_ads)
}
if (it.results.commercial_estates.size > maxCount) {
binding.tvMoreCommercialEstates.visibility = View.VISIBLE
val commercial_estates_list: MutableList<CommercialEstate> = mutableListOf()
for (i in 0..maxCount) {
commercial_estates_list.add(it.results.commercial_estates[i])
}
commercialEstatesData(commercial_estates_list)
} else {
binding.tvMoreCommercialEstates.visibility = View.INVISIBLE
commercialEstatesData(it.results.commercial_estates)
}
if (it.results.commercial_ads.size > maxCount) {
binding.tvMoreCommercialAds.visibility = View.VISIBLE
val CommercialEstate_list: MutableList<CommercialAd> = mutableListOf()
for (i in 0..maxCount) {
CommercialEstate_list.add(it.results.commercial_ads[i])
}
commercialAdsData(CommercialEstate_list)
} else {
binding.tvMoreCommercialAds.visibility = View.INVISIBLE
commercialAdsData(it.results.commercial_ads)
}
}
} else {
Toast.makeText(
context,
it.data?.status?.message.toString(),
Toast.LENGTH_SHORT
).show()
}
}
if (it.status == Resource.Status.ERROR) {
Toast.makeText(
context,
it.message.toString(),
Toast.LENGTH_SHORT
).show()
}
})
}
private fun housingAdsData(housingAds: MutableList<HousingAd>) {
if (housingAds.isNotEmpty()) {
housingAdsAdapter = HousingAdsAdapter(housingAds, {
if (prefs.isLoggedIn && !token.isNullOrEmpty()) {
it!!.is_favorite = !it.is_favorite
AddRemoveFavorite(id = it.id, it.is_favorite)
} else {
// IF USER NOT LOGIN SHOW DIALOG
requireContext().showLoginDialog(
onPositiveButtonClick = {
findNavController().navigate(R.id.action_homeFragment_to_sigininFragment)
it.dismiss()
}, onNegativeButtonClick = {
it.dismiss()
})
}
}, {
EstateDetailsFragment.housing = it!!
EstateDetailsFragment.type = "housing"
findNavController().navigate(R.id.action_homeFragment_to_estateDetailsFragment)
})
housingAdsAdapter.notifyDataSetChanged()
binding.rvHousingAds.adapter = housingAdsAdapter
} else {
binding.tvHousingAds.visibility = View.GONE
binding.tvMoreHousingAds.visibility = View.GONE
}
}
private fun realEstateAdsData(realEstateAds: MutableList<RealEstateAd>) {
if (realEstateAds.isNotEmpty()) {
realEstateAdsAdapter = RealEstateAdsAdapter(realEstateAds, {
if (prefs.isLoggedIn && !token.isNullOrEmpty()) {
it!!.is_favorite = !it.is_favorite
AddRemoveFavorite(id = it.id, it.is_favorite)
} else {
// IF USER NOT LOGIN SHOW DIALOG
requireContext().showLoginDialog(
onPositiveButtonClick = {
findNavController().navigate(R.id.action_homeFragment_to_sigininFragment)
it.dismiss()
}, onNegativeButtonClick = {
it.dismiss()
})
}
}, {
EstateDetailsFragment.realEstate = it!!
EstateDetailsFragment.type = "real_estate"
findNavController().navigate(R.id.action_homeFragment_to_estateDetailsFragment)
})
realEstateAdsAdapter.notifyDataSetChanged()
binding.rvRealEstateAds.adapter = realEstateAdsAdapter
} else {
binding.tvRealEstateAds.visibility = View.GONE
binding.tvMoreRealEstateAds.visibility = View.GONE
}
}
private fun commercialEstatesData(commercialEstates: MutableList<CommercialEstate>) {
if (commercialEstates.isNotEmpty()) {
commercialEstatesAdapter = CommercialEstatesAdapter(commercialEstates, {
if (prefs.isLoggedIn && !token.isNullOrEmpty()) {
it!!.is_favorite = !it.is_favorite
AddRemoveFavorite(id = it.id, it.is_favorite)
} else {
// IF USER NOT LOGIN SHOW DIALOG
requireContext().showLoginDialog(
onPositiveButtonClick = {
findNavController().navigate(R.id.action_homeFragment_to_sigininFragment)
it.dismiss()
}, onNegativeButtonClick = {
it.dismiss()
})
}
}, {
EstateDetailsFragment.commertcial_estate = it!!
EstateDetailsFragment.type = "commertcial_estate"
findNavController().navigate(R.id.action_homeFragment_to_estateDetailsFragment)
})
commercialEstatesAdapter.notifyDataSetChanged()
binding.rvCommercialEstates.adapter = commercialEstatesAdapter
} else {
binding.tvCommercialEstates.visibility = View.GONE
binding.tvMoreCommercialEstates.visibility = View.GONE
}
}
private fun commercialAdsData(commercialAds: MutableList<CommercialAd>) {
if (commercialAds.isNotEmpty()) {
commercialAdsAdapter = CommercialAdsAdapter(commercialAds, {
if (prefs.isLoggedIn && !token.isNullOrEmpty()) {
it!!.is_favorite = !it.is_favorite!!
it.id?.let { it1 -> AddRemoveFavorite(id = it1, it.is_favorite!!) }
} else {
// IF USER NOT LOGIN SHOW DIALOG
requireContext().showLoginDialog(
onPositiveButtonClick = {
findNavController().navigate(R.id.action_homeFragment_to_sigininFragment)
it.dismiss()
}, onNegativeButtonClick = {
it.dismiss()
})
}
}, {
EstateDetailsFragment.commertcial = it!!
EstateDetailsFragment.type = "commertcial"
findNavController().navigate(R.id.action_homeFragment_to_estateDetailsFragment)
})
commercialAdsAdapter.notifyDataSetChanged()
binding.rvCommercialAds.adapter = commercialAdsAdapter
} else {
binding.tvMoreCommercialAds.visibility = View.GONE
binding.tvCommercialAds.visibility = View.GONE
}
}
private fun AddRemoveFavorite(id: Int, isFavorite: Boolean) {
if (isFavorite) {
id.let { id ->
viewModel.addFavoriteItem(
token!!, id
)
}
viewModel.addFavoriteResponse.observe(
viewLifecycleOwner
) {
if (it.status == Resource.Status.SUCCESS) {
} else if (it.status == Resource.Status.ERROR) {
Toast.makeText(
requireContext(),
it.message,
Toast.LENGTH_SHORT
)
.show()
}
}
} else {
id.let { id ->
viewModel.removeFavoriteItem(
token!!, id
)
}
viewModel.removeFavoriteResponse.observe(
viewLifecycleOwner
) {
if (it.status == Resource.Status.SUCCESS) {
} else if (it.status == Resource.Status.ERROR) {
Toast.makeText(
requireContext(),
it.message,
Toast.LENGTH_SHORT
)
.show()
}
}
}
}
private fun bannerSetData(banners: MutableList<Banner>) {
if (banners.isNotEmpty()) {
bannerAdapter = BannerAdapter(requireContext(), banners) {
openUrl(context = requireContext(), it!!.link)
}
bannerAdapter.notifyDataSetChanged()
binding.viewPager.adapter = bannerAdapter
binding.tabLayout.setupWithViewPager(binding.viewPager, true)
} else {
binding.viewPager.visibility = View.GONE
binding.tabLayout.visibility = View.GONE
}
}
fun openUrl(context: Context, url: String) = try {
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
true
} catch (exception: ActivityNotFoundException) {
Log.d("exception", exception.toString())
false
}
private fun setRecycleView() {
}
}
private const val MIN_SCALE = 0.85f
private const val MIN_ALPHA = 0.5f
class ZoomOutPageTransformer : ViewPager.PageTransformer {
override fun transformPage(view: View, position: Float) {
view.apply {
val pageWidth = width
val pageHeight = height
when {
position < -1 -> { // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0f
}
position <= 1 -> { // [-1,1]
// Modify the default slide transition to shrink the page as well
val scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position))
val vertMargin = pageHeight * (1 - scaleFactor) / 2
val horzMargin = pageWidth * (1 - scaleFactor) / 2
translationX = if (position < 0) {
horzMargin - vertMargin / 2
} else {
horzMargin + vertMargin / 2
}
// Scale the page down (between MIN_SCALE and 1)
scaleX = scaleFactor
scaleY = scaleFactor
// Fade the page relative to its size.
alpha = (MIN_ALPHA +
(((scaleFactor - MIN_SCALE) / (1 - MIN_SCALE)) * (1 - MIN_ALPHA)))
}
else -> { // (1,+Infinity]
// This page is way off-screen to the right.
alpha = 0f
}
}
}
}
} | 0 | Java | 0 | 0 | 909f22dbfea3d01cbd10529248763f0fceddf7f0 | 18,476 | caravan | MIT License |
app/src/main/java/com/dominate/caravan/ui/home/HomeFragment.kt | NoorAlnajjar1993 | 720,250,705 | false | {"Gradle": 5, "Java Properties": 7, "Shell": 1, "Text": 20, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 155, "XML": 709, "JSON": 154, "Java": 501, "Motorola 68K Assembly": 12, "SQL": 6, "INI": 4, "Ignore List": 1} | package com.dominate.caravan.ui.home
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.viewpager.widget.ViewPager
import com.caravan.R
import com.caravan.databinding.FragmentHomeBinding
import com.dominate.caravan.core.base.BaseFragment
import com.dominate.caravan.core.showLoginDialog
import com.dominate.caravan.medule.home.Banner
import com.dominate.caravan.medule.home.CommercialAd
import com.dominate.caravan.medule.home.CommercialEstate
import com.dominate.caravan.medule.home.HousingAd
import com.dominate.caravan.medule.home.RealEstateAd
import com.dominate.caravan.ui.estatedetails.EstateDetailsFragment
import com.dominate.caravan.ui.home.adapter.CommercialAdsAdapter
import com.dominate.caravan.ui.home.adapter.CommercialEstatesAdapter
import com.dominate.caravan.ui.home.adapter.HousingAdsAdapter
import com.dominate.caravan.ui.home.adapter.RealEstateAdsAdapter
import com.dominate.caravan.utils.Resource
import dagger.hilt.android.AndroidEntryPoint
import java.util.Timer
import java.util.TimerTask
@AndroidEntryPoint
class HomeFragment : BaseFragment() {
lateinit var binding: FragmentHomeBinding
private val viewModel: HomeViewModel by viewModels()
lateinit var housingAdsAdapter: HousingAdsAdapter
lateinit var realEstateAdsAdapter: RealEstateAdsAdapter
lateinit var commercialEstatesAdapter: CommercialEstatesAdapter
lateinit var commercialAdsAdapter: CommercialAdsAdapter
lateinit var bannerAdapter: BannerAdapter
var maxCount = 2
var token: String? = ""
var currentPage = 0
var NUM_PAGES = 5
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setData()
setRecycleView()
}
private fun setData() {
try {
token = prefs.getCurrentUser().token.toString()
} catch (_: Exception) {
}
val slideUpAnimation: Animation = AnimationUtils.loadAnimation(
requireContext(),
R.anim.slide_up
)
binding.constraintLayout01.startAnimation(slideUpAnimation)
binding.viewPager.startAnimation(slideUpAnimation)
binding.tabLayout.startAnimation(slideUpAnimation)
binding.tvHousingAds.startAnimation(slideUpAnimation)
binding.tvMoreHousingAds.startAnimation(slideUpAnimation)
binding.rvHousingAds.startAnimation(slideUpAnimation)
binding.tvMoreRealEstateAds.startAnimation(slideUpAnimation)
binding.tvRealEstateAds.startAnimation(slideUpAnimation)
binding.rvRealEstateAds.startAnimation(slideUpAnimation)
binding.constraintLayout02.startAnimation(slideUpAnimation)
binding.tvMoreCommercialEstates.startAnimation(slideUpAnimation)
binding.tvCommercialEstates.startAnimation(slideUpAnimation)
binding.rvCommercialEstates.startAnimation(slideUpAnimation)
binding.tvMoreCommercialAds.startAnimation(slideUpAnimation)
binding.tvCommercialAds.startAnimation(slideUpAnimation)
binding.rvCommercialAds.startAnimation(slideUpAnimation)
binding.rvCommercialAds.startAnimation(slideUpAnimation)
Handler().postDelayed({
binding.loading.visibility = View.GONE
}, 2000)
// binding.viewPager.setPageTransformer(true, ZoomOutPageTransformer())
val handler = Handler()
val update = Runnable {
if (currentPage == NUM_PAGES) {
currentPage = 0
}
binding.viewPager.setCurrentItem(currentPage++, true)
}
Timer().schedule(object : TimerTask() {
override fun run() {
handler.post(update)
}
}, 400, 10000)
binding.btnSearchNow.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_searchFragment)
}
binding.tvMoreHousingAds.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_housingAdsFragment)
}
binding.tvMoreCommercialEstates.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_commercialEstateFragment)
}
binding.tvMoreRealEstateAds.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_realEstateAdsFragment2)
}
binding.tvMoreCommercialAds.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_commercialAdsFragment)
}
binding.btnPostAdNow.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_addAdsFragment)
}
observeHome()
}
fun observeHome() {
viewModel.getHome()
viewModel.getHomeResponse.observe(viewLifecycleOwner, Observer {
if (it.status == Resource.Status.SUCCESS) {
if (it.data?.status?.code == 200) {
it.data!!.let { it ->
bannerSetData(it.results.banners)
if (it.results.housing_ads.size > maxCount) {
binding.tvMoreHousingAds.visibility = View.VISIBLE
val housing_ads_list: MutableList<HousingAd> = mutableListOf()
for (i in 0..maxCount) {
housing_ads_list.add(it.results.housing_ads[i])
}
housingAdsData(housing_ads_list)
} else {
binding.tvMoreHousingAds.visibility = View.INVISIBLE
housingAdsData(it.results.housing_ads)
}
if (it.results.real_estate_ads.size > maxCount) {
binding.tvMoreRealEstateAds.visibility = View.VISIBLE
val real_estate_ads_list: MutableList<RealEstateAd> = mutableListOf()
for (i in 0..maxCount) {
real_estate_ads_list.add(it.results.real_estate_ads[i])
}
realEstateAdsData(real_estate_ads_list)
} else {
binding.tvMoreRealEstateAds.visibility = View.INVISIBLE
realEstateAdsData(it.results.real_estate_ads)
}
if (it.results.commercial_estates.size > maxCount) {
binding.tvMoreCommercialEstates.visibility = View.VISIBLE
val commercial_estates_list: MutableList<CommercialEstate> = mutableListOf()
for (i in 0..maxCount) {
commercial_estates_list.add(it.results.commercial_estates[i])
}
commercialEstatesData(commercial_estates_list)
} else {
binding.tvMoreCommercialEstates.visibility = View.INVISIBLE
commercialEstatesData(it.results.commercial_estates)
}
if (it.results.commercial_ads.size > maxCount) {
binding.tvMoreCommercialAds.visibility = View.VISIBLE
val CommercialEstate_list: MutableList<CommercialAd> = mutableListOf()
for (i in 0..maxCount) {
CommercialEstate_list.add(it.results.commercial_ads[i])
}
commercialAdsData(CommercialEstate_list)
} else {
binding.tvMoreCommercialAds.visibility = View.INVISIBLE
commercialAdsData(it.results.commercial_ads)
}
}
} else {
Toast.makeText(
context,
it.data?.status?.message.toString(),
Toast.LENGTH_SHORT
).show()
}
}
if (it.status == Resource.Status.ERROR) {
Toast.makeText(
context,
it.message.toString(),
Toast.LENGTH_SHORT
).show()
}
})
}
private fun housingAdsData(housingAds: MutableList<HousingAd>) {
if (housingAds.isNotEmpty()) {
housingAdsAdapter = HousingAdsAdapter(housingAds, {
if (prefs.isLoggedIn && !token.isNullOrEmpty()) {
it!!.is_favorite = !it.is_favorite
AddRemoveFavorite(id = it.id, it.is_favorite)
} else {
// IF USER NOT LOGIN SHOW DIALOG
requireContext().showLoginDialog(
onPositiveButtonClick = {
findNavController().navigate(R.id.action_homeFragment_to_sigininFragment)
it.dismiss()
}, onNegativeButtonClick = {
it.dismiss()
})
}
}, {
EstateDetailsFragment.housing = it!!
EstateDetailsFragment.type = "housing"
findNavController().navigate(R.id.action_homeFragment_to_estateDetailsFragment)
})
housingAdsAdapter.notifyDataSetChanged()
binding.rvHousingAds.adapter = housingAdsAdapter
} else {
binding.tvHousingAds.visibility = View.GONE
binding.tvMoreHousingAds.visibility = View.GONE
}
}
private fun realEstateAdsData(realEstateAds: MutableList<RealEstateAd>) {
if (realEstateAds.isNotEmpty()) {
realEstateAdsAdapter = RealEstateAdsAdapter(realEstateAds, {
if (prefs.isLoggedIn && !token.isNullOrEmpty()) {
it!!.is_favorite = !it.is_favorite
AddRemoveFavorite(id = it.id, it.is_favorite)
} else {
// IF USER NOT LOGIN SHOW DIALOG
requireContext().showLoginDialog(
onPositiveButtonClick = {
findNavController().navigate(R.id.action_homeFragment_to_sigininFragment)
it.dismiss()
}, onNegativeButtonClick = {
it.dismiss()
})
}
}, {
EstateDetailsFragment.realEstate = it!!
EstateDetailsFragment.type = "real_estate"
findNavController().navigate(R.id.action_homeFragment_to_estateDetailsFragment)
})
realEstateAdsAdapter.notifyDataSetChanged()
binding.rvRealEstateAds.adapter = realEstateAdsAdapter
} else {
binding.tvRealEstateAds.visibility = View.GONE
binding.tvMoreRealEstateAds.visibility = View.GONE
}
}
private fun commercialEstatesData(commercialEstates: MutableList<CommercialEstate>) {
if (commercialEstates.isNotEmpty()) {
commercialEstatesAdapter = CommercialEstatesAdapter(commercialEstates, {
if (prefs.isLoggedIn && !token.isNullOrEmpty()) {
it!!.is_favorite = !it.is_favorite
AddRemoveFavorite(id = it.id, it.is_favorite)
} else {
// IF USER NOT LOGIN SHOW DIALOG
requireContext().showLoginDialog(
onPositiveButtonClick = {
findNavController().navigate(R.id.action_homeFragment_to_sigininFragment)
it.dismiss()
}, onNegativeButtonClick = {
it.dismiss()
})
}
}, {
EstateDetailsFragment.commertcial_estate = it!!
EstateDetailsFragment.type = "commertcial_estate"
findNavController().navigate(R.id.action_homeFragment_to_estateDetailsFragment)
})
commercialEstatesAdapter.notifyDataSetChanged()
binding.rvCommercialEstates.adapter = commercialEstatesAdapter
} else {
binding.tvCommercialEstates.visibility = View.GONE
binding.tvMoreCommercialEstates.visibility = View.GONE
}
}
private fun commercialAdsData(commercialAds: MutableList<CommercialAd>) {
if (commercialAds.isNotEmpty()) {
commercialAdsAdapter = CommercialAdsAdapter(commercialAds, {
if (prefs.isLoggedIn && !token.isNullOrEmpty()) {
it!!.is_favorite = !it.is_favorite!!
it.id?.let { it1 -> AddRemoveFavorite(id = it1, it.is_favorite!!) }
} else {
// IF USER NOT LOGIN SHOW DIALOG
requireContext().showLoginDialog(
onPositiveButtonClick = {
findNavController().navigate(R.id.action_homeFragment_to_sigininFragment)
it.dismiss()
}, onNegativeButtonClick = {
it.dismiss()
})
}
}, {
EstateDetailsFragment.commertcial = it!!
EstateDetailsFragment.type = "commertcial"
findNavController().navigate(R.id.action_homeFragment_to_estateDetailsFragment)
})
commercialAdsAdapter.notifyDataSetChanged()
binding.rvCommercialAds.adapter = commercialAdsAdapter
} else {
binding.tvMoreCommercialAds.visibility = View.GONE
binding.tvCommercialAds.visibility = View.GONE
}
}
private fun AddRemoveFavorite(id: Int, isFavorite: Boolean) {
if (isFavorite) {
id.let { id ->
viewModel.addFavoriteItem(
token!!, id
)
}
viewModel.addFavoriteResponse.observe(
viewLifecycleOwner
) {
if (it.status == Resource.Status.SUCCESS) {
} else if (it.status == Resource.Status.ERROR) {
Toast.makeText(
requireContext(),
it.message,
Toast.LENGTH_SHORT
)
.show()
}
}
} else {
id.let { id ->
viewModel.removeFavoriteItem(
token!!, id
)
}
viewModel.removeFavoriteResponse.observe(
viewLifecycleOwner
) {
if (it.status == Resource.Status.SUCCESS) {
} else if (it.status == Resource.Status.ERROR) {
Toast.makeText(
requireContext(),
it.message,
Toast.LENGTH_SHORT
)
.show()
}
}
}
}
private fun bannerSetData(banners: MutableList<Banner>) {
if (banners.isNotEmpty()) {
bannerAdapter = BannerAdapter(requireContext(), banners) {
openUrl(context = requireContext(), it!!.link)
}
bannerAdapter.notifyDataSetChanged()
binding.viewPager.adapter = bannerAdapter
binding.tabLayout.setupWithViewPager(binding.viewPager, true)
} else {
binding.viewPager.visibility = View.GONE
binding.tabLayout.visibility = View.GONE
}
}
fun openUrl(context: Context, url: String) = try {
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
true
} catch (exception: ActivityNotFoundException) {
Log.d("exception", exception.toString())
false
}
private fun setRecycleView() {
}
}
private const val MIN_SCALE = 0.85f
private const val MIN_ALPHA = 0.5f
class ZoomOutPageTransformer : ViewPager.PageTransformer {
override fun transformPage(view: View, position: Float) {
view.apply {
val pageWidth = width
val pageHeight = height
when {
position < -1 -> { // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0f
}
position <= 1 -> { // [-1,1]
// Modify the default slide transition to shrink the page as well
val scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position))
val vertMargin = pageHeight * (1 - scaleFactor) / 2
val horzMargin = pageWidth * (1 - scaleFactor) / 2
translationX = if (position < 0) {
horzMargin - vertMargin / 2
} else {
horzMargin + vertMargin / 2
}
// Scale the page down (between MIN_SCALE and 1)
scaleX = scaleFactor
scaleY = scaleFactor
// Fade the page relative to its size.
alpha = (MIN_ALPHA +
(((scaleFactor - MIN_SCALE) / (1 - MIN_SCALE)) * (1 - MIN_ALPHA)))
}
else -> { // (1,+Infinity]
// This page is way off-screen to the right.
alpha = 0f
}
}
}
}
} | 0 | Java | 0 | 0 | 909f22dbfea3d01cbd10529248763f0fceddf7f0 | 18,476 | caravan | MIT License |
app/src/main/java/com/example/androiddevchallenge/model/Repository.kt | tritter | 342,313,177 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.model
object Repository {
fun all(): List<Dog> = dogs
fun get(name: String) = all().find { it.name == name }
}
| 0 | Kotlin | 0 | 0 | 7f0fdad0f3c3c8c8150207caf4995510cf44cca4 | 776 | android-dev-challenge-puppy | Apache License 2.0 |
bluetooth_low_energy_android/android/src/main/kotlin/dev/hebei/bluetooth_low_energy_android/MyPeripheralManager.kt | yanshouwang | 375,652,911 | false | null | package dev.hebei.bluetooth_low_energy_android
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothGattServer
import android.bluetooth.BluetoothGattServerCallback
import android.bluetooth.BluetoothGattService
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothStatusCodes
import android.bluetooth.le.AdvertiseCallback
import android.bluetooth.le.AdvertiseSettings
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import androidx.core.content.ContextCompat
import io.flutter.plugin.common.BinaryMessenger
import java.util.concurrent.Executor
class MyPeripheralManager(context: Context, binaryMessenger: BinaryMessenger) : MyBluetoothLowEnergyManager(context), MyPeripheralManagerHostAPI {
private val mAPI: MyPeripheralManagerFlutterAPI
private val mBluetoothGattServerCallback: BluetoothGattServerCallback by lazy { MyBluetoothGattServerCallback(this, executor) }
private val mAdvertiseCallback: AdvertiseCallback by lazy { MyAdvertiseCallback(this) }
private var mServer: BluetoothGattServer?
private var mAdvertising: Boolean
private val mServicesArgs: MutableMap<Int, MyMutableGATTServiceArgs>
private val mCharacteristicsArgs: MutableMap<Int, MyMutableGATTCharacteristicArgs>
private val mDescriptorsArgs: MutableMap<Int, MyMutableGATTDescriptorArgs>
private val mDevices: MutableMap<String, BluetoothDevice>
private val mServices: MutableMap<Long, BluetoothGattService>
private val mCharacteristics: MutableMap<Long, BluetoothGattCharacteristic>
private val mDescriptors: MutableMap<Long, BluetoothGattDescriptor>
private var mAuthorizeCallback: ((Result<Boolean>) -> Unit)?
private var mSetNameCallback: ((Result<String?>) -> Unit)?
private var mAddServiceCallback: ((Result<Unit>) -> Unit)?
private var mStartAdvertisingCallback: ((Result<Unit>) -> Unit)?
private val mNotifyCharacteristicValueChangedCallbacks: MutableMap<String, (Result<Unit>) -> Unit>
init {
mAPI = MyPeripheralManagerFlutterAPI(binaryMessenger)
mServer = null
mAdvertising = false
mServicesArgs = mutableMapOf()
mCharacteristicsArgs = mutableMapOf()
mDescriptorsArgs = mutableMapOf()
mDevices = mutableMapOf()
mServices = mutableMapOf()
mCharacteristics = mutableMapOf()
mDescriptors = mutableMapOf()
mAuthorizeCallback = null
mSetNameCallback = null
mAddServiceCallback = null
mStartAdvertisingCallback = null
mNotifyCharacteristicValueChangedCallbacks = mutableMapOf()
}
private val permissions: Array<String>
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
arrayOf(android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.BLUETOOTH_ADVERTISE, android.Manifest.permission.BLUETOOTH_CONNECT)
} else {
arrayOf(android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION)
}
private val manager get() = ContextCompat.getSystemService(context, BluetoothManager::class.java) as BluetoothManager
private val adapter get() = manager.adapter as BluetoothAdapter
private val advertiser get() = adapter.bluetoothLeAdvertiser
private val server get() = mServer ?: throw IllegalStateException()
private val executor get() = ContextCompat.getMainExecutor(context) as Executor
override fun initialize(): MyPeripheralManagerArgs {
if (mAdvertising) {
stopAdvertising()
}
mServer?.close()
mServicesArgs.clear()
mCharacteristicsArgs.clear()
mDescriptorsArgs.clear()
mDevices.clear()
mServices.clear()
mCharacteristics.clear()
mDescriptors.clear()
mAuthorizeCallback = null
mSetNameCallback = null
mAddServiceCallback = null
mStartAdvertisingCallback = null
mNotifyCharacteristicValueChangedCallbacks.clear()
val enableNotificationValue = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
val enableIndicationValue = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
val disableNotificationValue = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE
return MyPeripheralManagerArgs(enableNotificationValue, enableIndicationValue, disableNotificationValue)
}
override fun getState(): MyBluetoothLowEnergyStateArgs {
// Use isMultipleAdvertisementSupported() to check whether LE Advertising is supported on this device before calling this method.
// See https://developer.android.com/reference/kotlin/android/bluetooth/BluetoothAdapter#getbluetoothleadvertiser
val supported = context.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE) && adapter.isMultipleAdvertisementSupported
return if (supported) {
val authorized = permissions.all { permission -> ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED }
return if (authorized) adapter.state.toBluetoothLowEnergyStateArgs()
else MyBluetoothLowEnergyStateArgs.UNAUTHORIZED
} else MyBluetoothLowEnergyStateArgs.UNSUPPORTED
}
override fun authorize(callback: (Result<Boolean>) -> Unit) {
try {
ActivityCompat.requestPermissions(activity, permissions, AUTHORIZE_CODE)
mAuthorizeCallback = callback
} catch (e: Throwable) {
callback(Result.failure(e))
}
}
override fun showAppSettings() {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
intent.data = Uri.fromParts("package", activity.packageName, null)
val options = ActivityOptionsCompat.makeBasic().toBundle()
ActivityCompat.startActivity(activity, intent, options)
}
override fun setName(nameArgs: String, callback: (Result<String?>) -> Unit) {
try {
val setting = adapter.setName(nameArgs)
if (!setting) {
throw IllegalStateException()
}
mSetNameCallback = callback
} catch (e: Throwable) {
callback(Result.failure(e))
}
}
override fun openGATTServer() {
mServer = manager.openGattServer(context, mBluetoothGattServerCallback)
}
override fun closeGATTServer() {
server.close()
}
override fun addService(serviceArgs: MyMutableGATTServiceArgs, callback: (Result<Unit>) -> Unit) {
try {
val service = addServiceArgs(serviceArgs)
val adding = server.addService(service)
if (!adding) {
throw IllegalStateException()
}
mAddServiceCallback = callback
} catch (e: Throwable) {
callback(Result.failure(e))
}
}
override fun removeService(hashCodeArgs: Long) {
val service = mServices[hashCodeArgs] ?: throw IllegalArgumentException()
val removed = server.removeService(service)
if (!removed) {
throw IllegalStateException()
}
val hashCode = service.hashCode()
val serviceArgs = mServicesArgs[hashCode] ?: throw IllegalArgumentException()
removeServiceArgs(serviceArgs)
}
override fun removeAllServices() {
server.clearServices()
mServices.clear()
mCharacteristics.clear()
mDescriptors.clear()
mServicesArgs.clear()
mCharacteristicsArgs.clear()
mDescriptorsArgs.clear()
}
override fun startAdvertising(settingsArgs: MyAdvertiseSettingsArgs, advertiseDataArgs: MyAdvertiseDataArgs, scanResponseArgs: MyAdvertiseDataArgs, callback: (Result<Unit>) -> Unit) {
try {
val settings = settingsArgs.toAdvertiseSettings()
val advertiseData = advertiseDataArgs.toAdvertiseData()
val scanResponse = scanResponseArgs.toAdvertiseData()
advertiser.startAdvertising(settings, advertiseData, scanResponse, mAdvertiseCallback)
mStartAdvertisingCallback = callback
} catch (e: Throwable) {
callback(Result.failure(e))
}
}
override fun stopAdvertising() {
advertiser.stopAdvertising(mAdvertiseCallback)
mAdvertising = false
}
override fun sendResponse(addressArgs: String, idArgs: Long, statusArgs: MyGATTStatusArgs, offsetArgs: Long, valueArgs: ByteArray?) {
val device = mDevices[addressArgs] ?: throw IllegalArgumentException()
val requestId = idArgs.toInt()
val status = statusArgs.toStatus()
val offset = offsetArgs.toInt()
val sent = server.sendResponse(device, requestId, status, offset, valueArgs)
if (!sent) {
throw IllegalStateException("Send response failed.")
}
}
override fun notifyCharacteristicChanged(addressArgs: String, hashCodeArgs: Long, confirmArgs: Boolean, valueArgs: ByteArray, callback: (Result<Unit>) -> Unit) {
try {
val device = mDevices[addressArgs] ?: throw IllegalArgumentException()
val characteristic = mCharacteristics[hashCodeArgs] ?: throw IllegalArgumentException()
val notifying = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
val statusCode = server.notifyCharacteristicChanged(device, characteristic, confirmArgs, valueArgs)
statusCode == BluetoothStatusCodes.SUCCESS
} else { // TODO: remove this when minSdkVersion >= 33
characteristic.value = valueArgs
server.notifyCharacteristicChanged(device, characteristic, confirmArgs)
}
if (!notifying) {
throw IllegalStateException()
}
mNotifyCharacteristicValueChangedCallbacks[addressArgs] = callback
} catch (e: Throwable) {
callback(Result.failure(e))
}
}
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
BluetoothAdapter.ACTION_STATE_CHANGED -> {
val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF)
val stateArgs = state.toBluetoothLowEnergyStateArgs()
mAPI.onStateChanged(stateArgs) {}
}
BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED -> {
val callback = mSetNameCallback ?: return
mSetNameCallback = null
val nameArgs = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME)
callback(Result.success(nameArgs))
}
else -> {}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, results: IntArray): Boolean {
if (requestCode != AUTHORIZE_CODE) {
return false
}
val callback = mAuthorizeCallback ?: return false
mAuthorizeCallback = null
val authorized = permissions.contentEquals(this.permissions) && results.all { r -> r == PackageManager.PERMISSION_GRANTED }
callback(Result.success(authorized))
return true
}
fun onServiceAdded(status: Int, service: BluetoothGattService) {
val callback = mAddServiceCallback ?: return
mAddServiceCallback = null
if (status == BluetoothGatt.GATT_SUCCESS) {
callback(Result.success(Unit))
} else {
val error = IllegalStateException("Read rssi failed with status: $status")
callback(Result.failure(error))
}
}
fun onStartSuccess(settingsInEffect: AdvertiseSettings) {
mAdvertising = true
val callback = mStartAdvertisingCallback ?: return
mStartAdvertisingCallback = null
callback(Result.success(Unit))
}
fun onStartFailure(errorCode: Int) {
val callback = mStartAdvertisingCallback ?: return
mStartAdvertisingCallback = null
val error = IllegalStateException("Start advertising failed with error code: $errorCode")
callback(Result.failure(error))
}
fun onConnectionStateChange(device: BluetoothDevice, status: Int, newState: Int) {
val centralArgs = device.toCentralArgs()
val addressArgs = centralArgs.addressArgs
val statusArgs = status.args
val stateArgs = newState.toConnectionStateArgs()
mDevices[addressArgs] = device
mAPI.onConnectionStateChanged(centralArgs, statusArgs, stateArgs) {}
}
fun onMtuChanged(device: BluetoothDevice, mtu: Int) {
val centralArgs = device.toCentralArgs()
val mtuArgs = mtu.args
mAPI.onMTUChanged(centralArgs, mtuArgs) {}
}
fun onCharacteristicReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, characteristic: BluetoothGattCharacteristic) {
val centralArgs = device.toCentralArgs()
val idArgs = requestId.args
val offsetArgs = offset.args
val hashCode = characteristic.hashCode()
val characteristicArgs = mCharacteristicsArgs[hashCode]
if (characteristicArgs == null) {
val status = BluetoothGatt.GATT_FAILURE
server.sendResponse(device, requestId, status, offset, null)
} else {
val hashCodeArgs = characteristicArgs.hashCodeArgs
mAPI.onCharacteristicReadRequest(centralArgs, idArgs, offsetArgs, hashCodeArgs) {}
}
}
fun onCharacteristicWriteRequest(device: BluetoothDevice, requestId: Int, characteristic: BluetoothGattCharacteristic, preparedWrite: Boolean, responseNeeded: Boolean, offset: Int, value: ByteArray) {
val centralArgs = device.toCentralArgs()
val idArgs = requestId.args
val hashCode = characteristic.hashCode()
val characteristicArgs = mCharacteristicsArgs[hashCode]
if (characteristicArgs == null) {
if (!responseNeeded) {
return
}
val status = BluetoothGatt.GATT_FAILURE
server.sendResponse(device, requestId, status, offset, null)
} else {
val hashCodeArgs = characteristicArgs.hashCodeArgs
val offsetArgs = offset.args
mAPI.onCharacteristicWriteRequest(centralArgs, idArgs, hashCodeArgs, preparedWrite, responseNeeded, offsetArgs, value) {}
}
}
fun onNotificationSent(device: BluetoothDevice, status: Int) {
val addressArgs = device.address
val callback = mNotifyCharacteristicValueChangedCallbacks.remove(addressArgs) ?: return
if (status == BluetoothGatt.GATT_SUCCESS) {
callback(Result.success(Unit))
} else {
val error = IllegalStateException("Notify characteristic value changed failed with status: $status")
callback(Result.failure(error))
}
}
fun onDescriptorReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, descriptor: BluetoothGattDescriptor) {
val centralArgs = device.toCentralArgs()
val idArgs = requestId.args
val offsetArgs = offset.args
val hashCode = descriptor.hashCode()
val descriptorArgs = mDescriptorsArgs[hashCode]
if (descriptorArgs == null) {
val status = BluetoothGatt.GATT_FAILURE
server.sendResponse(device, requestId, status, offset, null)
} else {
val hashCodeArgs = descriptorArgs.hashCodeArgs
mAPI.onDescriptorReadRequest(centralArgs, idArgs, offsetArgs, hashCodeArgs) {}
}
}
fun onDescriptorWriteRequest(device: BluetoothDevice, requestId: Int, descriptor: BluetoothGattDescriptor, preparedWrite: Boolean, responseNeeded: Boolean, offset: Int, value: ByteArray) {
val centralArgs = device.toCentralArgs()
val idArgs = requestId.args
val hashCode = descriptor.hashCode()
val descriptorArgs = mDescriptorsArgs[hashCode]
if (descriptorArgs == null) {
if (!responseNeeded) {
return
}
val status = BluetoothGatt.GATT_FAILURE
server.sendResponse(device, requestId, status, offset, null)
} else {
val hashCodeArgs = descriptorArgs.hashCodeArgs
val offsetArgs = offset.args
mAPI.onDescriptorWriteRequest(centralArgs, idArgs, hashCodeArgs, preparedWrite, responseNeeded, offsetArgs, value) {}
}
}
fun onExecuteWrite(device: BluetoothDevice, requestId: Int, execute: Boolean) {
val centralArgs = device.toCentralArgs()
val idArgs = requestId.args
mAPI.onExecuteWrite(centralArgs, idArgs, execute) {}
}
private fun addServiceArgs(serviceArgs: MyMutableGATTServiceArgs): BluetoothGattService {
val service = serviceArgs.toService()
this.mServicesArgs[service.hashCode] = serviceArgs
this.mServices[serviceArgs.hashCodeArgs] = service
val includedServicesArgs = serviceArgs.includedServicesArgs.requireNoNulls()
for (includedServiceArgs in includedServicesArgs) {
val includedService = addServiceArgs(includedServiceArgs)
val adding = service.addService(includedService)
if (!adding) {
throw IllegalStateException()
}
}
val characteristicsArgs = serviceArgs.characteristicsArgs.requireNoNulls()
for (characteristicArgs in characteristicsArgs) {
val characteristic = characteristicArgs.toCharacteristic()
this.mCharacteristicsArgs[characteristic.hashCode] = characteristicArgs
this.mCharacteristics[characteristicArgs.hashCodeArgs] = characteristic
val descriptorsArgs = characteristicArgs.descriptorsArgs.requireNoNulls()
for (descriptorArgs in descriptorsArgs) {
val descriptor = descriptorArgs.toDescriptor()
this.mDescriptorsArgs[descriptor.hashCode] = descriptorArgs
this.mDescriptors[descriptorArgs.hashCodeArgs] = descriptor
val descriptorAdded = characteristic.addDescriptor(descriptor)
if (!descriptorAdded) {
throw IllegalStateException()
}
}
val characteristicAdded = service.addCharacteristic(characteristic)
if (!characteristicAdded) {
throw IllegalStateException()
}
}
return service
}
private fun removeServiceArgs(serviceArgs: MyMutableGATTServiceArgs) {
val includedServicesArgs = serviceArgs.includedServicesArgs.requireNoNulls()
for (includedServiceArgs in includedServicesArgs) {
removeServiceArgs(includedServiceArgs)
}
val characteristicsArgs = serviceArgs.characteristicsArgs.requireNoNulls()
for (characteristicArgs in characteristicsArgs) {
val descriptorsArgs = characteristicArgs.descriptorsArgs.requireNoNulls()
for (descriptorArgs in descriptorsArgs) {
val descriptor = mDescriptors.remove(descriptorArgs.hashCodeArgs) ?: throw IllegalArgumentException()
this.mDescriptorsArgs.remove(descriptor.hashCode)
}
val characteristic = mCharacteristics.remove(characteristicArgs.hashCodeArgs) ?: throw IllegalArgumentException()
this.mCharacteristicsArgs.remove(characteristic.hashCode)
}
val service = mServices.remove(serviceArgs.hashCodeArgs) ?: throw IllegalArgumentException()
mServicesArgs.remove(service.hashCode)
}
} | 5 | null | 15 | 47 | e24d1bc302a15dbb1232ad0f3db30406f5776060 | 20,061 | bluetooth_low_energy | MIT License |
livenesscamerax/core/src/main/java/com/schaefer/core/resourceprovider/ResourcesProvider.kt | arturschaefer | 412,866,499 | false | null | package com.schaefer.core.resourceprovider
interface ResourcesProvider {
fun getString(resourceIdentifier: Int, vararg arguments: Any = arrayOf()): String
fun getStringArray(resourceIdentifier: Int): Array<String>
fun getInteger(resourceIdentifier: Int): Int
fun getIntegerArray(resourceIdentifier: Int): IntArray
fun getBoolean(resourceIdentifier: Int): Boolean
fun getColor(resourceIdentifier: Int): Int
}
| 0 | Kotlin | 5 | 7 | ed9bbdaf766209f640a0b9fc28a123b2d65fb4b6 | 438 | liveness-camerax-android | Apache License 2.0 |
data/src/main/java/lucassales/com/data/entities/relation/PileWithCards.kt | lucassales2 | 181,433,644 | false | null | package lucassales.com.data.entities.relation
import androidx.room.Embedded
import androidx.room.Relation
import lucassales.com.data.entities.SolitaireCard
import lucassales.com.data.entities.pile.Pile
data class PileWithCards(
@Embedded val pile: Pile,
@Relation(
entity = SolitaireCard::class,
parentColumn = "id",
entityColumn = "pile_id"
)
val cards: List<SolitaireCard>
) | 0 | Kotlin | 0 | 0 | fc6db5e6de890e075fcb8a215721b8ca7bc2f8ad | 418 | CardGame | MIT License |
src/main/kotlin/io/ipfs/kotlin/MultiHashProvider.kt | GustaveNimant | 240,869,379 | false | null | package io.ipfs.kotlin
import io.ipfs.kotlin.defaults.*
/**
* Provide : the MultiHashValue for a MultiHashType
* Needs : Hash Function name stored in ParameterMap
* Needs : Hash Hashable information (directory, file, string) stored in ParameterMap
* Done : LocalIpfs().add.string(str).MultiHash
* Author : <NAME> 22 fรฉvrier 2020 at 10:32:18+01:00;
* Improve : Implement Hash Stuff
* Revision : Register as singleton by <NAME> 11 mars 2020 at 17:48:32+01:00
*/
class MultiHashProvider {
val register = MultiHashRegister
private fun build (funNam: String, hasInf: String): MultiHashValue {
val (here, caller) = moduleHereAndCaller()
entering(here, caller)
println("$here: input funNam '$funNam'")
println("$here: input hasInf '$hasInf'")
val hash = hashStringOfTypeOfInput(funNam, hasInf)
val result = MultiHashValue(funNam, hash)
println("$here: output result $result")
exiting(here)
return result
}
private fun buildAndStore(mulTyp: MultiHashType) : MultiHashValue {
val (here, caller) = moduleHereAndCaller()
entering(here, caller)
println("$here: input mulTyp '$mulTyp'")
// Improve get from ParameterMap Input
val hasFunTyp = hashFunctionType()
val hasInpStr = hashInputString()
val result = build(hasFunTyp, hasInpStr)
register.store(mulTyp, result)
println("$here: output result $result")
exiting(here)
return result
}
public fun provideOfMultiHashType(mulTyp: MultiHashType) : MultiHashValue {
val (here, caller) = moduleHereAndCaller()
entering(here, caller)
println("$here: input mulTyp '$mulTyp'")
val result =
if (register.isStored(mulTyp)){
register.retrieve(mulTyp)
}
else {
buildAndStore(mulTyp)
}
println()
println(mulTyp.toString()+" => '$result'")
println()
exiting(here)
return result
}
fun print (mulTyp: MultiHashType) {
val (here, caller) = moduleHereAndCaller()
entering(here, caller)
val result = provideOfMultiHashType(mulTyp)
println ("MultiHashValue: $result")
exiting(here)
}
}
| 0 | Kotlin | 0 | 0 | beb37a6dd94e342d589047b89144467ff1e59a62 | 2,072 | irp-kotlin-minichain | MIT License |
app/src/main/java/com/debugger/spotifylite/ui/setting/storage/StorageFragment.kt | danhtran-dev | 382,124,861 | false | null | package com.debugger.spotifylite.ui.setting.storage
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.debugger.spotifylite.databinding.LayoutToolbarBinding
import com.debugger.spotifylite.databinding.StorageFragmentBinding
import com.debugger.spotifylite.di.component.FragmentComponent
import com.debugger.base.ui.BaseFragment
class StorageFragment : BaseFragment<StorageFragmentBinding, StorageViewModel>(), View.OnClickListener {
private lateinit var settingToolbar: LayoutToolbarBinding
override fun provideViewBinding(inflater: LayoutInflater, container: ViewGroup?) =
StorageFragmentBinding.inflate(inflater, container, false)
override fun injectDependencies(fragmentComponent: FragmentComponent) {
fragmentComponent.inject(this)
}
override fun setupView(savedInstanceState: Bundle?) {
settingToolbar = requireViewBinding().settingToolbar
settingToolbar.settingBackNav.setOnClickListener(this)
}
override fun onClick(v: View?) {
when (v!!) {
settingToolbar.settingBackNav -> {
findNavController().navigateUp()
}
}
}
} | 0 | Kotlin | 0 | 1 | 02037f6852877849cc96d42db71d7a62d7b720b7 | 1,278 | Spotify-Lite-UI | MIT License |
plot-base-portable/src/commonMain/kotlin/jetbrains/datalore/plot/base/scale/Mappers.kt | paddlelaw | 397,769,862 | true | {"Kotlin": 5197304, "Python": 774830, "C": 2832, "CSS": 1948, "Shell": 1773, "JavaScript": 1121} | /*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plot.base.scale
import jetbrains.datalore.base.function.Function
import jetbrains.datalore.base.gcommon.base.Preconditions.checkState
import jetbrains.datalore.base.gcommon.collect.ClosedRange
import jetbrains.datalore.plot.base.scale.breaks.QuantizeScale
import jetbrains.datalore.plot.common.data.SeriesUtil
import kotlin.math.round
object Mappers {
val IDENTITY = { v: Double? -> v }
fun <T> undefined(): (Double?) -> T = { throw IllegalStateException("Undefined mapper") }
fun <T> nullable(f: (Double?) -> T, ifNull: T): (Double?) -> T {
return { n ->
if (n == null) {
ifNull
} else {
f(n)
}
}
}
fun constant(v: Double): (Double?) -> Double = { v }
fun mul(domain: ClosedRange<Double>, rangeSpan: Double): (Double?) -> Double? {
val factor = rangeSpan / (domain.upperEnd - domain.lowerEnd)
checkState(!(factor.isInfinite() || factor.isNaN()), "Can't create mapper with ratio: $factor")
return mul(factor)
}
fun mul(factor: Double): (Double?) -> Double? {
return { v ->
if (v != null) {
factor * v
} else null
}
}
fun linear(domain: ClosedRange<Double>, range: ClosedRange<Double>): (Double?) -> Double {
return linear(
domain,
range.lowerEnd,
range.upperEnd,
Double.NaN
)
}
fun linear(domain: ClosedRange<Double>, range: ClosedRange<Double>, defaultValue: Double): (Double?) -> Double {
return linear(
domain,
range.lowerEnd,
range.upperEnd,
defaultValue
)
}
fun linear(
domain: ClosedRange<Double>,
rangeLow: Double,
rangeHigh: Double,
defaultValue: Double
): (Double?) -> Double {
val slop = (rangeHigh - rangeLow) / (domain.upperEnd - domain.lowerEnd)
if (!SeriesUtil.isFinite(slop)) {
// no slop
val v = (rangeHigh - rangeLow) / 2 + rangeLow
return constant(v)
}
val intersect = rangeLow - domain.lowerEnd * slop
return { input ->
if (SeriesUtil.isFinite(input))
input!! * slop + intersect
else
defaultValue
}
}
fun discreteToContinuous(
domainValues: Collection<*>,
outputRange: ClosedRange<Double>,
naValue: Double
): (Double?) -> Double? {
val numberByDomainValue =
MapperUtil.mapDiscreteDomainValuesToNumbers(domainValues)
val dataRange = SeriesUtil.range(numberByDomainValue.values) ?: return IDENTITY
return linear(dataRange, outputRange, naValue)
}
fun <T> discrete(outputValues: List<T?>, defaultOutputValue: T): (Double?) -> T? {
val f = DiscreteFun(outputValues, defaultOutputValue)
return { f.apply(it) }
}
fun <T> quantized(
domain: ClosedRange<Double>?,
outputValues: Collection<T>,
defaultOutputValue: T
): (Double?) -> T {
if (domain == null) {
return { defaultOutputValue }
}
// todo: extract quantizer
val quantizer = QuantizeScale<T>()
quantizer.domain(domain.lowerEnd, domain.upperEnd)
quantizer.range(outputValues)
val f = QuantizedFun(quantizer, defaultOutputValue)
return { f.apply(it) }
}
private class DiscreteFun<T>(
private val myOutputValues: List<T?>,
private val myDefaultOutputValue: T
) : Function<Double?, T?> {
override fun apply(value: Double?): T? {
if (!SeriesUtil.isFinite(value)) {
return myDefaultOutputValue
}
// ToDo: index-based discrete fun won't work for discrete numeric onput (see: MapperUtil#mapDiscreteDomainValuesToNumbers())
var index = round(value!!).toInt()
index %= myOutputValues.size
if (index < 0) {
index += myOutputValues.size
}
return myOutputValues[index]
}
}
private class QuantizedFun<T> internal constructor(
private val myQuantizer: QuantizeScale<T>,
private val myDefaultOutputValue: T
) : Function<Double?, T> {
override fun apply(value: Double?): T {
return if (!SeriesUtil.isFinite(value)) myDefaultOutputValue else myQuantizer.quantize(value!!)
}
}
}
| 1 | null | 0 | 0 | d75d67cd94448b548c59520392385ec41de84bfe | 4,682 | lets-plot | MIT License |
app/src/test/kotlin/aoc2021/day06/Day06Test.kt | dbubenheim | 435,284,482 | false | null | package aoc2021.day06
import aoc2021.day06.Day06.Companion.lanternfishPart1
import aoc2021.day06.Day06.Companion.lanternfishPart2
import assertk.assertThat
import assertk.assertions.isEqualTo
import org.junit.jupiter.api.Test
class Day06Test {
@Test
fun testLanternfishPart1() =
assertThat(lanternfishPart1()).isEqualTo(353079)
@Test
fun testLanternfishPart2() =
assertThat(lanternfishPart2()).isEqualTo(1605400130036)
} | 6 | Kotlin | 0 | 0 | aa6d15c339965d226670cc6b882f34153c7d52ee | 456 | advent-of-code-2021 | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/EraserSmall.kt | Konyaco | 574,321,009 | false | null |
package com.konyaco.fluent.icons.regular
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Regular.EraserSmall: ImageVector
get() {
if (_eraserSmall != null) {
return _eraserSmall!!
}
_eraserSmall = fluentIcon(name = "Regular.EraserSmall") {
fluentPath {
moveTo(15.84f, 2.66f)
curveToRelative(-0.87f, -0.89f, -2.3f, -0.9f, -3.19f, -0.02f)
lineToRelative(-9.6f, 9.5f)
curveToRelative(-0.89f, 0.89f, -0.89f, 2.33f, 0.0f, 3.21f)
lineToRelative(5.1f, 5.0f)
curveToRelative(0.9f, 0.88f, 2.31f, 0.87f, 3.18f, -0.01f)
lineToRelative(1.79f, -1.8f)
arcToRelative(4.51f, 4.51f, 0.0f, false, true, 0.02f, -2.16f)
lineToRelative(-0.35f, 0.35f)
lineToRelative(-6.09f, -6.09f)
lineToRelative(7.0f, -6.94f)
curveToRelative(0.3f, -0.29f, 0.78f, -0.29f, 1.07f, 0.01f)
lineToRelative(4.91f, 5.01f)
curveToRelative(0.29f, 0.3f, 0.29f, 0.76f, 0.0f, 1.05f)
lineToRelative(-3.35f, 3.38f)
arcToRelative(4.5f, 4.5f, 0.0f, false, true, 2.16f, -0.04f)
lineToRelative(2.25f, -2.28f)
curveToRelative(0.87f, -0.88f, 0.87f, -2.28f, 0.01f, -3.16f)
lineToRelative(-4.9f, -5.0f)
close()
moveTo(5.64f, 11.7f)
lineToRelative(6.1f, 6.1f)
lineToRelative(-1.47f, 1.48f)
curveToRelative(-0.3f, 0.3f, -0.77f, 0.3f, -1.06f, 0.0f)
lineToRelative(-5.1f, -5.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.0f, -1.07f)
lineToRelative(1.53f, -1.51f)
close()
moveTo(17.6f, 14.0f)
arcToRelative(3.5f, 3.5f, 0.0f, true, true, -3.6f, 3.51f)
verticalLineToRelative(-0.01f)
arcToRelative(3.5f, 3.5f, 0.0f, false, true, 3.6f, -3.5f)
close()
}
}
return _eraserSmall!!
}
private var _eraserSmall: ImageVector? = null
| 1 | Kotlin | 3 | 83 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 2,330 | compose-fluent-ui | Apache License 2.0 |
app/src/main/java/com/fracta7/crafter/domain/repository/AppRepository.kt | fracta7 | 749,375,185 | false | {"Kotlin": 447882} | package com.fracta7.crafter.domain.repository
import com.fracta7.crafter.domain.model.Category
import com.fracta7.crafter.domain.model.ItemRegistry
import com.fracta7.crafter.domain.model.RecipeRegistry
import com.fracta7.crafter.domain.model.RecipeType
import com.fracta7.crafter.domain.model.RecipeTypeID
interface AppRepository {
/**
* Provides an instance of ItemRegistry class that holds all items.
* @return ItemRegistry instance
*/
fun itemRegistryProvider(): ItemRegistry
/**
* Provides an instance of RecipeRegistry class that holds all recipes for items.
* @return RecipeRegistry instance.
*/
fun recipeRegistryProvider(): RecipeRegistry
fun getRecipeType(recipeTypeID: RecipeTypeID): RecipeType
fun getAllTags(): List<Category>
} | 0 | Kotlin | 0 | 2 | 6a836bd6c958f9ba641d78b51dd0f227b9530134 | 799 | crafter | MIT License |
tools/generator/src/main/kotlin/top/bettercode/summer/tools/generator/dom/java/StringOperator1.kt | top-bettercode | 387,652,015 | false | null | package top.bettercode.summer.tools.generator.dom.java
class StringOperator1(private val collections: MutableCollection<String>) {
operator fun String.unaryPlus() {
collections.add(this)
}
}
| 0 | Kotlin | 0 | 2 | 3e4c089f6a05cf0dcd658e1e792f0f3edcbff649 | 209 | summer | Apache License 2.0 |
app/src/main/java/com/example/starwarswiki/ui/films/FilmsViewModel.kt | VitalyMakarkin | 513,420,871 | false | null | package com.example.starwarswiki.ui.films
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.starwarswiki.data.StarWarsApi
import com.example.starwarswiki.model.FilmsPage
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class FilmsViewModel @Inject constructor(
private val starWarsApi: StarWarsApi
) : ViewModel() {
private var _films: MutableLiveData<FilmsPage> = MutableLiveData()
val films: LiveData<FilmsPage> get() = _films
init {
viewModelScope.launch {
_films.value = starWarsApi.getFilms().body()
}
}
} | 0 | Kotlin | 0 | 0 | 0afc0bb586f927b9d7bdee11dd40a58cc99425ef | 762 | star-wars-wiki | MIT License |
app/src/main/kotlin/com/fibelatti/pinboard/core/di/modules/NetworkModule.kt | fibelatti | 165,537,939 | false | {"Kotlin": 1138952} | package com.fibelatti.pinboard.core.di.modules
import com.fibelatti.pinboard.BuildConfig
import com.fibelatti.pinboard.core.AppConfig
import com.fibelatti.pinboard.core.di.UrlParser
import com.fibelatti.pinboard.core.network.ApiInterceptor
import com.fibelatti.pinboard.core.network.UnauthorizedInterceptor
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.serialization.json.Json
import okhttp3.CipherSuite
import okhttp3.ConnectionPool
import okhttp3.ConnectionSpec
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.kotlinx.serialization.asConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun retrofit(okHttpClient: OkHttpClient, json: Json): Retrofit = Retrofit.Builder()
.baseUrl(AppConfig.API_BASE_URL)
.client(okHttpClient)
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.build()
@Provides
fun json(): Json = Json {
ignoreUnknownKeys = true
}
@Provides
fun okHttpClient(
apiInterceptor: ApiInterceptor,
unauthorizedInterceptor: UnauthorizedInterceptor,
loggingInterceptor: HttpLoggingInterceptor,
): OkHttpClient {
// These are the server preferred Ciphers + all the ones included in COMPATIBLE_TLS
val cipherSuites: List<CipherSuite> = listOf(
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
) + ConnectionSpec.COMPATIBLE_TLS.cipherSuites.orEmpty()
val spec = ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
.cipherSuites(*cipherSuites.toTypedArray())
.build()
return OkHttpClient.Builder()
.connectionSpecs(listOf(spec))
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.connectionPool(ConnectionPool(0, 5, TimeUnit.MINUTES))
.addInterceptor(apiInterceptor)
.addInterceptor(unauthorizedInterceptor)
.apply { if (BuildConfig.DEBUG) addInterceptor(loggingInterceptor) }
.build()
}
@Provides
@UrlParser
fun urlParserOkHttpClient(
loggingInterceptor: HttpLoggingInterceptor,
): OkHttpClient = OkHttpClient.Builder()
.followRedirects(true)
.followSslRedirects(true)
.apply { if (BuildConfig.DEBUG) addInterceptor(loggingInterceptor) }
.build()
@Provides
fun httpLoggingInterceptor(): HttpLoggingInterceptor = HttpLoggingInterceptor()
.apply { level = HttpLoggingInterceptor.Level.BODY }
}
| 4 | Kotlin | 12 | 119 | 6ca7c7d852db25db9a5f14a893592224e565faad | 3,084 | pinboard-kotlin | Apache License 2.0 |
app/src/main/java/pl/valueadd/mvi/example/presentation/main/about/AboutView.kt | valueadd-poland | 238,159,445 | false | null | package pl.valueadd.mvi.example.presentation.main.about
import pl.valueadd.mvi.presenter.IBaseView
interface AboutView :
IBaseView<AboutViewState, IBaseView.IBaseIntent, IBaseView.IBaseEffect>
| 6 | Kotlin | 0 | 3 | 7d52819415c10e85dc6806d41433ad7ced63b5e9 | 199 | mvi-valueadd | Apache License 2.0 |
sq-core/src/main/kotlin/me/ore/sq/generic/SqGenericUpdate.kt | o-r-e | 614,027,727 | false | null | package me.ore.sq.generic
import me.ore.sq.*
open class SqGenericUpdate<T: SqTable>(
override val context: SqContext,
override val table: T,
override var set: Map<SqTableColumn<*, *>, SqExpression<*, *>>? = null,
override var where: SqExpression<*, Boolean>? = null,
): SqUpdate<T> {
companion object {
val CONSTRUCTOR: SqUpdateConstructor = object : SqUpdateConstructor {
override fun <T : SqTable> createUpdate(
context: SqContext,
table: T,
set: Map<SqTableColumn<*, *>, SqExpression<*, *>>?,
where: SqExpression<*, Boolean>?
): SqUpdate<T> {
return SqGenericUpdate(context, table, set, where)
}
}
}
override val definitionItem: SqItem
get() = this
override fun createValueMapping(): SqColumnValueMapping<T> = SqGenericColumnValueMapping(this)
}
| 0 | Kotlin | 0 | 0 | bb6fe063fc16ddda63067e821737b6e8b0f96812 | 927 | sq | MIT License |
app/src/main/java/bapspatil/flickoff/ui/splash/SplashActivityModule.kt | bapspatil | 102,198,607 | false | null | package bapspatil.flickoff.ui.splash
import dagger.Module
/*
** Created by Bapusaheb Patil {@link https://bapspatil.com}
*/
@Module
class SplashActivityModule {
} | 3 | Kotlin | 6 | 32 | f69aa21ab00443da552e1a9085295dfc52f5ae18 | 166 | FlickOff | Apache License 2.0 |
collaboration-suite-phone-ui/src/main/java/com/kaleyra/collaboration_suite_phone_ui/filesharing/model/TransferData.kt | Bandyer | 337,367,845 | false | null | /*
* Copyright 2023 Kaleyra @ https://www.kaleyra.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kaleyra.collaboration_suite_phone_ui.filesharing.model
import android.content.Context
import android.net.Uri
import com.kaleyra.collaboration_suite_phone_ui.extensions.getFileName
import com.kaleyra.collaboration_suite_phone_ui.extensions.getMimeType
import java.util.*
/**
*
* @property context Context
* @property id The id of the file transferred
* @property uri The uri which specifies the file location
* @property name The file's name
* @property mimeType The file's mime type
* @property sender The user who sent the file
* @property creationTime The creation time of the file
* @property bytesTransferred The bytes of the file transferred
* @property size The size of the file
* @property successUri The
* @property state The transfer's state
* @property type The transfer's type
* @constructor
*/
data class TransferData(
val context: Context,
val id: String = UUID.randomUUID().toString(),
val uri: Uri,
val name: String = uri.getFileName(context),
val mimeType: String = uri.getMimeType(context),
val sender: String,
val creationTime: Long = Date().time,
val bytesTransferred: Long = 0L,
val size: Long = -1L,
val successUri: Uri? = null,
val state: State,
val type: Type
) {
/**
* The states of the transfer
*/
sealed class State {
/**
* The file is available to download
*/
object Available : State()
/**
* The file transfer is pending
*/
object Pending : State()
/**
* The file transfer is on progress
*/
object OnProgress : State()
/**
* The file transfer has been successful
*/
object Success : State()
/**
* An error occurred during the file transfer
*/
object Error : State()
/**
* The file transfer has been cancelled
*/
object Cancelled : State()
}
/**
* The types of the transfer
*/
sealed class Type {
/**
* The file transfer is an upload
*/
object Upload : Type()
/**
* The file transfer is a download
*/
object Download : Type()
}
// override fun equals(other: Any?): Boolean {
// if (this === other) return true
// if (other !is TransferData) return false
//
// if (id != other.id) return false
// if (uri != other.uri) return false
// if (name != other.name) return false
// if (mimeType != other.mimeType) return false
// if (sender != other.sender) return false
// if (creationTime != other.creationTime) return false
// if (bytesTransferred != other.bytesTransferred) return false
// if (size != other.size) return false
// if (successUri != other.successUri) return false
// if (state != other.state) return false
// if (type != other.type) return false
//
// return true
// }
//
// override fun hashCode(): Int {
// var result = id.hashCode()
// result = 31 * result + bytesTransferred.hashCode()
// result = 31 * result + state.hashCode()
// return result
// }
} | 1 | Kotlin | 2 | 2 | b102f07b8572ec40f61446d4f052a0f023cdb815 | 3,851 | Bandyer-Android-Design | Apache License 2.0 |
app/src/main/java/lastsubmission/capstone/basantaraapps/helper/Result.kt | Rizald95 | 806,373,749 | false | {"Kotlin": 45683} | package lastsubmission.capstone.basantaraapps.helper
sealed class Result<out R> private constructor(){
data class Success<out T>(val data: T): Result<T>()
data class Error(val error: String) : Result<Nothing>()
object Loading : Result<Nothing>()
} | 0 | Kotlin | 0 | 0 | e712a8035404900f4a05c6c803f94375a33fdd6e | 260 | BasantaraApps | MIT License |
app/src/main/java/com/kusamaru/standroid/nguploader/work/UpdateNGUploaderVideoListWork.kt | kusamaru | 442,642,043 | false | null | package com.kusamaru.standroid.nguploader.work
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.kusamaru.standroid.R
import com.kusamaru.standroid.nguploader.NGUploaderTool
/**
* NGๆ็จฟ่
ใฎๆ็จฟใใๅ็ปไธ่ฆงใๆดๆฐใใ
*
* WorkManagerใไฝฟใฃใฆๅฎๆๅฎ่กใใใ
* */
class UpdateNGUploaderVideoListWork(private val context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) {
/** ้็ฅID */
private val NOTIFIACTION_ID = 334
/**
* ไปไบๅ
ๅฎนใใณใซใผใใณๅฏพๅฟ๏ผ
* */
override suspend fun doWork(): Result {
// ใใผใฟใใผใน้ข้ฃใฏใฉใน
val ngUploaderTool = NGUploaderTool(context)
// NGๅ็ปๆฐใ่จ็ฎ
ngUploaderTool.getNGUploader().forEach { userIdData ->
// ๆดๆฐ็จ้ขๆฐใๅผใถ
ngUploaderTool.updateNGUploaderVideoList(userIdData.userId)
}
// ๆๅใ่ฟใ
showNotification()
return Result.success()
}
/** ้็ฅใ้ไฟกใใ */
private fun showNotification() {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// ้็ฅใกใใใญใใงๅๅฒ
val notification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "ng_uploader_notification"
NotificationChannel(channelId, "NGๆ็จฟ่
/ๆ็จฟๅ็ปใใผใฟใใผใน้็ฅ", NotificationManager.IMPORTANCE_LOW).let { channel ->
// ใชใใใฐ่ฟฝๅ
if (notificationManager.getNotificationChannel(channelId) == null) {
notificationManager.createNotificationChannel(channel)
}
}
NotificationCompat.Builder(context, channelId)
} else {
NotificationCompat.Builder(context)
}
notification.apply {
setContentTitle("NGๆ็จฟ่
ๆดๆฐ้็ฅ")
setContentText("ๅฎๆๅฎ่กใๅฎไบใใพใใใ")
setSmallIcon(R.drawable.ng_uploader_icon)
}
// ๆ็จฟ
notificationManager.notify(NOTIFIACTION_ID, notification.build())
}
} | 0 | null | 0 | 3 | 5c58707eecc7a994fbd4bc900b22106697bf3806 | 2,147 | StanDroid | Apache License 2.0 |
android/app/src/main/kotlin/co/zw/amosesuwali/dog_playground_flutter/MainActivity.kt | amosesuwali | 444,852,501 | false | {"Dart": 5539, "Swift": 404, "Kotlin": 145, "Objective-C": 38} | package co.zw.amosesuwali.dog_playground_flutter
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 1 | 310a43d1906d41f29c8f9a3e8427665a059da53e | 145 | Dog-Playground-flutter | Apache License 2.0 |
core/src/main/java/com/alamkanak/weekview/EventChipCache.kt | AlexFedosenko | 201,034,801 | true | {"Kotlin": 214465} | package com.alamkanak.weekview
import androidx.collection.ArrayMap
import java.util.Calendar
internal class EventChipCache<T> {
val allEventChips: List<EventChip<T>>
get() = normalEventChipsByDate.values.flatten() + allDayEventChipsByDate.values.flatten()
private val normalEventChipsByDate = ArrayMap<Calendar, MutableList<EventChip<T>>>()
private val allDayEventChipsByDate = ArrayMap<Calendar, MutableList<EventChip<T>>>()
fun groupedByDate(): Map<Calendar, List<EventChip<T>>> {
return allEventChips.groupBy { it.event.startTime.atStartOfDay }
}
fun normalEventChipsByDate(date: Calendar): List<EventChip<T>> {
return normalEventChipsByDate[date.atStartOfDay].orEmpty()
}
fun allDayEventChipsByDate(date: Calendar): List<EventChip<T>> {
return allDayEventChipsByDate[date.atStartOfDay].orEmpty()
}
private fun put(newChips: List<EventChip<T>>) {
val (allDay, normal) = newChips.partition { it.event.isAllDay }
normal.forEach {
val key = it.event.startTime.atStartOfDay
normalEventChipsByDate.add(key, it)
}
allDay.forEach {
val key = it.event.startTime.atStartOfDay
allDayEventChipsByDate.add(key, it)
}
}
operator fun plusAssign(newChips: List<EventChip<T>>) = put(newChips)
fun clearCache() {
allEventChips.filter { it.originalEvent.isNotAllDay }.forEach(EventChip<T>::clearCache)
}
fun clear() {
allDayEventChipsByDate.clear()
normalEventChipsByDate.clear()
}
private fun ArrayMap<Calendar, MutableList<EventChip<T>>>.add(
key: Calendar,
eventChip: EventChip<T>
) {
val results = getOrElse(key) { mutableListOf() }
val indexOfExisting = results.indexOfFirst { it.event.id == eventChip.event.id }
if (indexOfExisting != -1) {
// If an event with the same ID already exists, replace it. The new event will likely be
// more up-to-date.
results.replace(indexOfExisting, eventChip)
} else {
results.add(eventChip)
}
this[key] = results
}
private fun <T> MutableList<T>.replace(index: Int, element: T) {
removeAt(index)
add(index, element)
}
}
| 0 | Kotlin | 0 | 0 | e5f4731a02f3611b257307832fcbea9cf8182310 | 2,317 | Android-Week-View | Apache License 2.0 |
src/main/kotlin/org/code4everything/hutool/Utils.kt | code4everything | 307,718,842 | false | {"Kotlin": 96703, "Go": 1860} | package org.code4everything.hutool
import cn.hutool.core.comparator.ComparatorChain
import cn.hutool.core.date.ChineseDate
import cn.hutool.core.date.DateTime
import cn.hutool.core.date.DateUtil
import cn.hutool.core.exceptions.ExceptionUtil
import cn.hutool.core.io.FileUtil
import cn.hutool.core.lang.Holder
import cn.hutool.core.lang.JarClassLoader
import cn.hutool.core.math.Calculator
import cn.hutool.core.util.ReflectUtil
import com.alibaba.fastjson.JSONObject
import java.io.File
import java.lang.reflect.Field
import java.lang.reflect.Modifier
import java.util.Arrays
import java.util.Date
import java.util.StringJoiner
import java.util.regex.Pattern
import java.util.stream.Collectors
import javassist.ClassPool
import javassist.CtMethod
import javassist.bytecode.LocalVariableAttribute
import kotlin.math.ceil
import org.code4everything.hutool.converter.ClassConverter
import org.code4everything.hutool.converter.DateConverter
import org.code4everything.hutool.converter.FileConverter
import org.code4everything.hutool.converter.ListStringConverter
import org.code4everything.hutool.converter.PatternConverter
object Utils {
@JvmStatic
private var classAliasJson: JSONObject? = null
@JvmStatic
var classLoader: JarClassLoader? = null
@JvmStatic
private var mvnRepositoryHome: List<String>? = null
@JvmStatic
fun listFiles(@IOConverter(FileConverter::class) file: File): String {
if (!FileUtil.exist(file)) {
return "file not found!"
}
if (FileUtil.isFile(file)) {
val date = DateUtil.formatDateTime(Date(file.lastModified()))
val size = FileUtil.readableFileSize(file)
return "$date\t$size\t${file.name}"
}
val filter = MethodArg.getSubParams(Hutool.ARG, 1)
val files = file.listFiles { _, name ->
isCollectionEmpty(filter) || filter.stream().anyMatch { name.lowercase().contains(it) }
}
if (isArrayEmpty(files)) {
return ""
}
Arrays.sort(
files!!, ComparatorChain.of(Comparator.comparingInt { if (it.isDirectory) 0 else 1 },
Comparator.comparing { it.name },
Comparator.comparingLong { it.lastModified() })
)
val joiner = StringJoiner("\n")
var maxLen = 0
val size = Array(files.size) { "" }
for (i in files.indices) {
size[i] = addSuffixIfNot(FileUtil.readableFileSize(files[i]).replace(" ", ""), "B")
val last = size[i].length - 2
if (!Character.isDigit(size[i][last])) {
// remove 'B' if has K,M...
size[i] = size[i].substring(0, size[i].length - 1)
}
if (size[i].length > maxLen) {
maxLen = size[i].length
}
}
for (i in files.indices) {
val date = DateUtil.formatDateTime(Date(files[i].lastModified()))
val fmtSize = size[i].padStart(maxLen, ' ')
joiner.add("$date $fmtSize ${files[i].name}")
}
return joiner.toString()
}
@JvmStatic
fun dayProcess(@IOConverter(DateConverter::class) specificDate: DateTime): String {
val date = DateUtil.beginOfDay(specificDate)
val todayProcess = (specificDate.time - date.time) * 100 / 24.0 / 60 / 60 / 1000
val weekEnum = DateUtil.dayOfWeekEnum(date)
var week = weekEnum.value - 1
week = (if (week == 0) 7 else week) * 24 - 24
val weekProcess = (week + specificDate.hour(true)) * 100 / 7.0 / 24
val monthProcess = DateUtil.dayOfMonth(date) * 100 / DateUtil.endOfMonth(date).dayOfMonth().toDouble()
val yearProcess = DateUtil.dayOfYear(date) * 100 / DateUtil.endOfYear(date).dayOfYear().toDouble()
var template = String.format(
"%s %s %s%n", lunar(specificDate), weekEnum.toChinese("ๅจ"), Hutool.simpleDateFormat.format(specificDate)
)
template += String.format("%nไปๆฅ [%s]: %05.2f%%", getDayProcessString(todayProcess), todayProcess)
template += String.format("%nๆฌๅจ [%s]: %05.2f%%", getDayProcessString(weekProcess), weekProcess)
template += String.format("%nๆฌๆ [%s]: %05.2f%%", getDayProcessString(monthProcess), monthProcess)
return template + String.format("%nๆฌๅนด [%s]: %05.2f%%", getDayProcessString(yearProcess), yearProcess)
}
@JvmStatic
private fun getDayProcessString(@IOConverter process: Double): String {
val p = (ceil(process * 100) / 100).toInt()
val cs = CharArray(100)
Arrays.fill(cs, 0, p, 'o')
Arrays.fill(cs, p, 100, ' ')
return String(cs)
}
@JvmStatic
fun toHttpUrlString(paramMap: Map<String?, *>?): String {
if (paramMap == null || paramMap.isEmpty()) {
return ""
}
val sb = StringBuilder()
var sep = "?"
for ((k, v) in paramMap) {
val value = v?.toString()
if (isStringEmpty(value)) {
continue
}
sb.append(sep).append(k).append("=").append(value).also { sep = "&" }
}
return sb.toString()
}
@JvmStatic
fun getFieldNames(@IOConverter(ClassConverter::class) clazz: Class<*>): String {
var clz = clazz
if (clz.isPrimitive) {
clz = parseClass0(parseClassName0("j." + clz.name))
}
val fields = ReflectUtil.getFields(clz)
val joiner = StringJoiner("\n")
val modifierMap: MutableMap<String, List<String>> = HashMap()
val comparators = ComparatorChain<String>().apply {
addComparator(Comparator.comparingInt { o ->
modifierMap.computeIfAbsent(o) { s ->
val ss = s.split(" ").toTypedArray()
if (ss.size > 2) Arrays.stream(ss).limit(ss.size - 2L).collect(Collectors.toList()) else emptyList()
}.size
})
addComparator(Comparator.naturalOrder())
}
val modifierList: MutableList<String> = ArrayList()
val holder = Holder.of("")
val filter = MethodArg.getSubParams(Hutool.ARG, 1)
Arrays.stream(fields).filter { e: Field ->
if (isCollectionEmpty(filter)) {
return@filter true
}
val fieldName = e.name.lowercase()
filter.stream().anyMatch { fieldName.contains(it) }
}.map { field: Field ->
var line = ""
val modifiers = field.modifiers
if (Modifier.isPrivate(modifiers)) {
line += "private "
} else if (Modifier.isProtected(modifiers)) {
line += "protected "
} else if (Modifier.isPublic(modifiers)) {
line += "public "
}
if (Modifier.isStatic(modifiers)) {
line += "static "
}
if (Modifier.isFinal(modifiers)) {
line += "final "
}
if (Modifier.isTransient(modifiers)) {
line += "transient "
}
if (Modifier.isVolatile(modifiers)) {
line += "volatile "
}
line + field.type.simpleName + " " + field.name
}.sorted(comparators).forEach { s: String ->
var line = s
val list = modifierMap[s]!!
if (modifierList != list) {
line = holder.get().toString() + line
modifierList.clear()
modifierList.addAll(list)
}
joiner.add(line)
holder.set("\n")
}
return joiner.toString()
}
@JvmStatic
fun getStaticFieldValue(@IOConverter(ClassConverter::class) clazz: Class<*>, fieldName: String?): Any {
var clz = clazz
if (clz.isPrimitive) {
clz = parseClass0(parseClassName0("j." + clz.name))
}
val field = ReflectUtil.getField(clz, fieldName)
return ReflectUtil.getStaticFieldValue(field)
}
@JvmStatic
@IOConverter(ListStringConverter::class)
fun getMatchedItems(@IOConverter(PatternConverter::class) regex: Pattern, content: String?): List<String> {
val result = ArrayList<String>()
val matcher = regex.matcher(content ?: "")
while (matcher.find()) {
result.add(matcher.group(0))
}
return result
}
@JvmStatic
fun getSupperClass(@IOConverter(ClassConverter::class) clazz: Class<*>?): String {
val joiner = StringJoiner("\n")
getSupperClass(joiner, "", clazz)
return joiner.toString()
}
@JvmStatic
private fun getSupperClass(joiner: StringJoiner, prefix: String, clazz: Class<*>?) {
if (clazz == null || Any::class.java == clazz) {
return
}
joiner.add(prefix + (if (clazz.isInterface) "<>" else "") + clazz.name)
getSupperClass(joiner, "$prefix|${" ".repeat(4)}", clazz.superclass)
for (anInterface in clazz.interfaces) {
getSupperClass(joiner, "$prefix|${" ".repeat(4)}", anInterface)
}
}
@JvmStatic
fun assignableFrom(
@IOConverter(ClassConverter::class) sourceClass: Class<*>,
@IOConverter(ClassConverter::class) testClass: Class<*>
): Boolean {
return sourceClass.isAssignableFrom(testClass)
}
@JvmStatic
fun calc(expression: String?, @IOConverter scale: Int): String {
val res = Calculator.conversion(expression)
return String.format("%.${scale}f", res)
}
@JvmStatic
fun lunar(@IOConverter(DateConverter::class) date: Date?): String = ChineseDate(date).toString()
@JvmStatic
fun date2Millis(@IOConverter(DateConverter::class) date: Date?): Long = date?.time ?: 0
@JvmStatic
fun toUpperCase(str: String?): String = str?.uppercase() ?: ""
@JvmStatic
fun toLowerCase(str: String?): String = str?.lowercase() ?: ""
@JvmStatic
fun grep(
@IOConverter(PatternConverter::class) pattern: Pattern,
@IOConverter(ListStringConverter::class) lines: List<String>?
): String {
var line = lines
if (isCollectionEmpty(line) && !isStringEmpty(Hutool.resultString)) {
line = ListStringConverter().useLineSep().string2Object(Hutool.resultString)
}
val joiner = StringJoiner("\n")
for (lin in line!!) {
if (pattern.matcher(lin).find()) {
joiner.add(lin)
}
}
return joiner.toString()
}
@JvmStatic
fun <T> isArrayEmpty(arr: Array<T>?): Boolean = arr?.isEmpty() ?: true
@JvmStatic
fun parseClass(className: String): Class<*>? {
return when (className) {
"bool", "boolean" -> Boolean::class.javaPrimitiveType
"byte" -> Byte::class.javaPrimitiveType
"short" -> Short::class.javaPrimitiveType
"char" -> Char::class.javaPrimitiveType
"int" -> Int::class.javaPrimitiveType
"long" -> Long::class.javaPrimitiveType
"float" -> Float::class.javaPrimitiveType
"double" -> Double::class.javaPrimitiveType
else -> parseClass0(className)
}
}
@JvmStatic
private fun parseClass0(className: String): Class<*> {
var cn = className
cn = parseClassName0(cn)
try {
return Class.forName(cn)
} catch (e: Exception) {
// ignore
}
Hutool.debugOutput("loading class: %s", cn)
if (classLoader == null) {
classLoader = JarClassLoader()
classLoader!!.addJar(FileUtil.file(Hutool.homeDir, "external"))
val externalConf = FileUtil.file(Hutool.homeDir, "external.conf")
if (FileUtil.exist(externalConf)) {
val externalPaths = FileUtil.readUtf8String(externalConf).split(Pattern.compile("\n|,"))
for (externalPath in externalPaths) {
val external = parseClasspath(externalPath)
if (FileUtil.exist(external)) {
Hutool.debugOutput("add class path: %s", external!!.absolutePath)
classLoader!!.addURL(external)
}
}
}
}
return classLoader!!.loadClass(cn)
}
@JvmStatic
private fun parseClasspath(path: String): File? {
var p = path
p = p.trim().trimEnd(',')
if (p.isEmpty() || p.startsWith("//")) {
return null
}
if (p.startsWith("mvn:")) {
p = p.substring(4)
if (isStringEmpty(p)) {
return null
}
val coordinates = p.split(Pattern.compile(":"), 3).toTypedArray()
if (coordinates.size != 3) {
Hutool.debugOutput("mvn coordinate format error: %s", p)
return null
}
mvnRepositoryHome ?: run { mvnRepositoryHome = listOf("~", ".m2", "repository") }
val paths: MutableList<String> = ArrayList(mvnRepositoryHome!!)
paths.addAll(coordinates[0].split('.'))
val name = coordinates[1]
val version = coordinates[2]
paths.add(name)
paths.add(version)
paths.add("$name-$version.jar")
val file = FileUtil.file(*paths.toTypedArray())
Hutool.debugOutput("get mvn path: %s", file.absolutePath)
return file
}
return FileUtil.file(p)
}
@JvmStatic
fun parseClassName(className: String): String {
return when (className) {
"bool", "boolean" -> "boolean"
"byte" -> "byte"
"short" -> "short"
"char" -> "char"
"int" -> "int"
"long" -> "long"
"float" -> "float"
"double" -> "double"
else -> parseClassName0(className)
}
}
@JvmStatic
private fun parseClassName0(className: String): String {
return when (className) {
"string" -> "java.lang.String"
"j.char.seq" -> "java.lang.CharSequence"
"file" -> "java.io.File"
"charset" -> "java.nio.charset.Charset"
"date" -> "java.util.Date"
"class" -> "java.lang.Class"
"j.bool", "j.boolean" -> "java.lang.Boolean"
"j.byte" -> "java.lang.Byte"
"j.short" -> "java.lang.Short"
"j.int", "j.integer" -> "java.lang.Integer"
"j.char" -> "java.lang.Character"
"j.long" -> "java.lang.Long"
"j.float" -> "java.lang.Float"
"j.double" -> "java.lang.Double"
"reg.pattern" -> "java.util.regex.Pattern"
"map" -> "java.util.Map"
"list" -> "java.util.List"
"set" -> "java.util.Set"
else -> parseClassName00(className)
}
}
@JvmStatic
private fun parseClassName00(className: String): String {
var cn = className
if (cn.endsWith(";") && cn.contains("[L")) {
val idx = cn.indexOf("L")
val prefix = cn.substring(0, idx + 1)
val name = parseClassName(cn.substring(idx + 1, cn.length - 1))
return "$prefix$name;"
}
if (cn.length > 16) {
return cn
}
if (classAliasJson == null) {
classAliasJson = Hutool.getAlias("", Hutool.homeDir, Hutool.CLASS_JSON)
classAliasJson!!.putAll(Hutool.getAlias("", "", Hutool.CLASS_JSON))
}
val classJson = classAliasJson!!.getJSONObject(cn)
if (classJson != null) {
val className0 = classJson.getString(Hutool.CLAZZ_KEY)
if (!isStringEmpty(className0)) {
cn = className0
}
}
return cn
}
@JvmStatic
fun isStringEmpty(str: String?): Boolean = str?.isEmpty() ?: true
@JvmStatic
fun <T> isCollectionEmpty(collection: Collection<T>?): Boolean = collection?.isEmpty() ?: true
fun addPrefixIfNot(str: String, prefix: String): String {
return if (isStringEmpty(str) || isStringEmpty(prefix) || str.startsWith(prefix)) str else prefix + str
}
@JvmStatic
fun addSuffixIfNot(str: String, suffix: String): String {
return if (isStringEmpty(str) || isStringEmpty(suffix) || str.endsWith(suffix)) str else str + suffix
}
@JvmStatic
fun outputPublicStaticMethods(className: String): String {
if (isStringEmpty(className)) {
return ""
}
val filter = MethodArg.getSubParams(Hutool.ARG, 1).map { it.lowercase() }
return outputPublicStaticMethods0(className, filter)
}
@JvmStatic
fun outputPublicStaticMethods0(className: String, filter: List<String>, forceEquals: Boolean = false): String {
val pool = ClassPool.getDefault()
val joiner = StringJoiner("\n")
try {
val ctClass = pool[parseClassName(className)]
val methods = ctClass.methods
val lineList: MutableList<String> = ArrayList(methods.size)
for (method in methods) {
val modifiers = method.modifiers
if (!Modifier.isPublic(modifiers) || !Modifier.isStatic(modifiers)) {
continue
}
if (filter.isNotEmpty()) {
val methodName = method.name.lowercase()
if (filter.stream().noneMatch { if (forceEquals) methodName == it else methodName.contains(it) }) {
continue
}
}
lineList.add(getMethodFullInfo(method, null))
}
lineList.stream().sorted(String::compareTo).forEach(joiner::add)
} catch (e: Exception) {
Hutool.debugOutput(
"parse class static methods error: %s", ExceptionUtil.stacktraceToString(e, Int.MAX_VALUE)
)
}
return joiner.toString()
}
@JvmStatic
fun getMethodFullInfo(method: CtMethod, defaultValueMap: Map<String?, String?>?): String {
val parameterTypes = method.parameterTypes
if (Hutool.isDebug) {
val joiner = StringJoiner(",")
Arrays.stream(parameterTypes).forEach { joiner.add(it.name) }
Hutool.debugOutput("parse method full info: %s#%s(%s)", method.declaringClass.name, method.name, joiner)
}
val paramJoiner = StringJoiner(", ")
val attribute =
method.methodInfo.codeAttribute.getAttribute(LocalVariableAttribute.tag) as LocalVariableAttribute?
for (i in parameterTypes.indices) {
val parameterType = parameterTypes[i]
val paramType = parameterType.name
var paramStr = attribute!!.variableName(i) + ":" + paramType
if (defaultValueMap != null) {
val defaultValue = defaultValueMap[paramType + i]
if (!isStringEmpty(defaultValue)) {
paramStr = "$paramStr=$defaultValue"
}
}
paramJoiner.add(paramStr)
}
return "${method.name}($paramJoiner)"
}
}
| 0 | Kotlin | 1 | 3 | fc8d22ab359cd89cf1232ea95464860e72df9be9 | 19,254 | hutool-cli | MIT License |
app/src/main/java/com/example/toDoListKotlin/ui/screens/alertDialog/CustomDetailDialog.kt | ShinyParadise | 531,014,248 | false | {"Kotlin": 38329} | package com.example.toDoListKotlin.ui.screens.alertDialog
import android.content.res.Configuration
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
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 androidx.compose.ui.unit.sp
import com.example.toDoListKotlin.R
import com.example.toDoListKotlin.ui.screens.detailScreen.DetailViewModel
import com.example.toDoListKotlin.ui.theme.ToDoListAppTheme
@Composable
fun CustomDetailDialog(
dialogDescription: String,
onPositiveClick: () -> Unit,
onNegativeClick: () -> Unit,
onChangeDescription: (String) -> Unit
) {
AlertDialog(
onDismissRequest = onNegativeClick,
contentColor = MaterialTheme.colors.onBackground,
backgroundColor = MaterialTheme.colors.background,
buttons = {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
BackButton {
onNegativeClick()
}
AddButton {
onPositiveClick()
}
}
},
text = {
Column(Modifier.padding(vertical = 8.dp)) {
Text(
text = stringResource(R.string.add_list_item_title),
fontSize = 20.sp,
style = MaterialTheme.typography.h6,
modifier = Modifier.padding(8.dp)
)
InputField(
label = "Description",
storedValue = dialogDescription,
onChangeDescription
)
}
}
)
}
@Preview(showBackground = true)
@Composable
private fun Dialog_Preview_Light() {
ToDoListAppTheme {
CustomDetailDialog(
dialogDescription = "",
onPositiveClick = {},
onNegativeClick = {},
onChangeDescription = {}
)
}
}
@Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun Dialog_Preview_Dark() {
ToDoListAppTheme {
CustomDetailDialog(
dialogDescription = "",
onPositiveClick = {},
onNegativeClick = {},
onChangeDescription = {}
)
}
}
| 0 | Kotlin | 0 | 0 | bac22229d1af1ee4d9c64f865c293dff4e3b4bee | 2,473 | todolist-kotlin | MIT License |
app/src/main/java/reactivecircus/releaseprobe/ReleaseProbeAppNavigator.kt | ReactiveCircus | 142,655,149 | false | null | package reactivecircus.releaseprobe
import android.app.Activity
import androidx.core.os.bundleOf
import androidx.navigation.findNavController
import reactivecircus.releaseprobe.artifactlist.ARG_COLLECTION_KEY
import reactivecircus.releaseprobe.core.AppNavigator
/**
* Implementation of [AppNavigator].
*/
class ReleaseProbeAppNavigator : AppNavigator {
override fun navigateToArtifactListScreen(
activity: Activity,
collectionName: String
) {
activity.findNavController(R.id.mainNavHostFragment).navigate(
R.id.action_global_artifactListFragment,
bundleOf(ARG_COLLECTION_KEY to collectionName)
)
}
}
| 7 | Kotlin | 4 | 8 | b97fb5b8f161f29b70db1de6446af76166f42aa4 | 673 | release-probe | MIT License |
src/Day01.kt | tsdenouden | 572,703,357 | false | {"Kotlin": 8295} | fun main() {
fun getInventories(input: List<String>): MutableList<Int> {
val calories: MutableList<Int> = mutableListOf()
var currentInventory = 0
input.forEach { line ->
if (line == "") {
calories.add(currentInventory)
currentInventory = 0
} else {
currentInventory += line.toInt()
}
}
if (currentInventory != 0) {
calories.add(currentInventory)
}
return calories
}
fun part1(input: List<String>): Int {
val calories = getInventories(input)
return calories.maxOrNull() ?: 0
}
fun part2(input: List<String>): Int {
val calories = getInventories(input)
calories.sortDescending()
return calories[0] + calories[1] + calories[2]
}
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 68982ebffc116f3b49a622d81e725c8ad2356fed | 1,061 | aoc-2022-kotlin | Apache License 2.0 |
pp-views/src/main/java/com/dansdev/app/view/PDConstraintLayout.kt | Daniil-Pavenko | 301,665,045 | false | null | package com.dansdev.app.view
import android.content.Context
import android.util.AttributeSet
import androidx.constraintlayout.widget.ConstraintLayout
import com.dansdev.app.util.onAttachWindow
open class PDConstraintLayout : ConstraintLayout, IPerfectDesignView {
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
initSizes(isInEditMode, context, attrs)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
onAttachWindow(this)
}
override var percentMarginTop: Int = 0
override var percentMarginBottom: Int = 0
override var percentMarginStart: Int = 0
override var percentMarginEnd: Int = 0
override var percentHeight: Int = 0
override var percentWidth: Int = 0
override var percentPaddingStart: Int = 0
override var percentPaddingEnd: Int = 0
override var percentPaddingTop: Int = 0
override var percentPaddingBottom: Int = 0
override var percentTextSize: Float = 0f
}
| 0 | Kotlin | 0 | 0 | f2db30928db2b0ab01a93f5c0fa7b22eccf973db | 1,200 | pp-views | Apache License 2.0 |
app/src/main/java/com/imarti/affirmations/alarm/AlarmReceiver.kt | karan31q | 748,974,945 | false | {"Kotlin": 87957} | package com.imarti.affirmations.alarm
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import java.time.LocalDateTime
import java.util.Calendar
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val tag = "DailyAffirmations"
val action = intent.action
val sharedPrefs = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
val alarmSet = sharedPrefs.getBoolean("alarm_set", false) // false is default value
if (action != null && action == "android.intent.action.BOOT_COMPLETED") {
Log.i(tag, "Received boot intent")
if (alarmSet) {
val selectedHour = sharedPrefs.getInt("hour_selected", 8)
val selectedMinute = sharedPrefs.getInt("minute_selected", 30)
// get user specified
val now = Calendar.getInstance()
now[Calendar.HOUR_OF_DAY] = LocalDateTime.now().hour
now[Calendar.MINUTE] = LocalDateTime.now().minute
now[Calendar.SECOND] = 0
now[Calendar.MILLISECOND] = 0
val calendar = Calendar.getInstance()
calendar[Calendar.HOUR_OF_DAY] = selectedHour
calendar[Calendar.MINUTE] = selectedMinute
calendar[Calendar.SECOND] = 0
calendar[Calendar.MILLISECOND] = 0
/*
check if the time has already passed today and add a day if it that's the case
*/
if (now.after(calendar)) {
Log.i(tag, "Added a day.")
calendar.add(Calendar.DATE, 1)
}
setAlarm(calendar, context)
} else {
Log.i(tag, "Alarms not set")
}
} else if (action != null && (action == "com.imarti.affirmations.ACTION_SET_ALARM" ||
action == "com.imarti.affirmations.ACTION_CANCEL_ALARM")
) {
notificationBuilder(context)
} else {
Log.i(tag, "Received unexpected action $action")
}
}
} | 0 | Kotlin | 0 | 2 | b1f0311940b8fcf30cd62e8626dd55ee137c0f59 | 2,216 | affirmations_app | MIT License |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/medialive/CfnEventBridgeRuleTemplateProps.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 149148378} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.medialive
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Any
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.collections.Map
/**
* Properties for defining a `CfnEventBridgeRuleTemplate`.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.medialive.*;
* CfnEventBridgeRuleTemplateProps cfnEventBridgeRuleTemplateProps =
* CfnEventBridgeRuleTemplateProps.builder()
* .eventType("eventType")
* .groupIdentifier("groupIdentifier")
* .name("name")
* // the properties below are optional
* .description("description")
* .eventTargets(List.of(EventBridgeRuleTemplateTargetProperty.builder()
* .arn("arn")
* .build()))
* .tags(Map.of(
* "tagsKey", "tags"))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html)
*/
public interface CfnEventBridgeRuleTemplateProps {
/**
* A resource's optional description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html#cfn-medialive-eventbridgeruletemplate-description)
*/
public fun description(): String? = unwrap(this).getDescription()
/**
* The destinations that will receive the event notifications.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html#cfn-medialive-eventbridgeruletemplate-eventtargets)
*/
public fun eventTargets(): Any? = unwrap(this).getEventTargets()
/**
* The type of event to match with the rule.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html#cfn-medialive-eventbridgeruletemplate-eventtype)
*/
public fun eventType(): String
/**
* An eventbridge rule template group's identifier.
*
* Can be either be its id or current name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html#cfn-medialive-eventbridgeruletemplate-groupidentifier)
*/
public fun groupIdentifier(): String
/**
* A resource's name.
*
* Names must be unique within the scope of a resource type in a specific region.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html#cfn-medialive-eventbridgeruletemplate-name)
*/
public fun name(): String
/**
* Represents the tags associated with a resource.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html#cfn-medialive-eventbridgeruletemplate-tags)
*/
public fun tags(): Map<String, String> = unwrap(this).getTags() ?: emptyMap()
/**
* A builder for [CfnEventBridgeRuleTemplateProps]
*/
@CdkDslMarker
public interface Builder {
/**
* @param description A resource's optional description.
*/
public fun description(description: String)
/**
* @param eventTargets The destinations that will receive the event notifications.
*/
public fun eventTargets(eventTargets: IResolvable)
/**
* @param eventTargets The destinations that will receive the event notifications.
*/
public fun eventTargets(eventTargets: List<Any>)
/**
* @param eventTargets The destinations that will receive the event notifications.
*/
public fun eventTargets(vararg eventTargets: Any)
/**
* @param eventType The type of event to match with the rule.
*/
public fun eventType(eventType: String)
/**
* @param groupIdentifier An eventbridge rule template group's identifier.
* Can be either be its id or current name.
*/
public fun groupIdentifier(groupIdentifier: String)
/**
* @param name A resource's name.
* Names must be unique within the scope of a resource type in a specific region.
*/
public fun name(name: String)
/**
* @param tags Represents the tags associated with a resource.
*/
public fun tags(tags: Map<String, String>)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.medialive.CfnEventBridgeRuleTemplateProps.Builder =
software.amazon.awscdk.services.medialive.CfnEventBridgeRuleTemplateProps.builder()
/**
* @param description A resource's optional description.
*/
override fun description(description: String) {
cdkBuilder.description(description)
}
/**
* @param eventTargets The destinations that will receive the event notifications.
*/
override fun eventTargets(eventTargets: IResolvable) {
cdkBuilder.eventTargets(eventTargets.let(IResolvable.Companion::unwrap))
}
/**
* @param eventTargets The destinations that will receive the event notifications.
*/
override fun eventTargets(eventTargets: List<Any>) {
cdkBuilder.eventTargets(eventTargets.map{CdkObjectWrappers.unwrap(it)})
}
/**
* @param eventTargets The destinations that will receive the event notifications.
*/
override fun eventTargets(vararg eventTargets: Any): Unit = eventTargets(eventTargets.toList())
/**
* @param eventType The type of event to match with the rule.
*/
override fun eventType(eventType: String) {
cdkBuilder.eventType(eventType)
}
/**
* @param groupIdentifier An eventbridge rule template group's identifier.
* Can be either be its id or current name.
*/
override fun groupIdentifier(groupIdentifier: String) {
cdkBuilder.groupIdentifier(groupIdentifier)
}
/**
* @param name A resource's name.
* Names must be unique within the scope of a resource type in a specific region.
*/
override fun name(name: String) {
cdkBuilder.name(name)
}
/**
* @param tags Represents the tags associated with a resource.
*/
override fun tags(tags: Map<String, String>) {
cdkBuilder.tags(tags)
}
public fun build(): software.amazon.awscdk.services.medialive.CfnEventBridgeRuleTemplateProps =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.medialive.CfnEventBridgeRuleTemplateProps,
) : CdkObject(cdkObject),
CfnEventBridgeRuleTemplateProps {
/**
* A resource's optional description.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html#cfn-medialive-eventbridgeruletemplate-description)
*/
override fun description(): String? = unwrap(this).getDescription()
/**
* The destinations that will receive the event notifications.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html#cfn-medialive-eventbridgeruletemplate-eventtargets)
*/
override fun eventTargets(): Any? = unwrap(this).getEventTargets()
/**
* The type of event to match with the rule.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html#cfn-medialive-eventbridgeruletemplate-eventtype)
*/
override fun eventType(): String = unwrap(this).getEventType()
/**
* An eventbridge rule template group's identifier.
*
* Can be either be its id or current name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html#cfn-medialive-eventbridgeruletemplate-groupidentifier)
*/
override fun groupIdentifier(): String = unwrap(this).getGroupIdentifier()
/**
* A resource's name.
*
* Names must be unique within the scope of a resource type in a specific region.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html#cfn-medialive-eventbridgeruletemplate-name)
*/
override fun name(): String = unwrap(this).getName()
/**
* Represents the tags associated with a resource.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-medialive-eventbridgeruletemplate.html#cfn-medialive-eventbridgeruletemplate-tags)
*/
override fun tags(): Map<String, String> = unwrap(this).getTags() ?: emptyMap()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): CfnEventBridgeRuleTemplateProps {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.medialive.CfnEventBridgeRuleTemplateProps):
CfnEventBridgeRuleTemplateProps = CdkObjectWrappers.wrap(cdkObject) as?
CfnEventBridgeRuleTemplateProps ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: CfnEventBridgeRuleTemplateProps):
software.amazon.awscdk.services.medialive.CfnEventBridgeRuleTemplateProps = (wrapped as
CdkObject).cdkObject as
software.amazon.awscdk.services.medialive.CfnEventBridgeRuleTemplateProps
}
}
| 0 | Kotlin | 0 | 4 | 652b030da47fc795f7a987eba0f8c82f64035d24 | 9,908 | kotlin-cdk-wrapper | Apache License 2.0 |
src/security/src/main/kotlin/org/vaccineimpact/api/security/TokenValidationException.kt | vimc | 85,062,678 | false | null | package org.vaccineimpact.api.security
class TokenValidationException(message: String) : Exception("Token validation failed: $message")
{
constructor(field: String, expected: String, actual: String)
: this("$field was '$actual' - it should have been '$expected'")
} | 1 | Kotlin | 1 | 2 | 0b3acb5f22b71300d6c260c5ecb252b0bddbe6ea | 282 | montagu-api | MIT License |
src/main/kotlin/com/sparetimedevs/ami/app/icon/Piano.kt | sparetimedevs | 731,672,148 | false | {"Kotlin": 235966} | /*
* Copyright (c) 2023 sparetimedevs and respective authors and developers.
*
* 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.sparetimedevs.ami.app.icon
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
public val AmiDesktopAppIcons.Piano: ImageVector
get() {
if (_piano != null) {
return _piano!!
}
_piano =
Builder(
name = "Piano",
defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp,
viewportWidth = 64.0f,
viewportHeight = 64.0f
)
.apply {
path(
fill = SolidColor(Color(0xFF000000)),
stroke = SolidColor(Color(0x00000000)),
strokeLineWidth = 0.0f,
strokeLineCap = Butt,
strokeLineJoin = Miter,
strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(31.0f, 62.0f)
curveTo(31.0f, 62.0f, 17.0f, 62.0f, 17.0f, 62.0f)
curveTo(17.0f, 62.0f, 17.0f, 42.0f, 17.0f, 42.0f)
curveTo(17.0f, 42.0f, 20.0f, 42.0f, 20.0f, 42.0f)
curveTo(20.553f, 42.0f, 21.0f, 41.553f, 21.0f, 41.0f)
curveTo(21.0f, 41.0f, 21.0f, 2.0f, 21.0f, 2.0f)
curveTo(21.0f, 2.0f, 27.0f, 2.0f, 27.0f, 2.0f)
curveTo(27.0f, 2.0f, 27.0f, 41.0f, 27.0f, 41.0f)
curveTo(27.0f, 41.553f, 27.447f, 42.0f, 28.0f, 42.0f)
curveTo(28.0f, 42.0f, 31.0f, 42.0f, 31.0f, 42.0f)
curveTo(31.0f, 42.0f, 31.0f, 62.0f, 31.0f, 62.0f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)),
stroke = SolidColor(Color(0x00000000)),
strokeLineWidth = 0.0f,
strokeLineCap = Butt,
strokeLineJoin = Miter,
strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(47.0f, 62.0f)
curveTo(47.0f, 62.0f, 33.0f, 62.0f, 33.0f, 62.0f)
curveTo(33.0f, 62.0f, 33.0f, 42.0f, 33.0f, 42.0f)
curveTo(33.0f, 42.0f, 36.0f, 42.0f, 36.0f, 42.0f)
curveTo(36.553f, 42.0f, 37.0f, 41.553f, 37.0f, 41.0f)
curveTo(37.0f, 41.0f, 37.0f, 2.0f, 37.0f, 2.0f)
curveTo(37.0f, 2.0f, 43.0f, 2.0f, 43.0f, 2.0f)
curveTo(43.0f, 2.0f, 43.0f, 41.0f, 43.0f, 41.0f)
curveTo(43.0f, 41.553f, 43.447f, 42.0f, 44.0f, 42.0f)
curveTo(44.0f, 42.0f, 47.0f, 42.0f, 47.0f, 42.0f)
curveTo(47.0f, 42.0f, 47.0f, 62.0f, 47.0f, 62.0f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)),
stroke = SolidColor(Color(0x00000000)),
strokeLineWidth = 0.0f,
strokeLineCap = Butt,
strokeLineJoin = Miter,
strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(62.0f, 60.0f)
curveTo(62.0f, 61.104f, 61.104f, 62.0f, 60.0f, 62.0f)
curveTo(60.0f, 62.0f, 49.0f, 62.0f, 49.0f, 62.0f)
curveTo(49.0f, 62.0f, 49.0f, 42.0f, 49.0f, 42.0f)
curveTo(49.0f, 42.0f, 52.0f, 42.0f, 52.0f, 42.0f)
curveTo(52.553f, 42.0f, 53.0f, 41.553f, 53.0f, 41.0f)
curveTo(53.0f, 41.0f, 53.0f, 2.0f, 53.0f, 2.0f)
curveTo(53.0f, 2.0f, 60.0f, 2.0f, 60.0f, 2.0f)
curveTo(61.016f, 2.0f, 62.0f, 2.896f, 62.0f, 4.0f)
curveTo(62.0f, 4.0f, 62.0f, 60.0f, 62.0f, 60.0f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)),
stroke = SolidColor(Color(0x00000000)),
strokeLineWidth = 0.0f,
strokeLineCap = Butt,
strokeLineJoin = Miter,
strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(2.0f, 60.0f)
curveTo(2.0f, 60.0f, 2.0f, 4.0f, 2.0f, 4.0f)
curveTo(2.0f, 2.896f, 2.641f, 2.0f, 4.0f, 2.0f)
curveTo(4.0f, 2.0f, 11.0f, 2.0f, 11.0f, 2.0f)
curveTo(11.0f, 2.0f, 11.0f, 41.0f, 11.0f, 41.0f)
curveTo(11.0f, 41.553f, 11.447f, 42.0f, 12.0f, 42.0f)
curveTo(12.0f, 42.0f, 15.0f, 42.0f, 15.0f, 42.0f)
curveTo(15.0f, 42.0f, 15.0f, 62.0f, 15.0f, 62.0f)
curveTo(15.0f, 62.0f, 4.0f, 62.0f, 4.0f, 62.0f)
curveTo(2.896f, 62.0f, 2.0f, 61.104f, 2.0f, 60.0f)
close()
}
}
.build()
return _piano!!
}
private var _piano: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 0eba1e31391cf44922d354f7614206d91e0cbd1c | 6,555 | ami-desktop | Apache License 2.0 |
src/main/kotlin/fp/kotlin/example/chapter04/CurriedFunctions.kt | funfunStory | 101,662,895 | false | null | package fp.kotlin.example.chapter04
fun main() {
println(multiThree(1, 2, 3)) // 6
val partial1 = multiThree(1)
val partial2 = partial1(2)
val partial3 = partial2(3)
println(partial3) // 6
println(multiThree(1)(2)(3)) // 6
val multiThree = { a: Int, b: Int, c: Int -> a * b * c }
val curried = multiThree.curried()
println(curried(1)(2)(3)) // 6
val uncurried = curried.uncurried()
println(uncurried(1, 2, 3)) // 6
}
private fun multiThree(a: Int, b: Int, c: Int): Int = a * b * c
private fun multiThree(a: Int) = { b: Int -> { c: Int -> a * b * c } }
private fun <P1, P2, P3, R> ((P1, P2, P3) -> R).curried(): (P1) -> (P2) -> (P3) -> R =
{ p1: P1 -> { p2: P2 -> { p3: P3 -> this(p1, p2, p3) } } }
private fun <P1, P2, P3, R> ((P1) -> (P2) -> (P3) -> R).uncurried(): (P1, P2, P3) -> R =
{ p1: P1, p2: P2, p3: P3 -> this(p1)(p2)(p3) } | 2 | Kotlin | 19 | 39 | 29b9940890ef50f5165af25a7ee45ea0b955f28b | 911 | fp-kotlin-example | MIT License |
shared/src/androidMain/kotlin/player/PlayerType.kt | Snd-R | 563,948,420 | false | {"Kotlin": 229752, "Java": 90203} | package player
import kotlinx.serialization.Serializable
@Serializable(with = PlayerTypeSerializer::class)
actual class PlayerType actual constructor(type: String) {
actual val type: String
init {
this.type = type
}
}
| 0 | Kotlin | 0 | 0 | 568ee05a99532d55257d7690d0a4a0de64bf40b6 | 241 | PotatoTube | MIT License |
processor/src/test/kotlin/fr/smarquis/sealed/SealedExtensionsTest.kt | SimonMarquis | 527,279,535 | false | null | package fr.smarquis.sealed
import kotlin.test.Test
import kotlin.test.assertEquals
class SealedExtensionsTest {
@Test
fun `reflect extension produces the same output`() = assertEquals(
expected = MySealedClass::class.sealedObjectInstances(),
actual = MySealedClass::class.reflectSealedObjectInstances(),
)
} | 3 | Kotlin | 0 | 17 | 9a8f7f5f5ea859e114187944707d74314f389eeb | 340 | SealedObjectInstances | Apache License 2.0 |
app/src/main/kotlin/org/dersbian/klexicon/Evaluator.kt | Giuseppe-Bianc | 633,500,872 | false | null | package org.dersbian.klexicon
class Evaluator(input: String) {
val expr = Parser(input).parse()
fun evaluate(): Double = evaluate(expr)
private inline fun evaluate(expr: Expr): Double {
return when (expr) {
is Num -> expr.value
is BinOp -> evaluateBinaryOp(expr)
is UnaryOp -> evaluateUnaryOp(expr)
}
}
private fun evaluateBinaryOp(expr: BinOp): Double {
val left = evaluate(expr.left)
val right = evaluate(expr.right)
return when (expr.op.type) {
TokType.PLUS -> left + right
TokType.MINUS -> left - right
TokType.MULTIPLY -> left * right
TokType.DIVIDE -> left / right
else -> throw UnsupportedOperationException("Unsupported operator ${expr.op}")
}
}
private fun evaluateUnaryOp(expr: UnaryOp): Double {
val operand = evaluate(expr.operand)
return when (expr.operator.type) {
TokType.MINUS -> -operand
else -> throw UnsupportedOperationException("Unsupported operator ${expr.operator}")
}
}
}
| 0 | Kotlin | 0 | 0 | b8dd2fe423b9ec0dc1b83893d8ae5c70ccac3178 | 1,126 | KLexicon | MIT License |
app/src/main/java/com/example/sharesheet/MetadataActivity.kt | weblineindia | 730,622,730 | false | {"Kotlin": 7890} | package com.example.sharesheet
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MetadataActivity : AppCompatActivity() {
private lateinit var heightTextView: TextView
private lateinit var lengthTextView: TextView
private lateinit var orientationTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_metadata)
heightTextView = findViewById(R.id.heightTv)
lengthTextView = findViewById(R.id.lengthTv)
orientationTextView = findViewById(R.id.orientationTv)
val array = intent.getStringArrayListExtra("metadata")
if (array != null) {
Log.d("metadataArray", array.toString())
heightTextView.text = "Height : " + array[0]
lengthTextView.text = "Length : " + array[1]
orientationTextView.text = "Orientation : " + array[2]
}
}
} | 0 | Kotlin | 0 | 0 | 616fe6637c87a7c67833e2480320d7b086cf3aa0 | 1,028 | Android-Share-sheet | MIT License |
src/main/kotlin/cn/yyxx/apklink/ext/TransformExt.kt | Suyghur | 470,003,377 | false | {"Kotlin": 14276, "Shell": 2598} | package cn.yyxx.apklink.ext
import cn.yyxx.apklink.GlobalConfig
import java.io.File
fun jar2dex(src: String, dst: String) {
val jars = StringBuilder()
File(src).walk().maxDepth(1).filter {
it.extension == "jar"
}.forEach {
jars.append(" ").append(it.absolutePath)
}
"${GlobalConfig.d8} --lib ${GlobalConfig.androidJar} --output $dst $jars".execute()
}
fun dex2smali(src: String, dst: String) {
"java -jar -Xms2048m -Xmx2048m ${GlobalConfig.baksmali} -o $dst $src".execute()
} | 0 | Kotlin | 0 | 0 | fd95c74a13ab4837ed21fca640542ae73e839c8f | 519 | apklink | Apache License 2.0 |
src/main/kotlin/com/mnnit/moticlubs/repository/AdminRepository.kt | CC-MNNIT | 583,707,830 | false | null | package com.mnnit.moticlubs.repository
import com.mnnit.moticlubs.dao.Admin
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate
import org.springframework.data.relational.core.query.Criteria
import org.springframework.data.relational.core.query.Query
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Transactional
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@Repository
class AdminRepository(
private val db: R2dbcEntityTemplate,
) {
@Transactional
fun save(admin: Admin): Mono<Admin> = exists(admin)
.flatMap { if (it) Mono.just(admin) else db.insert(admin) }
@Transactional
fun findAll(): Flux<Admin> = db.select(Query.empty(), Admin::class.java)
@Transactional
fun exists(admin: Admin): Mono<Boolean> = db
.exists(
Query.query(
Criteria
.where(Admin::cid.name)
.`is`(admin.cid)
.and(
Criteria.where(Admin::uid.name).`is`(admin.uid)
)
),
Admin::class.java
)
@Transactional
fun delete(admin: Admin): Mono<Void> = db.delete(admin).then()
}
| 0 | Kotlin | 2 | 0 | 46d547a95452f6f904d5cb0fb7c241c42f581951 | 1,249 | MotiClubs-Service | MIT License |
src/main/kotlin/com/mnnit/moticlubs/repository/AdminRepository.kt | CC-MNNIT | 583,707,830 | false | null | package com.mnnit.moticlubs.repository
import com.mnnit.moticlubs.dao.Admin
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate
import org.springframework.data.relational.core.query.Criteria
import org.springframework.data.relational.core.query.Query
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Transactional
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@Repository
class AdminRepository(
private val db: R2dbcEntityTemplate,
) {
@Transactional
fun save(admin: Admin): Mono<Admin> = exists(admin)
.flatMap { if (it) Mono.just(admin) else db.insert(admin) }
@Transactional
fun findAll(): Flux<Admin> = db.select(Query.empty(), Admin::class.java)
@Transactional
fun exists(admin: Admin): Mono<Boolean> = db
.exists(
Query.query(
Criteria
.where(Admin::cid.name)
.`is`(admin.cid)
.and(
Criteria.where(Admin::uid.name).`is`(admin.uid)
)
),
Admin::class.java
)
@Transactional
fun delete(admin: Admin): Mono<Void> = db.delete(admin).then()
}
| 0 | Kotlin | 2 | 0 | 46d547a95452f6f904d5cb0fb7c241c42f581951 | 1,249 | MotiClubs-Service | MIT License |
app/src/main/java/com/vivek/githubapisample/home/presentation/HomePage.kt | Vivekban | 731,416,734 | false | {"Kotlin": 113934} | package com.vivek.githubapisample.home.presentation
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.slideInVertically
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.text.selection.TextSelectionColors
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.PagingData
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.vivek.githubapisample.R
import com.vivek.githubapisample.common.data.AppResult
import com.vivek.githubapisample.common.presentation.ValueCallback
import com.vivek.githubapisample.common.presentation.component.NoNetwork
import com.vivek.githubapisample.common.presentation.component.TopBar
import com.vivek.githubapisample.common.presentation.toDisplayString
import com.vivek.githubapisample.repo.data.Repo
import com.vivek.githubapisample.repo.presentation.RepoListItem
import com.vivek.githubapisample.theme.GitHubApiSampleTheme
import com.vivek.githubapisample.theme.padding
import com.vivek.githubapisample.user.data.User
import com.vivek.githubapisample.user.presentation.UserInfo
import kotlinx.coroutines.flow.flowOf
import java.util.Locale
/**
* The home page of the app which contains UserNameField, UserInfo and RepoList.
*
* @param onRepoClick A callback that is called when a repo is clicked.
* @param modifier The modifier to apply to the page.
* @param homeViewModel The view model for the page.
*/
@Composable
fun HomePage(
onRepoClick: ValueCallback<Repo>,
modifier: Modifier = Modifier,
homeViewModel: HomeViewModel = hiltViewModel()
) {
val state by homeViewModel.state.collectAsState()
val repos = homeViewModel.reposByUserFlow.collectAsLazyPagingItems()
HomePage(
state = state,
repos = repos,
modifier = modifier,
onUiAction = homeViewModel::handleUiAction,
onRepoClick = onRepoClick
)
}
/**
* The home page of the app which contains UserNameField, UserInfo and RepoList.
*
* This composable without viewModel only final dependencies, helpful in composable preview.
*
* @param state The state of the home page.
* @param repos The list of repositories.
* @param modifier The modifier to apply to the page.
* @param onUiAction The callback for various ui actions.
* @param onRepoClick The callback to call when a repository is clicked.
*/
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun HomePage(
state: HomeUiState,
repos: LazyPagingItems<Repo>,
modifier: Modifier = Modifier,
onUiAction: ValueCallback<HomeUiAction>,
onRepoClick: ValueCallback<Repo>? = null,
) {
// For snack bar display
val hostState = remember { SnackbarHostState() }
// It will move list to last scroll position in case of configuration changes.
val listState = rememberLazyListState()
val keyboardController = LocalSoftwareKeyboardController.current
val focusManager = LocalFocusManager.current
val user = state.user?.getOrNull()
// Show SnackBar on error
val info = state.message?.getContent()?.toDisplayString()
LaunchedEffect(key1 = info) {
info?.let {
hostState.showSnackbar(
message = it
)
}
}
Scaffold(modifier = modifier,
snackbarHost = { SnackbarHost(hostState) },
topBar = { TopBar(title = R.string.take_home, modifier = modifier) }
) { contentPadding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(contentPadding),
) {
AnimatedVisibility(visible = !state.isOnline) {
NoNetwork()
}
Spacer(modifier = Modifier.height(MaterialTheme.padding.medium))
UserNameField(
modifier = Modifier.padding(horizontal = MaterialTheme.padding.medium),
username = state.usernameQuery,
onUsernameChange = {
onUiAction(HomeUiAction.UpdateUsernameSearch(it))
},
onSearchClick = {
keyboardController?.hide()
focusManager.clearFocus()
onUiAction(HomeUiAction.DoSearch(it))
}
)
Spacer(modifier = Modifier.height(MaterialTheme.padding.medium))
AnimatedVisibility(
visible = user != null,
enter = fadeIn() + slideInVertically(
initialOffsetY = { it / 2 },
),
) {
user?.let {
UserInfo(
modifier = Modifier.padding(horizontal = MaterialTheme.padding.medium),
user = user
)
}
}
AnimatedVisibility(
visible = state.user?.isSuccess() == true,
enter = fadeIn() + slideInVertically(
initialOffsetY = { it / 2 },
),
modifier = Modifier.weight(1f)
) {
LazyColumn(
Modifier
.fillMaxSize()
.padding(
vertical = MaterialTheme.padding.small,
horizontal = MaterialTheme.padding.extraSmall
),
state = listState,
) {
item {
Spacer(modifier = Modifier.height(MaterialTheme.padding.small))
}
items(repos.itemCount) { index ->
repos[index]?.let { repo ->
RepoListItem(
modifier = Modifier.padding(MaterialTheme.padding.small),
repo = repo,
onClick = {
// Make sure repo has valid owner information
repo.owner.login?.let {
onRepoClick?.invoke(repo)
}
}
)
}
}
}
}
}
}
}
/**
* A composable function that renders a text field for entering a user ID and a button for searching.
*
* @param username The current user ID.
* @param onUsernameChange A callback that is called when the user ID changes.
* @param onSearchClick A callback that is called when the search button is clicked.
* @param modifier The modifier to apply to the layout.
*/
@Composable
fun UserNameField(
username: String,
onUsernameChange: ValueCallback<String>,
onSearchClick: ValueCallback<String>,
modifier: Modifier = Modifier
) {
Row(modifier, verticalAlignment = Alignment.CenterVertically) {
TextField(
modifier = Modifier.weight(1f),
value = username,
onValueChange = onUsernameChange,
label = { Text(text = stringResource(R.string.placeholder_user_id)) },
colors = TextFieldDefaults.colors(
focusedLabelColor = MaterialTheme.colorScheme.tertiary,
focusedIndicatorColor = MaterialTheme.colorScheme.tertiary,
cursorColor = MaterialTheme.colorScheme.tertiary,
selectionColors = TextSelectionColors(
MaterialTheme.colorScheme.tertiary,
MaterialTheme.colorScheme.tertiary.copy(alpha = 0.4f)
)
)
)
Spacer(modifier = Modifier.width(MaterialTheme.padding.medium))
Button(
enabled = username.isNotEmpty(),
shape = MaterialTheme.shapes.extraSmall,
onClick = {
onSearchClick(username)
}) {
Text(text = stringResource(R.string.search).uppercase(Locale.ROOT))
}
}
}
@Preview(showBackground = true)
@Composable
fun UserNameFieldPreview() {
GitHubApiSampleTheme {
UserNameField("1", onUsernameChange = {}, onSearchClick = {})
}
}
@Preview(showBackground = true)
@Composable
fun HomePagePreview() {
GitHubApiSampleTheme {
HomePage(
state = HomeUiState(user = AppResult.Success(User.fake())),
repos = flowOf(
PagingData.from(listOf(Repo.fake(), Repo.fake()))
).collectAsLazyPagingItems(),
onUiAction = {},
onRepoClick = {},
)
}
}
| 1 | Kotlin | 0 | 2 | d40955e5436b9b9cc68324ce9418c2d277546c5d | 9,988 | GitHubApiSample | The Unlicense |
plugin/src/test/kotlin/com/ryandens/javaagent/JavaagentApplicationPluginTest.kt | ryandens | 365,618,234 | false | null | package com.ryandens.javaagent
import org.gradle.testfixtures.ProjectBuilder
import kotlin.test.Test
import kotlin.test.assertNotNull
/**
* A simple unit test for the 'com.ryandens.javaagent.attach' plugin.
*/
class JavaagentApplicationPluginTest {
@Test fun `plugin registers task`() {
// Create a test project and apply the plugin
val project = ProjectBuilder.builder().build()
project.plugins.apply("application")
project.plugins.apply("com.ryandens.javaagent-application")
// Verify the result
assertNotNull(project.configurations.findByName("javaagent"))
}
}
| 5 | Kotlin | 8 | 9 | 868c321c5e7e338de30e7da3b919107a20b1c243 | 625 | javaagent-gradle-plugin | Apache License 2.0 |
sdk/src/jsMain/kotlin/lib/module/Tiimers.kt | zimoyin | 675,280,596 | false | {"Kotlin": 306501, "JavaScript": 18388, "HTML": 15259} | package lib.module
/**
*
* @author : zimo
* @date : 2024/07/30
*/
//TODO
@Deprecated("use setTimeoutByKotlin")
external fun setTimeout(callback: () -> Unit, delay: Int, vararg args: Any)
/**
* ้ขๅฎๅจ delay ๆฏซ็งไนๅๆง่ก็ๅๆฌก callbackใ ่ฟๅไธไธช็จไบ clearTimeout() ็ idใ
* callback ๅฏ่ฝไธไผ็ฒพ็กฎๅฐๅจ delay ๆฏซ็ง่ขซ่ฐ็จใ Auto.js ไธ่ฝไฟ่ฏๅ่ฐ่ขซ่งฆๅ็็กฎๅๆถ้ด๏ผไนไธ่ฝไฟ่ฏๅฎไปฌ็้กบๅบใ ๅ่ฐไผๅจๅฐฝๅฏ่ฝๆฅ่ฟๆๆๅฎ็ๆถ้ดไธ่ฐ็จใ
* ๅฝ delay ๅฐไบ 0 ๆถ๏ผdelay ไผ่ขซ่ฎพไธบ 0ใ
*/
fun setTimeoutByKotlin(delay: Int, vararg args: Any, callback: () -> Unit) {
setTimeout(callback, delay, *args)
}
fun setTimeoutByKotlin(delay: Int, vararg args: Any) {
setTimeout(fun() {}, delay, *args)
}
@Deprecated("use setIntervalByKotlin")
external fun setInterval(callback: () -> Unit, delay: Int, vararg args: Any)
/**
* ้ขๅฎๆฏ้ delay ๆฏซ็ง้ๅคๆง่ก็ callbackใ ่ฟๅไธไธช็จไบ clearInterval() ็ idใ
*
* ๅฝ delay ๅฐไบ 0 ๆถ๏ผdelay ไผ่ขซ่ฎพไธบ 0ใ
*/
fun setIntervalByKotlin(delay: Int, vararg args: Any, callback: () -> Unit) {
setInterval(callback, delay, *args)
}
@Deprecated("use setImmediateByKotlin")
external fun setImmediate(callback: () -> Unit, vararg args: Any): Int
/**
* ้ขๅฎ็ซๅณๆง่ก็ callback๏ผๅฎๆฏๅจ I/O ไบไปถ็ๅ่ฐไนๅ่ขซ่งฆๅใ ่ฟๅไธไธช็จไบ clearImmediate() ็ idใ
* ๅฝๅคๆฌก่ฐ็จ setImmediate() ๆถ๏ผcallback ๅฝๆฐไผๆ็
งๅฎไปฌ่ขซๅๅปบ็้กบๅบไพๆฌกๆง่กใ ๆฏๆฌกไบไปถๅพช็ฏ่ฟญไปฃ้ฝไผๅค็ๆดไธชๅ่ฐ้ๅใ ๅฆๆไธไธช็ซๅณๅฎๆถๅจๆฏ่ขซไธไธชๆญฃๅจๆง่ก็ๅ่ฐๆๅ
ฅ้ๅ็๏ผๅ่ฏฅๅฎๆถๅจ็ดๅฐไธไธๆฌกไบไปถๅพช็ฏ่ฟญไปฃๆไผ่ขซ่งฆๅใ
* setImmediate()ใsetInterval() ๅ setTimeout() ๆนๆณๆฏๆฌก้ฝไผ่ฟๅ่กจ็คบ้ขๅฎ็่ฎกๆถๅจ็idใ ๅฎไปฌๅฏ็จไบๅๆถๅฎๆถๅจๅนถ้ฒๆญข่งฆๅใ
*/
fun setImmediateByKotlin(vararg args: Any, callback: () -> Unit): Int {
return setImmediate(callback, *args)
}
/**
* ๅๆถไธไธช็ฑ setInterval() ๅๅปบ็ๅพช็ฏๅฎๆถไปปๅกใ
*/
external fun clearInterval(id: Int)
/**
* ๅๆถไธไธช็ฑ setTimeout() ๅๅปบ็ๅฎๆถไปปๅกใ
*/
external fun clearTimeout(id: Int)
/**
* ๅๆถไธไธช็ฑ setImmediate() ๅๅปบ็ Immediate ๅฏน่ฑกใ
*/
external fun clearImmediate(id: Int)
| 0 | Kotlin | 5 | 10 | aa85a176280ce3a17a59454fbbe6bddd56044335 | 1,698 | Autojsx.WIFI | Apache License 2.0 |
common/src/androidMain/kotlin/au/com/auspost/feature/base/Logger.kt | markchristopherng | 248,622,980 | false | null | package au.com.auspost.feature.base
import android.util.Log
actual object Logger {
actual fun logMessage(msg: String) {
Log.d("AndroidApp", msg)
}
} | 0 | Kotlin | 0 | 0 | 60a9115c2551c3c5f010bc0da2764023cbbd7126 | 167 | kmp_example | Apache License 2.0 |
core/common/src/main/kotlin/com/seosh817/moviehub/core/common/network/di/DispatchersModule.kt | seosh817 | 722,390,551 | false | {"Kotlin": 353175} | package com.seosh817.moviehub.core.common.network.di
import com.seosh817.moviehub.core.common.network.Dispatcher
import com.seosh817.moviehub.core.common.network.MovieHubDispatchers
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
@Module
@InstallIn(SingletonComponent::class)
object DispatchersModule {
@Provides
@Dispatcher(MovieHubDispatchers.IO)
fun providesIODispatcher(): CoroutineDispatcher = Dispatchers.IO
@Provides
@Dispatcher(MovieHubDispatchers.DEFAULT)
fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default
}
| 12 | Kotlin | 0 | 3 | 774dd544024d1605ec5ac5b99c50fb686f6d7027 | 728 | MovieHub | Apache License 2.0 |
state-space/src/main/kotlin/org/futurerobotics/jargon/statespace/NoiseCovarianceProvider.kt | Future14473 | 199,776,352 | false | null | package org.futurerobotics.jargon.statespace
import org.futurerobotics.jargon.linalg.*
/**
* Provides [NoiseCovariance] for a [LinearKalmanFilter].
*/
interface NoiseCovarianceProvider {
/**
* Gets the current [NoiseCovariance] matrices for processing and measurement given
* [matrices], predicted state [x], past signal [u], measurement [y], and current time [timeInNanos].
*/
fun getNoiseCovariance(
matrices: DiscreteStateSpaceMatrices,
x: Vec,
u: Vec,
y: Vec,
timeInNanos: Long
): NoiseCovariance
}
/**
* A [NoiseCovarianceProvider] that always returns the given [noiseCovariance].
*/
class ConstantNoiseCovariance(private val noiseCovariance: NoiseCovariance) : NoiseCovarianceProvider {
override fun getNoiseCovariance(
matrices: DiscreteStateSpaceMatrices,
x: Vec,
u: Vec,
y: Vec,
timeInNanos: Long
): NoiseCovariance = noiseCovariance
}
| 9 | Kotlin | 0 | 1 | 2cb837a402fb3fe2ce634e07cff9bed426447125 | 969 | JARGON | MIT License |
domain/src/main/java/com/raghav/spacedawnv2/domain/model/Reminder.kt | avidraghav | 647,145,986 | false | null | package com.raghav.spacedawnv2.domain.model
import androidx.annotation.Keep
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* this entity represents a Launch object which is showed on the UI
* and saved in the Database.
*/
@Keep
@Entity(tableName = "saved_launches")
data class LaunchDetail(
val agencyLaunchAttemptCount: Int?,
val agencyLaunchAttemptCountYear: Int?,
val failreason: String?,
val holdreason: String?,
@PrimaryKey(autoGenerate = false)
val id: String,
val image: String?,
val infographic: String?,
val lastUpdated: String?,
val launchServiceProvider: LaunchServiceProvider?,
val locationLaunchAttemptCount: Int?,
val locationLaunchAttemptCountYear: Int?,
val mission: Mission?,
val name: String?,
val net: String,
val netPrecision: NetPrecision?,
val orbitalLaunchAttemptCount: Int?,
val orbitalLaunchAttemptCountYear: Int?,
val pad: Pad?,
val padLaunchAttemptCount: Int?,
val padLaunchAttemptCountYear: Int?,
val probability: String?,
val rocket: Rocket?,
val slug: String?,
val status: Status?,
val url: String?,
val webcastLive: Boolean?,
val windowEnd: String?,
val windowStart: String?
)
| 3 | null | 8 | 98 | 6c1d838203fc67a80a92ca760a0ef582f8013f45 | 1,246 | SpaceDawn | Apache License 2.0 |
app/src/main/java/com/example/qpuc/StateMachine.kt | PierreLeBlond | 842,879,957 | false | {"Kotlin": 39813} | package com.example.qpuc
import com.tinder.StateMachine
sealed class State {
data object Wait : State()
data object Top : State()
data object Buzz : State()
data object OtherBuzz : State()
data object Out : State()
}
sealed class Event {
data object OnTop: Event()
data object OnBuzz : Event()
data object OnOtherBuzz : Event()
}
sealed class SideEffect {
}
class HostStateMachine {
fun createStateMachine(): StateMachine<State, Event, SideEffect> {
val stateMachine = StateMachine.create<State, Event, SideEffect> {
initialState(State.Wait)
state<State.Wait> {
on<Event.OnTop> {
transitionTo(State.Top)
}
}
state<State.Top> {
on<Event.OnBuzz> {
transitionTo(State.Buzz)
}
on<Event.OnOtherBuzz> {
transitionTo(State.OtherBuzz)
}
}
state<State.OtherBuzz> {
on<Event.OnTop> {
transitionTo(State.Top)
}
}
state<State.Buzz> {
on<Event.OnTop> {
transitionTo(State.Out)
}
}
state<State.Out> {
on<Event.OnOtherBuzz> {
transitionTo(State.OtherBuzz)
}
}
}
return stateMachine;
}
} | 0 | Kotlin | 0 | 0 | d92204a4fd31a577a2ce81ede45172933b1d548a | 1,487 | qpuc | MIT License |
mulighetsrommet-api/src/main/kotlin/no/nav/mulighetsrommet/api/domain/dto/VirksomhetDto.kt | navikt | 435,813,834 | false | {"Kotlin": 1192202, "TypeScript": 993440, "SCSS": 39443, "JavaScript": 24814, "PLpgSQL": 10327, "HTML": 1504, "Dockerfile": 683, "CSS": 437, "Shell": 95} | package no.nav.mulighetsrommet.api.domain.dto
import kotlinx.serialization.Serializable
@Serializable
data class VirksomhetDto(
val organisasjonsnummer: String,
val navn: String,
val overordnetEnhet: String? = null,
val underenheter: List<VirksomhetDto>? = null,
val postnummer: String? = null,
val poststed: String? = null,
val slettedato: String? = null,
)
| 4 | Kotlin | 1 | 6 | f46a03dff0bd99d89a0e16c298fa8d62cbf5e5f8 | 389 | mulighetsrommet | MIT License |
kt/godot-library/src/main/kotlin/godot/gen/godot/PhysicalBone2D.kt | utopia-rise | 289,462,532 | false | null | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.NodePath
import godot.core.TypeManager
import godot.core.VariantType.BOOL
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.VariantType.NODE_PATH
import godot.core.VariantType.OBJECT
import godot.core.memory.TransferContext
import godot.util.VoidPtr
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.Suppress
/**
* A [godot.RigidBody2D]-derived node used to make [godot.Bone2D]s in a [godot.Skeleton2D] react to physics.
*
* The [godot.PhysicalBone2D] node is a [godot.RigidBody2D]-based node that can be used to make [godot.Bone2D]s in a [godot.Skeleton2D] react to physics.
*
* **Note:** To make the [godot.Bone2D]s visually follow the [godot.PhysicalBone2D] node, use a [godot.SkeletonModification2DPhysicalBones] modification on the [godot.Skeleton2D] parent.
*
* **Note:** The [godot.PhysicalBone2D] node does not automatically create a [godot.Joint2D] node to keep [godot.PhysicalBone2D] nodes together. They must be created manually. For most cases, you want to use a [godot.PinJoint2D] node. The [godot.PhysicalBone2D] node will automatically configure the [godot.Joint2D] node once it's been added as a child node.
*/
@GodotBaseType
public open class PhysicalBone2D : RigidBody2D() {
/**
* The [godot.core.NodePath] to the [godot.Bone2D] that this [godot.PhysicalBone2D] should simulate.
*/
public var bone2dNodepath: NodePath
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getBone2dNodepathPtr, NODE_PATH)
return (TransferContext.readReturnValue(NODE_PATH, false) as NodePath)
}
set(`value`) {
TransferContext.writeArguments(NODE_PATH to value)
TransferContext.callMethod(rawPtr, MethodBindings.setBone2dNodepathPtr, NIL)
}
/**
* The index of the [godot.Bone2D] that this [godot.PhysicalBone2D] should simulate.
*/
public var bone2dIndex: Int
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getBone2dIndexPtr, LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
set(`value`) {
TransferContext.writeArguments(LONG to value.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.setBone2dIndexPtr, NIL)
}
/**
* If `true`, the [godot.PhysicalBone2D] will automatically configure the first [godot.Joint2D] child node. The automatic configuration is limited to setting up the node properties and positioning the [godot.Joint2D].
*/
public var autoConfigureJoint: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getAutoConfigureJointPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, MethodBindings.setAutoConfigureJointPtr, NIL)
}
/**
* If `true`, the [godot.PhysicalBone2D] will start simulating using physics. If `false`, the [godot.PhysicalBone2D] will follow the transform of the [godot.Bone2D] node.
*
* **Note:** To have the [godot.Bone2D]s visually follow the [godot.PhysicalBone2D], use a [godot.SkeletonModification2DPhysicalBones] modification on the [godot.Skeleton2D] node with the [godot.Bone2D] nodes.
*/
public var simulatePhysics: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getSimulatePhysicsPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, MethodBindings.setSimulatePhysicsPtr, NIL)
}
/**
* If `true`, the [godot.PhysicalBone2D] will keep the transform of the bone it is bound to when simulating physics.
*/
public var followBoneWhenSimulating: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getFollowBoneWhenSimulatingPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, MethodBindings.setFollowBoneWhenSimulatingPtr, NIL)
}
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_PHYSICALBONE2D, scriptIndex)
return true
}
/**
* Returns the first [godot.Joint2D] child node, if one exists. This is mainly a helper function to make it easier to get the [godot.Joint2D] that the [godot.PhysicalBone2D] is autoconfiguring.
*/
public fun getJoint(): Joint2D? {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getJointPtr, OBJECT)
return (TransferContext.readReturnValue(OBJECT, true) as Joint2D?)
}
/**
* Returns a boolean that indicates whether the [godot.PhysicalBone2D] is running and simulating using the Godot 2D physics engine. When `true`, the PhysicalBone2D node is using physics.
*/
public fun isSimulatingPhysics(): Boolean {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isSimulatingPhysicsPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
public companion object
internal object MethodBindings {
public val getJointPtr: VoidPtr = TypeManager.getMethodBindPtr("PhysicalBone2D", "get_joint")
public val getAutoConfigureJointPtr: VoidPtr =
TypeManager.getMethodBindPtr("PhysicalBone2D", "get_auto_configure_joint")
public val setAutoConfigureJointPtr: VoidPtr =
TypeManager.getMethodBindPtr("PhysicalBone2D", "set_auto_configure_joint")
public val setSimulatePhysicsPtr: VoidPtr =
TypeManager.getMethodBindPtr("PhysicalBone2D", "set_simulate_physics")
public val getSimulatePhysicsPtr: VoidPtr =
TypeManager.getMethodBindPtr("PhysicalBone2D", "get_simulate_physics")
public val isSimulatingPhysicsPtr: VoidPtr =
TypeManager.getMethodBindPtr("PhysicalBone2D", "is_simulating_physics")
public val setBone2dNodepathPtr: VoidPtr =
TypeManager.getMethodBindPtr("PhysicalBone2D", "set_bone2d_nodepath")
public val getBone2dNodepathPtr: VoidPtr =
TypeManager.getMethodBindPtr("PhysicalBone2D", "get_bone2d_nodepath")
public val setBone2dIndexPtr: VoidPtr =
TypeManager.getMethodBindPtr("PhysicalBone2D", "set_bone2d_index")
public val getBone2dIndexPtr: VoidPtr =
TypeManager.getMethodBindPtr("PhysicalBone2D", "get_bone2d_index")
public val setFollowBoneWhenSimulatingPtr: VoidPtr =
TypeManager.getMethodBindPtr("PhysicalBone2D", "set_follow_bone_when_simulating")
public val getFollowBoneWhenSimulatingPtr: VoidPtr =
TypeManager.getMethodBindPtr("PhysicalBone2D", "get_follow_bone_when_simulating")
}
}
| 63 | null | 39 | 571 | 39dc30230a30d2a6ab4ec3277eb3bc270995ab23 | 7,450 | godot-kotlin-jvm | MIT License |
shoring/compat/src/main/java/com/panopset/compat/Logop.kt | panopset | 735,643,703 | false | {"Kotlin": 591951, "Java": 45005, "Shell": 10059, "CSS": 4623, "JavaScript": 4084, "Batchfile": 3046, "HTML": 1005} | package com.panopset.compat
import com.panopset.compat.Stringop.getEol
import java.io.File
import java.io.IOException
import java.io.PrintWriter
import java.io.StringWriter
import java.util.*
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.logging.Level
import java.util.logging.Logger
object Logop {
val logger = Logger.getGlobal()
val lozLiseners = ArrayList<LogListener>()
var isDebugging = false
val clearLogEntry = LogEntry(LogopAlert.GREEN, Level.INFO, "")
const val PAN_STANDARD_LOGIC_ERROR_MSG =
"Unexpected error, if your pull request is accepted, we'll send you 1000 currently worthless Panopset shares."
/**
* Keeping this around, because of the System/38 & AS/400 DSPMSG CLP command. Identical to
* info(msg).
*
* @param msg Message to log at Level.INFO.
*/
@JvmStatic
fun dspmsg(msg: String?) {
info(msg)
}
@JvmStatic
fun info(msg: String?) {
report(
LogEntry(
LogopAlert.GREEN, Level.INFO,
audit(msg)!!
)
)
}
@JvmStatic
fun warn(msg: String?) {
report(
LogEntry(
LogopAlert.YELLOW, Level.WARNING,
audit(msg)!!
)
)
}
@JvmStatic
fun debug(msg: String?) {
report(
LogEntry(
LogopAlert.ORANGE, Level.FINE,
audit(msg)!!
)
)
}
@JvmStatic
fun errorMsg(msg: String?) {
report(
LogEntry(
LogopAlert.RED, Level.SEVERE,
audit(msg)!!
)
)
}
@JvmStatic
private fun audit(msg: String?): String? {
return msg
}
@JvmStatic
fun warn(ex: Exception) {
warn(ex.message)
}
@JvmStatic
fun errorEx(ex: Exception?) {
handleException(ex!!)
}
@JvmStatic
fun errorMsg(msg: String?, ex: Throwable?) {
errorMsg(msg)
handleException(ex!!)
}
@JvmStatic
fun green(msg: String?) {
dspmsg(msg)
}
@JvmStatic
fun handle(e: Exception?) {
handleException(e!!)
}
@JvmStatic
fun errorMsg(message: String?, file: File?) {
if (file == null) {
errorMsg("Null file.")
return
}
errorMsg("$message: ${Fileop.getCanonicalPath(file)}")
}
@JvmStatic
@Throws(IOException::class)
fun getStackTrace(throwable: Throwable): String {
StringWriter().use { sw ->
PrintWriter(sw).use { pw ->
throwable.printStackTrace(pw)
pw.flush()
return sw.toString()
}
}
}
@JvmStatic
fun errorMsg(file: File, ex: Exception) {
info(Fileop.getCanonicalPath(file))
errorEx(ex)
}
@JvmStatic
fun handleException(ex: Throwable) {
logger.log(Level.SEVERE, ex.message, ex)
ex.printStackTrace()
val logEntry = LogEntry(
LogopAlert.RED, Level.SEVERE,
ex.message!!
)
for (listener in lozLiseners) {
listener.log(logEntry)
}
logalog(logEntry)
}
@JvmStatic
fun report(logRecord: LogEntry) {
logger.log(logRecord.level, logRecord.message)
for (listener in lozLiseners) {
listener.log(logRecord)
}
logalog(logRecord)
}
// public static String logAndReturnError(String msg) {
// Logop.errorMsg(msg);
// return msg;
// }
// public static String logAndReturnExceptionError(Exception ex) {
// String rtn = ex.getMessage();
// if (!Stringop.isPopulated(ex.getMessage())) {
// rtn = PAN_STANDARD_LOGIC_ERROR_MSG;
// }
// errorMsg(rtn);
// return rtn;
// }
// public static String logAndReturnError(String msg) {
@JvmStatic
fun getEntryStackAsText(): String {
return printHistory()
}
@JvmStatic
fun clear() {
stack.clear()
turnOffDebugging()
clearListeners()
}
private fun clearListeners() {
for (listener in lozLiseners) {
listener.log(clearLogEntry)
}
}
@JvmStatic
fun turnOnDebugging() {
isDebugging = true
}
@JvmStatic
fun turnOffDebugging() {
isDebugging = false
}
@JvmStatic
fun standardWierdErrorMessage() {
errorMsg(PAN_STANDARD_LOGIC_ERROR_MSG)
}
@JvmStatic
val stack: Deque<LogEntry> = ConcurrentLinkedDeque()
@JvmStatic
fun printHistory(): String {
val sw = StringWriter()
for (lr in stack) {
sw.append(timestampFormat.format(lr.timestamp))
sw.append(lr.message)
sw.append("\n")
}
return sw.toString()
}
@JvmStatic
fun logalog(logEntry: LogEntry) {
if (stack.size > 999) {
for (i in 0..99) {
stack.removeFirst()
}
}
stack.add(logEntry)
}
@JvmStatic
fun addLogListener(logListener: LogListener) {
lozLiseners.add(logListener)
}
fun getStackTraceAndCauses(throwable: Throwable): String {
val sw = StringWriter()
sw.append("See log")
sw.append(": ")
sw.append(throwable.message)
sw.append(getEol())
sw.append("*************************")
sw.append(getEol())
sw.append(getStackTrace(throwable))
sw.append(getEol())
var cause = throwable.cause
while (cause != null) {
sw.append("*************************")
sw.append(getEol())
sw.append(getStackTrace(cause))
sw.append(getEol())
cause = cause.cause
}
return sw.toString()
}
}
| 0 | Kotlin | 0 | 0 | 3db4947b509e036cbbdbae06f06c36abd620b1ca | 5,885 | pan | MIT License |
app/src/main/java/br/com/instagram/common/extension/ActivityExtension.kt | flavio-junior | 435,157,808 | false | {"Kotlin": 140166} | package br.com.instagram.common.extension
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.Activity
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
fun Activity.hideKeyboard() {
val imm: InputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
var view: View? = currentFocus
if (view == null) {
view = View(this)
}
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
fun Activity.animationEnd(callback: () -> Unit) : AnimatorListenerAdapter {
return object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
callback.invoke()
}
}
}
fun AppCompatActivity.replaceFragment(@IdRes id: Int, fragment: Fragment) {
if (supportFragmentManager.findFragmentById(id) == null) {
supportFragmentManager.beginTransaction().apply {
add(id, fragment, fragment.javaClass.simpleName)
commit()
}
} else {
supportFragmentManager.beginTransaction().apply {
replace(id, fragment, fragment.javaClass.simpleName)
addToBackStack(null)
commit()
}
}
hideKeyboard()
} | 0 | Kotlin | 0 | 0 | 12ca5fa3d6814562bdf5f5d86c1e8c34b02485dc | 1,383 | InstagramRemake1.0 | MIT License |
src/main/kotlin/no/anksoft/pginmem/statements/select/SelectRowProvider.kt | anders88 | 316,929,720 | false | null | package no.anksoft.pginmem.statements.select
import no.anksoft.pginmem.*
import no.anksoft.pginmem.clauses.WhereClause
import no.anksoft.pginmem.statements.OrderPart
import no.anksoft.pginmem.values.NullCellValue
import java.sql.SQLException
import java.util.*
interface SelectRowProvider {
fun size():Int
fun readRow(rowno: Int):Row
val limit:Int?
val offset:Int
val orderParts: List<OrderPart>
fun providerWithFixed(row:Row?):SelectRowProvider
}
private class TableJoinRow(val rowids:Map<String,String>,val cells:List<Cell>) {
override fun equals(other: Any?): Boolean {
if (other !is TableJoinRow) {
return false
}
return ((cells == other.cells) && (rowids == other.rowids))
}
override fun hashCode(): Int = 1
}
class LeftOuterJoin(val leftTable:Table, val rightTable:Table, val leftcol:Column, val rightcol:Column)
private interface RowForSelect {
fun reset()
fun next():Row?
fun isEmpty():Boolean
}
private class SimpleRowForSelect(tableInSelect:TableInSelect):RowForSelect {
private val myrows = tableInSelect.rowsFromSelect()
private var index = -1
override fun reset() {
index = -1
}
override fun next(): Row? {
index++
return if (index < myrows.size) myrows[index] else null
}
override fun isEmpty(): Boolean = myrows.isEmpty()
}
private class LeftOuterJoinRowForSelect(private val leftOuterJoin: LeftOuterJoin):RowForSelect {
private val leftSelect:RowForSelect = SimpleRowForSelect(leftOuterJoin.leftTable)
private val rigtSelect:RowForSelect = SimpleRowForSelect(leftOuterJoin.rightTable)
private var currentLeftRow:Row? = null
private var hasDeliveredFromCurrentLeft:Boolean = false
override fun reset() {
leftSelect.reset()
rigtSelect.reset()
currentLeftRow = null
hasDeliveredFromCurrentLeft = false
}
override fun next(): Row? {
if (currentLeftRow == null) {
currentLeftRow = leftSelect.next()?:return null
}
while (true) {
val rightRow:Row? = rigtSelect.next()
if (rightRow == null) {
if (hasDeliveredFromCurrentLeft) {
currentLeftRow = leftSelect.next()?:return null
rigtSelect.reset()
hasDeliveredFromCurrentLeft = false
continue
}
val resCells:MutableList<Cell> = mutableListOf()
resCells.addAll(currentLeftRow!!.cells)
for (column in leftOuterJoin.rightTable.colums) {
resCells.add(Cell(column,NullCellValue))
}
val rowIds:MutableMap<String,String> = mutableMapOf()
rowIds.putAll(currentLeftRow!!.rowids)
rowIds.put(leftOuterJoin.rightTable.name,UUID.randomUUID().toString())
currentLeftRow = null
return Row(resCells,rowIds)
}
val leftValue = currentLeftRow!!.cells.first { it.column.matches(leftOuterJoin.leftcol.tablename,leftOuterJoin.leftcol.name) }.value
val rightValue = rightRow.cells.first { it.column.matches(leftOuterJoin.rightcol.tablename,leftOuterJoin.rightcol.name) }.value
if (leftValue != rightValue) {
continue
}
hasDeliveredFromCurrentLeft = true
val resRow = Row(currentLeftRow!!.cells + rightRow.cells,currentLeftRow!!.rowids + rightRow.rowids)
return resRow
}
}
override fun isEmpty(): Boolean = leftSelect.isEmpty()
}
class TablesSelectRowProvider constructor(
private val dbTransaction: DbTransaction,
private val tablesPicked: List<TableInSelect>,
private val whereClause: WhereClause,
override val orderParts: List<OrderPart>,
override val limit:Int?,
override val offset: Int,
private val injectCells:List<Cell> = emptyList(),
private val leftOuterJoins:List<LeftOuterJoin> = emptyList()
):SelectRowProvider {
private val values:List<TableJoinRow> by lazy {
val tablesToParse:List<RowForSelect> = tablesPicked.map { t ->
val leftJoin:LeftOuterJoin? = leftOuterJoins.firstOrNull { it.leftTable.name == t.name }
val rightJoin:LeftOuterJoin? = leftOuterJoins.firstOrNull { it.rightTable.name == t.name }
when {
leftJoin != null -> LeftOuterJoinRowForSelect(leftJoin)
rightJoin != null -> null
else -> SimpleRowForSelect(t)
}
}.filterNotNull()
if (tablesToParse.isEmpty() || tablesToParse.any { it.isEmpty() }) {
emptyList()
} else {
val currentRowPicks:MutableList<Row?> = mutableListOf()
for (i in 0 until tablesToParse.size-1) {
currentRowPicks.add(tablesToParse[i].next())
}
currentRowPicks.add(null)
val resultRows:MutableList<TableJoinRow> = mutableListOf()
while (true) {
var didInc = false
var pos = tablesToParse.size-1
while (pos >= 0) {
val r:Row? = tablesToParse[pos].next()
currentRowPicks[pos] = r
if (r != null) {
didInc = true
break
}
pos--
}
if (!didInc) {
break
}
for (resetpos in pos+1 until tablesToParse.size) {
tablesToParse[resetpos].reset()
val next = tablesToParse[resetpos].next()
currentRowPicks[resetpos] = next
}
val cellsThisRow: MutableList<Cell> = mutableListOf()
val rowidsThisRow:MutableMap<String,String> = mutableMapOf()
for (row in currentRowPicks) {
cellsThisRow.addAll(row!!.cells)
rowidsThisRow.putAll(row.rowids)
}
cellsThisRow.addAll(injectCells)
if (whereClause.isMatch(cellsThisRow)) {
resultRows.add(TableJoinRow(rowidsThisRow,cellsThisRow))
}
}
/*
if (orderParts.isNotEmpty()) {x
resultRows.sortWith { a, b -> compareRows(a.cells,b.cells) }
}*/
resultRows
}
}
private fun compareRows(a:List<Cell>,b:List<Cell>):Int {
for (orderPart in orderParts) {
val aVal = a.first { it.column == orderPart.column }.value
val bVal = b.first { it.column == orderPart.column}.value
if (aVal == bVal) {
continue
}
return if (orderPart.ascending) aVal.compareMeTo(bVal) else bVal.compareMeTo(aVal)
}
return 0
}
override fun size(): Int = values.size
override fun readRow(rowno: Int): Row {
val myRow:TableJoinRow = values[rowno]
return Row(myRow.cells,myRow.rowids)
}
override fun providerWithFixed(row: Row?): SelectRowProvider {
if (row == null) {
return this
}
return TablesSelectRowProvider(
this.dbTransaction,
this.tablesPicked,
this.whereClause,
this.orderParts,
this.limit,
this.offset,
row.cells,
this.leftOuterJoins
)
}
}
class ImplicitOneRowSelectProvider(val whereClause: WhereClause,val injectedRow:Row?=null):SelectRowProvider {
private val rowExsists:Boolean by lazy {
whereClause.isMatch(injectedRow?.cells?: emptyList())
}
override fun size(): Int = if (rowExsists) 1 else 0
override fun readRow(rowno: Int): Row {
if (!rowExsists) {
throw SQLException("No row found")
}
return injectedRow?:Row(emptyList())
}
override val limit: Int? = null
override val offset: Int = 0
override val orderParts: List<OrderPart> = emptyList()
override fun providerWithFixed(row: Row?): SelectRowProvider = ImplicitOneRowSelectProvider(whereClause,row)
}
| 0 | Kotlin | 0 | 0 | 7f2a8be40e999b890999b4d9c0619028eb650f2d | 8,278 | pginmem | Apache License 2.0 |
src/opennlp-conll/main/opennlp/ext/conll/treebank/features/verbal/Voice.kt | rhdunn | 418,266,921 | false | null | // Copyright (C) 2021 Reece H. Dunn. SPDX-License-Identifier: Apache-2.0
package opennlp.ext.conll.treebank.features.verbal
import opennlp.ext.conll.treebank.Feature
import opennlp.ext.conll.treebank.FeatureSet
import opennlp.ext.conll.treebank.features.UnknownFeatureValue
// Reference: [Voice](https://universaldependencies.org/u/feat/Voice.html)
enum class Voice : Feature {
Act, Antip, Bfoc, Cau, Dir, Inv, Lfoc, Mid, Pass, Rcp;
override val type: String = "Voice"
override val value: String = name
override fun toString(): String = "$type=$value"
companion object : FeatureSet {
override val type: String = "Voice"
override fun create(value: String): Feature {
return values().find { it.value == value } ?: UnknownFeatureValue(type, value)
}
}
}
| 0 | Kotlin | 0 | 3 | 3b0f35236af1773bf28a5ccec8c2e8bf7a3de9b2 | 817 | opennlp-extensions | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.