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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
web/src/main/kotlin/com/cs346/web/board/Board.kt
|
wendyxz
| 652,021,298
| false
| null |
package com.cs346.web.board
import org.springframework.data.annotation.PersistenceConstructor
import org.springframework.data.annotation.PersistenceCreator
import java.io.Serializable
import java.util.UUID
data class Board @PersistenceCreator constructor(
val id: String?,
var name: String?,
var json: String?
) : Serializable
| 0
|
Kotlin
|
0
| 0
|
9702deb3565d938ce8ec3059509b6ce29b3c4591
| 343
|
SketchMate
|
MIT License
|
src/main/kotlin/example/examplemod/mineui/wrapper/PoseStack.kt
|
fuma-nama
| 537,793,028
| false
|
{"Kotlin": 99524}
|
package example.examplemod.mineui.wrapper
import com.mojang.blaze3d.vertex.PoseStack
import example.examplemod.mineui.style.Point4
import net.minecraft.client.gui.Gui
fun PoseStack.drawBorder(x: Int, y: Int, width: Int, height: Int, color: Int, thickness: Point4) {
val right = (x + width).coerceAtLeast(x)
val bottom = (y + height).coerceAtLeast(y)
fun line(
x: Int, y: Int,
width: Int, height: Int
) {
Gui.fill(this, x, y, x + width, y + height, color)
}
line(x + thickness.left, y, width - thickness.px, thickness.top)
line(right - thickness.right, y, thickness.right, height)
line(x + thickness.left, bottom - thickness.bottom, width - thickness.px, thickness.bottom)
line(x, y, thickness.left, height)
}
| 0
|
Kotlin
|
0
| 1
|
28c0b2fadbda25cf7d042b42ed6a4883e2392e35
| 772
|
mine-ui
|
MIT License
|
app/src/test/java/com/mkado/techtest/lotterytest/ui/view/LotteryListViewModelShould.kt
|
anuloo
| 829,710,533
| false
|
{"Kotlin": 76225}
|
package com.mkado.techtest.lotterytest.ui.view
import com.mkado.techtest.lotterytest.domain.model.Lottery
import com.mkado.techtest.lotterytest.domain.uscase.LotteryUsecase
import com.mkado.techtest.lotterytest.common.DataResult
import com.mkado.techtest.lotterytest.ui.view.viewmodel.LotteryListViewModel
import io.mockk.*
import junit.framework.TestCase.assertEquals
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.*
import org.junit.*
class LotteryListViewModelShould {
private lateinit var sut: LotteryListViewModel
private val mockGetLotteryDataUseCase: LotteryUsecase = mockk()
private val testDispatcher = StandardTestDispatcher()
private val testScope = TestScope(testDispatcher)
private val lotteryList = listOf(
Lottery(
id = "draw-88",
drawDate = "2024-05-15",
number1 = "10",
number2 = "23",
number3 = "36",
number4 = "47",
number5 = "21",
number6 = "52",
bonusBall = "39",
topPrize = 7000000
)
)
private val error = DataResult.Error("error",-1, null)
@OptIn(ExperimentalCoroutinesApi::class)
@Before
fun setup() {
Dispatchers.setMain(testDispatcher)
MockKAnnotations.init(this, relaxUnitFun = true)
}
@OptIn(ExperimentalCoroutinesApi::class)
@After
fun teardown() {
Dispatchers.resetMain()
unmockkAll()
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun emitLoadingState_and_then_loadedState_when_fetchLotteryData_succeeds() = testScope.runTest {
// Given
coEvery { mockGetLotteryDataUseCase.invoke() } returns flowOf(lotteryList)
sut = LotteryListViewModel(mockGetLotteryDataUseCase)
// Collect states to verify transitions
val states = mutableListOf<LotteryUIState>()
val job = launch {
sut.state.collect { state ->
states.add(state)
}
}
// When
advanceUntilIdle() // Simulates the delay and coroutine processing
// Then
// Ensure that the Loading state is emitted first
assert(states.contains(LotteryUIState.Loading)) {
"Expected Loading state to be emitted"
}
assertEquals(LotteryUIState.Loading, states.firstOrNull { it is LotteryUIState.Loading })
// Ensure that the Loaded state is eventually emitted
assert(states.contains(LotteryUIState.Loaded(lotteryList))) {
"Expected Loaded state with lottery data to be emitted"
}
job.cancel() // Clean up
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun emitLoadingState_and_then_loadedState_when_refreshData_succeeds() = testScope.runTest {
// Given
coEvery { mockGetLotteryDataUseCase.refresh() } returns DataResult.Success(lotteryList)
every { mockGetLotteryDataUseCase.invoke() } returns flowOf(lotteryList)
sut = LotteryListViewModel(mockGetLotteryDataUseCase)
// Collect states to verify transitions
val states = mutableListOf<LotteryUIState>()
val job = launch {
sut.state.toList(states)
}
// When
sut.refreshData()
advanceUntilIdle()
// Then
assertEquals(LotteryUIState.Loading, states[0])
assertEquals(LotteryUIState.Loaded(lotteryList), states[1])
job.cancel()
}
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun emitErrorState_when_refreshData_fails() = testScope.runTest {
// Given
coEvery { mockGetLotteryDataUseCase.refresh() } returns error
every { mockGetLotteryDataUseCase.invoke() } returns flowOf(lotteryList)
sut = LotteryListViewModel(mockGetLotteryDataUseCase)
// Collect states to verify transitions
val states = mutableListOf<LotteryUIState>()
val job = launch {
sut.state.toList(states)
}
// When
sut.refreshData()
advanceUntilIdle()
// Then
assertEquals(LotteryUIState.Loading, states[0])
assertEquals(LotteryUIState.Error("Refresh failed"), states[1])
job.cancel()
}
}
| 0
|
Kotlin
|
1
| 0
|
7c55dc01ca40326e335b1433d99ff13f841ba4ce
| 4,381
|
lotteryTest
|
MIT License
|
src/main/kotlin/dev/d1s/website/block/root/WhatAmIDoingBlock.kt
|
d1snin
| 691,812,284
| false
|
{"Kotlin": 31849, "Shell": 142, "Dockerfile": 103}
|
/*
* Copyright 2023 Mikhail Titov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.d1s.website.block.root
import dev.d1s.beam.client.ContentEntitiesBuilder
import dev.d1s.beam.client.app.state.BlockContext
import dev.d1s.beam.client.buttonLink
import dev.d1s.beam.client.text
import dev.d1s.beam.commons.BlockSize
import dev.d1s.beam.commons.asTemplate
import dev.d1s.website.translation.WebsiteTranslation
suspend fun BlockContext.whatAmIDoing() {
setSize {
BlockSize.MEDIUM
}
setEntities {
heading()
text()
businessLink()
}
}
private fun ContentEntitiesBuilder.heading() {
text(value = WebsiteTranslation.LOCATION_ROOT_WHAT_AM_I_DOING_HEADING.asTemplate, heading = "h2")
}
private fun ContentEntitiesBuilder.text() {
text(value = WebsiteTranslation.LOCATION_ROOT_WHAT_AM_I_DOING_FIRST_PARAGRAPH.asTemplate)
text(value = WebsiteTranslation.LOCATION_ROOT_WHAT_AM_I_DOING_SECOND_PARAGRAPH.asTemplate)
}
private fun ContentEntitiesBuilder.businessLink() {
buttonLink(
text = WebsiteTranslation.LOCATION_ROOT_WHAT_AM_I_DOING_BUSINESS_WEBSITE_TEXT.asTemplate,
url = WebsiteTranslation.LOCATION_ROOT_WHAT_AM_I_DOING_BUSINESS_WEBSITE_URL.asTemplate,
width = 100
)
}
| 0
|
Kotlin
|
0
| 0
|
966697183d022e342dce92475249cb9aa3f62dea
| 1,784
|
website
|
Apache License 2.0
|
app/src/main/java/com/example/assignment/utils/GoogleSignInClient.kt
|
098suraj
| 564,456,919
| false
|
{"Kotlin": 74526}
|
package com.example.assignment.utils
import android.content.Context
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
fun getGoogleSignInClient(context: Context): GoogleSignInClient {
val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
// Request id token if you intend to verify google user from your backend server
.requestIdToken("744383768737-6pbkqmncnnokkefed3dj85ul13g79kha.apps.googleusercontent.com")
.requestEmail()
.build()
return GoogleSignIn.getClient(context, signInOptions)
}
| 0
|
Kotlin
|
0
| 0
|
d2cbe0d43a66efbfc7dbc22dc8e04465e22bcd53
| 706
|
Assignment
|
Apache License 2.0
|
app/src/main/java/com/example/assignment/utils/GoogleSignInClient.kt
|
098suraj
| 564,456,919
| false
|
{"Kotlin": 74526}
|
package com.example.assignment.utils
import android.content.Context
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
fun getGoogleSignInClient(context: Context): GoogleSignInClient {
val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
// Request id token if you intend to verify google user from your backend server
.requestIdToken("744383768737-6pbkqmncnnokkefed3dj85ul13g79kha.apps.googleusercontent.com")
.requestEmail()
.build()
return GoogleSignIn.getClient(context, signInOptions)
}
| 0
|
Kotlin
|
0
| 0
|
d2cbe0d43a66efbfc7dbc22dc8e04465e22bcd53
| 706
|
Assignment
|
Apache License 2.0
|
app/src/main/java/com/example/daniel/cryptocurrencyconverter/common/dagger/ActivityScope.kt
|
danielmaman
| 126,005,852
| false
| null |
package com.example.daniel.cryptocurrencyconverter.common.dagger
import javax.inject.Scope
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityScope
| 0
|
Kotlin
|
0
| 0
|
20226db273edfb35f15b42f94e017d48fa960dc3
| 170
|
CryptoCurrencyConverter
|
MIT License
|
app/src/main/java/ru/alexmaryin/spacextimes_rx/data/api/remote/SpaceXApiImpl.kt
|
alexmaryin
| 324,776,487
| false
| null |
package ru.alexmaryin.spacextimes_rx.data.api.remote
import retrofit2.Response
import ru.alexmaryin.spacextimes_rx.data.model.*
import ru.alexmaryin.spacextimes_rx.data.model.api.*
import javax.inject.Inject
class SpaceXApiImpl @Inject constructor(private val apiRemote: ApiRemote) : SpaceXApi {
private val launchesDetails = PopulatedObject(
select = "-crew -capsules -cores -payloads -launchpad",
path = "launches",
populate = PopulatedObject(path = "rocket")
)
private val padDetails = PopulatedObject(path = "rockets")
private val populateNestedLaunches = ApiOptions(populate = listOf(launchesDetails))
private val populateLaunchesForPads = ApiOptions(populate = listOf(launchesDetails, padDetails), sort = "field name")
private val dragonWithCapsule = PopulatedObject(path = "dragon", populate = PopulatedObject(path = "capsule", select = "-launches"))
private val populateLaunchDetails = ApiOptions(
populate = listOf(
PopulatedObject(path = "rocket"),
PopulatedObject(path = "launchpad", select = "-launches -rockets"),
PopulatedObject(path = "crew", populate = PopulatedObject(path = "crew", select = "-launches")),
PopulatedObject(path = "capsules", select = "-launches"),
PopulatedObject(path = "cores", populate = PopulatedObject(path = "core", select = "-launches")),
PopulatedObject(path = "payloads", populate = dragonWithCapsule)
),
sort = "field -upcoming -flight_number name",
pagination = false
)
private val populatePayload = ApiOptions(populate = listOf(dragonWithCapsule))
private fun requestById(id: String, options: ApiOptions = ApiOptions()) = ApiRequest(ApiQuery(id), options)
override suspend fun getCapsules(): Response<ApiResponse<Capsule>> =
apiRemote.getCapsules(ApiRequest(options = populateNestedLaunches.apply { sort = "field -serial" }))
override suspend fun getCapsuleById(id: String): Response<ApiResponse<Capsule>> =
apiRemote.getCapsuleById(requestById(id, populateNestedLaunches))
override suspend fun getCores(): Response<ApiResponse<Core>> =
apiRemote.getCores(ApiRequest(options = populateNestedLaunches.apply { sort = "field -block -serial" }))
override suspend fun getCoreById(id: String): Response<ApiResponse<Core>> =
apiRemote.getCoreById(requestById(id, populateNestedLaunches))
override suspend fun getCrew(): Response<ApiResponse<Crew>> =
apiRemote.getCrew(ApiRequest(options = populateNestedLaunches.apply { sort = "field _id" }))
override suspend fun getCrewById(id: String): Response<ApiResponse<Crew>> =
apiRemote.getCrewById(requestById(id, populateNestedLaunches))
override suspend fun getDragons(): Response<ApiResponse<Dragon>> =
apiRemote.getDragons(ApiRequest(options = ApiOptions(sort = "field name")))
override suspend fun getDragonById(id: String): Response<ApiResponse<Dragon>> =
apiRemote.getDragonById(requestById(id))
override suspend fun getLaunchPads(): Response<ApiResponse<LaunchPad>> =
apiRemote.getLaunchPads(ApiRequest(options = populateLaunchesForPads))
override suspend fun getLaunchPadById(id: String): Response<ApiResponse<LaunchPad>> =
apiRemote.getLaunchPadById(requestById(id, populateLaunchesForPads))
override suspend fun getLandingPads(): Response<ApiResponse<LandingPad>> =
apiRemote.getLandingPads(ApiRequest(options = populateNestedLaunches.apply { sort = "field name"}))
override suspend fun getLandingPadById(id: String): Response<ApiResponse<LandingPad>> =
apiRemote.getLandingPadById(requestById(id, populateNestedLaunches.apply { sort = "field name"}))
override suspend fun getRockets(): Response<ApiResponse<Rocket>> =
apiRemote.getRockets(ApiRequest(options = ApiOptions(sort = "field name")))
override suspend fun getRocketById(id: String): Response<ApiResponse<Rocket>> =
apiRemote.getRocketById(requestById(id))
override suspend fun getLaunches(): Response<ApiResponse<Launch>> =
apiRemote.getLaunches(ApiRequest(options = populateLaunchDetails))
override suspend fun getLaunchById(id: String): Response<ApiResponse<Launch>> =
apiRemote.getLaunchById(requestById(id, populateLaunchDetails))
override suspend fun getPayloadById(id: String): Response<ApiResponse<Payload>> =
apiRemote.getPayloadById(requestById(id, populatePayload))
override suspend fun getHistoryEvents(): Response<ApiResponse<History>> =
apiRemote.getHistoryEvents(ApiRequest(options = ApiOptions(sort = "field event_date_unix")))
}
| 1
|
Kotlin
|
2
| 1
|
556bcd18d9c60c8922055a11976056cad812856a
| 4,707
|
spacextimes
|
Apache License 2.0
|
app/src/main/kotlin/com/github/willjgriff/ethereumwallet/ethereum/transactions/TransactionsAdapter.kt
|
willjgriff
| 79,726,997
| false
| null |
package com.github.willjgriff.ethereumwallet.ethereum.transactions
import com.github.willjgriff.ethereumwallet.ethereum.address.model.DomainAddress
import com.github.willjgriff.ethereumwallet.ethereum.transactions.model.DomainBlock
import com.github.willjgriff.ethereumwallet.ethereum.transactions.model.DomainTransaction
import io.reactivex.Observable
import io.reactivex.Single
import org.ethereum.geth.Block
import org.ethereum.geth.Context
import org.ethereum.geth.EthereumClient
import org.ethereum.geth.Transaction
import timber.log.Timber
import java.math.BigInteger
import java.util.concurrent.TimeUnit
/**
* Created by williamgriffiths on 19/04/2017.
*/
class TransactionsAdapter(private val ethereumClient: EthereumClient, private val context: Context) {
private val DEFAULT_TO_CURRENT_BLOCK_VALUE = -1L
private val TRY_GET_BLOCK_NUMBER_INTERVAL_SECONDS = 1L
fun getCurrentBlock(): Single<Long> {
return Observable.interval(TRY_GET_BLOCK_NUMBER_INTERVAL_SECONDS, TimeUnit.SECONDS)
.map { tryGetBlockByNumber() }
.filter { it > 0 }
.firstOrError()
}
private fun tryGetBlockByNumber(): Long = try {
ethereumClient.getBlockByNumber(context, DEFAULT_TO_CURRENT_BLOCK_VALUE).number
} catch (exception: Exception) {
-1L
}
fun getTransactionsInBlockRange(address: DomainAddress, fromBlock: Long, numberOfBlocks: Long, blockSearchedFunc: (Long) -> Unit): Observable<DomainTransaction> =
Observable
.rangeLong(0, numberOfBlocks)
.map { fromBlock - it }
.flatMap { getTransactionsForAddressInBlock(address, it, blockSearchedFunc) }
fun getTransactionsForAddressInBlock(address: DomainAddress, blockNumber: Long, blockSearchedFunc: (Long) -> Unit): Observable<DomainTransaction> =
Observable
.just(retryGetBlockByNumber(blockNumber))
.filterErroneousBlocks()
.doOnNext {
Timber.d("Block successfully found: ${it.number}")
blockSearchedFunc.invoke(it.number)
}
.flatMap { getTransactionsInBlockThatIncludeAddress(address, it) }
/**
* [EthereumClient.getBlockByNumber] may throw an error, currently unsure what scenario causes this.
* Alternatively we catch the error and return a [DomainBlock] wrapper with a null [Block] field.
* The [DomainBlock] is necessary as RxJava will error if we try to pass null through it. We then
* filter the null blocks.
*/
private fun retryGetBlockByNumber(blockNumber: Long): DomainBlock =
try {
DomainBlock(ethereumClient.getBlockByNumber(context, blockNumber))
} catch (exception: Exception) {
DomainBlock(null)
}
private fun Observable<DomainBlock>.filterErroneousBlocks() =
filter { it.block != null }
.map { it.block!! }
private fun getTransactionsInBlockThatIncludeAddress(address: DomainAddress, block: Block) =
getTransactionsForBlock(block)
.filter { addressInTransaction(address, it) }
.map { createDomainTransaction(it, block) }
private fun getTransactionsForBlock(block: Block): Observable<Transaction> =
Observable
.rangeLong(0, block.transactions.size())
.map { block.transactions.get(it) }
private fun addressInTransaction(address: DomainAddress, it: Transaction): Boolean {
val from = tryStringFuncCatchEmpty { it.from.hex }
val to = tryStringFuncCatchEmpty { it.to.hex }
// Timber.d("Transaction from: $from to: $to")
return from == address.hex || to == address.hex
}
private fun createDomainTransaction(transaction: Transaction, block: Block): DomainTransaction {
val fromAddress = DomainAddress(tryStringFuncCatchEmpty { transaction.from.hex })
val toAddress = DomainAddress(transaction.to.hex)
val value = BigInteger(transaction.value.string())
val time = block.time
return DomainTransaction(fromAddress, toAddress, value, time)
}
private fun tryStringFuncCatchEmpty(func: () -> String): String =
try {
func.invoke()
} catch (exception: Exception) {
""
}
}
| 0
|
Kotlin
|
1
| 12
|
3e8b894606df7fd5595078971ca0883cbf78badf
| 4,472
|
android-ethereum-wallet
|
Apache License 2.0
|
app/src/main/java/com/example/budgetapplication/BudgetApplication.kt
|
afcarzero1
| 808,772,468
| false
|
{"Kotlin": 431692}
|
package com.example.budgetapplication
import android.app.Application
import com.example.budgetapplication.data.AppContainer
import com.example.budgetapplication.data.AppDataContainer
class BudgetApplication : Application() {
lateinit var container: AppContainer
override fun onCreate() {
super.onCreate()
container = AppDataContainer(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
5f683104f1b0f76aa5ef3df3f1e1d2f6f7ce37da
| 375
|
Budget
|
MIT License
|
feature-account-impl/src/main/java/jp/co/soramitsu/feature_account_impl/presentation/exporting/json/confirm/ExportJsonConfirmFragment.kt
|
soramitsu
| 278,060,397
| false
| null |
package jp.co.soramitsu.feature_account_impl.presentation.exporting.json.confirm
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import coil.ImageLoader
import javax.inject.Inject
import jp.co.soramitsu.common.di.FeatureUtils
import jp.co.soramitsu.feature_account_api.di.AccountFeatureApi
import jp.co.soramitsu.feature_account_impl.R
import jp.co.soramitsu.feature_account_impl.di.AccountFeatureComponent
import jp.co.soramitsu.feature_account_impl.presentation.exporting.ExportFragment
import jp.co.soramitsu.feature_account_impl.presentation.view.advanced.AdvancedBlockView.FieldState
import kotlinx.android.synthetic.main.fragment_export_json_confirm.exportEthereumJsonConfirmValue
import kotlinx.android.synthetic.main.fragment_export_json_confirm.exportJsonConfirmAdvanced
import kotlinx.android.synthetic.main.fragment_export_json_confirm.exportJsonConfirmChangePassword
import kotlinx.android.synthetic.main.fragment_export_json_confirm.exportJsonConfirmExport
import kotlinx.android.synthetic.main.fragment_export_json_confirm.exportJsonConfirmNetworkInput
import kotlinx.android.synthetic.main.fragment_export_json_confirm.exportJsonConfirmToolbar
import kotlinx.android.synthetic.main.fragment_export_json_confirm.exportSubstrateJsonConfirmValue
class ExportJsonConfirmFragment : ExportFragment<ExportJsonConfirmViewModel>() {
@Inject
protected lateinit var imageLoader: ImageLoader
companion object {
private const val PAYLOAD_KEY = "PAYLOAD_KEY"
fun getBundle(payload: ExportJsonConfirmPayload) = bundleOf(PAYLOAD_KEY to payload)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_export_json_confirm, container, false)
}
override fun initViews() {
exportJsonConfirmToolbar.setHomeButtonListener { viewModel.back() }
exportJsonConfirmExport.setOnClickListener { viewModel.confirmClicked() }
exportJsonConfirmChangePassword.setOnClickListener { viewModel.changePasswordClicked() }
with(exportJsonConfirmAdvanced) {
configure(substrateEncryptionTypeField, FieldState.DISABLED)
configure(substrateDerivationPathField, FieldState.HIDDEN)
configureHint(substrateDerivationPathHintView, FieldState.HIDDEN)
configureEthereum(FieldState.HIDDEN)
}
exportJsonConfirmNetworkInput.isEnabled = false
exportJsonConfirmNetworkInput.isVisible = !viewModel.isExportFromWallet
}
override fun inject() {
val payload = argument<ExportJsonConfirmPayload>(PAYLOAD_KEY)
FeatureUtils.getFeature<AccountFeatureComponent>(requireContext(), AccountFeatureApi::class.java)
.exportJsonConfirmFactory()
.create(this, payload)
.inject(this)
}
override fun subscribe(viewModel: ExportJsonConfirmViewModel) {
super.subscribe(viewModel)
viewModel.cryptoTypeLiveData.observe {
exportJsonConfirmAdvanced.setSubstrateEncryption(it.name)
}
viewModel.chainLiveData.observe {
exportJsonConfirmNetworkInput.loadIcon(it.icon, imageLoader)
exportJsonConfirmNetworkInput.setMessage(it.name)
}
viewModel.isEthereum.observe { isEthereum ->
exportJsonConfirmAdvanced.isVisible = false
when {
viewModel.isExportFromWallet -> {
exportSubstrateJsonConfirmValue.isVisible = true
exportEthereumJsonConfirmValue.isVisible = true
exportJsonConfirmAdvanced.isVisible = false
}
!viewModel.isExportFromWallet && !isEthereum -> {
exportSubstrateJsonConfirmValue.isVisible = true
exportEthereumJsonConfirmValue.isVisible = false
exportJsonConfirmAdvanced.isVisible = true
}
!viewModel.isExportFromWallet && isEthereum -> {
exportSubstrateJsonConfirmValue.isVisible = false
exportEthereumJsonConfirmValue.isVisible = true
}
}
}
viewModel.substrateJson?.let { exportSubstrateJsonConfirmValue.setMessage(it) }
viewModel.ethereumJson?.let { exportEthereumJsonConfirmValue.setMessage(it) }
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
viewModel.shareCompleted()
}
super.onActivityResult(requestCode, resultCode, data)
}
}
| 1
|
Kotlin
|
14
| 54
|
9d3659e4f142cc4e0270c149ddfb8bd0d6a9eefc
| 4,881
|
fearless-Android
|
Apache License 2.0
|
codeSnippets/snippets/engine-main-modules/src/main/kotlin/com/example/Application.kt
|
ktorio
| 278,572,893
| false
| null |
package com.example
import io.ktor.application.*
import io.ktor.response.*
import io.ktor.routing.*
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
fun Application.module1() {
routing {
get("/module1") {
call.respondText("Hello from 'module1'!")
}
}
}
fun Application.module2() {
routing {
get("/module2") {
call.respondText("Hello from 'module2'!")
}
}
}
| 5
|
Kotlin
|
94
| 95
|
4ede19d93a98dd25c3e1665702f13a8468a364aa
| 465
|
ktor-documentation
|
Apache License 2.0
|
src/jmh/kotlin/benchmarks/LargeGraphServer.kt
|
alefedor
| 213,178,026
| false
| null |
package benchmarks
import benchmarks.util.Graph
import java.io.Serializable
import java.rmi.Remote
import java.rmi.RemoteException
import java.rmi.registry.LocateRegistry
import java.rmi.server.UnicastRemoteObject
private lateinit var ROAD_GRAPH: Graph
private lateinit var LIVE_JOURNAL_GRAPH: Graph
private lateinit var WEB_GRAPH: Graph
private lateinit var RANDOM_GRAPH: Graph
private lateinit var KRON_GRAPH: Graph
enum class LargeGraph : Serializable {
KRON,
RANDOM,
ROAD,
LIVE_JOURNAL,
}
fun loadGraph(graph: LargeGraph): Graph =
when (graph) {
LargeGraph.KRON -> loadGraph("KRON", "graph bz2", "https://www.cc.gatech.edu/dimacs10/archive/data/kronecker/kron_g500-logn21.graph.bz2")
LargeGraph.RANDOM -> loadGraph("RANDOM-LARGE", "graph bz2", "https://www.cc.gatech.edu/dimacs10/archive/data/er/er-fact1.5-scale22.graph.bz2")
LargeGraph.ROAD -> loadGraph("USA-ROADS-FULL", "gr gz", "http://www.diag.uniroma1.it/challenge9/data/USA-road-d/USA-road-d.USA.gr.gz")
LargeGraph.LIVE_JOURNAL -> loadGraph("LIVE-JOURNAL", "txt gz", "http://snap.stanford.edu/data/soc-LiveJournal1.txt.gz")
}
interface LargeGraphServerInterface : Remote {
@Throws(RemoteException::class)
fun graphByParams(params: LargeGraph): Graph
}
class LargeGraphServer : UnicastRemoteObject(), LargeGraphServerInterface {
override fun graphByParams(params: LargeGraph) = when (params) {
LargeGraph.KRON -> {
if (!::KRON_GRAPH.isInitialized)
KRON_GRAPH = loadGraph(params)
KRON_GRAPH
}
LargeGraph.RANDOM -> {
if (!::RANDOM_GRAPH.isInitialized)
RANDOM_GRAPH = loadGraph(params)
RANDOM_GRAPH
}
LargeGraph.ROAD -> {
if (!::ROAD_GRAPH.isInitialized)
ROAD_GRAPH = loadGraph(params)
ROAD_GRAPH
}
LargeGraph.LIVE_JOURNAL -> {
if (!::LIVE_JOURNAL_GRAPH.isInitialized)
LIVE_JOURNAL_GRAPH = loadGraph(params)
LIVE_JOURNAL_GRAPH
}
}
companion object {
var obj: LargeGraphServer? = null
const val NAME = "//localhost/GraphServer"
@JvmStatic
fun main(args: Array<String>) {
val registry = LocateRegistry.createRegistry(1099)
obj = LargeGraphServer()
registry.rebind(NAME, obj)
}
fun getLookup(): LargeGraphServerInterface {
val registry = LocateRegistry.getRegistry()
return (registry.lookup(NAME) as LargeGraphServerInterface)
}
fun close() {
LocateRegistry.getRegistry().unbind(NAME)
UnicastRemoteObject.unexportObject(obj, false)
}
}
}
| 0
| null |
1
| 1
|
ac6739141f866ed7d88f19b787958a8ac244c06f
| 2,761
|
concurrent-dynamic-connectivity
|
Apache License 2.0
|
app/src/main/java/com/doubean/ford/data/db/model/GroupTabEntity.kt
|
Bumblebee202111
| 453,416,432
| false
| null |
package com.doubean.ford.data.db.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity("group_tabs")
data class GroupTabEntity(
@PrimaryKey
val id: String,
val name: String?,
val seq: Int,
@ColumnInfo("group_id")
val groupId: String,
)
| 0
|
Kotlin
|
0
| 5
|
7f92e341028d187b351dadec6eccde2d7715b65e
| 314
|
doubean
|
Apache License 2.0
|
chat-gui/src/main/java/ru/usedesk/chat_gui/chat/offlineformselector/OfflineFormSelectorAdapter.kt
|
usedesk
| 127,645,126
| false
| null |
package ru.usedesk.chat_gui.chat.offlineformselector
import android.view.ViewGroup
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import ru.usedesk.chat_gui.R
import ru.usedesk.common_gui.UsedeskCommonFieldCheckBoxAdapter
import ru.usedesk.common_gui.inflateItem
internal class OfflineFormSelectorAdapter(
recyclerView: RecyclerView,
binding: OfflineFormSelectorPage.Binding,
private val viewModel: OfflineFormSelectorViewModel,
lifecycleOwner: LifecycleOwner,
private val items: List<String>,
var selectedIndex: Int
) : RecyclerView.Adapter<OfflineFormSelectorAdapter.ViewHolder>() {
private val itemStyle =
binding.styleValues.getStyle(R.attr.usedesk_chat_screen_offline_form_selector_checkbox)
init {
onSelected(selectedIndex)
recyclerView.run {
layoutManager = LinearLayoutManager(recyclerView.context)
adapter = this@OfflineFormSelectorAdapter
}
viewModel.selectedIndexLiveData.observe(lifecycleOwner) {
it?.let {
onSelected(it)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(inflateItem(
parent, R.layout.usedesk_item_field_checkbox,
itemStyle
) { rootView, defaultStyleId ->
UsedeskCommonFieldCheckBoxAdapter.Binding(rootView, defaultStyleId)
})
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(position)
}
override fun getItemCount() = items.size
private fun onSelected(index: Int) {
if (index != selectedIndex) {
val oldSelectedIndex = selectedIndex
selectedIndex = index
notifyItemChanged(oldSelectedIndex)
notifyItemChanged(selectedIndex)
}
}
inner class ViewHolder(
binding: UsedeskCommonFieldCheckBoxAdapter.Binding
) : RecyclerView.ViewHolder(binding.rootView) {
private val adapter = UsedeskCommonFieldCheckBoxAdapter(binding)
fun bind(index: Int) {
adapter.setTitle(items[index])
adapter.setChecked(index == selectedIndex)
adapter.setOnClickListener {
viewModel.onSelected(
if (selectedIndex != index) {
index
} else {
-1
}
)
}
}
}
}
| 0
|
Kotlin
|
4
| 3
|
3ee34eaeeaa0668e94cf8dadf78afad6901b52c4
| 2,588
|
Android_SDK
|
MIT License
|
PedidosServer/app/src/main/java/com/opdeveloper/pedidosserver/productlist/viewholder/ProductListViewHolder.kt
|
Afrothundera
| 608,736,651
| false
| null |
package com.opdeveloper.pedidosserver.productlist.viewholder
import android.view.ContextMenu
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.opdeveloper.pedidosserver.R
import com.opdeveloper.pedidosserver.interfaces.OnItemClick
class ProductListViewHolder(v: View): RecyclerView.ViewHolder(v), View.OnClickListener, View.OnCreateContextMenuListener {
var productName: TextView
var image: ImageView
var precio: TextView
var descripcion: TextView
lateinit var itemClicklistener : OnItemClick
init {
productName = v.findViewById(R.id.txt_name)
image = v.findViewById(R.id.product_by_Category_Image)
precio = v.findViewById(R.id.txt_price)
descripcion = v.findViewById(R.id.txt_descripcion)
v.setOnCreateContextMenuListener(this)
v.setOnClickListener(this)
}
override fun onClick(p0: View?) {
itemClicklistener.onClick(p0!!, adapterPosition, false)
}
override fun onCreateContextMenu(contextMenu: ContextMenu?, p1: View?, p2: ContextMenu.ContextMenuInfo?) {
contextMenu!!.setHeaderTitle("Selecciona la accion")
contextMenu.add(0,0,adapterPosition, "Actualizar")
contextMenu.add(0,1,adapterPosition, "Borrar")
}
}
| 0
|
Kotlin
|
0
| 0
|
b3377305ea9d7f7c7d764a686edc4a3b38f2d098
| 1,341
|
App-Pedidos-Online-Restaurantes
|
The Unlicense
|
app/src/main/java/com/olehka/currencyrates/ui/viewmodel/RatesViewModel.kt
|
olehka
| 209,806,725
| false
| null |
package com.olehka.currencyrates.ui.viewmodel
import androidx.lifecycle.*
import com.olehka.currencyrates.R
import com.olehka.currencyrates.data.CurrencyRate
import com.olehka.currencyrates.data.Repository
import com.olehka.currencyrates.data.Result
import com.olehka.currencyrates.util.Event
import com.olehka.currencyrates.util.mapValues
import kotlinx.coroutines.*
import timber.log.Timber
import java.lang.Exception
import javax.inject.Inject
const val DELAY_MILLIS = 1_000L
const val DEFAULT_VALUE = 100f
const val EURO = "EUR"
class RatesViewModel
@Inject constructor(private val repository: Repository) : ViewModel() {
private lateinit var periodicJob: Job
private var baseCurrency = EURO
private var baseValue = DEFAULT_VALUE
private val mutableRateList =
MutableLiveData<List<CurrencyRate>>().apply { value = emptyList() }
val rateList: LiveData<List<CurrencyRate>> = mutableRateList
val empty: LiveData<Boolean> = Transformations.map(mutableRateList) { it.isEmpty() }
private val snackbarText = MutableLiveData<Event<Int>>()
val shackbarMessage: LiveData<Event<Int>> = snackbarText
private val exceptionHandler = CoroutineExceptionHandler { _, exception ->
Timber.e(exception)
}
var isConnected: Boolean = false
set(value) {
field = value
if (value) startPeriodicCurrencyRatesUpdate()
else cancelPeriodicCurrencyRatesUpdate()
}
private fun startPeriodicCurrencyRatesUpdate() {
cancelPeriodicCurrencyRatesUpdate()
// alternative: liveData building block
periodicJob = viewModelScope.launch(exceptionHandler) {
while (isActive) {
updateRateList(repository.getCurrencyRates(baseCurrency, fromNetwork = true))
delay(DELAY_MILLIS)
}
}
}
fun updateCurrencyRatesFromCache() {
viewModelScope.launch(exceptionHandler) {
updateRateList(repository.getCurrencyRates(baseCurrency))
}
}
fun onBaseCurrencyValueChanged(currency: String, value: Float) {
Timber.v("onBaseCurrencyValueChanged: $currency: $value")
if (isConnected && baseCurrency != currency) {
baseCurrency = currency
baseValue = value
startPeriodicCurrencyRatesUpdate()
} else {
showErrorMessage()
}
}
fun onBaseValueChanged(value: Float) {
Timber.v("onBaseValueChanged: $value")
if (baseValue != value) {
baseValue = value
updateCurrencyRatesFromCache()
}
}
private fun cancelPeriodicCurrencyRatesUpdate() {
if (::periodicJob.isInitialized) {
periodicJob.cancel()
}
}
private fun updateRateList(result: Result<List<CurrencyRate>>) {
when (result) {
is Result.Success -> {
mutableRateList.value = result.data.mapValues(baseValue)
}
is Result.Error -> {
showErrorMessage()
}
}
}
fun showErrorMessage() {
snackbarText.value = Event(R.string.currency_rates_loading_error)
}
}
| 0
|
Kotlin
|
0
| 0
|
cb9a5dca4554e9960bde3de6b86680f65b8ea325
| 3,193
|
currency-rates-task
|
Apache License 2.0
|
trixnity-client/trixnity-client-repository-indexeddb/src/jsTest/kotlin/net/folivo/trixnity/client/store/repository/indexeddb/IndexedDBRoomStateRepositoryTest.kt
|
benkuly
| 330,904,570
| false
| null |
package net.folivo.trixnity.client.store.repository.indexeddb
import com.benasher44.uuid.uuid4
import com.juul.indexeddb.openDatabase
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.maps.shouldHaveSize
import io.kotest.matchers.shouldBe
import net.folivo.trixnity.client.store.repository.RoomStateRepositoryKey
import net.folivo.trixnity.core.model.EventId
import net.folivo.trixnity.core.model.RoomId
import net.folivo.trixnity.core.model.UserId
import net.folivo.trixnity.core.model.events.Event.StateEvent
import net.folivo.trixnity.core.model.events.m.room.MemberEventContent
import net.folivo.trixnity.core.model.events.m.room.Membership
import net.folivo.trixnity.core.model.events.m.room.NameEventContent
import net.folivo.trixnity.core.serialization.createMatrixEventJson
class IndexedDBRoomStateRepositoryTest : ShouldSpec({
timeout = 10_000
lateinit var cut: IndexedDBRoomStateRepository
lateinit var rtm: IndexedDBRepositoryTransactionManager
beforeTest {
cut = IndexedDBRoomStateRepository(createMatrixEventJson())
val db = openDatabase(uuid4().toString(), 1) { database, oldVersion, _ ->
IndexedDBRoomStateRepository.apply { migrate(database, oldVersion) }
}
rtm = IndexedDBRepositoryTransactionManager(db, arrayOf(cut.objectStoreName))
}
should("save, get and delete") {
val key1 = RoomStateRepositoryKey(RoomId("room1", "server"), "m.room.member")
val key2 = RoomStateRepositoryKey(RoomId("room2", "server"), "m.room.name")
val state1 = mapOf(
"@alice:server" to StateEvent(
MemberEventContent(membership = Membership.JOIN),
EventId("$1event"),
UserId("alice", "server"),
RoomId("room1", "server"),
1234,
stateKey = "@alice:server"
)
)
val state1Copy = state1 + mapOf(
"@bob:server" to StateEvent(
MemberEventContent(membership = Membership.LEAVE),
EventId("$1event"),
UserId("alice", "server"),
RoomId("room1", "server"),
1234,
stateKey = "@bob:server"
)
)
val state2 = mapOf(
"" to StateEvent(
NameEventContent("room name"),
EventId("$2eventId"),
UserId("bob", "server"),
RoomId("room2", "server"),
originTimestamp = 24,
stateKey = ""
)
)
rtm.writeTransaction {
cut.save(key1, state1)
cut.save(key2, state2)
cut.get(key1) shouldBe state1
cut.get(key2) shouldBe state2
cut.save(key1, state1Copy)
cut.get(key1) shouldBe state1Copy
cut.delete(key1)
cut.get(key1) shouldHaveSize 0
}
}
should("save and get by second key") {
val key = RoomStateRepositoryKey(RoomId("room3", "server"), "m.room.member")
val event = StateEvent(
MemberEventContent(membership = Membership.JOIN),
EventId("\$event"),
UserId("alice", "server"),
RoomId("room1", "server"),
1234,
stateKey = "@cedric:server"
)
rtm.writeTransaction {
cut.saveBySecondKey(key, "@cedric:server", event)
cut.getBySecondKey(key, "@cedric:server") shouldBe event
}
}
})
| 0
|
Kotlin
|
3
| 25
|
607e61dad063037518bcba654a625f218bfb7df9
| 3,513
|
trixnity
|
Apache License 2.0
|
app/src/main/java/com/example/mycredman/CredentialDetailsActivity.kt
|
ko-koiwai
| 699,702,980
| false
|
{"Kotlin": 57313}
|
package com.example.mycredman
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat.startActivity
import com.example.mycredman.ui.theme.MyCredManTheme
class CredentialDetailsActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intent = intent
// Receive String type values
val stringVal = intent.getStringExtra("ServiceName")?:""
val stringValUrl = intent.getStringExtra("ServiceNameUrl")?:""
val stringValId = intent.getStringExtra("ServiceNameId")?:""
val stringcredentialId = intent.getByteArrayExtra("stringcredentialId")?: byteArrayOf()
setContent {
MyCredManTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
CredentialEntry(stringVal, stringValUrl, stringValId, stringcredentialId)
}
}
}
}
}
@Composable
fun CredentialEntry(name: String, url: String, id: String, credentialId: ByteArray, modifier: Modifier = Modifier) {
val openDialog = remember { mutableStateOf(false) }
val context = LocalContext.current
val intent = Intent(context,MainActivity::class.java)
Column(
verticalArrangement= Arrangement.spacedBy(12.dp),
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
) {
Text(text = name, fontSize = 30.sp, fontWeight = FontWeight.Bold,color = MaterialTheme.colorScheme.primary)
Text(text = "URL", color = MaterialTheme.colorScheme.secondary)
Text(text = url, Modifier.padding(start = 12.dp))
Text(text = "ID", color = MaterialTheme.colorScheme.secondary)
Text(text = id, Modifier.padding(start = 12.dp))
Button(onClick = {
openDialog.value = true
},
colors = ButtonDefaults.buttonColors(Color(0xFFEB5505), Color.White)
) {
Text(text = "Delete")
}
}
if (openDialog.value) {
AlertDialog(
containerColor = MaterialTheme.colorScheme.background,
onDismissRequest = {
// Dismiss the dialog when the user clicks outside the dialog or on the back
// button. If you want to disable that functionality, simply use an empty
// onDismissRequest.
openDialog.value = false
},
// icon = { Icon(Icons.Filled.Favorite, contentDescription = null) },
// title = {
// Text(text = "Title")
// },
text = {
Text(
text = "Are you sure to delete?",
color = MaterialTheme.colorScheme.primary
)
},
confirmButton = {
TextButton(
onClick = {
openDialog.value = false
// Log.d("MyCredMan",credentialId)
//delect credential
MyCredentialDataManager.delete(context,url,credentialId)
startActivity(context,intent,null)
},colors = ButtonDefaults.textButtonColors(Color(0xFFEB5505), Color.White)
) {
Text("Delete")
}
},
dismissButton = {
TextButton(
onClick = {
openDialog.value = false
},colors = ButtonDefaults.buttonColors(Color.Transparent, Color.Gray)
) {
Text("Cancel")
}
}
)
}
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
MyCredManTheme {
CredentialEntry("Android", "example.com", "apple", byteArrayOf())
}
}
| 1
|
Kotlin
|
4
| 4
|
af2e122add1ce2e8cd540a538ebc72e1901385d9
| 5,157
|
MyCredentialManager
|
MIT License
|
app/src/main/java/com/example/prodman/LoginFragment.kt
|
PabloDino
| 804,058,522
| false
|
{"Kotlin": 205892}
|
package com.example.prodman
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.example.prodman.model.ProdViewModelFactory
import com.example.product.databinding.FragmentLoginBinding
import android.os.Bundle
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.example.prodman.model.ProdViewModel
class LoginFragment : Fragment(){
private val viewModel: ProdViewModel by activityViewModels {
ProdViewModelFactory(
(activity?.application as ProductApplication).database.productDao(),
(activity?.application as ProductApplication).database.prodVersionDao(),
(activity?.application as ProductApplication).database.prodVersionBatchDao(),
(activity?.application as ProductApplication).database.prodBatchStepDao(),
(activity?.application as ProductApplication).database.hazardDao(),
(activity?.application as ProductApplication).database.measureDao(),
(activity?.application as ProductApplication).database.userDao(),
activity?.application as ProductApplication
)
}
private var _binding: FragmentLoginBinding? = null
private val binding get() = _binding!!
private lateinit var editTextUsername: EditText
private lateinit var editTextPassword: EditText
private lateinit var buttonLogin: Button
//private val userDao:UserDao
//private lateinit var buttonSignUp: Button
//private lateinit var dbHelper: DatabaseHelper
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentLoginBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.fragmentName="FragmentLogin"
//val adapter = LocalProdAdapter(ProdClick {})
var loggedIn = viewModel.checkIfLoggedIn()
if (loggedIn) {
// Successful login, proceed to next activity
//startActivity(Intent(this, MainActivity::class.java))
//finish()
//Toast.makeText(this, "Login successful", Toast.LENGTH_SHORT).show()
val action = LoginFragmentDirections.actionLoginFragmentToProductListFragment()
// = ProductListFragmentDirections.actionProductListFragmentToProductDetailFragment(it.id)
this.findNavController().navigate(action)
}
editTextUsername = binding.usernameEditText
editTextPassword = binding.passwordEditText
buttonLogin = binding.loginButton
// buttonSignUp = binding.
// Initialize Database Helper
// dbHelper = DatabaseHelper(this)
// Set click listener for the login button
buttonLogin.setOnClickListener {
val username = editTextUsername.text.toString()
val password = editTextPassword.text.toString()
// Attempt to login using local SQLite database
loggedIn = viewModel.attemptLogin(username, password, requireContext())
if (loggedIn) {
// Successful login, proceed to next activity
//startActivity(Intent(this, MainActivity::class.java))
//finish()
//Toast.makeText(this, "Login successful", Toast.LENGTH_SHORT).show()
val action = LoginFragmentDirections.actionLoginFragmentToProductListFragment()
// = ProductListFragmentDirections.actionProductListFragmentToProductDetailFragment(it.id)
this.findNavController().navigate(action)
//val action = loginfr
}
else {
Toast.makeText(requireContext(), "Incorrect user name or password", Toast.LENGTH_LONG)
}
}
val passwordEditText= binding.passwordEditText
val showPasswordCheckBox= binding.checkBox
// Set listener for checkbox state changes
showPasswordCheckBox.setOnCheckedChangeListener { buttonView, isChecked ->
// If the checkbox is checked, show the password
// Otherwise, hide the password
if (isChecked) {
passwordEditText.transformationMethod = HideReturnsTransformationMethod.getInstance()
} else {
passwordEditText.transformationMethod = PasswordTransformationMethod.getInstance()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b1558da8b460f16f011f26d45a6b9e547e1b8361
| 4,887
|
s7.prodtrac
|
Apache License 2.0
|
data/src/main/kotlin/ru/khiraevmalik/theguardiannews/api/Api.kt
|
Hiraev
| 278,637,711
| false
| null |
package ru.khiraevmalik.theguardiannews.api
import ru.khiraevmalik.theguardiannews.data.BuildConfig
object Api {
object TheGuardian {
const val baseUrl = BuildConfig.THE_GUARDIAN_API_URL
const val api_key_value = BuildConfig.THE_GUARDIAN_API_KEY
const val api_key = "api-key"
object Path {
const val search = "search?$api_key=$api_key_value&${Params.showFieldsParams}"
}
object Params {
const val query = "q"
const val showFields = "show-fields"
const val page = "page"
const val pageSize = "page-size"
const val orderBy = "order-by"
object QueryField {
const val thumbnail = "thumbnail"
const val bodyText = "bodyText"
const val headline = "headline"
const val trailText = "trailText"
}
object OrderByValue {
const val newest = "newest"
}
const val showFieldsParams = "$showFields=${QueryField.bodyText}," +
"${QueryField.thumbnail},${QueryField.headline},${QueryField.trailText}"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
19ce6605f1d8c33def4d0a70340c8e75bd4c9a20
| 1,194
|
TheGuardianNews
|
Apache License 2.0
|
data/src/main/kotlin/ru/khiraevmalik/theguardiannews/api/Api.kt
|
Hiraev
| 278,637,711
| false
| null |
package ru.khiraevmalik.theguardiannews.api
import ru.khiraevmalik.theguardiannews.data.BuildConfig
object Api {
object TheGuardian {
const val baseUrl = BuildConfig.THE_GUARDIAN_API_URL
const val api_key_value = BuildConfig.THE_GUARDIAN_API_KEY
const val api_key = "api-key"
object Path {
const val search = "search?$api_key=$api_key_value&${Params.showFieldsParams}"
}
object Params {
const val query = "q"
const val showFields = "show-fields"
const val page = "page"
const val pageSize = "page-size"
const val orderBy = "order-by"
object QueryField {
const val thumbnail = "thumbnail"
const val bodyText = "bodyText"
const val headline = "headline"
const val trailText = "trailText"
}
object OrderByValue {
const val newest = "newest"
}
const val showFieldsParams = "$showFields=${QueryField.bodyText}," +
"${QueryField.thumbnail},${QueryField.headline},${QueryField.trailText}"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
19ce6605f1d8c33def4d0a70340c8e75bd4c9a20
| 1,194
|
TheGuardianNews
|
Apache License 2.0
|
app/src/main/java/pl/mobilization/konfeo/checkin/adapters/AttendeesAdapter.kt
|
Mobilization
| 109,166,961
| false
| null |
package pl.mobilization.konfeo.checkin.adapters
import android.arch.persistence.room.Room
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.ResultReceiver
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import checkin.konfeo.com.konfeocheckin.R.layout.attendee_list_item
import org.apache.commons.lang3.StringUtils
import pl.mobilization.konfeo.checkin.entities.Attendee
import java.util.regex.Pattern
import kotlinx.android.synthetic.main.attendee_list_item.view.*
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import pl.mobilization.konfeo.checkin.entities.KonfeoDatabase
import org.jetbrains.anko.toast
import pl.mobilization.konfeo.checkin.KonfeoIntentService
class AttendeeHolder(val view: View) : RecyclerView.ViewHolder(view) {
fun bind(attendee: Attendee, update : (Attendee) -> Unit) {
with(itemView) {
checkBoxPresent.setOnCheckedChangeListener(null)
textViewName.text = "${attendee.first_name} ${attendee.last_name}"
textViewEmail.text = attendee.email
textViewGroup.text = attendee.group
checkBoxPresent.isChecked = attendee.checked_in
checkBoxPresent.setOnCheckedChangeListener { compoundButton, value -> attendee.checked_in = value ; update(attendee)}
}
}
}
class AttendeeAdapter(val context: Context) : RecyclerView.Adapter<AttendeeHolder>() {
private val attendees = mutableMapOf<Pair<Long, Long>, Attendee>()
private var filtered: List<Attendee> = arrayListOf<Attendee>()
private val db: KonfeoDatabase = Room.databaseBuilder(context,
KonfeoDatabase::class.java, "konfeo").build()
private fun updateAttendee(attendee: Attendee) {
attendee.needs_update = true
launch {
db.attendeeDAO().updateAttendees(attendee)
delay(5000)
KonfeoIntentService.startActionUpdate(this@AttendeeAdapter.context, AttendeeUpdateReceiver())
}
}
inner internal class AttendeeUpdateReceiver() : ResultReceiver(Handler(Looper.getMainLooper())) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
launch(UI) {
this@AttendeeAdapter.context.toast("Updated")
}
}
}
override fun onBindViewHolder(holder: AttendeeHolder, position: Int) {
holder.bind(filtered[position], this::updateAttendee)
}
override fun getItemCount(): Int = filtered.count()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AttendeeHolder {
val view = LayoutInflater.from(parent.context).inflate(attendee_list_item, parent, false)
return AttendeeHolder(view)
}
fun add(attendees: List<Attendee>) {
for (attendee in attendees) {
this.attendees.put(Pair(attendee.id, attendee.event_id), attendee)
}
requery()
}
private fun requery() {
if (filters.isEmpty()) {
filtered = attendees.values.toList()
} else {
filtered = attendees.values.filter {
matches_all(it)
}.toList()
}
notifyDataSetChanged()
}
private fun matches_all(it: Attendee): Boolean {
for (filter in filters) {
if (!it.matches(filter))
return false
}
return true
}
private var filters: List<String> = arrayListOf<String>()
var filter: String = ""
set(value) {
field = StringUtils.stripAccents(value.toLowerCase())
filters = field.split(Pattern.compile("\\s+"))
requery()
}
}
| 0
|
Kotlin
|
0
| 0
|
46d154cb756eac27e143fefa6b47b3f75b3aa1cf
| 3,856
|
konfeo-checkin
|
MIT License
|
user-agent/user-agent-impl/src/main/java/com/duckduckgo/user/agent/impl/UserAgentPlugin.kt
|
duckduckgo
| 78,869,127
| false
|
{"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784}
|
/*
* Copyright (c) 2024 DuckDuckGo
*
* 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.duckduckgo.user.agent.impl
import com.duckduckgo.di.scopes.AppScope
import com.duckduckgo.privacy.config.api.PrivacyFeaturePlugin
import com.duckduckgo.user.agent.store.UserAgentExceptionEntity
import com.duckduckgo.user.agent.store.UserAgentFeatureName
import com.duckduckgo.user.agent.store.UserAgentFeatureToggle
import com.duckduckgo.user.agent.store.UserAgentFeatureToggleRepository
import com.duckduckgo.user.agent.store.UserAgentRepository
import com.squareup.anvil.annotations.ContributesMultibinding
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import javax.inject.Inject
@ContributesMultibinding(AppScope::class)
class UserAgentPlugin @Inject constructor(
private val userAgentRepository: UserAgentRepository,
private val userAgentFeatureToggleRepository: UserAgentFeatureToggleRepository,
) : PrivacyFeaturePlugin {
override fun store(
featureName: String,
jsonString: String,
): Boolean {
val privacyFeature = userAgentFeatureValueOf(featureName) ?: return false
if (privacyFeature.value == this.featureName) {
val userAgentExceptions = mutableListOf<UserAgentExceptionEntity>()
val moshi = Moshi.Builder().build()
val jsonAdapter: JsonAdapter<UserAgentFeature> =
moshi.adapter(UserAgentFeature::class.java)
val userAgentFeature: UserAgentFeature? = jsonAdapter.fromJson(jsonString)
val exceptionsList = userAgentFeature?.exceptions.orEmpty()
exceptionsList.forEach {
userAgentExceptions.add(UserAgentExceptionEntity(it.domain, it.reason.orEmpty()))
}
userAgentRepository.updateAll(userAgentExceptions)
val isEnabled = userAgentFeature?.state == "enabled"
userAgentFeatureToggleRepository.insert(UserAgentFeatureToggle(this.featureName, isEnabled, userAgentFeature?.minSupportedVersion))
return true
}
return false
}
override val featureName: String = UserAgentFeatureName.UserAgent.value
}
| 67
|
Kotlin
|
901
| 3,823
|
6415f0f087a11a51c0a0f15faad5cce9c790417c
| 2,682
|
Android
|
Apache License 2.0
|
Extensions/Music/src/main/kotlin/net/sourcebot/module/music/Music.kt
|
RoMeAh-zz
| 299,405,471
| true
|
{"Kotlin": 207948}
|
package net.sourcebot.module.music
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager
import net.dv8tion.jda.api.entities.Guild
import net.sourcebot.api.module.SourceModule
import net.sourcebot.module.music.audio.AudioSubsystem
import net.sourcebot.module.music.command.*
class Music : SourceModule() {
override fun onEnable() {
AudioSourceManagers.registerRemoteSources(PLAYER_MANAGER)
registerCommands(
PauseCommand(),
ResumeCommand(),
SkipCommand(),
StopCommand(),
PlayCommand(),
VolumeCommand()
)
}
override fun onDisable() {
PLAYER_MANAGER.shutdown()
}
companion object {
@JvmStatic
val PLAYER_MANAGER = DefaultAudioPlayerManager().also {
it.registerSourceManager(YoutubeAudioSourceManager())
}
@JvmStatic
val SUBSYSTEM_CACHE = HashMap<String, AudioSubsystem>()
@JvmStatic
fun getSubsystem(
guild: Guild
): AudioSubsystem = SUBSYSTEM_CACHE.computeIfAbsent(guild.id) {
AudioSubsystem(PLAYER_MANAGER.createPlayer()).also { it.applyTo(guild) }
}
}
}
| 0
| null |
0
| 0
|
32c7bccb80e27745c339b5cc582b4416d06de58e
| 1,363
|
Source
|
MIT License
|
linea/src/commonMain/kotlin/compose/icons/lineaicons/arrows/Glide.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36719092}
|
package compose.icons.lineaicons.arrows
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Bevel
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.lineaicons.ArrowsGroup
public val ArrowsGroup.Glide: ImageVector
get() {
if (_glide != null) {
return _glide!!
}
_glide = Builder(name = "Glide", defaultWidth = 64.0.dp, defaultHeight = 64.0.dp,
viewportWidth = 64.0f, viewportHeight = 64.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Bevel,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(45.968f, 48.968f)
lineToRelative(-14.001f, 14.0f)
lineToRelative(-13.967f, -13.968f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Bevel,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(18.0f, 15.0f)
lineToRelative(14.032f, -14.032f)
lineToRelative(14.0f, 14.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Bevel,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(31.968f, 31.968f)
moveToRelative(-5.0f, 0.0f)
arcToRelative(5.0f, 5.0f, 0.0f, true, true, 10.0f, 0.0f)
arcToRelative(5.0f, 5.0f, 0.0f, true, true, -10.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Bevel,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(49.0f, 18.0f)
lineToRelative(14.0f, 14.0f)
lineToRelative(-14.0f, 14.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Bevel,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(15.032f, 45.968f)
lineToRelative(-14.032f, -14.033f)
lineToRelative(13.968f, -13.967f)
}
}
.build()
return _glide!!
}
private var _glide: ImageVector? = null
| 17
|
Kotlin
|
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 3,209
|
compose-icons
|
MIT License
|
linea/src/commonMain/kotlin/compose/icons/lineaicons/arrows/Glide.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36719092}
|
package compose.icons.lineaicons.arrows
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Bevel
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.lineaicons.ArrowsGroup
public val ArrowsGroup.Glide: ImageVector
get() {
if (_glide != null) {
return _glide!!
}
_glide = Builder(name = "Glide", defaultWidth = 64.0.dp, defaultHeight = 64.0.dp,
viewportWidth = 64.0f, viewportHeight = 64.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Bevel,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(45.968f, 48.968f)
lineToRelative(-14.001f, 14.0f)
lineToRelative(-13.967f, -13.968f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Bevel,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(18.0f, 15.0f)
lineToRelative(14.032f, -14.032f)
lineToRelative(14.0f, 14.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Bevel,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(31.968f, 31.968f)
moveToRelative(-5.0f, 0.0f)
arcToRelative(5.0f, 5.0f, 0.0f, true, true, 10.0f, 0.0f)
arcToRelative(5.0f, 5.0f, 0.0f, true, true, -10.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Bevel,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(49.0f, 18.0f)
lineToRelative(14.0f, 14.0f)
lineToRelative(-14.0f, 14.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Bevel,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(15.032f, 45.968f)
lineToRelative(-14.032f, -14.033f)
lineToRelative(13.968f, -13.967f)
}
}
.build()
return _glide!!
}
private var _glide: ImageVector? = null
| 17
|
Kotlin
|
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 3,209
|
compose-icons
|
MIT License
|
client-misk/src/main/kotlin/app/cash/backfila/client/misk/BackfillMetadata.kt
|
cashapp
| 209,384,085
| false
|
{"Kotlin": 952510, "TypeScript": 78934, "Java": 14790, "Shell": 4170, "JavaScript": 1107, "HTML": 990, "Dockerfile": 486}
|
package app.cash.backfila.client.misk
import app.cash.backfila.client.spi.BackfillBackend
import app.cash.backfila.client.spi.BackfillRegistration
import jakarta.inject.Inject
import misk.web.metadata.Metadata
import misk.web.metadata.MetadataProvider
import misk.web.metadata.toFormattedJson
import wisp.moshi.adapter
import wisp.moshi.defaultKotlinMoshi
internal data class BackfillMetadata(
val name: String,
val description: String?,
val parametersClass: String?,
)
internal data class BackfillsMetadata(
val backfills: Map<String, List<BackfillMetadata>>,
) : Metadata(
metadata = backfills,
prettyPrint = defaultKotlinMoshi
.adapter<Map<String, List<BackfillMetadata>>>()
.toFormattedJson(backfills),
descriptionString = "Backfill classes registered with Backfila.",
)
internal class BackfillMetadataProvider : MetadataProvider<BackfillsMetadata> {
@Inject lateinit var backends: Set<BackfillBackend>
override val id = "backfila"
override fun get(): BackfillsMetadata {
val backfills = backends.associate { it::class.simpleName!! to it.backfills().map { it.toMetadata() } }
return BackfillsMetadata(backfills)
}
private fun BackfillRegistration.toMetadata() = BackfillMetadata(
name = name,
description = description,
parametersClass = parametersClass.simpleName,
)
}
| 50
|
Kotlin
|
49
| 31
|
5d9f39a12fd4dc95533889978d70b043a817b287
| 1,335
|
backfila
|
Apache License 2.0
|
ui/lists-edit/src/main/java/com/gnoemes/shimori/lists_edit/ListsEditSheet.kt
|
gnoemes
| 213,210,354
| false
| null |
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.*
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInParent
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.annotation.ExperimentalCoilApi
import coil.compose.rememberImagePainter
import com.gnoemes.shimori.common.compose.LocalShimoriRateUtil
import com.gnoemes.shimori.common.compose.LocalShimoriTextCreator
import com.gnoemes.shimori.common.compose.noRippleClickable
import com.gnoemes.shimori.common.compose.theme.ShimoriDefaultRoundedCornerShape
import com.gnoemes.shimori.common.compose.theme.ShimoriSmallestRoundedCornerShape
import com.gnoemes.shimori.common.compose.ui.*
import com.gnoemes.shimori.common.extensions.rememberStateWithLifecycle
import com.gnoemes.shimori.lists_edit.ListEditInputState
import com.gnoemes.shimori.lists_edit.ListsEditViewModel
import com.gnoemes.shimori.lists_edit.R
import com.gnoemes.shimori.lists_edit.UiEvents
import com.gnoemes.shimori.model.common.ShimoriImage
import com.gnoemes.shimori.model.rate.RateStatus
import com.gnoemes.shimori.model.rate.RateTargetType
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
@Composable
fun ListsEdit(
bottomSheetOffset: State<Float>,
navigateUp: () -> Unit
) {
ListsEdit(
viewModel = hiltViewModel(),
bottomSheetOffset = bottomSheetOffset,
navigateUp = navigateUp
)
}
@Composable
private fun ListsEdit(
viewModel: ListsEditViewModel,
bottomSheetOffset: State<Float>,
navigateUp: () -> Unit
) {
val state by rememberStateWithLifecycle(viewModel.state)
LaunchedEffect(viewModel) {
viewModel.uiEvents.collect {
when (it) {
UiEvents.NavigateUp -> navigateUp()
}
}
}
ListEdit(
bottomSheetOffset = bottomSheetOffset,
inputState = state.inputState,
titleName = state.name,
image = state.image,
status = state.status,
progress = state.progress,
size = state.size,
rewatches = state.rewatches,
score = state.score,
comment = state.comment,
type = state.type,
newRate = state.newRate,
pinned = state.pinned,
onStatusChanged = viewModel::onStatusChanged,
onProgressChanged = viewModel::onProgressChanged,
onRewatchesChanged = viewModel::onRewatchesChanged,
onScoreChanged = viewModel::onScoreChanged,
onProgressEdit = viewModel::onProgressInput,
onRewatchesEdit = viewModel::onRewatchingInput,
onCommentEdit = viewModel::onCommentInput,
onCommentChanged = viewModel::onCommentChanged,
onDefaultInputState = viewModel::onNoneInput,
onDelete = viewModel::delete,
onSave = viewModel::createOrUpdate,
onTogglePin = viewModel::togglePin,
)
}
@OptIn(ExperimentalAnimationApi::class)
@Composable
private fun ListEdit(
bottomSheetOffset: State<Float>,
inputState: ListEditInputState,
titleName: String,
image: ShimoriImage?,
status: RateStatus,
progress: Int,
size: Int?,
rewatches: Int,
score: Int?,
comment: String?,
type: RateTargetType,
newRate: Boolean,
pinned: Boolean,
onStatusChanged: (RateStatus) -> Unit,
onProgressChanged: (Int) -> Unit,
onRewatchesChanged: (Int) -> Unit,
onScoreChanged: (Int?) -> Unit,
onProgressEdit: () -> Unit,
onRewatchesEdit: () -> Unit,
onCommentEdit: () -> Unit,
onDefaultInputState: () -> Unit,
onCommentChanged: (String?) -> Unit,
onDelete: () -> Unit,
onSave: () -> Unit,
onTogglePin: () -> Unit,
) {
val offset = remember { mutableStateOf(0) }
SheetLayout(
modifier = Modifier
.navigationBarsPadding()
.imePadding(),
offset = offset,
bottomSheetOffset = bottomSheetOffset,
bottomBar = {
if (inputState == ListEditInputState.None) {
BottomBar(
modifier = Modifier
.height(84.dp)
.align(Alignment.BottomCenter)
.offset { IntOffset(0, offset.value) },
newRate = newRate,
pinned = pinned,
onDelete = onDelete,
onSave = onSave,
onTogglePin = onTogglePin
)
}
}
) {
Column {
BottomSheetThumb()
val title = when (inputState) {
ListEditInputState.Progress -> stringResource(id = R.string.progress)
ListEditInputState.Rewatching -> stringResource(id = R.string.re_watches)
ListEditInputState.Comment -> stringResource(id = R.string.note)
else -> titleName
}
val progressText = when {
inputState != ListEditInputState.Progress -> null
progress == size -> null
else -> stringResource(
id = R.string.left_format,
size?.let { it - progress } ?: "?"
)
}
Title(
image = image,
text = title,
progressText = progressText
)
Spacer(modifier = Modifier.height(24.dp))
// AnimatedContent(inputState) { state ->
when (inputState) {
ListEditInputState.Progress -> ProgressInputState(
progress = progress,
size = size,
onProgressChanged = onProgressChanged,
onDefaultInputState = onDefaultInputState
)
ListEditInputState.Rewatching -> RewatchingInputState(
rewatches = rewatches,
onRewatchesChanged = onRewatchesChanged,
onDefaultInputState = onDefaultInputState
)
ListEditInputState.Comment -> CommentInputState(
comment = comment,
onCommentChanged = onCommentChanged,
onDefaultInputState = onDefaultInputState
)
else -> DefaultInputState(
titleName = titleName,
type = type,
status = status,
progress = progress,
size = size,
rewatches = rewatches,
score = score,
comment = comment,
onStatusChanged = onStatusChanged,
onProgressEdit = onProgressEdit,
onProgressChanged = onProgressChanged,
onRewatchesEdit = onRewatchesEdit,
onRewatchesChanged = onRewatchesChanged,
onScoreChanged = onScoreChanged,
onCommentEdit = onCommentEdit,
)
}
// }
}
}
}
@Composable
private fun DefaultInputState(
titleName: String,
type: RateTargetType,
status: RateStatus,
progress: Int,
size: Int?,
rewatches: Int,
score: Int?,
comment: String?,
onStatusChanged: (RateStatus) -> Unit,
onProgressEdit: () -> Unit,
onProgressChanged: (Int) -> Unit,
onRewatchesEdit: () -> Unit,
onRewatchesChanged: (Int) -> Unit,
onScoreChanged: (Int?) -> Unit,
onCommentEdit: () -> Unit,
) {
Column(
verticalArrangement = Arrangement.spacedBy(24.dp)
) {
StatusSelector(
initialized = titleName.isNotEmpty(),
type = type,
selectedStatus = status,
onStatusChanged = onStatusChanged
)
ProgressBoxes(
progress = progress,
size = size,
onProgressChanged = onProgressChanged,
onProgressEdit = onProgressEdit,
rewatches = rewatches,
onRewatchesChanged = onRewatchesChanged,
onRewatchesEdit = onRewatchesEdit
)
Rating(
score = score,
onScoreChanged = onScoreChanged
)
Note(
comment = comment,
onCommentEdit = onCommentEdit
)
Spacer(
modifier = Modifier
.height(36.dp)
.navigationBarsPadding()
)
}
}
@Composable
private fun ProgressInputState(
progress: Int,
size: Int?,
onProgressChanged: (Int) -> Unit,
onDefaultInputState: () -> Unit
) {
Column(
Modifier.padding(horizontal = 16.dp)
) {
var progressState by remember(progress) { mutableStateOf(progress) }
ProgressInput(
progress = progressState,
size = size,
onChangedLocal = { progressState = it },
onCommit = { onProgressChanged(progressState) }
)
EditButtons(
onDefaultInputState = {
onDefaultInputState()
progressState = progress
},
onChangeAccept = {
onProgressChanged(progressState)
onDefaultInputState()
},
)
}
}
@Composable
private fun RewatchingInputState(
rewatches: Int,
onRewatchesChanged: (Int) -> Unit,
onDefaultInputState: () -> Unit
) {
Column(
Modifier.padding(horizontal = 16.dp)
) {
var rewatchesState by remember(rewatches) { mutableStateOf(rewatches) }
RewatchesInput(
rewatches = rewatchesState,
onChangedLocal = { rewatchesState = it },
onCommit = { onRewatchesChanged(rewatchesState) }
)
EditButtons(
onDefaultInputState = onDefaultInputState,
onChangeAccept = {
onRewatchesChanged(rewatchesState)
onDefaultInputState()
},
)
}
}
@Composable
private fun CommentInputState(
comment: String?,
onCommentChanged: (String?) -> Unit,
onDefaultInputState: () -> Unit
) {
Column(
Modifier.padding(horizontal = 16.dp)
) {
var commentState by remember(comment) { mutableStateOf(comment) }
CommentInput(
commentState,
onChangedLocal = { commentState = it },
onCommit = { onCommentChanged(commentState) }
)
EditButtons(
onDefaultInputState = onDefaultInputState,
onChangeAccept = {
onCommentChanged(commentState)
onDefaultInputState()
},
)
}
}
@OptIn(ExperimentalCoilApi::class)
@Composable
private fun Title(
image: ShimoriImage?,
text: String,
progressText: String?
) {
Row(
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 16.dp)
) {
Box(
modifier = Modifier.size(24.dp)
) {
Image(
modifier = Modifier
.fillMaxSize()
.clip(ShimoriSmallestRoundedCornerShape),
painter = rememberImagePainter(image),
contentDescription = text,
contentScale = ContentScale.Crop
)
}
val modifier =
if (progressText.isNullOrEmpty()) Modifier.weight(1f)
else Modifier
Text(
modifier = modifier,
text = text,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onBackground,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
AnimatedVisibility(visible = !progressText.isNullOrEmpty()) {
Text(
text = progressText.orEmpty(),
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.secondary,
)
}
}
}
@Composable
private fun StatusSelector(
initialized: Boolean,
type: RateTargetType,
selectedStatus: RateStatus,
onStatusChanged: (RateStatus) -> Unit
) {
val statuses = RateStatus.listPagesOrder
val scrollState = rememberScrollState()
var initialScrolled by remember { mutableStateOf(false) }
val offset = with(LocalDensity.current) {
16.dp.roundToPx()
}
val coroutineScope = rememberCoroutineScope()
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.selectableGroup()
.horizontalScroll(scrollState)
.animateContentSize()
) {
Spacer(modifier = Modifier.width(8.dp))
statuses.forEach { status ->
ShimoriChip(
onClick = { onStatusChanged(status) },
text = LocalShimoriTextCreator.current.rateStatusText(type, status),
selected = status == selectedStatus,
modifier = Modifier
.height(32.dp)
.onGloballyPositioned { coordinates ->
if (initialized && !initialScrolled && status == selectedStatus) {
coroutineScope.launch {
val pixelPosition =
coordinates.positionInParent().x.roundToInt()
scrollState.scrollTo(pixelPosition - offset)
}
initialScrolled = true
}
},
icon = {
Icon(
modifier = Modifier.size(16.dp),
painter = painterResource(LocalShimoriRateUtil.current.rateStatusIcon(status)),
contentDescription = null
)
}
)
}
Spacer(modifier = Modifier.width(8.dp))
}
}
@Composable
private fun ProgressBoxes(
progress: Int,
size: Int?,
onProgressChanged: (Int) -> Unit,
onProgressEdit: () -> Unit,
rewatches: Int,
onRewatchesChanged: (Int) -> Unit,
onRewatchesEdit: () -> Unit
) {
Row(
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.horizontalScroll(rememberScrollState())
) {
Spacer(modifier = Modifier.width(4.dp))
Progress(
progress = progress,
size = size,
onProgressChanged = onProgressChanged,
onEditClicked = onProgressEdit
)
Rewatches(
rewatches = rewatches,
onRewatchesChanged = onRewatchesChanged,
onEditClicked = onRewatchesEdit
)
Spacer(modifier = Modifier.width(4.dp))
}
}
@Composable
private fun Progress(
progress: Int,
size: Int?,
onProgressChanged: (Int) -> Unit,
onEditClicked: () -> Unit,
) {
ProgressBox(
onEditClicked = onEditClicked
) {
Column {
Text(
text = stringResource(id = R.string.progress),
style = MaterialTheme.typography.labelLarge,
)
Spacer(modifier = Modifier.height(12.dp))
val progressText = stringResource(
R.string.progress_format,
progress,
size.let { if (it == null || it == 0) "?" else "$it" }
)
Row(
verticalAlignment = Alignment.Bottom,
modifier = Modifier.weight(1f)
) {
CompositionLocalProvider(
LocalContentColor provides MaterialTheme.colorScheme.primary
) {
ValueWithIncrementDecrementButtons(
progressText = progressText,
value = progress,
decrementEnabled = progress - 1 >= 0,
incrementEnabled = progress + 1 <= size ?: Integer.MAX_VALUE,
onDecrementClick = onProgressChanged,
onIncrementClick = onProgressChanged,
)
}
}
}
}
}
@Composable
private fun Rewatches(
rewatches: Int,
onRewatchesChanged: (Int) -> Unit,
onEditClicked: () -> Unit,
) {
ProgressBox(
onEditClicked = onEditClicked
) {
Column {
Text(
text = stringResource(id = R.string.re_watches),
style = MaterialTheme.typography.labelLarge,
)
Spacer(modifier = Modifier.height(12.dp))
Row(
verticalAlignment = Alignment.Bottom,
modifier = Modifier.weight(1f)
) {
CompositionLocalProvider(
LocalContentColor provides MaterialTheme.colorScheme.primary
) {
ValueWithIncrementDecrementButtons(
progressText = "$rewatches",
value = rewatches,
decrementEnabled = rewatches - 1 >= 0,
incrementEnabled = true,
onDecrementClick = onRewatchesChanged,
onIncrementClick = onRewatchesChanged,
)
}
}
}
}
}
@Composable
private fun Rating(
score: Int?,
onScoreChanged: (Int?) -> Unit
) {
RatingBar(
rating = (score ?: 0) / 2f,
modifier = Modifier
.height(40.dp)
.fillMaxWidth()
.padding(horizontal = 16.dp),
onRatingChanged = { rating -> onScoreChanged((rating * 2f).roundToInt()) }
)
}
@Composable
private fun ProgressBox(
onEditClicked: () -> Unit,
content: @Composable () -> Unit
) {
var boxSize by remember { mutableStateOf(0) }
Box(
modifier = Modifier
.background(MaterialTheme.colorScheme.surfaceVariant, ShimoriDefaultRoundedCornerShape)
.border(
1.dp,
MaterialTheme.colorScheme.outline.copy(alpha = 0.12f),
ShimoriDefaultRoundedCornerShape
)
.height(80.dp)
.width(240.dp)
.padding(horizontal = 16.dp, vertical = 12.dp)
.pointerInput(onEditClicked) {
detectTapGestures(
onTap = {
if (it.x <= boxSize / 2) {
onEditClicked()
}
}
)
}
.onGloballyPositioned {
boxSize = it.size.width
},
contentAlignment = Alignment.CenterStart
) {
CompositionLocalProvider(LocalContentColor provides contentColorFor(MaterialTheme.colorScheme.surfaceVariant)) {
content()
}
}
}
@OptIn(ExperimentalAnimationApi::class)
@Composable
private fun RowScope.ValueWithIncrementDecrementButtons(
progressText: String,
value: Int,
decrementEnabled: Boolean,
incrementEnabled: Boolean,
onDecrementClick: (newValue: Int) -> Unit,
onIncrementClick: (newValue: Int) -> Unit,
) {
Text(
text = progressText,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.primary,
)
Spacer(modifier = Modifier.weight(1f))
IconButton(
onClick = { onDecrementClick(value - 1) },
enabled = decrementEnabled,
modifier = Modifier.size(32.dp)
) {
Icon(painter = painterResource(id = R.drawable.ic_remove), contentDescription = null)
}
Spacer(modifier = Modifier.width(24.dp))
IconButton(
onClick = { onIncrementClick(value + 1) },
enabled = incrementEnabled,
modifier = Modifier.size(32.dp)
) {
Icon(painter = painterResource(id = R.drawable.ic_add), contentDescription = null)
}
}
private val numberRegex = "(?![0-9]{1,4})".toRegex()
@Composable
private fun BottomBar(
modifier: Modifier,
newRate: Boolean,
pinned: Boolean,
onDelete: () -> Unit,
onSave: () -> Unit,
onTogglePin: () -> Unit
) {
Surface(
modifier = modifier,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
IconButton(
onClick = onDelete,
modifier = Modifier.size(32.dp),
enabled = !newRate
) {
Icon(
painter = painterResource(id = R.drawable.ic_delete),
contentDescription = null
)
}
ShimoriConformationButton(
onClick = onSave,
text = stringResource(id = if (newRate) R.string.add else R.string.save),
type = ConfirmationButtonType.Primary,
modifier = Modifier
.weight(1f)
.height(IntrinsicSize.Min)
)
IconButton(
onClick = onTogglePin,
modifier = Modifier.size(32.dp),
) {
Icon(
painter = painterResource(id = R.drawable.ic_pin),
contentDescription = null,
tint =
if (pinned) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurface
)
}
}
}
}
@Composable
private fun Note(
comment: String?,
onCommentEdit: () -> Unit
) {
val text =
if (!comment.isNullOrEmpty()) comment
else stringResource(id = R.string.add_note)
Box(
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 48.dp)
.padding(horizontal = 16.dp)
.noRippleClickable { onCommentEdit() }
) {
Text(
text = text,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
.fillMaxWidth(),
)
}
}
@Composable
private fun ProgressInput(
progress: Int,
size: Int?,
onChangedLocal: (Int) -> Unit,
onCommit: () -> Unit
) {
NumberInput(
value = progress,
limit = size,
onChangedLocal = onChangedLocal,
onCommit = onCommit
)
}
@Composable
private fun RewatchesInput(
rewatches: Int,
onChangedLocal: (Int) -> Unit,
onCommit: () -> Unit
) {
NumberInput(
value = rewatches,
limit = null,
onChangedLocal = onChangedLocal,
onCommit = onCommit
)
}
@Composable
private fun NumberInput(
value: Int,
limit: Int?,
onChangedLocal: (Int) -> Unit,
onCommit: () -> Unit
) {
val valueLimit = limit ?: Integer.MAX_VALUE
val focusRequester = remember { FocusRequester() }
LaunchedEffect(focusRequester) {
focusRequester.requestFocus()
}
ShimoriTextField(
value = "$value",
textStyle = MaterialTheme.typography.labelLarge,
onValueChange = { text ->
val nums = text.replace(numberRegex, "")
val intValue = nums.toIntOrNull()
if (nums.isNotEmpty() && nums.length <= 4 && intValue != null && intValue <= valueLimit) {
onChangedLocal(intValue)
} else if (nums.isEmpty()) {
onChangedLocal(0)
} else if (intValue != null && intValue > valueLimit) {
onChangedLocal(valueLimit)
}
},
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 10.dp, max = 150.dp)
.focusRequester(focusRequester),
cursorColor = MaterialTheme.colorScheme.primary,
keyboardActions = KeyboardActions(onDone = { onCommit() }),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
)
}
@Composable
private fun CommentInput(
comment: String?,
onChangedLocal: (String) -> Unit,
onCommit: () -> Unit
) {
val focusRequester = remember { FocusRequester() }
LaunchedEffect(focusRequester) {
focusRequester.requestFocus()
}
ShimoriTextField(
value = comment.orEmpty(),
textStyle = MaterialTheme.typography.labelLarge,
onValueChange = onChangedLocal,
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 10.dp, max = 150.dp)
.focusRequester(focusRequester),
keyboardActions = KeyboardActions(onDone = { onCommit() }),
hint = {
Text(
text = stringResource(id = R.string.add_note),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.12f)
)
}
)
}
@Composable
private fun EditButtons(
onDefaultInputState: () -> Unit,
onChangeAccept: () -> Unit
) {
Row(
modifier = Modifier.padding(vertical = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurface) {
IconButton(
onClick = onDefaultInputState,
modifier = Modifier.size(32.dp),
) {
Icon(
painter = painterResource(id = R.drawable.ic_back),
contentDescription = null
)
}
Spacer(modifier = Modifier.weight(1f))
IconButton(
onClick = onChangeAccept,
modifier = Modifier.size(32.dp),
) {
Icon(
painter = painterResource(id = R.drawable.ic_completed),
contentDescription = null
)
}
}
}
}
@Composable
private fun SheetLayout(
modifier: Modifier,
offset: MutableState<Int>,
bottomSheetOffset: State<Float>,
bottomBar: @Composable BoxWithConstraintsScope.() -> Unit,
content: @Composable () -> Unit,
) {
var parentHeight by remember { mutableStateOf(0) }
val navigationBarHeight = WindowInsets.navigationBars.getBottom(LocalDensity.current)
BoxWithConstraints(
modifier = modifier then Modifier
.onGloballyPositioned {
parentHeight = it.size.height
}
) {
content()
val screenHeight = constraints.maxHeight + navigationBarHeight
val bottomSheetOffsetValue = bottomSheetOffset.value.roundToInt()
offset.value = if (screenHeight / 2 <= bottomSheetOffsetValue) {
//snap to parent
-parentHeight + screenHeight / 2 - navigationBarHeight
} else {
val visiblePart = screenHeight - bottomSheetOffsetValue
//fixed offset at bottom screen
-parentHeight + visiblePart - navigationBarHeight
}
bottomBar()
}
}
| 0
|
Kotlin
|
0
| 9
|
7a8373881e2abc29be51a2030ddfd329d9928d80
| 28,537
|
Shimori
|
Apache License 2.0
|
app/src/main/java/com/github/firenox89/shinobooru/service/ShinoboorusWallpaperService.kt
|
Firenox89
| 61,946,482
| false
| null |
package com.github.firenox89.shinobooru.service
import android.content.Context
import android.graphics.*
import android.graphics.Paint.ANTI_ALIAS_FLAG
import android.service.wallpaper.WallpaperService
import android.util.Size
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.SurfaceHolder
import com.github.firenox89.shinobooru.repo.FileManager
import com.github.firenox89.shinobooru.repo.model.DownloadedPost
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import org.koin.android.ext.android.inject
import org.koin.core.KoinComponent
import timber.log.Timber
/**
* Creates a live wallpaper that uses the downloaded posts as homescreen backgrounds.
* The wallpaper changes on every time the homescreen gets visible(like when minimizing an app or turn on the screen).
* Also landscape and portray mode get a different set of wallpapers.
*/
class ShinoboorusWallpaperService : WallpaperService() {
override fun onCreateEngine(): Engine = ShinoboorusWallpaperEngine(applicationContext)
companion object {
val black = Paint().apply {
color = 0x000000
alpha = 255
}
//smooths the scaled image while drawing
val filter = Paint().apply {
isAntiAlias = true
isFilterBitmap = true
isDither = true
}
}
/**
* The engine drawing on te live wallpaper.
*/
inner class ShinoboorusWallpaperEngine(applicationContext: Context) : Engine(), KoinComponent {
//TODO: make the wallpaperService more configurable
private var displayWidth: Int = 0
private var displayHeight: Int = 0
private val drawRequestQueue = Channel<() -> Unit>()
private val fileManager: FileManager by inject()
private lateinit var gestureDetector: GestureDetector
override fun onCreate(surfaceHolder: SurfaceHolder?) {
super.onCreate(surfaceHolder)
Timber.w("TODO Implement double click listener")
val listener = object : GestureDetector.SimpleOnGestureListener() {
override fun onDoubleTap(e: MotionEvent?): Boolean {
draw()
return true
}
}
gestureDetector = GestureDetector(applicationContext, listener)
GlobalScope.launch {
for (drawCall in drawRequestQueue) {
drawCall.invoke()
}
}
}
/**
* Issue a draw call on a visibility change.
*
* @param visible gets ignored.
*/
override fun onVisibilityChanged(visible: Boolean) {
//hide drawing through doing it when invisible
if (!visible)
draw()
}
override fun onTouchEvent(event: MotionEvent?) {
gestureDetector.onTouchEvent(event)
}
/**
* Gets called on display rotation, sets new display width and height and issues a draw request.
* Calls super method.
*
* @param holder gets ignored
* @param format gets ignored
* @param width will be set as new [displayWidth]
* @param height will be set as new [displayHeight]
*/
override fun onSurfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
displayWidth = width
displayHeight = height
GlobalScope.launch { draw() }
super.onSurfaceChanged(holder, format, width, height)
}
/**
* Draws an image fitting the current rotation and draws it to the canvas obtained from the surface.
*/
private fun draw() {
drawRequestQueue.offer {
try {
//stop if surface got invalid
if (isSurfaceInvalid()) return@offer
val canvas = surfaceHolder.lockCanvas() ?: return@offer
//clear previous drawing
canvas.drawPaint(black)
val image = pickImage()
val transformationInfo = calcTransformation(image)
if (isSurfaceInvalid()) return@offer
//scales image
canvas.translate(transformationInfo.second.width.toFloat() / 2,
transformationInfo.second.height.toFloat() / 2)
if (isSurfaceInvalid()) return@offer
//draws scaled image
canvas.drawBitmap(image, transformationInfo.first, filter)
if (isSurfaceInvalid()) return@offer
//TODO this sometimes crashes when setting this as lockscreen
surfaceHolder.unlockCanvasAndPost(canvas)
image.recycle()
} catch (OoM: OutOfMemoryError) {
OoM.printStackTrace()
} catch (iae: IllegalArgumentException) {
//unlockCanvasAndPost throws this in the wallpaper chooser
iae.printStackTrace()
}
}
}
/**
* Returns true if surface is invalid
*/
private fun isSurfaceInvalid(): Boolean = !surfaceHolder.surface.isValid
/**
* Calculates the scaling factors, apply the scaling to a transformation matrix,
* calculates the drawing offsets and retrun them as a pair.
*
* @param image to calculate the transformation and offset for
*
* @return a [Pair] containing the matrix and offset
*/
private fun calcTransformation(image: Bitmap): Pair<Matrix, Size> {
val width = image.width
val height = image.height
val ratioBitmap = width.toFloat() / height.toFloat()
val ratioDisplay = displayWidth.toFloat() / displayHeight.toFloat()
var finalWidth = displayWidth
var finalHeight = displayHeight
//in landscape mode takes full display width and calculate height according to the image ration,
//in portray mode its the other way around, since images are picked according to the screen rotation
//we don't have to border about the case where image and display ratios are not both above or below 1
if (ratioDisplay > 1) {
//landscape mode
finalWidth = (displayHeight.toFloat() * ratioBitmap).toInt()
} else {
//portray mode
finalHeight = (displayWidth.toFloat() / ratioBitmap).toInt()
}
if (finalWidth > displayWidth) {
finalHeight = (displayWidth.toFloat() / ratioBitmap).toInt()
finalWidth = displayWidth
}
if (finalHeight > displayHeight) {
finalWidth = (displayHeight.toFloat() * ratioBitmap).toInt()
finalHeight = displayHeight
}
//get scaling factors
val scaleX = finalWidth.toFloat() / width.toFloat()
val scaleY = finalHeight.toFloat() / height.toFloat()
val matrix = Matrix()
matrix.postScale(scaleX, scaleY)
//merge matrix and offset inside a pair
return Pair(matrix, Size(displayWidth - finalWidth, displayHeight - finalHeight))
}
/**
* Picks a random image and checks if the image ratio fits the display ratio.
*
* @return a loaded [Bitmap] fitting for the display ratio.
*/
private fun pickImage(): Bitmap {
if (fileManager.getAllDownloadedPosts().isEmpty())
return genNoImagesBitmap()
//TODO stop looping when no image with a fitting ration is present
//picks random image
var post = pickRandomPost()
//load image bounds from file
var bounds = getBounds(post.file.absolutePath)
//landscape or portray?
if (displayWidth > displayHeight) {
//while not fitting try new image
while (bounds.width < bounds.height) {
post = pickRandomPost()
bounds = getBounds(post.file.absolutePath)
}
} else {
//while not fitting try new image
while (bounds.width > bounds.height) {
post = pickRandomPost()
bounds = getBounds(post.file.absolutePath)
}
}
val options = BitmapFactory.Options()
if (bounds.width > displayWidth * 2 && bounds.height > displayHeight * 2)
options.inSampleSize = 2
return BitmapFactory.decodeFile(post.file.absolutePath, options)
}
/**
* Picks a random image from the image list.
*
* @return a random post.
*/
private fun pickRandomPost(): DownloadedPost {
//TODO handle 0 images case
val postList = fileManager.getAllDownloadedPosts()
var i = (Math.random() * postList.size).toInt()
return postList[i]
}
/**
* Load the image bounds from a given path.
*
* @param path to the image
* @return size of the image
*/
private fun getBounds(path: String): Size {
//don't load whole image just bounds
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeFile(path, options)
return Size(options.outWidth, options.outHeight)
}
fun genNoImagesBitmap(): Bitmap {
val text = "No Images to display."
val paint = Paint(ANTI_ALIAS_FLAG)
paint.textSize = 24f
paint.color = Color.WHITE
paint.textAlign = Paint.Align.LEFT
val baseline = -paint.ascent() // ascent() is negative
val width = (paint.measureText(text) + 0.5f).toInt() // round
val height = (baseline + paint.descent() + 0.5f).toInt()
val image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(image)
canvas.drawPaint(black)
canvas.drawText(text, 0f, baseline, paint)
return image
}
}
}
| 1
|
Kotlin
|
2
| 6
|
eccf4688b861f0df7feeb72084064c5cf84759f2
| 10,508
|
Shinobooru
|
MIT License
|
app/src/main/java/com/hulkrent/app/host/payout/addPayout/AddPayoutViewModel.kt
|
Hulk-Cars
| 772,120,218
| false
|
{"Kotlin": 2511410, "Java": 358761}
|
package com.hulkrent.app.host.payout.addPayout
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.hulkrent.app.*
import com.hulkrent.app.data.DataManager
import com.hulkrent.app.ui.base.BaseViewModel
import com.hulkrent.app.util.Utils
import com.hulkrent.app.util.performOnBackOutOnMain
import com.hulkrent.app.util.resource.ResourceProvider
import com.hulkrent.app.util.rx.Scheduler
import com.hulkrent.app.vo.Payout
import com.stripe.android.ApiResultCallback
import com.stripe.android.Stripe
import com.stripe.android.model.AccountParams
import com.stripe.android.model.Address
import com.stripe.android.model.PersonTokenParams
import com.stripe.android.model.Token
import org.json.JSONObject
import timber.log.Timber
import javax.inject.Inject
class AddPayoutViewModel @Inject constructor(
dataManager: DataManager,
val scheduler: Scheduler,
val resourceProvider: ResourceProvider
) : BaseViewModel<AddPayoutNavigator>(dataManager, resourceProvider) {
val firstName = ObservableField("")
val accountType = ObservableField(resourceProvider.getString(R.string.individual))
val lastNameVisible = MutableLiveData<Boolean>()
val lastName = ObservableField("")
val account = ObservableField("")
val cnfAccount = ObservableField("")
val ssn = ObservableField("")
val routingNo = ObservableField("")
val country = ObservableField("")
val countryCode = ObservableField("")
val address1 = ObservableField("")
val address2 = ObservableField("")
val city = ObservableField("")
val state = ObservableField("")
val zip = ObservableField("")
val listPref = ObservableField("")
val email = ObservableField("")
val currency = ObservableField("")
var isDOB = false
var connectingURL: String = ""
var accountID: String = ""
var onRetryCalled: String = ""
private var personToken: String? = null
private lateinit var accountToken: String
lateinit var stripe: Stripe
lateinit var list: MutableLiveData<List<GetCountrycodeQuery.Result>>
val listSearch = MutableLiveData<ArrayList<GetCountrycodeQuery.Result>>()
lateinit var payoutsList: MutableLiveData<ArrayList<Payout>>
val europeCountries = listOf(
"AT", "BE", "BG", "CY", "CZ", "DK", "EE",
"FI", "FR", "DE", "GR", "HU", "IE", "IT",
"LV", "LT", "LU", "MT", "NL", "NO", "PL",
"PT", "RO", "SK", "SI", "ES", "SE", "CH"
)
lateinit var paymentMethods: MutableLiveData<List<GetPaymentMethodsQuery.Result>>
init {
isDOB = dataManager.isDOB!!
listPref.set(resourceProvider.getString(R.string.individual))
}
fun loadPayoutMethods(): MutableLiveData<List<GetPaymentMethodsQuery.Result>> {
if (!::paymentMethods.isInitialized) {
paymentMethods = MutableLiveData()
getPayoutMethods()
}
return paymentMethods
}
fun loadCountryCode(): MutableLiveData<List<GetCountrycodeQuery.Result>> {
if (!::list.isInitialized) {
list = MutableLiveData()
getCountryCode()
} else {
list = MutableLiveData()
getCountryCode()
}
return list
}
fun getCountryCode() {
val query = GetCountrycodeQuery
.builder()
.build()
compositeDisposable.add(dataManager.getCountryCode(query)
.doOnSubscribe { setIsLoading(true) }
.doFinally { setIsLoading(false) }
.performOnBackOutOnMain(scheduler)
.subscribe({ response ->
try {
val data = response.data()!!.countries
if (data?.status() == 200) {
list.value = response.data()!!.countries!!.results()
} else {
navigator.showError()
}
} catch (e: Exception) {
e.printStackTrace()
navigator.showError()
}
}, {
handleException(it)
})
)
}
fun checkPaypalInfo(): Boolean {
if (email.get()!!.trim().isNotBlank()) {
if (Utils.isValidEmail(email.get()!!)) {
if (currency.get()!!.isNotBlank()) {
return true
} else navigator.showToast(resourceProvider.getString(R.string.please_select_currency))
} else navigator.showToast(resourceProvider.getString(R.string.please_enter_valid_email_address))
} else navigator.showToast(resourceProvider.getString(R.string.please_enter_email_address))
return false
}
fun checkAccountInfo(): Boolean {
if(country.get()!!.trim().isNotBlank()) {
if (address1.get()!!.trim().isNotBlank()) {
if (city.get()!!.trim().isNotBlank()) {
if (state.get()!!.trim().isNotBlank()) {
if (zip.get()!!.isNotBlank()) {
return true
} else navigator.showToast(resourceProvider.getString(R.string.please_enter_zip_code))
} else navigator.showToast(resourceProvider.getString(R.string.please_enter_the_state))
} else navigator.showToast(resourceProvider.getString(R.string.please_enter_city))
} else navigator.showToast(resourceProvider.getString(R.string.please_enter_address_1))
}else navigator.showToast(resourceProvider.getString(R.string.please_choose_country_toast))
return false
}
fun checkAccountDetails(): Boolean {
if (accountType.get() == "Individual") {
if (!accountType.get()!!.trim()
.equals(resourceProvider.getString(R.string.account_type))
) {
if (firstName.get()!!.trim().isNotBlank()) {
if (lastName.get()!!.trim().isNotBlank()) {
if (routingNo.get()!!.trim().isNotBlank() || (europeCountries.contains(
countryCode.get()
) || countryCode.get() == "MX" || countryCode.get() == "NZ")
) {
if (account.get()!!.trim().isNotBlank()) {
if (cnfAccount.get()!!.trim().isNotBlank()) {
if (account.get()!! == cnfAccount.get()!!) {
return true
} else navigator.showToast(
resourceProvider.getString(
R.string.please_enter_correct_confirm_account_number,
checkCountryAndReturn()
)
)
} else navigator.showToast(
resourceProvider.getString(
R.string.please_enter_confirm_account_number,
checkCountryAndReturn()
)
)
} else navigator.showToast(
resourceProvider.getString(
R.string.please_enter_account_number,
checkCountryAndReturn()
)
)
} else navigator.showToast(
(if (countryCode.get() == "UK" || countryCode.get() == "GB") resourceProvider.getString(
R.string.please_enter_sort_number
) else resourceProvider.getString(R.string.please_enter_routing_number))
)
} else navigator.showToast(resourceProvider.getString(R.string.please_enter_last_name))
} else navigator.showToast(resourceProvider.getString(R.string.please_enter_first_name))
} else navigator.showToast(resourceProvider.getString(R.string.account_type_error))
return false
} else {
if (!accountType.get()!!.trim()
.equals(resourceProvider.getString(R.string.account_type))
) {
if (firstName.get()!!.trim().isNotBlank()) {
if (routingNo.get()!!.trim().isNotBlank() || (europeCountries.contains(
countryCode.get()
) || countryCode.get() == "MX" || countryCode.get() == "NZ")
) {
if (account.get()!!.trim().isNotBlank()) {
if (cnfAccount.get()!!.trim().isNotBlank()) {
if (account.get()!! == cnfAccount.get()!!) {
return true
} else navigator.showToast(
resourceProvider.getString(
R.string.please_enter_correct_confirm_account_number,
checkCountryAndReturn()
)
)
} else navigator.showToast(
resourceProvider.getString(
R.string.please_enter_confirm_account_number,
checkCountryAndReturn()
)
)
} else navigator.showToast(
resourceProvider.getString(
R.string.please_enter_account_number,
checkCountryAndReturn()
)
)
} else navigator.showToast(
if (countryCode.get() == "UK" || countryCode.get() == "GB") resourceProvider.getString(
R.string.please_enter_sort_number
) else resourceProvider.getString(R.string.please_enter_routing_number)
)
} else navigator.showToast(resourceProvider.getString(R.string.please_enter_first_name))
} else navigator.showToast(resourceProvider.getString(R.string.account_type_error))
return false
}
}
fun getResultAccountToken(type: Int, accountHashMap: HashMap<String, String>) {
setIsLoading(true)
val payoutEmail: String = if (email.get()!!.isEmpty()) {
dataManager.currentUserEmail.toString()
} else {
email.get()!!
}
val accountParams: AccountParams =
if (accountHashMap["accountHolderType"] == resourceProvider.getString(R.string.individual)) {
AccountParams.create(
true,
AccountParams.BusinessTypeParams.Individual(
firstName = accountHashMap["firstName"],
lastName = accountHashMap["lastName"],
email = payoutEmail,
address = Address.fromJson(JSONObject("""{"city": "${accountHashMap["city"]}","country": "${accountHashMap["country"]}","line1": "${accountHashMap["line1"]}","line2": "${accountHashMap["line2"]}","postal_code": "${accountHashMap["postal_code"]}","state": "${accountHashMap["state"]}"}"""))
)
)
} else {
AccountParams.create(
true,
AccountParams.BusinessTypeParams.Company(
name = accountHashMap["firstName"],
address = Address.fromJson(JSONObject("""{"city": "${accountHashMap["city"]}","country": "${accountHashMap["country"]}","line1": "${accountHashMap["line1"]}","line2": "${accountHashMap["line2"]}","postal_code": "${accountHashMap["postal_code"]}","state": "${accountHashMap["state"]}"}"""))
)
)
}
stripe.createAccountToken(accountParams, callback = object : ApiResultCallback<Token> {
override fun onError(e: Exception) {
Timber.e(e, e.message)
navigator.showToast(e.message ?: "Token Error")
setIsLoading(false)
}
override fun onSuccess(result: Token) {
// channelResult.success(result.id)
accountToken = result.id
val accType: String =
if (accountType.get().equals(resourceProvider.getString(R.string.individual))) {
"individual"
} else {
"company"
}
if (accType == "company") {
val personAcc = PersonTokenParams.Builder()
.setAddress(Address.fromJson(JSONObject("""{"city": "${accountHashMap["city"]}","country": "${accountHashMap["country"]}","line1": "${accountHashMap["line1"]}","line2": "${accountHashMap["line2"]}","postal_code": "${accountHashMap["postal_code"]}","state": "${accountHashMap["state"]}"}""")))
.setEmail(payoutEmail)
.setRelationship(
PersonTokenParams.Relationship.Builder().setRepresentative(true).build()
)
.setFirstName(accountHashMap["firstName"])
.setLastName(accountHashMap["lastName"])
.build()
stripe.createPersonToken(
personAcc,
callback = object : ApiResultCallback<Token> {
override fun onError(e: Exception) {
Timber.e(e, e.message)
navigator.showToast(e.message ?: "Token Error")
setIsLoading(false)
}
override fun onSuccess(result: Token) {
personToken = result.id
addPayout(type)
setIsLoading(false)
}
})
} else {
personToken = null
addPayout(type)
setIsLoading(false)
}
}
})
}
private fun checkCountryAndReturn(): String {
return if (europeCountries.contains(countryCode.get())) resourceProvider.getString(R.string.iban_number)
else resourceProvider.getString(R.string.account_number)
}
fun addPayout(type: Int) {
var accType: String
if (accountType.get()
.equals(resourceProvider.getString(R.string.individual), ignoreCase = true)
) {
accType = "individual"
} else {
accType = "company"
}
var payoutEmail: String
if (email.get()!!.isEmpty()) {
payoutEmail = dataManager.currentUserEmail.toString()
} else {
payoutEmail = email.get()!!
}
var mutate: AddPayoutMutation
if (europeCountries.contains(countryCode.get())
.not() && (countryCode.get() != "MX" || countryCode.get() != "NZ")
) {
mutate = AddPayoutMutation
.builder()
.methodId(type)
.payEmail(payoutEmail)
.address1(address1.get()!!)
.address2(address2.get()!!)
.city(city.get()!!)
.country(countryCode.get()!!)
.state(state.get()!!)
.zipcode(zip.get()!!)
.currency(currency.get() ?: "USD")
.firstname(firstName.get()!!)
.lastname(lastName.get()!!)
.accountNumber(account.get()!!)
.routingNumber(routingNo.get()!!)
.businessType(accType)
.accountToken(if (::accountToken.isInitialized) accountToken else null)
.personToken(personToken)
.build()
} else {
mutate = AddPayoutMutation
.builder()
.methodId(type)
.payEmail(payoutEmail)
.address1(address1.get()!!)
.address2(address2.get()!!)
.city(city.get()!!)
.country(countryCode.get()!!)
.state(state.get()!!)
.zipcode(zip.get()!!)
.currency(currency.get() ?: "USD")
.firstname(firstName.get()!!)
.lastname(lastName.get()!!)
.accountNumber(account.get()!!)
.businessType(accType)
.accountToken(accountToken)
.personToken(personToken)
.build()
}
compositeDisposable.add(dataManager.addPayout(mutate)
.doOnSubscribe { setIsLoading(true) }
.doFinally { setIsLoading(false) }
.performOnBackOutOnMain(scheduler)
.subscribe({ response ->
try {
val data = response.data()!!.addPayout()
if (data?.status() == 200) {
if (type == 1) {
navigator.moveToScreen(AddPayoutActivity.Screen.FINISH)
} else {
connectingURL = data?.connectUrl()!!
accountID = data?.stripeAccountId()!!
navigator.moveToScreen(AddPayoutActivity.Screen.WEBVIEW)
navigator.moveToScreen(AddPayoutActivity.Screen.FINISH)
}
} else if (data?.status() == 400) {
navigator.showToast(data.errorMessage()!!)
} else if (data?.status() == 500) {
navigator.openSessionExpire("AddPayoutVM")
}
} catch (e: Exception) {
e.printStackTrace()
navigator.showError()
}
}, {
handleException(it)
})
)
}
fun buildTokenHashMap(): HashMap<String, String> {
val hashMap = hashMapOf<String, String>()
hashMap["firstName"] = firstName.get().toString()
hashMap["lastName"] = lastName.get().toString()
hashMap["country"] = countryCode.get().toString()
hashMap["currency"] = currency.get().toString()
hashMap["accountNumber"] = account.get().toString()
hashMap["accountHolderType"] = accountType.get().toString()
hashMap["routingNumber"] = routingNo.get().toString()
hashMap["line1"] = address1.get().toString()
hashMap["line2"] = address2.get().toString()
hashMap["city"] = city.get().toString()
hashMap["state"] = state.get().toString()
hashMap["postal_code"] = zip.get().toString()
return hashMap
}
fun setPayout() {
val query = ConfirmPayoutMutation
.builder()
.currentAccountId(accountID)
.build()
compositeDisposable.add(dataManager.setPayout(query)
.doOnSubscribe { setIsLoading(true) }
.doFinally { setIsLoading(false) }
.performOnBackOutOnMain(scheduler)
.subscribe({ response ->
try {
val data = response.data()!!.confirmPayout()
if (data!!.status() == 200) {
navigator.moveToScreen(AddPayoutActivity.Screen.FINISH)
} else {
navigator.showError()
}
} catch (e: Exception) {
e.printStackTrace()
navigator.showError()
}
}, {
handleException(it)
})
)
}
fun getPayoutMethods() {
val query = GetPaymentMethodsQuery
.builder()
.build()
compositeDisposable.add(dataManager.getPayoutsMethod(query)
.doOnSubscribe { setIsLoading(true) }
.doFinally { setIsLoading(false) }
.performOnBackOutOnMain(scheduler)
.subscribe({ response ->
try {
val data = response.data()!!.paymentMethods
if (data!!.status() == 200) {
paymentMethods.value = data.results()
} else {
if (data.errorMessage() == null) {
navigator.showError()
} else {
navigator.showToast(data.errorMessage().toString())
}
}
} catch (e: Exception) {
e.printStackTrace()
navigator.showError()
}
}, {
handleException(it)
})
)
}
fun onSearchTextChanged(text: CharSequence) {
if (text.isNotEmpty()) {
val searchText = text.toString().capitalize()
val containsItem = ArrayList<GetCountrycodeQuery.Result>()
list.value?.forEachIndexed { _, result ->
result.countryName()?.let {
if (it.contains(searchText)) {
containsItem.add(result)
}
}
}
listSearch.value = containsItem
} else {
list.value?.let {
listSearch.value = ArrayList(it)
}
}
}
fun onRoutingTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
if (s.length > 5) {
Timber.d("greater than 5")
} else {
Timber.d("lesser than 5")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9886a3455e3d404110a85cdaaf5bbff449390814
| 22,119
|
Hulk-Rent-Android
|
Artistic License 1.0 w/clause 8
|
openfoodfacts-kotlin-dev-app/shared/src/previewMain/kotlin/openfoodfacts/github/scrachx/openfood/api/SharedMainPreview.kt
|
openfoodfacts
| 541,555,488
| false
| null |
package openfoodfacts.github.scrachx.openfood.api
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import openfoodfacts.github.scrachx.openfood.api.v0.model.Product
import openfoodfacts.github.scrachx.openfood.api.v0.model.ProductResponse
import openfoodfacts.github.scrachx.openfood.api.v0.service.OpenFoodFactsClient
@Composable
fun SharedMainPreview() {
val scope = rememberCoroutineScope()
MainView(
viewModel = MainViewModel(
scope = scope,
client = previewClient
),
modifier = Modifier.fillMaxHeight()
)
}
private val previewClient = object : OpenFoodFactsClient {
override suspend fun fetchProductByCode(code: String): ProductResponse {
return ProductResponse(
product = Product(productName = "Preview"),
code = "012345",
status = 0,
statusVerbose = "Preview"
)
}
}
| 3
| null |
2
| 5
|
06c821bd142aa1c30a077e66006f9a79b8437baa
| 1,049
|
openfoodfacts-kotlin
|
Apache License 2.0
|
app/src/main/java/com/realsoc/shiby/componentization/ItemComponent.kt
|
realsoc
| 208,658,394
| false
| null |
package com.realsoc.shiby.componentization
import android.annotation.SuppressLint
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.lifecycle.LifecycleObserver
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayout
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlin.reflect.KClass
abstract class ItemComponent<V : ItemView<S>, S : Any>(
val uiView: V,
val componentId: ComponentId? = null
) : RecyclerView.ViewHolder(uiView.root) {
fun layout() {
uiView.layout()
onViewReady(uiView.root)
}
fun isSame(clazz: KClass<out Any>, componentId: ComponentId?): Boolean {
return this::class == clazz && this.componentId == componentId
}
fun isSame(other: ItemComponent<*, *>): Boolean {
return this::class == other::class && this.componentId == other.componentId
}
abstract fun onViewReady(view: View)
fun setViewState(block: S?.() -> S?) {
uiView.setState(uiView.state.run(block))
}
}
@SuppressLint("CheckResult")
abstract class ItemView<S : Any>(
private val container: ViewGroup,
private val layoutId: Int,
private val initialState: S?,
attachToContainer: Boolean?,
protected val eventBusFactory: EventBusFactory
) : LifecycleObserver {
val root: View = attachToContainer?.let { LayoutInflater.from(container.context).inflate(layoutId, container, attachToContainer) }
?: container
val asTab: TabLayout.Tab
get() = TabLayout.Tab().apply { customView = root }
var state: S? = null
private set
init {
eventBusFactory.getSafeManagedObservable(LoadingState::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe {
onLoadingStateChange(it.loading)
}
}
protected open fun onLoadingStateChange(isLoading: Boolean) {}
fun layout() {
assert(Looper.myLooper() == Looper.getMainLooper()) { "layout() should be called on the UI Thread" }
onViewCreated(root)
setState(initialState)
}
fun setState(state: S?) {
this.state = state
root.post {
onStateChange(state)
}
}
abstract fun onViewCreated(view: View)
@CallSuper
protected open fun onStateChange(state: S?) {
onLoadingStateChange(false)
}
}
abstract class ComponentId
data class LoadingState(val loading: Boolean)
| 0
|
Kotlin
|
0
| 0
|
8d8c9e18c1b49d777ed86e01ae524346108e2b4d
| 2,627
|
Shiby
|
Apache License 2.0
|
contact_access/custom_adapter.kt
|
nitish098123
| 481,869,940
| false
| null |
package com.example.database_part_3.contact_access
/*
created in 2/3/2022: By <NAME>
this method will bring all the contacts from phone with velocity 200 contacts per second
*/
import android.content.Context
import android.provider.ContactsContract
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.database_part_3.R
import java.util.*
import kotlin.collections.ArrayList
import android.net.Uri
import android.Manifest
import android.content.ContentUris
import androidx.annotation.RequiresPermission
import com.example.database_part_3.model.ContactModel
import com.example.database_part_3.model.universal_model
// making class for retriving contacts
class custom_adapter(private val context: Context, private val contactModelArrayList: ArrayList<ContactModel>) : BaseAdapter() {
override fun getViewTypeCount(): Int {
return count
}
override fun getItemViewType(position: Int): Int {
return position
}
override fun getCount(): Int {
return contactModelArrayList.size
}
override fun getItem(position: Int): Any {
return contactModelArrayList[position]
}
override fun getItemId(position: Int): Long {
return 0
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertView = convertView
val holder: ViewHolder
if (convertView == null) {
holder = ViewHolder()
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
convertView = inflater.inflate(R.layout.home_page, null, true)
holder.tvname = convertView!!.findViewById(R.id.name) as TextView
holder.tvnumber = convertView.findViewById(R.id.number) as TextView
convertView.tag = holder
} else {
// the getTag returns the viewHolder object set as a tag to the view
holder = convertView.tag as ViewHolder
}
holder.tvname!!.setText(contactModelArrayList[position].getNames())
holder.tvnumber!!.setText(contactModelArrayList[position].getNumbers())
return convertView
}
private inner class ViewHolder {
var tvname: TextView? = null
var tvnumber: TextView? = null
}
}
| 1
|
Kotlin
|
0
| 1
|
61ef3ffb99db93ece011f701a55804cb8fedf211
| 2,451
|
Sofessist-a-messaging-specialist
|
Apache License 2.0
|
core/src/com/lyeeedar/Map/Objective/ObjectiveExplore.kt
|
Lyeeedar
| 62,673,759
| false
| null |
package com.lyeeedar.Map.Objective
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.utils.XmlReader
import com.lyeeedar.Board.Level
import com.lyeeedar.Global
import com.lyeeedar.Map.DungeonMap
import com.lyeeedar.Map.DungeonMapEntry
/**
* Created by Philip on 29-Jul-16.
*/
class ObjectiveExplore(): AbstractObjective()
{
var label: Label = Label("Explore n more rooms", Global.skin)
var complete = false
override fun getDescription(): String = "Explore all the rooms in the dungeon to complete the quest"
override fun update(map: DungeonMap)
{
val roomCount = map.map.filter { it.value.isRoom }.count()
val exploredCount = map.map.filter { it.value.isRoom && it.value.isCompleted }.count()
val diff = roomCount - exploredCount
if (diff <= 0)
{
label.setText("Complete")
complete = true
}
else if (diff == 1)
{
label.setText("Explore $diff more room")
}
else
{
label.setText("Explore $diff more rooms")
}
}
override fun isCompleted(): Boolean = complete
override fun createDynamicTable(skin: Skin): Table
{
val table = Table()
table.add(Label("Explore", skin)).left()
table.row()
table.add(label).left()
return table
}
override fun createStaticTable(skin: Skin): Table
{
val table = Table()
table.add(Label("Explore", skin)).left()
table.row()
table.add(Label(label.text, skin)).left()
return table
}
override fun getRequiredLevels(): Array<Level> = Array()
override fun parse(xml: XmlReader.Element)
{
}
}
| 0
|
Kotlin
|
0
| 0
|
1902dc00693baa1f9f295e0a3d767357bda7b03a
| 1,655
|
Match3
|
Apache License 2.0
|
core/src/main/kotlin/io/itch/mattekudasai/metallance/screen/TurnOffEasyModeScreen.kt
|
matte-made
| 783,774,435
| false
|
{"Kotlin": 202234}
|
package io.itch.mattekudasai.metallance.screen
import com.badlogic.gdx.Input.Keys
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.utils.Align
import com.badlogic.gdx.utils.viewport.FitViewport
import io.itch.mattekudasai.metallance.GlobalState.isPaused
import io.itch.mattekudasai.metallance.player.Controls.isDown
import io.itch.mattekudasai.metallance.player.Controls.isShoot
import io.itch.mattekudasai.metallance.player.Controls.isUp
import io.itch.mattekudasai.metallance.screen.touch.TouchMenuAdapter
import io.itch.mattekudasai.metallance.util.disposing.Disposing
import io.itch.mattekudasai.metallance.util.disposing.Self
import io.itch.mattekudasai.metallance.util.drawing.MonoSpaceTextDrawer
import io.itch.mattekudasai.metallance.util.files.overridable
import ktx.app.KtxInputAdapter
import ktx.app.KtxScreen
import ktx.app.clearScreen
import ktx.graphics.use
class TurnOffEasyModeScreen(
val apply: (easyMode: Boolean) -> Unit,
) : KtxScreen, KtxInputAdapter, Disposing by Self() {
private val batch: SpriteBatch by remember { SpriteBatch() }
private val camera = OrthographicCamera()
private val viewport = FitViewport(0f, 0f, camera)
private val shipTexture: Texture by remember { Texture("texture/ship/normal.png".overridable) }
private var internalTimer = 0f
private var selection = 0
private val menuItems = listOf("TURN OFF", "KEEP EASY")
private val textDrawer: MonoSpaceTextDrawer by remember {
MonoSpaceTextDrawer(
fontFileName = "texture/font_white.png",
alphabet = ('A'..'Z').joinToString(separator = "") + ".,'0123456789:Ж?",
fontLetterWidth = 5,
fontLetterHeight = 9,
fontHorizontalSpacing = 1,
fontVerticalSpacing = 0,
fontHorizontalPadding = 1,
)
}
private val touchMenuAdapter = TouchMenuAdapter(
onDragUp = { if (selection > 0) moveCursorUp() },
onDragDown = { if (selection < menuItems.size - 1) moveCursorDown() },
onTap = { select() }
)
override fun render(delta: Float) {
internalTimer += delta
clearScreen(red = 0f, green = 0f, blue = 0f)
viewport.apply(true)
batch.use(camera) {
textDrawer.drawText(
it,
listOf("TURN OFF EASY MODE?"),
viewport.worldWidth / 2f,
viewport.worldHeight * 0.8f,
Align.top
)
val menuGoesFrom = viewport.worldHeight / 3f
menuItems.forEachIndexed { index, item ->
val itemY = menuGoesFrom - index * 32f
textDrawer.drawText(it, listOf(item), viewport.worldWidth / 2f, itemY, Align.top)
if (selection == index) {
it.draw(
shipTexture,
viewport.worldWidth * 0.27f,
itemY + 11f,
shipTexture.width.toFloat(),
shipTexture.height.toFloat()
)
}
}
}
super.render(delta)
}
override fun resize(width: Int, height: Int) {
viewport.setWorldSize(width.toFloat(), height.toFloat())
viewport.setScreenSize(width, height)
}
override fun touchDown(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
return touchMenuAdapter.touchDown(screenX, screenY, pointer, button)
}
override fun touchDragged(screenX: Int, screenY: Int, pointer: Int): Boolean {
return touchMenuAdapter.touchDragged(screenX, screenY, pointer)
}
override fun touchUp(screenX: Int, screenY: Int, pointer: Int, button: Int): Boolean {
return touchMenuAdapter.touchUp(screenX, screenY, pointer, button)
}
override fun keyDown(keycode: Int): Boolean {
if (isPaused) {
return false
}
if (keycode.isShoot || keycode == Keys.SPACE || keycode == Keys.ENTER) {
select()
} else if (keycode.isUp) {
moveCursorUp()
} else if (keycode.isDown) {
moveCursorDown()
}
return true
}
private fun select() {
when (selection) {
0 -> apply(false)
1 -> apply(true)
}
}
private fun moveCursorUp() {
selection = (selection + 1) % menuItems.size
}
private fun moveCursorDown() {
selection = (selection + menuItems.size - 1) % menuItems.size
}
}
| 0
|
Kotlin
|
0
| 0
|
a75cb74d4a5dea40c8f395e4865cea431e005e80
| 4,635
|
metal-lance
|
Creative Commons Attribution 4.0 International
|
data/src/main/kotlin/com/zeongit/data/database/primary/dao/ComplaintDao.kt
|
fuzeongit
| 265,537,118
| false
| null |
package com.zeongit.data.database.primary.dao
import com.zeongit.data.database.primary.entity.Complaint
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import org.springframework.stereotype.Repository
@Repository
interface ComplaintDao : JpaRepository<Complaint, Int>, JpaSpecificationExecutor<Complaint> {
}
| 2
|
Kotlin
|
1
| 1
|
695043ba1e5f4a7a7ad662817de77758c97f408e
| 395
|
zeongit-beauty
|
MIT License
|
kode/src/main/kotlin/net/pelsmaeker/kode/types/JvmMemberRef.kt
|
Virtlink
| 550,764,695
| false
| null |
package net.pelsmaeker.kode.types
/**
* A JVM member reference.
*/
interface JvmMemberRef : JvmRef {
/** A reference to the class that declares this member. */
val owner: JvmClassRef
/** Whether this is an instance member. */
val isInstance: Boolean
/** Whether this is a static member. */
val isStatic: Boolean
/** Whether this is a static or instance constructor. */
val isConstructor: Boolean
/** Whether this is a field. */
val isField: Boolean
/** Whether this is a method (but not a constructor). */
val isMethod: Boolean
}
| 0
|
Kotlin
|
0
| 0
|
7410ec5e82d4dd8071c69be1678d63af489cba9f
| 581
|
kode
|
Apache License 2.0
|
engine/src/main/kotlin/io/rsbox/engine/plugin/RSPluginManager.kt
|
old-kyle-escabar
| 219,073,297
| false
| null |
package io.rsbox.engine.plugin
import io.rsbox.api.plugin.PluginInfo
import io.rsbox.api.plugin.PluginManager
import io.rsbox.api.plugin.RSPlugin
import io.rsbox.api.plugin.script.KotlinScriptPlugin
import io.rsbox.util.Injectable
import org.koin.core.inject
import org.tinylog.kotlin.Logger
import kotlin.reflect.KClass
/**
* Responsible for storing / loading plugins.
*
* @author Kyle Escobar
*/
class RSPluginManager : PluginManager, Injectable {
/**
* The plugin storage in memory.
*/
private val plugins = mutableListOf<Plugin>()
private val loader: PluginLoader by inject()
/**
* Get the number of loaded plugins.
*/
override fun count(): Int = plugins.size
/**
* Get the number of enabled plugins
*/
override fun countEnabled(): Int = plugins.filter { it.enabled }.size
/**
* Get the number of disabled plugins.
*/
override fun countDisabled(): Int = plugins.filter { !it.enabled }.size
/**
* Loads the plugin jars from the plugin directory.
* If [reload] is true, the current map of plugins are disabled
* and cleared from memory.
*/
@Suppress("UNCHECKED_CAST")
fun loadPluginJars(reload: Boolean = false) {
Logger.info { "Preparing to load/reload plugin directory." }
if(reload) {
Logger.info { "Reloading all plugins." }
plugins.filter { it.enabled }.forEach { plugin ->
this.disablePlugin(plugin.name)
}
plugins.clear()
}
val pluginJars = loader.getJars()
pluginJars.forEach { jar ->
val jarClasses = loader.unpackJar(jar)
val name: String
val version: String
val author: String
var mainClass: KClass<*>? = null
val scripts = hashSetOf<KClass<out KotlinScriptPlugin>>()
/**
* Find the mainClass
*/
jarClasses.forEach { (_, kClass) ->
if(kClass.java.superclass.simpleName == "RSPlugin") {
mainClass = kClass
}
}
/**
* Extract annotation info
*/
val pluginInfo = mainClass!!.java.getDeclaredAnnotation(PluginInfo::class.java)
name = pluginInfo.name
version = pluginInfo.version
author = pluginInfo.author
/**
* Find scripts within the plugin.
*/
jarClasses.forEach { (_, kClass) ->
if(kClass.java.superclass.simpleName == "KotlinScriptPlugin") {
scripts.add(kClass as KClass<out KotlinScriptPlugin>)
}
}
@Suppress("UNCHECKED_CAST") val plugin = Plugin(
name = name,
version = version,
author = author,
enabled = false,
mainClass = mainClass!! as KClass<out RSPlugin>,
pluginInstance = null,
scripts = scripts
)
plugins.add(plugin)
Logger.info { "Loaded plugin '$name - v$version' with ${scripts.size} scripts." }
}
}
/**
* Gets a plugin by name.
*/
@Suppress("UNCHECKED_CAST")
override fun <T : RSPlugin> getPlugin(name: String): T? {
/*
* Check if plugin is found and enabled.
*/
if(plugins.firstOrNull { it.name == name && it.enabled } == null) {
return null
}
return plugins.first { it.name == name } as T
}
/**
* Enables a plugin and invokes its enabler logic.
*
* @param name The name of the plugin.
*/
override fun enablePlugin(name: String) {
/*
* Check if plugin is loaded and already enabled. If so throw error.
*/
if(plugins.firstOrNull { it.name == name && it.enabled } != null) {
Logger.warn { "Failed to enable plugin $name. Plugin not found or is already enabled." }
return
}
val plugin = plugins.first { it.name == name }
val inst = plugin.mainClass.java.getDeclaredConstructor().newInstance()
plugin.pluginInstance = inst
/*
* Execute all scripts.
*/
plugin.scripts.forEach { script ->
script.java.getDeclaredConstructor().newInstance()
}
inst.onEnable()
plugin.enabled = true
Logger.info { "Enabled plugin '${plugin.name} - v${plugin.version}'." }
}
/**
* Disables a plugin and invokes its disabler logic.
*
* @param name The name of the plugin.
*/
override fun disablePlugin(name: String) {
/*
* Check if plugin is loaded and is not enabled. If so throw error.
*/
if(plugins.firstOrNull { it.name == name && !it.enabled } != null) {
Logger.warn { "Failed to disable plugin $name. Plugin not found or is already disabled." }
return
}
val plugin = plugins.first { it.name == name }
val inst = plugin.pluginInstance
inst!!.onDisable()
plugin.enabled = false
Logger.info { "Disabled plugin '${plugin.name} - v${plugin.version}'." }
}
/**
* Gets all of the loaded plugins.
*/
internal fun getPlugins(): List<Plugin> = plugins
}
| 0
|
Kotlin
|
0
| 3
|
5d04e508a316342a716a10a51dc9c841a4eabe5e
| 5,399
|
rsbox-rsps
|
MIT License
|
app/src/main/java/com/mytests/MainActivity.kt
|
FredNekrasov
| 766,574,196
| false
|
{"Kotlin": 46367}
|
package com.mytests
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import com.mytests.testExam.presentation.ExamScaffold
import com.mytests.ui.theme.MyTestsTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyTestsTheme {
Surface(Modifier.fillMaxSize(),color = MaterialTheme.colorScheme.background) {
ExamScaffold { message: String ->
Toast.makeText(this@MainActivity,message,Toast.LENGTH_SHORT).show()
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
2b1129429abfb21aa7d49aa9293798fd6e27d90f
| 940
|
my-tests
|
MIT License
|
ui/src/main/java/io/hoopit/android/ui/NetworkState.kt
|
hoopit
| 159,476,396
| false
| null |
package io.hoopit.android.ui
import android.content.Context
import androidx.annotation.StringRes
import io.hoopit.android.common.extensions.getStringOrDefault
@Suppress("DataClassPrivateConstructor")
data class NetworkState private constructor(
val status: Status,
val msg: String? = null,
@StringRes val stringRes: Int? = null,
val data: Map<String, *>? = null
) {
fun getErrorMessage(context: Context): String? {
return stringRes?.let { context.getStringOrDefault(it, msg) } ?: msg
}
companion object {
val success = NetworkState(Status.SUCCESS)
val loading = NetworkState(Status.RUNNING)
fun error(msg: String?, data: Map<String, *>? = null) = NetworkState(
Status.FAILED,
msg = msg,
data = data
)
fun error(@StringRes stringRes: Int?, data: Map<String, *>? = null) = NetworkState(
Status.FAILED,
stringRes = stringRes,
data = data
)
fun error(msg: String?, @StringRes stringRes: Int?, data: Map<String, *>? = null) =
NetworkState(
Status.FAILED,
msg = msg,
stringRes = stringRes,
data = data
)
}
enum class Status {
RUNNING,
SUCCESS,
FAILED
}
}
| 16
|
Kotlin
|
0
| 0
|
1e54e987915ee81b70689d490afc8ebed9dd34c6
| 1,345
|
android-components
|
MIT License
|
newm-server/src/main/kotlin/io/newm/server/features/walletconnection/model/GenerateChallengeResponse.kt
|
projectNEWM
| 447,979,150
| false
|
{"Kotlin": 2433442, "HTML": 185244, "Dockerfile": 2535, "Shell": 1986, "Procfile": 60}
|
package io.newm.server.features.walletconnection.model
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import java.time.LocalDateTime
import java.util.UUID
@Serializable
data class GenerateChallengeResponse(
@Contextual
val challengeId: UUID,
@Contextual
val expiresAt: LocalDateTime,
// hex_string(data) or cbor(transaction) to be signed by requester (depending on GenerateChallengeRequest.method)
val payload: String
)
| 1
|
Kotlin
|
5
| 10
|
83abe43e0dd7c8dc7888b4ddbe7bbecaa709b986
| 481
|
newm-server
|
Apache License 2.0
|
src/test/enhetstester/kotlin/no/nav/familie/ba/sak/integrasjoner/journalføring/InnkommendeJournalføringServiceEnhetTest.kt
|
navikt
| 224,639,942
| false
|
{"Kotlin": 6514101, "Gherkin": 993119, "PLpgSQL": 4478, "Shell": 3178, "Dockerfile": 522}
|
package no.nav.familie.ba.sak.integrasjoner.journalføring
import io.mockk.every
import io.mockk.mockk
import no.nav.familie.ba.sak.integrasjoner.familieintegrasjoner.IntegrasjonClient
import no.nav.familie.ba.sak.integrasjoner.journalføring.domene.JournalføringRepository
import no.nav.familie.ba.sak.integrasjoner.lagTilgangsstyrtJournalpost
import no.nav.familie.ba.sak.kjerne.behandling.BehandlingHentOgPersisterService
import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingSøknadsinfoService
import no.nav.familie.ba.sak.kjerne.fagsak.FagsakService
import no.nav.familie.ba.sak.kjerne.logg.LoggService
import no.nav.familie.ba.sak.kjerne.steg.StegService
import no.nav.familie.kontrakter.felles.BrukerIdType
import no.nav.familie.kontrakter.felles.Tema
import no.nav.familie.kontrakter.felles.journalpost.Bruker
import no.nav.familie.kontrakter.felles.journalpost.JournalposterForBrukerRequest
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class InnkommendeJournalføringServiceEnhetTest {
private val mockedIntegrasjonClient: IntegrasjonClient = mockk()
private val mockedFagsakService: FagsakService = mockk()
private val mockedBehandlingHentOgPersisterService: BehandlingHentOgPersisterService = mockk()
private val mockedJournalføringRepository: JournalføringRepository = mockk()
private val mockedLoggService: LoggService = mockk()
private val mockedStegService: StegService = mockk()
private val mockedJournalføringMetrikk: JournalføringMetrikk = mockk()
private val mockedBehandlingSøknadsinfoService: BehandlingSøknadsinfoService = mockk()
private val innkommendeJournalføringService: InnkommendeJournalføringService =
InnkommendeJournalføringService(
integrasjonClient = mockedIntegrasjonClient,
fagsakService = mockedFagsakService,
behandlingHentOgPersisterService = mockedBehandlingHentOgPersisterService,
journalføringRepository = mockedJournalføringRepository,
loggService = mockedLoggService,
stegService = mockedStegService,
journalføringMetrikk = mockedJournalføringMetrikk,
behandlingSøknadsinfoService = mockedBehandlingSøknadsinfoService,
)
@Test
fun `skal hente og returnere tilgangsstyrte journalposter`() {
// Arrange
val brukerId = "12345678910"
val journalpostId = "123"
val journalposter =
listOf(
lagTilgangsstyrtJournalpost(
personIdent = brukerId,
journalpostId = journalpostId,
harTilgang = true,
),
)
every {
mockedIntegrasjonClient.hentTilgangsstyrteJournalposterForBruker(
JournalposterForBrukerRequest(
antall = 1000,
brukerId = Bruker(id = brukerId, type = BrukerIdType.FNR),
tema = listOf(Tema.BAR),
),
)
} returns journalposter
// Act
val journalposterForBruker = innkommendeJournalføringService.hentJournalposterForBruker(brukerId)
// Assert
assertThat(journalposterForBruker.first { it.journalpost.journalpostId === journalpostId }.harTilgang).isTrue
}
}
| 13
|
Kotlin
|
1
| 9
|
ce534f2feb45a66b0b01ddda7edbd6646bae306b
| 3,322
|
familie-ba-sak
|
MIT License
|
database/src/commonMain/kotlin/uk/co/sentinelweb/cuer/db/adapter/InstantAdapter.kt
|
sentinelweb
| 220,796,368
| false
|
{"Kotlin": 2383617, "CSS": 205156, "Java": 98919, "Swift": 85812, "HTML": 19322, "JavaScript": 12105, "Ruby": 2170}
|
package uk.co.sentinelweb.cuer.db.adapter
import com.squareup.sqldelight.ColumnAdapter
import kotlinx.datetime.Instant
class InstantAdapter: ColumnAdapter<Instant, String> {
override fun decode(databaseValue: String) = Instant.parse(databaseValue)
override fun encode(value: Instant) = value.toString()
}
| 94
|
Kotlin
|
0
| 2
|
8fa2f9590eb37051442aa359262826dac83e5562
| 314
|
cuer
|
Apache License 2.0
|
app/src/main/java/com/immortalweeds/pedometer/model/gps/Routes.kt
|
Weedlly
| 523,343,757
| false
|
{"Kotlin": 65187}
|
package com.immortalweeds.pedometer.model.gps
data class Routes(
val code: String,
val routes: List<Route>,
val uuid: String,
val waypoints: List<Waypoint>
)
| 0
|
Kotlin
|
0
| 7
|
411c6fcf45a7a9aa34214148264297b345211ed7
| 174
|
Pedometer
|
Apache License 2.0
|
data/src/main/java/com/android/template/data/remote/adapters/mappers/ErrorMappers.kt
|
huuphuoc1396
| 831,253,387
| false
|
{"Kotlin": 72560}
|
package com.android.template.data.remote.adapters.mappers
import com.android.template.data.remote.models.responses.errors.ErrorResponse
import com.android.template.domain.models.errors.ApiException
import com.android.template.domain.models.errors.UnauthorizedException
import com.android.template.domain.utils.orEmpty
import com.android.template.domain.utils.orZero
import com.google.gson.Gson
import retrofit2.Response
import timber.log.Timber
import java.net.HttpURLConnection
internal fun Response<*>.toThrowable(): Throwable {
if (code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
return UnauthorizedException()
}
val jsonString = errorBody()?.string()
val errorResponse = try {
val gson = Gson()
gson.fromJson(jsonString, ErrorResponse::class.java)
} catch (exception: Exception) {
Timber.e(exception, "Error parsing: \n$jsonString")
return exception
}
return ApiException(
code = errorResponse?.code.orZero(),
message = errorResponse?.message.orEmpty(),
)
}
| 0
|
Kotlin
|
0
| 11
|
bb4856fe8bc7d34d285bae9e6c534c9d3064ece5
| 1,052
|
android-template
|
MIT License
|
app/src/main/java/com/redridgeapps/remoteforqbittorrent/ui/log/model/LogListItem.kt
|
SaurabhSandav
| 123,869,187
| false
| null |
package com.redridgeapps.remoteforqbittorrent.ui.log.model
import androidx.recyclerview.widget.DiffUtil
data class LogListItem(
val id: Int,
val message: String,
val timestamp: String,
val type: Int
) {
object DiffCallback : DiffUtil.ItemCallback<LogListItem>() {
override fun areItemsTheSame(oldItem: LogListItem, newItem: LogListItem): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: LogListItem, newItem: LogListItem) = true
}
}
| 0
|
Kotlin
|
0
| 1
|
1d3d81dfd9add116333e5892de1c7dda96a58dcb
| 549
|
qBittorrentRemote
|
MIT License
|
gankio/src/main/java/com/panyz/gankio/GankIoApplication.kt
|
panyz
| 333,628,190
| false
| null |
package com.panyz.gankio
import com.panyz.core_frame.base.BaseApplication
class GankIoApplication : BaseApplication() {
}
| 0
|
Kotlin
|
0
| 0
|
5f382b9e6b64d7533af88cce928b1eb4cac44a21
| 123
|
GankIO
|
Apache License 2.0
|
app/src/main/java/com/github/cfogrady/vitalwear/character/data/BEMCharacter.kt
|
cfogrady
| 619,941,986
| false
|
{"Kotlin": 516565}
|
package com.github.cfogrady.vitalwear.character.data
import android.util.Log
import com.github.cfogrady.vitalwear.character.VBCharacter
import com.github.cfogrady.vitalwear.character.transformation.ExpectedTransformation
import com.github.cfogrady.vitalwear.character.transformation.FusionTransformation
import com.github.cfogrady.vitalwear.character.transformation.TransformationOption
import com.github.cfogrady.vitalwear.common.card.CardType
import com.github.cfogrady.vitalwear.common.card.db.AttributeFusionEntity
import com.github.cfogrady.vitalwear.common.card.db.CardMetaEntity
import com.github.cfogrady.vitalwear.common.card.db.SpeciesEntity
import com.github.cfogrady.vitalwear.common.card.db.SpecificFusionEntity
import com.github.cfogrady.vitalwear.common.character.CharacterSprites
import com.github.cfogrady.vitalwear.settings.CharacterSettingsEntity
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import java.time.LocalDateTime
class BEMCharacter(
cardMetaEntity: CardMetaEntity,
characterSprites: CharacterSprites,
characterStats: CharacterEntity,
speciesStats : SpeciesEntity,
transformationWaitTimeSeconds: Long,
transformationOptions: List<TransformationOption>,
attributeFusionEntity: AttributeFusionEntity?,
specificFusionOptions: List<SpecificFusionEntity>,
settings: CharacterSettingsEntity,
_readyToTransform: MutableStateFlow<ExpectedTransformation?> = MutableStateFlow<ExpectedTransformation?>(null),
activityIdx : Int = 1,
lastTransformationCheck: LocalDateTime = LocalDateTime.MIN,
currentTimeProvider: ()->LocalDateTime = LocalDateTime::now
): VBCharacter(
cardMetaEntity,
characterSprites,
characterStats,
speciesStats,
transformationWaitTimeSeconds,
transformationOptions,
attributeFusionEntity,
specificFusionOptions,
settings,
_readyToTransform,
activityIdx,
lastTransformationCheck,
currentTimeProvider
) {
companion object {
const val TAG = "BEMCharacter"
const val MAX_VITALS = 9999
val DEFAULT_CHARACTER: BEMCharacter? = null
}
fun copy(
cardMetaEntity: CardMetaEntity = this.cardMetaEntity,
characterSprites: CharacterSprites = this.characterSprites,
characterStats: CharacterEntity = this.characterStats,
speciesStats : SpeciesEntity = this.speciesStats,
transformationWaitTimeSeconds: Long = this.transformationWaitTimeSeconds,
transformationOptions: List<TransformationOption> = this.transformationOptions,
attributeFusionEntity: AttributeFusionEntity? = this.attributeFusionEntity,
specificFusionOptions: List<SpecificFusionEntity> = this.specificFusionOptions,
settings: CharacterSettingsEntity = this.settings,
): BEMCharacter {
return BEMCharacter(
cardMetaEntity,
characterSprites,
characterStats,
speciesStats,
transformationWaitTimeSeconds,
transformationOptions,
attributeFusionEntity,
specificFusionOptions,
settings,
_readyToTransform = _readyToTransform,
activityIdx = activityIdx,
lastTransformationCheck = lastTransformationCheck,
)
}
override fun isBEM() : Boolean {
return cardMetaEntity.cardType == CardType.BEM
}
override fun totalBp(): Int {
return speciesStats.bp + characterStats.trainedBp.coerceAtMost(999)
}
override fun totalAp(): Int {
return speciesStats.ap + characterStats.trainedAp.coerceAtMost(999)
}
override fun totalHp(): Int {
return speciesStats.hp + characterStats.trainedHp.coerceAtMost(999)
}
}
| 12
|
Kotlin
|
0
| 4
|
e55a7a02a089d8097f8b167fc734c35b47b2d35b
| 3,769
|
VitalWear
|
MIT License
|
finnhub-api/src/commonMain/kotlin/com/hibernix/finnhub/model/SymbolChangeInfo.kt
|
hibernix
| 591,662,668
| false
| null |
package com.hibernix.finnhub.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* @property atDate Event's date.
* @property oldSymbol Old symbol.
* @property newSymbol New symbol.
*/
@Serializable
data class SymbolChangeInfo(
@SerialName("atDate") var atDate: String? = null,
@SerialName("oldSymbol") var oldSymbol: String? = null,
@SerialName("newSymbol") var newSymbol: String? = null,
)
| 0
|
Kotlin
|
0
| 1
|
cb570830c8af1ee5fd80bd9604649606c692fe09
| 450
|
finnhub-api
|
Apache License 2.0
|
src/commonMain/kotlin/fr/amoya/ktaglib/tag/riff/RiffTagParser.kt
|
moya-a
| 363,263,644
| false
| null |
package fr.amoya.ktaglib.tag.riff
import fr.amoya.ktaglib.tag.Tag
import fr.amoya.ktaglib.tag.TagParser
/*
* fr.amoya.ktaglib.common.parsers.riff
* As a part of the Project k-taglib
* @Author Arnaud Moya : <contact@amoya.fr>
* Created on 06/05/2021
*/
class RiffTagParser : TagParser
{
override fun parse(rawData: ByteArray): Tag
{
TODO("Not yet implemented")
}
}
| 0
|
Kotlin
|
0
| 1
|
d3dd69285fa3d1d1efc35e22d5766f5a24a7f248
| 380
|
k-taglib
|
MIT License
|
app/src/main/java/io/henrikhorbovyi/moviesapp/ui/screen/movies/favorites/Favorites.kt
|
henrikhorbovyi
| 447,833,912
| false
| null |
package io.henrikhorbovyi.moviesapp.ui.screen.movies.favorites
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.GridItemSpan
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import io.henrikhorbovyi.moviesapp.R
import io.henrikhorbovyi.moviesapp.entity.MoviePreview
import io.henrikhorbovyi.moviesapp.ui.components.HeaderText
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Favorites(
modifier: Modifier = Modifier,
/*moviesViewModel: MoviesViewModel,*/
onMovieSelected: (id: String) -> Unit = {}
) {
LazyVerticalGrid(
modifier = modifier,
cells = GridCells.Fixed(2),
content = {
item(
span = { GridItemSpan(2) },
content = {
HeaderText(
text = "Favorite Movies",
Modifier.padding(vertical = 16.dp, horizontal = 24.dp)
)
}
)
items(5) {
FavoriteMovieItem(onMovieSelected = onMovieSelected)
}
}
)
}
@Composable
fun FavoriteMovieItem(movie: MoviePreview? = null, onMovieSelected: (String) -> Unit = {}) {
Box(
modifier = Modifier
.padding(4.dp)
.clip(RoundedCornerShape(8.dp))
.clickable { onMovieSelected(movie?.id ?: "123") }
.wrapContentSize(unbounded = false)
) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painterResource(id = R.drawable.spiderman),
contentScale = ContentScale.FillWidth,
contentDescription = ""
)
}
}
@Preview(showSystemUi = true)
@Composable
fun FavoritesPreview() {
Favorites()
}
| 0
|
Kotlin
|
0
| 1
|
e5a03e6f2140379f565fc725f39b082dab8802af
| 2,932
|
movies-app
|
MIT License
|
app/src/main/java/pl/grajek/actions/model/dao/CategoryDao.kt
|
dawids222
| 169,272,010
| false
| null |
package pl.grajek.actions.model.dao
import android.arch.lifecycle.LiveData
import android.arch.persistence.room.*
import pl.grajek.actions.model.entity.Category
@Dao
interface CategoryDao {
@Insert
fun insert(category: Category)
@Update
fun update(category: Category)
@Delete
fun delete(category: Category)
@Query("DELETE FROM category_table WHERE id = :id")
fun delete(id: Long)
@Query("SELECT * FROM category_table")
fun selectAll(): LiveData<MutableList<Category>>
}
| 0
|
Kotlin
|
0
| 0
|
dc8c674b0b171ee68698133bcd023b2e26279612
| 516
|
Actions
|
MIT License
|
app/src/main/java/com/example/demoassignment/data/repository/FetchDataRepository.kt
|
rahulhundekari
| 400,115,940
| false
| null |
package com.example.demoassignment.data.repository
import android.util.Log
import com.example.demoassignment.di.NetworkModule
import com.example.demoassignment.network.NYTimesApi
import com.example.demoassignment.network.entities.MostViewedApiResponse
import dagger.hilt.android.scopes.ViewModelScoped
import okhttp3.Credentials
import retrofit2.Response
import javax.inject.Inject
@ViewModelScoped
class FetchDataRepository @Inject constructor(
private val nyTimesApi: NYTimesApi,
) {
suspend fun fetchMostPopularData(period: Int) =
nyTimesApi.getMostPopularViewedApi(
period,
NetworkModule.API_KEY
)
}
| 0
|
Kotlin
|
0
| 0
|
9b3135fb7241a01cb545a4adb688a4e26f133fbf
| 655
|
KotlinMVVMDemo
|
Apache License 2.0
|
sample/src/main/java/club/cred/sample/view/SampleScreensFragment.kt
|
CRED-CLUB
| 498,671,676
| false
|
{"Kotlin": 135999}
|
package club.cred.sample.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import club.cred.sample.R
import club.cred.sample.databinding.FragmentScreensContainerBinding
import club.cred.sample.viewHolders.INavigator
import club.cred.sample.viewHolders.ScreensAdapter
class SampleScreensFragment : DialogFragment(), INavigator {
override fun getTheme(): Int = R.style.FullScreenDialog
private var binding: FragmentScreensContainerBinding? = null
private val adapter by lazy { ScreensAdapter(this) }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentScreensContainerBinding.inflate(inflater, container, false)
return binding!!.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val currentPage = requireArguments().getInt("current_page")
binding?.viewPager?.adapter = adapter
binding?.viewPager?.setCurrentItem(currentPage, false)
}
override fun onDestroyView() {
binding = null
super.onDestroyView()
}
override fun onNextPageClicked() {
binding?.viewPager?.currentItem = binding?.viewPager?.currentItem?.plus(1) ?: 0
}
override fun onPreviousPageClicked() {
val previousPage = if ((binding?.viewPager?.currentItem?.minus(1) ?: 0) < 0) {
(binding?.viewPager?.currentItem?.plus(3) ?: 0)
} else {
(binding?.viewPager?.currentItem?.minus(1) ?: 0)
}
binding?.viewPager?.currentItem = previousPage
}
override fun onCloseClicked() {
dismiss()
}
companion object {
fun show(fragmentManager: FragmentManager, currentPage: Int) {
SampleScreensFragment().apply {
arguments = bundleOf("current_page" to currentPage)
show(fragmentManager, "DemoScreensFragment")
}
}
}
}
| 5
|
Kotlin
|
33
| 275
|
67e62066f6152f83d3e429da1e0de9501e817a24
| 2,163
|
neopop-android
|
Apache License 2.0
|
zowe-cli/src/jsMain/kotlin/zowe/cli/zosfiles/strings/Unmount.kt
|
lppedd
| 761,812,661
| false
|
{"Kotlin": 1887051}
|
package zowe.cli.zosfiles.strings
external interface Unmount {
var SUMMARY: String
var DESCRIPTION: String
var ACTIONS: Temp162
}
| 0
|
Kotlin
|
0
| 3
|
0f493d3051afa3de2016e5425a708c7a9ed6699a
| 137
|
kotlin-externals
|
MIT License
|
app/src/androidTest/java/bez/dev/featurenotes/NotesTest.kt
|
AmChuri
| 697,345,656
| false
|
{"Kotlin": 87118}
|
package bez.dev.featurenotes
import android.app.Activity
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.*
import androidx.test.espresso.NoMatchingViewException
import androidx.test.espresso.ViewAssertion
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry
import androidx.test.runner.lifecycle.Stage
import bez.dev.featurenotes.views.screens.notes_list.MainActivity
import org.hamcrest.Matchers.`is`
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import java.text.SimpleDateFormat
import java.util.*
class NotesTest {
@get:Rule
var mainActivityTestRule = ActivityTestRule(MainActivity::class.java)
private var runningActivity: Activity? = null
private val notesToAdd: Int = 3
private val maxItemsToAdd: Int = 2
@Test
fun clickFab_openNewNote_addItems() {
onView(withId(R.id.fab_add_note)).perform(click())
val numItems = Random().nextInt(maxItemsToAdd) + 1
addItems(numItems)
pressBack()
pressBack()
}
@Test
fun addNotes() {
val recyclerView = mainActivityTestRule.activity.findViewById<RecyclerView>(R.id.recycler_view)
val noteCount = getRecyclerItemCount(recyclerView)
for (i in 1..notesToAdd) {
clickFab_openNewNote_addItems()
}
onView(withId(R.id.recycler_view)).check(RecyclerViewItemCountAssertion(noteCount + notesToAdd))
}
@Ignore("can add reason")
@Test
fun clickNoteEdit_openDetailActivityEditItem() {
// val title = "test mock"
// onView(withId(R.id.recycler_view))
// .perform(RecyclerViewActions.actionOnItem<RecyclerView.ViewHolder>(hasDescendant(withText(title)), click()));
//
// onView(withId(R.id.edit_text_title))
// .check(matches(withText(title)))
// //click item by position//
// onView(withId(R.id.recycler_view))
// .perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(0, click()));
}
@Test
fun clickOverflowMenuButton_addNote() {
openActionBarOverflowOrOptionsMenu(ApplicationProvider.getApplicationContext())
onView(withText("Add Note"))
.perform(click())
onView(withId(R.id.edit_text_title))
.perform(typeText(getTimeStamp()))
}
private fun getTimeStamp(): String {
val formatter = SimpleDateFormat("h:mm a, d MMM")
return formatter.format(Date(System.currentTimeMillis()))
}
private fun addItems(numItems: Int) {
val detailRecyclerView = getActivityInstance()!!.findViewById<RecyclerView>(R.id.recycler_view_detail)
val itemCount = getRecyclerItemCount(detailRecyclerView)
for (i in 0 until numItems) {
onView(withId(R.id.top_add_item_btn))
.perform(click())
onView(withId(R.id.dialogEditText))
.perform(typeText(String.format("item %d", i + 1)))
onView(withId(R.id.dialogSaveTextBtn))
.perform(click())
}
onView(withId(R.id.recycler_view_detail)).check(RecyclerViewItemCountAssertion(itemCount + numItems))
}
private fun getRecyclerItemCount(recyclerView: RecyclerView): Int {
return recyclerView.adapter!!.itemCount
}
private fun getActivityInstance(): Activity? {
InstrumentationRegistry.getInstrumentation().runOnMainSync {
val resumedActivities: Collection<*> = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)
if (resumedActivities.iterator().hasNext()) {
runningActivity = resumedActivities.iterator().next() as Activity
}
}
return runningActivity
}
class RecyclerViewItemCountAssertion(private val expectedCount: Int) : ViewAssertion {
override fun check(view: View, noViewFoundException: NoMatchingViewException?) {
if (noViewFoundException != null) {
throw noViewFoundException
}
view as RecyclerView
assertThat(view.adapter?.itemCount, `is`(expectedCount))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f95d1c42c3fa22f55f12f28042152afdacaf7768
| 4,570
|
Notes-App
|
Apache License 2.0
|
foosball/foosball/app/src/tablet/java/com/instructure/androidfoosball/services/FoosballSyncService.kt
|
JJSWART
| 180,793,227
| true
|
{"Markdown": 2, "Proguard": 12, "Gradle": 44, "Ignore List": 28, "Java": 1313, "XML": 1469, "Text": 11, "Shell": 6, "Batchfile": 2, "Java Properties": 3, "YAML": 4, "HTML": 12, "Python": 1, "Kotlin": 59, "Ruby": 2, "INI": 2, "CSS": 1, "Ant Build System": 1}
|
package com.instructure.androidfoosball.services
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.support.v7.app.NotificationCompat
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import com.instructure.androidfoosball.App
import com.instructure.androidfoosball.BuildConfig
import com.instructure.androidfoosball.R
import com.instructure.androidfoosball.ktmodels.Table
import com.instructure.androidfoosball.ktmodels.User
import java.util.*
class FoosballSyncService : Service() {
private val SERVICE_ID = 12321
inner class FoosballSyncServiceBinder : Binder() {
fun getService() = this@FoosballSyncService
}
lateinit private var mAuth: FirebaseAuth
lateinit private var mDatabase: DatabaseReference
private val mBinder = FoosballSyncServiceBinder()
private val mPendingSyncs = ArrayList<(Boolean) -> Unit>()
private var mIsFirebaseReady = false
private var mIsFirebaseFailed = false
private var mIsSyncing = false
private var mIsListeningForUserChanges = false
private var mSyncStep = 0
override fun onBind(intent: Intent?) = mBinder
override fun onCreate() {
super.onCreate()
startForeground(SERVICE_ID, NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("Foosball Service Running")
.build())
mAuth = FirebaseAuth.getInstance()
mAuth.signInWithEmailAndPassword(BuildConfig.FIREBASE_USERNAME, BuildConfig.FIREBASE_PASSWORD).addOnCompleteListener { task ->
if (!task.isSuccessful) {
mIsFirebaseFailed = true
finishSync(false)
} else {
mIsFirebaseReady = true
if (mPendingSyncs.isNotEmpty()) startSync()
}
}
mDatabase = FirebaseDatabase.getInstance().reference
}
fun requestSync(onFinish: (Boolean) -> Unit) {
if (mIsFirebaseFailed) {
onFinish(false)
} else {
mPendingSyncs.add(onFinish)
startSync()
}
}
private fun startSync() {
if (!mIsFirebaseReady || mIsSyncing) return
performNextSyncStep()
}
private fun performNextSyncStep() {
mIsSyncing = true
mSyncStep++
when (mSyncStep) {
1 -> syncTables()
2 -> syncUsers()
3 -> finishSync(true)
}
}
private fun syncTables() {
mDatabase.child("tables").addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val tables = ArrayList<Table>()
val tableNames = ArrayList<String>()
for (child in dataSnapshot.children) {
val table = child.getValue(Table::class.java)
table.id = child.key
tables.add(table)
tableNames.add(table.name)
}
App.realm.beginTransaction()
App.realm.copyToRealmOrUpdate(tables)
App.realm.commitTransaction()
performNextSyncStep()
}
override fun onCancelled(databaseError: DatabaseError) {
finishSync(false)
}
})
}
private fun syncUsers() {
if (mIsListeningForUserChanges) {
performNextSyncStep()
} else {
mDatabase.child("users").addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val users = ArrayList<User>()
for (child in dataSnapshot.children) {
val user = child.getValue(User::class.java)
user.id = child.key
users.add(user)
}
App.realm.beginTransaction()
App.realm.copyToRealmOrUpdate(users)
App.realm.commitTransaction()
if (!mIsListeningForUserChanges) {
mIsListeningForUserChanges = true
performNextSyncStep()
}
}
override fun onCancelled(databaseError: DatabaseError) {
if (!mIsListeningForUserChanges) finishSync(false)
}
})
}
}
private fun finishSync(success: Boolean) {
mIsSyncing = false
mSyncStep = 0
mPendingSyncs.forEach { it(success) }
mPendingSyncs.clear()
}
}
| 0
|
Java
|
0
| 0
|
ebcdd3d66b2b6c34b8dd51a23bbb849983c869d3
| 4,702
|
instructure-android
|
Apache License 2.0
|
app/core/src/main/java/com/mail/ann/mailstore/MessageStoreFactory.kt
|
ZhangXinmin528
| 516,242,626
| true
|
{"INI": 1, "Shell": 6, "Gradle": 30, "EditorConfig": 1, "Markdown": 8, "Git Attributes": 1, "Batchfile": 1, "Text": 44, "Ignore List": 4, "Git Config": 1, "XML": 399, "YAML": 6, "Kotlin": 744, "AIDL": 2, "Java": 433, "Java Properties": 1, "SVG": 67, "PostScript": 1, "JSON": 23, "E-mail": 27, "Proguard": 1}
|
package com.mail.ann.mailstore
import com.mail.ann.Account
interface MessageStoreFactory {
fun create(account: Account): ListenableMessageStore
}
| 0
|
Java
|
0
| 0
|
3efc82014d57307996329fd057c505d2b88ed044
| 152
|
Ann-mail
|
Apache License 2.0
|
compiler/testData/diagnostics/tests/secondaryConstructors/constructorInObject.kt
|
anothem
| 32,282,897
| true
|
{"Markdown": 33, "XML": 646, "Ant Build System": 32, "Ignore List": 8, "Maven POM": 48, "Kotlin": 16461, "Java": 4172, "CSS": 10, "Shell": 7, "Batchfile": 7, "Java Properties": 9, "Gradle": 68, "HTML": 114, "INI": 7, "Groovy": 19, "JavaScript": 66, "Text": 3438, "JFlex": 3, "JAR Manifest": 2, "Roff": 30, "Roff Manpage": 10, "Protocol Buffer": 3}
|
object A {
<!SECONDARY_CONSTRUCTOR_IN_OBJECT!>constructor() {}<!>
init {}
}
enum class B {
X : B() {
<!SECONDARY_CONSTRUCTOR_IN_OBJECT!>constructor() {}<!>
}
}
class C {
default object {
<!SECONDARY_CONSTRUCTOR_IN_OBJECT!>constructor() {}<!>
}
}
val anonObject = object {
<!SECONDARY_CONSTRUCTOR_IN_OBJECT!>constructor() {}<!>
}
| 0
|
Java
|
0
| 0
|
b44dbe6ca2e1519a4ccf548758714ce9726b77c7
| 376
|
kotlin
|
Apache License 2.0
|
app/src/main/kotlin/com/lovoo/android/pickpic/ExampleAdapter.kt
|
lovoo
| 224,686,577
| false
| null |
/**
* Copyright 2018 LOVOO GmbH
*
* 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.lovoo.android.pickpic
import android.content.Context
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
class ExampleAdapter(context: Context) : RecyclerView.Adapter<ExampleAdapter.ViewHolder>() {
private val layoutInflater = LayoutInflater.from(context)
var list: List<Uri> = emptyList()
set(value) {
field = value
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(layoutInflater.inflate(R.layout.example_item, parent, false))
}
override fun getItemCount() = list.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
list.getOrNull(position)?.let {
holder.bind(it)
}
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(uri: Uri) {
(itemView as? ImageView)?.let {
it.setImageBitmap(null)
Glide.with(it).load(uri).into(it)
}
}
}
}
| 0
|
Kotlin
|
1
| 13
|
225b679bfc41d77d9b0573cbbc466d261c683c61
| 1,818
|
android-pickpic
|
Apache License 2.0
|
app/src/main/java/com/jdavifranco/letswatch/repository/MovieRepository.kt
|
jdavifranco
| 390,082,134
| false
| null |
package com.jdavifranco.letswatch.repository
import com.jdavifranco.letswatch.datasource.mappers.toDomain
import com.jdavifranco.letswatch.datasource.remote.RemoteDataSource
import com.jdavifranco.letswatch.domain.data.MovieDataRepository
import com.jdavifranco.letswatch.domain.model.Details
import com.jdavifranco.letswatch.domain.model.Genre
import com.jdavifranco.letswatch.domain.model.Movie
import retrofit2.HttpException
class MovieRepository(
private val remoteDataSource: RemoteDataSource
): MovieDataRepository{
override suspend fun getMovieListByGenre(query: String, pagePosition:Int): List<Movie> {
try {
return remoteDataSource.getMoviesByGenre(query, pagePosition).toDomain()
}catch (e:HttpException){
throw e
}
}
override suspend fun getGenreList() :List<Genre> {
try {
return remoteDataSource.getGenreList().toDomain()
}catch (e:HttpException){
throw e
}
}
override suspend fun getMovieDetails(id: Long): Details {
val detailsRM = remoteDataSource.getMovieDetails(id)
return detailsRM.toDomain()
}
}
/*
return Pager(
config = PagingConfig(
pageSize = MOVIES_PAGE_SIZE,
enablePlaceholders = false,
),
pagingSourceFactory = { PagingSource(remoteDataSource, query) }
).flow
* */
| 0
|
Kotlin
|
0
| 1
|
cd5b1c544804832c6e2ae63ac76c3f665c6f2232
| 1,418
|
LetsWatch
|
Apache License 2.0
|
parkingmanagement-api/src/main/kotlin/parkandrest/parkingmanagement/api/parking/ParkingNotExistsException.kt
|
pokemzok
| 166,366,410
| false
| null |
package parkandrest.parkingmanagement.api.parking
import parkandrest.exception.api.exceptionparent.BusinessException
import parkandrest.parkingmanagement.api.businessexception.BusinessExceptionCode
class ParkingNotExistsException : BusinessException(CODE, arrayOf(), "") {
companion object {
private val CODE = BusinessExceptionCode.PARKING_NOT_EXISTS.name
}
}
| 0
|
Kotlin
|
0
| 1
|
f079ade5c5407ac1d41dfb3432f8ba1b10c1b274
| 380
|
parkandrest-kotlin
|
MIT License
|
app/src/main/java/com/example/svbookmarket/activities/viewmodel/ItemDetailViewModelFactory.kt
|
khangbdd
| 406,396,585
| true
|
{"Kotlin": 317416, "Java": 4114}
|
package com.example.svbookmarket.activities.viewmodel
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.svbookmarket.activities.model.Book
//class ItemDetailViewModelFactory(private val book: Book?):ViewModelProvider.Factory{
// override fun <T : ViewModel?> create(modelClass: Class<T>): T {
// if (modelClass.isAssignableFrom(ItemDetailViewModel::class.java))
// return ItemDetailViewModel(book) as T
// throw IllegalArgumentException("Wrong view model class")
// }
//}
| 0
| null |
0
| 0
|
880507764d14c4b4ba6285caf07ae3ac403064f2
| 579
|
OnlineBookMarket
|
Apache License 2.0
|
samples/starter-mobile-app/src/main/kotlin/researchstack/presentation/screen/insight/SettingScreen.kt
|
S-ResearchStack
| 520,365,275
| false
|
{"Kotlin": 178868, "AIDL": 4785}
|
package researchstack.presentation.screen.insight
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import researchstack.BuildConfig
import researchstack.R.string
import researchstack.presentation.component.AppSwitch
import researchstack.presentation.component.TopBar
import researchstack.presentation.theme.AppTheme
import researchstack.presentation.viewmodel.UISettingViewModel
import researchstack.presentation.viewmodel.WearableMeasurementPrefViewModel
@Composable
fun SettingScreen(
uiSettingViewModel: UISettingViewModel = hiltViewModel(),
WearableMeasurementPrefViewModel: WearableMeasurementPrefViewModel = hiltViewModel(),
) {
val scrollState = rememberScrollState()
val mobileSyncEnabled = uiSettingViewModel.mobileDataSyncEnable.collectAsState().value
val inClinicModeUntil = uiSettingViewModel.inClinicModeUntil.collectAsState().value
val ecgMeasurementEnabled = uiSettingViewModel.ecgMeasurementEnabled.collectAsState().value
Scaffold(
topBar = {
TopBar(title = stringResource(id = string.settings))
}
) { innerPadding ->
Column(
modifier = Modifier
.padding(innerPadding)
.padding(horizontal = 24.dp)
.fillMaxSize()
.background(AppTheme.colors.background)
.verticalScroll(scrollState),
) {
if (BuildConfig.SUPPORT_IN_CLINIC_MODE) {
Text(
text = "Select Mode",
style = AppTheme.typography.body2,
color = AppTheme.colors.onSurface,
)
Spacer(Modifier.height(20.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = stringResource(id = string.in_clinic),
style = AppTheme.typography.caption,
color = AppTheme.colors.onSurface,
)
AppSwitch(
uiSettingViewModel.isInClinicMode(),
) {
uiSettingViewModel.updateInClinicModeUntil(!it)
}
}
Spacer(Modifier.height(20.dp))
}
Text(
text = "Data Sync",
style = AppTheme.typography.body2,
color = AppTheme.colors.onSurface,
)
Spacer(Modifier.height(20.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = stringResource(id = string.mobile_data_enable),
style = AppTheme.typography.caption,
color = AppTheme.colors.onSurface,
)
AppSwitch(
mobileSyncEnabled,
) {
uiSettingViewModel.setMobileDataEnable(it)
}
}
Spacer(Modifier.height(20.dp))
Text(
text = "ECG / BIA",
style = AppTheme.typography.body2,
color = AppTheme.colors.onSurface,
)
Spacer(Modifier.height(20.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = stringResource(id = string.enable_ecg_bia),
style = AppTheme.typography.caption,
color = AppTheme.colors.onSurface,
)
AppSwitch(
ecgMeasurementEnabled,
) {
uiSettingViewModel.setEcgMeasurementEnabled(it)
WearableMeasurementPrefViewModel.setEcgMeasurementEnabled(it)
}
}
}
}
}
| 0
|
Kotlin
|
20
| 26
|
58b4b9b64623a7d2a0865307d490a59a7538d7cd
| 5,145
|
app-sdk
|
Apache License 2.0
|
src/test/kotlin/org/randomcat/util/PrimaryKeyedTests.kt
|
randomnetcat
| 255,200,022
| false
| null |
package org.randomcat.util
import org.randomcat.util.test_util.assertSucceeds
import kotlin.test.Test
import kotlin.test.assertFails
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class PrimaryKeyedTests {
private data class KeyValuePair(val key: Int, val value: String)
@Test
fun `isPrimaryKeyedBy and groupByPrimaryKey exception works`() {
assertTrue(emptyList<KeyValuePair>().isPrimaryKeyedBy { it.key })
assertPrimaryKeyed(
KeyValuePair(1, "A"),
)
assertPrimaryKeyed(
KeyValuePair(1, "A"),
KeyValuePair(1, "A"),
)
assertPrimaryKeyed(
KeyValuePair(1, "A"),
KeyValuePair(2, "B"),
)
assertPrimaryKeyed(
KeyValuePair(1, "A"),
KeyValuePair(1, "A"),
KeyValuePair(2, "B"),
)
assertNotPrimaryKeyed(
KeyValuePair(1, "A"),
KeyValuePair(1, "B"),
)
assertNotPrimaryKeyed(
KeyValuePair(1, "A"),
KeyValuePair(1, "B"),
KeyValuePair(2, "A"),
KeyValuePair(2, "A"),
)
assertNotPrimaryKeyed(
KeyValuePair(1, "A"),
KeyValuePair(1, "B"),
KeyValuePair(2, "A"),
KeyValuePair(2, "B"),
)
}
private fun assertPrimaryKeyed(entries: List<KeyValuePair>) {
assertTrue(entries.isPrimaryKeyedBy { it.key })
assertSucceeds { entries.groupByPrimaryKey { it.key } }
}
private fun assertPrimaryKeyed(vararg entries: KeyValuePair) = assertPrimaryKeyed(entries.asList())
private fun assertNotPrimaryKeyed(entries: List<KeyValuePair>) {
assertFalse(entries.isPrimaryKeyedBy { it.key })
assertFails { entries.groupByPrimaryKey { it.key } }
}
private fun assertNotPrimaryKeyed(vararg entries: KeyValuePair) = assertNotPrimaryKeyed(entries.asList())
}
| 0
|
Kotlin
|
0
| 0
|
4183c9113c0bbddc50932110d764af7150283176
| 1,950
|
kotlin-utils
|
MIT License
|
api/src/main/kotlin/com/seedcompany/cordtables/components/tables/common/people_to_org_relationships/List.kt
|
CordField
| 409,237,733
| false
| null |
package com.seedcompany.cordtables.components.tables.common.people_to_org_relationships
import com.seedcompany.cordtables.common.ErrorType
import com.seedcompany.cordtables.common.Utility
import com.seedcompany.cordtables.components.admin.GetSecureListQuery
import com.seedcompany.cordtables.components.admin.GetSecureListQueryRequest
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.ResponseBody
import java.sql.SQLException
import javax.sql.DataSource
data class CommonPeopleToOrgRelationshipsListRequest(
val token: String?
)
data class CommonPeopleToOrgRelationshipsListResponse(
val error: ErrorType,
val peopleToOrgRelationships: MutableList<peopleToOrgRelationship>?
)
@CrossOrigin(origins = ["http://localhost:3333", "https://dev.cordtables.com", "https://cordtables.com", "*"])
@Controller("CommonPeopleToOrgRelationshipsList")
class List(
@Autowired
val util: Utility,
@Autowired
val ds: DataSource,
@Autowired
val secureList: GetSecureListQuery,
) {
var jdbcTemplate: NamedParameterJdbcTemplate = NamedParameterJdbcTemplate(ds)
@PostMapping("common/people-to-org-relationships/list")
@ResponseBody
fun listHandler(@RequestBody req:CommonPeopleToOrgRelationshipsListRequest): CommonPeopleToOrgRelationshipsListResponse {
var data: MutableList<peopleToOrgRelationship> = mutableListOf()
if (req.token == null) return CommonPeopleToOrgRelationshipsListResponse(ErrorType.TokenNotFound, mutableListOf())
val paramSource = MapSqlParameterSource()
paramSource.addValue("token", req.token)
val query = secureList.getSecureListQueryHandler(
GetSecureListQueryRequest(
tableName = "common.people_to_org_relationships",
filter = "order by id",
columns = arrayOf(
"id",
"org",
"person",
"relationship_type",
"begin_at",
"end_at",
"created_at",
"created_by",
"modified_at",
"modified_by",
"owning_person",
"owning_group",
)
)
).query
try {
val jdbcResult = jdbcTemplate.queryForRowSet(query, paramSource)
while (jdbcResult.next()) {
var id: String? = jdbcResult.getString("id")
if (jdbcResult.wasNull()) id = null
var org: String? = jdbcResult.getString("org")
if (jdbcResult.wasNull()) org = null
var person: String? = jdbcResult.getString("person")
if (jdbcResult.wasNull()) person = null
var relationship_type: String? = jdbcResult.getString("relationship_type")
if (jdbcResult.wasNull()) relationship_type = null
var begin_at: String? = jdbcResult.getString("begin_at")
if (jdbcResult.wasNull()) begin_at = null
var end_at: String? = jdbcResult.getString("end_at")
if (jdbcResult.wasNull()) end_at = null
var created_by: String? = jdbcResult.getString("created_by")
if (jdbcResult.wasNull()) created_by = null
var created_at: String? = jdbcResult.getString("created_at")
if (jdbcResult.wasNull()) created_at = null
var modified_at: String? = jdbcResult.getString("modified_at")
if (jdbcResult.wasNull()) modified_at = null
var modified_by: String? = jdbcResult.getString("modified_by")
if (jdbcResult.wasNull()) modified_by = null
var owning_person: String? = jdbcResult.getString("owning_person")
if (jdbcResult.wasNull()) owning_person = null
var owning_group: String? = jdbcResult.getString("owning_group")
if (jdbcResult.wasNull()) owning_group = null
data.add(
peopleToOrgRelationship(
id = id,
org = org,
person = person,
relationship_type = relationship_type,
begin_at = begin_at,
end_at = end_at,
created_at = created_at,
created_by = created_by,
modified_at = modified_at,
modified_by = modified_by,
owning_person = owning_person,
owning_group = owning_group,
)
)
}
} catch (e: SQLException) {
println("error while listing ${e.message}")
return CommonPeopleToOrgRelationshipsListResponse(ErrorType.SQLReadError, mutableListOf())
}
return CommonPeopleToOrgRelationshipsListResponse(ErrorType.NoError, data)
}
}
| 93
|
Kotlin
|
1
| 3
|
7e5588a8b3274917f9a5df2ffa12d27db23fb909
| 5,453
|
cordtables
|
MIT License
|
zowe-zos-console-for-zowe-sdk/src/jsMain/kotlin/zowe/sdk/console/doc/IConsoleResponse.kt
|
lppedd
| 761,812,661
| false
|
{"Kotlin": 1887051}
|
package zowe.sdk.console.doc
import zowe.imperative.error.ImperativeError
import zowe.sdk.console.doc.zosmf.IZosmfIssueResponse
/**
* The Console API response.
*/
external interface IConsoleResponse {
/**
* True if the command was issued and the responses were collected.
*/
var success: Boolean
/**
* The list of zOSMF console API responses. May issue multiple requests (because of user request) or
* to ensure that all messages are collected. Each individual response is placed here.
*/
var zosmfResponse: Array<IZosmfIssueResponse>
/**
* If an error occurs, returns the ImperativeError, which contains casue error.
*/
var failureResponse: ImperativeError?
/**
* The command response text.
*/
var commandResponse: String
/**
* The final command response key - used to "follow-up" and check for additional response messages for the command.
*/
var lastResponseKey: String?
/**
* If the solicited keyword is specified, indicates that the keyword was detected.
*/
var keywordDetected: Boolean?
/**
* The "follow-up" command response URL - you can paste this in the browser to do a "GET" using the command
* response key provided in the URI route.
*/
var cmdResponseUrl: String?
}
| 0
|
Kotlin
|
0
| 3
|
0f493d3051afa3de2016e5425a708c7a9ed6699a
| 1,265
|
kotlin-externals
|
MIT License
|
app/src/main/java/com/projekt/sobokan/GameView.kt
|
Gladiu
| 493,292,243
| false
| null |
package com.projekt.sobokan
import android.content.Context
import android.graphics.Canvas
import android.view.View
class GameView(context: Context) : View(context) {
lateinit var gameMap: GameMap
lateinit var player: Player
override fun onDraw(canvas: Canvas?) {
gameMap.Draw(canvas)
player.Draw(canvas)
}
}
| 0
|
Kotlin
|
0
| 1
|
c2dd4da4f9eac9034103e76ce6ba2009c8053b42
| 342
|
Sobokan
|
MIT License
|
app/src/main/java/com/example/digitalwhiteboard/DrawActivity.kt
|
Wrafttex
| 645,241,817
| false
| null |
package com.example.digitalwhiteboard
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Matrix
import android.os.Bundle
import android.util.Log
import android.util.Size
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.core.graphics.createBitmap
import com.example.digitalwhiteboard.databinding.ActivityDrawBinding
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import com.example.digitalwhiteboard.captureActivity
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
class DrawActivity : AppCompatActivity(), ImageAnalysis.Analyzer {
private lateinit var binding: ActivityDrawBinding
private lateinit var cameraExecutor: ExecutorService
private lateinit var imageView: ImageView
private lateinit var startButton: Button
private var startBoolean: Boolean = false
private lateinit var corners: FloatArray
private lateinit var resolution: Size
private lateinit var captureAct: captureActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDrawBinding.inflate(layoutInflater)
val intent = intent
corners = intent.getSerializableExtra("CornerValue") as FloatArray // TODO: getSerializableExtra is a deprecated method
setContentView(binding.root)
this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
imageView = findViewById(R.id.imageView)
val prefStorage = PrefStorage(this)
val preferredResolution = prefStorage.storageRead("module","")
if (preferredResolution.isNullOrEmpty() || !preferredResolution.contains('x')) {
resolution = Size(1280, 720)
} else {
val splitString = preferredResolution?.split("x")
resolution = Size(splitString!![0].toInt(), splitString[1].toInt())
}
imageView.layoutParams.width = resolution.width
imageView.layoutParams.height = resolution.height
cameraExecutor = Executors.newSingleThreadExecutor()
requestPermission()
startButton = findViewById(R.id.start)
startButton.setOnClickListener {
startOnClick(imageView)
}
onBackPressedDispatcher.addCallback(this, object: OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
val intent = Intent (this@DrawActivity, CornerActivity::class.java)
startActivity(intent)
}
})
}
private fun assetFilePath(context: Context, assetName: String): String? {
val file = File(context.filesDir, assetName)
if (file.exists() && file.length() > 0) {
return file.absolutePath
}
try {
context.assets.open(assetName).use { `is` ->
FileOutputStream(file).use { os ->
val buffer = ByteArray(4 * 1024)
var read: Int
while (`is`.read(buffer).also { read = it } != -1) {
os.write(buffer, 0, read)
}
os.flush()
}
return file.absolutePath
}
} catch (e: IOException) {
Log.e("captureActivity", "Error process asset $assetName to file path")
}
return null
}
private fun requestPermission() {
requestCameraPermissionIfMissing { granted ->
if (granted)
startCamera()
else
Toast.makeText(this, "Please allow", Toast.LENGTH_LONG).show()
}
}
private fun requestCameraPermissionIfMissing(onResult: ((Boolean) -> Unit)) {
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
onResult(true)
else
registerForActivityResult(ActivityResultContracts.RequestPermission()) {
onResult(it)
}.launch(android.Manifest.permission.CAMERA)
}
private fun startCamera() {
val processCameraProvider = ProcessCameraProvider.getInstance(this)
processCameraProvider.addListener({
try {
val cameraProvider = processCameraProvider.get()
val imageAnalysisUseCase = buildImageAnalysisUseCase()
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(
this,
CameraSelector.DEFAULT_BACK_CAMERA,
imageAnalysisUseCase
)
} catch (e: Exception) {
e.printStackTrace()
}
}, ContextCompat.getMainExecutor(this))
}
private fun buildImageAnalysisUseCase(): ImageAnalysis {
Log.v("buildImageAnalysisUseCase","inside buildImageAnalysisUseCase")
return ImageAnalysis.Builder()
.setTargetResolution(resolution)
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build().also { it.setAnalyzer(cameraExecutor, this) }
}
override fun analyze(image: ImageProxy) {
val bitmap = image.toBitmap()
if (!::captureAct.isInitialized) {
val manipulatedImage = bitmap.copy(bitmap.config, true)
var path = assetFilePath(this, "noQ_ADE20K_ViT_Seg_T_Mask_fbgemm_CPU.pt")!! //NOTE: needs to exist, otherwise model wont load
captureAct = captureActivity(corners, manipulatedImage)
}
if (startBoolean) {
val bitmapCopy = bitmap.copy(bitmap.config, true)
// val manipulatedImage = bitmap.copy(bitmap.config, true)
val manipulatedImage = createBitmap(captureAct.width, captureAct.height)
captureAct.capture(bitmapCopy, manipulatedImage)
runOnUiThread {
binding.imageView.setImageBitmap(manipulatedImage)
}
} else {
val rotatedImage = if (resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT) bitmap.rotate(90f) else bitmap
runOnUiThread {
binding.imageView.setImageBitmap(rotatedImage)
}
}
image.close()
}
private fun Bitmap.rotate(degrees: Float): Bitmap {
val matrix = Matrix().apply { postRotate(degrees) }
return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}
fun startOnClick(view: View) {
if (!startBoolean) {
startButton.text = getString(R.string.OFF)
startBoolean = true
} else {
startButton.text = getString(R.string.ON)
startBoolean = false
imageView.setImageBitmap(null)
}
}
/**
* A native method that is implemented by the 'digitalwhiteboard' native library,
* which is packaged with this application.
*/
companion object {
// Used to load the 'digitalwhiteboard' library on application startup.
init {
System.loadLibrary("digitalwhiteboard")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
432a7fa176da555dc21d91264a4524a5e73a4d70
| 7,923
|
DigitalWhiteboard
|
MIT License
|
image/src/main/java/com/smarttoolfactory/image/transform/MorphLayout.kt
|
T8RIN
| 478,710,402
| false
| null |
package com.smarttoolfactory.image.transform
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.*
/**
* Composable that changes dimensions of its content from handles, translates its position
* when dragged inside bounds
*
* @param modifier is modifier of Composable used as [content]
* @param containerModifier is modifier of SubcomposeLayout that measures content. Do not
* set a **Size** modifier because [MorphSubcomposeLayout] measures with unbounded constraints
* and size of this composable is changed. If you set a fixed size, size won't be calculated
* accurately.
* @param enabled flag for enabling morph operations and border and handle display
* @param handleRadius radius of circular handles to implement morphing operations
* @param handlePlacement determines how handles should be placed. They can be placed at corners
* ot center of each side or both.
* @param updatePhysicalSize when true this Composable's width inside parent is updated and
* siblings get updated according to updated dimensions
* @param onDown callback invoked when gesture has started
* @param onMove callback notifies composable has a pointer down and invoking operations
* @param onUp notifies last pointer down is now up
* @param content is the composable that will be contained in this Composable
*/
@Composable
fun MorphLayout(
modifier: Modifier = Modifier,
containerModifier: Modifier = Modifier,
enabled: Boolean = true,
handleRadius: Dp = 15.dp,
handlePlacement: HandlePlacement = HandlePlacement.Corner,
updatePhysicalSize: Boolean = false,
onDown: () -> Unit = {},
onMove: (DpSize) -> Unit = {},
onUp: () -> Unit = {},
content: @Composable () -> Unit
) {
MorphSubcomposeLayout(
modifier = containerModifier,
handleRadius = handleRadius,
updatePhysicalSize = updatePhysicalSize,
mainContent = {
Box(
modifier = modifier,
contentAlignment = Alignment.Center
) {
content()
}
},
dependentContent = { intSize: IntSize, constraints: Constraints ->
val dpSize = with(LocalDensity.current) {
val rawWidth = intSize.width.toDp()
val rawHeight = intSize.height.toDp()
DpSize(rawWidth, rawHeight)
}
MorphLayout(
handleRadius = handleRadius,
enabled = enabled,
dpSize = dpSize,
constraints = constraints,
handlePlacement = handlePlacement,
onDown = onDown,
onMove = onMove,
onUp = onUp,
content = content
)
}
)
}
@Composable
private fun MorphLayout(
enabled: Boolean = true,
handleRadius: Dp,
dpSize: DpSize,
constraints: Constraints,
handlePlacement: HandlePlacement,
onDown: () -> Unit = {},
onMove: (DpSize) -> Unit = {},
onUp: () -> Unit = {},
content: @Composable () -> Unit
) {
val density = LocalDensity.current
val touchRegionRadius: Float
val minDimension: Float
val initialSize = remember {
DpSize(
dpSize.width + handleRadius * 2,
dpSize.height + handleRadius * 2
)
}
var updatedSize by remember {
mutableStateOf(initialSize)
}
with(density) {
touchRegionRadius = handleRadius.toPx()
minDimension =
(touchRegionRadius * if (handlePlacement == HandlePlacement.Corner) 4 else 6)
}
val rectDraw = remember(updatedSize) {
with(density) {
val width = updatedSize.width.toPx().coerceAtMost(constraints.maxWidth.toFloat())
val height = updatedSize.height.toPx().coerceAtMost(constraints.maxHeight.toFloat())
Rect(offset = Offset.Zero, size = Size(width, height))
}
}
val editModifier = Modifier
.morph(
enabled = enabled,
initialSize = initialSize,
touchRegionRadius = touchRegionRadius,
minDimension = minDimension,
constraints = constraints,
handlePlacement = handlePlacement,
onDown = onDown,
onMove = { dpSizeChange: DpSize ->
updatedSize = dpSizeChange
onMove(updatedSize)
},
onUp = onUp
)
val transformModifier = Modifier
.padding(handleRadius)
.fillMaxSize()
ResizeImpl(
modifier = editModifier,
transformModifier = transformModifier,
enabled = enabled,
touchRegionRadius = touchRegionRadius,
rectDraw = rectDraw,
handlePlacement = handlePlacement,
content = content
)
}
@Composable
private fun ResizeImpl(
modifier: Modifier,
transformModifier: Modifier,
enabled: Boolean,
touchRegionRadius: Float,
rectDraw: Rect,
handlePlacement: HandlePlacement,
content: @Composable () -> Unit
) {
Box(
modifier = modifier,
contentAlignment = Alignment.Center
) {
Box(
modifier = transformModifier,
contentAlignment = Alignment.Center
) {
content()
}
if (enabled) {
HandleOverlay(
modifier = Modifier.fillMaxSize(),
radius = touchRegionRadius,
rectDraw = rectDraw,
handlePlacement = handlePlacement
)
}
}
}
| 14
|
Kotlin
|
47
| 568
|
bf80cfe6bc19e7d2cd163b060b5231fafa1bdd74
| 5,953
|
ImageToolbox
|
Apache License 2.0
|
core/usecases/src/main/kotlin/location/listAllLocations/LocationItem.kt
|
Soyle-Productions
| 239,407,827
| false
| null |
package com.soyle.stories.usecase.location.listAllLocations
import com.soyle.stories.domain.location.Location
class LocationItem(
val id: Location.Id,
val locationName: String
)
| 45
|
Kotlin
|
0
| 9
|
1a110536865250dcd8d29270d003315062f2b032
| 183
|
soyle-stories
|
Apache License 2.0
|
src/main/kotlin/com/madrapps/dagger/actions/CollapseAllAction.kt
|
Madrapps
| 245,758,107
| false
| null |
package com.madrapps.dagger.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.util.ui.tree.TreeUtil
import com.madrapps.dagger.services.service
class CollapseAllAction : AnAction() {
companion object {
const val ID = "com.madrapps.dagger.actions.CollapseAllAction"
}
override fun update(e: AnActionEvent) {
super.update(e)
val project = e.project
if (project != null) {
val treeModel = project.service.treeModel
e.presentation.isEnabled = treeModel.root != null
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project
if (project != null) {
val panel = project.service.getPanel()
if (panel != null) {
val tree = panel.tree
TreeUtil.collapseAll(tree, 0)
}
}
}
}
| 13
|
Kotlin
|
7
| 27
|
e75ebab16eb85139d55b4d31f04021938671a384
| 950
|
dagger-plugin
|
Apache License 2.0
|
app/src/main/java/com/example/sunnyweather/android/logic/Repository/PlaceRepository.kt
|
zeroxzp111
| 785,563,668
| false
|
{"Kotlin": 27946}
|
package com.example.sunnyweather.android.logic.Repository
import androidx.lifecycle.LiveData
import androidx.lifecycle.liveData
import com.example.sunnyweather.android.SunnyWeatherApplication
import com.example.sunnyweather.android.logic.dao.PlaceDao
import com.example.sunnyweather.android.logic.database.AppDatabase
import com.example.sunnyweather.android.logic.model.DataPlace
import com.example.sunnyweather.android.logic.model.Location
import com.example.sunnyweather.android.logic.model.Place
import kotlinx.coroutines.Dispatchers
import kotlin.coroutines.CoroutineContext
object PlaceRepository {
private val dao=AppDatabase.getDatabase(SunnyWeatherApplication.context)
fun getAllPlace():LiveData<List<DataPlace>>{
return dao.placeDao().getAllPlace()
}
suspend fun deletePlace(place: DataPlace){
dao.placeDao().deletePlace(place)
}
suspend fun addPlace(place: DataPlace){
dao.placeDao().insertPlace(place)
}
suspend fun clearAll(){
dao.placeDao().deleteAllPlace()
}
suspend fun getCount(){
dao.placeDao().getCount()
}
}
| 0
|
Kotlin
|
0
| 0
|
30593376bf7c740ac1f84c7e7ffefcae3dfe7705
| 1,118
|
SunnyWeather
|
Apache License 2.0
|
src/main/kotlin/csense/idea/base/bll/psiWrapper/class/operations/filter/NonRelated.kt
|
csense-oss
| 226,373,994
| false
|
{"Kotlin": 148126}
|
@file:Suppress("unused")
package csense.idea.base.bll.psiWrapper.`class`.operations.filter
import csense.idea.base.bll.psiWrapper.`class`.*
import csense.idea.base.bll.psiWrapper.`class`.operations.`is`.*
//TODO java and kotlin "common hierachies" not handled correctly in JVM case (where "Exception" != Exception & for throwable..)
fun List<KtPsiClass>.filterNonRelated(to: List<KtPsiClass>): List<KtPsiClass> {
//TODO caching etc? compute a map of "classes" and then going over the other and testing?
return this.filterNot {
it.isSubTypeOfAny(to)
}
}
| 0
|
Kotlin
|
0
| 0
|
8a31fff3774261bedc4caec23ba817ed9a335bca
| 576
|
idea-kotlin-shared-base
|
MIT License
|
app/src/debug/kotlin/io/plastique/inject/modules/DebugInitializerModule.kt
|
plastiqueapp
| 150,879,887
| false
| null |
package io.plastique.inject.modules
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoSet
import io.plastique.core.init.FlipperInitializer
import io.plastique.core.init.Initializer
import timber.log.Timber
@Module(includes = [InitializerModule::class])
abstract class DebugInitializerModule {
@Binds
@IntoSet
abstract fun bindFlipperInitializer(impl: FlipperInitializer): Initializer
companion object {
@Provides
@IntoSet
fun provideDebugTree(): Timber.Tree = Timber.DebugTree()
}
}
| 0
|
Kotlin
|
2
| 9
|
9271853f3741add18822858cbad9d4f8e8104f54
| 576
|
plastique
|
Apache License 2.0
|
src/main/kotlin/io/zeko/db/sql/Insert.kt
|
darkredz
| 253,306,508
| false
| null |
package io.zeko.db.sql
import io.zeko.db.sql.utilities.toSnakeCase
import io.zeko.model.Entity
open class Insert : DataManipulation {
protected var duplicateUpdateFields: Map<String, Any?>? = null
protected var ignore = false
protected var select: Query? = null
protected var insertFields: List<String>? = null
constructor(entity: Entity, parameterize: Boolean = false, espTableName: Boolean = false) {
this.entity = entity
this.parameterize = parameterize
this.espTableName = espTableName
}
constructor(entity: Entity, vararg columns: String) {
this.entity = entity
this.insertFields = arrayListOf(*columns)
}
override fun escapeTable(espTableName: Boolean): Insert {
super.escapeTable(espTableName)
return this
}
fun select(query: Query): Insert {
select = query
return this
}
fun ignore(): Insert {
this.ignore = true
return this
}
fun onDuplicateUpdate(fields: Map<String, Any?>?): Insert {
duplicateUpdateFields = fields
return this
}
override fun toSql(): String {
var sql = if (ignore)
"INSERT IGNORE INTO " + getTableName()
else
"INSERT INTO " + getTableName()
var columns = arrayListOf<String>()
var values = arrayListOf<String>()
val onDuplicatePart = arrayListOf<String>()
var onDuplicateSql = ""
if (duplicateUpdateFields != null) {
// ON DUPLICATE KEY UPDATE
for ((propName, value) in duplicateUpdateFields!!) {
if (value != null) {
if (parameterize) {
if (value is QueryBlock){
onDuplicatePart.add("$propName = $value")
} else {
onDuplicatePart.add("$propName = ?")
}
} else {
if (value is String) {
onDuplicatePart.add("$propName = '${value.replace("'", "''")}'")
} else if (value is QueryBlock){
onDuplicatePart.add("$propName = $value")
} else {
onDuplicatePart.add("$propName = $value")
}
}
}
}
onDuplicateSql = " ON DUPLICATE KEY UPDATE " + onDuplicatePart.joinToString(", ")
}
if (entity.dataMap().isNotEmpty()) {
val entries = entity.dataMap().entries
val ignores = entity.ignoreFields()
for ((propName, value) in entries) {
if (ignores.isNotEmpty() && ignores.indexOf(propName) > -1) continue
val prop = propName.toSnakeCase()
if (shouldIgnoreType(value)) continue
columns.add(prop)
if (parameterize) {
values.add("?")
} else {
if (value is String) {
values.add("'${value.replace("'", "''")}'")
} else {
values.add(value.toString())
}
}
}
sql += " ( " + columns.joinToString(", ") + " ) "
sql += "VALUES ( " + values.joinToString(", ") + " ) "
} else if (insertFields != null) {
sql += " ( " + insertFields?.joinToString(", ") + " ) "
} else {
sql += " "
}
if (this.select != null) {
sql += this.select?.toSql()
}
sql += onDuplicateSql
return sql.trimEnd()
}
}
| 2
|
Kotlin
|
6
| 89
|
a70f6d207d77048f690d0d728e22091fe152dda8
| 3,721
|
Zeko-SQL-Builder
|
Apache License 2.0
|
SS-W-Core/src/main/kotlin/com/github/syari/ss/wplugins/core/scheduler/CreateScheduler.kt
|
SecondStoryServer
| 314,996,172
| false
| null |
package com.github.syari.ss.wplugins.core.scheduler
import com.github.syari.ss.wplugins.core.Main.Companion.plugin
import net.md_5.bungee.api.plugin.Plugin
object CreateScheduler {
/**
* @param action 実行する処理
* @return [CustomRunnable]
*/
fun Plugin.schedule(
action: CustomTask.() -> Unit
): CustomRunnable {
return CustomRunnable(this, action)
}
/**
* @param action 実行する処理
* @return [CustomTask]?
*/
fun Plugin.runSchedule(
action: CustomTask.() -> Unit
): CustomTask? {
return schedule(action).runSchedule()
}
/**
* @param delay 遅らせる時間 tick
* @param action 遅らせて実行する処理
* @return [CustomTask]?
*/
fun Plugin.runLater(
delay: Long,
action: CustomTask.() -> Unit
): CustomTask? {
return schedule(action).runLater(delay)
}
/**
* @param period 繰り返し間隔 tick
* @param delay 遅らせる時間 tick default: 0
* @param action 繰り返し実行する処理
* @return [CustomTask]?
*/
fun Plugin.runTimer(
period: Long,
delay: Long = 0,
action: CustomTask.() -> Unit
): CustomTask? {
return schedule(action).runTimer(period, delay)
}
/**
* @param period 繰り返し間隔 tick
* @param times 繰り返し回数
* @param delay 遅らせる時間 tick default: 0
* @param action 繰り返し実行する処理
* @return [CustomTask]?
*/
fun Plugin.runRepeatTimes(
period: Long,
times: Int,
delay: Long = 0,
action: CustomTask.() -> Unit
): CustomTask? {
return schedule(action).runRepeatTimes(period, times, delay)
}
/**
* @param listWithDelay キーを待機時間としたマップ
* @param action 待機後に実行する処理
* @return [Set]<[CustomTask]>
*/
fun <T> runListWithDelay(
listWithDelay: Map<Long, Set<T>>,
action: (T) -> Unit
): Set<CustomTask> {
return mutableSetOf<CustomTask>().also { taskList ->
listWithDelay.forEach { (delay, value) ->
plugin.runLater(delay) {
plugin.runSchedule {
value.forEach {
action.invoke(it)
}
}
taskList.remove(this)
}?.let { taskList.add(it) }
}
}
}
}
| 25
|
Kotlin
|
1
| 2
|
9af898e4eef290b8a2e4c0f75e3f99afb0b19e57
| 2,338
|
SS-Plugins
|
Apache License 2.0
|
src/main/kotlin/modules/m4storage/ItemStorage.kt
|
glehu
| 384,708,417
| false
| null |
package modules.m4storage
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class ItemStorage(
@SerialName("n") val number: Long,
@SerialName("d") val description: String = "",
@SerialName("l") var locked: Boolean = false
) {
@SerialName("su")
var storageUnits: MutableList<ItemStorageUnit> = mutableListOf()
}
| 6
|
Kotlin
|
1
| 0
|
f05e2e92d316f552bde9d5a382b26fb52a2e6184
| 374
|
CWO_ERP
|
MIT License
|
app/src/main/java/com/pchasapis/cryptocurrency/network/client/Deserializer.kt
|
pandelisgreen13
| 197,902,982
| false
| null |
package com.pchasapis.cryptocurrency.network.client
import androidx.annotation.Nullable
import com.google.gson.*
import com.pchasapis.cryptocurrency.models.parsers.crypto.timeFrame.TimeFrameResponse
import java.lang.reflect.Type
import com.google.gson.JsonElement
import com.pchasapis.cryptocurrency.models.parsers.crypto.timeFrame.TimeFrame
class Deserializer : JsonDeserializer<TimeFrameResponse> {
companion object {
const val KEY_RATES = "rates"
const val KEY_TIME_FRAME = "timeframe"
const val KEY_START_DATE = "start_date"
const val KEY_END_DATE = "end_date"
const val KEY_TARGET = "target"
const val KEY_SUCCESS = "success"
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): TimeFrameResponse {
val jsonObject = json.asJsonObject
// Read simple String values.
val success = jsonObject.get(KEY_SUCCESS).asBoolean
val timeFrame = jsonObject.get(KEY_TIME_FRAME).asBoolean
val startDate = jsonObject.get(KEY_START_DATE).asString
val endDate = jsonObject.get(KEY_END_DATE).asString
val target = jsonObject.get(KEY_TARGET).asString
// Read the dynamic parameters object.
val rates = readParametersMap(jsonObject)
return TimeFrameResponse(
success = success,
timeFrame = timeFrame,
startDate = startDate,
endDate = endDate,
target = target,
rates = rates)
}
@Nullable
private fun readParametersMap(jsonObject: JsonObject): MutableList<TimeFrame> {
val paramsElement = jsonObject.get(KEY_RATES) ?: return mutableListOf()
val parametersObject = paramsElement.asJsonObject
val parameters = hashMapOf<String, String>()
val list = mutableListOf<TimeFrame>()
for ((key, value1) in parametersObject.entrySet()) {
val value = value1.toString()
list.add(TimeFrame(key, transformRate(value)))
parameters[key] = value
}
return list
}
private fun transformRate(rate: String): Double {
return rate.substringAfter(":").substringBefore("}").toDouble()
}
}
| 0
|
Kotlin
|
0
| 0
|
21ba7a6b31223e55f5bfe6c2e865437ef7921937
| 2,300
|
CryptoCurrencies
|
MIT License
|
protoc-gen-pbandk/lib/src/jvmMain/kotlin/pbandk/gen/BootstrapConverter.kt
|
streem
| 202,946,849
| false
|
{"Kotlin": 3831371, "Shell": 1992, "Go": 698}
|
package pbandk.gen
import com.google.protobuf.DescriptorProtos
import com.google.protobuf.compiler.PluginProtos
import pbandk.ByteArr
import pbandk.gen.pb.CodeGeneratorRequest
import pbandk.gen.pb.CodeGeneratorResponse
import pbandk.gen.pb.Version
import pbandk.wkt.*
// Simple conversion between JVM protos and Kotlin ones for bootstrapping
internal object BootstrapConverter {
fun fromReq(req: PluginProtos.CodeGeneratorRequest) = req.convert()
fun toResp(resp: CodeGeneratorResponse) = resp.convert()
private fun PluginProtos.CodeGeneratorRequest.convert() = CodeGeneratorRequest(
fileToGenerate = fileToGenerateList,
parameter = parameter.orNull(hasParameter()),
protoFile = protoFileList.map { it.convert() },
compilerVersion = compilerVersion?.let {
Version(
major = it.major.orNull(it.hasMajor()),
minor = it.minor.orNull(it.hasMinor()),
patch = it.patch.orNull(it.hasPatch()),
suffix = it.suffix.orNull(it.hasSuffix())
)
}
)
private fun DescriptorProtos.FileDescriptorProto.convert() = FileDescriptorProto(
name = name.orNull(hasName()),
`package` = `package`.orNull(hasPackage()),
dependency = dependencyList,
publicDependency = publicDependencyList,
weakDependency = weakDependencyList,
messageType = messageTypeList.map { it.convert() },
enumType = enumTypeList.map { it.convert() },
service = serviceList.map { it.convert() },
extension = extensionList.map { it.convert() },
options = options?.let {
FileOptions(
javaPackage = it.javaPackage.orNull(it.hasJavaPackage()),
javaOuterClassname = it.javaOuterClassname.orNull(it.hasJavaOuterClassname()),
javaMultipleFiles = it.javaMultipleFiles.orNull(it.hasJavaMultipleFiles()),
javaStringCheckUtf8 = it.javaStringCheckUtf8.orNull(it.hasJavaStringCheckUtf8()),
optimizeFor = it.optimizeFor?.number?.let { FileOptions.OptimizeMode.fromValue(it) },
goPackage = it.goPackage.orNull(it.hasGoPackage()),
ccGenericServices = it.ccGenericServices.orNull(it.hasCcGenericServices()),
javaGenericServices = it.javaGenericServices.orNull(it.hasJavaGenericServices()),
pyGenericServices = it.pyGenericServices.orNull(it.hasPyGenericServices()),
deprecated = it.deprecated.orNull(it.hasDeprecated()),
ccEnableArenas = it.ccEnableArenas.orNull(it.hasCcEnableArenas()),
objcClassPrefix = it.objcClassPrefix.orNull(it.hasObjcClassPrefix()),
csharpNamespace = it.csharpNamespace.orNull(it.hasCsharpNamespace()),
swiftPrefix = it.swiftPrefix.orNull(it.hasSwiftPrefix()),
phpClassPrefix = it.phpClassPrefix.orNull(it.hasPhpClassPrefix()),
phpNamespace = it.phpNamespace.orNull(it.hasPhpNamespace()),
phpMetadataNamespace = it.phpMetadataNamespace.orNull(it.hasPhpMetadataNamespace()),
rubyPackage = it.rubyPackage.orNull(it.hasRubyPackage()),
features = it.features?.convert(),
uninterpretedOption = it.uninterpretedOptionList.map { it.convert() }
)
},
sourceCodeInfo = sourceCodeInfo?.let {
SourceCodeInfo(location = it.locationList.map {
SourceCodeInfo.Location(
path = it.pathList,
span = it.spanList,
leadingComments = it.leadingComments.orNull(it.hasLeadingComments()),
trailingComments = it.trailingComments.orNull(it.hasTrailingComments()),
leadingDetachedComments = it.leadingDetachedCommentsList
)
})
},
syntax = syntax.orNull(hasSyntax()),
edition = edition.number.orNull(hasEdition())?.let { Edition.fromValue(it) },
)
private fun DescriptorProtos.UninterpretedOption.convert() = UninterpretedOption(
name = nameList.map { UninterpretedOption.NamePart(namePart = it.namePart, isExtension = false) },
stringValue = stringValue?.let { ByteArr(it.toByteArray()) }
)
private fun DescriptorProtos.DescriptorProto.convert(): DescriptorProto = DescriptorProto(
name = name.orNull(hasName()),
field = fieldList.map { it.convert() },
extension = fieldList.map { it.convert() },
nestedType = nestedTypeList.map { it.convert() },
enumType = enumTypeList.map { it.convert() },
extensionRange = extensionRangeList.map {
DescriptorProto.ExtensionRange(
start = it.start.orNull(it.hasStart()),
end = it.end.orNull(it.hasEnd()),
options = it.options?.let {
ExtensionRangeOptions(
uninterpretedOption = it.uninterpretedOptionList.map { it.convert() },
declaration = it.declarationList.map { it.convert() },
features = it.features?.convert(),
verification = it.verification?.number?.let {
ExtensionRangeOptions.VerificationState.fromValue(it)
}
)
}
)
},
oneofDecl = oneofDeclList.map { it.convert() },
options = options?.let {
@Suppress("DEPRECATION")
MessageOptions(
messageSetWireFormat = it.messageSetWireFormat.orNull(it.hasMessageSetWireFormat()),
noStandardDescriptorAccessor =
it.noStandardDescriptorAccessor.orNull(it.hasNoStandardDescriptorAccessor()),
deprecated = it.deprecated.orNull(it.hasDeprecated()),
mapEntry = it.mapEntry.orNull(it.hasMapEntry()),
deprecatedLegacyJsonFieldConflicts = it.deprecatedLegacyJsonFieldConflicts.orNull(it.hasDeprecatedLegacyJsonFieldConflicts()),
features = it.features?.convert(),
uninterpretedOption = it.uninterpretedOptionList.map { it.convert() }
)
},
reservedRange = reservedRangeList.map {
DescriptorProto.ReservedRange(start = it.start.orNull(it.hasStart()), end = it.end.orNull(it.hasEnd()))
},
reservedName = reservedNameList
)
private fun DescriptorProtos.ExtensionRangeOptions.Declaration.convert() = ExtensionRangeOptions.Declaration(
number = number.orNull(hasNumber()),
fullName = fullName.orNull(hasFullName()),
type = type.orNull(hasType()),
reserved = reserved.orNull(hasReserved()),
repeated = repeated.orNull(hasRepeated()),
)
private fun DescriptorProtos.FeatureSet.convert() = FeatureSet(
fieldPresence = fieldPresence?.number?.let { FeatureSet.FieldPresence.fromValue(it) },
enumType = enumType?.number?.let { FeatureSet.EnumType.fromValue(it) },
repeatedFieldEncoding = repeatedFieldEncoding?.number?.let { FeatureSet.RepeatedFieldEncoding.fromValue(it) },
utf8Validation = utf8Validation?.number?.let { FeatureSet.Utf8Validation.fromValue(it) },
messageEncoding = messageEncoding?.number?.let { FeatureSet.MessageEncoding.fromValue(it) },
jsonFormat = jsonFormat?.number?.let { FeatureSet.JsonFormat.fromValue(it) },
)
private fun DescriptorProtos.EnumDescriptorProto.convert() = EnumDescriptorProto(
name = name.orNull(hasName()),
value = valueList.map {
EnumValueDescriptorProto(
name = it.name.orNull(it.hasName()),
number = it.number.orNull(it.hasNumber()),
options = it.options?.let {
EnumValueOptions(
deprecated = it.deprecated.orNull(it.hasDeprecated()),
features = it.features?.convert(),
debugRedact = it.debugRedact.orNull(it.hasDebugRedact()),
featureSupport = it.featureSupport?.convert(),
uninterpretedOption = it.uninterpretedOptionList.map { it.convert() }
)
}
)
},
options = options?.let {
@Suppress("DEPRECATION")
EnumOptions(
allowAlias = it.allowAlias.orNull(it.hasAllowAlias()),
deprecated = it.deprecated.orNull(it.hasDeprecated()),
deprecatedLegacyJsonFieldConflicts = it.deprecatedLegacyJsonFieldConflicts.orNull(it.hasDeprecatedLegacyJsonFieldConflicts()),
features = it.features?.convert(),
uninterpretedOption = it.uninterpretedOptionList.map { it.convert() }
)
},
reservedRange = reservedRangeList.map {
EnumDescriptorProto.EnumReservedRange(
start = it.start.orNull(it.hasStart()),
end = it.end.orNull(it.hasEnd())
)
},
reservedName = reservedNameList
)
private fun DescriptorProtos.ServiceDescriptorProto.convert() = ServiceDescriptorProto(
name = name.orNull(hasName()),
method = methodList.map {
MethodDescriptorProto(
name = it.name.orNull(it.hasName()),
inputType = it.inputType.orNull(it.hasInputType()),
outputType = it.outputType.orNull(it.hasOutputType()),
options = it.options?.let {
MethodOptions(
deprecated = it.deprecated.orNull(it.hasDeprecated()),
idempotencyLevel =
it.idempotencyLevel?.number?.let { MethodOptions.IdempotencyLevel.fromValue(it) },
features = it.features?.convert(),
uninterpretedOption = it.uninterpretedOptionList.map { it.convert() }
)
},
clientStreaming = it.clientStreaming.orNull(it.hasClientStreaming()),
serverStreaming = it.serverStreaming.orNull(it.hasServerStreaming())
)
},
options = options?.let {
ServiceOptions(
features = it.features?.convert(),
deprecated = it.deprecated.orNull(it.hasDeprecated()),
uninterpretedOption = it.uninterpretedOptionList.map { it.convert() }
)
}
)
private fun DescriptorProtos.OneofDescriptorProto.convert() = OneofDescriptorProto(
name = name.orNull(hasName()),
options = options?.let {
OneofOptions(
features = it.features?.convert(),
uninterpretedOption = it.uninterpretedOptionList.map { it.convert() },
)
}
)
private fun DescriptorProtos.FieldDescriptorProto.convert() = FieldDescriptorProto(
name = name.orNull(hasName()),
number = number.orNull(hasNumber()),
label = label.number.orNull(hasLabel())?.let { FieldDescriptorProto.Label.fromValue(it) },
type = type.number.orNull(hasType())?.let { FieldDescriptorProto.Type.fromValue(it) },
typeName = typeName.orNull(hasTypeName()),
extendee = extendee.orNull(hasExtendee()),
defaultValue = defaultValue.orNull(hasDefaultValue()),
oneofIndex = oneofIndex.orNull(hasOneofIndex()),
jsonName = jsonName.orNull(hasJsonName()),
options = options?.let {
FieldOptions(
ctype = it.ctype?.number?.let { FieldOptions.CType.fromValue(it) },
packed = it.packed.orNull(it.hasPacked()),
jstype = it.jstype?.number?.let { FieldOptions.JSType.fromValue(it) },
lazy = it.lazy.orNull(it.hasLazy()),
unverifiedLazy = it.unverifiedLazy.orNull(it.hasUnverifiedLazy()),
deprecated = it.deprecated.orNull(it.hasDeprecated()),
weak = it.weak.orNull(it.hasWeak()),
debugRedact = it.debugRedact.orNull(it.hasDebugRedact()),
retention = it.retention?.number?.let { FieldOptions.OptionRetention.fromValue(it) },
targets = it.targetsList.map { FieldOptions.OptionTargetType.fromValue(it.number) },
editionDefaults = it.editionDefaultsList.map { it.convert() },
features = it.features?.convert(),
featureSupport = it.featureSupport?.convert(),
uninterpretedOption = it.uninterpretedOptionList.map { it.convert() }
)
}
)
private fun DescriptorProtos.FieldOptions.EditionDefault.convert() = FieldOptions.EditionDefault(
edition = edition?.number?.let { Edition.fromValue(it) },
value = value.orNull(hasValue()),
)
private fun DescriptorProtos.FieldOptions.FeatureSupport.convert() = FieldOptions.FeatureSupport(
editionIntroduced = editionIntroduced.number.orNull(hasEditionIntroduced())?.let { Edition.fromValue(it) },
editionDeprecated = editionDeprecated.number.orNull(hasEditionDeprecated())?.let { Edition.fromValue(it) },
deprecationWarning = deprecationWarning.orNull(hasDeprecationWarning()),
editionRemoved = editionRemoved.number.orNull(hasEditionRemoved())?.let { Edition.fromValue(it) },
)
private fun CodeGeneratorResponse.convert() = PluginProtos.CodeGeneratorResponse.newBuilder().apply {
error?.also { error = it }
addAllFile(file.map {
PluginProtos.CodeGeneratorResponse.File.newBuilder().apply {
it.name?.also { name = it }
it.insertionPoint?.also { insertionPoint = it }
it.content?.also { content = it }
}.build()
})
}.build()
private fun String?.orNull(cond: Boolean) = if (cond) this else null
private fun Int?.orNull(cond: Boolean) = if (cond) this else null
private fun Boolean?.orNull(cond: Boolean) = if (cond) this else null
}
| 42
|
Kotlin
|
38
| 264
|
90938ee880f744ef120cb749e8ffe6aa20ec7f81
| 14,095
|
pbandk
|
MIT License
|
app/src/main/java/info/juanmendez/breedgallery/ui/breedlist/adapter/BreedListAdapter.kt
|
juanmendez
| 121,443,075
| false
| null |
package info.juanmendez.breedgallery.ui.breedlist.adapter
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.OnLifecycleEvent
import android.databinding.Observable
import android.databinding.Observable.OnPropertyChangedCallback
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.android.databinding.library.baseAdapters.BR
import info.juanmendez.breedgallery.databinding.ViewPetItemBinding
import info.juanmendez.breedgallery.ui.breedlist.BreedListView
/**
* Created by <NAME> on 2/14/18.
* Through dataBinding the recyclerView can have a binding reference and refresh its content
* upon changes triggered at breadListObservable.breedList
*/
class BreedListAdapter(private val inflater: LayoutInflater, view: BreedListView) : RecyclerView.Adapter<BreedItemHolder>(),
LifecycleObserver {
private val mObservable = view.getBreadListObservable()
private lateinit var mCallBack: OnPropertyChangedCallback
init {
view.getLifeCycle().addObserver(this)
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): BreedItemHolder {
var binding = ViewPetItemBinding.inflate(inflater, parent, false)
binding.breedListObservable = mObservable
return BreedItemHolder(binding)
}
override fun getItemCount(): Int = mObservable.breedList.size
override fun onBindViewHolder(holder: BreedItemHolder?, position: Int) {
holder?.setBreed(mObservable.breedList[position])
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
mCallBack = object : OnPropertyChangedCallback() {
override fun onPropertyChanged(observable: Observable?, br: Int) {
if (br == BR.breedList) {
notifyDataSetChanged()
}
}
}
mObservable.addOnPropertyChangedCallback(mCallBack)
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
mObservable.removeOnPropertyChangedCallback(mCallBack)
}
}
| 0
|
Kotlin
|
0
| 1
|
bb108ca4648466c66eebc437884388f9875dc9f7
| 2,139
|
PetGallery
|
The Unlicense
|
Music Wiki/MusicWiki/app/src/main/java/com/adityamshidlyali/musicwiki/viewmodel/ArtistInfoViewModel.kt
|
AdityaShidlyali
| 591,732,762
| false
| null |
package com.adityamshidlyali.musicwiki.viewmodel
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.adityamshidlyali.musicwiki.model.artistmodel.ArtistInfo
import com.adityamshidlyali.musicwiki.network.Resource
import com.adityamshidlyali.musicwiki.repository.ArtistInfoRepository
import com.adityamshidlyali.musicwiki.utility.DispatcherProvider
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* viewmodel to hold the result of artist's information from the network calls
* and also manages the network call events
*/
@HiltViewModel
class ArtistInfoViewModel @Inject constructor(
private val artistInfoRepository: ArtistInfoRepository,
private val dispatchers: DispatcherProvider
) : ViewModel() {
private val TAG = javaClass.simpleName
sealed class GetArtistInfoEvent {
class Success(val artistInfo: ArtistInfo) :
GetArtistInfoEvent()
class Failure(val errorText: String) : GetArtistInfoEvent()
object Loading : GetArtistInfoEvent()
object Empty : GetArtistInfoEvent()
}
private val _artistInfoStateFlow =
MutableStateFlow<GetArtistInfoEvent>(GetArtistInfoEvent.Empty)
val artistInfoStateFlow: MutableStateFlow<GetArtistInfoEvent> = _artistInfoStateFlow
fun getArtistInfo(
api_key: String,
format: String,
method: String,
artist: String
) {
viewModelScope.launch(dispatchers.io) {
_artistInfoStateFlow.value = GetArtistInfoEvent.Loading
when (val genreTagResponse =
artistInfoRepository.getArtistInfo(api_key, format, method, artist)) {
is Resource.Error -> {
Log.d(TAG, genreTagResponse.message.toString())
_artistInfoStateFlow.value =
GetArtistInfoEvent.Failure(genreTagResponse.message.toString())
}
is Resource.Success -> {
Log.d(TAG, genreTagResponse.data.toString())
_artistInfoStateFlow.value =
GetArtistInfoEvent.Success(genreTagResponse.data!!.artist)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8170c323fec9c628249b3b85999666a15bc415fa
| 2,345
|
MusicWiki_Assessment
|
MIT License
|
infra/src/fanpoll/infra/redis/ktorio/utils/Deferred.kt
|
csieflyman
| 359,559,498
| false
|
{"Kotlin": 785294, "JavaScript": 17435, "HTML": 6167, "PLpgSQL": 5563, "Dockerfile": 126}
|
package fanpoll.infra.redis.ktorio.utils
import kotlinx.coroutines.CompletableDeferred
/**
* Use [block] to complete [deferred], also handles [block] exceptions
*/
inline fun <T> completeWith(deferred: CompletableDeferred<T>, block: () -> T) {
try {
deferred.complete(block())
} catch (cause: Throwable) {
deferred.completeExceptionally(cause)
}
}
| 1
|
Kotlin
|
9
| 74
|
1a7d54115dbc42c6a02230f527d9ad56862b4a0b
| 380
|
multi-projects-architecture-with-Ktor
|
MIT License
|
app/src/main/java/com/example/islamiapp/Adapters/SingleHadithAdapter.kt
|
Ahmed-Ssalem
| 408,444,696
| false
| null |
package com.example.islamiapp.Adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.islamiapp.R
class SingleHadithAdapter(var items: List<String>) : RecyclerView.Adapter<SingleHadithAdapter.hadithsViewHolder>() {
class hadithsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var hadithText: TextView = itemView.findViewById(R.id.single_hadith_text)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): hadithsViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_single_hadith, parent, false)
return hadithsViewHolder(
view
)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: hadithsViewHolder, position: Int) {
val item = items[position]
holder.hadithText.text = item
}
}
| 0
|
Kotlin
|
0
| 1
|
0fd7d080d25ca5802a2f12f1b05acc46e3b805d7
| 1,028
|
IslamiApp
|
Apache License 2.0
|
components/notification/impl/src/main/java/com/flipperdevices/notification/viewmodel/NotificationDialogViewModel.kt
|
flipperdevices
| 288,258,832
| false
|
{"Kotlin": 2884316, "FreeMarker": 10352, "CMake": 1780, "C++": 1152, "Fluent": 21}
|
package com.flipperdevices.notification.viewmodel
import androidx.datastore.core.DataStore
import androidx.lifecycle.viewModelScope
import com.flipperdevices.core.di.provideDelegate
import com.flipperdevices.core.preference.pb.Settings
import com.flipperdevices.core.ui.lifecycle.DecomposeViewModel
import com.flipperdevices.notification.api.FlipperAppNotificationApi
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.runBlocking
import javax.inject.Inject
import javax.inject.Provider
class NotificationDialogViewModel @Inject constructor(
settingsProvider: Provider<DataStore<Settings>>,
flipperNotificationApiProvider: Provider<FlipperAppNotificationApi>,
coroutineScopeProvider: Provider<CoroutineScope>
) : DecomposeViewModel() {
private val settings by settingsProvider
private val flipperNotificationApi by flipperNotificationApiProvider
private val coroutineScope by coroutineScopeProvider
private val isNotificationShownStateFlow = MutableStateFlow(false)
init {
settings.data.onEach {
isNotificationShownStateFlow.emit(it.notificationDialogShown.not())
}.launchIn(viewModelScope)
}
fun isNotificationShown(): StateFlow<Boolean> = isNotificationShownStateFlow.asStateFlow()
fun onEnableNotification() {
flipperNotificationApi.setSubscribeToUpdateAsync(
isSubscribe = true,
scope = coroutineScope,
withNotificationSuccess = true
)
onDismiss()
}
fun onDismiss() {
runBlocking {
settings.updateData {
it.toBuilder()
.setNotificationDialogShown(true)
.build()
}
}
}
}
| 14
|
Kotlin
|
142
| 1,198
|
07b4174d50e3189d688f0e12ada04bda41322953
| 1,946
|
Flipper-Android-App
|
MIT License
|
app/src/main/java/com/pratiksha/tmdbclient/di/UseCaseModule.kt
|
pratiksha2404
| 448,978,588
| false
| null |
package com.pratiksha.tmdbclient.di
import com.pratiksha.tmdbclient.data.MovieRepository
import com.pratiksha.tmdbclient.domain.SearchMovieUseCase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class UseCaseModule {
@Provides
@Singleton
fun provideSearchMovieUseCase(repository: MovieRepository): SearchMovieUseCase {
return SearchMovieUseCase(repository)
}
}
| 0
|
Kotlin
|
0
| 0
|
adeef3f27e9b65e0258f746f6927057d16c3a910
| 537
|
TMDb-Client
|
Apache License 2.0
|
ChartboostMediation/src/test/java/com/chartboost/chartboostmediationsdk/network/CBMNetworking_getAppConfig_Test.kt
|
ChartBoost
| 647,839,758
| false
|
{"Kotlin": 711726, "Ruby": 2509}
|
/*
* Copyright 2023-2024 Chartboost, Inc.
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file.
*/
package com.chartboost.chartboostmediationsdk.network
import com.chartboost.chartboostmediationsdk.domain.AppConfig
import com.chartboost.chartboostmediationsdk.network.model.ChartboostMediationNetworkingResult
import com.chartboost.chartboostmediationsdk.network.testutils.NetworkTestJsonObjects
import com.chartboost.chartboostmediationsdk.utils.ChartboostMediationJson
import com.chartboost.core.ChartboostCore
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import okhttp3.mockwebserver.MockResponse
import org.junit.Assert
import java.util.concurrent.TimeUnit
fun ChartboostMediationNetworkingTest.`verify result for sdk_init success with new config`() =
runTest {
val expectedResponseHttpCode = 200
MockResponse()
.setResponseCode(expectedResponseHttpCode)
.setHeader(ChartboostMediationNetworking.INIT_HASH_HEADER_KEY, ChartboostMediationNetworkingTest.INIT_HASH_NEW)
.setBody(NetworkTestJsonObjects.HTTP_200_SDK_INIT_SUCCESS.trimmedJsonString)
.let {
mockWebServer.enqueue(it)
}
launch {
val appSetId = ChartboostCore.analyticsEnvironment.getVendorIdentifier() ?: ""
val response =
ChartboostMediationNetworking.getAppConfig(
ChartboostMediationNetworkingTest.APP_ID,
ChartboostMediationNetworkingTest.INIT_HASH_OLD,
appSetId,
)
val request = mockWebServer.takeRequest(1, TimeUnit.SECONDS)
val expectedRequestUrl = "${Endpoints.Sdk.SDK_INIT.endpoint}/${ChartboostMediationNetworkingTest.APP_ID}"
val expectedRequestInitHashHeaderValue = ChartboostMediationNetworkingTest.INIT_HASH_OLD
val expectedResult =
ChartboostMediationJson.decodeFromString(
AppConfig.serializer(),
NetworkTestJsonObjects.HTTP_200_SDK_INIT_SUCCESS.trimmedJsonString,
)
val actualRequestUrl = request?.requestUrl.toString()
val actualRequestInitHashHeaderValue = request?.getHeader(ChartboostMediationNetworking.INIT_HASH_HEADER_KEY)
val actualRequestDebugHeaderValue = request?.getHeader(ChartboostMediationNetworking.DEBUG_HEADER_KEY)
Assert.assertEquals(expectedRequestUrl, actualRequestUrl)
Assert.assertEquals(
expectedRequestInitHashHeaderValue,
actualRequestInitHashHeaderValue,
)
Assert.assertEquals(ChartboostMediationNetworkingTest.APP_ID, actualRequestDebugHeaderValue)
Assert.assertNotNull(response)
Assert.assertTrue(response is ChartboostMediationNetworkingResult.Success)
val httpCode =
(response as ChartboostMediationNetworkingResult.Success<AppConfig?>).httpCode
Assert.assertEquals(expectedResponseHttpCode, httpCode)
val responseInitHashHeader = response.headers[ChartboostMediationNetworking.INIT_HASH_HEADER_KEY]
Assert.assertEquals(ChartboostMediationNetworkingTest.INIT_HASH_NEW, responseInitHashHeader)
val result = response.body
Assert.assertTrue(expectedResult == result)
}
}
fun ChartboostMediationNetworkingTest.`verify result for sdk_init success with no new config`() =
runTest {
val expectedResponseHttpCode = 204
MockResponse()
.setResponseCode(expectedResponseHttpCode)
.setHeader(ChartboostMediationNetworking.INIT_HASH_HEADER_KEY, ChartboostMediationNetworkingTest.INIT_HASH_NEW)
.let {
mockWebServer.enqueue(it)
}
launch {
val appSetId = ChartboostCore.analyticsEnvironment.getVendorIdentifier() ?: ""
val response =
ChartboostMediationNetworking.getAppConfig(
ChartboostMediationNetworkingTest.APP_ID,
ChartboostMediationNetworkingTest.INIT_HASH_OLD,
appSetId,
)
val request = mockWebServer.takeRequest(1, TimeUnit.SECONDS)
val expectedRequestUrl = "${Endpoints.Sdk.SDK_INIT.endpoint}/${ChartboostMediationNetworkingTest.APP_ID}"
val expectedRequestInitHashHeaderValue = ChartboostMediationNetworkingTest.INIT_HASH_OLD
val actualRequestUrl = request?.requestUrl.toString()
val actualRequestInitHashHeaderValue = request?.getHeader(ChartboostMediationNetworking.INIT_HASH_HEADER_KEY)
val actualRequestDebugHeaderValue = request?.getHeader(ChartboostMediationNetworking.DEBUG_HEADER_KEY)
Assert.assertEquals(expectedRequestUrl, actualRequestUrl)
Assert.assertEquals(
expectedRequestInitHashHeaderValue,
actualRequestInitHashHeaderValue,
)
Assert.assertEquals(ChartboostMediationNetworkingTest.APP_ID, actualRequestDebugHeaderValue)
Assert.assertNotNull(response)
Assert.assertTrue(response is ChartboostMediationNetworkingResult.Success)
val httpCode =
(response as ChartboostMediationNetworkingResult.Success<AppConfig?>).httpCode
Assert.assertEquals(expectedResponseHttpCode, httpCode)
val responseInitHashHeader = response.headers[ChartboostMediationNetworking.INIT_HASH_HEADER_KEY]
Assert.assertEquals(ChartboostMediationNetworkingTest.INIT_HASH_NEW, responseInitHashHeader)
val result = response.body
Assert.assertNull(result)
}
}
fun ChartboostMediationNetworkingTest.`verify result for sdk_init failure due to JSON parsing`() =
runTest {
val expectedResponseHttpCode = 200
MockResponse()
.setResponseCode(expectedResponseHttpCode)
.setHeader(ChartboostMediationNetworking.INIT_HASH_HEADER_KEY, ChartboostMediationNetworkingTest.INIT_HASH_NEW)
.setBody(NetworkTestJsonObjects.HTTP_200_SDK_INIT_FAILURE.trimmedJsonString)
.let {
mockWebServer.enqueue(it)
}
launch {
val appSetId = ChartboostCore.analyticsEnvironment.getVendorIdentifier() ?: ""
val response =
ChartboostMediationNetworking.getAppConfig(
ChartboostMediationNetworkingTest.APP_ID,
ChartboostMediationNetworkingTest.INIT_HASH_OLD,
appSetId,
)
val request = mockWebServer.takeRequest(1, TimeUnit.SECONDS)
val expectedRequestUrl = "${Endpoints.Sdk.SDK_INIT.endpoint}/${ChartboostMediationNetworkingTest.APP_ID}"
val expectedRequestInitHashHeaderValue = ChartboostMediationNetworkingTest.INIT_HASH_OLD
val actualRequestUrl = request?.requestUrl.toString()
val actualRequestInitHashHeaderValue = request?.getHeader(ChartboostMediationNetworking.INIT_HASH_HEADER_KEY)
val actualRequestDebugHeaderValue = request?.getHeader(ChartboostMediationNetworking.DEBUG_HEADER_KEY)
Assert.assertEquals(expectedRequestUrl, actualRequestUrl)
Assert.assertEquals(
expectedRequestInitHashHeaderValue,
actualRequestInitHashHeaderValue,
)
Assert.assertEquals(ChartboostMediationNetworkingTest.APP_ID, actualRequestDebugHeaderValue)
Assert.assertNotNull(response)
Assert.assertTrue(response is ChartboostMediationNetworkingResult.JsonParsingFailure)
}
}
fun ChartboostMediationNetworkingTest.`verify result for sdk_init failure due to http code`() =
runTest {
val expectedResponseHttpCode = 404
MockResponse()
.setResponseCode(expectedResponseHttpCode)
.setHeader(ChartboostMediationNetworking.INIT_HASH_HEADER_KEY, ChartboostMediationNetworkingTest.INIT_HASH_NEW)
.let {
mockWebServer.enqueue(it)
}
launch {
val appSetId = ChartboostCore.analyticsEnvironment.getVendorIdentifier() ?: ""
val response =
ChartboostMediationNetworking.getAppConfig(
ChartboostMediationNetworkingTest.APP_ID,
ChartboostMediationNetworkingTest.INIT_HASH_OLD,
appSetId,
)
val request = mockWebServer.takeRequest(1, TimeUnit.SECONDS)
val expectedRequestUrl = "${Endpoints.Sdk.SDK_INIT.endpoint}/${ChartboostMediationNetworkingTest.APP_ID}"
val expectedRequestInitHashHeaderValue = ChartboostMediationNetworkingTest.INIT_HASH_OLD
val actualRequestUrl = request?.requestUrl.toString()
val actualRequestInitHashHeaderValue = request?.getHeader(ChartboostMediationNetworking.INIT_HASH_HEADER_KEY)
val actualRequestDebugHeaderValue = request?.getHeader(ChartboostMediationNetworking.DEBUG_HEADER_KEY)
Assert.assertEquals(expectedRequestUrl, actualRequestUrl)
Assert.assertEquals(
expectedRequestInitHashHeaderValue,
actualRequestInitHashHeaderValue,
)
Assert.assertEquals(ChartboostMediationNetworkingTest.APP_ID, actualRequestDebugHeaderValue)
Assert.assertNotNull(response)
Assert.assertTrue(response is ChartboostMediationNetworkingResult.Failure)
}
}
| 0
|
Kotlin
|
0
| 0
|
18948613638191a0639eb264ec6e39f3d37bf722
| 9,672
|
chartboost-mediation-android-sdk
|
MIT License
|
app/src/main/java/io/android/todarch/ui/todo/TodoListAdapter.kt
|
todarch
| 152,471,665
| false
| null |
/*
* Copyright 2018 Todarch
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.android.todarch.ui.todo
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import io.android.todarch.R
import io.android.todarch.core.data.model.Task
import io.android.todarch.core.ui.ItemClickListener
import io.android.todarch.databinding.ItemTodoBinding
/**
* @author <NAME> <<EMAIL>>
* @since 1.11.2018.
*/
class TodoListAdapter(private val listener: TodoItemListener) : RecyclerView.Adapter<TodoListAdapter.TodoViewHolder>() {
private val items = mutableListOf<Task>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder =
TodoViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_todo, parent, false))
override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
val task = items[position]
task.run {
holder.binding.title.text = if (title.isNotEmpty()) {
title
} else {
description
}
holder.binding.root.setOnClickListener {
listener.onItemClick(this)
}
}
}
override fun getItemCount() = items.size
fun updateTasks(tasks: List<Task>?) {
items.clear()
tasks?.let {
items.addAll(it)
}
notifyDataSetChanged()
}
class TodoViewHolder(val binding: ItemTodoBinding) : RecyclerView.ViewHolder(binding.root)
interface TodoItemListener : ItemClickListener<Task> {
fun onTaskDelete(item: Task)
}
}
| 0
|
Kotlin
|
0
| 3
|
34e25e9cf457379e5cb0c8e6e7793d249767b2a1
| 2,220
|
todarch-android
|
Apache License 2.0
|
app/src/main/java/com/example/androidarchitecturesample/ui/promoted/PromotedDataSource.kt
|
arononak
| 236,748,515
| false
| null |
package com.example.androidarchitecturesample.ui.promoted
import android.util.Log
import androidx.paging.PageKeyedDataSource
import com.example.androidarchitecturesample.data.api.WykopApi
import com.example.androidarchitecturesample.data.model.Promoted
import kotlinx.coroutines.*
class PromotedDataSource(private val api: WykopApi) : PageKeyedDataSource<Long, Promoted>() {
override fun loadInitial(
params: LoadInitialParams<Long>,
callback: LoadInitialCallback<Long, Promoted>
) {
GlobalScope.launch {
try {
listOf(
async(Dispatchers.IO) { api.fetchPromoted(1) },
async(Dispatchers.IO) { api.fetchPromoted(2) },
async(Dispatchers.IO) { api.fetchPromoted(3) }
).awaitAll()
.filter { it.isSuccessful }
.mapNotNull { it.body() }
.flatten()
.let { callback.onResult(it, null, 4) }
} catch (exception: Exception) {
Log.e("PostsDataSource", "Failed to fetch data!")
}
}
}
override fun loadBefore(params: LoadParams<Long>, callback: LoadCallback<Long, Promoted>) {
Log.e("PostsDataSource", "Failed to fetch data!")
}
override fun loadAfter(params: LoadParams<Long>, callback: LoadCallback<Long, Promoted>) {
GlobalScope.launch {
try {
listOf(
async(Dispatchers.IO) { api.fetchPromoted(params.key.toInt()) }
).awaitAll()
.filter { it.isSuccessful }
.mapNotNull { it.body() }
.flatten()
.let { callback.onResult(it, params.key + 1) }
} catch (exception: Exception) {
Log.e("PostsDataSource", "Failed to fetch data!")
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
55612801bf8d37559b0c01aaa3a56348b7178779
| 1,919
|
AndroidArchitectureSample
|
Apache License 2.0
|
app/src/main/java/com/shane/helloworld/CLog.kt
|
shanearcaro
| 522,006,059
| false
| null |
package com.shane.helloworld
import android.util.Log
fun CLog(description: String, tag: String = "[DEBUG]") {
Log.d(tag, description)
}
| 0
|
Kotlin
|
0
| 0
|
75ac90a20875038270e63fec339d7814215fbbf2
| 141
|
BMICalculator
|
MIT License
|
android/src/main/java/com/bitmovin/player/reactnative/extensions/ReactContextExtension.kt
|
bitmovin
| 491,901,703
| false
|
{"TypeScript": 218192, "Swift": 175610, "Kotlin": 166930, "Objective-C": 19252, "Java": 16077, "Objective-C++": 9517, "C++": 6969, "Ruby": 4736, "JavaScript": 1959, "Makefile": 1527, "Shell": 279}
|
package com.bitmovin.player.reactnative.extensions
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
inline fun <reified T : ReactContextBaseJavaModule> ReactContext.getModule(): T? {
return getNativeModule(T::class.java)
}
| 15
|
TypeScript
|
10
| 31
|
75a40c43382b2b09003a7804fe95e97e4a3fe16f
| 286
|
bitmovin-player-react-native
|
MIT License
|
app/src/main/java/com/kleinreveche/playground/features/tictactoe/engine/WinPosition.kt
|
KleinReveche
| 537,970,451
| false
|
{"Kotlin": 293106}
|
package com.kleinreveche.playground.features.tictactoe.engine
sealed class WinPosition(val places: List<Int>) {
object H1 : WinPosition(listOf(0, 1, 2))
object H2 : WinPosition(listOf(3, 4, 5))
object H3 : WinPosition(listOf(6, 7, 8))
object V1 : WinPosition(listOf(0, 3, 6))
object V2 : WinPosition(listOf(1, 4, 7))
object V3 : WinPosition(listOf(2, 5, 8))
object D1 : WinPosition(listOf(0, 4, 8))
object D2 : WinPosition(listOf(2, 4, 6))
}
| 0
|
Kotlin
|
0
| 0
|
062c3257ef1a434ed5b11ec947104908467e9f7f
| 477
|
Playground
|
Apache License 2.0
|
src/main/kotlin/com/ort/firewolf/domain/model/myself/participant/VillageCreatorSituation.kt
|
h-orito
| 282,923,189
| false
| null |
package com.ort.firewolf.domain.model.myself.participant
data class VillageCreatorSituation(
val availableCreatorSetting: Boolean,
val availableCreatorSay: Boolean,
val availableCancelVillage: Boolean,
val availableKick: Boolean,
val availableModifySetting: Boolean,
val availableExtendEpilogue: Boolean
)
| 0
|
Kotlin
|
0
| 0
|
c2a7f651bb89285eafdb4967d84b8354b12748c0
| 331
|
firewolf-api
|
MIT License
|
src/main/kotlin/com/deflatedpickle/bugmagic/api/common/util/extension/EntityAITaskEntry.kt
|
DeflatedPickle
| 141,510,202
| false
| null |
/* Copyright (c) 2020 DeflatedPickle under the MIT license */
package com.deflatedpickle.bugmagic.api.common.util.extension
import com.deflatedpickle.bugmagic.api.common.util.AITaskString
import net.minecraft.entity.ai.EntityAITasks
fun EntityAITasks.EntityAITaskEntry.toTaskString(): AITaskString = AITaskString(this.priority, this.using, this.action::class.simpleName!!)
| 18
|
Kotlin
|
1
| 3
|
1781740bb23631aee8daef0806441182c387044e
| 376
|
BugMagic
|
MIT License
|
feature/main/src/main/java/com/example/main/MainNavigator.kt
|
jin5578
| 859,358,191
| false
|
{"Kotlin": 362176}
|
package com.example.main
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hasRoute
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.example.add_task.navigation.navigateAddTask
import com.example.calendar.navigation.navigateCalendar
import com.example.edit_task.navigation.navigateEditTask
import com.example.manage_categories.navigation.navigateManageCategories
import com.example.navigation.Route
import com.example.setting.navigation.navigateSetting
import com.example.tasks.navigation.navigateTasks
import java.time.LocalDate
internal class MainNavigator(
val navController: NavHostController
) {
private val currentDestination: NavDestination?
@Composable get() = navController.currentBackStackEntryAsState().value?.destination
val startDestination = Route.Home
fun navigateSetting() {
navController.navigateSetting()
}
fun navigateAddTask(date: LocalDate = LocalDate.now()) {
navController.navigateAddTask(date)
}
fun navigateEditTask(taskId: Long) {
navController.navigateEditTask(taskId)
}
fun navigateTasks(title: String) {
navController.navigateTasks(title)
}
fun navigateCalendar() {
navController.navigateCalendar()
}
fun navigateManageCategories() {
navController.navigateManageCategories()
}
private fun popBackStack() {
navController.popBackStack()
}
fun popBackStackIfNotHome() {
if (!isSameCurrentDestination<Route.Home>()) {
popBackStack()
}
}
private inline fun <reified T : Route> isSameCurrentDestination(): Boolean {
return navController.currentDestination?.hasRoute<T>() == true
}
}
@Composable
internal fun rememberMainNavigator(
navController: NavHostController = rememberNavController(),
): MainNavigator = remember(navController) {
MainNavigator(navController)
}
| 0
|
Kotlin
|
0
| 0
|
ee73d941ad2a7f7fe1ef6ce0b2c9e92f232eeed2
| 2,150
|
Todo
|
Apache License 2.0
|
app/src/main/java/com/example/truflag/Constants.kt
|
rohitvermaaa
| 743,136,444
| false
|
{"Kotlin": 31050}
|
package com.example.truflag
object Constants {
const val USER_NAME : String = "user_name"
const val TOTAL_QUESTION : String = "total_question"
const val CORRECT_ANSWER : String = "correct_answers"
fun getQuestion(): ArrayList<Question> {
val questionList = ArrayList<Question>()
val ques1 = Question(
1,
"What country does this flag belongs to?",
R.drawable.ic_flag_of_argentina,
"India",
"Peru",
"Argentina",
"Nepal",
3
)
questionList.add(ques1)
val ques2 = Question(
2,
"Which nation is represented by this flag?",
R.drawable.ic_flag_of_brazil,
"Brazil",
"Mexico",
"Argentina",
"Chile",
1
)
questionList.add(ques2)
val ques3 = Question(
3,
"Identify the country associated with this flag.",
R.drawable.ic_flag_of_france,
"Spain",
"Italy",
"France",
"Germany",
3
)
questionList.add(ques3)
val ques4 = Question(
4,
"Determine the nation to which this flag belongs.",
R.drawable.ic_flag_of_japan,
"South Korea",
"Japan",
"China",
"Vietnam",
2
)
questionList.add(ques4)
val ques5 = Question(
5,
"What is the country affiliated with this flag?",
R.drawable.ic_flag_of_united_kingdom,
"Canada",
"Australia",
"United Kingdom",
"New Zealand",
3
)
questionList.add(ques5)
val ques6 = Question(
6,
"Tell me the nation that this flag signifies.",
R.drawable.ic_flag_of_canada,
"United States",
"Mexico",
"Brazil",
"Canada",
4
)
questionList.add(ques6)
val ques7 = Question(
7,
"Point out the country owning this flag.",
R.drawable.ic_flag_of_germany,
"Germany",
"Netherlands",
"France",
"Belgium",
1
)
questionList.add(ques7)
val ques8 = Question(
8,
"Specify the country that possesses this particular flag.",
R.drawable.ic_flag_of_india,
"Pakistan",
"China",
"Bangladesh",
"India",
4
)
questionList.add(ques8)
val ques9 = Question(
9,
"Name the nation linked to this flag.",
R.drawable.ic_flag_of_italy,
"Spain",
"Greece",
"Italy",
"Portugal",
3
)
questionList.add(ques9)
val ques10 = Question(
10,
"Recognize the country to which this flag is linked.",
R.drawable.ic_flag_of_russia,
"Russia",
"Ukraine",
"Poland",
"Belarus",
1
)
questionList.add(ques10)
val ques11 = Question(
11,
"To which country does this intricately adorned flag belong?",
R.drawable.ic_flag_of_morocco,
"Tunisia",
"Libya",
"Morocco",
"Algeria",
3
)
questionList.add(ques11)
val ques12 = Question(
12,
"Identify the nation with this uniquely detailed flag.",
R.drawable.ic_flag_of_mongolia,
"Kyrgyzstan",
"Mongolia",
"Uzbekistan",
"Kazakhstan",
2
)
questionList.add(ques12)
val ques13 = Question(
13,
"Tell me the sophisticated nation represented by this flag.",
R.drawable.ic_flag_of_south_korea,
"China",
"Japan",
"South Korea",
"North Korea",
3
)
questionList.add(ques13)
val ques14 = Question(
14,
"Name the country possessing this elaborately designed flag.",
R.drawable.ic_flag_of_chile,
"Argentina",
"Chile",
"Bolivia",
"Peru",
3
)
questionList.add(ques14)
val ques15 = Question(
15,
"Which nation is indicated by this meticulously crafted flag?",
R.drawable.ic_flag_of_united_arab_emirates,
"Kuwait",
"Saudi Arabia",
"United Arab Emirates",
"Qatar",
3
)
questionList.add(ques15)
val ques16 = Question(
16,
"Tell me the sophisticated nation represented by this flag.",
R.drawable.ic_flag_of_hungary,
"Hungary",
"Austria",
"Czech Republic",
"Slovakia",
1
)
questionList.add(ques16)
val ques17 = Question(
17,
"Identify the nation with this uniquely detailed flag.",
R.drawable.ic_flag_of_thailand,
"Cambodia",
"Laos",
"Vietnam",
"Thailand",
4
)
questionList.add(ques17)
val ques18 = Question(
18,
"What nation does this intricately designed flag pertain to?",
R.drawable.ic_flag_of_cambodia,
"Laos",
"Cambodia",
"Myanmar",
"Thailand",
2
)
questionList.add(ques18)
val ques19 = Question(
19,
"Identify the nation with this uniquely detailed flag.",
R.drawable.ic_flag_of_tanzania,
"Kenya",
"Rwanda",
"Tanzania",
"Uganda",
3
)
questionList.add(ques19)
val ques20 = Question(
20,
"Identify the nation with this uniquely detailed flag.",
R.drawable.ic_flag_of_czech_republic,
"Czech Republic",
"Hungary",
"Poland",
"Slovakia",
1
)
questionList.add(ques20)
val ques21 = Question(
21,
"To which country does this flag belong?",
R.drawable.ic_flag_of_ireland,
"United Kingdom",
"Ireland",
"Scotland",
"Wales",
2
)
questionList.add(ques21)
val ques22 = Question(
22,
"Name the nation with this flag.",
R.drawable.ic_flag_of_indonesia,
"Malaysia",
"Singapore",
"Brunei",
"Indonesia",
4
)
questionList.add(ques22)
val ques23 = Question(
23,
"To which country does this flag belong?",
R.drawable.ic_flag_of_egypt,
"Iraq",
"Egypt",
"Saudi Arabia",
"Jordan",
2
)
questionList.add(ques23)
val ques24 = Question(
24,
"What nation is associated with this flag?",
R.drawable.ic_flag_of_colombia,
"Colombia",
"Ecuador",
"Venezuela",
"Peru",
1
)
questionList.add(ques24)
val ques25 = Question(
25,
"Which country owns this flag?",
R.drawable.ic_flag_of_denmark,
"Sweden",
"Norway",
"Denmark",
"Finland",
3
)
questionList.add(ques25)
val ques26 = Question(
26,
"Name the country with this detailed flag.",
R.drawable.ic_flag_of_pakistan,
"India",
"Pakistan",
"Bangladesh",
"Afghanistan",
2
)
questionList.add(ques26)
val ques27 = Question(
27,
"Identify the nation possessing this flag.",
R.drawable.ic_flag_of_nigeria,
"South Africa",
"Kenya",
"Ghana",
"Nigeria",
4
)
questionList.add(ques27)
val ques28 = Question(
28,
"What is the country linked to this flag?",
R.drawable.ic_flag_of_portugal,
"Spain",
"France",
"Portugal",
"Italy",
3
)
questionList.add(ques28)
val ques29 = Question(
29,
"Recognize the country with this flag.",
R.drawable.ic_flag_of_peru,
"Chile",
"Peru",
"Bolivia",
"Ecuador",
2
)
questionList.add(ques29)
val ques30 = Question(
30,
"Identify the country with this intricately detailed flag.",
R.drawable.ic_flag_of_ethiopia,
"Ethiopia",
"Eritrea",
"Somalia",
"Djibouti",
1
)
questionList.add(ques30)
// Questions 31-40
val ques31 = Question(
31,
"Which nation does this flag represent?",
R.drawable.ic_flag_of_switzerland,
"Austria",
"Switzerland",
"Liechtenstein",
"Luxembourg",
2
)
questionList.add(ques31)
val ques32 = Question(
32,
"Identify the country associated with this flag.",
R.drawable.ic_flag_of_saudi_arabia,
"Qatar",
"United Arab Emirates",
"Kuwait",
"Saudi Arabia",
4
)
questionList.add(ques32)
val ques33 = Question(
33,
"What is the nation linked to this flag?",
R.drawable.ic_flag_of_norway,
"Norway",
"Denmark",
"Sweden",
"Finland",
1
)
questionList.add(ques33)
val ques34 = Question(
34,
"Identify the South American nation with this flag.",
R.drawable.ic_flag_of_bolivia,
"Bolivia",
"Paraguay",
"Uruguay",
"Argentina",
1
)
questionList.add(ques34)
val ques35 = Question(
35,
"Identify the nation with this flag.",
R.drawable.ic_flag_of_australia,
"New Zealand",
"Australia",
"Papua New Guinea",
"Fiji",
2
)
questionList.add(ques35)
val ques36 = Question(
36,
"Recognize the country to which this flag is linked.",
R.drawable.ic_flag_of_south_africa,
"Zimbabwe",
"Namibia",
"South Africa",
"Botswana",
3
)
questionList.add(ques36)
val ques37 = Question(
37,
"Name the nation linked to this flag.",
R.drawable.ic_flag_of_malaysia,
"Thailand",
"Malaysia",
"Singapore",
"Brunei",
2
)
questionList.add(ques37)
val ques38 = Question(
43,
"Which East Asian region is represented by this flag?",
R.drawable.ic_flag_of_taiwan,
"Taiwan",
"China",
"Japan",
"South Korea",
1
)
questionList.add(ques38)
val ques39 = Question(
39,
"Specify the country that possesses this particular flag.",
R.drawable.ic_flag_of_israel,
"Jordan",
"Lebanon",
"Syria",
"Israel",
4
)
questionList.add(ques39)
val ques40 = Question(
40,
"Determine the nation to which this flag belongs.",
R.drawable.ic_flag_of_sri_lanka,
"Maldives",
"Sri Lanka",
"Bangladesh",
"Nepal",
2
)
questionList.add(ques40)
// Questions 41-50
val ques41 = Question(
41,
"Identify the nation with this uniquely detailed flag.",
R.drawable.ic_flag_of_burundi,
"Brunei",
"Burkina Faso",
"Burundi ",
"Chad",
3
)
questionList.add(ques41)
val ques42 = Question(
42,
"What nation is associated with this flag?",
R.drawable.ic_flag_of_sweden,
"Norway",
"Denmark",
"Finland",
"Sweden",
4
)
questionList.add(ques42)
val ques43 = Question(
43,
"Name the territory possessing this distinctive flag.",
R.drawable.ic_flag_of_puerto_rico,
"Puerto Rico",
"Dominican Republic",
"Cuba",
"Haiti",
1
)
questionList.add(ques43)
val ques44 = Question(
44,
"Recognize the country with this flag.",
R.drawable.ic_flag_of_rwanda,
"Uganda",
"Tanzania",
"Kenya",
"Rwanda",
4
)
questionList.add(ques44)
val ques45 = Question(
45,
"To which country does this flag belong?",
R.drawable.ic_flag_of_cuba,
"Dominican Republic",
"Cuba",
"Haiti",
"Puerto Rico",
2
)
questionList.add(ques45)
val ques46 = Question(
46,
"Which North African country is represented by this flag?",
R.drawable.ic_flag_of_tunisia,
"Algeria",
"Morocco",
"Libya",
"Tunisia",
4
)
questionList.add(ques46)
val ques47 = Question(
47,
"Identify the nation with this flag.",
R.drawable.ic_flag_of_singapore,
"Malaysia",
"Indonesia",
"Thailand",
"Singapore",
4
)
questionList.add(ques47)
val ques48 = Question(
48,
"To which country does this flag belong?",
R.drawable.ic_flag_of_ukraine,
"Russia",
"Poland",
"Belarus",
"Ukraine",
4
)
questionList.add(ques48)
val ques49 = Question(
49,
"Specify the country that possesses this particular flag.",
R.drawable.ic_flag_of_ghana,
"Nigeria",
"Ghana",
"Kenya",
"South Africa",
2
)
questionList.add(ques49)
val ques50 = Question(
50,
"Recognize the country to which this flag is linked.",
R.drawable.ic_flag_of_iraq,
"Iran",
"Syria",
"Iraq",
"Turkey",
3
)
questionList.add(ques50)
// Questions 51-60
val ques51 = Question(
51,
"Identify the nation linked to this flag.",
R.drawable.ic_flag_of_finland,
"Sweden",
"Norway",
"Denmark",
"Finland",
4
)
questionList.add(ques51)
val ques52 = Question(
52,
"What is the country affiliated with this flag?",
R.drawable.ic_flag_of_venezuela,
"Colombia",
"Ecuador",
"Venezuela",
"Peru",
3
)
questionList.add(ques52)
val ques53 = Question(
53,
"Specify the country that possesses this particular flag.",
R.drawable.ic_flag_of_croatia,
"Serbia",
"Bosnia and Herzegovina",
"Slovenia",
"Croatia",
4
)
questionList.add(ques53)
val ques54 = Question(
54,
"Determine the nation to which this flag belongs.",
R.drawable.ic_flag_of_malta,
"Malta",
"Greece",
"Italy",
"Cyprus",
1
)
questionList.add(ques54)
val ques55 = Question(
55,
"Recognize the country with this flag.",
R.drawable.ic_flag_of_new_zealand,
"Australia",
"New Zealand",
"Fiji",
"Papua New Guinea",
2
)
questionList.add(ques55)
val ques56 = Question(
56,
"Identify the nation with this flag.",
R.drawable.ic_flag_of_mexico,
"Argentina",
"Mexico",
"Brazil",
"Chile",
2
)
questionList.add(ques56)
val ques57 = Question(
57,
"To which country does this flag belong?",
R.drawable.ic_flag_of_philippines,
"Vietnam",
"Thailand",
"Indonesia",
"Philippines",
4
)
questionList.add(ques57)
val ques58 = Question(
58,
"Name the nation linked to this flag.",
R.drawable.ic_flag_of_eswatini,
"Lesotho",
"Eswatini",
"Botswana",
"Namibia",
2
)
questionList.add(ques58)
val ques59 = Question(
59,
"Identify the nation with this flag.",
R.drawable.ic_flag_of_azerbaijan,
"Armenia",
"Georgia",
"Azerbaijan",
"Iran",
3
)
questionList.add(ques59)
val ques60 = Question(
60,
"Recognize the country to which this flag is linked.",
R.drawable.ic_flag_of_cote_divoire,
"Ghana",
"Liberia",
"Côte d'Ivoire",
"Senegal",
3
)
questionList.add(ques60)
// Questions 61-70
val ques61 = Question(
61,
"What is the nation linked to this flag?",
R.drawable.ic_flag_of_uzbekistan,
"Uzbekistan",
"Kazakhstan",
"Turkmenistan",
"Kyrgyzstan",
1
)
questionList.add(ques61)
val ques62 = Question(
62,
"Name the country possessing this elaborately designed flag.",
R.drawable.ic_flag_of_albania,
"Kosovo",
"Montenegro",
"North Macedonia",
"Albania",
4
)
questionList.add(ques62)
val ques63 = Question(
63,
"Recognize the country with this flag.",
R.drawable.ic_flag_of_maldives,
"Sri Lanka",
"Maldives",
"Bangladesh",
"Nepal",
2
)
questionList.add(ques63)
val ques64 = Question(
64,
"To which country does this flag belong?",
R.drawable.ic_flag_of_bulgaria,
"Bulgaria",
"Romania",
"Greece",
"Serbia",
1
)
questionList.add(ques64)
val ques65 = Question(
65,
"Identify the nation with this flag.",
R.drawable.ic_flag_of_lithuania,
"Latvia",
"Lithuania",
"Estonia",
"Belarus",
2
)
questionList.add(ques65)
val ques66 = Question(
66,
"Determine the nation to which this flag belongs.",
R.drawable.ic_flag_of_georgia,
"Armenia",
"Azerbaijan",
"Georgia",
"Turkey",
3
)
questionList.add(ques66)
val ques67 = Question(
67,
"Recognize the country to which this flag is linked.",
R.drawable.ic_flag_of_slovakia,
"Czech Republic",
"Hungary",
"Poland",
"Slovakia",
4
)
questionList.add(ques67)
val ques68 = Question(
68,
"Name the nation linked to this flag.",
R.drawable.ic_flag_of_latvia,
"Lithuania",
"Latvia",
"Estonia",
"Finland",
2
)
questionList.add(ques68)
val ques69 = Question(
69,
"Identify the nation with this flag.",
R.drawable.ic_flag_of_slovenia,
"Croatia",
"Bosnia and Herzegovina",
"Serbia",
"Slovenia",
4
)
questionList.add(ques69)
val ques70 = Question(
70,
"What nation does this intricately designed flag pertain to?",
R.drawable.ic_flag_of_botswana,
"Botswana",
"Namibia",
"Senegal",
"Eswatini",
1
)
questionList.add(ques70)
return questionList
}
}
| 0
|
Kotlin
|
0
| 0
|
d537ffe7d0eca7dd5d3a974a90f58602d6decbc9
| 21,790
|
TruFlag
|
MIT License
|
app/src/main/java/com/cscorner/universe/model/UGYearModel.kt
|
Rithvik086
| 844,103,649
| false
|
{"Kotlin": 24188}
|
package com.cscorner.universe.model
data class UGYearModel(
val img:Int ,
val name:String = ""
)
| 0
|
Kotlin
|
0
| 0
|
93b3aecf4be94aede01af175506e9a27b5d6ad7d
| 106
|
UniVerse
|
MIT License
|
src/main/kotlin/poxah/blizzard/auth/model/AuthToken.kt
|
Krumbl
| 448,423,505
| false
| null |
package poxah.blizzard.auth.model
data class AuthToken (
val access_token: String,
val token_type: String,
val expires_in: Number,
val sub: String,
)
| 0
|
Kotlin
|
0
| 0
|
e8ae9b8bab6d10d6362fa200a0c91c8d50e56bbd
| 168
|
poxah
|
Apache License 2.0
|
features/search/src/test/java/com/fappslab/features/search/data/repository/SearchRepositoryImplIntegrationTest.kt
|
F4bioo
| 708,171,476
| false
|
{"Kotlin": 210868}
|
package com.fappslab.features.search.data.repository
import androidx.paging.PagingConfig
import app.cash.turbine.test
import com.fappslab.features.search.data.source.remote.SearchRemoteDataSourceImpl
import com.fappslab.features.search.domain.repository.SearchRepository
import com.fappslab.libraries.arch.testing.rules.MainCoroutineTestRule
import com.fappslab.libraries.arch.testing.rules.RemoteTestRule
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import kotlin.test.assertNotNull
internal class SearchRepositoryImplIntegrationTest {
@get:Rule
val remoteRule = RemoteTestRule()
@get:Rule
val mainCoroutineRule = MainCoroutineTestRule()
private lateinit var subject: SearchRepository
@Before
fun setUp() {
subject = SearchRepositoryImpl(
remoteDataSource = SearchRemoteDataSourceImpl(
service = remoteRule.createTestService()
),
config = PagingConfig(pageSize = 20)
)
}
@Test
fun `getMovies Should validate flow data creation When invoked`() = runTest {
// Given
remoteRule.toServerSuccessResponse { SEARCH_SUCCESS_RESPONSE }
// When
val result = subject.getSearchMovie(query = "Avatar")
// Then
result.test {
assertNotNull(awaitItem())
cancelAndConsumeRemainingEvents()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
3506b09c7b6b522899486fa45ba9686b404780f2
| 1,442
|
TMDBCompose
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.