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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
android/features/profile/deletion/src/main/kotlin/io/chefbook/features/profile/deletion/ui/ProfileDeletionScreen.kt
|
mephistolie
| 379,951,682
| false
|
{"Kotlin": 1334117, "Ruby": 16819, "Swift": 352}
|
package io.chefbook.features.profile.deletion.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.ramcosta.composedestinations.annotation.Destination
import io.chefbook.core.android.showToast
import io.chefbook.features.profile.deletion.ui.mvi.ProfileDeletionScreenEffect
import io.chefbook.navigation.navigators.BaseNavigator
import io.chefbook.navigation.styles.DismissibleDialog
import org.koin.androidx.compose.koinViewModel
@Destination(route = "profile/deletion", style = DismissibleDialog::class)
@Composable
fun ProfileDeletionScreen(
navigatior: BaseNavigator,
) {
val context = LocalContext.current
val viewModel = koinViewModel<ProfileDeletionScreenViewModel>()
val state = viewModel.state.collectAsStateWithLifecycle()
ProfileDeletionScreenContent(
state = state.value,
onIntent = viewModel::handleIntent,
)
LaunchedEffect(Unit) {
viewModel.effect.collect { effect ->
when (effect) {
is ProfileDeletionScreenEffect.ToastShown -> context.showToast(effect.message)
is ProfileDeletionScreenEffect.Closed -> navigatior.navigateUp()
}
}
}
}
| 0
|
Kotlin
|
0
| 12
|
ddaf82ee3142f30aee8920d226a8f07873cdcffe
| 1,276
|
chefbook-mobile
|
Apache License 2.0
|
src/test/kotlin/ar/edu/unq/mientradita/model/StadiumTest.kt
|
FeNixCrew
| 403,775,742
| false
|
{"Kotlin": 153585}
|
package ar.edu.unq.mientradita.model
import ar.edu.unq.mientradita.model.builders.StadiumBuilder
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class StadiumTest {
@Test
fun `un estadio tiene un nombre`() {
val estadio = StadiumBuilder().withName("<NAME>").build()
assertThat(estadio.name).isEqualTo("<NAME>")
}
@Test
fun `un estadio tiene como ubicacion una latitud y una longitud`() {
val estadio = StadiumBuilder().withLatitude(40.45306).withLongitude(-3.68835).build()
assertThat(estadio.latitude).isEqualTo(40.45306)
assertThat(estadio.longitude).isEqualTo(-3.68835)
}
@Test
fun `un estadio tiene una capacidad maxima`(){
val estadio = StadiumBuilder().withCapacity(20).build()
assertThat(estadio.capacity).isEqualTo(20)
}
}
| 0
|
Kotlin
|
0
| 1
|
3276ea3935a722ee6486ec6e2c08e224b6a4f87c
| 868
|
MiEntradita-backend
|
MIT License
|
kotest-tests/kotest-tests-android/src/androidTest/java/io/kotest/android/matchers/textview/TextViewMatchersTests.kt
|
kotest
| 249,072,229
| false
| null |
package io.kotest.android.matchers.textview
import android.graphics.Color
import androidx.test.core.app.launchActivity
import io.kotest.androidtest.MainActivity
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.runner.junit4.FreeSpec
import kotlinx.android.synthetic.main.activity_main.*
class TextViewMatchersTests : FreeSpec({
"Have Text" {
val scenario = launchActivity<MainActivity>()
scenario.onActivity {
it.textview.also { tv ->
tv shouldHaveText "Kotest!"
tv shouldNotHaveText "a"
tv shouldNotHaveText ""
shouldThrow<AssertionError> { tv shouldHaveText "a" }
shouldThrow<AssertionError> { tv shouldHaveText "" }
shouldThrow<AssertionError> { tv shouldNotHaveText "Kotest!" }
}
}
}
"Have Color" {
val scenario = launchActivity<MainActivity>()
scenario.onActivity {
val tv = it.textviewColored
tv shouldHaveTextColor Color.BLACK
tv shouldNotHaveTextColor Color.RED
tv shouldHaveTextColorId android.R.color.black
tv shouldNotHaveTextColorId android.R.color.white
shouldThrow<AssertionError> { tv shouldHaveTextColor Color.RED }
shouldThrow<AssertionError> { tv shouldNotHaveTextColor Color.BLACK }
shouldThrow<AssertionError> { tv shouldNotHaveTextColorId android.R.color.black }
shouldThrow<AssertionError> { tv shouldHaveTextColorId android.R.color.white }
}
}
"All Caps" {
val scenario = launchActivity<MainActivity>()
scenario.onActivity {
it.textviewAllCaps.shouldBeAllCaps()
shouldThrow<AssertionError> { it.textviewAllCaps.shouldNotBeAllCaps() }
it.textview.shouldNotBeAllCaps()
shouldThrow<AssertionError> { it.textview.shouldBeAllCaps() }
}
}
})
| 8
|
Kotlin
|
2
| 6
|
fe41d9506227d22a5c123015fe7a8d5f00713e05
| 1,869
|
kotest-android
|
Apache License 2.0
|
app/src/main/java/com/app/darktodoapp/features/projects/ProjectAdapter.kt
|
Magno-Ramos
| 341,404,929
| false
| null |
package com.app.darktodoapp.features.projects
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.app.darktodoapp.R
import com.app.darktodoapp.customview.PieProgress
import com.app.darktodoapp.customview.percentOf
import com.app.darktodoapp.helper.inflate
import com.app.sdk.entities.ProjectWithTasksEntity
import com.app.sdk.models.Task
class ProjectAdapter :
ListAdapter<ProjectWithTasksEntity, ProjectAdapter.ProjectViewModel>(ProjectDiffCallback()) {
var projectClickListener: ((projectId: Int) -> Unit)? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProjectViewModel =
object : ProjectViewModel(parent) {
override fun onClick(position: Int) {
projectClickListener?.invoke(currentList[position].projectEntity.id)
}
}
override fun onBindViewHolder(holder: ProjectViewModel, position: Int) =
holder.bindView(getItem(position))
abstract class ProjectViewModel(parent: ViewGroup) :
RecyclerView.ViewHolder(parent.inflate(R.layout.item_view_project)) {
private val txtTitle: TextView = itemView.findViewById(R.id.txt_title)
private val txtSubtitle: TextView = itemView.findViewById(R.id.txt_subtitle)
private val pieProgress: PieProgress = itemView.findViewById(R.id.pie_chart)
abstract fun onClick(position: Int)
init {
itemView.setOnClickListener { onClick(adapterPosition) }
}
fun bindView(projectEntity: ProjectWithTasksEntity) {
val tasksCount = projectEntity.tasks.size
txtTitle.text = projectEntity.projectEntity.title
txtSubtitle.text =
itemView.resources.getQuantityString(R.plurals.tasks_count, tasksCount, tasksCount)
updateProgress(projectEntity.tasks.map(::Task))
}
fun updateProgress(tasks: List<Task>) {
if (tasks.isEmpty()) {
pieProgress.setPercentage(0f)
} else {
val tasksCount = tasks.size
val completedCount = tasks.count { it.complete }
val completePercent = tasksCount.percentOf(completedCount)
pieProgress.setPercentage(completePercent.toFloat())
}
}
}
}
private class ProjectDiffCallback : DiffUtil.ItemCallback<ProjectWithTasksEntity>() {
override fun areItemsTheSame(
oldItem: ProjectWithTasksEntity,
newItem: ProjectWithTasksEntity
): Boolean =
oldItem.projectEntity.id == newItem.projectEntity.id
override fun areContentsTheSame(
oldItem: ProjectWithTasksEntity,
newItem: ProjectWithTasksEntity
): Boolean = oldItem.projectEntity == newItem.projectEntity
}
| 0
|
Kotlin
|
0
| 0
|
28d6e034a1431d9415763b9d27053a5fedfbe290
| 2,911
|
dark-todo-app
|
Apache License 2.0
|
core/src/main/java/com/zigis/paleontologas/core/ui/parallax/OnScrollViewChangeListener.kt
|
edgar-zigis
| 240,962,785
| false
|
{"Kotlin": 184730}
|
package com.zigis.paleontologas.core.ui.parallax
interface OnScrollViewChangeListener {
fun onInternalScrollChanged(left: Int, top: Int, oldLeft: Int, oldTop: Int)
}
| 0
|
Kotlin
|
16
| 122
|
5e8d658e8898a4c55c2f11f5dc54438c876ae8a3
| 170
|
Paleontologas
|
Apache License 2.0
|
src/main/kotlin/net/devoev/vanilla_cubed/item/armor/ArmorData.kt
|
Devoev
| 473,273,645
| false
| null |
package net.devoev.vanilla_cubed.item.armor
import net.minecraft.item.ArmorMaterial
import net.minecraft.item.Item.Settings
import net.minecraft.item.ArmorItem
/**
* Data needed for the creation of a set of [armor][ArmorItem].
*/
data class ArmorData(
val material: ArmorMaterial,
val settings: Settings
)
| 0
|
Kotlin
|
1
| 1
|
eeacd0115113a7bc1dd9a9ce6d17f95894fac3ee
| 318
|
vanilla-cubed
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/es/dam/pi/vinilaapp_v3/viewmodel/UserGalleryViewModel.kt
|
ptrdck
| 809,465,277
| false
|
{"Kotlin": 123243, "JavaScript": 1824}
|
package es.dam.pi.vinilaapp_v3.viewmodel
import android.net.Uri
import androidx.lifecycle.ViewModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.FirebaseStorage
import es.dam.pi.vinilaapp_v3.ui.model.Image
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class UserGalleryViewModel : ViewModel() {
private val firestore = FirebaseFirestore.getInstance()
private val storage = FirebaseStorage.getInstance()
private val userId = FirebaseAuth.getInstance().currentUser?.uid
private val _photos = MutableStateFlow<List<Image>>(emptyList())
val photos: StateFlow<List<Image>> = _photos
private val _loading = MutableStateFlow(false)
val loading: StateFlow<Boolean> = _loading
init {
fetchUserPhotos()
}
fun fetchUserPhotos() { // Cambiado a público
userId?.let {
firestore.collection("users").document(it).collection("photos")
.addSnapshotListener { result, error ->
if (error != null) {
// Handle error
return@addSnapshotListener
}
val photoList = result?.documents?.map { document -> document.toObject(Image::class.java)!! }
_photos.value = photoList ?: emptyList()
}
}
}
fun uploadPhoto(uri: Uri) {
val user = FirebaseAuth.getInstance().currentUser
if (user != null) {
val userId = user.uid
val storageRef = FirebaseStorage.getInstance().reference.child("gallery/$userId/${uri.lastPathSegment}")
_loading.value = true
storageRef.putFile(uri).addOnSuccessListener {
storageRef.downloadUrl.addOnSuccessListener { url ->
val photo = Image(imageId = firestore.collection("images").document().id, galleryId = "galleryId1", imageUrl = url.toString())
savePhotoToFirestore(photo)
}.addOnCompleteListener {
_loading.value = false
}
}.addOnFailureListener {
_loading.value = false
// Handle error
}
} else {
// Handle unauthenticated user
}
}
private fun savePhotoToFirestore(photo: Image) {
userId?.let {
val docRef = firestore.collection("users").document(it).collection("photos").document(photo.imageId)
docRef.set(photo)
}
}
fun deleteSelectedPhotos(photoIds: List<String>) {
userId?.let { userId ->
photoIds.forEach { photoId ->
val docRef = firestore.collection("users").document(userId).collection("photos").document(photoId)
docRef.delete().addOnSuccessListener {
val storageRef = storage.reference.child("gallery/$userId/$photoId")
storageRef.delete()
}
}
}
}
fun onPhotoTaken(uri: Uri) {
uploadPhoto(uri)
}
fun onPhotoTakingFailed() {
// Handle photo taking failure
}
}
| 0
|
Kotlin
|
0
| 0
|
430399f6ab9f40e6a536a747cef41df94d8c0c39
| 3,232
|
VinilaApp_v3
|
MIT License
|
src/test/java/no/nav/bidrag/dokument/arkiv/hendelser/JournalpostKafkaEventProducerTest.kt
|
navikt
| 157,384,962
| false
|
{"Kotlin": 645757, "Java": 63620, "Shell": 1505, "Dockerfile": 261}
|
package no.nav.bidrag.dokument.arkiv.hendelser
import no.nav.bidrag.dokument.arkiv.dto.JournalStatus
import no.nav.bidrag.dokument.arkiv.dto.Sak
import no.nav.bidrag.dokument.arkiv.dto.TilknyttetJournalpost
import no.nav.bidrag.dokument.arkiv.dto.TilleggsOpplysninger
import no.nav.bidrag.dokument.arkiv.stubs.BRUKER_AKTOER_ID
import no.nav.bidrag.dokument.arkiv.stubs.BRUKER_ENHET
import no.nav.bidrag.dokument.arkiv.stubs.DATO_DOKUMENT
import no.nav.bidrag.dokument.arkiv.stubs.DATO_JOURNALFORT
import no.nav.bidrag.dokument.arkiv.stubs.Stubs
import no.nav.bidrag.dokument.arkiv.stubs.opprettSafResponse
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import java.time.LocalDateTime
@Disabled
internal class JournalpostKafkaEventProducerTest : BaseKafkaHendelseTest() {
val stubs: Stubs = Stubs()
@Test
@Disabled
@DisplayName("skal publisere journalpost hendelser for mottatt journalpost")
fun skalPublisereJournalpostHendelser() {
val journalpostId = 123213L
stubs.mockSts()
stubs.mockSafResponseHentJournalpost(
opprettSafResponse(
journalpostId = journalpostId.toString(),
journalstatus = JournalStatus.MOTTATT,
journalforendeEnhet = BRUKER_ENHET
)
)
stubs.mockDokarkivOppdaterRequest(journalpostId)
stubs.mockBidragOrganisasjonSaksbehandler()
sendMessageToJoarkTopic(createHendelseRecord(journalpostId))
val journalpostHendelse = readFromJournalpostTopic()!!
assertThat(journalpostHendelse).isNotNull
assertThat(journalpostHendelse.journalpostId).isEqualTo("JOARK-$journalpostId")
assertThat(journalpostHendelse.journalstatus).isEqualTo("M")
assertThat(journalpostHendelse.fagomrade).isEqualTo("BID")
assertThat(journalpostHendelse.aktorId).isEqualTo(BRUKER_AKTOER_ID)
assertThat(journalpostHendelse.enhet).isNull()
assertThat(journalpostHendelse.dokumentDato).isEqualTo(DATO_DOKUMENT.somDato())
assertThat(journalpostHendelse.journalfortDato).isNull()
stubs.verifyStub.dokarkivOppdaterIkkeKalt(journalpostId)
stubs.verifyStub.harIkkeEnSafKallEtterTilknyttedeJournalposter()
}
@Test
@Disabled
@DisplayName("skal publisere journalpost hendelser for journalført journalpost")
fun skalPublisereJournalpostHendelserForJournalfortJournalpost() {
val journalpostId = 123213L
val sak1 = "123213213"
val sak2 = "5124123"
val journalfortAvIdent = "Z123123"
val journalfortAvNavn = "Saksbehandler navn"
val tilleggsOpplysninger = TilleggsOpplysninger()
tilleggsOpplysninger.setJournalfortAvIdent(journalfortAvIdent)
stubs.mockSts()
stubs.mockSafResponseTilknyttedeJournalposter(listOf(TilknyttetJournalpost(journalpostId, JournalStatus.FERDIGSTILT, Sak(sak2))))
stubs.mockSafResponseHentJournalpost(
opprettSafResponse(
journalpostId = journalpostId.toString(),
journalstatus = JournalStatus.JOURNALFOERT,
journalforendeEnhet = BRUKER_ENHET,
sak = Sak(sak1),
relevanteDatoer = listOf(DATO_DOKUMENT, DATO_JOURNALFORT),
tilleggsopplysninger = tilleggsOpplysninger,
journalfortAvNavn = journalfortAvNavn
)
)
stubs.mockDokarkivOppdaterRequest(journalpostId)
stubs.mockBidragOrganisasjonSaksbehandler()
val hendelse = createHendelseRecord(journalpostId)
hendelse.journalpostStatus = "JOURNALFOERT"
sendMessageToJoarkTopic(hendelse)
val journalpostHendelse = readFromJournalpostTopic()!!
assertThat(journalpostHendelse).isNotNull
assertThat(journalpostHendelse.journalpostId).isEqualTo("JOARK-$journalpostId")
assertThat(journalpostHendelse.journalstatus).isEqualTo("J")
assertThat(journalpostHendelse.fagomrade).isEqualTo("BID")
assertThat(journalpostHendelse.aktorId).isEqualTo(BRUKER_AKTOER_ID)
assertThat(journalpostHendelse.enhet).isNull()
assertThat(journalpostHendelse.dokumentDato).isEqualTo(LocalDateTime.parse(DATO_DOKUMENT.dato).toLocalDate())
assertThat(journalpostHendelse.journalfortDato).isEqualTo(LocalDateTime.parse(DATO_JOURNALFORT.dato).toLocalDate())
assertThat(journalpostHendelse.sakstilknytninger?.size).isEqualTo(2)
assertThat(journalpostHendelse.sakstilknytninger).contains(sak1, sak2)
assertThat(journalpostHendelse.sporing?.brukerident).isEqualTo(journalfortAvIdent)
assertThat(journalpostHendelse.sporing?.saksbehandlersNavn).isEqualTo(journalfortAvNavn)
assertThat(journalpostHendelse.sporing?.enhetsnummer).isEqualTo(BRUKER_ENHET)
stubs.verifyStub.dokarkivOppdaterIkkeKalt(journalpostId)
stubs.verifyStub.harEnSafKallEtterTilknyttedeJournalposter()
}
}
| 2
|
Kotlin
|
1
| 1
|
ef939947f72bb1f928a120d035f997ac1ce6bcdc
| 5,051
|
bidrag-dokument-arkiv
|
MIT License
|
app/src/main/java/com/sys1yagi/safe_args_sample/ui/MainActivity.kt
|
sys1yagi
| 174,689,109
| false
| null |
package com.sys1yagi.safe_args_sample.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.sys1yagi.safe_args_sample.R
import com.sys1yagi.safe_args_sample.ui.top.TopFragment
import com.sys1yagi.safe_args_sample.util.newFragmentInstance
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
supportFragmentManager
.beginTransaction()
.add(
R.id.container,
newFragmentInstance<TopFragment>(),
TopFragment::class.java.name
)
.commit()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
54351ff6c7c7791c8d90efe018774b49b8bdc1d5
| 802
|
tbf6-safe-args
|
MIT License
|
modules/api/src/commonMain/kotlin/api/OllamaException.kt
|
nirmato
| 816,013,962
| false
|
{"Kotlin": 133457, "JavaScript": 203}
|
package org.nirmato.ollama.api
/** Ollama client exception */
public sealed class OllamaException(message: String? = null, throwable: Throwable? = null) : RuntimeException(message, throwable)
/** Runtime Http Client exception */
public class OllamaClientException(throwable: Throwable? = null) : OllamaException(throwable?.message, throwable)
/** An exception thrown in case of a server error */
public class OllamaServerException(throwable: Throwable? = null) : OllamaException(throwable?.message, throwable)
| 1
|
Kotlin
|
1
| 1
|
ce995579460485520852ddbd804c29dd8a319881
| 513
|
nirmato-ollama
|
Apache License 2.0
|
android/app/src/main/kotlin/com/v2ray/ang/viewmodel/SettingsViewModel.kt
|
PsrkGrmez
| 759,525,035
| false
| null |
package com.v2ray.ang.viewmodel
import android.app.Application
import android.content.SharedPreferences
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.preference.PreferenceManager
import com.tencent.mmkv.MMKV
import com.v2ray.ang.AppConfig
import com.v2ray.ang.util.MmkvManager
class SettingsViewModel(application: Application) : AndroidViewModel(application), SharedPreferences.OnSharedPreferenceChangeListener {
private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) }
fun startListenPreferenceChange() {
PreferenceManager.getDefaultSharedPreferences(getApplication()).registerOnSharedPreferenceChangeListener(this)
}
override fun onCleared() {
PreferenceManager.getDefaultSharedPreferences(getApplication()).unregisterOnSharedPreferenceChangeListener(this)
Log.i(AppConfig.ANG_PACKAGE, "Settings ViewModel is cleared")
super.onCleared()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String?) {
Log.d(AppConfig.ANG_PACKAGE, "Observe settings changed: $key")
when(key) {
AppConfig.PREF_MODE,
AppConfig.PREF_VPN_DNS,
AppConfig.PREF_REMOTE_DNS,
AppConfig.PREF_DOMESTIC_DNS,
AppConfig.PREF_LOCAL_DNS_PORT,
AppConfig.PREF_SOCKS_PORT,
AppConfig.PREF_HTTP_PORT,
AppConfig.PREF_LOGLEVEL,
AppConfig.PREF_LANGUAGE,
AppConfig.PREF_ROUTING_DOMAIN_STRATEGY,
AppConfig.PREF_ROUTING_MODE,
AppConfig.PREF_V2RAY_ROUTING_AGENT,
AppConfig.PREF_V2RAY_ROUTING_BLOCKED,
AppConfig.PREF_V2RAY_ROUTING_DIRECT, -> {
settingsStorage?.encode(key, sharedPreferences.getString(key, ""))
}
AppConfig.PREF_SPEED_ENABLED,
AppConfig.PREF_PROXY_SHARING,
AppConfig.PREF_LOCAL_DNS_ENABLED,
AppConfig.PREF_FAKE_DNS_ENABLED,
AppConfig.PREF_ALLOW_INSECURE,
AppConfig.PREF_PREFER_IPV6,
AppConfig.PREF_PER_APP_PROXY,
AppConfig.PREF_BYPASS_APPS,
AppConfig.PREF_CONFIRM_REMOVE,
AppConfig.PREF_START_SCAN_IMMEDIATE, -> {
settingsStorage?.encode(key, sharedPreferences.getBoolean(key, false))
}
AppConfig.PREF_SNIFFING_ENABLED -> {
settingsStorage?.encode(key, sharedPreferences.getBoolean(key, true))
}
AppConfig.PREF_PER_APP_PROXY_SET -> {
settingsStorage?.encode(key, sharedPreferences.getStringSet(key, setOf()))
}
}
}
}
| 2
| null |
7
| 85
|
1a6d3d8e6c6edcfd3be8f23bee339e1c83ab9346
| 2,717
|
ChiselBox
|
MIT License
|
desktop/views/src/main/kotlin/com/soyle/stories/layout/WindowChild.kt
|
Soyle-Productions
| 239,407,827
| false
| null |
package com.soyle.stories.layout
import com.soyle.stories.project.layout.WindowChildViewModel
import javafx.beans.property.Property
import tornadofx.Fragment
/**
* Created by Brendan
* Date: 2/15/2020
* Time: 4:32 PM
*/
abstract class WindowChild : Fragment() {
val model: Property<WindowChildViewModel> by params
}
| 45
|
Kotlin
|
0
| 9
|
1a110536865250dcd8d29270d003315062f2b032
| 327
|
soyle-stories
|
Apache License 2.0
|
src/main/kotlin/org/veupathdb/vdi/lib/common/util/short-id.kt
|
VEuPathDB
| 619,968,031
| false
|
{"Kotlin": 45667}
|
package org.veupathdb.vdi.lib.common.util
import org.unbrokendome.base62.Base62
import java.nio.ByteBuffer
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.random.Random
object ShortID {
private val random = Random(System.nanoTime())
private val miniLock = ReentrantLock()
private var now = System.currentTimeMillis()
private var miniCount: UShort = 0u
/**
* Generates an 11 digit time-based "mini" identifier encoded in base-62.
*
* This identifier is constructed of 3 parts:
*
* 1. 64 bits of random data. This is to prevent conflicts between IDs
* generated by different service stacks on the same millisecond.
* 2. 16 bits of "tie-breaker". This is a counter that increments when more
* than one id is generated within a single millisecond. If more than
* 65535 IDs are generated in a millisecond, this method will pause for one
* millisecond to reset the tie-break counter.
* 3. 40 bits of timestamp milliseconds. This is to prevent ID conflicts over
* time for up to 35 years.
*
* @return A new random identifier string.
*/
@JvmStatic
fun generate(): String {
var time = System.currentTimeMillis()
miniLock.withLock {
if (time == now) {
if (miniCount == UShort.MAX_VALUE) {
while (time == now) {
Thread.sleep(1)
time = System.currentTimeMillis()
}
now = time
miniCount = 0u
} else {
miniCount++
}
} else {
now = time
miniCount = 0u
}
}
val raw = ByteArray(15)
val buf = ByteBuffer.wrap(raw)
buf.putLong(random.nextLong())
buf.putShort(miniCount.toShort())
buf.appendBytes(time.toULong() shl 24, 5)
buf.rewind()
return Base62.encode(buf.asLongBuffer())
}
private fun ByteBuffer.appendBytes(v: ULong, count: Int) {
if (count > 8)
throw IllegalArgumentException()
var mask = 0xFF00000000000000uL
for (i in 1 .. count) {
val shift = (8 - i) * 8
put((((v and mask) shr shift) and 0xFFuL).toUByte().toByte())
mask = mask shr 8
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c0d231a00980ccffb0b04d2cd68cd878aab84761
| 2,188
|
vdi-component-common
|
Apache License 2.0
|
lib/src/main/java/com/sha/rxrequester/exception/handler/resumable/ResumableHandler.kt
|
thasneemp
| 216,811,559
| true
|
{"Kotlin": 33828, "Java": 660}
|
package com.sha.rxrequester.exception.handler.resumable
import com.sha.rxrequester.exception.handler.throwable.ThrowableInfo
import io.reactivex.Flowable
abstract class ResumableHandler {
/**
* checks if the handler can handle the error
* @return true if can handle
*/
abstract fun canHandle(info: ThrowableInfo): Boolean
/**
* handle the error
* @return Flowable that will be invoked after the error
* and if it succeeds, the original request will be resumed again
* For example, when receive 401 toke expired error, return the flowable that
* refreshes the token here to be invoked and retry the original request again.
*/
abstract fun handle(info: ThrowableInfo): Flowable<Any>
}
| 0
| null |
0
| 0
|
ad38fff6e7061212d80ec8e201ca59bc58feb728
| 749
|
RxRequester
|
Apache License 2.0
|
src/main/java/com/sayzen/campfiresdk/models/events/fandom/EventFandomReviewTextRemoved.kt
|
HorsePower68
| 230,018,763
| true
|
{"Kotlin": 1489208}
|
package com.sayzen.campfiresdk.models.events.fandom
class EventFandomReviewTextRemoved(
var publicationId: Long
)
| 0
| null |
0
| 0
|
214a4ee9262e185eb33a0ddcfc3a6803f22d54fd
| 123
|
CampfireSDK
|
Apache License 2.0
|
src/commonMain/kotlin/ch/tutteli/kbox/isNotNullAndNot.kt
|
robstoll
| 79,735,987
| false
| null |
package ch.tutteli.kbox
/**
* Returns true if this [CharSequence] is neither `null` nor empty.
*/
fun CharSequence?.isNotNullAndNotEmpty() = this != null && this.isNotEmpty()
/**
* Returns true if this [CharSequence] is neither `null` nor blank.
*/
fun CharSequence?.isNotNullAndNotBlank() = this != null && this.isNotBlank()
| 2
|
Kotlin
|
3
| 7
|
de34a0239d64ed0fdebf61c4f8163e7b8d05e316
| 332
|
kbox
|
Apache License 2.0
|
app/src/main/java/br/com/gilbercs/pokemon/api/RetrofitService.kt
|
gilbercs
| 406,868,895
| false
|
{"Kotlin": 7911}
|
package br.com.gilbercs.pokemon.api
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitService {
//url p/ API pokemon
private val base_url = "https://pokeapi.co/api/v2/"
//Create
val retrofit = Retrofit.Builder()
.baseUrl(base_url)
.addConverterFactory(GsonConverterFactory.create())
.build()
//create class generica
fun <T> buildService(service: Class<T>): T{
return retrofit.create(service)
}
}
| 0
|
Kotlin
|
0
| 3
|
f7caa424af63d13eee62eeb5c089319f21e7510b
| 501
|
appPokemon
|
MIT License
|
app/src/main/java/xyz/sentrionic/harmony/repository/main/SearchRepository.kt
|
sentrionic
| 220,498,638
| false
|
{"Kotlin": 325826}
|
package xyz.sentrionic.harmony.repository.main
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.switchMap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Job
import kotlinx.coroutines.withContext
import xyz.sentrionic.harmony.api.GenericResponse
import xyz.sentrionic.harmony.api.main.HarmonyMainService
import xyz.sentrionic.harmony.api.main.responses.ProfileListSearchResponse
import xyz.sentrionic.harmony.models.AuthToken
import xyz.sentrionic.harmony.models.Profile
import xyz.sentrionic.harmony.persistence.ProfileDao
import xyz.sentrionic.harmony.repository.JobManager
import xyz.sentrionic.harmony.repository.NetworkBoundResource
import xyz.sentrionic.harmony.session.SessionManager
import xyz.sentrionic.harmony.ui.DataState
import xyz.sentrionic.harmony.ui.Response
import xyz.sentrionic.harmony.ui.ResponseType
import xyz.sentrionic.harmony.ui.main.story.state.StoryViewState
import xyz.sentrionic.harmony.util.AbsentLiveData
import xyz.sentrionic.harmony.util.ApiSuccessResponse
import xyz.sentrionic.harmony.util.Constants.Companion.PAGINATION_PAGE_SIZE
import xyz.sentrionic.harmony.util.ErrorHandling.Companion.ERROR_UNKNOWN
import xyz.sentrionic.harmony.util.GenericApiResponse
import xyz.sentrionic.harmony.util.SuccessHandling
import javax.inject.Inject
class SearchRepository
@Inject
constructor(
val harmonyMainService: HarmonyMainService,
val profileDao: ProfileDao,
val sessionManager: SessionManager
) : JobManager("SearchRepository") {
private val TAG: String = "AppDebug"
fun searchUserProfiles(
authToken: AuthToken,
query: String,
filterAndOrder: String,
page: Int
): LiveData<DataState<StoryViewState>> {
return object :
NetworkBoundResource<ProfileListSearchResponse, List<Profile>, StoryViewState>(
sessionManager.isConnectedToTheInternet(),
true,
false,
true
) {
// if network is down, view cache only and return
override suspend fun createCacheRequestAndReturn() {
withContext(Dispatchers.Main) {
// finishing by viewing db cache
result.addSource(loadFromCache()) { viewState ->
viewState.userFields.isQueryInProgress = false
if (page * PAGINATION_PAGE_SIZE > viewState.userFields.userList.size) {
viewState.userFields.isQueryExhausted = true
}
onCompleteJob(DataState.data(viewState, null))
}
}
}
override suspend fun handleApiSuccessResponse(
response: ApiSuccessResponse<ProfileListSearchResponse>
) {
val profileList: ArrayList<Profile> = ArrayList()
for (profileResponse in response.body.results) {
profileList.add(
Profile(
pk = profileResponse.pk,
username = profileResponse.username,
display_name = profileResponse.display_name,
description = profileResponse.description,
website = profileResponse.website,
image = profileResponse.image,
posts = profileResponse.posts,
followers = profileResponse.followers,
following = profileResponse.following,
isFollowing = profileResponse.isFollowing
)
)
}
updateLocalDb(profileList)
createCacheRequestAndReturn()
}
override fun createCall(): LiveData<GenericApiResponse<ProfileListSearchResponse>> {
return harmonyMainService.searchProfiles(
"Token ${authToken.token!!}",
query = query,
ordering = filterAndOrder,
page = page
)
}
override fun loadFromCache(): LiveData<StoryViewState> {
return profileDao.getProfiles(query, page)
.switchMap {
object : LiveData<StoryViewState>() {
override fun onActive() {
super.onActive()
value = StoryViewState(
StoryViewState.StoryFields(),
StoryViewState.ViewStoryFields(),
StoryViewState.UserFields(
userList = it,
isQueryInProgress = true
)
)
}
}
}
}
override suspend fun updateLocalDb(cacheObject: List<Profile>?) {
// loop through list and update the local db
if (cacheObject != null) {
withContext(IO) {
for (profile in cacheObject) {
try {
// Launch each insert as a separate job to be executed in parallel
Log.d(TAG, "updateLocalDb: inserting story: ${profile}")
profileDao.insert(profile)
} catch (e: Exception) {
Log.e(
TAG,
"updateLocalDb: error updating cache data on story post with slug: ${profile.username}. " +
"${e.message}"
)
// Could send an error report here or something but I don't think you should throw an error to the UI
// Since there could be many story posts being inserted/updated.
}
}
}
} else {
Log.d(TAG, "updateLocalDb: story post list is null")
}
}
override fun setJob(job: Job) {
addJob("searchUserProfiles", job)
}
}.asLiveData()
}
fun toggleFollow(
authToken: AuthToken,
profile: Profile
) : LiveData<DataState<StoryViewState>> {
return object : NetworkBoundResource<GenericResponse, Profile, StoryViewState>(
sessionManager.isConnectedToTheInternet(),
true,
true,
false
) {
override suspend fun createCacheRequestAndReturn() {}
override suspend fun handleApiSuccessResponse(response: ApiSuccessResponse<GenericResponse>) {
when {
response.body.response == SuccessHandling.FOLLOWED -> {
profile.isFollowing = true
profile.followers += 1
updateLocalDb(profile)
}
response.body.response == SuccessHandling.UNFOLLOWED -> {
profile.isFollowing = false
profile.followers -= 1
updateLocalDb(profile)
}
else -> onCompleteJob(
DataState.error(
Response(
ERROR_UNKNOWN,
ResponseType.Dialog()
)
)
)
}
withContext(Dispatchers.Main){
// finish with success response
onCompleteJob(
DataState.data(
data = null,
response = null
)
)
}
}
override fun createCall(): LiveData<GenericApiResponse<GenericResponse>> {
return harmonyMainService.toggleFollow(
"Token ${authToken.token!!}",
profile.username
)
}
override fun loadFromCache(): LiveData<StoryViewState> {
return AbsentLiveData.create()
}
override suspend fun updateLocalDb(cacheObject: Profile?) {
cacheObject?.let { profile ->
profileDao.updateProfile(
profile.pk,
profile.followers,
profile.isFollowing
)
}
}
override fun setJob(job: Job) {
addJob("toggleLike", job)
}
}.asLiveData()
}
fun getProfile(authToken: AuthToken, username: String): LiveData<DataState<StoryViewState>> {
return object :
NetworkBoundResource<Profile, Profile, StoryViewState>(
sessionManager.isConnectedToTheInternet(),
true,
true,
false
) {
// if network is down, view the cache and return
override suspend fun createCacheRequestAndReturn() {
withContext(Dispatchers.Main) {
// finishing by viewing db cache
result.addSource(loadFromCache()) { viewState ->
onCompleteJob(DataState.data(viewState, null))
}
}
}
override suspend fun handleApiSuccessResponse(response: ApiSuccessResponse<Profile>) {
updateLocalDb(response.body)
createCacheRequestAndReturn()
}
override fun loadFromCache(): LiveData<StoryViewState> {
return profileDao.getProfile(username)
.switchMap {
object : LiveData<StoryViewState>() {
override fun onActive() {
super.onActive()
value = StoryViewState(
StoryViewState.StoryFields(),
StoryViewState.ViewStoryFields(),
StoryViewState.UserFields(),
StoryViewState.ViewProfileField(it, it.isFollowing, it.username)
)
}
}
}
}
override suspend fun updateLocalDb(cacheObject: Profile?) {
cacheObject?.let {
profileDao.insert(cacheObject)
}
}
override fun createCall(): LiveData<GenericApiResponse<Profile>> {
return harmonyMainService
.getProfile(
"Token ${authToken.token!!}",
username
)
}
override fun setJob(job: Job) {
addJob("getProfile", job)
}
}.asLiveData()
}
}
| 0
|
Kotlin
|
0
| 1
|
0751148a2566ad11098ddd7f122cade7c1792dc3
| 11,525
|
HarmonyApp
|
MIT License
|
src/test/kotlin/AsyncTest.kt
|
syahrulfahmi
| 734,462,073
| false
|
{"Kotlin": 34990}
|
import kotlinx.coroutines.*
import org.junit.jupiter.api.Test
import kotlin.system.measureTimeMillis
@OptIn(DelicateCoroutinesApi::class)
class AsyncTest {
/**
* Async mengembalikan object Deferred. Deffered adalah turunan dari job yang membawa
* hasil dari async function
*/
private suspend fun getFoo(): Int {
delay(1_000)
return 10
}
private suspend fun getBar(): Int {
delay(1_000)
return 5
}
@Test
fun testSuspendAsync() {
runBlocking {
val time = measureTimeMillis {
val foo = GlobalScope.async { getFoo() }
val bar = GlobalScope.async { getBar() }
val total = foo.await() + bar.await()
println("total sum: $total")
}
println("Total Time: $time")
}
}
@Test
fun testAwaitAll() {
runBlocking {
val time = measureTimeMillis {
val foo = GlobalScope.async { getFoo() }
val bar = GlobalScope.async { getBar() }
val total = awaitAll(foo, bar).sum()
println("total sum: $total")
}
println("Total Time: $time")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
df7b4f7b8226cc657d15b750b716b1b3ecd0e64f
| 1,243
|
learn-kotlin-coroutines
|
MIT License
|
ethers-core/src/test/kotlin/io/ethers/core/types/transactions/TransactionUnsignedTest.kt
|
Kr1ptal
| 712,963,462
| false
|
{"Kotlin": 854851, "Solidity": 3601}
|
package io.ethers.core.types.transactions
import io.ethers.core.types.AccessList
import io.ethers.core.types.Address
import io.ethers.core.types.Bytes
import io.ethers.core.types.Hash
import io.ethers.core.types.transaction.TransactionUnsigned
import io.ethers.core.types.transaction.TxAccessList
import io.ethers.core.types.transaction.TxDynamicFee
import io.ethers.core.types.transaction.TxLegacy
import io.ethers.rlp.RlpDecoder
import io.ethers.rlp.RlpEncoder
import io.kotest.core.spec.style.FunSpec
import io.kotest.datatest.withData
import io.kotest.matchers.shouldBe
class TransactionUnsignedTest : FunSpec({
val accessList = listOf(
AccessList.Item(
Address("0x2f62f2b4c5fcd7570a709dec05d68ea19c82a9ec"),
listOf(
Hash("0x9c2c23028bf4f085740a3671821db14e440561f617ea5532ee805d7f054741f6"),
Hash("0x000000000000000000000000000000000000000000000000000000000000000b"),
Hash("0x000000000000000000000000000000000000000000000000000000000000000a"),
),
),
)
context("signatureHash is correct") {
test("TxLegacy without chain ID") {
val tx = TxLegacy(
to = Address("0x32be343b94f860124dc4fee278fdcbd38c102d88"),
value = "53940392390000001024".toBigInteger(),
nonce = 71,
gas = 21000,
gasPrice = "60317759056".toBigInteger(),
data = null,
chainId = -1L,
)
tx.signatureHash().toHexString() shouldBe "3bb0e0f64fc2ccaeac16a5b6a54261b235371421647328b32ab3152c447f4b43"
}
test("TxLegacy with chain ID") {
val tx = TxLegacy(
to = Address("0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"),
value = "1000000000".toBigInteger(),
nonce = 0,
gas = 2000000,
gasPrice = "21000000000".toBigInteger(),
data = null,
chainId = 1L,
)
tx.signatureHash().toHexString() shouldBe "88cfbd7e51c7a40540b233cf68b62ad1df3e92462f1c6018d6d67eae0f3b08f5"
}
test("TxAccessList without access list") {
val tx = TxAccessList(
to = Address("0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"),
value = "1000000000".toBigInteger(),
nonce = 0,
gas = 2000000,
gasPrice = "21000000000".toBigInteger(),
data = Bytes("0x1214abcdef12445980"),
chainId = 1L,
accessList = null,
)
tx.signatureHash().toHexString() shouldBe "9cac944f150142405ab1873c80b72f75368664e417a87b90455d1f2e83178157"
}
test("TxAccessList with access list") {
val tx = TxAccessList(
to = Address("0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"),
value = "1000000000".toBigInteger(),
nonce = 0,
gas = 2000000,
gasPrice = "21000000000".toBigInteger(),
data = Bytes("0x1214abcdef12445980"),
chainId = 1L,
accessList = accessList,
)
tx.signatureHash().toHexString() shouldBe "d03f1041524fc50938d8ac6e8543dfcc31c51eeb66e6793655e8067a8165bd8c"
}
test("TxDynamicFee without access list") {
val tx = TxDynamicFee(
to = Address("0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"),
value = "1000000000".toBigInteger(),
nonce = 12425132,
gas = 2000000,
gasFeeCap = "210000000000".toBigInteger(),
gasTipCap = "21000000000".toBigInteger(),
data = Bytes("0x1214abcdef12445980"),
chainId = 1L,
accessList = null,
)
tx.signatureHash().toHexString() shouldBe "af6891de644ea94fb026f73fe8716d9e5aac2e374e81bea8aaa4e4f1e7ab50b5"
}
test("TxDynamicFee with access list") {
val tx = TxDynamicFee(
to = Address("0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"),
value = "1000000000".toBigInteger(),
nonce = 12425132,
gas = 2000000,
gasFeeCap = "210000000000".toBigInteger(),
gasTipCap = "21000000000".toBigInteger(),
data = Bytes("0x1214abcdef12445980"),
chainId = 1L,
accessList = accessList,
)
tx.signatureHash().toHexString() shouldBe "02f1301823f1eaa4cbf6832369fea3a5754bf88a13d95ac7eb6d2f8320f85c27"
}
}
context("RLP decoding") {
withData(
TxLegacy(
to = Address("0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"),
value = "1000000000".toBigInteger(),
nonce = 1,
gas = 2000000,
gasPrice = "21000000000".toBigInteger(),
data = Bytes("0x01"),
chainId = 1L,
),
TxAccessList(
to = Address("0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"),
value = "1000000000".toBigInteger(),
nonce = 1,
gas = 2000000,
gasPrice = "21000000000".toBigInteger(),
data = Bytes("0x1214abcdef12445980"),
chainId = 1L,
accessList = accessList,
),
TxDynamicFee(
to = Address("0xF0109fC8DF283027b6285cc889F5aA624EaC1F55"),
value = "1000000000".toBigInteger(),
nonce = 12425132,
gas = 2000000,
gasFeeCap = "210000000000".toBigInteger(),
gasTipCap = "21000000000".toBigInteger(),
data = Bytes("0x1214abcdef12445980"),
chainId = 1L,
accessList = accessList,
),
) { tx ->
val encoder = RlpEncoder()
tx.rlpEncode(encoder)
val decoder = RlpDecoder(encoder.toByteArray())
TransactionUnsigned.rlpDecode(decoder, tx.chainId) shouldBe tx
}
}
})
| 13
|
Kotlin
|
1
| 5
|
6c71cceb6461c8fd50f64b7746b53139a1c6f726
| 6,227
|
ethers-kt
|
Apache License 2.0
|
app/src/main/java/com/example/cryptoassets/core/repository/TransacaoRepository.kt
|
fabiosoaza
| 275,875,400
| false
| null |
package com.example.cryptoassets.core.repository
import com.example.cryptoassets.core.model.entidade.Ativo
import com.example.cryptoassets.core.model.entidade.Transacao
interface TransacaoRepository {
fun transacoes():Set<Transacao>
fun transacoes(ativo:Ativo):Set<Transacao>
fun salvar(transacao: Transacao)
fun excluir(transacao: Transacao)
fun excluirTodas(ativo:Ativo)
}
| 0
|
Kotlin
|
0
| 0
|
312bbd3448e1aa1b44493b321a781af1f65a4019
| 401
|
crypto-assets
|
MIT License
|
app/src/main/java/com/example/getty_images_app/data/source/mapper/MainMapper.kt
|
dev-baik
| 806,049,181
| false
|
{"Kotlin": 21027}
|
package com.example.getty_images_app.data.source.mapper
import com.example.getty_images_app.data.model.main.MainDTO
import com.example.getty_images_app.data.model.main.MainResponse
import com.example.getty_images_app.domain.model.HtmlParseResult
import com.example.getty_images_app.domain.model.MainList
import com.example.getty_images_app.domain.model.MainRecyclerViewItem
object MainMapper {
fun HtmlParseResult<MainResponse>.toMainDomain(): HtmlParseResult<MainList> {
return when (this) {
is HtmlParseResult.Success -> HtmlParseResult.Success(data.toMainList())
is HtmlParseResult.Error -> HtmlParseResult.Error(exception)
}
}
private fun MainResponse.toMainList(): MainList {
val mainItems = contents.map { it.toItem() }
val combinedList = mainItems + MainRecyclerViewItem.PageNumber(pageNumber = 1)
return MainList(combinedList)
}
private fun MainDTO.toItem(): MainRecyclerViewItem.MainItem =
MainRecyclerViewItem.MainItem(
url = this.url,
title = this.title
)
}
| 0
|
Kotlin
|
0
| 0
|
1b28c4875cfebe90c2c28e2f2dc99402948516ab
| 1,097
|
Getty-Images-App
|
Apache License 2.0
|
app/src/main/java/com/example/getty_images_app/data/source/mapper/MainMapper.kt
|
dev-baik
| 806,049,181
| false
|
{"Kotlin": 21027}
|
package com.example.getty_images_app.data.source.mapper
import com.example.getty_images_app.data.model.main.MainDTO
import com.example.getty_images_app.data.model.main.MainResponse
import com.example.getty_images_app.domain.model.HtmlParseResult
import com.example.getty_images_app.domain.model.MainList
import com.example.getty_images_app.domain.model.MainRecyclerViewItem
object MainMapper {
fun HtmlParseResult<MainResponse>.toMainDomain(): HtmlParseResult<MainList> {
return when (this) {
is HtmlParseResult.Success -> HtmlParseResult.Success(data.toMainList())
is HtmlParseResult.Error -> HtmlParseResult.Error(exception)
}
}
private fun MainResponse.toMainList(): MainList {
val mainItems = contents.map { it.toItem() }
val combinedList = mainItems + MainRecyclerViewItem.PageNumber(pageNumber = 1)
return MainList(combinedList)
}
private fun MainDTO.toItem(): MainRecyclerViewItem.MainItem =
MainRecyclerViewItem.MainItem(
url = this.url,
title = this.title
)
}
| 0
|
Kotlin
|
0
| 0
|
1b28c4875cfebe90c2c28e2f2dc99402948516ab
| 1,097
|
Getty-Images-App
|
Apache License 2.0
|
chrome/src/main/kotlin/chrome/index.chrome.system.storage.kt
|
GaryLaurenceau
| 626,374,779
| false
| null |
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "NESTED_CLASS_IN_EXTERNAL_INTERFACE")
@file:JsQualifier("chrome.system.storage")
package chrome.system.storage
import kotlin.js.*
import kotlin.js.Json
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
external interface StorageUnitInfo {
var id: String
var name: String
var type: String
var capacity: Number
}
external interface StorageCapacityInfo {
var id: String
var availableCapacity: Number
}
external interface SystemStorageAttachedEvent : chrome.events.Event<(info: StorageUnitInfo) -> Unit>
external interface SystemStorageDetachedEvent : chrome.events.Event<(id: String) -> Unit>
external fun getInfo(callback: (info: Array<StorageUnitInfo>) -> Unit): Unit = definedExternally
external fun ejectDevice(id: String, callback: (result: String) -> Unit): Unit = definedExternally
external fun getAvailableCapacity(id: String, callback: (info: StorageCapacityInfo) -> Unit): Unit = definedExternally
external var onAttached: SystemStorageAttachedEvent = definedExternally
external var onDetached: SystemStorageDetachedEvent = definedExternally
| 0
|
Kotlin
|
0
| 22
|
d74e08a26e34f6b93572af18aededfc92736b9a7
| 1,487
|
kotlin-chrome-extension
|
The Unlicense
|
app/src/unitTest/kotlin/batect/ui/FailureErrorMessageFormatterSpec.kt
|
camjackson
| 201,380,011
| true
|
{"Kotlin": 1979130, "Python": 19036, "Shell": 12803, "Groovy": 11432, "PowerShell": 5620, "Dockerfile": 5069, "Batchfile": 2828, "Java": 1205, "HTML": 400}
|
/*
Copyright 2017-2019 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.ui
import batect.config.BuildImage
import batect.config.Container
import batect.config.PullImage
import batect.docker.DockerContainer
import batect.execution.CleanupOption
import batect.execution.RunOptions
import batect.execution.model.events.ContainerCreatedEvent
import batect.execution.model.events.ContainerCreationFailedEvent
import batect.execution.model.events.ContainerDidNotBecomeHealthyEvent
import batect.execution.model.events.ContainerRemovalFailedEvent
import batect.execution.model.events.ContainerRunFailedEvent
import batect.execution.model.events.ContainerStartFailedEvent
import batect.execution.model.events.ContainerStopFailedEvent
import batect.execution.model.events.ExecutionFailedEvent
import batect.execution.model.events.ImageBuildFailedEvent
import batect.execution.model.events.ImagePullFailedEvent
import batect.execution.model.events.TaskEvent
import batect.execution.model.events.TaskFailedEvent
import batect.execution.model.events.TaskNetworkCreationFailedEvent
import batect.execution.model.events.TaskNetworkDeletedEvent
import batect.execution.model.events.TaskNetworkDeletionFailedEvent
import batect.execution.model.events.TemporaryDirectoryDeletionFailedEvent
import batect.execution.model.events.TemporaryFileDeletionFailedEvent
import batect.execution.model.events.UserInterruptedExecutionEvent
import batect.os.SystemInfo
import batect.testutils.equivalentTo
import batect.testutils.given
import batect.testutils.imageSourceDoesNotMatter
import batect.testutils.on
import batect.testutils.osIndependentPath
import batect.testutils.withMessage
import batect.ui.text.Text
import batect.ui.text.TextRun
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.throws
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object FailureErrorMessageFormatterSpec : Spek({
describe("a failure error message formatter") {
val lineEnding = "\nthe-line-ending\n"
val systemInfo = mock<SystemInfo> {
on { lineSeparator } doReturn lineEnding
}
val formatter = FailureErrorMessageFormatter(systemInfo)
fun Text.withPlatformSpecificLineSeparator() = this.copy(content.replace("\n", lineEnding))
fun TextRun.withPlatformSpecificLineSeparator() = this.map { it.withPlatformSpecificLineSeparator() }
describe("formatting a message to display after a failure event occurs") {
val container = Container("the-container", imageSourceDoesNotMatter())
data class Scenario(val description: String, val event: TaskFailedEvent, val expectedMessage: TextRun)
setOf(
Scenario(
"task network creation failed",
TaskNetworkCreationFailedEvent("Something went wrong."),
Text.red(Text.bold("Error: ") + Text("Could not create network for task.\n")) + Text("Something went wrong.")
),
Scenario(
"image build failed",
ImageBuildFailedEvent(BuildImage(osIndependentPath("/some-build-dir")), "Something went wrong."),
Text.red(Text.bold("Error: ") + Text("Could not build image from directory '/some-build-dir'.\n")) + Text("Something went wrong.")
),
Scenario(
"image pull failed",
ImagePullFailedEvent(PullImage("the-image"), "Something went wrong."),
Text.red(Text.bold("Error: ") + Text("Could not pull image ") + Text.bold("the-image") + Text(".\n")) + Text("Something went wrong.")
),
Scenario(
"container creation failed",
ContainerCreationFailedEvent(container, "Something went wrong."),
Text.red(Text.bold("Error: ") + Text("Could not create container ") + Text.bold("the-container") + Text(".\n")) + Text("Something went wrong.")
),
Scenario(
"task network deletion failed",
TaskNetworkDeletionFailedEvent("Something went wrong."),
Text.red(Text.bold("Error: ") + Text("Could not delete the task network.\n")) + Text("Something went wrong.")
),
Scenario(
"temporary file deletion failed",
TemporaryFileDeletionFailedEvent(osIndependentPath("/tmp/some-file"), "Something went wrong."),
Text.red(Text.bold("Error: ") + Text("Could not delete temporary file '/tmp/some-file'.\n")) + Text("Something went wrong.")
),
Scenario(
"temporary directory deletion failed",
TemporaryDirectoryDeletionFailedEvent(osIndependentPath("/tmp/some-directory"), "Something went wrong."),
Text.red(Text.bold("Error: ") + Text("Could not delete temporary directory '/tmp/some-directory'.\n")) + Text("Something went wrong.")
),
Scenario(
"container run failed",
ContainerRunFailedEvent(container, "Something went wrong."),
Text.red(Text.bold("Error: ") + Text("Could not run container ") + Text.bold("the-container") + Text(".\n")) + Text("Something went wrong.")
),
Scenario(
"container stop failed",
ContainerStopFailedEvent(container, "Something went wrong."),
Text.red(Text.bold("Error: ") + Text("Could not stop container ") + Text.bold("the-container") + Text(".\n")) + Text("Something went wrong.")
),
Scenario(
"container removal failed",
ContainerRemovalFailedEvent(container, "Something went wrong."),
Text.red(Text.bold("Error: ") + Text("Could not remove container ") + Text.bold("the-container") + Text(".\n")) + Text("Something went wrong.")
),
Scenario(
"execution failed",
ExecutionFailedEvent("Something went wrong."),
Text.red(Text.bold("Error: ") + Text("An unexpected exception occurred during execution.\n")) + Text("Something went wrong.")
),
Scenario(
"user interrupted execution",
UserInterruptedExecutionEvent,
Text.red(Text.bold("Error: ") + Text("Interrupt received during execution.\n")) + Text("User interrupted execution.")
)
).forEach { (description, event, expectedMessage) ->
given("a '$description' event") {
on("getting the message for that event") {
val message = formatter.formatErrorMessage(event, mock())
it("returns an appropriate error message") {
assertThat(message, equivalentTo(expectedMessage.withPlatformSpecificLineSeparator()))
}
}
}
}
setOf(
Scenario(
"container start failed",
ContainerStartFailedEvent(container, "Something went wrong."),
Text.red(Text.bold("Error: ") + Text("Could not start container ") + Text.bold("the-container") + Text(".\n")) + Text("Something went wrong.")
),
Scenario(
"container did not become healthy",
ContainerDidNotBecomeHealthyEvent(container, "Something went wrong."),
Text.red(Text.bold("Error: ") + Text("Container ") + Text.bold("the-container") + Text(" did not become healthy.\n")) + Text("Something went wrong.")
)
).forEach { (description, event, expectedMessage) ->
given("a '$description' event") {
given("cleanup after failure is disabled") {
val runOptions = mock<RunOptions> {
on { behaviourAfterFailure } doReturn CleanupOption.DontCleanup
}
on("getting the message for that event") {
val message = formatter.formatErrorMessage(event, runOptions)
it("returns an appropriate error message") {
assertThat(message, equivalentTo(expectedMessage.withPlatformSpecificLineSeparator()))
}
}
}
given("cleanup after failure is enabled") {
val runOptions = mock<RunOptions> {
on { behaviourAfterFailure } doReturn CleanupOption.Cleanup
}
on("getting the message for that event") {
val message = formatter.formatErrorMessage(event, runOptions)
val expectedMessageWithCleanupInfo = expectedMessage + Text("\n\nYou can re-run the task with ") + Text.bold("--no-cleanup-after-failure") + Text(" to leave the created containers running to diagnose the issue.")
it("returns an appropriate error message with a message mentioning that the task can be re-run with cleanup disabled") {
assertThat(
message,
equivalentTo(expectedMessageWithCleanupInfo.withPlatformSpecificLineSeparator())
)
}
}
}
}
}
}
describe("formatting a message to display after the task has failed with cleanup disabled") {
given("no events were posted") {
val events = emptySet<TaskEvent>()
it("throws an appropriate exception") {
assertThat(
{ formatter.formatManualCleanupMessageAfterTaskFailureWithCleanupDisabled(events, emptyList()) },
throws<IllegalArgumentException>(withMessage("No containers were created and so this method should not be called."))
)
}
}
given("no containers were created") {
val events = setOf(
TaskNetworkDeletedEvent
)
it("throws an appropriate exception") {
assertThat(
{ formatter.formatManualCleanupMessageAfterTaskFailureWithCleanupDisabled(events, emptyList()) },
throws<IllegalArgumentException>(withMessage("No containers were created and so this method should not be called."))
)
}
}
given("a container was created") {
val events = setOf(
ContainerCreatedEvent(Container("http-server", imageSourceDoesNotMatter()), DockerContainer("http-server-container-id"))
)
given("there are no cleanup commands") {
val cleanupCommands = emptyList<String>()
on("formatting the message") {
it("throws an appropriate exception") {
assertThat(
{ formatter.formatManualCleanupMessageAfterTaskFailureWithCleanupDisabled(events, cleanupCommands) },
throws<IllegalArgumentException>(withMessage("No cleanup commands were provided."))
)
}
}
}
given("there is one cleanup command") {
val cleanupCommands = listOf(
"docker network rm some-network"
)
on("formatting the message") {
val message = formatter.formatManualCleanupMessageAfterTaskFailureWithCleanupDisabled(events, cleanupCommands)
val expectedMessage = Text.red(Text("As the task was run with ") + Text.bold("--no-cleanup-after-failure") + Text(", the created containers will not be cleaned up.\n")) +
Text("For container ") + Text.bold("http-server") + Text(", view its output by running '") + Text.bold("docker logs http-server-container-id") +
Text("', or run a command in the container with '") + Text.bold("docker exec -it http-server-container-id <command>") + Text("'.\n") +
Text("\n") +
Text("Once you have finished investigating the issue, clean up all temporary resources created by batect by running:\n") +
Text.bold("docker network rm some-network")
it("returns an appropriate message") {
assertThat(message, equivalentTo(expectedMessage.withPlatformSpecificLineSeparator()))
}
}
}
given("there are multiple cleanup commands") {
val cleanupCommands = listOf(
"docker rm some-container",
"docker network rm some-network"
)
on("formatting the message") {
val message = formatter.formatManualCleanupMessageAfterTaskFailureWithCleanupDisabled(events, cleanupCommands)
val expectedMessage =
Text.red(Text("As the task was run with ") + Text.bold("--no-cleanup-after-failure") + Text(", the created containers will not be cleaned up.\n")) +
Text("For container ") + Text.bold("http-server") + Text(", view its output by running '") + Text.bold("docker logs http-server-container-id") +
Text("', or run a command in the container with '") + Text.bold("docker exec -it http-server-container-id <command>") + Text("'.\n") +
Text("\n") +
Text("Once you have finished investigating the issue, clean up all temporary resources created by batect by running:\n") +
Text.bold("docker rm some-container\n") +
Text.bold("docker network rm some-network")
it("returns an appropriate message") {
assertThat(message, equivalentTo(expectedMessage.withPlatformSpecificLineSeparator()))
}
}
}
}
given("some containers were created") {
val events = setOf(
ContainerCreatedEvent(Container("http-server", imageSourceDoesNotMatter()), DockerContainer("http-server-container-id")),
ContainerCreatedEvent(Container("database", imageSourceDoesNotMatter()), DockerContainer("database-container-id"))
)
given("there are no cleanup commands") {
val cleanupCommands = emptyList<String>()
on("formatting the message") {
it("throws an appropriate exception") {
assertThat(
{ formatter.formatManualCleanupMessageAfterTaskFailureWithCleanupDisabled(events, cleanupCommands) },
throws<IllegalArgumentException>(withMessage("No cleanup commands were provided."))
)
}
}
}
given("there is one cleanup command") {
val cleanupCommands = listOf(
"docker network rm some-network"
)
on("formatting the message") {
val message = formatter.formatManualCleanupMessageAfterTaskFailureWithCleanupDisabled(events, cleanupCommands)
val expectedMessage =
Text.red(Text("As the task was run with ") + Text.bold("--no-cleanup-after-failure") + Text(", the created containers will not be cleaned up.\n")) +
Text("For container ") + Text.bold("database") + Text(", view its output by running '") + Text.bold("docker logs database-container-id") +
Text("', or run a command in the container with '") + Text.bold("docker exec -it database-container-id <command>") + Text("'.\n") +
Text("For container ") + Text.bold("http-server") + Text(", view its output by running '") + Text.bold("docker logs http-server-container-id") +
Text("', or run a command in the container with '") + Text.bold("docker exec -it http-server-container-id <command>") + Text("'.\n") +
Text("\n") +
Text("Once you have finished investigating the issue, clean up all temporary resources created by batect by running:\n") +
Text.bold("docker network rm some-network")
it("returns an appropriate message") {
assertThat(message, equivalentTo(expectedMessage.withPlatformSpecificLineSeparator()))
}
}
}
given("there are multiple cleanup commands") {
val cleanupCommands = listOf(
"docker rm some-container",
"docker network rm some-network"
)
on("formatting the message") {
val message = formatter.formatManualCleanupMessageAfterTaskFailureWithCleanupDisabled(events, cleanupCommands)
val expectedMessage =
Text.red(Text("As the task was run with ") + Text.bold("--no-cleanup-after-failure") + Text(", the created containers will not be cleaned up.\n")) +
Text("For container ") + Text.bold("database") + Text(", view its output by running '") + Text.bold("docker logs database-container-id") +
Text("', or run a command in the container with '") + Text.bold("docker exec -it database-container-id <command>") + Text("'.\n") +
Text("For container ") + Text.bold("http-server") + Text(", view its output by running '") + Text.bold("docker logs http-server-container-id") +
Text("', or run a command in the container with '") + Text.bold("docker exec -it http-server-container-id <command>") + Text("'.\n") +
Text("\n") +
Text("Once you have finished investigating the issue, clean up all temporary resources created by batect by running:\n") +
Text.bold("docker rm some-container\n") +
Text.bold("docker network rm some-network")
it("returns an appropriate message") {
assertThat(message, equivalentTo(expectedMessage.withPlatformSpecificLineSeparator()))
}
}
}
}
}
describe("formatting a message to display after cleanup failed") {
given("there are no cleanup commands") {
val cleanupCommands = emptyList<String>()
on("formatting the message") {
val message = formatter.formatManualCleanupMessageAfterCleanupFailure(cleanupCommands)
it("returns an empty set of text") {
assertThat(message, equivalentTo(TextRun()))
}
}
}
given("there is one cleanup command") {
val cleanupCommands = listOf(
"docker network rm some-network"
)
on("formatting the message") {
val message = formatter.formatManualCleanupMessageAfterCleanupFailure(cleanupCommands)
val expectedMessage = Text.red("Clean up has failed, and batect cannot guarantee that all temporary resources created have been completely cleaned up.\n") +
Text("You may need to run the following command to clean up any remaining resources:\n") +
Text.bold("docker network rm some-network")
it("returns an appropriate message") {
assertThat(message, equivalentTo(expectedMessage.withPlatformSpecificLineSeparator()))
}
}
}
given("there are multiple cleanup commands") {
val cleanupCommands = listOf(
"rm -rf /tmp/the-thing",
"docker rm some-container",
"docker network rm some-network"
)
on("formatting the message") {
val message = formatter.formatManualCleanupMessageAfterCleanupFailure(cleanupCommands)
val expectedMessage = Text.red("Clean up has failed, and batect cannot guarantee that all temporary resources created have been completely cleaned up.\n") +
Text("You may need to run some or all of the following commands to clean up any remaining resources:\n") +
Text.bold("rm -rf /tmp/the-thing\n") +
Text.bold("docker rm some-container\n") +
Text.bold("docker network rm some-network")
it("returns an appropriate message") {
assertThat(message, equivalentTo(expectedMessage.withPlatformSpecificLineSeparator()))
}
}
}
}
}
})
| 0
|
Kotlin
|
0
| 0
|
940b607ea42d5d87b0e841aa692a4d9f058282bc
| 22,910
|
batect
|
Apache License 2.0
|
bbimageview/src/main/java/com/cjespinozani/widget/BbImageViewSwitcher.kt
|
cjespinoza-ni
| 267,804,586
| false
| null |
/*
* Copyright (C) 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cjespinozani.widget
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.util.AttributeSet
import android.widget.ViewSwitcher
/**
* Displays images using [BbImageView]
* extends [ViewSwitcher] to apply transition effects when the image changes
*
* @attr ref [R.styleable.BbImageViewSwitcher_src]
* @attr ref [R.styleable.BbImageViewSwitcher_show_blurred_background]
* @attr ref [R.styleable.BbImageViewSwitcher_blur_radius]
* @attr ref [R.styleable.BbImageViewSwitcher_hide_main_image]
*/
open class BbImageViewSwitcher(context: Context, attrs: AttributeSet?, defStyleAttr: Int = 0) :
ViewSwitcher(context, attrs) {
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context) : this(context, null, 0)
private var mShowBlurredBackground: Boolean
private var mBlurRadius: Float
private var mHideMainImage: Boolean
var showBlurredBackground: Boolean
/**
* Return whether to show a blurred background.
* @return whether to show a blurred background.
*/
get() = mShowBlurredBackground
/**
* Sets whether to show a blurred background.
* @param value whether to show a blurred background.
*/
set(value) {
if (value != mShowBlurredBackground) {
mShowBlurredBackground = value
handleShowBlurRadiusChanged()
}
}
var blurRadius: Float
/**
* Gets the radius to use when blurring the background.
* @return the radius used to blur the background drawable.
*/
get() = mBlurRadius
/**
* Sets the radius of the blur to apply to the background.
* Supported range 0 < radius <= 25
* @param value The radius of the blur
*/
set(value) {
if (value <= 0 || value > 25) return
if (value != mBlurRadius) {
mBlurRadius = value
handleBlurRadiusChanged()
}
}
var hideMainImage: Boolean
/**
* Return whether to hide the main image.
* @return whether to hide the main image.
*/
get() = mHideMainImage
/**
* Sets whether to hide the main image.
* @param value whether to hide the main image.
*/
set(value) {
if (value != mHideMainImage) {
mHideMainImage = value
handleHideMainImageChanged()
}
}
init {
BbImageView(context).also {
this.addView(it)
}
BbImageView(context).also {
this.addView(it)
}
val a = context.obtainStyledAttributes(
attrs, R.styleable.BbImageViewSwitcher, defStyleAttr, 0
)
mShowBlurredBackground = a.getBoolean(
R.styleable.BbImageViewSwitcher_show_blurred_background,
DEFAULT_SHOW_BLURRED_BACKGROUND
)
mBlurRadius = a.getFloat(R.styleable.BbImageViewSwitcher_blur_radius, DEFAULT_BLUR_RADIUS)
mHideMainImage =
a.getBoolean(R.styleable.BbImageViewSwitcher_hide_main_image, DEFAULT_HIDE_MAIN_IMAGE)
if (a.hasValue(R.styleable.BbImageViewSwitcher_src)) {
a.getDrawable(R.styleable.BbImageViewSwitcher_src)?.also {
setImageDrawable(it)
}
}
a.recycle()
//update children values
handleShowBlurRadiusChanged()
handleBlurRadiusChanged()
handleHideMainImageChanged()
}
/**
* Sets a drawable as the content of this view.
* @param drawable the Drawable to set, or {@code null} to clear the content
*/
fun setImageDrawable(drawable: Drawable?) {
nextView.also {
if (it is BbImageView)
it.setImageDrawable(drawable)
showNext()
}
}
/**
* Sets a bitmap as the content of this view.
* @param bitmap the Bitmap to set, or {@code null} to clear the content
*/
fun setImageBitmap(bitmap: Bitmap?) {
nextView.also {
if (it is BbImageView)
it.setImageBitmap(bitmap)
showNext()
}
}
/**
* Sets a drawable as the content of this view.
* @param resId the resource identifier of the drawable
*/
fun setImageSrc(resId: Int) {
nextView.also {
if (it is BbImageView)
it.setImageResource(resId)
showNext()
}
}
/**
* Sets the content of this ImageView to the specified Uri.
* Note that you use this method to load images from a local Uri only.
* @param uri the Uri of an image, or {@code null} to clear the content
*/
fun setImageURI(uri: Uri?) {
nextView.also {
if (it is BbImageView)
it.setImageURI(uri)
showNext()
}
}
/**
* Updates children's [BbImageView.showBlurredBackground]
*/
private fun handleShowBlurRadiusChanged() {
for (i in 0 until childCount) {
getChildAt(i)?.also {
if (it is BbImageView)
it.showBlurredBackground = mShowBlurredBackground
}
}
}
/**
* Updates children's [BbImageView.blurRadius]
*/
private fun handleBlurRadiusChanged() {
for (i in 0 until childCount) {
getChildAt(i)?.also {
if (it is BbImageView)
it.blurRadius = mBlurRadius
}
}
}
/**
* Updates children's [BbImageView.hideMainImage]
*/
private fun handleHideMainImageChanged() {
for (i in 0 until childCount) {
getChildAt(i)?.also {
if (it is BbImageView)
it.hideMainImage = mHideMainImage
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
4f2138c4f821fbf6e1a5c705f1881dea47cc40a0
| 6,609
|
BbImageView
|
Apache License 2.0
|
bbimageview/src/main/java/com/cjespinozani/widget/BbImageViewSwitcher.kt
|
cjespinoza-ni
| 267,804,586
| false
| null |
/*
* Copyright (C) 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cjespinozani.widget
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.util.AttributeSet
import android.widget.ViewSwitcher
/**
* Displays images using [BbImageView]
* extends [ViewSwitcher] to apply transition effects when the image changes
*
* @attr ref [R.styleable.BbImageViewSwitcher_src]
* @attr ref [R.styleable.BbImageViewSwitcher_show_blurred_background]
* @attr ref [R.styleable.BbImageViewSwitcher_blur_radius]
* @attr ref [R.styleable.BbImageViewSwitcher_hide_main_image]
*/
open class BbImageViewSwitcher(context: Context, attrs: AttributeSet?, defStyleAttr: Int = 0) :
ViewSwitcher(context, attrs) {
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context) : this(context, null, 0)
private var mShowBlurredBackground: Boolean
private var mBlurRadius: Float
private var mHideMainImage: Boolean
var showBlurredBackground: Boolean
/**
* Return whether to show a blurred background.
* @return whether to show a blurred background.
*/
get() = mShowBlurredBackground
/**
* Sets whether to show a blurred background.
* @param value whether to show a blurred background.
*/
set(value) {
if (value != mShowBlurredBackground) {
mShowBlurredBackground = value
handleShowBlurRadiusChanged()
}
}
var blurRadius: Float
/**
* Gets the radius to use when blurring the background.
* @return the radius used to blur the background drawable.
*/
get() = mBlurRadius
/**
* Sets the radius of the blur to apply to the background.
* Supported range 0 < radius <= 25
* @param value The radius of the blur
*/
set(value) {
if (value <= 0 || value > 25) return
if (value != mBlurRadius) {
mBlurRadius = value
handleBlurRadiusChanged()
}
}
var hideMainImage: Boolean
/**
* Return whether to hide the main image.
* @return whether to hide the main image.
*/
get() = mHideMainImage
/**
* Sets whether to hide the main image.
* @param value whether to hide the main image.
*/
set(value) {
if (value != mHideMainImage) {
mHideMainImage = value
handleHideMainImageChanged()
}
}
init {
BbImageView(context).also {
this.addView(it)
}
BbImageView(context).also {
this.addView(it)
}
val a = context.obtainStyledAttributes(
attrs, R.styleable.BbImageViewSwitcher, defStyleAttr, 0
)
mShowBlurredBackground = a.getBoolean(
R.styleable.BbImageViewSwitcher_show_blurred_background,
DEFAULT_SHOW_BLURRED_BACKGROUND
)
mBlurRadius = a.getFloat(R.styleable.BbImageViewSwitcher_blur_radius, DEFAULT_BLUR_RADIUS)
mHideMainImage =
a.getBoolean(R.styleable.BbImageViewSwitcher_hide_main_image, DEFAULT_HIDE_MAIN_IMAGE)
if (a.hasValue(R.styleable.BbImageViewSwitcher_src)) {
a.getDrawable(R.styleable.BbImageViewSwitcher_src)?.also {
setImageDrawable(it)
}
}
a.recycle()
//update children values
handleShowBlurRadiusChanged()
handleBlurRadiusChanged()
handleHideMainImageChanged()
}
/**
* Sets a drawable as the content of this view.
* @param drawable the Drawable to set, or {@code null} to clear the content
*/
fun setImageDrawable(drawable: Drawable?) {
nextView.also {
if (it is BbImageView)
it.setImageDrawable(drawable)
showNext()
}
}
/**
* Sets a bitmap as the content of this view.
* @param bitmap the Bitmap to set, or {@code null} to clear the content
*/
fun setImageBitmap(bitmap: Bitmap?) {
nextView.also {
if (it is BbImageView)
it.setImageBitmap(bitmap)
showNext()
}
}
/**
* Sets a drawable as the content of this view.
* @param resId the resource identifier of the drawable
*/
fun setImageSrc(resId: Int) {
nextView.also {
if (it is BbImageView)
it.setImageResource(resId)
showNext()
}
}
/**
* Sets the content of this ImageView to the specified Uri.
* Note that you use this method to load images from a local Uri only.
* @param uri the Uri of an image, or {@code null} to clear the content
*/
fun setImageURI(uri: Uri?) {
nextView.also {
if (it is BbImageView)
it.setImageURI(uri)
showNext()
}
}
/**
* Updates children's [BbImageView.showBlurredBackground]
*/
private fun handleShowBlurRadiusChanged() {
for (i in 0 until childCount) {
getChildAt(i)?.also {
if (it is BbImageView)
it.showBlurredBackground = mShowBlurredBackground
}
}
}
/**
* Updates children's [BbImageView.blurRadius]
*/
private fun handleBlurRadiusChanged() {
for (i in 0 until childCount) {
getChildAt(i)?.also {
if (it is BbImageView)
it.blurRadius = mBlurRadius
}
}
}
/**
* Updates children's [BbImageView.hideMainImage]
*/
private fun handleHideMainImageChanged() {
for (i in 0 until childCount) {
getChildAt(i)?.also {
if (it is BbImageView)
it.hideMainImage = mHideMainImage
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
4f2138c4f821fbf6e1a5c705f1881dea47cc40a0
| 6,609
|
BbImageView
|
Apache License 2.0
|
core/src/main/java/org/bitcoinj/core/AlertMessage.kt
|
brad1121
| 128,862,201
| false
|
{"Java": 3778141, "Kotlin": 908516, "Shell": 2950, "Groovy": 2178, "CSS": 1838, "Batchfile": 746}
|
/*
* Copyright 2011 Google Inc.
* Copyright 2015 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bitcoinj.core
import java.util.Date
import java.util.HashSet
/**
* Alerts are signed messages that are broadcast on the peer-to-peer network if they match a hard-coded signing key.
* The private keys are held by a small group of core Bitcoin developers, and alerts may be broadcast in the event of
* an available upgrade or a serious network problem. Alerts have an expiration time, data that specifies what
* set of software versions it matches and the ability to cancel them by broadcasting another type of alert.
*
*
*
* The right course of action on receiving an alert is usually to either ensure a human will see it (display on screen,
* log, email), or if you decide to use alerts for notifications that are specific to your app in some way, to parse it.
* For example, you could treat it as an upgrade notification specific to your app. Satoshi designed alerts to ensure
* that software upgrades could be distributed independently of a hard-coded website, in order to allow everything to
* be purely peer-to-peer. You don't have to use this of course, and indeed it often makes more sense not to.
*
*
*
*
* Before doing anything with an alert, you should check [AlertMessage.isSignatureValid].
*
*
* Instances of this class are not safe for use by multiple threads.
*/
class AlertMessage @Throws(ProtocolException::class)
constructor(params: NetworkParameters, payloadBytes: ByteArray) : Message(params, payloadBytes, 0) {
private var content: ByteArray? = null
private var signature: ByteArray? = null
// See the getters for documentation of what each field means.
var version: Long = 1
private set
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Field accessors.
/**
* The time at which the alert should stop being broadcast across the network. Note that you can still receive
* the alert after this time from other nodes if the alert still applies to them or to you.
*/
var relayUntil: Date? = null
/**
* The time at which the alert ceases to be relevant. It should not be presented to the user or app administrator
* after this time.
*/
var expiration: Date? = null
/**
* The numeric identifier of this alert. Each alert should have a unique ID, but the signer can choose any number.
* If an alert is broadcast with a cancel field higher than this ID, this alert is considered cancelled.
* @return uint32
*/
var id: Long = 0
/**
* A marker that results in any alerts with an ID lower than this value to be considered cancelled.
* @return uint32
*/
var cancel: Long = 0
/**
* The inclusive lower bound on software versions that are considered for the purposes of this alert. Bitcoin Core
* compares this against a protocol version field, but as long as the subVer field is used to restrict it your
* alerts could use any version numbers.
* @return uint32
*/
var minVer: Long = 0
/**
* The inclusive upper bound on software versions considered for the purposes of this alert. Bitcoin Core
* compares this against a protocol version field, but as long as the subVer field is used to restrict it your
* alerts could use any version numbers.
*/
var maxVer: Long = 0
/**
* Provides an integer ordering amongst simultaneously active alerts.
* @return uint32
*/
var priority: Long = 0
/**
* This field is unused. It is presumably intended for the author of the alert to provide a justification for it
* visible to protocol developers but not users.
*/
var comment: String? = null
/**
* A string that is intended to display in the status bar of Bitcoin Core's GUI client. It contains the user-visible
* message. English only.
*/
var statusBar: String? = null
/**
* This field is never used.
*/
var reserved: String? = null
/**
* Returns true if the digital signature attached to the message verifies. Don't do anything with the alert if it
* doesn't verify, because that would allow arbitrary attackers to spam your users.
*/
val isSignatureValid: Boolean
get() = ECKey.verify(Sha256Hash.hashTwice(content), signature!!, params!!.alertSigningKey)
override fun toString(): String {
return "ALERT: " + statusBar!!
}
@Throws(ProtocolException::class)
override fun parse() {
// Alerts are formatted in two levels. The top level contains two byte arrays: a signature, and a serialized
// data structure containing the actual alert data.
val startPos = cursor
content = readByteArray()
signature = readByteArray()
// Now we need to parse out the contents of the embedded structure. Rewind back to the start of the message.
cursor = startPos
readVarInt() // Skip the length field on the content array.
// We're inside the embedded structure.
version = readUint32()
// Read the timestamps. Bitcoin uses seconds since the epoch.
relayUntil = Date(readUint64().toLong() * 1000)
expiration = Date(readUint64().toLong() * 1000)
id = readUint32()
cancel = readUint32()
// Sets are serialized as <len><item><item><item>....
val cancelSetSize = readVarInt()
if (cancelSetSize < 0 || cancelSetSize > MAX_SET_SIZE) {
throw ProtocolException("Bad cancel set size: " + cancelSetSize)
}
// Using a hashset here is very inefficient given that this will normally be only one item. But Java doesn't
// make it easy to do better. What we really want is just an array-backed set.
val cancelSet = HashSet<Long>(cancelSetSize.toInt())
for (i in 0 until cancelSetSize) {
cancelSet.add(readUint32())
}
minVer = readUint32()
maxVer = readUint32()
// Read the subver matching set.
val subverSetSize = readVarInt()
if (subverSetSize < 0 || subverSetSize > MAX_SET_SIZE) {
throw ProtocolException("Bad subver set size: " + subverSetSize)
}
val matchingSubVers = HashSet<String>(subverSetSize.toInt())
for (i in 0 until subverSetSize) {
matchingSubVers.add(readStr())
}
priority = readUint32()
comment = readStr()
statusBar = readStr()
reserved = readStr()
length = cursor - offset
}
companion object {
// Chosen arbitrarily to avoid memory blowups.
private val MAX_SET_SIZE: Long = 100
}
}
| 1
| null |
1
| 1
|
d25f870673836ef09eaf31eab6f7c3cb77a13035
| 7,305
|
bitcoinkt-cash
|
Apache License 2.0
|
kotlin-dsl/example/src/test/kotlin/com/chutneytesting/example/selenium/SeleniumTest.kt
|
owerfelli
| 791,217,559
| true
|
{"Markdown": 64, "Batchfile": 2, "Shell": 2, "Gradle Kotlin DSL": 6, "INI": 5, "Java": 984, "HTML": 64, "JavaScript": 6, "Kotlin": 241, "SQL": 4, "Java Properties": 1, "Dockerfile": 3, "CSS": 1, "TypeScript": 250}
|
package com.chutneytesting.example.selenium
import com.chutneytesting.example.scenario.selenium_scenario
import com.chutneytesting.kotlin.dsl.Environment
import com.chutneytesting.kotlin.launcher.Launcher
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.openqa.selenium.firefox.FirefoxOptions
import org.testcontainers.containers.BrowserWebDriverContainer
import org.testcontainers.containers.GenericContainer
import org.testcontainers.containers.Network
import org.testcontainers.images.PullPolicy
import org.testcontainers.junit.jupiter.Testcontainers
import org.testcontainers.utility.DockerImageName
import java.time.Duration
@Testcontainers
class SeleniumTest {
val network = Network.newNetwork()
val chutneyServer = GenericContainer(DockerImageName.parse("ghcr.io/chutney-testing/chutney/server:latest"))
.withImagePullPolicy(PullPolicy.alwaysPull())
.withNetworkAliases("chutneyServer")
.withExposedPorts(8443)
.withNetwork(network)
.withStartupTimeout(Duration.ofSeconds(80))
val webDriverContainer = BrowserWebDriverContainer()
.withCapabilities(FirefoxOptions().setAcceptInsecureCerts(true))
.withNetwork(network)
@BeforeEach
fun setUp() {
chutneyServer.start()
webDriverContainer.start()
}
@AfterEach
fun tearDown() {
webDriverContainer.stop()
chutneyServer.stop()
}
@Test
fun `Selenium test`() {
val env = Environment("Global", "") {}
Launcher().run(selenium_scenario(webDriverContainer.seleniumAddress.toString()), env)
}
}
| 0
| null |
0
| 0
|
a7b0bf69921fd29f846763ba4e67e271dbfaad13
| 1,673
|
chutney
|
Apache License 2.0
|
jdbc/spring-data-jpa/src/test/kotlin/tech/ydb/jpa/YdbDockerTest.kt
|
ydb-platform
| 491,175,873
| false
|
{"Maven POM": 20, "Text": 1, "Ignore List": 1, "Markdown": 2, "INI": 9, "XML": 12, "Kotlin": 30, "SQL": 2, "Java": 74, "YAML": 3, "HTML": 1}
|
package tech.ydb.jpa
import org.junit.jupiter.api.extension.RegisterExtension
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.DynamicPropertyRegistry
import org.springframework.test.context.DynamicPropertySource
import tech.ydb.test.junit5.YdbHelperExtension
/**
* @author Kirill Kurdyukov
*/
@ActiveProfiles("test", "ydb")
abstract class YdbDockerTest {
companion object {
@JvmField
@RegisterExtension
val ydb = YdbHelperExtension()
@JvmStatic
@DynamicPropertySource
fun propertySource(registry: DynamicPropertyRegistry) {
registry.add("spring.datasource.url") {
"jdbc:ydb:${if (ydb.useTls()) "grpcs://" else "grpc://"}" +
"${ydb.endpoint()}${ydb.database()}${ydb.authToken()?.let { "?token=$it" } ?: ""}"
}
}
}
}
| 1
|
Java
|
4
| 6
|
125bb467d959b5a10c44d7a30557996a6d204d6e
| 895
|
ydb-java-examples
|
Apache License 2.0
|
library_api/src/main/java/com/crow/ksp/api/RouteInterceptor.kt
|
crowforkotlin
| 798,153,843
| false
|
{"Kotlin": 27881}
|
package com.crow.ksp.api
interface RouteInterceptor {
fun intercept(request: RouteRequest): Boolean
}
| 0
|
Kotlin
|
0
| 0
|
5a89525b8254cf84f9da450714e8df631cbe2a76
| 107
|
Ksp-Template
|
Apache License 2.0
|
feature-wallet-api/src/main/java/io/novafoundation/nova/feature_wallet_api/data/network/crosschain/CrossChainTransfersRepository.kt
|
novasamatech
| 415,834,480
| false
|
{"Kotlin": 8137060, "Java": 14723, "JavaScript": 425}
|
package io.novafoundation.nova.feature_wallet_api.data.network.crosschain
import io.novafoundation.nova.feature_wallet_api.domain.model.CrossChainTransfersConfiguration
import kotlinx.coroutines.flow.Flow
interface CrossChainTransfersRepository {
suspend fun syncConfiguration()
fun configurationFlow(): Flow<CrossChainTransfersConfiguration>
suspend fun getConfiguration(): CrossChainTransfersConfiguration
}
| 12
|
Kotlin
|
6
| 9
|
618357859a4b7af95391fc0991339b78aff1be82
| 427
|
nova-wallet-android
|
Apache License 2.0
|
app/src/main/java/com/btpj/wanandroid/ui/share/add/AddArticleViewModel.kt
|
BTPJ
| 486,802,334
| false
| null |
package com.btpj.module_mine.ui.share.add
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.btpj.lib_base.base.BaseViewModel
import com.btpj.lib_base.data.local.UserManager
import com.btpj.lib_base.ext.handleRequest
import com.btpj.lib_base.ext.launch
import com.btpj.module_mine.data.DataRepository
class AddArticleViewModel : BaseViewModel() {
val title = ObservableField("")
val articleLink = ObservableField("")
val shareUserName = ObservableField("")
/** 登录按键是否可点击(这样可避免在dataBinding中写较复杂的逻辑) */
val shareBtnEnable = object : ObservableBoolean(title, articleLink) {
override fun get(): Boolean {
return !title.get()?.trim().isNullOrEmpty() && !articleLink.get()?.trim()
.isNullOrEmpty()
}
}
override fun start() {
shareUserName.set(UserManager.getUser()?.nickname ?: "")
}
/**
* 添加分享的文章
*
* @param title 标题
* @param link 文章链接
*/
fun addArticle(title: String, link: String, successAction: () -> Any? = {}) {
launch({
val response = DataRepository.addArticle(title, link)
handleRequest(response, {
successAction.invoke()
})
})
}
}
| 1
| null |
33
| 91
|
139d4bfe53154ad6da773e94c6a71d96e1f4b25c
| 1,279
|
WanAndroid
|
Apache License 2.0
|
src/main/kotlin/org/opensearch/replication/task/shard/TranslogSequencer.kt
|
saikaranam-amazon
| 395,243,911
| true
|
{"Kotlin": 737317, "Shell": 1132}
|
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.replication.task.shard
import org.opensearch.replication.ReplicationException
import org.opensearch.replication.action.changes.GetChangesResponse
import org.opensearch.replication.action.replay.ReplayChangesAction
import org.opensearch.replication.action.replay.ReplayChangesRequest
import org.opensearch.replication.metadata.store.ReplicationMetadata
import org.opensearch.replication.util.suspendExecute
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.actor
import kotlinx.coroutines.launch
import org.opensearch.client.Client
import org.opensearch.common.logging.Loggers
import org.opensearch.index.shard.ShardId
import org.opensearch.index.translog.Translog
import org.opensearch.tasks.TaskId
import java.util.concurrent.ConcurrentHashMap
/**
* A TranslogSequencer allows multiple producers of [Translog.Operation]s to write them in sequence number order to an
* index. It internally uses an [actor] to serialize writes to the index. Producer can call the [send] method
* to add a batch of operations to the queue. If the queue is full the producer will be suspended. Operations can be
* sent out of order i.e. the operation with sequence number 2 can be sent before the operation with sequence number 1.
* In this case the Sequencer will internally buffer the operations that cannot be delivered until the missing in-order
* operations arrive.
*
* This uses the ObsoleteCoroutinesApi actor API. As described in the [actor] docs there is no current replacement for
* this API and a new one is being worked on to which we can migrate when needed.
*/
@ObsoleteCoroutinesApi
class TranslogSequencer(scope: CoroutineScope, private val replicationMetadata: ReplicationMetadata,
private val followerShardId: ShardId,
private val leaderAlias: String, private val leaderIndexName: String,
private val parentTaskId: TaskId, private val client: Client, initialSeqNo: Long) {
private val unAppliedChanges = ConcurrentHashMap<Long, GetChangesResponse>()
private val log = Loggers.getLogger(javaClass, followerShardId)!!
private val completed = CompletableDeferred<Unit>()
private val sequencer = scope.actor<Unit>(capacity = Channel.UNLIMITED) {
// Exceptions thrown here will mark the channel as failed and the next attempt to send to the channel will
// raise the same exception. See [SendChannel.close] method for details.
var highWatermark = initialSeqNo
for (m in channel) {
while (unAppliedChanges.containsKey(highWatermark + 1)) {
val next = unAppliedChanges.remove(highWatermark + 1)!!
val replayRequest = ReplayChangesRequest(followerShardId, next.changes, next.maxSeqNoOfUpdatesOrDeletes,
leaderAlias, leaderIndexName)
replayRequest.parentTask = parentTaskId
launch {
val replayResponse = client.suspendExecute(replicationMetadata, ReplayChangesAction.INSTANCE, replayRequest)
if (replayResponse.shardInfo.failed > 0) {
replayResponse.shardInfo.failures.forEachIndexed { i, failure ->
log.error("Failed replaying changes. Failure:$i:$failure")
}
throw org.opensearch.replication.ReplicationException("failed to replay changes", replayResponse.shardInfo.failures)
}
}
highWatermark = next.changes.lastOrNull()?.seqNo() ?: highWatermark
}
}
completed.complete(Unit)
}
suspend fun close() {
sequencer.close()
completed.await()
}
suspend fun send(changes : GetChangesResponse) {
unAppliedChanges[changes.fromSeqNo] = changes
sequencer.send(Unit)
}
}
| 0
| null |
0
| 0
|
4e552ff07fd5284e30327f9558ce0ea04488ab0e
| 4,377
|
cross-cluster-replication-2
|
Apache License 2.0
|
app/src/main/java/com/mob/lee/fastair/fragment/ConnectFragment.kt
|
hongui
| 123,892,735
| false
| null |
package com.mob.lee.fastair.fragment
import com.mob.lee.fastair.R
import com.mob.lee.fastair.base.AppFragment
import com.mob.lee.fastair.p2p.P2PManager
abstract class ConnectFragment : AppFragment() {
override fun setting() {
if (!P2PManager.isConnected()) {
navigation(R.id.discoverFragment)
} else {
super.setting()
}
}
}
| 3
|
Kotlin
|
14
| 72
|
0526fe4bb1eff33c1278c1ac86f02785710817bd
| 382
|
FastAir
|
Apache License 2.0
|
app/src/main/java/com/soneso/lumenshine/presentation/wallets/FundedWalletCardView.kt
|
Soneso
| 144,008,654
| false
| null |
package com.soneso.lumenshine.presentation.wallets
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.TextView
import androidx.core.view.size
import com.soneso.lumenshine.R
import com.soneso.lumenshine.domain.data.Wallet
import com.soneso.lumenshine.model.entities.wallet.WalletBalanceEntity
import com.soneso.lumenshine.presentation.util.setStyleCompat
import kotlinx.android.synthetic.main.view_funded_wallet_card.view.*
class FundedWalletCardView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.style.AppTheme_LsCardView
) : WalletCardView(context, attrs, defStyleAttr) {
init {
View.inflate(context, R.layout.view_funded_wallet_card, this)
}
override fun populate(wallet: Wallet) {
nameView.text = wallet.name
if (wallet.federationAddress.isBlank()) {
subtitleView.setText(R.string.no_stellar_address)
} else {
subtitleView.text = wallet.federationAddress
}
if (wallet.balances?.size ?: 0 > 1) {
balanceTitleView.setText(R.string.wallet_balances)
} else {
balanceTitleView.setText(R.string.wallet_balance)
}
populateBalances(wallet.balances ?: return)
populateAvailabilities(wallet.minimumAccountBalance(), wallet.balances ?: return)
}
private fun populateBalances(balances: List<WalletBalanceEntity>) {
if (balancesView.childCount > balances.size) {
for (index in balances.size until balancesView.childCount) {
balancesView.removeViewAt(index)
}
} else {
for (index in balancesView.size until balances.size) {
balancesView.addView(TextView(context).apply { setStyleCompat(R.style.WalletCardBalanceValueView) }, index)
}
}
for (index in 0 until balances.size) {
val balance = balances[index]
@SuppressLint("SetTextI18n")
(balancesView.getChildAt(index) as TextView).text = "${"%.2f".format(balance.amount)} ${balance.code}"
}
}
private fun populateAvailabilities(minBalance: Double, balances: List<WalletBalanceEntity>) {
if (availabilitiesView.childCount > balances.size) {
for (index in balances.size until availabilitiesView.childCount) {
availabilitiesView.removeViewAt(index)
}
} else {
for (index in availabilitiesView.size until balances.size) {
availabilitiesView.addView(TextView(context).apply { setStyleCompat(R.style.WalletCardAvailabilityValueView) }, index)
}
}
for (index in 0 until balances.size) {
val balance = balances[index]
@SuppressLint("SetTextI18n")
(availabilitiesView.getChildAt(index) as TextView).text = "${"%.2f".format(balance.availableAmount(minBalance))} ${balance.code}"
}
}
}
| 0
|
Kotlin
|
2
| 1
|
a088d0107dbe769c2814b199dddea0177a9aabec
| 3,047
|
lumenshine-android-wallet
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com.zzx/common/socket/FileHelper.kt
|
zhangzexin
| 695,853,977
| false
|
{"Kotlin": 182996, "Java": 921, "Swift": 580, "Shell": 228}
|
package com.zzx.common.socket
import com.zzx.common.socket.ByteType.MARK_END
import com.zzx.common.socket.ByteType.MARK_READY
import okhttp3.WebSocket
import okio.ByteString.Companion.toByteString
import java.io.File
import java.nio.ByteBuffer
/**
*@描述:
*@time:2023/9/25
*@author:zhangzexin
*/
object FileHelper {
var byteBuffer:ByteBuffer? = null
fun createFileDir(filePath:String):File {
val dir = File(filePath)
if (!dir.exists()) {
dir.mkdir()
}
return dir
}
suspend fun pushFileReady(webSocket: WebSocket) {
var byteBuffer = ByteBuffer.allocate(4 * 1024)
byteBuffer.put(ByteType.BYTE_FILE_READY)
byteBuffer.put(MARK_READY.toByteArray())
byteBuffer.flip()
webSocket.send(byteBuffer.toByteString())
byteBuffer.clear()
}
fun senFileEnd(webSocket: WebSocket) {
if (byteBuffer == null) {
byteBuffer = ByteBuffer.allocate(4*1024)
}
byteBuffer?.apply {
put(ByteType.BYTE_FILE_END)
put(MARK_END.toByteArray())
flip()
webSocket.send(this.toByteString())
}
close()
}
fun close() {
byteBuffer?.clear()
byteBuffer = null
}
}
| 0
|
Kotlin
|
0
| 0
|
acd46309574857fe28f0414ca5bd6fc9745d73ef
| 1,272
|
Team_Deck
|
Apache License 2.0
|
feature/weight/src/main/java/com/paradise/ptpt/feature/weight/nav/FeatureWeightModule.kt
|
sksowk156
| 624,277,724
| false
|
{"Kotlin": 579556}
|
package com.paradise.ptpt.feature.weight.nav
import com.paradise.ptpt.core.common_ui.navicontract.FeatureWeightContract
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object FeatureWeightModule {
@Singleton
@Provides
fun providesFeatureWeightContract(): FeatureWeightContract = FeatureWeightContractImpl()
}
| 0
|
Kotlin
|
0
| 1
|
f498af23b88d27870467efca989a12a2be7b851a
| 472
|
Hellth
|
Apache License 2.0
|
app/src/main/java/com/ved/ui/fragment/select/SelectItemFragment.kt
|
vedeng
| 244,312,896
| false
| null |
package com.ved.ui.fragment.select
import android.view.View
import com.bese.view.SelectTextAttr
import com.bese.view.SelectTextLayout
import com.blankj.utilcode.util.LogUtils
import com.ved.R
import com.ved.ui.base.BaseFragment
import kotlinx.android.synthetic.main.fragment_select_item.*
import kotlin.random.Random
/**
* Author: Endless
* Date: 2020/5/19
* Desc:
*/
class SelectItemFragment : BaseFragment() {
override fun loadView(): Int {
return R.layout.fragment_select_item
}
override fun init() {
initTitle("单选复选")
fragment_select_item_sl_01?.run {
val list = generateLabels()
initChild(list)
setSelectListener(object : SelectTextLayout.OnSelectChangeListener {
override fun onSelect(pos: Int, view: View) {
LogUtils.e("选中=====", "$pos")
}
override fun onUnSelect(pos: Int, view: View) {
LogUtils.e("取关=====", "$pos")
}
})
}
fragment_select_item_sl_02?.run {
val list = generateLabels()
initChild(list, true)
setSelectListener(object : SelectTextLayout.OnSelectChangeListener {
override fun onSelect(pos: Int, view: View) {
LogUtils.e("选中2=====", "$pos")
}
override fun onUnSelect(pos: Int, view: View) {
LogUtils.e("取关2=====", "$pos")
}
})
}
val baseUseArea = "●单选复选场景使用,可自动换行,改变颜色。"
val baseUseRole = "●可设置单选和多选\n" +
"●可设置最大、最小选中数量\n"
val baseInteract = "●点你就懂了"
val baseStyle = "●未选中为灰底黑字,选中为蓝色描边蓝字\n" +
"●字体大小为16sp, 标签横向间距为16dp, 纵向间距为10dp\n" +
"●标签间距为10dp\n" +
"●尺寸可修改,选中样式可修改\n"
initContent(baseUseArea, baseUseRole, baseInteract, baseStyle)
}
override fun doExecute() {
}
private fun generateLabels(): ArrayList<SelectTextAttr> {
val list = arrayListOf<SelectTextAttr>()
for (index in 0..Random.nextInt(5, 20)) {
list.add(SelectTextAttr("标签$index", false, Random.nextBoolean()))
}
return list
}
}
| 0
|
Kotlin
|
0
| 0
|
8a92cd925b57a481a8e0422d225da2c5396bca22
| 2,259
|
Bese
|
Creative Commons Zero v1.0 Universal
|
frogosdk/src/main/java/com/frogobox/sdk/core/FrogoConstant.kt
|
frogobox
| 293,762,352
| false
| null |
package com.frogobox.sdk.core
import android.os.Environment
/*
* Created by faisalamir on 26/07/21
* FrogoSDK
* -----------------------------------------
* Name : <NAME>
* E-mail : <EMAIL>
* Github : github.com/amirisback
* -----------------------------------------
* Copyright (C) 2021 FrogoBox Inc.
* All rights reserved
*
*/
object FrogoConstant {
val TAG = FrogoConstant::class.java.simpleName
const val OPTION_GET = "OPTION_GET"
const val OPTION_DELETE = "OPTION_DELETE"
const val DEFAULT_NULL = "null"
const val DEFAULT_ERROR_MESSAGE = "Failed"
const val FRAGMENT_DIALOG = "dialog"
const val SPLASH_INTERVAL = 1000
object Value {
const val VALUE_SENSOR_ORIENTATION_DEFAULT_DEGREES = 90
const val VALUE_SENSOR_ORIENTATION_INVERSE_DEGREES = 270
}
object Tag {
const val TAG_ACTIVITY_EDIT = 300
const val TAG_ACTIVITY_CREATE = 301
const val TAG_ACTIVITY_DETAIL = 302
const val TAG_FROM_ACTIVITY = 801
const val TAG_FROM_FRAGMENT = 800
const val TAG_CAMERA_VIDEO = "Camera2VideoFragment"
}
object Ext {
const val MP4 = ".mp4"
const val PNG = ".png"
const val CSV = ".csv"
}
object Dir {
private const val BASE_FILE_NAME = "SPEECH_"
private const val BASE_DIR_NAME = "BaseMusicPlayer"
val DIR_NAME = "${Environment.DIRECTORY_PICTURES}/$BASE_DIR_NAME"
val VIDEO_FILE_NAME = "$BASE_FILE_NAME${System.currentTimeMillis()}${Ext.MP4}"
}
}
| 0
|
Kotlin
|
0
| 8
|
427d5a98ef5027f000fab91d8e563a606bbb0462
| 1,553
|
frogo-android-sdk
|
Apache License 2.0
|
BlogMVVM/app/src/main/java/com/juanma/blogmvvm/presentation/screens/new_post/NewPostScreen.kt
|
JmanuelJ
| 604,375,672
| false
|
{"Kotlin": 147282}
|
package com.juanma.blogmvvm.presentation.screens.new_post
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.juanma.blogmvvm.presentation.components.DefaultButton
import com.juanma.blogmvvm.presentation.components.DefaultTopBar
import com.juanma.blogmvvm.presentation.screens.new_post.components.NewPost
import com.juanma.blogmvvm.presentation.screens.new_post.components.NewPostContent
@Composable
fun NewPostScreen(navController: NavHostController, viewModel: NewPostViewModel = hiltViewModel()){
Scaffold(
topBar = {
DefaultTopBar(
title = "Nuevo Post",
upAvailable = true,
navController = navController
)
},
content = {
NewPostContent()
},
bottomBar = {
DefaultButton(
modifier = Modifier.fillMaxWidth(),
text = "PUBLICAR",
onClick = { viewModel.onNewPost() })
}
)
NewPost()
}
| 0
|
Kotlin
|
0
| 1
|
6504b78b62abcf317cef58211edee9f0c15ff9af
| 1,301
|
Blog_Example
|
Academic Free License v1.1
|
buildSrc/src/main/kotlin/Modules.kt
|
im-o
| 718,908,780
| false
|
{"Kotlin": 156609}
|
/** Created by github.com/im-o on 11/15/2023. */
object Modules {
const val core = ":core"
const val home = ":features:home"
const val auth = ":features:auth"
}
| 0
|
Kotlin
|
1
| 0
|
6cc1658634eb8273d6cf6d02d37b3a9c7f33dd30
| 173
|
android-compose-haidoc-ui
|
MIT License
|
src/main/kotlin/com/retheviper/excel/worker/BookWorker.kt
|
retheviper
| 352,027,386
| false
| null |
package com.retheviper.excel.worker
import com.retheviper.excel.definition.BookDef
import com.retheviper.excel.definition.SheetDef
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.ss.usermodel.WorkbookFactory
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
/**
* Worker for manipulate excel file.
*/
open class BookWorker(
/**
* Definition of book.
*/
private val bookDef: BookDef,
/**
* Path for input.
*/
private val inputPath: String,
/**
* Path for output.
*/
private var outputPath: String? = null
) : AutoCloseable {
/**
* Apache POI's workbook class.
*/
private val workbook: Workbook = WorkbookFactory.create(File(inputPath))
/**
* Path for output.
*/
private var output: Path? = null
init {
outputPath?.let { output = Path.of(it) }
}
/**
* Get [SheetWorker].
*
* @param sheetName
* @return SheetWorker
*/
private fun getSheetWorker(sheetName: String?) = searchSheetDef { it.name == sheetName }
/**
* Get [SheetWorker].
*
* @param index
* @return SheetWorker
*/
private fun getSheetWorker(index: Int) = searchSheetDef { it.index == index }
/**
* Get [SheetWorker].
*
* @param dataClass
* @return SheetWorker
*/
private fun getSheetWorker(dataClass: Class<*>) = searchSheetDef { it.dataClass == dataClass }
/**
* Search [SheetDef] with condition and map to [SheetWorker].
*
* @param condition
* @return
*/
private fun searchSheetDef(condition: (target: SheetDef) -> Boolean) =
bookDef.sheetDefs.first(condition).let { getSheetWorker(it) }
/**
* Get [SheetWorker].
*
* @param sheetDef
* @return
*/
private fun getSheetWorker(sheetDef: SheetDef) =
SheetWorker(
sheetDef = sheetDef,
sheet = if (sheetDef.index > -1) workbook.getSheetAt(sheetDef.index) else workbook.getSheet(sheetDef.name)
)
/**
* Write data into sheet.
*
* @param data
* @param <T>
</T> */
fun <T> write(data: List<T>) =
getSheetWorker(data.first()!!::class.java).listToSheet(data)
/**
* Read data from sheet as list.
*
* @param sheetName
* @param <T>
* @return
</T> */
fun <T> read(sheetName: String): List<T> =
getSheetWorker(sheetName).sheetToList()
/**
* Read data from sheet as list.
*
* @param index
* @param <T>
* @return
</T> */
fun <T> read(index: Int): List<T> =
getSheetWorker(index).sheetToList()
/**
* Read data from sheet as list.
*
* @param dataClass
* @param <T>
* @return
</T> */
fun <T> read(dataClass: Class<T>): List<T> =
getSheetWorker(dataClass).sheetToList()
override fun close() {
if (output != null) {
output!!.let {
if (Files.notExists(it.parent)) {
Files.createDirectories(it.parent)
}
Files.newOutputStream(it).use { stream -> workbook.write(stream) }
}
} else {
workbook.close()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
518f78b17911d10a093ce19a467829f7d0074884
| 3,279
|
ExcelWeaverKotlin
|
MIT License
|
app/src/main/java/com/breezefsmshreebajrangsteeludyog/features/stockCompetetorStock/api/AddCompStockRepository.kt
|
DebashisINT
| 645,424,403
| false
| null |
package com.breezefsmshreebajrangsteeludyog.features.stockCompetetorStock.api
import com.breezefsmshreebajrangsteeludyog.base.BaseResponse
import com.breezefsmshreebajrangsteeludyog.features.orderList.model.NewOrderListResponseModel
import com.breezefsmshreebajrangsteeludyog.features.stockCompetetorStock.ShopAddCompetetorStockRequest
import com.breezefsmshreebajrangsteeludyog.features.stockCompetetorStock.model.CompetetorStockGetData
import io.reactivex.Observable
class AddCompStockRepository(val apiService:AddCompStockApi){
fun addCompStock(shopAddCompetetorStockRequest: ShopAddCompetetorStockRequest): Observable<BaseResponse> {
return apiService.submShopCompStock(shopAddCompetetorStockRequest)
}
fun getCompStockList(sessiontoken: String, user_id: String, date: String): Observable<CompetetorStockGetData> {
return apiService.getCompStockList(sessiontoken, user_id, date)
}
}
| 0
|
Kotlin
|
0
| 0
|
45503058a15346909552eeab08a9e78ffb3a199a
| 922
|
ShreeBajrangSteelUdyog
|
Apache License 2.0
|
app/src/main/java/com/example/epoxypagingsample/ui/model/DataBindingModel.kt
|
yutaro6547
| 226,437,428
| false
| null |
package com.example.epoxypagingsample.ui.model
import android.content.Context
import androidx.databinding.ViewDataBinding
import com.airbnb.epoxy.EpoxyModel
import com.airbnb.epoxy.EpoxyModelWithHolder
abstract class DataBindingModel<in T : ViewDataBinding> :
EpoxyModelWithHolder<DataBindingEpoxyHolder<Any?>>() {
abstract fun bind(binding: T, context: Context)
abstract fun bind(binding: T, context: Context, previouslyBoundModel: EpoxyModel<*>)
abstract fun unbind(binding: T)
@Suppress("UNCHECKED_CAST")
override fun bind(holder: DataBindingEpoxyHolder<Any?>) {
val binding = holder.binding as? T ?: return
val context = binding.root.context
bind(binding, context)
}
@Suppress("UNCHECKED_CAST")
override fun bind(holder: DataBindingEpoxyHolder<Any?>, previouslyBoundModel: EpoxyModel<*>) {
val binding = holder.binding as? T ?: return
val context = binding.root.context
bind(binding, context, previouslyBoundModel)
}
@Suppress("UNCHECKED_CAST")
override fun unbind(holder: DataBindingEpoxyHolder<Any?>) {
val binding = holder.binding as? T ?: return
unbind(binding)
}
}
| 0
|
Kotlin
|
0
| 0
|
8e853536b49b080bd595d233e2dc794e5b8142b8
| 1,199
|
EpoxyPagingSample
|
Apache License 2.0
|
app/src/main/java/com/ozan/cleanpokedex/ui/detail/recycler/stats/PokemonStatsRecyclerAdapter.kt
|
rooest
| 365,615,639
| true
|
{"Kotlin": 54971}
|
package com.ozan.cleanpokedex.ui.detail.recycler.stats
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.ozan.cleanpokedex.R
import com.ozan.cleanpokedex.databinding.ItemPokemonStatBinding
import com.ozan.cleanpokedex.extension.inflateBinding
import com.ozan.cleanpokedex.ui.uimodel.pokemon.PokemonStatUiModel
class PokemonStatsRecyclerAdapter : RecyclerView.Adapter<PokemonStatsViewHolder>() {
private var statList = listOf<PokemonStatUiModel>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PokemonStatsViewHolder {
val binding= parent.inflateBinding<ItemPokemonStatBinding>(R.layout.item_pokemon_stat)
return PokemonStatsViewHolder(binding)
}
override fun onBindViewHolder(holder: PokemonStatsViewHolder, position: Int) {
holder.bind(statList[position])
}
override fun getItemCount()= statList.size
fun show(newList: List<PokemonStatUiModel>) {
statList= newList
notifyDataSetChanged()
}
}
| 0
| null |
0
| 0
|
fc7bab2501e2b9a836db21bed3d241cd71f35ce2
| 1,033
|
CleanPokedex
|
Apache License 2.0
|
app/src/main/kotlin/me/xizzhu/android/joshua/infra/arch/ViewPresenter.kt
|
andriiginting
| 288,359,910
| true
|
{"Kotlin": 1000193}
|
/*
* Copyright (C) 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.xizzhu.android.joshua.infra.arch
import androidx.annotation.CallSuper
import androidx.annotation.UiThread
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.CoroutineScope
interface ViewHolder
abstract class ViewPresenter<VH : ViewHolder, VM : ViewModel, A : AppCompatActivity>(
protected val viewModel: VM, protected val activity: A, protected val coroutineScope: CoroutineScope
) : LifecycleObserver {
protected val tag: String = javaClass.simpleName
protected lateinit var viewHolder: VH
@UiThread
fun bind(viewHolder: VH) {
this.viewHolder = viewHolder
onBind()
activity.lifecycle.addObserver(this)
}
@UiThread
@CallSuper
open fun onBind() {
}
}
| 0
| null |
0
| 1
|
2372855404bc56da08adff1f5b03f2f2026d50c3
| 1,434
|
Joshua
|
Apache License 2.0
|
member/src/main/kotlin/com/brainbackdoor/members/domain/Member.kt
|
brainbackdoor
| 671,999,287
| false
|
{"Kotlin": 158130, "Shell": 253}
|
package com.brainbackdoor.members.domain
import com.brainbackdoor.domain.RandomId
import jakarta.persistence.CascadeType
import jakarta.persistence.Column
import jakarta.persistence.Embeddable
import jakarta.persistence.Embedded
import jakarta.persistence.Entity
import jakarta.persistence.FetchType
import jakarta.persistence.ForeignKey
import jakarta.persistence.JoinColumn
import jakarta.persistence.JoinTable
import jakarta.persistence.ManyToMany
@Entity
class Member(
@Embedded
var email: Email,
@Embedded
var password: Password?,
var consentByMember: Boolean = false,
var consentByPrivacy: Boolean = false,
@ManyToMany(fetch = FetchType.EAGER, cascade = [CascadeType.MERGE])
@JoinTable(
name = "member_roles",
joinColumns = [
JoinColumn(
name = "member_id", referencedColumnName = "id",
foreignKey = ForeignKey(name = "fk_member_roles_to_member")
)
],
inverseJoinColumns = [
JoinColumn(
name = "role_id", referencedColumnName = "id",
foreignKey = ForeignKey(name = "fk_member_roles_to_role")
)
]
)
val roles: MutableList<Role>
) : RandomId<Member>() {
constructor(
email: String,
password: String,
consentByMember: Boolean,
consentByPrivacy: Boolean,
role: Role
) : this(
email(email),
Password(password),
consentByMember,
consentByPrivacy,
mutableListOf(role)
)
init {
password
?.isMatched(this.email.address)
?.let {
check(it) { throw IllegalArgumentException("이용자 ID를 이용한 패스워드는 사용할 수 없습니다.") }
}
}
fun checkPassword(password: String) {
this.password?.check(password)
}
fun email(): String = email.address
fun maskedEmail(): String = email.masking()
@Embeddable
class Email(
@Column(unique = true, length = 100)
val address: String
) {
init {
if (!checkMailFormat(this.address)) {
throw IllegalArgumentException("이메일 형식이 유효하지 않습니다")
}
}
fun masking(): String = address.replace(EMAIL_MASKING_REGEX) {
it.groupValues[1] +
"*".repeat(it.groupValues[2].length) +
it.groupValues[3] +
"*".repeat(it.groupValues[4].length)
}
private fun checkMailFormat(address: String): Boolean = EMAIL_REGEX.matches(address)
companion object {
private val EMAIL_REGEX = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,6}\$".toRegex()
private val EMAIL_MASKING_REGEX = """^([^@]{2})([^@]+)([^@]{0}@)([^@]{4})""".toRegex()
}
}
}
fun email(address: String): Member.Email = Member.Email(address)
| 0
|
Kotlin
|
4
| 3
|
6e66d19d6e2e8fce7b1eb51d86e51a4634aaa35b
| 2,879
|
infra-workshop
|
MIT License
|
app/src/main/java/com/kanyideveloper/muviz/favorites/presentation/FavoritesViewModel.kt
|
joelkanyi
| 458,180,234
| false
|
{"Kotlin": 259972}
|
/*
* Copyright 2024 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kanyideveloper.muviz.favorites.presentation
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kanyideveloper.muviz.favorites.data.data.local.Favorite
import com.kanyideveloper.muviz.favorites.domain.repository.FavoritesRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class FavoritesViewModel @Inject constructor(private val repository: FavoritesRepository) :
ViewModel() {
val favorites = repository.getFavorites()
fun insertFavorite(favorite: Favorite) {
viewModelScope.launch {
repository.insertFavorite(favorite)
}
}
fun isAFavorite(mediaId: Int): LiveData<Boolean>{
return repository.isFavorite(mediaId)
}
fun deleteOneFavorite(favorite: Favorite) {
viewModelScope.launch {
repository.deleteOneFavorite(favorite)
}
}
fun deleteAllFavorites() {
viewModelScope.launch {
repository.deleteAllFavorites()
}
}
}
| 4
|
Kotlin
|
24
| 88
|
8f496c15795a14d9e4c5b3fd593d15ee5ae5fd41
| 1,715
|
Muviz
|
Apache License 2.0
|
app/src/main/java/com/ainshams/graduation_booking_halls/navigation/graphs/wellcomeNavGraph.kt
|
Tonistark92
| 700,629,104
| false
|
{"Kotlin": 354268}
|
package com.ainshams.graduation_booking_halls.navigation.graphs
import androidx.fragment.app.FragmentActivity
import androidx.navigation.*
import androidx.navigation.compose.composable
import com.ainshams.graduation_booking_halls.navigation.HallsScreans
import com.ainshams.graduation_booking_halls.presentation.screens.core.requests.RequestsScreen
import com.ainshams.graduation_booking_halls.presentation.screens.wellcom.SignUp.SignUpScreen
import com.ainshams.graduation_booking_halls.presentation.screens.wellcom.SplashScreen
import com.ainshams.graduation_booking_halls.presentation.screens.wellcom.login.LogInScreen
import com.ainshams.graduation_booking_halls.presentation.screens.wellcom.onscreens.OnScreen1
import com.ainshams.graduation_booking_halls.presentation.screens.wellcom.onscreens.OnScreen2
import com.ainshams.graduation_booking_halls.presentation.screens.wellcom.onscreens.OnScreen3
fun NavGraphBuilder.OnBoardingNavGraph(navController: NavHostController,activity: FragmentActivity) {
navigation(
route = Graph.ONBOARDING,
startDestination = WelcomeScreens.Splash.route,
) {
composable(
route = WelcomeScreens.Splash.route,
) {
SplashScreen(navController)
}
composable(
route = WelcomeScreens.LogIn.route,
)
{
LogInScreen(navController,activity)
}
composable(
route = WelcomeScreens.SignUp.route,
)
{
SignUpScreen(navController)
}
composable(
route = WelcomeScreens.OnBoarding1.route,)
{
OnScreen1(navController)
}
composable(
route = WelcomeScreens.OnBoarding2.route,)
{
OnScreen2(navController)
}
composable(
route = WelcomeScreens.OnBoarding3.route,)
{
OnScreen3(navController)
}
}
}
sealed class WelcomeScreens(val route: String) {
object OnBoarding1 : WelcomeScreens(route = "ONBOARDING1")
object OnBoarding2 : WelcomeScreens(route = "ONBOARDING2")
object OnBoarding3 : WelcomeScreens(route = "ONBOARDING3")
object Splash : WelcomeScreens(route = "SPLASH")
object LogIn : WelcomeScreens(route = "LOGIN")
object SignUp : WelcomeScreens(route = "SIGNUP")
}
| 0
|
Kotlin
|
0
| 0
|
e7e08886afa9d8936727ad75e2a966a6feeb4030
| 2,369
|
Booking-Halls
|
MIT License
|
app/src/main/java/com/zigis/paleontologas/quiz/usecases/QuizGenerateQuestionsUseCase.kt
|
edgar-zigis
| 240,962,785
| false
| null |
package com.zigis.paleontologas.quiz.usecases
import com.zigis.paleontologas.quiz.data.entities.Question
import com.zigis.paleontologas.quiz.repositories.QuestionRepository
class QuizGenerateQuestionsUseCase(
private val questionRepository: QuestionRepository
) {
suspend fun generateRandomQuestions(questionCount: Int): List<Question> {
val questions = questionRepository.findAll().shuffled()
return processQuestions(questions.take(questionCount))
}
private fun processQuestions(questions: List<Question>): List<Question> {
questions.forEach {
it.variantList.addAll(
listOf(
it.periodName + "_variant_" + it.questionIndex + "_1",
it.periodName + "_variant_" + it.questionIndex + "_2",
it.periodName + "_variant_" + it.questionIndex + "_3",
it.periodName + "_variant_" + it.questionIndex + "_4"
)
)
it.variantList.shuffle()
}
return questions
}
}
| 0
|
Kotlin
|
16
| 126
|
4ee09d3c6f29278aa1762e71f7db6a84d0ca3dea
| 1,057
|
Paleontologas
|
Apache License 2.0
|
core/src/test/kotlin/main/operation/Reset_test.kt
|
elect86
| 364,643,104
| false
| null |
package main.operation
import main.*
import main.Gik.ResetMode
import main.Status.Changes
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertFailsWith
class Reset_test : SimpleGit() {
val commits = ArrayList<Commit>()
@BeforeTest
override fun setup() {
super.setup()
repoFile("1.bat") += "1"
repoFile("something/2.txt") += "2"
repoFile("test/3.bat") += "3"
repoFile("test/4.txt") += "4"
repoFile("test/other/5.txt") += "5"
gik.add(patterns = setOf("."))
commits += gik.commit(message = "Test")
repoFile("1.bat") += "2"
repoFile("test/3.bat") += "4"
gik.add(patterns = setOf("."))
commits += gik.commit(message = "Test")
repoFile("1.bat") += "3"
repoFile("something/2.txt") += "2"
gik.add(patterns = setOf("."))
repoFile("test/other/5.txt") += "6"
repoFile("test/4.txt") += "5"
}
@Test
fun `reset soft changes HEAD only`() {
gik.reset(mode = ResetMode.soft, commit = commits[0].id)
assert(commits[0] == gik.head)
assert(gik.status() == Status(staged = Changes(modified = setOf("1.bat", "test/3.bat", "something/2.txt")),
unstaged = Changes(modified = setOf("test/4.txt", "test/other/5.txt"))))
}
@Test
fun `reset mixed changes HEAD and index`() {
gik.reset(mode = ResetMode.mixed, commit = commits[0].id)
assert(commits[0] == gik.head)
assert(gik.status() == Status(unstaged = Changes(modified = setOf("1.bat", "test/3.bat", "test/4.txt", "something/2.txt", "test/other/5.txt"))))
}
@Test
fun `reset hard changes HEAD, index, and working tree`() {
gik.reset(mode = ResetMode.hard, commit = commits[0].id)
assert(commits[0] == gik.head)
assert(gik.status().isClean)
}
@Test
fun `reset with paths changes index only`() {
gik.reset(paths = setOf("something/2.txt"))
assert(commits[1] == gik.head)
assert(gik.status() == Status(staged = Changes(modified = setOf("1.bat")),
unstaged = Changes(modified = setOf("test/4.txt", "something/2.txt", "test/other/5.txt"))))
}
@Test
fun `reset with paths and mode set not supported`() {
assertFailsWith<IllegalStateException> {
gik.reset(mode = ResetMode.hard, paths = setOf("."))
}
}
}
| 1
|
Kotlin
|
1
| 2
|
f5f28edfee6a2683ce5da5ea8fdc4e1ba32a3f33
| 2,470
|
gik
|
Apache License 2.0
|
src/main/kotlin/be/arby/taffy/lang/tuples/T3.kt
|
adjabaev
| 839,569,114
| false
|
{"Kotlin": 638630, "HTML": 558738, "JavaScript": 9416, "CSS": 2507, "Shell": 866}
|
package be.arby.taffy.lang.tuples
data class T3<out A, out B, out C>(
val first: A,
val second: B,
val third: C
) {
override fun toString(): String = "($first, $second, $third)"
}
| 0
|
Kotlin
|
0
| 0
|
464b84e9bc323a43d349dc2b72c72319df359a87
| 197
|
TaffyKT
|
MIT License
|
app/src/main/java/com/nelc/cakesizer/welcomeactivity/SettingsScreen.kt
|
chakflying
| 636,123,689
| false
|
{"Kotlin": 166391, "Shell": 350, "PowerShell": 283}
|
package com.nelc.cakesizer.welcomeactivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.os.LocaleListCompat
import com.nelc.cakesizer.R
import com.nelc.cakesizer.data.SettingsStore
import com.nelc.cakesizer.ui.theme.CakeSizerTheme
import kotlinx.coroutines.launch
@Composable
fun SettingsScreen(
modifier: Modifier = Modifier,
onClose: () -> Unit = {},
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val settingsStore = SettingsStore(context)
val language = settingsStore.languageFlow.collectAsState(initial = "")
val quality = settingsStore.qualityFlow.collectAsState(initial = 0)
Surface(
modifier = modifier
.fillMaxSize()
.padding(vertical = 12.dp),
color = MaterialTheme.colorScheme.background,
shape = RoundedCornerShape(12.dp),
shadowElevation = 4.dp,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 12.dp, horizontal = 24.dp),
) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 12.dp),
) {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 12.dp),
text = stringResource(R.string.settings),
style = MaterialTheme.typography.titleLarge,
textAlign = TextAlign.Center
)
IconButton(
modifier = Modifier.align(Alignment.CenterEnd),
onClick = {
onClose()
}
) {
Icon(
Icons.Rounded.Close,
contentDescription = "Close Settings",
tint = MaterialTheme.colorScheme.onSurface,
)
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
modifier = Modifier.padding(vertical = 6.dp),
text = stringResource(R.string.language),
style = MaterialTheme.typography.bodyLarge,
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(
modifier = Modifier
.clickable {
scope.launch {
settingsStore.setLanguage("zh")
}
}
.padding(24.dp),
text = "繁",
color = if (language.value == "zh") {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurface
},
style = MaterialTheme.typography.bodyLarge,
)
Text(
modifier = Modifier
.clickable {
scope.launch {
settingsStore.setLanguage("en")
}
}
.padding(24.dp),
text = "Eng",
color = if (language.value == "en") {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurface
},
style = MaterialTheme.typography.bodyLarge,
)
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
modifier = Modifier.padding(vertical = 6.dp),
text = stringResource(R.string.quality),
style = MaterialTheme.typography.bodyLarge,
)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(
modifier = Modifier
.clickable {
scope.launch {
settingsStore.setQuality(0)
}
}
.padding(24.dp),
color = if (quality.value == 0) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurface
},
text = stringResource(R.string.high),
style = MaterialTheme.typography.bodyLarge,
)
Text(
modifier = Modifier
.clickable {
scope.launch {
settingsStore.setQuality(1)
}
}
.padding(24.dp),
color = if (quality.value == 1) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurface
},
text = stringResource(R.string.medium),
style = MaterialTheme.typography.bodyLarge,
)
}
}
}
}
}
fun setAppLanguage(language: String) {
val enLocale: LocaleListCompat = LocaleListCompat.forLanguageTags("en")
val zhLocale: LocaleListCompat = LocaleListCompat.forLanguageTags("zh-HK")
// Call this on the main thread as it may require Activity.restart()
if (language == "zh") {
AppCompatDelegate.setApplicationLocales(zhLocale)
}
if (language == "en") {
AppCompatDelegate.setApplicationLocales(enLocale)
}
}
@Preview(showBackground = true)
@Composable
fun SettingsScreenPreview() {
CakeSizerTheme {
SettingsScreen()
}
}
| 0
|
Kotlin
|
0
| 0
|
5d5f17a2beef3670d4e212207d724fd1564753c7
| 8,187
|
cakesizer
|
MIT License
|
app/src/main/java/com/layfones/composewanandroid/data/services/model/CollectArticleInfo.kt
|
layfones
| 623,881,761
| false
| null |
package com.layfones.composewanandroid.data.services.model
/**
* 收藏文章信息
*/
data class CollectArticleInfo(
val count: Int = 0
)
| 0
|
Kotlin
|
1
| 3
|
6944e510e0e41f7d5c105a8e308adee417478ac4
| 133
|
Jetpack-Compose-Practice
|
Apache License 2.0
|
app/src/main/java/xyz/teamgravity/runningtracker/fragment/fragment/StatisticsFragment.kt
|
raheemadamboev
| 326,260,049
| false
| null |
package xyz.teamgravity.runningtracker.fragment.fragment
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.viewModels
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import dagger.hilt.android.AndroidEntryPoint
import xyz.teamgravity.runningtracker.R
import xyz.teamgravity.runningtracker.databinding.FragmentStatisticsBinding
import xyz.teamgravity.runningtracker.fragment.dialog.RunDialog
import xyz.teamgravity.runningtracker.helper.util.Helper
import xyz.teamgravity.runningtracker.viewmodel.StatisticsViewModel
import kotlin.math.round
@AndroidEntryPoint
class StatisticsFragment : Fragment() {
private var _binding: FragmentStatisticsBinding? = null
private val binding get() = _binding!!
private val statisticsViewModel: StatisticsViewModel by viewModels()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentStatisticsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
activity?.let {
updateUI(it)
}
}
private fun updateUI(activity: FragmentActivity) {
updateTotalDistance()
updateTotalDuration()
updateAverageSpeed()
updateCaloriesBurned()
updateBarChart(activity)
}
private fun updateTotalDuration() {
statisticsViewModel.getTotalDuration().observe(viewLifecycleOwner) {
it?.let { totalRun ->
binding.totalTimeT.text = Helper.formatStopwatch(totalRun)
}
}
}
private fun updateTotalDistance() {
statisticsViewModel.getTotalDistanceInMeters().observe(viewLifecycleOwner) {
it?.let { totalDistance ->
binding.totalDistanceT.text =
Helper.addTwoString((round((totalDistance / 1000F) * 10F) / 10F).toString(), resources.getString(R.string.km))
}
}
}
private fun updateAverageSpeed() {
statisticsViewModel.getTotalAverageSpeed().observe(viewLifecycleOwner) {
it?.let { averageSpeed ->
binding.averageSpeedT.text =
Helper.addTwoString((round(averageSpeed * 10F) / 10F).toString(), resources.getString(R.string.km_hour))
}
}
}
private fun updateCaloriesBurned() {
statisticsViewModel.getTotalCaloriesBurned().observe(viewLifecycleOwner) {
it?.let { totalCalories ->
binding.totalCaloriesT.text = Helper.addTwoString(totalCalories.toString(), resources.getString(R.string.kcal))
}
}
}
private fun updateBarChart(activity: FragmentActivity) {
binding.apply {
barChart.xAxis.apply {
position = XAxis.XAxisPosition.BOTTOM
setDrawLabels(false)
axisLineColor = Color.WHITE
textColor = Color.WHITE
setDrawGridLines(false)
}
barChart.axisLeft.apply {
axisLineColor = Color.WHITE
textColor = Color.WHITE
setDrawGridLines(false)
}
barChart.axisRight.apply {
axisLineColor = Color.WHITE
textColor = Color.WHITE
setDrawGridLines(false)
}
barChart.apply {
description.text = resources.getString(R.string.average_speed_over_time)
legend.isEnabled = false
}
statisticsViewModel.getAllRunsSortedByDate().observe(viewLifecycleOwner) {
val allAverageSpeed = it.indices.map { i -> BarEntry(i.toFloat(), it[i].averageSpeedInKmh) }
val barDataSet = BarDataSet(allAverageSpeed, resources.getString(R.string.average_speed_over_time)).apply {
valueTextColor = Color.WHITE
color = ContextCompat.getColor(activity, R.color.yellow)
}
barChart.data = BarData(barDataSet)
barChart.marker = RunDialog(it.reversed(), resources, activity, R.layout.dialog_run)
barChart.invalidate()
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 0
|
8a069bbfdf0d4b987b4c7f74b5d89c159bab5a3e
| 4,793
|
running-tracker-app
|
Apache License 2.0
|
api/type/type-builders/src/main/kotlin/org/rsmod/api/type/builders/loc/LocBuilder.kt
|
rsmod
| 293,875,986
| false
|
{"Kotlin": 1695754}
|
package org.rsmod.api.type.builders.loc
import org.rsmod.api.type.builders.HashTypeBuilder
import org.rsmod.game.type.loc.LocTypeBuilder
import org.rsmod.game.type.loc.UnpackedLocType
public abstract class LocBuilder : HashTypeBuilder<LocTypeBuilder, UnpackedLocType>() {
override fun build(internal: String, init: LocTypeBuilder.() -> Unit) {
val type = LocTypeBuilder(internal).apply(init).build(id = -1)
cache += type
}
}
| 0
|
Kotlin
|
64
| 92
|
8821a9cddc54314c03c873d4fdaaef760a3a2ada
| 451
|
rsmod
|
ISC License
|
bot/src/main/java/com/dongtronic/diabot/exceptions/NoSuchEpisodeException.kt
|
discord-diabetes
| 151,116,011
| false
|
{"Kotlin": 408572, "Dockerfile": 527, "Procfile": 67}
|
package com.dongtronic.diabot.exceptions
class NoSuchEpisodeException : Exception()
| 18
|
Kotlin
|
14
| 19
|
8be95fd823503913f612978442c06ca8653afb5a
| 85
|
diabot
|
MIT License
|
AlsatIPGCore/src/main/java/com/alsatpardakht/alsatipgcore/data/remote/dto/VERIFYDto.kt
|
AlsatPardakht
| 460,316,372
| false
| null |
package com.alsatpardakht.alsatipgcore.data.remote.dto
import com.alsatpardakht.alsatipgcore.data.Mapper
import com.alsatpardakht.alsatipgcore.domain.model.VERIFY
import kotlinx.serialization.Serializable
@Serializable
data class VERIFYDto(
val HashedCardNumber: String?,
val IsSuccess: Boolean?,
val MaskedCardNumber: String?,
val Message: String?,
val ShaparakRefNumber: String?
) : Mapper<VERIFY> {
override fun toDomainModel(): VERIFY {
return VERIFY(
HashedCardNumber = HashedCardNumber!!,
IsSuccess = IsSuccess!!,
MaskedCardNumber = MaskedCardNumber!!,
Message = Message!!,
ShaparakRefNumber = ShaparakRefNumber!!
)
}
}
| 0
|
Kotlin
|
0
| 4
|
52f8ad23d4f8675a7e7179d212a6a7e22272ddee
| 732
|
AlsatIPGCore
|
MIT License
|
app/src/main/java/com/xeniac/chillclub/feature_settings/domain/use_cases/SettingsUseCases.kt
|
WilliamGates99
| 840,710,908
| false
|
{"Kotlin": 380219}
|
package com.xeniac.chillclub.feature_settings.domain.use_cases
import dagger.Lazy
data class SettingsUseCases(
val getCurrentAppThemeUseCase: Lazy<GetCurrentAppThemeUseCase>,
val getIsPlayInBackgroundEnabledUseCase: Lazy<GetIsPlayInBackgroundEnabledUseCase>,
val storeCurrentAppThemeUseCase: Lazy<StoreCurrentAppThemeUseCase>,
val storeIsPlayInBackgroundEnabledUseCase: Lazy<StoreIsPlayInBackgroundEnabledUseCase>
)
| 0
|
Kotlin
|
0
| 2
|
4740cc0fca1dc7445c0a28793aefc35fbbf780e6
| 433
|
ChillClub
|
Apache License 2.0
|
app/src/main/java/com/connectycube/messenger/api/UserService.kt
|
ConnectyCube
| 198,286,170
| false
| null |
package com.connectycube.messenger.api
import android.content.Context
import com.connectycube.chat.ConnectycubeChatService
import com.connectycube.core.exception.ResponseException
import com.connectycube.messenger.data.AppDatabase
import com.connectycube.users.ConnectycubeUsers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
class UserService private constructor() {
private object Holder {
val INSTANCE = UserService()
}
companion object {
val instance: UserService by lazy { Holder.INSTANCE }
}
suspend fun ultimateLogout(applicationContext: Context) {
ConnectycubeChatService.getInstance().destroy()
clearDatabaseAsync(applicationContext).await()
signOut()
}
private fun clearDatabaseAsync(applicationContext: Context) = GlobalScope.async(Dispatchers.IO) {
AppDatabase.getInstance(applicationContext).clearTablesForLogout()
}
suspend fun signOut() {
try {
signOutAsync().await()
} catch (ex: ResponseException) {
// suppress exception
}
}
private fun signOutAsync() = GlobalScope.async(Dispatchers.IO) {
ConnectycubeUsers.signOut().perform()
}
}
| 8
| null |
22
| 50
|
a0e4f3be09f39ff43fc66c94bcbfe0b9f2e3cf4f
| 1,269
|
android-messenger-app
|
Apache License 2.0
|
app/src/main/java/com/example/jetpack_compose_all_in_one/features/download_manager/DownloadReceiver.kt
|
myofficework000
| 626,474,700
| false
|
{"Kotlin": 1392414}
|
package com.example.jetpack_compose_all_in_one.features.download_manager
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.activity.ComponentActivity
import androidx.work.WorkManager
import java.util.UUID
class DownloadReceiver: BroadcastReceiver() {
override fun onReceive(p0: Context, p1: Intent) {
when (p1.action) {
// Warning: Pause and resume isn't working for now.
DOWNLOAD_PAUSE -> {
DownloadWorker.downloadState.status = DownloadStatus.PAUSED
pauseOrResumeDownload(p0, true)
}
DOWNLOAD_RESUME -> {
DownloadWorker.downloadState.status = DownloadStatus.STARTED
pauseOrResumeDownload(p0, false)
}
DOWNLOAD_CANCEL -> {
val downloadWorkerId = p1.getStringExtra(download_worker_id_arg)
val downloadManagerId = p1.getLongExtra(download_manager_id_arg, -1)
WorkManager.getInstance(p0).cancelWorkById(UUID.fromString(downloadWorkerId))
if (downloadManagerId >= 0) {
(p0.getSystemService(ComponentActivity.DOWNLOAD_SERVICE) as DownloadManager)
.remove(downloadManagerId)
}
}
}
}
// Note that for simplicity, this pauses ALL downloads currently running.
private fun pauseOrResumeDownload(context: Context, isPausing: Boolean) {
try {
context.contentResolver.update(
Uri.parse("content://downloads/all_downloads"),
ContentValues().apply {
put("control", if (isPausing) 1 else 0) },
"title=?",
arrayOf(DownloadWorker.downloadState.fileName)
)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
}
companion object {
const val DOWNLOAD_PAUSE = "ACTION_DOWNLOAD_PAUSE"
const val DOWNLOAD_RESUME = "ACTION_DOWNLOAD_RESUME"
const val DOWNLOAD_CANCEL = "ACTION_DOWNLOAD_CANCEL"
const val download_worker_id_arg = "download_worker"
const val download_manager_id_arg = "download_manager"
}
}
| 21
|
Kotlin
|
22
| 222
|
4de5418608d6917b5c97fac7d868454c424daa26
| 2,358
|
Jetpack-Compose-All-in-one-Guide
|
MIT License
|
panna-shared/src/main/kotlin/com/mgtriffid/games/panna/shared/game/effects/MovementEffect.kt
|
mgtriffid
| 524,701,185
| false
|
{"Kotlin": 478306, "Java": 9323}
|
package com.mgtriffid.games.panna.shared.game.effects
import com.mgtriffid.games.cotta.core.effects.CottaEffect
import com.mgtriffid.games.cotta.core.entities.id.EntityId
interface MovementEffect : CottaEffect {
val velocityX: Float
val velocityY: Float
val entityId: EntityId // should be careful when transferring this over the wire
}
| 2
|
Kotlin
|
0
| 6
|
ee0bd897c67451b31f68a3a31a6ee8de756b2b52
| 351
|
cotta
|
MIT License
|
app/src/main/kotlin/Reversi/ReversiState.kt
|
aqtech-ca
| 311,016,146
| false
|
{"Kotlin": 88461, "TeX": 4464, "Shell": 96}
|
package Reversi
class ReversiState : Cloneable {
val squares: Array<Array<ReversiSquare>>
val size: Int
var currentPlayer: ReversiSquare
constructor(size: Int) {
squares = Array(size) {
Array(size) {
ReversiSquare.EMPTY
}
}
squares[size/2 - 1][size/2 - 1] = ReversiSquare.LIGHT
squares[size/2][size/2] = ReversiSquare.LIGHT
squares[size/2 - 1][size/2] = ReversiSquare.DARK
squares[size/2][size/2 - 1] = ReversiSquare.DARK
this.size = size
currentPlayer = ReversiSquare.DARK
}
constructor(otherState: ReversiState) {
squares = Array(otherState.size) { emptyArray() }
for (row in otherState.squares.indices) {
squares[row] = otherState.squares[row].copyOf()
}
size = otherState.size
currentPlayer = otherState.currentPlayer
}
public override fun clone(): ReversiState {
return ReversiState(this)
}
public override fun equals(other: Any?): Boolean {
if (this === other) {
return true;
}
if (!(other is ReversiState))
{
return false
}
if (this.currentPlayer != other.currentPlayer) {
return false
}
if (this.size != other.size) {
return false
}
for (row in squares.indices) {
for (col in squares[row].indices) {
val square = squares[row][col]
if (square == ReversiSquare.DARK || square == ReversiSquare.LIGHT) {
if (other.squares[row][col] != square) {
return false
}
}
}
}
return true
}
}
| 8
|
Kotlin
|
1
| 6
|
a9a533f9004a96c09bdef3e67c9c7c7dcb62655d
| 1,787
|
mctreesearch4j
|
MIT License
|
app/src/main/java/com/example/groxcounter/MainActivity.kt
|
kshirsagarps
| 139,342,598
| false
|
{"Kotlin": 6376}
|
package com.example.groxcounter
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
launchSimpleActivity.setOnClickListener {
startActivity(Intent(this, SimpleActivity::class.java))
}
launchPersistActivity.setOnClickListener {
startActivity(Intent(this, PersistActivity::class.java))
}
}
}
| 1
|
Kotlin
|
0
| 0
|
a4c36e833e85c50ce24ca1a3bf133e40061cac58
| 650
|
GroxCounterApp
|
Apache License 2.0
|
types/src/test/kotlin/org/kethereum/contract/abi/types/ThePaddingFun.kt
|
komputing
| 92,780,266
| false
|
{"Kotlin": 776856}
|
package org.kethereum.contract.abi.types
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import kotlin.test.assertFailsWith
class ThePaddingFun {
@Test
fun paddingWorks() {
assertThat(byteArrayOf(2).leftPadToFixedSize(3)).isEqualTo(byteArrayOf(0, 0, 2))
}
@Test
fun noChangeWhenNotNeeded() {
assertThat(byteArrayOf(4, 2).leftPadToFixedSize(2)).isEqualTo(byteArrayOf(4, 2))
}
@Test
fun emptyWorks() {
assertThat(ByteArray(0)).isEqualTo(byteArrayOf())
}
@Test
fun failsOnTooLargeInput() {
assertFailsWith(java.lang.IllegalArgumentException::class) {
byteArrayOf(2, 3).leftPadToFixedSize(1)
}
}
}
| 43
|
Kotlin
|
82
| 333
|
1f42cede2d31cb5d3c488bd74eeb8480ec47c919
| 739
|
KEthereum
|
MIT License
|
app/src/main/java/io/github/satoshun/example/AppActivity.kt
|
satoshun-android-example
| 539,307,380
| false
| null |
package io.github.satoshun.example
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import io.github.satoshun.example.share.Share
import javax.inject.Inject
class AppActivity : AppCompatActivity() {
@Inject lateinit var viewModel: AppViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ComponentHolder.component<AppComponent>().inject(this)
println(Share)
println(viewModel)
setContent {
AppTheme {
AppContent()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a072d10961034239013c4822603a7e7cd28bed9c
| 588
|
napt-sample
|
Apache License 2.0
|
app/src/main/java/com/rickinc/decibels/presentation/ui/components/RationaleDialog.kt
|
Rick-AB
| 540,820,468
| false
|
{"Kotlin": 126933}
|
package com.rickinc.decibels.presentation.ui.components
import androidx.annotation.StringRes
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.rickinc.decibels.R
import com.rickinc.decibels.presentation.ui.theme.Typography
@Composable
fun RationaleDialog(
@StringRes messageRes: Int,
isPermanentlyDenied: Boolean,
dismissDialog: () -> Unit,
actionPositiveButtonClick: () -> Unit
) {
Dialog(
onDismissRequest = dismissDialog,
properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)
) {
Card(
modifier = Modifier
.width(300.dp)
.clip(RoundedCornerShape(4.dp))
) {
Column(modifier = Modifier.padding(vertical = 16.dp, horizontal = 12.dp)) {
Text(
text = stringResource(messageRes),
style = Typography.bodyMedium,
color = Color.Black
)
Spacer(modifier = Modifier.height(16.dp))
Row(modifier = Modifier.align(Alignment.End)) {
if (isPermanentlyDenied) {
Text(
text = stringResource(id = R.string.cancel),
style = Typography.bodyMedium,
modifier = Modifier
.clickable { dismissDialog() }
.padding(4.dp)
)
}
val textRes = if (isPermanentlyDenied) R.string.go_to_settings else R.string.ok
val onClick =
if (isPermanentlyDenied) actionPositiveButtonClick else dismissDialog
Spacer(modifier = Modifier.width(16.dp))
Text(
text = stringResource(id = textRes),
style = Typography.bodyMedium,
modifier = Modifier
.clickable { onClick() }
.padding(4.dp)
)
}
}
}
}
}
@Preview
@Composable
fun RationalePrev() {
RationaleDialog(
messageRes = R.string.storage_permission_denied_message,
isPermanentlyDenied = false,
dismissDialog = { /*TODO*/ }) {
}
}
| 0
|
Kotlin
|
0
| 0
|
33b9a8fc4f68af2dddf829d07e664f82edd10655
| 2,974
|
Decibels
|
Apache License 2.0
|
src/main/java/org/module/structure/CommandListenerAdapter.kt
|
krabiworld
| 449,676,433
| false
|
{"Kotlin": 85903}
|
package org.module.structure
interface CommandListenerAdapter {
fun onCommand() {}
}
| 0
|
Kotlin
|
0
| 3
|
0e558e7858521f801d347ffa64df38758f9b5a60
| 90
|
Module
|
MIT License
|
src/main/kotlin/com/tradeshift/blayze/dto/Update.kt
|
Tradeshift
| 132,719,809
| false
|
{"Kotlin": 91470}
|
package com.tradeshift.blayze.dto
import com.tradeshift.blayze.Protos
/**
* Outcome and [Inputs], e.g. (in json)
*
* {
* "outcome": "spam",
* "inputs": {
* "text": {
* "subject": "Attention, is it true?",
* "body": "Good day dear beneficiary. This is Secretary to president of Benin republic is writing this email ..."
* },
* "categorical": {
* "sender": "WWW.@galaxy.ocn.ne.jp",
* "mailed-by": "galaxy.ocn.ne.jp",
* "reply-to": "njokua35@gmail.com"
* },
* "gaussian": {
* "n_words": 482
* }
* }
* }
*/
data class Update(
val inputs: Inputs,
val outcome: Outcome
) {
fun toProto(): Protos.Update {
return Protos.Update.newBuilder()
.setInputs(inputs.toProto())
.setOutcome(outcome)
.build()
}
companion object {
fun fromProto(proto: Protos.Update): Update {
return Update(Inputs.fromProto(proto.inputs), proto.outcome)
}
}
}
| 4
|
Kotlin
|
11
| 20
|
7d53dbef7a39af44f753417e80af7305a4f675ae
| 1,181
|
blayze
|
MIT License
|
room/room-compiler/src/test/test-data/common/input/GuavaRoom.kt
|
androidx
| 256,589,781
| false
|
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
|
/*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("GuavaRoom")
@file:Suppress("UNUSED_PARAMETER")
package androidx.room.guava
import android.os.CancellationSignal
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.sqlite.SQLiteConnection
import androidx.sqlite.db.SupportSQLiteQuery
import com.google.common.util.concurrent.ListenableFuture
import java.util.concurrent.Callable
import java.util.concurrent.Executor
class GuavaRoomArtifactMarker private constructor()
fun <T> createListenableFuture(
db: RoomDatabase,
isReadOnly: Boolean,
inTransaction: Boolean,
block: (SQLiteConnection) -> T
): ListenableFuture<T> {
TODO()
}
fun <T> createListenableFuture(
roomDatabase: RoomDatabase,
inTransaction: Boolean,
callable: Callable<T>,
query: RoomSQLiteQuery,
releaseQuery: Boolean
): ListenableFuture<T> {
TODO()
}
fun <T> createListenableFuture(
roomDatabase: RoomDatabase,
inTransaction: Boolean,
callable: Callable<T>,
query: RoomSQLiteQuery,
releaseQuery: Boolean,
cancellationSignal: CancellationSignal?
): ListenableFuture<T> {
TODO()
}
fun <T> createListenableFuture(
roomDatabase: RoomDatabase,
inTransaction: Boolean,
callable: Callable<T>,
query: SupportSQLiteQuery,
releaseQuery: Boolean,
cancellationSignal: CancellationSignal?
): ListenableFuture<T> {
TODO()
}
fun <T> createListenableFuture(
executor: Executor,
callable: Callable<T>,
query: SupportSQLiteQuery,
releaseQuery: Boolean,
cancellationSignal: CancellationSignal?
): ListenableFuture<T> {
TODO()
}
fun <T> createListenableFuture(
roomDatabase: RoomDatabase,
inTransaction: Boolean,
callable: Callable<T>
): ListenableFuture<T> {
TODO()
}
| 29
|
Kotlin
|
1011
| 5,321
|
98b929d303f34d569e9fd8a529f022d398d1024b
| 2,393
|
androidx
|
Apache License 2.0
|
LogisticManager/src/main/kotlin/engine/Warehouse.kt
|
ostis-apps
| 209,274,423
| false
|
{"C++": 190974, "Python": 158695, "JavaScript": 121504, "Kotlin": 28151, "CSS": 16444, "CMake": 15212, "Shell": 13239, "HTML": 5019, "Dockerfile": 1567}
|
package engine
data class Warehouse(
val name: String,
val connectedShops: MutableMap<Shop, Int>,
val connectedFactories: MutableMap<Factory, Int>,
val connectedWarehouse: MutableMap<Warehouse, Int>
){
override fun toString(): String {
return "Warehouse(name='$name.', connectedShops=$connectedShops, connectedFactories=$connectedFactories, connectedWarehouse=${connectedWarehouse.size})"
}
}
| 46
|
C++
|
128
| 2
|
dade10e5ffdb02a7cd7dab3ebeb83496ac43d5ae
| 425
|
ostis-geography
|
MIT License
|
src/me/anno/rubikscube/api/Side.kt
|
AntonioNoack
| 777,290,171
| false
|
{"Kotlin": 28143}
|
package me.anno.rubikscube.api
enum class Side(val colorSeenFromFront: Color) {
LEFT(Color.ORANGE),
RIGHT(Color.RED),
FRONT(Color.GREEN),
BACK(Color.BLUE),
UP(Color.WHITE),
DOWN(Color.YELLOW)
}
| 0
|
Kotlin
|
0
| 0
|
6188297619ee8b2c84cc5b9acd5e121cc16167c3
| 218
|
RubiksCubeUI
|
Apache License 2.0
|
karballo-common/src/main/kotlin/karballo/Square.kt
|
albertoruibal
| 87,008,703
| false
| null |
package karballo
object Square {
val ALL: Long = -1
val WHITES: Long = -6172840429334713771
val BLACKS: Long = 6172840429334713770
val H1 = 1L
val G1 = H1 shl 1
val F1 = H1 shl 2
val E1 = H1 shl 3
val D1 = H1 shl 4
val C1 = H1 shl 5
val B1 = H1 shl 6
val A1 = H1 shl 7
val H2 = H1 shl 8
val G2 = H1 shl 9
val F2 = H1 shl 10
val E2 = H1 shl 11
val D2 = H1 shl 12
val C2 = H1 shl 13
val B2 = H1 shl 14
val A2 = H1 shl 15
val H3 = H1 shl 16
val G3 = H1 shl 17
val F3 = H1 shl 18
val E3 = H1 shl 19
val D3 = H1 shl 20
val C3 = H1 shl 21
val B3 = H1 shl 22
val A3 = H1 shl 23
val H4 = H1 shl 24
val G4 = H1 shl 25
val F4 = H1 shl 26
val E4 = H1 shl 27
val D4 = H1 shl 28
val C4 = H1 shl 29
val B4 = H1 shl 30
val A4 = H1 shl 31
val H5 = H1 shl 32
val G5 = H1 shl 33
val F5 = H1 shl 34
val E5 = H1 shl 35
val D5 = H1 shl 36
val C5 = H1 shl 37
val B5 = H1 shl 38
val A5 = H1 shl 39
val H6 = H1 shl 40
val G6 = H1 shl 41
val F6 = H1 shl 42
val E6 = H1 shl 43
val D6 = H1 shl 44
val C6 = H1 shl 45
val B6 = H1 shl 46
val A6 = H1 shl 47
val H7 = H1 shl 48
val G7 = H1 shl 49
val F7 = H1 shl 50
val E7 = H1 shl 51
val D7 = H1 shl 52
val C7 = H1 shl 53
val B7 = H1 shl 54
val A7 = H1 shl 55
val H8 = H1 shl 56
val G8 = H1 shl 57
val F8 = H1 shl 58
val E8 = H1 shl 59
val D8 = H1 shl 60
val C8 = H1 shl 61
val B8 = H1 shl 62
val A8 = H1 shl 63
}
| 0
|
Kotlin
|
2
| 12
|
a709a7eefa3ad966a775821e80b1e566b77b9491
| 1,610
|
karballo
|
MIT License
|
app/src/main/java/com/lostincontext/users/UsersActivity.kt
|
LostInContext
| 65,417,953
| false
| null |
package com.lostincontext.users
import android.os.Bundle
import com.lostincontext.R
import com.lostincontext.commons.BaseActivity
import com.lostincontext.utils.addFragmentToActivity
class UsersActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.users_screen)
val fm = supportFragmentManager
var fragment: UsersFragment? = fm.findFragmentById(R.id.contentFrame) as UsersFragment?
if (fragment == null) {
fragment = UsersFragment.newInstance()
addFragmentToActivity(fm, fragment, R.id.contentFrame)
}
}
}
| 1
|
Kotlin
|
5
| 46
|
0a2650852fb8bc56cb71c158fc1724f69cdbb640
| 682
|
LostContext-App
|
Beerware License
|
app/src/main/java/com/haton/walletwise/presentation/screen/auth/view/firstentry/FirstEntryView.kt
|
KotlinType
| 802,754,938
| false
|
{"Kotlin": 120404}
|
package com.haton.walletwise.presentation.screen.auth.view.firstentry
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.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.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.haton.walletwise.R
import com.haton.walletwise.presentation.screen.auth.view.firstentry.model.FirstEntryEvent
import com.haton.walletwise.presentation.screen.auth.view.firstentry.model.FirstEntryState
import com.haton.walletwise.presentation.ui.theme.WiseCommon
@Composable
fun FirstEntryView(
firstEntryViewModel: FirstEntryViewModel,
onSignIn: () -> Unit,
onSignUp: () -> Unit,
) {
val state = firstEntryViewModel.state.collectAsState()
val context = LocalContext.current
val wrapHorizontal = WiseCommon.dimens.wrap
LaunchedEffect(state.value) {
when (state.value) {
FirstEntryState.Default -> {}
FirstEntryState.SignIn -> {
onSignIn()
}
FirstEntryState.SignUp -> {
onSignUp()
}
}
}
Surface(
modifier = Modifier
.fillMaxSize()
.background(WiseCommon.colors.background)
) {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.background(WiseCommon.colors.background)
) {
item {
Box(
modifier = Modifier
.fillMaxWidth()
.height((LocalConfiguration.current.screenHeightDp * 0.5).dp)
.paint(
painter = painterResource(id = R.drawable.auth_background),
contentScale = ContentScale.FillBounds
),
contentAlignment = Alignment.TopCenter
) {
Image(
modifier = Modifier
.fillMaxSize()
.padding(WiseCommon.dimens.firstEntryLogoPaddingValue),
painter = painterResource(id = R.drawable.authorization_logo),
contentScale = ContentScale.FillHeight,
contentDescription = null
)
}
}
item {
Column(
modifier = Modifier
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
modifier = Modifier.padding(top = 6.dp),
text = context.getString(R.string.authorization__greeting),
style = WiseCommon.typography.appTitle
)
Button(
modifier = Modifier
.padding(
top = WiseCommon.dimens.buttonPaddingTop,
start = wrapHorizontal,
end = wrapHorizontal
)
.fillMaxWidth(),
contentPadding = PaddingValues(
vertical = WiseCommon.dimens.buttonPaddingVertical
),
colors = ButtonDefaults.buttonColors(
containerColor = WiseCommon.colors.primary,
contentColor = WiseCommon.colors.blackText
),
shape = WiseCommon.shape.big,
onClick = {
firstEntryViewModel.send(FirstEntryEvent.EnterSignUp)
}
) {
Text(
text = context.getString(R.string.authorization__sign_up),
style = WiseCommon.typography.buttonText
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = context.getString(R.string.authorization__question),
style = WiseCommon.typography.fadedText
)
TextButton(onClick = {
firstEntryViewModel.send(FirstEntryEvent.EnterSignIn)
}) {
Text(
text = context.getString(R.string.authorization__sign_in),
style = WiseCommon.typography.underlinedText
)
}
}
Spacer(modifier = Modifier.weight(1f))
}
}
}
/*Column(
modifier = Modifier
.fillMaxSize()
) {
Box(
modifier = Modifier
.fillMaxWidth()
.weight(3f)
.paint(
painter = painterResource(id = R.drawable.auth_background),
contentScale = ContentScale.FillBounds
),
contentAlignment = Alignment.TopCenter
) {
Image(
modifier = Modifier
.fillMaxSize()
.padding(
start = wrapHorizontal,
end = wrapHorizontal,
top = 50.dp,
bottom = 60.dp
),
painter = painterResource(id = R.drawable.authorization_logo),
contentScale = ContentScale.FillHeight,
contentDescription = null
)
}
Column(
modifier = Modifier
.fillMaxWidth()
.weight(2f),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
modifier = Modifier.padding(top = 6.dp),
text = context.getString(R.string.authorization__greeting),
style = WiseCommon.typography.appTitle
)
Button(
modifier = Modifier
.padding(
top = WiseCommon.dimens.buttonPaddingTop,
start = wrapHorizontal,
end = wrapHorizontal
)
.fillMaxWidth(),
contentPadding = PaddingValues(
vertical = WiseCommon.dimens.buttonPaddingVertical
),
colors = ButtonDefaults.buttonColors(
containerColor = WiseCommon.colors.primary,
contentColor = WiseCommon.colors.blackText
),
shape = WiseCommon.shape.big,
onClick = {
firstEntryViewModel.send(FirstEntryEvent.EnterSignUp)
}
) {
Text(
text = context.getString(R.string.authorization__sign_up),
style = WiseCommon.typography.buttonText
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = context.getString(R.string.authorization__question),
style = WiseCommon.typography.fadedText
)
TextButton(onClick = {
firstEntryViewModel.send(FirstEntryEvent.EnterSignIn)
}) {
Text(
text = context.getString(R.string.authorization__sign_in),
style = WiseCommon.typography.underlinedText
)
}
}
Spacer(modifier = Modifier.weight(1f))
}
}*/
}
}
| 0
|
Kotlin
|
0
| 0
|
7c80997b132a423c0bee59d3c0ec70af9e870838
| 10,142
|
WalletWise-Front
|
MIT License
|
plugins/analysis/common/src/main/kotlin/arrow/meta/plugins/analysis/phases/analysis/solver/ast/context/elements/WhenConditionWithExpression.kt
|
arrow-kt
| 217,378,939
| false
| null |
package arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.elements
interface WhenConditionWithExpression : WhenCondition {
val expression: Expression?
}
| 97
|
Kotlin
|
40
| 316
|
8d2a80cf3a1275a752c18baceed74cb61aa13b4d
| 169
|
arrow-meta
|
Apache License 2.0
|
plugins/idea-plugin/src/main/kotlin/dev/ahmedmourad/nocopy/idea/inspections/fixes/ConvertToDataClassFix.kt
|
AhmedMourad0
| 242,375,329
| false
|
{"Kotlin": 24100}
|
package dev.ahmedmourad.nocopy.idea.inspections.fixes
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
class ConvertToDataClassFix : LocalQuickFix {
override fun getName() = "Convert to data class"
override fun getFamilyName() = "Convert to data class"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val containingClass = descriptor.startElement.getParentOfType<KtClass>(strict = false) ?: return
if (!FileModificationService.getInstance().preparePsiElementForWrite(containingClass)) {
return
}
containingClass.addModifier(KtTokens.DATA_KEYWORD)
}
}
| 1
|
Kotlin
|
4
| 150
|
e62c2564f114c0dcff9b09760601f651b21d6762
| 936
|
no-copy
|
Apache License 2.0
|
app/src/main/java/com/kotlin/architecture/utils/StatusCode.kt
|
KaranMavadhiya
| 270,289,104
| false
| null |
package com.kotlin.architecture.utils
object StatusCode {
const val STATUS_CODE_INTERNET_VALIDATION = 100
const val STATUS_CODE_NAME_VALIDATION = 101
const val STATUS_CODE_EMAIL_VALIDATION = 102
const val STATUS_CODE_PASSWORD_VALIDATION = 103
const val STATUS_CODE_SUCCESS = 200
const val STATUS_CODE_SERVER_ERROR = 500
const val SERVER_ERROR_MESSAGE = "Sorry! Something is wrong, Please try again."
const val SUCCESS = 1
const val FAILURE = 0
}
| 0
|
Kotlin
|
1
| 2
|
022d88d54f0d0217f5bbd64e2dadbc53b16671ec
| 487
|
Kotlin-Architecture
|
Apache License 2.0
|
plugins/net/src/main/kotlin/org/rsmod/plugins/net/login/downstream/BadSessionIdCodec.kt
|
rsmod
| 293,875,986
| false
| null |
package org.rsmod.plugins.net.login.downstream
import org.rsmod.protocol.packet.ZeroLengthPacketCodec
import javax.inject.Singleton
@Singleton
class BadSessionIdCodec : ZeroLengthPacketCodec<LoginResponse.BadSessionId>(
packet = LoginResponse.BadSessionId,
opcode = 10
)
| 0
|
Kotlin
|
49
| 55
|
5293efb07c833715f9bd9df4cad6ff9aa68143da
| 281
|
rsmod
|
ISC License
|
zzsong-device-edge/src/main/kotlin/com/zzsong/device/edge/infrastructure/repository/EdgeSentCommandRepositoryImpl.kt
|
Songzhizong
| 465,969,434
| false
| null |
package com.zzsong.device.edge.infrastructure.repository
import com.zzsong.device.edge.domain.model.command.EdgeSentCommandDo
import com.zzsong.device.edge.domain.model.command.EdgeSentCommandRepository
import kotlinx.coroutines.reactor.awaitSingle
import kotlinx.coroutines.reactor.awaitSingleOrNull
import org.springframework.data.mongodb.core.ReactiveMongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.stereotype.Repository
/**
* @author 宋志宗 on 2022/4/7
*/
@Repository
class EdgeSentCommandRepositoryImpl(
private val template: ReactiveMongoTemplate,
) : EdgeSentCommandRepository {
override suspend fun insert(command: EdgeSentCommandDo): EdgeSentCommandDo {
return template.insert(command).awaitSingle()
}
override suspend fun findAndRemoveByOpCommandId(opCommandId: String): EdgeSentCommandDo? {
val query = Query.query(Criteria.where("opCommandId").`is`(opCommandId))
return template.findAndRemove(query, EdgeSentCommandDo::class.java).awaitSingleOrNull()
}
}
| 0
|
Kotlin
|
0
| 0
|
06f8f2664499e92576b0bc329083ec15bebfdad9
| 1,102
|
zzsong-device
|
MIT License
|
core/src/commonMain/kotlin/Dsl.kt
|
kowasm
| 586,987,800
| false
|
{"Kotlin": 620989, "JavaScript": 545, "Shell": 263}
|
/*
* Copyright 2023 the original author or authors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.kowasm.core
/**
* A marker annotation for KoWasm DSLs.
*/
@DslMarker
annotation class Dsl
| 10
|
Kotlin
|
5
| 315
|
a45430d559057f5a3e10ee88d26eba07103bf69d
| 266
|
kowasm
|
Apache License 2.0
|
app/src/main/java/dev/pankaj/cleanarchitecture/di/FactoryModule.kt
|
pankaj046
| 806,227,972
| false
|
{"Kotlin": 79661}
|
package dev.pankaj.cleanarchitecture.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dev.pankaj.cleanarchitecture.App
import dev.pankaj.cleanarchitecture.domain.usecase.AuthUseCase
import dev.pankaj.cleanarchitecture.domain.usecase.ProductUseCase
import dev.pankaj.cleanarchitecture.domain.usecase.UserUseCase
import dev.pankaj.cleanarchitecture.presentation.auth.viewmodel.AuthViewModelFactory
import dev.pankaj.cleanarchitecture.presentation.home.viewmodel.ProductViewModelFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class FactoryModule {
@Singleton
@Provides
fun provideSignInViewModelFactory(
app: App,
userUseCase: UserUseCase,
authUseCase: AuthUseCase,
): AuthViewModelFactory {
return AuthViewModelFactory(
app,
userUseCase,
authUseCase
)
}
@Singleton
@Provides
fun provideProductViewModelFactory(
app: App,
productUseCase: ProductUseCase,
): ProductViewModelFactory {
return ProductViewModelFactory(
app,
productUseCase
)
}
}
| 0
|
Kotlin
|
0
| 0
|
050fa0aae45e4500c9fc85a04c6b7ee5b6439d71
| 1,234
|
Clean-Architecture
|
The Unlicense
|
krefty-core/src/commonTest/kotlin/dev/ustits/krefty/predicate/collections/EmptyTest.kt
|
ustitc
| 410,678,793
| false
|
{"Kotlin": 49157}
|
package dev.ustits.krefty.predicate.collections
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.kotest.property.Arb
import io.kotest.property.arbitrary.list
import io.kotest.property.arbitrary.string
import io.kotest.property.forAll
class EmptyTest : StringSpec({
"returns true if list is empty" {
val predicate = Empty<List<String>>()
predicate.isRefined(emptyList()) shouldBe true
}
"returns false if list is not empty" {
forAll(Arb.list(Arb.string(), 1..100)) {
val predicate = Empty<List<String>>()
!predicate.isRefined(it)
}
}
})
| 0
|
Kotlin
|
1
| 8
|
a0c6301bcf28154b59afcd14f32563ba40dd2993
| 653
|
krefty
|
MIT License
|
app/src/main/java/com/androidstarter/ui/settings/ISettings.kt
|
syedtehrimabbas
| 526,100,544
| false
| null |
package com.androidstarter.ui.settings
import com.androidstarter.base.interfaces.IBase
interface ISettings {
interface State : IBase.State {
}
interface ViewModel : IBase.ViewModel<State> {
}
}
| 0
|
Kotlin
|
0
| 0
|
b89ab5c66b9e750915481295a30034889d590480
| 212
|
dida-procop-android
|
MIT License
|
day03/src/test/kotlin/Tests.kt
|
rstockbridge
| 225,212,001
| false
| null |
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class Tests {
@Test
fun closestDistance1() {
val wire1 = parseInput("R8,U5,L5,D3")
val wire2 = parseInput("U7,R6,D4,L4")
val output = calculateDistanceToClosestIntersectionPoint(wire1, wire2)
Assertions.assertEquals(output, 6)
}
@Test
fun closestDistance2() {
val wire1 = parseInput("R75,D30,R83,U83,L12,D49,R71,U7,L72")
val wire2 = parseInput("U62,R66,U55,R34,D71,R55,D58,R83")
val output = calculateDistanceToClosestIntersectionPoint(wire1, wire2)
Assertions.assertEquals(output, 159)
}
@Test
fun closestDistance3() {
val wire1 = parseInput("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51")
val wire2 = parseInput("U98,R91,D20,R16,D67,R40,U7,R15,U6,R7")
val output = calculateDistanceToClosestIntersectionPoint(wire1, wire2)
Assertions.assertEquals(output, 135)
}
@Test
fun minTotalSteps1() {
val wire1 = parseInput("R8,U5,L5,D3")
val wire2 = parseInput("U7,R6,D4,L4")
val output = calculateMinTotalNumberOfSteps(wire1, wire2)
Assertions.assertEquals(output, 30)
}
@Test
fun minTotalSteps2() {
val wire1 = parseInput("R75,D30,R83,U83,L12,D49,R71,U7,L72")
val wire2 = parseInput("U62,R66,U55,R34,D71,R55,D58,R83")
val output = calculateMinTotalNumberOfSteps(wire1, wire2)
Assertions.assertEquals(output, 610)
}
@Test
fun minTotalSteps3() {
val wire1 = parseInput("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51")
val wire2 = parseInput("U98,R91,D20,R16,D67,R40,U7,R15,U6,R7")
val output = calculateMinTotalNumberOfSteps(wire1, wire2)
Assertions.assertEquals(output, 410)
}
}
| 0
|
Kotlin
|
0
| 0
|
bcd6daf81787ed9a1d90afaa9646b1c513505d75
| 1,821
|
AdventOfCode2019
|
MIT License
|
app/src/main/java/com/sothsez/sqliteconnect/MainActivity.kt
|
Senzlter
| 274,884,772
| false
| null |
package com.sothsez.sqliteconnect
import android.content.ContentValues
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.BaseColumns
import android.text.Editable
import android.util.Log
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.sothsez.sqliteconnect.databinding.ActivityMainBinding
import com.sothsez.sqliteconnect.model.TitleAdapter
import com.sothsez.sqliteconnect.model.TitleData
import com.sothsez.sqliteconnect.model.db.FeedEntry
import com.sothsez.sqliteconnect.model.db.FeedReaderDbHelper
class MainActivity : AppCompatActivity(), TitleAdapter.TitleInterface {
private lateinit var binding: ActivityMainBinding
private lateinit var dbHelper: FeedReaderDbHelper
private lateinit var datasList: ArrayList<TitleData>
private var idSelect: Long = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setContentView(R.layout.activity_main)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
dbHelper = FeedReaderDbHelper(this)
readDatabase()
binding.recyclerName.apply {
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = TitleAdapter(datasList, this@MainActivity)
}
binding.btnCreate.setOnClickListener {
insertItem()
readDatabase()
updateRecyclerView()
}
binding.btnUpdate.setOnClickListener {
updateItem()
readDatabase()
updateRecyclerView()
}
binding.btnSearch.setOnClickListener {
searchDatabase()
updateRecyclerView()
}
binding.btnDelete.setOnClickListener {
deleteItem()
readDatabase()
updateRecyclerView()
}
}
private fun insertItem() {
if (!binding.etTitle.text.equals("")) {
val db = dbHelper.writableDatabase
val values = ContentValues().apply {
put(FeedEntry.COLUMN_NAME_TITLE, binding.etTitle.text.toString())
put(FeedEntry.COLUMN_NAME_SUBTITLE, binding.etSubtitle.text.toString())
}
val newRowId = db?.insert(FeedEntry.TABLE_NAME, null, values)
db.close()
updateRecyclerView()
Toast.makeText(this, "Insert data complete.", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Input data should fill in title.", Toast.LENGTH_SHORT).show()
binding.etTitle.requestFocus()
}
}
private fun readDatabase() {
val db = dbHelper.readableDatabase
val sortOrder = "${FeedEntry.COLUMN_NAME_TITLE} ASC"
val cursor = db.query(
FeedEntry.TABLE_NAME, // The table to query
null, // The array of columns to return (pass null to get all)
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
)
datasList = ArrayList<TitleData>()
with(cursor) {
while (moveToNext()) {
val item = TitleData(
getLong(getColumnIndexOrThrow(BaseColumns._ID)),
getString(getColumnIndex("title")),
getString(getColumnIndex("subtitle"))
)
datasList.add(item)
}
}
cursor.close()
db.close()
}
private fun searchDatabase() {
if (!binding.etTitle.text.equals("")) {
val db = dbHelper.readableDatabase
val selector = "${FeedEntry.COLUMN_NAME_TITLE} = \"" + binding.etTitle.text.toString() + "\""
Log.d("TAGG", "searchDatabase: "+"${FeedEntry.COLUMN_NAME_TITLE} = \"" + binding.etTitle.text.toString() + "\"")
val cursor = db.query(
FeedEntry.TABLE_NAME, // The table to query
null, // The array of columns to return (pass null to get all)
selector, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
)
datasList = ArrayList<TitleData>()
with(cursor) {
while (moveToNext()) {
val item = TitleData(
getLong(getColumnIndexOrThrow(BaseColumns._ID)),
getString(getColumnIndex("title")),
getString(getColumnIndex("subtitle"))
)
datasList.add(item)
Log.d("TAGG", "searchDatabase: "+ item.id + " : " + item.title)
}
}
cursor.close()
db.close()
}
}
private fun updateItem() {
if (!binding.etTitle.text.equals("")) {
val db = dbHelper.writableDatabase
val values = ContentValues().apply {
put(FeedEntry.COLUMN_NAME_TITLE, binding.etTitle.text.toString())
put(FeedEntry.COLUMN_NAME_SUBTITLE, binding.etSubtitle.text.toString())
}
val selection = "${BaseColumns._ID} = \'" + idSelect + "\'"
val count = db.update(
FeedEntry.TABLE_NAME,
values,
selection,
null
)
Toast.makeText(this, "Update data complete.", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Input data should fill in title. ", Toast.LENGTH_SHORT).show()
binding.etTitle.requestFocus()
}
}
private fun deleteItem() {
if (!idSelect.equals(-1)) {
val db = dbHelper.writableDatabase
val selection = "${BaseColumns._ID} = \'" + idSelect + "\'"
val deletedRows = db.delete(FeedEntry.TABLE_NAME, selection, null)
db.close()
updateRecyclerView()
idSelect = -1
Toast.makeText(this, "Delete data complete.", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Please select item.", Toast.LENGTH_SHORT).show()
binding.etTitle.requestFocus()
}
}
private fun updateRecyclerView() {
val recyclerViewTop =
(binding.recyclerName.layoutManager as LinearLayoutManager)?.findFirstVisibleItemPosition()
binding.recyclerName.adapter = TitleAdapter(datasList, this)
binding.recyclerName.scrollToPosition(recyclerViewTop)
}
override fun onSelectTitleItem(title: String, subtitle: String, id: Long) {
idSelect = id
binding.etTitle.text = title.toEditable()
binding.etSubtitle.text = subtitle.toEditable()
Toast.makeText(this, "Select at item : "+idSelect, Toast.LENGTH_SHORT).show()
}
fun String.toEditable(): Editable = Editable.Factory.getInstance().newEditable(this)
}
| 0
|
Kotlin
|
0
| 0
|
4f971f0ab6dc9affed0888cd8c28511953289181
| 7,437
|
SQLiteConnect
|
Apache License 2.0
|
rentalproperty-mp-common/src/commonMain/kotlin/ru/otus/otuskotlin/vd/rentalproperty/kmp/common/validation/validators/ValidatorHasInList.kt
|
otuskotlin
| 327,227,710
| false
| null |
package ru.otus.otuskotlin.vd.rentalproperty.kmp.common.validation.validators
import ru.otus.otuskotlin.vd.rentalproperty.kmp.common.validation.IValidator
import ru.otus.otuskotlin.vd.rentalproperty.kmp.common.validation.ValidationFieldError
import ru.otus.otuskotlin.vd.rentalproperty.kmp.common.validation.ValidationResult
class ValidatorHasInList(
private val field: String = "",
private val message: String = "List does not contain target value",
private val values: List<String> = emptyList(),
) : IValidator<List<String>> {
override fun validate(sample: List<String>): ValidationResult =
if (sample.containsAll(values)) {
ValidationResult.SUCCESS
} else {
ValidationResult(
errors = listOf(
ValidationFieldError(
field = field,
message = message,
)
)
)
}
}
| 1
|
Kotlin
|
1
| 0
|
d921e9c8ce4b071efa9ae7bc251f663660b8f5f6
| 864
|
otuskotlin-202012-rentalproperty-vd
|
MIT License
|
subprojects/gradle/instrumentation-tests/src/main/kotlin/com/avito/instrumentation/suite/dex/TestInApk.kt
|
matzuk
| 344,157,673
| true
|
{"Kotlin": 2509850, "Shell": 16022, "Python": 14063, "Dockerfile": 7151, "Makefile": 2131}
|
package com.avito.android
import com.avito.report.model.TestName
/**
* Тест это обязательно метод, запуск на классе хоть и поддерживается из IDE или фильтром по классу,
* по факту обозначает запуск всех методов в классе
*
* @param annotations при совпадении аннотаций на классе и методе будет выброшен exception
*/
data class TestInApk(
val testName: TestName,
val annotations: List<AnnotationData>
) {
companion object
}
| 0
| null |
1
| 0
|
96463f7714c0550e331d2a37fb32ad98fac9d62d
| 441
|
avito-android
|
MIT License
|
OfficialSite/Coroutine/ContextAndDispatchers/ChildrenCoroutine.kt
|
kazenetu
| 238,936,555
| false
| null |
import kotlinx.coroutines.*
/*
* コルーチン:ディスパッチャーとスレッド:兄弟コルーチンのキャンセル
*/
fun main() = runBlocking {
// 「GlobalScopeとrunBlockingに属するスレッドの兄弟コルーチン」のキャンセル時の動作の違い
println("---Children of a coroutine---")
val request = launch {
GlobalScope.launch {
// GlobalScopeのためキャンセル対象外
println("job1: I run in GlobalScope and execute independently!")
delay(1000)
println("job1: I am not affected by cancellation of the request")
}
// 親(runBlocking)に属するスレッドのためキャンセル対象
launch {
println("job2: I am a child of the request coroutine")
delay(1000)
println("job2: I will not execute this line if my parent request is cancelled")
}
}
// 500ミリ秒まってジョブをキャンセル
delay(500)
request.cancel()
println("main: run request.cancel()")
// GlobalScopeコルーチンの実行待ち
delay(1000)
println("main: Who has survived request cancellation?")
}
// 出力:
// ---Children of a coroutine---
// job1: I run in GlobalScope and execute independently!
// job2: I am a child of the request coroutine
// main: run request.cancel()
// job1: I am not affected by cancellation of the request
// main: Who has survived request cancellation?
| 0
|
Kotlin
|
0
| 0
|
77df823ed3131e45d6aadd325a4726e106c6ef60
| 1,246
|
kotlin-practice
|
MIT License
|
app/src/main/java/com/example/todoperfect/logic/dao/TaskDao.kt
|
Spark-RTG
| 530,464,724
| false
| null |
package com.example.todoperfect.logic.dao
import androidx.room.*
import com.example.todoperfect.TodoPerfectApplication
import com.example.todoperfect.logic.model.Task
import java.sql.Timestamp
import java.util.*
@Dao
interface TaskDao {
@Insert
fun insertTask(task: Task): Long
@Update
fun updateTask(newTask: Task)
@Query("select * from Task where user = :user order by due")
fun loadAllTasks(user: String): List<Task>
@Query("select * from Task where (user = :user and due < :due and stared = 0) order by due")
fun loadTasksEarlierThan(user: String, due: Timestamp): List<Task>
@Query("select * from Task where (user = :user and due < :end and due >= :start and stared == 0) order by due")
fun loadTasksBetween(user: String, start: Timestamp, end: Timestamp): List<Task>
@Query("select * from Task where (user = :user and due >= :start and stared == 0) order by due")
fun loadTasksAfter(user: String, start: Timestamp): List<Task>
@Query("select * from Task where (user = :user and importance > :importance and stared == 0) order by due")
fun loadTaskHigherImportance(user: String, importance: Int): List<Task>
@Query("select * from Task where (user = :user and stared == 1) order by due")
fun loadStaredTasks(user: String): List<Task>
@Delete
fun deleteTask(task: Task)
@Query("delete from Task where user = :user")
fun deleteAllTasks(user: String)
}
| 0
|
Kotlin
|
0
| 0
|
29df23623699b40af791ebe5f5dcec3f0312cf39
| 1,446
|
CS8803-First-Assignment
|
Apache License 2.0
|
app/src/main/java/ludugz/pomodoro/ui/theme/IbmPlexSansTypography.kt
|
ludugz
| 644,216,137
| false
|
{"Kotlin": 54378}
|
package ludugz.pomodoro.ui.theme
/**
* Created by <NAME>, on 28 August, 2024
* Email: <EMAIL>
*/
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import ludugz.pomodoro.R
private val ibmPlexSans = FontFamily(
Font(R.font.ibm_plex_sans_light, FontWeight.Light),
Font(R.font.ibm_plex_sans_medium, FontWeight.Normal),
Font(R.font.ibm_plex_sans_italic, FontWeight.Normal, FontStyle.Italic),
Font(R.font.ibm_plex_sans_medium, FontWeight.Medium),
Font(R.font.ibm_plex_sans_bold, FontWeight.Bold)
)
// Set of Material typography styles to start with
val IbmPlexSansTypography = Typography(
// Title
titleLarge = TextStyle(
fontFamily = ibmPlexSans,
fontWeight = FontWeight.Normal,
fontSize = 32.sp,
lineHeight = 40.sp,
letterSpacing = 1.5.sp
),
titleMedium = TextStyle(
fontFamily = ibmPlexSans,
fontWeight = FontWeight.Normal,
fontSize = 28.sp,
lineHeight = 36.sp,
letterSpacing = 1.sp
),
titleSmall = TextStyle(
fontFamily = ibmPlexSans,
fontWeight = FontWeight.Normal,
fontSize = 24.sp,
lineHeight = 32.sp,
letterSpacing = 0.5.sp
),
// Label
labelLarge = TextStyle(
fontFamily = ibmPlexSans,
fontWeight = FontWeight.Normal,
fontSize = 20.sp,
lineHeight = 28.sp,
letterSpacing = 0.5.sp
),
labelMedium = TextStyle(
fontFamily = ibmPlexSans,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
),
labelSmall = TextStyle(
fontFamily = ibmPlexSans,
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
),
// Body
bodyLarge = TextStyle(
fontFamily = ibmPlexSans,
fontWeight = FontWeight.Normal,
fontSize = 18.sp,
lineHeight = 28.sp,
letterSpacing = 0.5.sp
),
bodyMedium = TextStyle(
fontFamily = ibmPlexSans,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
lineHeight = 22.sp,
letterSpacing = 0.25.sp
),
bodySmall = TextStyle(
fontFamily = ibmPlexSans,
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
lineHeight = 14.sp,
letterSpacing = 0.1.sp
),
)
| 0
|
Kotlin
|
0
| 0
|
caf369f3be96a53755cece064fb699ff9da653ad
| 2,655
|
pomodoro
|
MIT License
|
undertow/src/test/kotlin/org/springframework/samples/petclinic/rest/webmvc/jdbc/UndertowWebMvcJdbcPetTypeControllerTest.kt
|
kotoant
| 612,221,740
| false
|
{"Kotlin": 230920, "JavaScript": 102019, "Mustache": 10054, "PLpgSQL": 2929, "Shell": 1403, "Dockerfile": 709}
|
package org.springframework.samples.petclinic.rest.webmvc.jdbc
class UndertowWebMvcJdbcPetTypeControllerTest : WebMvcJdbcPetTypeControllerTest()
| 0
|
Kotlin
|
0
| 2
|
365b0ce4d9eaacee8c888511915c404f414cbd8c
| 146
|
spring-petclinic-rest
|
Apache License 2.0
|
app/src/main/java/cn/cqautotest/sunnybeach/paging/source/RichPagingSource.kt
|
anjiemo
| 378,095,612
| false
|
{"Kotlin": 1615160, "Java": 17208, "HTML": 2257, "JavaScript": 1720}
|
package cn.cqautotest.sunnybeach.paging.source
import androidx.paging.PagingSource
import androidx.paging.PagingState
import cn.cqautotest.sunnybeach.execption.ServiceException
import cn.cqautotest.sunnybeach.http.network.UserNetwork
import cn.cqautotest.sunnybeach.model.RichList
import cn.cqautotest.sunnybeach.util.CacheHelper
import cn.cqautotest.sunnybeach.util.CacheKey
import timber.log.Timber
import java.util.concurrent.TimeUnit
/**
* author : <NAME>
* github : https://github.com/anjiemo/SunnyBeach
* time : 2021/11/01
* desc : 富豪榜 PagingSource
*/
class RichPagingSource : PagingSource<Int, RichList.RichUserItem>() {
override fun getRefreshKey(state: PagingState<Int, RichList.RichUserItem>): Int? = null
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, RichList.RichUserItem> {
return try {
val page = params.key ?: FIRST_PAGE_INDEX
Timber.d("load:===> page is $page")
takeUnless { CacheHelper.checkExpired(cacheKey, TimeUnit.HOURS.toMillis(1)) }?.let {
val dataFromCache = CacheHelper.getFromCache<List<RichList.RichUserItem>>(cacheKey).orEmpty()
if (dataFromCache.isNotEmpty()) {
return LoadResult.Page(dataFromCache, null, null)
}
}
val response = UserNetwork.getRichList()
val responseData = response.getData()
if (response.isSuccess()) {
LoadResult.Page<Int, RichList.RichUserItem>(responseData, null, null).also {
CacheHelper.saveToCache(cacheKey, responseData)
}
} else LoadResult.Error(ServiceException())
} catch (t: Throwable) {
t.printStackTrace()
LoadResult.Error(t)
}
}
companion object {
private const val FIRST_PAGE_INDEX = 1
private const val cacheKey = CacheKey.CACHE_RICH_LIST
}
}
| 0
|
Kotlin
|
25
| 148
|
5d9b1a38bd594bced70cd4f5b7963815a9dfe005
| 1,944
|
SunnyBeach
|
Apache License 2.0
|
src/test/kotlin/com/gentooway/blog/web/WebControllerTest.kt
|
acmilanfan
| 167,793,213
| false
| null |
package com.gentooway.blog.web
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.web.servlet.MockMvc
import org.springframework.transaction.annotation.Transactional
@Transactional
@SpringBootTest
@AutoConfigureMockMvc
abstract class WebControllerTest {
@Autowired
lateinit var mvc: MockMvc
@Autowired
lateinit var objectMapper: ObjectMapper
}
| 0
|
Kotlin
|
0
| 0
|
2b059d8e8c67d98fdf50e03ce3d85de9dbadee21
| 602
|
blog-backend-kotlin
|
MIT License
|
app/src/main/java/com/kanedasoftware/masterscrobbler/main/MainActivity.kt
|
cardoso-thiago
| 272,305,777
| false
| null |
package com.kanedasoftware.masterscrobbler.main
import android.app.WallpaperManager
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.preference.PreferenceManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import butterknife.BindView
import butterknife.ButterKnife
import com.google.android.material.snackbar.Snackbar
import com.jaredrummler.cyanea.Cyanea
import com.jaredrummler.cyanea.app.CyaneaAppCompatActivity
import com.jaredrummler.cyanea.prefs.CyaneaThemePickerActivity
import com.kanedasoftware.masterscrobbler.R
import com.kanedasoftware.masterscrobbler.adapters.GridViewTopAdapter
import com.kanedasoftware.masterscrobbler.adapters.ListViewTrackAdapter
import com.kanedasoftware.masterscrobbler.beans.Recent
import com.kanedasoftware.masterscrobbler.beans.TopInfo
import com.kanedasoftware.masterscrobbler.services.LastFmService
import com.kanedasoftware.masterscrobbler.utils.Constants
import com.kanedasoftware.masterscrobbler.utils.ImageUtils
import com.kanedasoftware.masterscrobbler.utils.NotificationUtils
import com.kanedasoftware.masterscrobbler.utils.Utils
import com.mikepenz.aboutlibraries.Libs
import com.mikepenz.aboutlibraries.LibsBuilder
import com.mikepenz.aboutlibraries.util.Colors
import de.adorsys.android.securestoragelibrary.SecurePreferences
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.defaultSharedPreferences
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import org.koin.android.ext.android.inject
import java.util.*
import kotlin.collections.ArrayList
class MainActivity : CyaneaAppCompatActivity() {
//Koin
private val utils: Utils by inject()
private val imageUtils: ImageUtils by inject()
private val notificationUtils: NotificationUtils by inject()
private val lastFmService: LastFmService by inject()
//ButterKnife
@BindView(R.id.profile)
lateinit var profile: ImageView
@BindView(R.id.username)
lateinit var username: TextView
@BindView(R.id.info)
lateinit var info: TextView
@BindView(R.id.list_tracks)
lateinit var listTracks: ListView
@BindView(R.id.grid_view)
lateinit var gridView: GridView
@BindView(R.id.top_artists_albuns)
lateinit var artistsAlbumsSpinner: Spinner
@BindView(R.id.period)
lateinit var periodSpinner: Spinner
@BindView(R.id.text_recent_tracks)
lateinit var recentTracks: TextView
@BindView(R.id.swipe_container)
lateinit var swipeRefreshLayout: SwipeRefreshLayout
@BindView(android.R.id.content)
lateinit var parentLayout: View
private var lastArtistsAlbumsSpinner = ""
private var lastPeriodSpinner = ""
private var topArtists: String = ""
private var topAlbums: String = ""
private lateinit var valuesArtistsAlbums: List<String>
private var sevenDays: String = ""
private var oneMonth: String = ""
private var threeMonths: String = ""
private var sixMonths: String = ""
private var oneYear: String = ""
private var overall: String = ""
private lateinit var valuesPeriods: List<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
ButterKnife.bind(this)
setSupportActionBar(toolbar)
//Obtém os resources
topArtists = getString(R.string.top_artists)
topAlbums = getString(R.string.top_albums)
valuesArtistsAlbums = mutableListOf(topAlbums, topArtists)
sevenDays = getString(R.string.period_7day)
oneMonth = getString(R.string.period_1month)
threeMonths = getString(R.string.period_3month)
sixMonths = getString(R.string.period_6month)
oneYear = getString(R.string.period_12month)
overall = getString(R.string.period_overall)
valuesPeriods = mutableListOf(overall, oneYear, sixMonths, threeMonths, oneMonth, sevenDays)
validateTheme()
val user: String? = SecurePreferences.getStringValue(applicationContext, Constants.SECURE_USER_TAG, "")
if (utils.isValidSessionKey()) {
if (user != null) {
profile.setOnClickListener {
utils.openUrl("https://www.last.fm/user/$user")
}
initService()
updateData(user)
}
} else {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
swipeRefreshLayout.setOnRefreshListener {
updateData(user)
}
fab_menu.setClosedOnTouchOutside(true)
fab_update.setOnClickListener {
updateData(user)
}
fab_wall.setOnClickListener {
fab_menu.close(true)
doAsync {
try {
val finalBitmap = getBitmapFromGrid(false)
val wallManager = WallpaperManager.getInstance(applicationContext)
wallManager.setBitmap(finalBitmap)
uiThread {
Snackbar.make(parentLayout, getString(R.string.applied_wallpaper), Snackbar.LENGTH_LONG).show()
}
finalBitmap.recycle()
} catch (e: Exception) {
uiThread {
Snackbar.make(parentLayout, getString(R.string.error_wallpaper), Snackbar.LENGTH_LONG).show()
}
}
}
}
fab_share.setOnClickListener {
fab_menu.close(true)
doAsync {
val finalBitmap = getBitmapFromGrid(true)
val imageToShareUri = imageUtils.saveImageToShare(finalBitmap)
if (imageToShareUri != null) {
uiThread {
var messageId = R.string.share_image_text
if (periodSpinner.selectedItem == getString(R.string.period_overall)) {
messageId = R.string.share_image_all_time_text
}
imageUtils.shareImage(imageToShareUri, getString(messageId,
artistsAlbumsSpinner.selectedItem.toString().toLowerCase(Locale.getDefault()),
periodSpinner.selectedItem.toString().toLowerCase(Locale.getDefault())))
finalBitmap.recycle()
}
}
}
}
}
private fun getBitmapFromGrid(full: Boolean): Bitmap {
val destSize = Resources.getSystem().displayMetrics.widthPixels / 3
val listBitmaps = mutableListOf<Bitmap>()
val topAdapter = gridView.adapter as GridViewTopAdapter
for (item in topAdapter.getList()) {
val futureBitmap = imageUtils.getBitmapSync(item.url, destSize)
listBitmaps.add(futureBitmap.get())
}
return imageUtils.mergeMultiple(listBitmaps, full, destSize)
}
private fun updateData(user: String?) {
lastArtistsAlbumsSpinner = ""
lastPeriodSpinner = ""
if (utils.isValidSessionKey()) {
if (user != null) {
if (utils.isConnected()) {
utils.scrobblePendingMediaService()
} else {
Snackbar.make(parentLayout, getString(R.string.no_connection), Snackbar.LENGTH_LONG).show()
}
getUserInfo(user)
initSpinners(user)
getRecentTracks(user)
}
}
}
private fun startFabAnimation() {
if (fab_menu.isOpened) {
val rotate = RotateAnimation(0f, 360f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f
)
rotate.duration = 900
rotate.repeatCount = Animation.INFINITE
fab_update.startAnimation(rotate)
}
}
private fun stopAnimations() {
fab_update.clearAnimation()
fab_menu.close(true)
swipeRefreshLayout.isRefreshing = false
}
private fun validateTheme() {
if (Cyanea.instance.isDark) {
username.setTextColor(ContextCompat.getColor(applicationContext, R.color.white))
info.setTextColor(ContextCompat.getColor(applicationContext, R.color.white))
recentTracks.setTextColor(ContextCompat.getColor(applicationContext, R.color.white))
}
if (Cyanea.instance.isActionBarDark) {
toolbar.setTitleTextColor(ContextCompat.getColor(applicationContext, R.color.white))
val colorFilter = PorterDuffColorFilter(ContextCompat.getColor(applicationContext, R.color.white), PorterDuff.Mode.MULTIPLY)
toolbar.overflowIcon?.let { it.colorFilter = colorFilter }
}
toolbar.setBackgroundColor(Cyanea.instance.primary)
}
override fun onRestart() {
super.onRestart()
initService()
if (!utils.isValidSessionKey()) {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
}
override fun onResume() {
super.onResume()
if (!utils.isValidSessionKey()) {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
}
}
private fun initService() {
notificationUtils.createQuietNotificationChannel(this)
notificationUtils.createNotificationChannel(this)
if (notificationUtils.verifyNotificationAccess()) {
utils.startMediaService()
} else {
notificationUtils.changeNotificationAccess(this)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_settings -> {
val intent = Intent(this, SettingsActivity::class.java)
startActivity(intent)
return true
}
R.id.action_theme_picker -> {
val intent = Intent(this, CyaneaThemePickerActivity::class.java)
startActivity(intent)
return true
}
R.id.action_about -> {
LibsBuilder().withAboutAppName(getString(R.string.app_name))
.withSortEnabled(false)
.withActivityColor(Colors(Cyanea.instance.primary, Cyanea.instance.primary))
.withActivityStyle(Libs.ActivityStyle.LIGHT)
.withAboutIconShown(true)
.withAboutVersionShown(true)
.withAboutDescription(getString(R.string.about_description))
.start(this)
return true
}
R.id.action_logoff -> {
notificationUtils.cancelNoPlayerNotification()
utils.stopMediaService()
SecurePreferences.clearAllValues(applicationContext)
applicationContext.defaultSharedPreferences.edit().clear().apply()
utils.setNotFirstExecution()
val intent = Intent(this, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
return true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun getUserInfo(user: String) {
doAsync {
val response = lastFmService.userInfo(user, Constants.API_KEY).execute()
if (response.isSuccessful) {
val profileUrl = response.body()?.user?.image?.last()?.text
val name = response.body()?.user?.name
var realName = response.body()?.user?.realname
if (realName.isNullOrEmpty()) {
realName = name
}
val registered = response.body()?.user?.registered?.text
uiThread {
if (profileUrl != null) {
profile.let { profileImage -> imageUtils.getAvatarImage(profileUrl, profileImage) }
}
username.text = name
if (registered != null) {
info.text = applicationContext.getString(R.string.scrobbling_since, realName, utils.getDateTimeFromEpoch(registered))
} else {
info.text = realName
}
}
}
}
}
private fun initSpinners(user: String) {
startFabAnimation()
var artistsAlbumsAdapter = ArrayAdapter(this, R.layout.spinner_item_artist_album, valuesArtistsAlbums)
artistsAlbumsAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item)
if (Cyanea.instance.isDark) {
artistsAlbumsAdapter = ArrayAdapter(this, R.layout.spinner_item_artist_album_dark, valuesArtistsAlbums)
artistsAlbumsAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item_dark)
}
artistsAlbumsSpinner.adapter = artistsAlbumsAdapter
artistsAlbumsSpinner.setSelection(getSharedPreferences("Spinners", Context.MODE_PRIVATE).getInt("artistsAlbums", 0))
artistsAlbumsSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
//Do nothing
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
getSharedPreferences("Spinners", Context.MODE_PRIVATE).edit().putInt("artistsAlbums", position).apply()
val artistImage = parent?.getItemAtPosition(position).toString()
searchImages(user, artistImage, periodSpinner.selectedItem.toString())
}
}
var periodAdapter = ArrayAdapter(this, R.layout.spinner_item_period, valuesPeriods)
periodAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item)
if (Cyanea.instance.isDark) {
periodAdapter = ArrayAdapter(this, R.layout.spinner_item_period_dark, valuesPeriods)
periodAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item_dark)
}
periodSpinner.adapter = periodAdapter
periodSpinner.setSelection(getSharedPreferences("Spinners", Context.MODE_PRIVATE).getInt("period", 0))
periodSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
//Do nothing
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
getSharedPreferences("Spinners", Context.MODE_PRIVATE).edit().putInt("period", position).apply()
val period = parent?.getItemAtPosition(position).toString()
searchImages(user, artistsAlbumsSpinner.selectedItem.toString(), period)
}
}
}
private fun getRecentTracks(user: String) {
doAsync {
val recentTracksList = ArrayList<Recent>()
val response = lastFmService.recentTracks(user, Constants.API_KEY).execute()
if (response.isSuccessful) {
val tracks = response.body()?.recenttracks?.track
if (tracks != null) {
for (track in tracks) {
val name = track.name
val artist = track.artist.name
var imageUrl: String
var timestamp: String
var loved = false
var scrobbling = false
val lastFmUrl = track.url
if (track.attr != null && track.attr.nowplaying.toBoolean()) {
imageUrl = "https://tse2.mm.bing.net/th?q=${track.artist.name} Band&w=500&h=500&c=7&rs=1&p=0&dpr=3&pid=1.7&mkt=en-IN&adlt=on"
timestamp = "Scrobbling now"
scrobbling = true
} else {
imageUrl = track.image.last().text
if (imageUrl.isBlank()) {
imageUrl = "https://tse2.mm.bing.net/th?q=${track.artist.name} ${track.name} Album&w=500&h=500&c=7&rs=1&p=0&dpr=3&pid=1.7&mkt=en-IN&adlt=on"
}
timestamp = utils.convertUTCToLocalPretty(track.date.text)
loved = track.loved == "1"
}
recentTracksList.add(Recent(imageUrl, name, artist, timestamp, loved, scrobbling, lastFmUrl))
}
}
}
uiThread {
val listAdapter = ListViewTrackAdapter(applicationContext, recentTracksList)
listTracks.adapter = listAdapter
utils.setListViewHeightBasedOnItems(listTracks)
stopAnimations()
}
}
}
private fun searchImages(user: String, artistAlbum: String, period: String) {
if (artistAlbum == lastArtistsAlbumsSpinner && period == lastPeriodSpinner) {
utils.log("Não houve mudança, não vai carregar de novo o grid")
} else {
utils.log("Carregando a grid. Spinner: $artistAlbum - Period: $period")
if (artistAlbum == topArtists) {
getTopArtists(user, artistAlbum, period)
} else {
getTopAlbums(user, artistAlbum, period)
}
}
}
private fun getTopArtists(user: String, artistAlbum: String, period: String) {
doAsync {
val response = lastFmService.topArtists(user,
utils.getPeriodParameter(period), Constants.API_KEY).execute()
if (response.isSuccessful) {
lastArtistsAlbumsSpinner = artistAlbum
lastPeriodSpinner = period
val listTopInfo = ArrayList<TopInfo>()
val artists = response.body()?.topartists?.artist
if (artists != null) {
for (artist in artists) {
val url = "https://tse2.mm.bing.net/th?q=${artist.name} Band&w=500&h=500&c=7&rs=1&p=0&dpr=3&pid=1.7&mkt=en-IN&adlt=on"
val topBean = TopInfo(url, artist.name, artist.playcount.plus(" plays"), artist.url)
listTopInfo.add(topBean)
}
}
uiThread {
showArtistWarningDialog()
gridView.adapter = GridViewTopAdapter(applicationContext, listTopInfo, Constants.ARTISTS)
}
} else {
snackDataError()
}
}
}
private fun showArtistWarningDialog() {
if (showDialog()) {
var style = R.style.Cyanea_AlertDialog_Theme_Light
if (Cyanea.instance.isDark) {
style = R.style.Cyanea_AlertDialog_Theme_Dark
}
val builder = AlertDialog.Builder(this@MainActivity, style)
val view = View.inflate(this@MainActivity, R.layout.dialog_artists, null)
val checkBox = view.findViewById<CheckBox>(R.id.checkBox)
builder.setTitle(getString(R.string.warning_title))
builder.setMessage(getString(R.string.warning_message))
builder.setView(view)
builder.setPositiveButton("OK") { dialog, _ -> dialog.dismiss() }
val dialog = builder.create()
dialog.setOnShowListener {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setBackgroundColor(Cyanea.instance.accent)
}
dialog.show()
checkBox.setOnCheckedChangeListener { buttonView, _ ->
if (buttonView.isChecked) {
setShowDialog(!buttonView.isChecked)
}
}
}
}
private fun setShowDialog(showDialog: Boolean) = PreferenceManager.getDefaultSharedPreferences(applicationContext).edit().putBoolean("show_dialog", showDialog).apply()
private fun showDialog() = PreferenceManager.getDefaultSharedPreferences(applicationContext).getBoolean("show_dialog", true)
private fun getTopAlbums(user: String, artistAlbum: String, period: String) {
doAsync {
val response = lastFmService.topAlbums(user,
utils.getPeriodParameter(period), Constants.API_KEY).execute()
if (response.isSuccessful) {
lastArtistsAlbumsSpinner = artistAlbum
lastPeriodSpinner = period
val albums = response.body()?.topalbums?.album
val listTopInfo = ArrayList<TopInfo>()
if (albums != null) {
for (album in albums) {
var imageUrl = album.image.last().text
if (imageUrl.isBlank()) {
imageUrl = "https://tse2.mm.bing.net/th?q=${album.artist.name} ${album.name} Album&w=500&h=500&c=7&rs=1&p=0&dpr=3&pid=1.7&mkt=en-IN&adlt=on"
}
val topBean = TopInfo(imageUrl, album.name, album.artist.name, album.url)
topBean.text3 = album.playcount.plus(" plays")
listTopInfo.add(topBean)
}
}
uiThread {
gridView.adapter = GridViewTopAdapter(applicationContext, listTopInfo, Constants.ALBUMS)
}
} else {
snackDataError()
}
}
}
private fun snackDataError() {
var snackMessage = R.string.error_loading_data
if (!utils.isConnected()) {
snackMessage = R.string.no_connection
}
Snackbar.make(parentLayout, getString(snackMessage), Snackbar.LENGTH_LONG).show()
}
}
| 0
|
Kotlin
|
0
| 0
|
b1f66f4fc85e0b9514b6b0f6f1eb55395d7ce0cc
| 22,693
|
master-scrobbler
|
MIT License
|
data/src/main/java/com/mnatsakanyan/data/network/CollectionService.kt
|
araratthehero
| 667,529,727
| false
| null |
package com.mnatsakanyan.data.network
import com.mnatsakanyan.data.model.NetworkArtObjectCollectionResponse
import com.mnatsakanyan.data.model.NetworkArtObjectResponse
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
internal interface CollectionService {
@GET("collection?s=artist")
suspend fun getCollection(
@Query("p")
pageNumber: Int,
@Query("ps")
itemCountPerPage: Int
): NetworkArtObjectCollectionResponse
@GET("collection/{artObjectNumber}")
suspend fun getArtObjectDetail(
@Path("artObjectNumber")
artObjectNumber: String
): NetworkArtObjectResponse
}
| 0
|
Kotlin
|
0
| 0
|
c65d7e18bbd9cab9b9ddbc3fc28349797668f08d
| 693
|
rijksmuseum-collection
|
Apache License 2.0
|
app/src/main/java/com/modmobility/weatherapp/models/Main.kt
|
yash300685
| 228,751,285
| false
| null |
package com.modmobility.weatherapp.models
data class Main (val temp:String)
| 0
|
Kotlin
|
0
| 0
|
529f6216f6d16717ef1484c3c1422e764ea08784
| 76
|
WeatherApplication
|
The Unlicense
|
app/src/main/java/com/swc/sampleapp_mvvm/di/NetworkModule.kt
|
JuheonYi
| 870,656,016
| false
|
{"Kotlin": 8521}
|
package com.swc.sampleapp_mvvm.di
import com.swc.sampleapp_mvvm.network.RetrofitClient
import com.swc.sampleapp_mvvm.network.WeatherApiService
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
fun provideWeatherApiService(): WeatherApiService {
return RetrofitClient.getInstance().create(WeatherApiService::class.java)
}
}
| 0
| null |
0
| 0
|
e223580c1f3f45804daac731c223eef50942d41d
| 496
|
sampleapp-mvvm
|
MIT License
|
magic-obs-bootstrap/src/main/kotlin/com/github/vatbub/magic/bootstrap/UpdateAndLaunchTask.kt
|
vatbub
| 352,061,373
| false
| null |
/*-
* #%L
* magic-obs-bootstrap
* %%
* Copyright (C) 2019 - 2021 Frederik Kammel
* %%
* 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.
* #L%
*/
package com.github.vatbub.magic.bootstrap
import com.github.vatbub.magic.bootstrap.FilesAndFolders.appDir
import com.github.vatbub.magic.bootstrap.FilesAndFolders.mavenHome
import com.github.vatbub.magic.bootstrap.FilesAndFolders.pomFile
import com.github.vatbub.magic.bootstrap.FilesAndFolders.repositoryLocation
import javafx.concurrent.Task
import org.apache.maven.shared.invoker.DefaultInvocationRequest
import org.apache.maven.shared.invoker.DefaultInvoker
import org.apache.maven.shared.invoker.Invoker
import java.io.File
import java.nio.file.DirectoryNotEmptyException
import java.nio.file.FileSystemException
import java.nio.file.Files
object UpdateAndLaunchTask : Task<Invoker>() {
override fun call(): Invoker {
updateProgress(-1, 0)
updateMessage(strings["preparing"])
FilesAndFolders.createALlDirectories()
Files.deleteIfExists(pomFile.toPath())
pomFile.writeText(
createDummyPom(
Configuration.groupId,
Configuration.artifactId,
Configuration.initialVersion,
Configuration.mainClass,
Configuration.releasesUrl,
Configuration.snapshotUrl
)
)
mavenHome.deleteAllChildrenIfPossible()
MavenExtractor.extract(mavenHome)
val invoker = DefaultInvoker()
invoker.localRepositoryDirectory = repositoryLocation
invoker.mavenHome = mavenHome
invoker.setOutputHandler(MavenOutputHandler)
updateMessage(strings["checking_for_updates"])
val updateVersionsRequest = createRequest(listOf("versions:use-latest-versions"), true)
val updateVersionsResult = invoker.execute(updateVersionsRequest)
if (updateVersionsResult.exitCode != 0) {
throw IllegalStateException(strings["update_check_failed"])
}
updateMessage(strings["downloading_updates"])
val updateAppRequest = DefaultInvocationRequest()
updateAppRequest.pomFile = pomFile
updateAppRequest.goals = listOf("dependency:resolve")
updateAppRequest.baseDirectory = appDir
updateAppRequest.isUpdateSnapshots = true
val updateAppResult = invoker.execute(updateAppRequest)
if (updateAppResult.exitCode != 0) {
throw IllegalStateException(strings["download_failed"])
}
return invoker
}
}
fun createRequest(goals: List<String>, isUpdateSnapshots: Boolean) = DefaultInvocationRequest().also {
it.pomFile = pomFile
it.goals = goals
it.baseDirectory = appDir
it.isUpdateSnapshots = isUpdateSnapshots
}
private fun File.deleteAllChildrenIfPossible() = listFiles()!!
.map { it.listAllChildrenForDeletion() }
.flatten()
.forEach {
try {
Files.delete(it.toPath())
} catch (e: FileSystemException) {
e.printStackTrace()
} catch (e: DirectoryNotEmptyException) {
e.printStackTrace()
}
}
private fun File.listAllChildrenForDeletion(): List<File> =
if (isFile) listOf(this)
else listFiles()!!
.map { it.listAllChildrenForDeletion() }
.flatten() + this
| 0
|
Kotlin
|
0
| 0
|
9919d8db94fd972cba32fab334f59cc43a156988
| 3,851
|
magic-obs
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.