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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
test/src/me/anno/tests/ui/DeepImportIsMessingUpImages.kt | AntonioNoack | 456,513,348 | false | {"Kotlin": 10912545, "C": 236426, "Java": 6754, "Lua": 4496, "C++": 3070, "GLSL": 2698} | package me.anno.tests.ui
fun main() {
// todo when deep-importing, we must copy images as-is
} | 0 | Kotlin | 3 | 24 | 013af4d92e0f89a83958008fbe1d1fdd9a10e992 | 99 | RemsEngine | Apache License 2.0 |
common/src/main/java/com/remote/common/app/BaseActivity.kt | xhh4215 | 244,554,186 | false | {"Java": 136718, "Kotlin": 21924} | package com.remote.common.app
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
abstract class BaseActivity : AppCompatActivity() {
/***
* activity初次创建调用的方法
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initWindow()
if( initArgs(intent.extras)){
setContentView(getLayoutId())
initWidget()
initData()
}else{
finish()
}
}
/***
* 初始化窗口的方法
*/
open fun initWindow() {
}
/***
* 初始化别的activity传递的信息的方法
*/
open fun initArgs(bundle: Bundle?) = true
/***
* 获取布局id的方法
*/
open abstract fun getLayoutId():Int
/***
* 初始化控件的方法
*/
open fun initWidget() {
}
/***
* 初始化数据的方法
*/
open fun initData() {
}
override fun onSupportNavigateUp(): Boolean {
finish()
return super.onSupportNavigateUp()
}
/***
* backpress按键点击执行的方法
*/
override fun onBackPressed() {
// 得到当前Activity下的所有Fragment
@SuppressLint("RestrictedApi")
val fragments = supportFragmentManager.fragments
// 判断fragments是不是空的 并且fragments个数大于0
if (fragments != null && fragments.size > 0) {
//遍历fragments
for (fragment in fragments) {
// 判断是否为我们能够处理的Fragment类型
if (fragment is BaseFragment) {
// 判断是否拦截了返回按钮
if ((fragment).onBackPressed()) {
// 如果有直接Return
return
}
}
}
}
super.onBackPressed()
finish()
}
} | 1 | null | 1 | 1 | bf6cf2a079f7a5e6f95da4fc1ffcfacf9f520201 | 1,773 | RemoteInquiry | Apache License 2.0 |
common/src/commonMain/kotlin/mes/inc/aic/common/data/cache/Daos.kt | victorkemboi | 585,276,784 | false | null | package mes.inc.aic.common.data.cache
import co.touchlab.kermit.Logger
import com.squareup.sqldelight.runtime.coroutines.asFlow
import com.squareup.sqldelight.runtime.coroutines.mapToList
import kotlinx.coroutines.flow.Flow
import mes.inc.aic.common.data.model.Artwork
import mes.inc.aic.common.database.ArtworkQueries
interface ArtworkDao {
fun insert(artwork: Artwork)
fun insert(artworks: List<Artwork>)
fun fetchArtworks(query: String? = null): Flow<List<Artwork>>
suspend fun recordExists(title: String): Boolean
fun removeAllArtworks()
}
class ArtworkDaoImpl(private val artworkQueries: ArtworkQueries) : ArtworkDao {
@Suppress("TooGenericExceptionCaught")
override fun insert(artwork: Artwork) {
try {
artworkQueries.insertArtwork(
localId = null,
serverId = artwork.serverId,
title = artwork.title,
thumbnail = artwork.thumbnail,
dateDisplay = artwork.dateDisplay,
artistId = artwork.artistId,
categoryTitles = artwork.categoryTitles.joinToString(separator = ","),
styleTitle = artwork.styleTitle,
updatedAt = artwork.updatedAt,
origin = artwork.origin,
searchString = artwork.searchString
)
} catch (e: Exception) {
Logger.i("Error inserting: $e")
}
}
override fun insert(artworks: List<Artwork>) {
artworks.forEach { insert(it) }
}
override fun fetchArtworks(query: String?): Flow<List<Artwork>> {
return if (query != null) {
artworkQueries.search(query = "%$query%", mapper = Artwork.mapper)
} else {
artworkQueries.selectAll(mapper = Artwork.mapper)
}.asFlow().mapToList()
}
override suspend fun recordExists(title: String): Boolean {
val exists = artworkQueries.recordExists(title).executeAsOne()
Logger.i("Record exists: $exists")
return exists == 1L
}
override fun removeAllArtworks() {
artworkQueries.transaction {
artworkQueries.removeAllArtworks()
}
}
}
internal class ArtistDao | 0 | Kotlin | 0 | 0 | 189de15c4d4ab25c50409ccdcf076f375ca73f7d | 2,215 | Art-Space | Apache License 2.0 |
src/commonMain/kotlin/tile/Tile.kt | glubo | 745,395,684 | false | {"Kotlin": 28103, "Smarty": 1812, "Dockerfile": 377, "Shell": 127} | package tile
import Direction
import kotlin.time.Duration
sealed class Tile {
abstract fun onUpdate(dt: Duration): TileEvent?
abstract fun takeLiquid(
direction: Direction,
dt: Duration,
): Boolean
abstract fun isEditable(): Boolean
}
sealed interface TileEvent
data class Overflow(
val dt: Duration,
val direction: Direction,
val score: Long,
) : TileEvent {
init {
println(this)
}
}
| 0 | Kotlin | 0 | 0 | 7f380dfbdcd06f4aab334c662af8bddcc2082cc3 | 451 | plumbeteer | MIT License |
app/src/main/java/com/example/electrorui/ui/RegistroActivity.kt | DGCORruie23 | 771,695,261 | false | {"Kotlin": 369231} | package com.example.electrorui.ui
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.activity.viewModels
import com.example.electrorui.databinding.ActivityRegistroBinding
import com.example.electrorui.networkApi.model.RegistroNacionalidadModel
import com.example.electrorui.ui.fragments.CapturaFragment
import com.example.electrorui.ui.viewModel.RegistroNuevo_AVM
import com.example.electrorui.ui.viewModel.Registro_AVM
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class RegistroActivity : AppCompatActivity() {
companion object{
val EXTRA_REGISTRO = "RegistroActivity:registro"
}
private lateinit var binding : ActivityRegistroBinding
private val dataActivityViewM : Registro_AVM by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRegistroBinding.inflate(layoutInflater)
setContentView(binding.root)
dataActivityViewM.onCreated()
binding.editTextNucleosFam.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun afterTextChanged(p0: Editable?) {
val numS = p0.toString()
if(!numS.isEmpty()){
if (numS.toInt() > 0){
binding.LLFamiliares.visibility = View.VISIBLE
} else if(numS.toInt() == 0){
binding.LLFamiliares.visibility = View.GONE
}
}
}
})
var nacio = emptyArray<String>()
val spinnerArrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, nacio)
binding.spinnerPAIS.adapter = spinnerArrayAdapter
dataActivityViewM.paises.observe(this){
spinnerArrayAdapter.clear()
spinnerArrayAdapter.addAll(it)
spinnerArrayAdapter.notifyDataSetChanged()
}
binding.buttonGuardarForm.setOnClickListener {
val nacionalidad = binding.spinnerPAIS.selectedItem.toString()
val AS_hombres = (binding.editTextASHombres.text.toString())
val AS_mujeresNoEmb = (binding.editTextASMujeresNoEmb.text.toString())
val AS_mujeresEmb = (binding.editTextASMujeresEmb.text.toString())
val nucleosFamiliares = (binding.editTextNucleosFam.text.toString())
val AA_NNAs_hombres = (binding.editTextAANNAsHombres.text.toString())
val AA_NNAs_mujeresNoEmb = (binding.editTextAANNAsMujeresNoEmb.text.toString())
val AA_NNAs_mujeresEmb = (binding.editTextAANNAsMujeresEmb.text.toString())
val NNAsA_hombres = (binding.editTextNNAsAHombres.text.toString())
val NNAsA_mujeresNoEmb = (binding.editTextNNAsAMujeresNoEmb.text.toString())
val NNAsA_mujeresEmb = (binding.editTextNNAsAMujeresEmb.text.toString())
val NNAsS_hombres = (binding.editTextNNAsSHombres.text.toString())
val NNAsS_mujeresNoEmb = (binding.editTextNNAsSMujeresNoEmb.text.toString())
val NNAsS_mujeresEmb = (binding.editTextNNAsSMujeresEmb.text.toString())
val datosRetorno = RegistroNacionalidadModel(
nacionalidad,
"",
verificarDatoInt(AS_hombres),
verificarDatoInt(AS_mujeresNoEmb),
verificarDatoInt(AS_mujeresEmb),
verificarDatoInt(nucleosFamiliares),
verificarDatoInt(AA_NNAs_hombres),
verificarDatoInt(AA_NNAs_mujeresNoEmb),
verificarDatoInt(AA_NNAs_mujeresEmb),
verificarDatoInt(NNAsA_hombres),
verificarDatoInt(NNAsA_mujeresNoEmb),
verificarDatoInt(NNAsA_mujeresEmb),
verificarDatoInt(NNAsS_hombres),
verificarDatoInt(NNAsS_mujeresNoEmb),
verificarDatoInt(NNAsS_mujeresEmb),
)
val datosRetornoIntent = Intent()
datosRetornoIntent.putExtra(CapturaFragment.EXTRA_REGISTRO, datosRetorno)
setResult(RESULT_OK, datosRetornoIntent)
Toast.makeText(this, "Guardando datos", Toast.LENGTH_LONG).show()
finish()
}
val registro = intent.getParcelableExtra<RegistroNacionalidadModel>(EXTRA_REGISTRO)
if (registro != null){
binding.spinnerPAIS.setSelection(spinnerArrayAdapter.getPosition("${registro.nacionalidad}"))
binding.editTextASHombres.setText(registro.AS_hombres.toString())
binding.editTextASMujeresNoEmb.setText(registro.AS_mujeresNoEmb.toString())
binding.editTextASMujeresEmb.setText(registro.AS_mujeresEmb.toString())
binding.editTextNucleosFam.setText(registro.nucleosFamiliares.toString())
binding.editTextAANNAsHombres.setText(registro.AA_NNAs_hombres.toString())
binding.editTextAANNAsMujeresNoEmb.setText(registro.AA_NNAs_mujeresNoEmb.toString())
binding.editTextAANNAsMujeresEmb.setText(registro.AA_NNAs_mujeresEmb.toString())
binding.editTextNNAsAHombres.setText(registro.NNAsA_hombres.toString())
binding.editTextNNAsAMujeresNoEmb.setText(registro.NNAsA_mujeresNoEmb.toString())
binding.editTextNNAsAMujeresEmb.setText(registro.NNAsA_mujeresEmb.toString())
binding.editTextNNAsSHombres.setText(registro.NNAsS_hombres.toString())
binding.editTextNNAsSMujeresNoEmb.setText(registro.NNAsS_mujeresNoEmb.toString())
binding.editTextNNAsSMujeresEmb.setText(registro.NNAsS_mujeresEmb.toString())
}
}
fun verificarDatoInt( dato : String) : Int{
if (dato == ""){
return 0
}else
return Integer.parseInt(dato)
}
} | 0 | Kotlin | 0 | 0 | a861b2614b5d8b765bbb8a226302da0a98f73326 | 6,199 | RUIeAndroid | The Unlicense |
app/src/main/java/com/example/androiddevchallenge/ui/BannerView.kt | vitaviva | 342,156,412 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
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.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.data.DemoDataProvider
import com.example.androiddevchallenge.data.Puppy
import com.example.androiddevchallenge.ui.theme.MyTheme
@Composable
fun BannerView(
listState: LazyListState,
list: List<Puppy>,
onClickItem: (puppy: Puppy) -> Unit
) {
Column {
Text(
modifier = Modifier.padding(16.dp),
text = "Featured Puppies",
style = MaterialTheme.typography.subtitle1
)
LazyRow(
state = listState,
) {
items(
count = list.size,
itemContent = {
BannerItem(
list[it],
Modifier.padding(start = 16.dp, bottom = 16.dp, top = 8.dp)
) { onClickItem.invoke(list[it]) }
}
)
}
}
}
@Composable
private fun BannerItem(
puppy: Puppy,
modifier: Modifier = Modifier,
onClick: () -> Unit
) {
Card(
shape = MaterialTheme.shapes.medium,
modifier = modifier
.size(280.dp, 200.dp)
.shadow(20.dp)
) {
Box(modifier = Modifier.clickable { onClick() }) {
val image = ImageBitmap.imageResource(puppy.images.first())
Image(
bitmap = image,
contentScale = ContentScale.Crop,
contentDescription = null,
modifier = Modifier
.fillMaxHeight()
.fillMaxWidth()
)
Column(
modifier = Modifier
.background(Color.White.copy(alpha = 0.9f))
.fillMaxWidth()
.padding(16.dp)
.align(Alignment.BottomStart)
) {
Row {
Text(
text = puppy.name,
style = MaterialTheme.typography.h6,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
Spacer(modifier = Modifier.padding(1.dp))
Image(
modifier = Modifier
.size(16.dp)
.align(Alignment.CenterVertically),
colorFilter = ColorFilter.tint(puppy.sex.color),
imageVector = puppy.sex.label, contentDescription = null
)
}
Text(
text = puppy.breed,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.body2
)
Text(
text = puppy.location,
style = MaterialTheme.typography.body2
)
}
}
}
}
@Preview
@Composable
fun PreviewHorizontalListItem() {
val puppy = DemoDataProvider.Edison
MyTheme {
BannerItem(puppy = puppy, onClick = {})
}
}
| 0 | Kotlin | 1 | 14 | 3bbdd385ecd774714d5b94ebc6e483ce21e2e513 | 5,007 | android-dev-challenge-compose | Apache License 2.0 |
lib/src/main/java/com/kirkbushman/redgifs/auth/TokenBearer.kt | KirkBushman | 229,434,144 | false | null | package com.kirkbushman.redgifs.auth
import com.kirkbushman.gfycat.auth.Credentials
import com.kirkbushman.redgifs.managers.StorageManager
data class TokenBearer(
private val authManager: AuthManager,
private val storManager: StorageManager,
private var token: Token?,
private val credentials: Credentials
) {
init {
if (token != null) {
storManager.saveToken(token!!)
}
}
fun getRawAccessToken(): String {
if (shouldRenew()) {
renewToken()
}
return token!!.accessToken
}
fun getAuthHeader(): Map<String, String> {
return hashMapOf("Authorization" to "Bearer ".plus(getRawAccessToken()))
}
private fun shouldRenew(): Boolean {
return token?.shouldRenew() ?: false
}
fun renewToken() {
if (token == null) {
return
}
val res = authManager.refreshToken(token)
val token = res.body()
if (!res.isSuccessful || token == null) {
throw IllegalStateException("Error during token renewal")
}
this.token = token
storManager.saveToken(token)
}
}
| 0 | Kotlin | 0 | 4 | ea7b424d4140a31dea372b8d2f79644e5fe068c6 | 1,175 | gfycat-android | MIT License |
app/src/main/java/com/example/hello_world/MainActivity.kt | horllan | 527,069,041 | false | {"Kotlin": 1753} | package com.example.hello_world
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.util.Log
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnSayHello = findViewById<Button>(R.id.btnSayHello)
btnSayHello.setOnClickListener{
Log.v("Hello world", "Hello world button clicked")
// this is like a modal it display the specified text for the specified duration
Toast.makeText(this, "Hello to you too", Toast.LENGTH_SHORT).show()
}
}
} | 0 | Kotlin | 0 | 0 | ff21d0c3c67ba9ba7ae869cc612e1ed002e2412a | 733 | codepath_prework_proj | Apache License 2.0 |
impl/src/main/java/com/huya/mobile/uinspector/impl/properties/view/ViewPropertiesParserService.kt | findvoid | 329,785,127 | true | {"Kotlin": 143263} | package com.huya.mobile.uinspector.impl.properties.view
import android.view.View
/**
* Using Java SPI: To add your custom view's properties
*
* @author YvesCheung
* 2021/1/3
*/
interface ViewPropertiesParserService {
fun tryCreate(v: View): ViewPropertiesParser<out View>?
} | 0 | null | 0 | 0 | 599fdbd308711eabbd9d0424473c67b123cc8259 | 286 | UInspector | Apache License 2.0 |
src/main/kotlin/one/oktw/galaxy/internal/types/Member.kt | koru1130 | 119,349,323 | true | {"Kotlin": 32224} | package one.oktw.galaxy.internal.types
import one.oktw.galaxy.internal.enums.Group
import java.util.*
data class Member(
val uuid: UUID? = null,
var group: Group = Group.MEMBER
)
| 0 | Kotlin | 0 | 0 | 6566ddc2e26663c336374a5a50a638d0a5fd643d | 197 | oktw-galaxy | MIT License |
core/src/main/kotlin/com/github/prologdb/execplan/UnifyFunctor.kt | prologdb | 113,687,585 | false | null | package com.github.prologdb.execplan
import com.github.prologdb.async.LazySequence
import com.github.prologdb.async.flatMapRemaining
import com.github.prologdb.dbms.DBProofSearchContext
import com.github.prologdb.runtime.VariableMapping
import com.github.prologdb.runtime.term.Predicate
import com.github.prologdb.runtime.unification.VariableBucket
import com.github.prologdb.runtime.unification.VariableDiscrepancyException
import com.github.prologdb.storage.fact.PersistenceID
/**
* Implements `[+, fact] -> unify(fact) -> +`
*/
class UnifyFunctor(
val rhs: Predicate
) : PlanFunctor<Pair<PersistenceID, Predicate>, PersistenceID> {
private val rhsVariables = rhs.variables
override fun invoke(ctxt: DBProofSearchContext, inputs: LazySequence<Pair<VariableBucket, Pair<PersistenceID, Predicate>>>): LazySequence<Pair<VariableBucket, PersistenceID>> {
val rhsMapping = VariableMapping()
val randomRHS = ctxt.randomVariableScope.withRandomVariables(rhs, rhsMapping)
return inputs
.flatMapRemaining { (variableCarry, pidAndFact) ->
val (persistenceID, fact) = pidAndFact
val randomFact = ctxt.randomVariableScope.withRandomVariables(fact, VariableMapping())
randomRHS.unify(randomFact)?.let { unification ->
val resolvedBucket = unification.variableValues.withVariablesResolvedFrom(rhsMapping)
resolvedBucket.retainAll(rhsVariables)
try {
resolvedBucket.incorporate(variableCarry)
yield(Pair(resolvedBucket, persistenceID))
} catch (ex: VariableDiscrepancyException) {
// mismatch, do not yield (equals to prolog false)
}
}
}
}
override val explanation: Predicate
get() = Predicate("unify", arrayOf(rhs))
} | 10 | Kotlin | 0 | 2 | 788ab81bf872fa82c86f89bcbae8a13247e77e05 | 1,928 | prologdb | MIT License |
runtime/src/androidUnitTest/kotlin/dev/galex/yamvil/viewmodels/models/TestedMVIViewModel.kt | galex | 799,153,870 | false | {"Kotlin": 52718} | package dev.galex.yamvil.viewmodels.models
import dev.galex.yamvil.models.base.Consumable
import dev.galex.yamvil.viewmodels.MVIViewModel
class TestedViewModel: MVIViewModel<TestedUiState, TestedUiEvent>() {
override fun initializeUiState() = TestedUiState()
override fun handleEvent(event: TestedUiEvent) {
when (event) {
is TestedUiEvent.FirstEvent -> update { copy(firstEventTriggered = true) }
is TestedUiEvent.SecondEvent -> update { copy(secondEventTriggered = true) }
is TestedUiEvent.ThirdEvent -> update { copy(action = Consumable(TestedUiAction.FirstAction)) }
}
}
} | 3 | Kotlin | 0 | 5 | dc08a2eb66bc0247db79353da5d25253cbe74a0f | 644 | yamvil | Apache License 2.0 |
runtime/src/androidUnitTest/kotlin/dev/galex/yamvil/viewmodels/models/TestedMVIViewModel.kt | galex | 799,153,870 | false | {"Kotlin": 52718} | package dev.galex.yamvil.viewmodels.models
import dev.galex.yamvil.models.base.Consumable
import dev.galex.yamvil.viewmodels.MVIViewModel
class TestedViewModel: MVIViewModel<TestedUiState, TestedUiEvent>() {
override fun initializeUiState() = TestedUiState()
override fun handleEvent(event: TestedUiEvent) {
when (event) {
is TestedUiEvent.FirstEvent -> update { copy(firstEventTriggered = true) }
is TestedUiEvent.SecondEvent -> update { copy(secondEventTriggered = true) }
is TestedUiEvent.ThirdEvent -> update { copy(action = Consumable(TestedUiAction.FirstAction)) }
}
}
} | 3 | Kotlin | 0 | 5 | dc08a2eb66bc0247db79353da5d25253cbe74a0f | 644 | yamvil | Apache License 2.0 |
app/src/main/java/com/devcommop/joaquin/codeforgood/ui/students_screen/student_detail_screen/StudentDetailViewModel.kt | RahulSoni0 | 522,188,041 | false | null | package com.devcommop.joaquin.codeforgood.ui.students_screen.student_detail_screen
import androidx.lifecycle.ViewModel
import com.devcommop.joaquin.codeforgood.domain.repository.Repository
class StudentDetailViewModel(val repository: Repository): ViewModel() {
} | 0 | Kotlin | 1 | 1 | 02f20d700cea6bf0cd9a59ae51ffec9b928f41d8 | 264 | DucoSign | Creative Commons Zero v1.0 Universal |
remote/src/test/java/com/abhrp/daily/remote/mapper/detail/NewsDetailMapperTest.kt | abhrp | 215,215,257 | false | null | package com.abhrp.daily.remote.mapper.detail
import com.abhrp.daily.remote.factory.FeedItemFactory
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class NewsDetailMapperTest {
private lateinit var newsDetailMapper: NewsDetailMapper
@Before
fun setup() {
newsDetailMapper = NewsDetailMapper()
}
@Test
fun testMapsToEntityCorrectly() {
val detailResponse = FeedItemFactory.getDetailsResponse()
val newsDetailData = newsDetailMapper.mapToEntity(detailResponse.response)
val feedItem = detailResponse.response.details
Assert.assertEquals(feedItem.id, newsDetailData.id)
Assert.assertEquals(feedItem.publicationDate, newsDetailData.publicationDate)
Assert.assertEquals(feedItem.sectionName, newsDetailData.sectionName)
Assert.assertEquals(feedItem.fields.headline, newsDetailData.headline)
Assert.assertEquals(feedItem.fields.thumbnail, newsDetailData.thumbnail)
Assert.assertEquals(feedItem.fields.body, newsDetailData.body)
Assert.assertEquals(feedItem.fields.byline, newsDetailData.byline)
}
} | 0 | Kotlin | 0 | 0 | ec839445ff53e5de8bcc4d83e90fdbc3efbb2bb4 | 1,223 | daily | MIT License |
Study/app/src/main/java/com/example/study/ui/recycler/RecyclerSearchViewHolder.kt | nascimentoJulio | 318,672,400 | false | null | package com.example.study.ui.recycler
import android.view.View
import android.widget.Button
import android.widget.ImageButton
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.example.study.R
import com.example.study.listeners.OnClickLastSearch
import com.example.study.listeners.OnDeleteSearch
import com.example.study.models.SearchModel
class RecyclerSearchViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val title: TextView = itemView.findViewById(R.id.text_title_search)
private val container: ConstraintLayout = itemView.findViewById(R.id.id_search_item_container)
private val buttonDelete: ImageButton = itemView.findViewById(R.id.button_delete_search)
fun render(searchModel: SearchModel, deleteClick: OnDeleteSearch, searchClick: OnClickLastSearch){
title.text = searchModel.title
this.buttonDelete.setOnClickListener {
deleteClick.onClick(searchModel)
}
this.container.setOnClickListener {
searchClick.onLastClick(searchModel.title)
}
}
}
| 0 | Kotlin | 0 | 0 | a19e68b0364130c36cc49973a9b203779806a40c | 1,160 | Lab | MIT License |
app/src/main/java/com/projeto/notebook/model/Note.kt | Willian-Ribeiro | 207,454,140 | false | null | package com.projeto.notebook.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.projeto.notebook.AppProps.Companion.DATE_FORMAT
import java.util.*
// POJO
@Entity(tableName = "note_table")
data class Note(
@PrimaryKey(autoGenerate = true)
val id : Int,
var title: String ?,
var date : String = DATE_FORMAT.format(Date()),
var data : String ?
) | 0 | Kotlin | 0 | 0 | b64f5dcacadc23763e4ac62503f5b1232024523d | 393 | Android_Notebook | MIT License |
app/src/main/java/com/serhatd/chatapp/data/remote/UserService.kt | serhat-demir | 618,120,872 | false | null | package com.serhatd.chatapp.data.remote
import com.serhatd.chatapp.data.model.ApiResponse
import com.serhatd.chatapp.data.model.User
import com.serhatd.chatapp.data.model.UserRequest
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.POST
interface UserService {
@POST("login")
suspend fun login(
@Body user: UserRequest
): Response<ApiResponse<User>>
@POST("register")
suspend fun register(
@Body user: UserRequest
): Response<ApiResponse<Nothing>>
} | 0 | Kotlin | 0 | 0 | 478be4e51bab490f1a8e28a7c5b373166029116e | 518 | chatapp-android | MIT License |
app/src/main/java/com/skeleton/mvp/utils/TextFormatting.kt | jungleworks | 387,698,917 | false | {"Java": 3814012, "Kotlin": 3282940, "Shell": 4734, "Ruby": 1078, "Starlark": 152} | package com.skeleton.mvp.utils
import android.text.Spannable
import android.text.SpannableStringBuilder
import java.lang.StringBuilder
object TextFormatting {
var preFormattedString = ""
var postFormattedString: StringBuilder? = null
var finalFormattedString: SpannableStringBuilder? = null
var doubleAsterik = "**"
var doubleUnderscore = "__"
var charArray: CharArray? = null
var formatPositions = ArrayList<Int>()
var isFormatCharFound = false
var skipLoopIndex = false
fun formatString(toBeFormattedString: String): SpannableStringBuilder? {
this.preFormattedString = toBeFormattedString
addPreAndPostSpace()
charArray = this.preFormattedString.toCharArray()
formatPositions = getCharactersToBeManipukated()
if (formatPositions.size > 1) {
this.postFormattedString = removeAllFormatCharacters(this.preFormattedString)
finalFormattedString = SpannableStringBuilder(this.postFormattedString.toString())
var message = this.postFormattedString.toString()
for (index in 0..formatPositions.size - 1 step 2) {
if (formatPositions.size > index + 1) {
if (finalFormattedString.toString().substring(formatPositions[index], formatPositions[index + 1] + 1).trim().isNotEmpty()) {
finalFormattedString?.setSpan(android.text.style.StyleSpan(android.graphics.Typeface.BOLD),
formatPositions[index], formatPositions[index + 1] + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
}
return finalFormattedString
} else {
return SpannableStringBuilder(toBeFormattedString)
}
}
private fun addPreAndPostSpace() {
if (!this.preFormattedString.toString().equals(doubleAsterik)) {
this.preFormattedString = " $preFormattedString "
}
}
private fun getCharactersToBeManipukated(): ArrayList<Int> {
val formatPositions = ArrayList<Int>()
for (index in 0..charArray!!.size - 2) {
if (skipLoopIndex) {
skipLoopIndex = false
continue
}
if (!isFormatCharFound && charArray!![index].toString().equals(" ") && charArray!![index + 1].toString().equals("*")) {
isFormatCharFound = true
skipLoopIndex = true
formatPositions.add(index + 1)
} else if (isFormatCharFound && charArray!![index].toString().equals("*") && charArray!![index + 1].toString().equals(" ")) {
formatPositions.add(index)
skipLoopIndex = true
isFormatCharFound = false
}
}
return formatPositions
}
private fun removeAllFormatCharacters(preFormattedString: String): StringBuilder {
var stringWithRemovedFormatCharacters = StringBuilder(preFormattedString)
var decValue = 0
for (index in 0..formatPositions.size - 1) {
stringWithRemovedFormatCharacters = StringBuilder(stringWithRemovedFormatCharacters.removeRange(formatPositions[index] - decValue, formatPositions[index] + 1 - decValue))
decValue += 1
formatPositions[index] = formatPositions[index] - decValue
}
return stringWithRemovedFormatCharacters
}
}
| 0 | Java | 5 | 3 | 44f1bdd5af887302448b0fad00ab180b0fe98526 | 3,405 | fugu-android | Apache License 2.0 |
fearless-utils/src/test/java/jp/co/soramitsu/fearless_utils/encrypt/ECDSAUtilsTest.kt | novasamatech | 429,839,517 | false | {"Kotlin": 630308, "Rust": 10890, "Java": 4260} | package jp.co.soramitsu.fearless_utils.encrypt
import jp.co.soramitsu.fearless_utils.encrypt.keypair.ECDSAUtils
import org.bouncycastle.util.encoders.Hex
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
import java.math.BigInteger
@RunWith(MockitoJUnitRunner::class)
class ECDSAUtilsTest {
@Test
fun `should create compressed public key with leading zero bits`() {
val seed =
BigInteger("92cf62b905b27f71494c539e50545b3a3265d9b34a6865a2460c242b75cfc9b9", 16)
val expectedPublicKey = "<KEY>"
val publicKey = Hex.toHexString(ECDSAUtils.compressedPublicKeyFromPrivate(seed))
assertEquals(expectedPublicKey, publicKey)
}
} | 3 | Kotlin | 5 | 5 | da027e7418e98ee558c48263eb954368031680e7 | 765 | substrate-sdk-android | Apache License 2.0 |
core/src/main/kotlin/run/qontract/core/DiscardExampleDeclarations.kt | masaldaan | 294,952,483 | true | {"Kotlin": 895402, "Gherkin": 2586} | package run.qontract.core
class DiscardExampleDeclarations : ExampleDeclarations {
override fun plus(more: ExampleDeclarations): ExampleDeclarations = more
override fun plus(more: Pair<String, String>): ExampleDeclarations = this
override fun getNewName(typeName: String, keys: Collection<String>): String = typeName
override val messages: List<String> = emptyList()
override val examples: Map<String, String> = emptyMap()
}
| 0 | Kotlin | 0 | 0 | f3614c22af37821525eb00ebf9ccd03f3daba2f2 | 446 | qontract | MIT License |
libnavigation-core/src/test/java/com/mapbox/navigation/core/trip/model/roadobject/RestStopTest.kt | bikemap | 335,976,180 | true | {"Kotlin": 2691763, "Java": 72665, "Python": 11557, "Makefile": 6135, "JavaScript": 2362, "Shell": 1686} | package com.mapbox.navigation.core.trip.model.roadobject
import com.mapbox.navigation.core.trip.model.roadobject.reststop.RestStop
import com.mapbox.navigation.core.trip.model.roadobject.reststop.RestStopType
import com.mapbox.navigation.testing.BuilderTest
import io.mockk.mockk
import org.junit.Assert.assertEquals
import org.junit.Test
class RestStopTest : BuilderTest<RestStop, RestStop.Builder>() {
override fun getImplementationClass() = RestStop::class
override fun getFilledUpBuilder() = RestStop.Builder(
(mockk(relaxed = true)),
RestStopType.REST_AREA
)
.distanceFromStartOfRoute(123.0)
@Test
override fun trigger() {
// see docs
}
@Test
fun `distanceFromStartOfRoute is null if negative value passed`() {
val restStop = RestStop.Builder(mockk(), RoadObjectType.REST_STOP)
.distanceFromStartOfRoute(-1.0)
.build()
assertEquals(null, restStop.distanceFromStartOfRoute)
}
@Test
fun `distanceFromStartOfRoute is null if null passed`() {
val restStop = RestStop.Builder(mockk(), RoadObjectType.REST_STOP)
.distanceFromStartOfRoute(null)
.build()
assertEquals(null, restStop.distanceFromStartOfRoute)
}
@Test
fun `distanceFromStartOfRoute not null if positive value passed`() {
val restStop = RestStop.Builder(mockk(), RoadObjectType.REST_STOP)
.distanceFromStartOfRoute(1.0)
.build()
assertEquals(1.0, restStop.distanceFromStartOfRoute)
}
}
| 0 | Kotlin | 0 | 0 | 5de9c3c9484466b641ab8907ce9ed316598bad56 | 1,569 | mapbox-navigation-android | Apache License 2.0 |
src/main/kotlin/g0701_0800/s0738_monotone_increasing_digits/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0701_0800.s0738_monotone_increasing_digits
// #Medium #Math #Greedy #2023_03_03_Time_127_ms_(100.00%)_Space_32.9_MB_(100.00%)
@Suppress("NAME_SHADOWING")
class Solution {
fun monotoneIncreasingDigits(n: Int): Int {
var n = n
var i = 10
while (n / i > 0) {
val digit = n / i % 10
val endNum = n % i
val firstEndNum = endNum * 10 / i
if (digit > firstEndNum) {
n -= endNum + 1
}
i *= 10
}
return n
}
}
| 0 | Kotlin | 20 | 43 | e8b08d4a512f037e40e358b078c0a091e691d88f | 547 | LeetCode-in-Kotlin | MIT License |
src/main/java/uk/ac/cam/cl/bravo/overlay/InnerWarpTransformer.kt | jjurm | 166,785,284 | false | null | package uk.ac.cam.cl.bravo.overlay
import com.jhlabs.image.WarpFilter
import com.jhlabs.image.WarpGrid
import uk.ac.cam.cl.bravo.util.ImageTools
import java.awt.Color
import java.awt.Point
import java.awt.image.BufferedImage
class InnerWarpTransformer(
parameterScale: Double,
parameterPenaltyScale: Double,
/** number of flexible points in one dimension */
private val resolution: Int
) : AbstractTransformer(parameterScale, parameterPenaltyScale) {
// number of flexible+fixed points in one dimension (points at the edges are fixed)
private val SIZE = resolution + 2
// flexible points (in principle resolution in two dimensions)
private val FLEXIBLE = resolution * resolution
// total number of points in the grid
private val GRID_POINTS = SIZE * SIZE
override val parameterCount get() = FLEXIBLE * 2 // X, Y coordinates for each grid point
override val initialGuess0
get() = List(FLEXIBLE * 2) { 0.0 }
override val minBounds0 get() = List(FLEXIBLE * 2) { -1.0 }
override val maxBounds0 get() = List(FLEXIBLE * 2) { 1.0 }
private fun paramsToGrid(parameters: DoubleArray, planeSize: Point): WarpGrid {
val dstGrid = WarpGrid(SIZE, SIZE, planeSize.x, planeSize.y)
(0 until FLEXIBLE).forEach { i ->
val x = i % resolution
val y = i / resolution
dstGrid.xGrid[(y + 1) * SIZE + (x + 1)] += (parameters[i] * planeSize.x).toFloat()
dstGrid.yGrid[(y + 1) * SIZE + (x + 1)] += (parameters[FLEXIBLE + i] * planeSize.y).toFloat()
}
return dstGrid
}
override fun transform0(image: BufferedImage, parameters: DoubleArray, planeSize: Point): BufferedImage {
val srcGrid = WarpGrid(SIZE, SIZE, planeSize.x, planeSize.y)
val dstGrid = paramsToGrid(parameters, planeSize)
val filter = WarpFilter(srcGrid, dstGrid)
return filter.filter(image, ImageTools.getPlaneImage(planeSize))
}
fun drawMarks(image: BufferedImage, params: DoubleArray, planeSize: Point) {
val grid = paramsToGrid(rescaleIn(params), planeSize)
val size = 5
fun pointX(x: Int, y: Int) = grid.xGrid[y * SIZE + x].toInt()
fun pointY(x: Int, y: Int) = grid.yGrid[y * SIZE + x].toInt()
ImageTools.withGraphics(image) {
color = Color.blue
for (y in 0 until SIZE) {
for (x in 0 until SIZE) {
fillOval(
pointX(x, y) - size / 2,
pointY(x, y) - size / 2,
size,
size
)
}
}
// vertical lines
for (y in 0 until (SIZE - 1)) {
for (x in 0 until SIZE) {
drawLine(pointX(x, y), pointY(x, y), pointX(x, y + 1), pointY(x, y + 1))
}
}
// horizontal lines
for (y in 0 until SIZE) {
for (x in 0 until (SIZE - 1)) {
drawLine(pointX(x, y), pointY(x, y), pointX(x + 1, y), pointY(x + 1, y))
}
}
}
}
}
| 0 | null | 2 | 2 | f08b2a7f57062f14301ae12c9e5295ffa4016aab | 3,169 | bonedoctor | MIT License |
app/src/main/java/com/codrutursache/casey/data/remote/repository/ProfileRepositoryImpl.kt | ursachecodrut | 739,025,706 | false | {"Kotlin": 104275} | package com.codrutursache.casey.data.remote.repository
import android.util.Log
import com.codrutursache.casey.data.remote.model.User
import com.codrutursache.casey.data.remote.response.RecipeInformationResponse
import com.codrutursache.casey.data.remote.response.RecipeResponse
import com.codrutursache.casey.data.remote.service.SpoonacularService
import com.codrutursache.casey.domain.model.UserDetails
import com.codrutursache.casey.domain.repository.ProfileRepository
import com.codrutursache.casey.util.Constants.LOGGING_INTERCEPTOR_TAG
import com.codrutursache.casey.util.Constants.SAVED_RECIPES_FIELD
import com.codrutursache.casey.util.Constants.USERS_COLLECTION
import com.codrutursache.casey.util.Response
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.toObject
import kotlinx.coroutines.tasks.await
import okhttp3.internal.wait
import javax.inject.Inject
class ProfileRepositoryImpl @Inject constructor(
private val auth: FirebaseAuth,
private val firestore: FirebaseFirestore,
) : ProfileRepository {
override val userId = auth.currentUser?.uid
override val userDetails: UserDetails
get() = UserDetails(
displayName = auth.currentUser?.displayName,
photoUrl = auth.currentUser?.photoUrl.toString()
)
override suspend fun getSavedRecipesIds(): Response<List<RecipeResponse>> = try {
val recipe = firestore
.collection(USERS_COLLECTION)
.document(userId ?: "")
.get()
.await()
.toObject<User>()
?.savedRecipes
Response.Success(recipe)
} catch (e: Exception) {
Response.Failure(e)
}
} | 0 | Kotlin | 0 | 1 | f47a35989af88b37f81f4d9705fff4d6ac61a5ef | 1,752 | casey | MIT License |
feature/characters/src/main/kotlin/app/rickandmorty/characters/CharactersNavigation.kt | simonlebras | 628,022,976 | false | null | package app.rickandmorty.characters
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptions
import androidx.navigation.compose.composable
public const val charactersRoute: String = "characters"
public fun NavController.navigateToCharacters(navOptions: NavOptions? = null) {
navigate(charactersRoute, navOptions)
}
public fun NavGraphBuilder.characters() {
composable(route = charactersRoute) {
CharactersScreen()
}
}
| 6 | Kotlin | 0 | 0 | 848b0c62d97a210118fa342d60802fc26bcaf28c | 507 | rickandmorty | MIT License |
src/test/kotlin/com/blueanvil/kerch/AdminTest.kt | blueanvil | 163,659,278 | false | null | package com.blueanvil.kerch
import com.blueanvil.kerch.error.IndexError
import com.blueanvil.kerch.nestie.NestieDoc
import org.elasticsearch.index.query.QueryBuilders.matchQuery
import org.elasticsearch.index.query.QueryBuilders.termQuery
import org.testng.Assert.*
import org.testng.annotations.Test
/**
* @author <NAME>
*/
class AdminTest : TestBase() {
@Test
fun readOnlyIndex() {
val store = store()
batchIndex(store, 100) { Person(faker) }
store.readOnly = true
wait("Index not read only") { store.readOnly }
}
@Test(expectedExceptions = [IndexError::class])
fun readOnlyWrite() {
val store = store()
batchIndex(store, 1) { Person(faker) }
store.readOnly = true
wait("Index not read only") { store.readOnly }
batchIndex(store, 1) { Person(faker) }
}
@Test
fun readOnlyOnOff() {
val store = store()
batchIndex(store, 1) { Person(faker) }
store.readOnly = true
wait("Index not read only") { store.readOnly }
store.readOnly = false
wait("Index still read only") { !store.readOnly }
batchIndex(store, 1) { Person(faker) }
assertEquals(store.count(), 1)
}
@Test
fun listIndices() {
val index1 = uuid()
kerch.admin.createIndex(index1)
val index2 = uuid()
kerch.admin.createIndex(index2)
val index3 = uuid()
kerch.admin.createIndex(index3)
val names = kerch.admin.allIndices().map { it.name }
assertTrue(names.contains(index1))
assertTrue(names.contains(index2))
assertTrue(names.contains(index3))
}
@Test
fun saveTemplateAndReindex() {
val alias = "savetemplateandreindex"
val templateName = "savetemplateandreindex-template"
val template1 = resourceAsString("template-update1.json")
val template2 = resourceAsString("template-update2.json")
val indexWrapper = kerch.indexWrapper(alias, 1)
indexWrapper.initialise()
val index1 = indexWrapper.currentIndex
kerch.admin.createTemplate(templateName, template1)
nestie.store(TemplateUpdateTestDoc::class, alias)
val nestieStore = nestie.store(TemplateUpdateTestDoc::class, alias)
nestieStore.save(TemplateUpdateTestDoc("<NAME>"), true)
nestieStore.save(TemplateUpdateTestDoc("<NAME>"), true)
val nameField = TemplateUpdateTestDoc::class.nestieField("name")
assertEquals(nestieStore.count(matchQuery(nameField, "<NAME>")), 2)
assertEquals(nestieStore.count(termQuery(nameField, "<NAME>")), 0)
assertEquals(nestieStore.count(termQuery(nameField, "<NAME>")), 0)
kerch.admin.saveTemplateAndReindex(templateName, template2)
assertFalse(kerch.admin.indexExists(index1))
assertTrue(kerch.admin.indexExists(indexWrapper.currentIndex))
assertNotEquals(index1, indexWrapper.currentIndex)
val newStore = nestie.store(TemplateUpdateTestDoc::class, alias)
assertEquals(newStore.count(termQuery(nameField, "<NAME>")), 1)
assertEquals(newStore.count(termQuery(nameField, "<NAME>")), 1)
// Now test that we can update the template but no reindexing is done
val beforeSecondUpdate = indexWrapper.currentIndex
kerch.admin.saveTemplateAndReindex(templateName, template2)
assertEquals(beforeSecondUpdate, indexWrapper.currentIndex)
}
}
@NestieDoc(type = "template-update-test")
data class TemplateUpdateTestDoc(val name: String, val id: String = uuid())
| 0 | Kotlin | 0 | 0 | 4b3eb2f91b26d4b85d41ff8f5427a3ccbf3f3616 | 3,589 | kerch | Apache License 2.0 |
src/main/kotlin/io/github/rxcats/aws/dynamodb/query/DynamoDbPageQueryParam.kt | rxcats | 837,469,929 | false | {"Kotlin": 45450} | package io.github.rxcats.aws.dynamodb.query
import software.amazon.awssdk.enhanced.dynamodb.Key
data class DynamoDbPageQueryParam(
val key: Key,
val queryConditional: DynamoDbQueryConditional,
val limit: Int = 10,
val sort: DynamoDbSortDirection = DynamoDbSortDirection.ASC,
)
| 0 | Kotlin | 0 | 0 | a034e829776603e16a8a95182daa88ac27512a36 | 295 | dynamodb-kotlin-module | Apache License 2.0 |
src/main/kotlin/com/github/tyrrx/buntenachtaddr/language/resolve/SymbolReference.kt | bluehands | 509,068,691 | false | null | package com.github.tyrrx.buntenachtaddr.language.resolve
import com.github.tyrrx.buntenachtaddr.language.psi.AddRNamedElement
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
class SymbolReference(private val referencingElement: AddRNamedElement) : PsiReference {
override fun getElement(): PsiElement {
return referencingElement
}
override fun getRangeInElement(): TextRange {
return referencingElement.textRangeInParent
}
override fun resolve(): PsiElement? {
val resolveSymbolVisitor = ResolveSymbolReferenceInParentVisitor(referencingElement)
referencingElement.accept(resolveSymbolVisitor)
return resolveSymbolVisitor.resolvedElement
}
override fun getCanonicalText(): String {
return referencingElement.name ?: ""
}
override fun handleElementRename(newElementName: String): PsiElement {
referencingElement.setName(newElementName)
return referencingElement
}
override fun bindToElement(element: PsiElement): PsiElement {
TODO("Not yet implemented")
}
override fun isReferenceTo(element: PsiElement): Boolean {
return element == resolve()
}
override fun isSoft(): Boolean {
return false
}
} | 0 | Kotlin | 0 | 0 | 8eeab90ad55326035071968dde3036f8f4476a92 | 1,321 | Sample-language-plugin-for-IntelliJ | Apache License 2.0 |
app/src/main/java/dk/ku/sund/smartsleep/model/AuthLoginBody.kt | smartsleep | 195,872,393 | false | null | package dk.ku.sund.smartsleep.model
data class AuthLoginBody(
var email: String,
var password: String,
var clientId: String,
var clientSecret: String,
var attendeeCode: String
)
| 0 | Kotlin | 1 | 0 | fe3ab0d5490a935dcbed2aef319577499fd6e840 | 199 | android | MIT License |
app/src/main/java/cz/fontan/gomoku_gui/model/MainViewModel.kt | Hexik | 369,313,533 | false | {"C++": 723092, "Kotlin": 72860, "CMake": 6436, "Java": 598} | package cz.fontan.gomoku_gui.model
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.*
import androidx.preference.PreferenceManager
import cz.fontan.gomoku_gui.InterfaceMainViewModel
import cz.fontan.gomoku_gui.NativeInterface
import cz.fontan.gomoku_gui.R
import cz.fontan.gomoku_gui.game.BOARD_SIZE_MAX
import cz.fontan.gomoku_gui.game.EnumMove
import cz.fontan.gomoku_gui.game.Game
import cz.fontan.gomoku_gui.game.Move
import kotlinx.coroutines.Dispatchers
/**
* ViewModel, current game status, can be saved and restored
*/
class MainViewModel(application: Application) : AndroidViewModel(application),
InterfaceMainViewModel {
private val game = Game(BOARD_SIZE_MAX)
// LiveData variables
private val _isDirty = MutableLiveData<Boolean>()
/**
* Model was changed
*/
val isDirty: LiveData<Boolean>
get() = _isDirty
private val _canSearch = MutableLiveData<Boolean>()
/**
* canSearch status
*/
val canSearch: LiveData<Boolean>
get() = _canSearch
private val _canStop = MutableLiveData<Boolean>()
/**
* canStop status
*/
val canStop: LiveData<Boolean>
get() = _canStop
private val _canRedo = MutableLiveData<Boolean>()
/**
* canRedo status
*/
val canRedo: LiveData<Boolean>
get() = _canRedo
private val _canUndo = MutableLiveData<Boolean>()
/**
* canUndo status
*/
val canUndo: LiveData<Boolean>
get() = _canUndo
private val _msgDepth = MutableLiveData<String>()
/**
* Current search depth parsed from message
*/
val msgDepth: LiveData<String>
get() = _msgDepth
private val _msgEval = MutableLiveData<String>()
/**
* Current search evaluation parsed from message
*/
val msgEval: LiveData<String>
get() = _msgEval
private val _msgNodes = MutableLiveData<String>()
/**
* Current node count parsed from message
*/
val msgNodes: LiveData<String>
get() = _msgNodes
private val _msgSpeed = MutableLiveData<String>()
/**
* Current search speed in N/ms parsed from message
*/
val msgSpeed: LiveData<String>
get() = _msgSpeed
private val _msgResult = MutableLiveData<String>()
/**
* Game result as answer from brain
*/
val msgResult: LiveData<String>
get() = _msgResult
private val isRunningTest: Boolean by lazy {
try {
Class.forName("androidx.test.espresso.Espresso")
true
} catch (e: ClassNotFoundException) {
false
}
}
private val _dataFromBrain = AnswersRepository(isRunningTest)
.fetchStrings()
.asLiveData(
// Use Default dispatcher for CPU intensive work and
// viewModel scope for auto cancellation when viewModel
// is destroyed
Dispatchers.Default + viewModelScope.coroutineContext
)
/**
* LiveData from C++ brain, messages sent from brain
*/
val dataFromBrain: LiveData<ConsumableValue<String>>
get() = _dataFromBrain
// Settings variables
private val sharedPreferences: SharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getApplication<Application>().applicationContext)
private var autoBlack: Boolean = false
private var autoWhite: Boolean = false
private var stopWasPressed = false
private var inSearch: Boolean = false
init {
loadGamePrivate()
afterAction()
}
/**
* Start search if possible, current position is sent to brain
*/
fun startSearch(forceSearch: Boolean) {
if (!inSearch && (!stopWasPressed || forceSearch)) {
inSearch = true
_canSearch.value = false
_canStop.value = true
_canUndo.value = false
_canRedo.value = false
stopWasPressed = false
NativeInterface.writeToBrain(game.toBoard(true))
_isDirty.value = true
} else {
setIdleStatus()
}
}
/**
* Stop running search, the brain should understand the YXSTOP command
*/
fun stopSearch() {
NativeInterface.writeToBrain("YXSTOP")
queryGameResult()
setIdleStatus()
stopWasPressed = true
}
/**
* @see Game.undoMove
*/
fun undoMove() {
game.undoMove()
stopWasPressed = false
afterAction()
}
/**
* @see Game.redoMove
*/
fun redoMove() {
game.redoMove()
afterAction()
}
/**
* Start new game, init C++ brain
*/
fun newGame() {
game.newGame()
stopWasPressed = false
NativeInterface.writeToBrain("start ${game.dim}")
afterAction()
}
private fun afterAction() {
NativeInterface.writeToBrain(game.toBoard(false))
queryGameResult()
setIdleStatus()
}
private fun setIdleStatus() {
inSearch = false
_canStop.value = false
_canUndo.value = game.canUndo()
_canRedo.value = game.canRedo()
_isDirty.value = true
}
private fun readSettings() {
autoBlack = sharedPreferences.getBoolean("check_box_preference_AI_black", false)
autoWhite = sharedPreferences.getBoolean("check_box_preference_AI_white", false)
val tmpDim = getDimension()
if (tmpDim != game.dim) {
game.dim = tmpDim
newGame()
}
}
// InterfaceMain overrides
override fun canMakeMove(move: Move): Boolean {
return game.canMakeMove(move)
}
override fun makeMove(move: Move) {
game.makeMove(move)
queryGameResult()
when {
autoBlack && game.playerToMove == EnumMove.Black -> startSearch(false)
autoWhite && game.playerToMove == EnumMove.White -> startSearch(false)
else -> setIdleStatus()
}
stopWasPressed = false
_isDirty.value = true
}
override fun refresh() {
readSettings()
}
private fun queryGameResult() {
NativeInterface.writeToBrain("YXRESULT")
val resp = NativeInterface.readFromBrain(10)
processResponse(resp)
}
override fun moveCount(): Int {
return game.moveCount()
}
override fun getIthMove(i: Int): Move {
return game[i]
}
override fun isSearching(): Boolean {
return inSearch
}
/**
* Parse incoming data from brain
* @param response incoming data
*/
fun processResponse(response: String) {
val upper = response.uppercase()
when {
upper.startsWith("DEBUG ") -> return
upper.startsWith("ERROR ") -> return
upper.startsWith("FORBID ") -> return
upper.startsWith("MESSAGE ") -> parseMessage(upper.removePrefix("MESSAGE "))
upper.startsWith("OK") -> return
upper.startsWith("SUGGEST ") -> return
upper.startsWith("UNKNOWN") -> return
upper.contains("NAME") -> return // ABOUT response
else -> parseMoveResponse(upper)
}
}
private fun parseMessage(response: String) {
// MESSAGE ...
when {
response.startsWith("DEPTH ") -> parseStatus(response)
response.startsWith("REALTIME ") -> parseRealTime(response.removePrefix("REALTIME "))
response.startsWith("RESULT ") -> parseResult(response.removePrefix("RESULT "))
else -> return
}
}
private fun parseResult(response: String) {
// MESSAGE RESULT ...
var gameOver = true
when (response) {
"BLACK" -> _msgResult.value = getResourceString(R.string.result_black)
"WHITE" -> _msgResult.value = getResourceString(R.string.result_white)
"DRAW" -> _msgResult.value = getResourceString(R.string.result_draw)
else -> {
_msgResult.value = getResourceString(R.string.none)
gameOver = false
}
}
_canSearch.value = !gameOver
}
private fun getResourceString(resID: Int): String {
return getApplication<Application>().applicationContext.getString(resID)
}
private fun parseRealTime(response: String) {
// MESSAGE REALTIME ...
when {
response.startsWith("BEST ") -> return
response.startsWith("LOSE ") -> return
response.startsWith("POS ") -> return
response.startsWith("PV ") -> return
response.startsWith("REFRESH") -> return
else -> return
}
}
private fun parseStatus(response: String) {
// MESSAGE [DEPTH] ...
val splitted = response.split(" ")
val it = splitted.iterator()
// Caution: the message should be well-formed
while (it.hasNext()) {
when (it.next()) {
"DEPTH" -> _msgDepth.value = it.next()
"EV" -> _msgEval.value = it.next()
"N" -> _msgNodes.value = it.next()
"N/MS" -> _msgSpeed.value = it.next()
}
}
}
private fun parseMoveResponse(response: String) {
// x,y
Log.v("Res", response)
val splitted = response.split(",")
try {
require(splitted.size == 2)
inSearch = false
makeMove(Move(splitted[0].toInt(), splitted[1].toInt()))
} catch (e: IllegalArgumentException) {
Log.wtf("Res", response)
}
}
/**
* When the instance is cleared, the game is saved
*/
override fun onCleared() {
super.onCleared()
Log.i("MainVM", "onCleared")
saveGamePrivate()
}
/**
* Serialize game
* @see Game.toStream
*/
fun getGameAsStream(): String {
return game.toStream()
}
/**
* Save current position as shared preference
*/
fun saveGamePrivate() {
val sharedPreference =
getApplication<Application>().applicationContext.getSharedPreferences(
"GAME_DATA",
Context.MODE_PRIVATE
)
sharedPreference.edit().putString("Moves", game.toStream()).apply()
}
/**
* Set game position from external data string
*/
fun loadGameFromStream(data: String?) {
try {
game.fromStream(data)
afterAction()
} catch (e: IllegalArgumentException) {
game.reset()
Log.wtf("Load", data)
Toast.makeText(
getApplication<Application>().applicationContext,
"Wrong game size!",
Toast.LENGTH_SHORT
).show()
}
}
private fun loadGamePrivate() {
val sharedPreference =
getApplication<Application>().applicationContext.getSharedPreferences(
"GAME_DATA",
Context.MODE_PRIVATE
)
try {
game.dim = getDimension()
NativeInterface.writeToBrain("start ${game.dim}")
game.fromStream(sharedPreference.getString("Moves", "")?.trimMargin())
} catch (e: IllegalArgumentException) {
game.reset()
Log.wtf("Load", "Private")
}
}
private fun getDimension(): Int {
val defaultDimension = getResourceString(R.string.default_board).toInt()
return sharedPreferences.getString(
"list_preference_board_size",
defaultDimension.toString()
)?.toInt() ?: defaultDimension
}
} | 0 | C++ | 1 | 2 | 36940e0d5390cc8ca91370535993ee278ec6a288 | 11,798 | Gomoku_GUI | MIT License |
app/src/main/java/cz/fontan/gomoku_gui/model/MainViewModel.kt | Hexik | 369,313,533 | false | {"C++": 723092, "Kotlin": 72860, "CMake": 6436, "Java": 598} | package cz.fontan.gomoku_gui.model
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.*
import androidx.preference.PreferenceManager
import cz.fontan.gomoku_gui.InterfaceMainViewModel
import cz.fontan.gomoku_gui.NativeInterface
import cz.fontan.gomoku_gui.R
import cz.fontan.gomoku_gui.game.BOARD_SIZE_MAX
import cz.fontan.gomoku_gui.game.EnumMove
import cz.fontan.gomoku_gui.game.Game
import cz.fontan.gomoku_gui.game.Move
import kotlinx.coroutines.Dispatchers
/**
* ViewModel, current game status, can be saved and restored
*/
class MainViewModel(application: Application) : AndroidViewModel(application),
InterfaceMainViewModel {
private val game = Game(BOARD_SIZE_MAX)
// LiveData variables
private val _isDirty = MutableLiveData<Boolean>()
/**
* Model was changed
*/
val isDirty: LiveData<Boolean>
get() = _isDirty
private val _canSearch = MutableLiveData<Boolean>()
/**
* canSearch status
*/
val canSearch: LiveData<Boolean>
get() = _canSearch
private val _canStop = MutableLiveData<Boolean>()
/**
* canStop status
*/
val canStop: LiveData<Boolean>
get() = _canStop
private val _canRedo = MutableLiveData<Boolean>()
/**
* canRedo status
*/
val canRedo: LiveData<Boolean>
get() = _canRedo
private val _canUndo = MutableLiveData<Boolean>()
/**
* canUndo status
*/
val canUndo: LiveData<Boolean>
get() = _canUndo
private val _msgDepth = MutableLiveData<String>()
/**
* Current search depth parsed from message
*/
val msgDepth: LiveData<String>
get() = _msgDepth
private val _msgEval = MutableLiveData<String>()
/**
* Current search evaluation parsed from message
*/
val msgEval: LiveData<String>
get() = _msgEval
private val _msgNodes = MutableLiveData<String>()
/**
* Current node count parsed from message
*/
val msgNodes: LiveData<String>
get() = _msgNodes
private val _msgSpeed = MutableLiveData<String>()
/**
* Current search speed in N/ms parsed from message
*/
val msgSpeed: LiveData<String>
get() = _msgSpeed
private val _msgResult = MutableLiveData<String>()
/**
* Game result as answer from brain
*/
val msgResult: LiveData<String>
get() = _msgResult
private val isRunningTest: Boolean by lazy {
try {
Class.forName("androidx.test.espresso.Espresso")
true
} catch (e: ClassNotFoundException) {
false
}
}
private val _dataFromBrain = AnswersRepository(isRunningTest)
.fetchStrings()
.asLiveData(
// Use Default dispatcher for CPU intensive work and
// viewModel scope for auto cancellation when viewModel
// is destroyed
Dispatchers.Default + viewModelScope.coroutineContext
)
/**
* LiveData from C++ brain, messages sent from brain
*/
val dataFromBrain: LiveData<ConsumableValue<String>>
get() = _dataFromBrain
// Settings variables
private val sharedPreferences: SharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getApplication<Application>().applicationContext)
private var autoBlack: Boolean = false
private var autoWhite: Boolean = false
private var stopWasPressed = false
private var inSearch: Boolean = false
init {
loadGamePrivate()
afterAction()
}
/**
* Start search if possible, current position is sent to brain
*/
fun startSearch(forceSearch: Boolean) {
if (!inSearch && (!stopWasPressed || forceSearch)) {
inSearch = true
_canSearch.value = false
_canStop.value = true
_canUndo.value = false
_canRedo.value = false
stopWasPressed = false
NativeInterface.writeToBrain(game.toBoard(true))
_isDirty.value = true
} else {
setIdleStatus()
}
}
/**
* Stop running search, the brain should understand the YXSTOP command
*/
fun stopSearch() {
NativeInterface.writeToBrain("YXSTOP")
queryGameResult()
setIdleStatus()
stopWasPressed = true
}
/**
* @see Game.undoMove
*/
fun undoMove() {
game.undoMove()
stopWasPressed = false
afterAction()
}
/**
* @see Game.redoMove
*/
fun redoMove() {
game.redoMove()
afterAction()
}
/**
* Start new game, init C++ brain
*/
fun newGame() {
game.newGame()
stopWasPressed = false
NativeInterface.writeToBrain("start ${game.dim}")
afterAction()
}
private fun afterAction() {
NativeInterface.writeToBrain(game.toBoard(false))
queryGameResult()
setIdleStatus()
}
private fun setIdleStatus() {
inSearch = false
_canStop.value = false
_canUndo.value = game.canUndo()
_canRedo.value = game.canRedo()
_isDirty.value = true
}
private fun readSettings() {
autoBlack = sharedPreferences.getBoolean("check_box_preference_AI_black", false)
autoWhite = sharedPreferences.getBoolean("check_box_preference_AI_white", false)
val tmpDim = getDimension()
if (tmpDim != game.dim) {
game.dim = tmpDim
newGame()
}
}
// InterfaceMain overrides
override fun canMakeMove(move: Move): Boolean {
return game.canMakeMove(move)
}
override fun makeMove(move: Move) {
game.makeMove(move)
queryGameResult()
when {
autoBlack && game.playerToMove == EnumMove.Black -> startSearch(false)
autoWhite && game.playerToMove == EnumMove.White -> startSearch(false)
else -> setIdleStatus()
}
stopWasPressed = false
_isDirty.value = true
}
override fun refresh() {
readSettings()
}
private fun queryGameResult() {
NativeInterface.writeToBrain("YXRESULT")
val resp = NativeInterface.readFromBrain(10)
processResponse(resp)
}
override fun moveCount(): Int {
return game.moveCount()
}
override fun getIthMove(i: Int): Move {
return game[i]
}
override fun isSearching(): Boolean {
return inSearch
}
/**
* Parse incoming data from brain
* @param response incoming data
*/
fun processResponse(response: String) {
val upper = response.uppercase()
when {
upper.startsWith("DEBUG ") -> return
upper.startsWith("ERROR ") -> return
upper.startsWith("FORBID ") -> return
upper.startsWith("MESSAGE ") -> parseMessage(upper.removePrefix("MESSAGE "))
upper.startsWith("OK") -> return
upper.startsWith("SUGGEST ") -> return
upper.startsWith("UNKNOWN") -> return
upper.contains("NAME") -> return // ABOUT response
else -> parseMoveResponse(upper)
}
}
private fun parseMessage(response: String) {
// MESSAGE ...
when {
response.startsWith("DEPTH ") -> parseStatus(response)
response.startsWith("REALTIME ") -> parseRealTime(response.removePrefix("REALTIME "))
response.startsWith("RESULT ") -> parseResult(response.removePrefix("RESULT "))
else -> return
}
}
private fun parseResult(response: String) {
// MESSAGE RESULT ...
var gameOver = true
when (response) {
"BLACK" -> _msgResult.value = getResourceString(R.string.result_black)
"WHITE" -> _msgResult.value = getResourceString(R.string.result_white)
"DRAW" -> _msgResult.value = getResourceString(R.string.result_draw)
else -> {
_msgResult.value = getResourceString(R.string.none)
gameOver = false
}
}
_canSearch.value = !gameOver
}
private fun getResourceString(resID: Int): String {
return getApplication<Application>().applicationContext.getString(resID)
}
private fun parseRealTime(response: String) {
// MESSAGE REALTIME ...
when {
response.startsWith("BEST ") -> return
response.startsWith("LOSE ") -> return
response.startsWith("POS ") -> return
response.startsWith("PV ") -> return
response.startsWith("REFRESH") -> return
else -> return
}
}
private fun parseStatus(response: String) {
// MESSAGE [DEPTH] ...
val splitted = response.split(" ")
val it = splitted.iterator()
// Caution: the message should be well-formed
while (it.hasNext()) {
when (it.next()) {
"DEPTH" -> _msgDepth.value = it.next()
"EV" -> _msgEval.value = it.next()
"N" -> _msgNodes.value = it.next()
"N/MS" -> _msgSpeed.value = it.next()
}
}
}
private fun parseMoveResponse(response: String) {
// x,y
Log.v("Res", response)
val splitted = response.split(",")
try {
require(splitted.size == 2)
inSearch = false
makeMove(Move(splitted[0].toInt(), splitted[1].toInt()))
} catch (e: IllegalArgumentException) {
Log.wtf("Res", response)
}
}
/**
* When the instance is cleared, the game is saved
*/
override fun onCleared() {
super.onCleared()
Log.i("MainVM", "onCleared")
saveGamePrivate()
}
/**
* Serialize game
* @see Game.toStream
*/
fun getGameAsStream(): String {
return game.toStream()
}
/**
* Save current position as shared preference
*/
fun saveGamePrivate() {
val sharedPreference =
getApplication<Application>().applicationContext.getSharedPreferences(
"GAME_DATA",
Context.MODE_PRIVATE
)
sharedPreference.edit().putString("Moves", game.toStream()).apply()
}
/**
* Set game position from external data string
*/
fun loadGameFromStream(data: String?) {
try {
game.fromStream(data)
afterAction()
} catch (e: IllegalArgumentException) {
game.reset()
Log.wtf("Load", data)
Toast.makeText(
getApplication<Application>().applicationContext,
"Wrong game size!",
Toast.LENGTH_SHORT
).show()
}
}
private fun loadGamePrivate() {
val sharedPreference =
getApplication<Application>().applicationContext.getSharedPreferences(
"GAME_DATA",
Context.MODE_PRIVATE
)
try {
game.dim = getDimension()
NativeInterface.writeToBrain("start ${game.dim}")
game.fromStream(sharedPreference.getString("Moves", "")?.trimMargin())
} catch (e: IllegalArgumentException) {
game.reset()
Log.wtf("Load", "Private")
}
}
private fun getDimension(): Int {
val defaultDimension = getResourceString(R.string.default_board).toInt()
return sharedPreferences.getString(
"list_preference_board_size",
defaultDimension.toString()
)?.toInt() ?: defaultDimension
}
} | 0 | C++ | 1 | 2 | 36940e0d5390cc8ca91370535993ee278ec6a288 | 11,798 | Gomoku_GUI | MIT License |
src/main/kotlin/com/webperformance/muse/measurements/stepduration/StepDurations.kt | ChrisLMerrill | 105,173,031 | false | null | package com.webperformance.muse.measurements.stepduration
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.databind.ObjectMapper
import org.musetest.core.datacollection.TestResultData
import java.io.InputStream
import java.io.OutputStream
class StepDurations : TestResultData
{
val durations: MutableMap<Long, MutableList<Long>> = mutableMapOf()
private var name: String = "StepDurations"
override fun getName(): String
{
return name
}
override fun setName(name: String)
{
this.name = name
}
override fun suggestFilename(): String
{
return name + ".json"
}
override fun write(outstream: OutputStream)
{
val mapper = ObjectMapper()
mapper.writerWithDefaultPrettyPrinter().writeValue(outstream, this)
}
@JsonIgnore
fun getStepIds(): Set<Long>
{
return durations.keys
}
@JsonIgnore
fun getDurations(step_id: Long): List<Long>
{
val list = durations.get(step_id)
if (list == null)
return emptyList()
else
return list
}
override fun read(instream: InputStream): Any
{
val mapper = ObjectMapper()
return mapper.reader().readValue(instream)
}
fun record(stepid: Long, duration: Long)
{
var list = durations.get(stepid)
if (list == null)
{
list = mutableListOf()
durations.put(stepid, list)
}
list.add(duration)
}
} | 0 | Kotlin | 0 | 0 | a066b7c5add26b694b9f38ab5db9563284ec92b6 | 1,328 | muse-webperformance-measurements | Apache License 2.0 |
src/main/kotlin/miragefairy2024/mod/fairy/GainFairyDreamChannel.kt | MirageFairy | 721,291,232 | false | null | package miragefairy2024.mod.fairy
import miragefairy2024.MirageFairy2024
import miragefairy2024.util.Channel
import miragefairy2024.util.string
import miragefairy2024.util.toIdentifier
import net.minecraft.network.PacketByteBuf
object GainFairyDreamChannel : Channel<Motif>(MirageFairy2024.identifier("gain_fairy_dream")) {
override fun writeToBuf(buf: PacketByteBuf, packet: Motif) {
buf.writeString(packet.getIdentifier()!!.string)
}
override fun readFromBuf(buf: PacketByteBuf): Motif {
val motifId = buf.readString()
return motifRegistry.get(motifId.toIdentifier())!!
}
}
| 0 | null | 1 | 1 | 8ba4226085d367b2c34a4f2a3a41410a3e49a9ee | 619 | MirageFairy2024 | Apache License 2.0 |
app/src/main/java/com/knowledgeways/idocs/ui/main/search/SearchFragment.kt | mishashribak | 832,422,026 | false | {"Kotlin": 606406, "Java": 68502} | package com.knowledgeways.idocs.ui.main.search
import android.app.DatePickerDialog
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.recyclerview.widget.LinearLayoutManager
import com.github.msarhan.ummalqura.calendar.UmmalquraCalendar
import com.knowledgeways.idocs.R
import com.knowledgeways.idocs.base.BaseFragment
import com.knowledgeways.idocs.databinding.FragmentSearchBinding
import com.knowledgeways.idocs.db.PreferenceManager
import com.knowledgeways.idocs.di.Injectable
import com.knowledgeways.idocs.network.model.Category
import com.knowledgeways.idocs.network.model.theme.Theme
import com.knowledgeways.idocs.network.model.user.Organization
import com.knowledgeways.idocs.ui.component.dialog.documentType.CategoryAdapter
import com.knowledgeways.idocs.ui.component.dialog.documentType.CategoryPicker
import com.knowledgeways.idocs.ui.component.dialog.externalorganization.ExternalOrganizationPicker
import com.knowledgeways.idocs.ui.component.dialog.internalorganization.InternalOrganizationPicker
import com.knowledgeways.idocs.ui.component.dialog.organization.OrganizationAdapter
import com.knowledgeways.idocs.ui.main.MainActivity
import com.knowledgeways.idocs.ui.main.MainViewModel
import com.knowledgeways.idocs.utils.CommonUtils
import com.knowledgeways.idocs.utils.ResUtils
import java.text.SimpleDateFormat
import java.util.*
class SearchFragment : BaseFragment<FragmentSearchBinding?, MainViewModel>(), Injectable , OrganizationAdapter.OnOrganizationClickedListener,
CategoryAdapter.OnCategorySelectedListener{
override val layoutId: Int
get() = R.layout.fragment_search
override val viewModel: MainViewModel
get() {
return getViewModel(baseActivity, MainViewModel::class.java)
}
private var defaultTheme: Theme ?= null
lateinit var categoryAdapter: CategoryAdapter
lateinit var externalOrganizationAdapter: OrganizationAdapter
lateinit var internalOrganizationAdapter: OrganizationAdapter
lateinit var fromDatePicker: DatePickerDialog
lateinit var toDatePicker: DatePickerDialog
var fromTime = 0L
var toTime = 0L
var currentOrganizationDialogType = 1
var dateFormatToSave = SimpleDateFormat("yyyy-MM-dd")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
observeThemeData()
initValues()
iniUI()
}
private fun getToday(){
val date = Calendar.getInstance().time
val df = SimpleDateFormat("MMM dd, yyyy")
val formattedDate = df.format(date)
val dateToSave = dateFormatToSave.format(date)
viewModel.apply {
dateFrom = dateToSave
dateTo = dateToSave
dateFromHijri = convertToHijri(Calendar.getInstance())
dateToHijri = convertToHijri(Calendar.getInstance())
}
viewDataBinding?.apply {
tvFromDate.text = formattedDate
tvToDate.text = formattedDate
}
}
private fun observeThemeData(){
viewModel.isThemeChanged.observe(baseActivity){
initValues()
iniUI()
}
}
private fun initValues(){
defaultTheme = viewModel.getDefaultTheme()
}
private fun iniUI(){
initFromDatePicker()
initToDatePicker()
if (baseActivity.isTablet()){
initTapViewEvents()
}
viewDataBinding?.apply {
layoutChooseType.setOnClickListener {
if (baseActivity.isTablet()){
initParentTypeLayout()
viewDataBinding?.viewOverlay?.visibility = VISIBLE
viewDataBinding?.layoutParentDocumentType?.visibility = VISIBLE
}else{
CategoryPicker.openDialog(baseActivity, (baseActivity as MainActivity).toolbarColor,
defaultTheme?.popupForm!!.title!!.fgColor ?: "", {
category -> onSelected(category)
}, {
})
}
}
tvExternalOrganization.setOnClickListener {
currentOrganizationDialogType = 1
if (baseActivity.isTablet()){
initExternalOrganizationLayout()
viewDataBinding?.layoutExternalOrganization?.visibility = VISIBLE
}else{
ExternalOrganizationPicker.openDialog(baseActivity, (baseActivity as MainActivity).toolbarColor
, {
organization -> onExternalOrganizationSelected(organization)
}, {
viewDataBinding?.viewOverlay?.visibility = GONE
})
}
}
tvInternalOrganization.setOnClickListener {
currentOrganizationDialogType = 2
if (baseActivity.isTablet()){
initInternalOrganizationLayout()
viewDataBinding?.layoutInternalOrganization?.visibility = VISIBLE
}else{
InternalOrganizationPicker.openDialog(baseActivity, (baseActivity as MainActivity).toolbarColor
, {
organization -> onInternalOrganizationSelected(organization)
}, {
viewDataBinding?.viewOverlay?.visibility = GONE
})
}
}
layoutFrom.setOnClickListener {
hideOverLayouts()
if (toTime != 0L){
fromDatePicker.datePicker.maxDate = toTime
}
fromDatePicker.show()
}
layoutTo.setOnClickListener {
hideOverLayouts()
if (fromTime != 0L){
toDatePicker.datePicker.minDate = fromTime
}
toDatePicker.show()
}
}
getToday()
}
private fun initTapViewEvents(){
viewDataBinding?.apply {
viewOverlay?.setOnClickListener {
viewOverlay.visibility = GONE
layoutExternalOrganization?.visibility = GONE
layoutInternalOrganization?.visibility = GONE
layoutParentDocumentType?.visibility = GONE
}
edittextSearchKey.setOnFocusChangeListener { view, b ->
if (b) hideOverLayouts()
}
edittextReferenceNumber.setOnFocusChangeListener { view, b ->
if (b) hideOverLayouts()
}
layoutConfirm.setOnClickListener {
hideOverLayouts()
}
layoutOrganization.setOnClickListener {
hideOverLayouts()
}
tvOrganization.setOnClickListener {
hideOverLayouts()
}
layoutDate.setOnClickListener {
hideOverLayouts()
}
layoutReferenceNumber.setOnClickListener {
hideOverLayouts()
}
layoutSubject.setOnClickListener {
hideOverLayouts()
}
layoutDocumentType.setOnClickListener {
hideOverLayouts()
}
tvDocumentDate.setOnClickListener {
hideOverLayouts()
}
layoutContent.setOnClickListener {
hideOverLayouts()
}
layoutParent.setOnScrollChangeListener { _, _, _, _, _ ->
}
tvCancel.setOnClickListener {
onClearSelected()
}
tvSearch.setOnClickListener {
onSearchClicked()
}
dialogInternalOrganizations?.edittextSearch?.addTextChangedListener(
object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun afterTextChanged(textChanged: Editable?) {
if (::internalOrganizationAdapter.isInitialized){
internalOrganizationAdapter.setFilterString(textChanged.toString().trim())
}
}
}
)
dialogExternalOrganizations?.edittextSearch?.addTextChangedListener(
object : TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun afterTextChanged(textChanged: Editable?) {
if (::externalOrganizationAdapter.isInitialized){
externalOrganizationAdapter.setFilterString(textChanged.toString().trim())
}
}
}
)
}
}
private fun initFromDatePicker(){
val calendar = Calendar.getInstance()
// Set Date-Format for Picker Dialog
fromDatePicker = DatePickerDialog(
baseActivity,
R.style.DateTimePickerDialogStyle,
{ _, year, monthOfYear, dayOfMonth ->
val newDate = Calendar.getInstance()
newDate.set(year, monthOfYear, dayOfMonth)
val sd = SimpleDateFormat("MMM dd, yyyy", Locale.US)
val rawDate = newDate.time
val fdate = sd.format(rawDate)
val dateToSave = dateFormatToSave.format(rawDate)
viewDataBinding?.tvFromDate?.text = fdate
viewModel.dateFrom = dateToSave
fromTime = newDate.timeInMillis
viewModel.dateFromHijri = convertToHijri(newDate)
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
)
fromDatePicker.setTitle("")
}
private fun initToDatePicker(){
val calendar = Calendar.getInstance()
// Set Date-Format for Picker Dialog
toDatePicker = DatePickerDialog(
baseActivity,
R.style.DateTimePickerDialogStyle,
{ _, year, monthOfYear, dayOfMonth ->
val newDate = Calendar.getInstance()
newDate.set(year, monthOfYear, dayOfMonth)
val sd = SimpleDateFormat("MMM dd, yyyy", Locale.US)
val rawDate = newDate.time
val fdate = sd.format(rawDate)
viewDataBinding?.tvToDate?.text = fdate
toTime = newDate.timeInMillis
viewModel.dateToHijri = convertToHijri(newDate)
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(
Calendar.DAY_OF_MONTH
)
)
// Customer should be more than 6 years old
toDatePicker.setTitle("")
}
private fun hideOverLayouts(){
viewDataBinding?.layoutParentDocumentType?.visibility = GONE
}
private fun initExternalOrganizationLayout(){
viewDataBinding?.viewOverlay?.visibility = VISIBLE
viewDataBinding?.dialogExternalOrganizations?.apply {
ivBackground.setColorFilter(Color.parseColor((baseActivity as MainActivity).toolbarColor),
PorterDuff.Mode.SRC_IN)
recyclerView.layoutManager = LinearLayoutManager(baseActivity)
recyclerView.isNestedScrollingEnabled = false
initExternalOrganizationList()
}
}
private fun initExternalOrganizationList(){
externalOrganizationAdapter = OrganizationAdapter()
externalOrganizationAdapter.listener = this
viewDataBinding?.dialogExternalOrganizations?.recyclerView?.adapter = externalOrganizationAdapter
externalOrganizationAdapter.setItems(PreferenceManager.externalOrganization)
}
private fun initInternalOrganizationLayout(){
viewDataBinding?.viewOverlay?.visibility = VISIBLE
viewDataBinding?.dialogInternalOrganizations?.apply {
ivBackground.setColorFilter(Color.parseColor((baseActivity as MainActivity).toolbarColor),
PorterDuff.Mode.SRC_IN)
recyclerView.layoutManager = LinearLayoutManager(baseActivity)
recyclerView.isNestedScrollingEnabled = false
initInternalOrganizationList()
}
}
private fun initInternalOrganizationList(){
internalOrganizationAdapter = OrganizationAdapter()
internalOrganizationAdapter.listener = this
viewDataBinding?.dialogInternalOrganizations?.recyclerView?.adapter = internalOrganizationAdapter
internalOrganizationAdapter.setItems(PreferenceManager.internalOrganization)
}
private fun initParentTypeLayout(){
viewDataBinding?.dialogDocumentType?.apply {
tvTitle.setTextAppearance(ResUtils.getTextViewStyle(CommonUtils.getDefaultTheme()?.popupForm?.button?.bold!!))
tvTitle.setTextColor(Color.parseColor(defaultTheme?.popupForm!!.title!!.fgColor ?: ""))
ivBackground.setColorFilter(Color.parseColor((baseActivity as MainActivity).toolbarColor),
PorterDuff.Mode.SRC_IN)
triangle?.setColorFilter(Color.parseColor((baseActivity as MainActivity).toolbarColor),
PorterDuff.Mode.SRC_IN)
recyclerView.layoutManager = LinearLayoutManager(baseActivity)
recyclerView.isNestedScrollingEnabled = false
initCategoryList()
}
}
fun onExternalOrganizationSelected(organization: Organization){
viewModel.selectedExternalOrganization = organization
viewDataBinding?.tvExternalOrganization?.text = organization.name ?: ""
}
fun onInternalOrganizationSelected(organization: Organization){
viewModel.selectedInternalOrganization = organization
viewDataBinding?.tvInternalOrganization?.text = organization.name ?: ""
}
private fun initCategoryList(){
categoryAdapter = CategoryAdapter()
categoryAdapter.listener = this
viewDataBinding?.dialogDocumentType?.recyclerView?.adapter = categoryAdapter
categoryAdapter.setItems(PreferenceManager.categories)
}
override fun onSelected(organization: Organization) {
if (currentOrganizationDialogType == 1) {
onExternalOrganizationSelected(organization)
viewDataBinding?.layoutExternalOrganization?.visibility = GONE
viewDataBinding?.viewOverlay?.visibility = GONE
}
else if (currentOrganizationDialogType == 2) {
onInternalOrganizationSelected(organization)
viewDataBinding?.layoutInternalOrganization?.visibility = GONE
viewDataBinding?.viewOverlay?.visibility = GONE
}
}
override fun onSelected(category: Category) {
viewModel.selectedCategory = category
viewDataBinding?.tvChooseType?.text = category.label ?: ""
if (baseActivity.isTablet()){
viewDataBinding?.layoutParentDocumentType?.visibility = GONE
}
viewDataBinding?.viewOverlay?.visibility = GONE
}
private fun onClearSelected(){
viewDataBinding?.apply {
edittextSearchKey.setText("")
tvChooseType.text = ""
edittextReferenceNumber.setText("")
getToday()
tvExternalOrganization.text = ""
tvInternalOrganization.text = ""
}
}
private fun onSearchClicked(){
viewDataBinding?.apply {
viewModel.searchKey = edittextSearchKey.text.toString().trim()
viewModel.referenceNumber = edittextReferenceNumber.text.toString().trim()
}
(baseActivity as MainActivity).onSearchClicked()
}
private fun convertToHijri(calendar: Calendar): String{
val gregorianCalendar = GregorianCalendar(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH))
val uCal: Calendar = UmmalquraCalendar()
uCal.time = gregorianCalendar.time
val year = uCal.get(Calendar.YEAR)
val month = uCal.get(Calendar.MONTH)
val day = uCal.get(Calendar.DAY_OF_MONTH)
return "$year-${convertDateFormat(month)}-${convertDateFormat(day)}"
}
private fun convertDateFormat(value: Int): String{
return if (value < 10) "0$value"
else value.toString()
}
override fun onDestroy() {
viewModel.apply {
selectedCategory = null
selectedInternalOrganization = null
selectedExternalOrganization = null
searchKey = ""
referenceNumber = ""
}
super.onDestroy()
}
} | 0 | Kotlin | 0 | 0 | 12737fd2075734800c60fc9943e90ac4fd27d491 | 17,342 | idox | MIT License |
app/src/main/java/com/domatix/yevbes/nucleus/utils/ConstantManager.kt | sm2x | 234,568,179 | true | {"Kotlin": 782306} | package com.domatix.yevbes.nucleus.utils
interface ConstantManager {
// SHARED PREFS CONTACT PROFILE
companion object {
// for detail cards
const val MODEL_ITEM_ID = "MODEL_ITEM_ID"
// Language
const val EN = "en"
const val ES = "es"
const val LOCALE_LANGUAGE = "LOCALE_LANGUAGE"
const val IS_EDITED = "IS_EDITED"
// SharedPreferences
const val START_TIME: String = "START_TIME"
const val END_TIME: String = "END_TIME"
}
} | 0 | null | 0 | 0 | 237e9496b5fb608f543e98111269da9b91a06ed3 | 520 | nucleus | MIT License |
src/main/kotlin/com/refinedmods/refinedstorage/gui/widget/sidebutton/AccessTypeSideButton.kt | thinkslynk | 290,596,653 | true | {"Kotlin": 695976, "Shell": 456} | package com.refinedmods.refinedstorage.gui.widget.sidebutton
import com.refinedmods.refinedstorage.api.storage.AccessType
import com.refinedmods.refinedstorage.gui.screen.BaseScreen
import com.refinedmods.refinedstorage.tile.data.TileDataManager
import com.refinedmods.refinedstorage.tile.data.TileDataParameter
import com.refinedmods.refinedstorage.util.AccessTypeUtils
import net.minecraft.client.resource.language.I18n
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.util.Formatting
class AccessTypeSideButton(screen: BaseScreen<*>, private val parameter: TileDataParameter<AccessType, *>) : SideButton(screen) {
override fun renderButtonIcon(matrixStack: MatrixStack?, x: Int, y: Int) {
screen.drawTexture(matrixStack, x, y, 16 * parameter.value.getId(), 240, 16, 16)
}
override fun getTooltip(): String {
return I18n.translate("sidebutton.refinedstorage.access_type").toString() + "\n" + Formatting.GRAY + I18n.translate("sidebutton.refinedstorage.access_type." + parameter.value.getId())
}
override fun onPress() {
TileDataManager.setParameter(parameter, AccessTypeUtils.getAccessType(parameter.value.getId() + 1))
}
} | 1 | Kotlin | 0 | 2 | c92afa51af0e5e08caded00882f91171652a89e3 | 1,199 | refinedstorage | MIT License |
app/src/androidTest/java/dev/christopheredwards/openperiod/GetMostRecentPeriodTest.kt | cedwards036 | 490,478,497 | false | null | package dev.christopheredwards.openperiod
import androidx.test.ext.junit.runners.AndroidJUnit4
import dev.christopheredwards.openperiod.data.Period
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import java.time.LocalDate
@RunWith(AndroidJUnit4::class)
class GetMostRecentPeriodTest : PeriodRepositoryTest() {
private fun assertMostRecentPeriodIs(date: String, expectedPeriod: Period?) {
repository.getMostRecentPeriod(LocalDate.parse(date)).observeForever {
assertEquals(expectedPeriod, it)
}
}
@Test
@Throws(Exception::class)
fun returnsNull_ifNoDateDataHasBeenInserted() {
assertMostRecentPeriodIs("2022-01-01", null)
}
@Test
@Throws(Exception::class)
fun returnsNull_ifNoDateDataHasPeriodEvents() {
insertDates(noEventDate("2022-01-01"))
assertMostRecentPeriodIs("2022-01-01", null)
}
@Test
@Throws(Exception::class)
fun returnsNull_ifAllExistingDateDataIsAfterGivenDate() {
insertDates(periodStartDate("2022-02-02"))
assertMostRecentPeriodIs("2022-01-01", null)
}
@Test
@Throws(Exception::class)
fun returnsPeriodThatStartsOnTheDate_IfOneExists() {
insertDates(
periodStartDate("2022-01-01"),
periodStartDate("2021-12-16"),
periodEndDate("2021-12-21"),
)
assertMostRecentPeriodIs("2022-01-01", Period(startDate = LocalDate.parse("2022-01-01")))
}
@Test
@Throws(Exception::class)
fun returnsMostRecentOnGoingPeriodThatStartedBeforeTheDate_IfNoPeriodStartedOnTheDate() {
insertDates(
periodStartDate("2021-12-16"),
periodEndDate("2021-12-21"),
periodStartDate("2022-01-29"),
)
assertMostRecentPeriodIs("2022-02-04", Period(startDate = LocalDate.parse("2022-01-29")))
}
@Test
@Throws(Exception::class)
fun returnsMostRecentCompletedPeriodThatStartedBeforeTheDate_IfNoPeriodIsOnGoingOnTheDate() {
insertDates(
periodStartDate("2021-12-16"),
periodEndDate("2021-12-21"),
periodStartDate("2022-01-14"),
periodEndDate("2022-01-19"),
)
assertMostRecentPeriodIs(
"2022-02-04",
Period(
startDate = LocalDate.parse("2022-01-14"),
endDate = LocalDate.parse("2022-01-19"),
periodLength = 6
)
)
}
} | 0 | Kotlin | 0 | 2 | 392f5b1bb94210fd872947ee05ff748aed69115c | 2,498 | OpenPeriod | MIT License |
app/src/main/java/com/rainbowweather/android/logic/network/PlaceService.kt | kkingso | 315,858,383 | false | null | package com.rainbowweather.android.logic.network
import com.rainbowweather.android.RainbowWeatherApplication
import com.rainbowweather.android.logic.model.PlaceResponse
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
/**
* 城市搜索API的Retrofit接口
* #https://api.caiyunapp.com/v2/place?query=北京&token={token}&lang=zh_CN
*/
interface PlaceService {
@GET("v2/place?token=${RainbowWeatherApplication.TOKEN}&lang=zh_CN")
fun searchPlaces(@Query("query") query: String): Call<PlaceResponse>
} | 0 | Kotlin | 0 | 0 | aea977ccf22e9c0881251869449216ab68a51c5f | 523 | RainbowWeather | Apache License 2.0 |
desktop/application/src/main/kotlin/com/soyle/stories/layout/usecases/toggleToolOpened/ToggleToolOpened.kt | Soyle-Productions | 239,407,827 | false | null | package com.soyle.stories.layout.usecases.toggleToolOpened
import com.soyle.stories.layout.tools.FixedTool
import com.soyle.stories.layout.usecases.getSavedLayout.GetSavedLayout
/**
* Created by Brendan
* Date: 2/15/2020
* Time: 5:16 PM
*/
interface ToggleToolOpened {
suspend operator fun invoke(fixedTool: FixedTool, outputPort: OutputPort)
interface OutputPort {
fun failedToToggleToolOpen(failure: Throwable)
fun receiveToggleToolOpenedResponse(response: GetSavedLayout.ResponseModel)
}
} | 45 | Kotlin | 0 | 9 | 1a110536865250dcd8d29270d003315062f2b032 | 529 | soyle-stories | Apache License 2.0 |
firestore-realtime/app/src/main/java/com/azharkova/photoram/BaseFragment.kt | anioutkazharkova | 390,453,654 | false | null | package com.azharkova.photoram
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.launch
open class BaseFragment : Fragment() {
protected fun doInScope(
state: Lifecycle.State = Lifecycle.State.STARTED,
action: suspend () -> Unit
) {
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.lifecycle.repeatOnLifecycle(state) {
action()
}
}
}
override fun onDestroy() {
super.onDestroy()
}
} | 0 | Kotlin | 0 | 4 | 09e061e92b14450f0deace6d164fbc2eb45d9c52 | 633 | android-firestore_realtime | Apache License 2.0 |
app/src/main/java/com/udacity/MainActivity.kt | andreFwagner | 425,807,223 | false | {"Kotlin": 12898} | package com.udacity
import android.app.DownloadManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
/**
* MainActivity to display Downloadoptions, initiate Download and handle Notification once finished
*/
class MainActivity : AppCompatActivity() {
private val NOTIFICATION_ID = 0
private val REQUEST_CODE = 0
private val FLAGS = 0
private var downloadID: Long = 0
private lateinit var notificationManager: NotificationManager
private lateinit var pendingIntent: PendingIntent
private lateinit var action: NotificationCompat.Action
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
notificationManager =
ContextCompat.getSystemService(
applicationContext,
NotificationManager::class.java
) as NotificationManager
createChannel("load_app_channel", "loadApp")
registerReceiver(receiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
custom_button.setOnClickListener {
custom_button.buttonState = ButtonState.Loading
download(
when (radio_group.checkedRadioButtonId) {
retrofit_button.id -> RETROFIT_URL
app_button.id -> APP_URL
glide_button.id -> GLIDE_URL
else -> null
}
)
}
}
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
custom_button.buttonState = ButtonState.Completed
val downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
val cursor = downloadManager.query(DownloadManager.Query().setFilterById(id!!))
if (cursor.moveToFirst()) {
val status = when (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
DownloadManager.STATUS_SUCCESSFUL -> true
else -> false
}
val fileName = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE))
val fileDescription = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION))
val fileText = "$fileName - $fileDescription"
notificationManager.sendNotification(status, fileText, applicationContext)
}
}
}
private fun NotificationManager.sendNotification(status: Boolean, fileText: String, applicationContext: Context) {
val extras = Bundle()
extras.putBoolean("status", status)
extras.putString("fileText", fileText)
val contentIntent = Intent(applicationContext, DetailActivity::class.java)
contentIntent.putExtras(extras)
pendingIntent = PendingIntent.getActivity(
applicationContext,
NOTIFICATION_ID,
contentIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val builder = NotificationCompat.Builder(applicationContext, "load_app_channel")
.setSmallIcon(R.drawable.ic_assistant_black_24dp)
.setContentTitle(resources.getString(R.string.notification_title))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.addAction(R.drawable.ic_assistant_black_24dp, getString(R.string.notification_button), pendingIntent)
if (status) builder.setContentText(resources.getString(R.string.notification_description))
else builder.setContentText(resources.getString(R.string.notification_description_fail))
notify(NOTIFICATION_ID, builder.build())
}
private fun createChannel(channelId: String, channelName: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
channelId,
channelName,
NotificationManager.IMPORTANCE_HIGH
)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationChannel.description = getString(R.string.channel_description)
notificationManager.createNotificationChannel(notificationChannel)
}
}
private fun download(url: String?) {
if (url != null) {
val request =
DownloadManager.Request(Uri.parse(url))
.setRequiresCharging(false)
.setAllowedOverMetered(true)
.setAllowedOverRoaming(true)
when (url) {
APP_URL -> {
request.setTitle(getString(R.string.app_name))
request.setDescription(getString(R.string.app_description))
}
GLIDE_URL -> {
request.setTitle(getString(R.string.glide_name))
request.setDescription(getString(R.string.glide_description))
}
RETROFIT_URL -> {
request.setTitle(getString(R.string.retrofit_name))
request.setDescription(getString(R.string.retrofit_description))
}
}
val downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
downloadID =
downloadManager.enqueue(request) // enqueue puts the download request in the queue.
} else {
custom_button.buttonState = ButtonState.Clicked
val toast = Toast.makeText(applicationContext, resources.getText(R.string.please_select), Toast.LENGTH_SHORT)
toast.show()
}
}
companion object {
private const val APP_URL = "https://github.com/udacity/nd940-c3-advanced-android-programming-project-starter/archive/refs/heads/master.zip"
private const val RETROFIT_URL = "https://github.com/square/retrofit/archive/refs/heads/master.zip"
private const val GLIDE_URL = "https://github.com/bumptech/glide/archive/refs/heads/master.zip"
}
}
| 0 | Kotlin | 0 | 0 | 377eb385cc4e581251a092a9106b6428cbedf5b0 | 6,926 | udacity_LoadApp | The Unlicense |
app/src/main/java/petrov/ivan/bsc/ui/MainActivity.kt | peiwal | 289,732,500 | false | null | package petrov.ivan.bsc.ui
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import kotlinx.android.synthetic.main.activity_main.*
import petrov.ivan.bsc.R
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navController = this.findNavController(R.id.myNavHostFragment)
NavigationUI.setupActionBarWithNavController(this, navController, null)
}
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(navController, null)
}
}
| 0 | Kotlin | 0 | 0 | dd61a1334130025e58409b559995c943a801323c | 1,126 | BSC_test | MIT License |
app/src/main/java/com/erictoader/compose/cartographer/ScreenDestination.kt | erictoader | 655,898,558 | false | null | package com.erictoader.compose.cartographer
import com.erictoader.compose.cartographer.annotations.NamedArgument
import com.erictoader.compose.cartographer.destination.Destination
object Main : Destination() {
object Home : Destination()
data class Details(
@NamedArgument("primary")
val primaryAsset: Asset,
@NamedArgument("secondary")
val secondaryAsset: Asset
) : Destination()
}
| 0 | Kotlin | 0 | 6 | 728f99983fa35ec0f4c44c6e778df2337b85b03d | 429 | Cartographer | MIT License |
app/src/main/java/com/lwt/qmqiu/widget/ItemView.kt | lianwt115 | 152,687,979 | false | null | package com.lwt.qmqiu.widget
import android.content.Context
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.lwt.qmqiu.R
/**
* Created by Administrator on 2018\1\6 0006.
*/
class ItemView(context: Context, attrs: AttributeSet?, defStyleAttr:Int) : RelativeLayout(context,attrs,defStyleAttr), View.OnClickListener {
//private val mContext: Context
private var mDrawable: Drawable? = null
private var mTitle: String? = null
private var mShowLine = false
private lateinit var mTextViewName: TextView
private lateinit var mTextViewContent: TextView
private lateinit var mImageView: ImageView
private lateinit var mLine: View
private lateinit var mRootView: RelativeLayout
private var mItemOnClickListener: ItemOnClickListener? = null
private var mViewID = 0
constructor(context: Context,attrs: AttributeSet): this(context,attrs,0) {
initAttrs(context, attrs)
initView(context)
}
constructor(context: Context): this(context,null,0)
fun setBarOnClickListener(itemOnClickListener: ItemOnClickListener,id:Int) {
this.mViewID = id
this.mItemOnClickListener = itemOnClickListener
}
private fun initView(context: Context) {
val view = View.inflate(context, R.layout.widget_itemview, null)
//输入标题
mTextViewName = view.findViewById(R.id.show_name) as TextView
mTextViewContent = view.findViewById(R.id.show_content) as TextView
mImageView = view.findViewById(R.id.show_img) as ImageView
mLine = view.findViewById(R.id.line) as View
mRootView = view.findViewById(R.id.itemview_root) as RelativeLayout
if (mDrawable!=null)
mImageView.setImageDrawable(mDrawable)
if (mTitle != null)
mTextViewName.text = mTitle
mLine.visibility = if (mShowLine) View.VISIBLE else View.GONE
mRootView.setOnClickListener(this)
addView(view, RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT))
}
private fun initAttrs(context: Context, attrs: AttributeSet?) {
val ta = context.obtainStyledAttributes(attrs,
R.styleable.ItemView)
mTitle = ta.getString(R.styleable.ItemView_show_name)
mDrawable = ta.getDrawable(R.styleable.ItemView_show_img)
mShowLine = ta.getBoolean(R.styleable.ItemView_show_bottom_line,false)
ta.recycle()
}
override fun onClick(v: View?) {
if (mItemOnClickListener==null) {
return
}
when (v?.id) {
R.id.itemview_root -> {
mItemOnClickListener!!.itemViewClick(mViewID)
}
}
}
fun setShowContent(content:String){
mTextViewContent.text = content
mTextViewContent.visibility = if (TextUtils.isEmpty(content)) View.GONE else View.VISIBLE
}
fun getShowContent():String{
return mTextViewContent.text.toString()
}
interface ItemOnClickListener {
fun itemViewClick(id: Int)
}
} | 0 | Kotlin | 2 | 4 | 2fec69b68b593b6eca530019f383d25699b6650b | 3,333 | qmqiu | Apache License 2.0 |
backend.native/tests/codegen/localClass/innerWithCapture.kt | JetBrains | 58,957,623 | false | null | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package codegen.localClass.innerWithCapture
import kotlin.test.*
fun box(s: String): String {
class Local {
open inner class Inner() {
open fun result() = s
}
}
return Local().Inner().result()
}
@Test fun runTest() {
println(box("OK"))
} | 0 | Kotlin | 625 | 7,100 | 9fb0a75ab17e9d8cddd2c3d1802a1cdd83774dfa | 437 | kotlin-native | Apache License 2.0 |
src/main/kotlin/com/hoangtien2k3/userservice/service/impl/RoleServiceImpl.kt | hoangtien2k3qx1 | 724,051,146 | false | {"Kotlin": 44285} | package com.hoangtien2k3.userservice.service.impl
import com.hoangtien2k3.userservice.model.entity.Role
import com.hoangtien2k3.userservice.model.entity.RoleName
import com.hoangtien2k3.userservice.repository.IRoleRepository
import com.hoangtien2k3.userservice.service.IRoleService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*
@Service
class RoleServiceImpl @Autowired constructor(private val roleRepository: IRoleRepository) : IRoleService {
override fun findByName(name: RoleName): Optional<Role> {
return roleRepository.findByName(name)
}
}
| 1 | Kotlin | 0 | 0 | 192bb887f33bdf37b9d0daff6569f780bd47a4d2 | 644 | kotlin-security-jwt-token | MIT License |
plugin-dotnet-common/src/main/kotlin/jetbrains/buildServer/depcache/DotnetDependencyCacheConstants.kt | JetBrains | 49,584,664 | false | {"Kotlin": 2713429, "C#": 319161, "Java": 96855, "Dockerfile": 831, "CSS": 123} | package jetbrains.buildServer.depcache
object DotnetDependencyCacheConstants {
const val CACHE_ROOT_TYPE: String = "nuget-packages"
const val CACHE_DISPLAY_NAME: String = "NuGet"
const val FEATURE_TOGGLE_DOTNET_DEPENDENCY_CACHE: String = "teamcity.internal.depcache.buildFeature.dotnet.enabled"
const val FEATURE_TOGGLE_DOTNET_DEPENDENCY_CACHE_DEFAULT: Boolean = false
} | 3 | Kotlin | 25 | 94 | 5f444c22b3354955d1060e08478d543d2b0b99b0 | 387 | teamcity-dotnet-plugin | Apache License 2.0 |
multilibrary/src/main/java/com/zhongjh/albumcamerarecorder/camera/listener/CaptureListener.kt | NamedJack | 516,565,393 | true | {"Java Properties": 3, "Markdown": 6, "Gradle": 10, "Shell": 1, "Batchfile": 1, "Text": 2, "Ignore List": 9, "INI": 6, "Proguard": 8, "XML": 187, "Kotlin": 90, "Java": 116} | package com.zhongjh.albumcamerarecorder.camera.listener
import com.zhongjh.albumcamerarecorder.camera.entity.BitmapData
/**
* 拍摄后操作图片的事件
*
* @author zhongjh
* @date 2018/10/11
*/
interface CaptureListener {
/**
* 删除图片后剩下的相关数据
*
* @param captureData 数据源
*/
fun remove(captureData: List<BitmapData>)
/**
* 添加图片
*
* @param captureDatas 图片数据
*/
fun add(captureDatas: List<BitmapData>)
} | 0 | null | 0 | 0 | 567ee4cf7aa6010afecf9d14d5ede28f5ddac6a7 | 447 | AlbumCameraRecorder | MIT License |
app/src/main/java/com/ranaaditya/hackinout/MainActivity.kt | ranaaditya | 319,345,095 | false | null | package com.ranaaditya.hackinout
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.ranaaditya.hackinout.api.ApiUtils
import com.ranaaditya.hackinout.api.LoginRequest
import com.ranaaditya.hackinout.databinding.ActivityMainBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.logging.HttpLoggingInterceptor
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val user = LoginRequest("", "")
//makeUserLogin(user)
}
// fun makeUserLogin(loginRequest: LoginRequest) = lifecycleScope.launch {
// val httpsinterceptor =
// HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
//
// val client = ApiUtils.provideOkHttpClient(httpsinterceptor, this@MainActivity)
//
// val gson = ApiUtils.provideGson()
//
// val retrofit = ApiUtils.provideRetrofit(client, gson)
//
// val response = withContext(Dispatchers.IO) {
// retrofit.login(loginRequest)
// }
//
// withContext(Dispatchers.Main) {
// Log.d("is success", response.sucess.toString())
// if (response.sucess) {
// Log.d("LOGIN SUCCESSFUL", response.toString())
// } else {
// Log.d("LOGIN FAILED", response.toString())
// }
//
// }
//
// }
} | 0 | Kotlin | 0 | 1 | afece359ca615ccfdce529150b3db1e8f61d95e4 | 1,662 | InOut-app | MIT License |
shared/src/commonMain/kotlin/app/duss/easyproject/domain/params/SupplierCreateRequest.kt | Shahriyar13 | 721,031,988 | false | {"Kotlin": 247935, "Swift": 6282, "Ruby": 2302} | package app.duss.easyproject.domain.params
class SupplierCreateRequest (
val code: String,
val companyId: Long?,
val company: CompanyCreateRequest?,
) | 0 | Kotlin | 0 | 0 | 3b21efcf1c9bcdc2148884458a7c34f75020e071 | 163 | Kara_EasyProject_CMP | Apache License 2.0 |
app/src/main/kotlin/me/nanova/subspace/domain/model/Account.kt | kid1412621 | 737,778,999 | false | {"Kotlin": 70038} | package me.nanova.subspace.domain.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import me.nanova.subspace.data.AccountType
@Entity
data class Account(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
// schema + host + port + path
val url: String = "",
val type: AccountType,
val name: String = "",
val user: String = "",
// api key or password
val pass: String = "",
val created: Long = System.currentTimeMillis()
)
| 5 | Kotlin | 0 | 0 | 6da76a9eb3f652e2770b3d9eca703ba538fe9c9d | 481 | subspace | MIT License |
app/src/main/java/com/saharw/mymusicplayer/entities/adapters/MusicPlayerPagerAdapter.kt | SaharWeissman | 132,341,806 | false | null | package com.saharw.mymusicplayer.entities.adapters
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import com.saharw.mymusicplayer.presentation.fragments.base.BaseFragment
/**
* Created by saharw on 08/05/2018.
*/
class MusicPlayerPagerAdapter(private val fragments: Array<Fragment>,
fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) {
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getCount(): Int {
return fragments.size
}
override fun getPageTitle(position: Int): CharSequence {
return (fragments[position] as BaseFragment).getTabTitle()
}
} | 0 | Kotlin | 0 | 0 | ce2773b06df865e7c5aafaeca46d8a85c6f3021e | 783 | MyMusicPlayer | Apache License 2.0 |
app/src/main/java/com/tsukiymk/surgo/ui/MainActivity.kt | tsukiymk | 382,220,719 | false | null | package com.tsukiymk.surgo.ui
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.layout.*
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.core.view.WindowCompat
import androidx.navigation.compose.rememberNavController
import app.surgo.common.compose.components.*
import app.surgo.common.compose.runtime.LocalContentPadding
import app.surgo.common.compose.theme.AppTheme
import app.surgo.ui.playback.PlaybackScreen
import com.google.accompanist.insets.LocalWindowInsets
import com.google.accompanist.insets.ProvideWindowInsets
import com.google.accompanist.insets.navigationBarsHeight
import com.google.accompanist.insets.navigationBarsPadding
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.tsukiymk.surgo.ui.pages.HomeBottomNavigation
import com.tsukiymk.surgo.ui.pages.HomeNavigationRail
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
AppTheme {
AppContent()
}
}
}
}
@OptIn(ExperimentalMaterialApi::class, ExperimentalAnimationApi::class)
@Composable
private fun AppContent() {
ProvideWindowInsets(consumeWindowInsets = false) {
val systemUiController = rememberSystemUiController()
val useDarkIcons = MaterialTheme.colors.isLight
SideEffect {
systemUiController.setSystemBarsColor(
color = Color.Transparent,
darkIcons = useDarkIcons
)
}
val configuration = LocalConfiguration.current
val useBottomNavigation by remember {
derivedStateOf { configuration.smallestScreenWidthDp < 600 }
}
Box(Modifier.navigationBarsPadding(bottom = false)) {
val scope = rememberCoroutineScope()
val sheetState = rememberBottomSheetLayoutState(BottomSheetLayoutValue.Collapsed)
val navController = rememberNavController()
navController.enableOnBackPressed(sheetState.isCollapsed)
BackHandler(
enabled = sheetState.isExpanded,
onBack = {
scope.launch { sheetState.collapse() }
}
)
val bottomInsets = with(LocalDensity.current) { LocalWindowInsets.current.systemBars.bottom.toDp() }
val sheetPeekHeight = when {
useBottomNavigation -> BottomAppBarHeight + BottomNavigationHeight + bottomInsets
else -> BottomNavigationHeight + bottomInsets
}
BottomSheetLayout(
sheetState = sheetState,
bottomBar = {
if (useBottomNavigation) {
HomeBottomNavigation(navController)
} else {
Spacer(
Modifier
.fillMaxWidth()
.navigationBarsHeight()
)
}
},
sheetPeekHeight = sheetPeekHeight,
sheetContent = { openFraction ->
PlaybackScreen(
openFraction = openFraction,
doCollapse = {
scope.launch { sheetState.collapse() }
},
toArtistDetails = { artistId ->
navController.navigate("${MainDestinations.ARTIST_DETAILS_ROUTE}/$artistId")
}
)
},
bodyContent = { contentPadding ->
Row(Modifier.fillMaxSize()) {
if (!useBottomNavigation) {
HomeNavigationRail(navController)
}
CompositionLocalProvider(LocalContentPadding provides contentPadding) {
AppNavigation(navController)
}
}
}
)
}
}
}
| 0 | Kotlin | 0 | 0 | 270baf768c5bfab528384693ed85289fecb0e365 | 4,753 | surgo-android | Apache License 2.0 |
ruri-admin/src/main/kotlin/top/lyuiowo/admin/model/User.kt | lyuiowo | 717,624,820 | false | {"Kotlin": 18629, "Vue": 18047, "JavaScript": 2780, "CSS": 2168, "HTML": 331} | package top.lyuiowo.admin.model
import com.fasterxml.jackson.annotation.JsonIgnore
import jakarta.persistence.Entity
import jakarta.persistence.Id
import org.springframework.security.crypto.bcrypt.BCrypt
import java.sql.Timestamp
import java.util.UUID
@Entity
data class User (
@Id
val userID: UUID,
var username: String,
var email: String,
@get:JsonIgnore
var password: String,
val createAt: Timestamp,
var lastJoinAt: Timestamp,
@get:JsonIgnore
var isDeleted: Boolean = false
) {
companion object {
/**
* @param password 密码原文
* @return 经过 hash 加密后的密码密文
*/
fun hashPassword(password: String): String {
return BCrypt.hashpw(password, BCrypt.gensalt())
}
}
/**
* @param inputPassword 密码
* @return 密码是否正确
*/
fun verifyPassword(inputPassword: String): Boolean {
return BCrypt.checkpw(inputPassword, this.password)
}
}
| 0 | Kotlin | 0 | 1 | b5e8c840322b5c4ca4af4b83e7e0e097e57dad3f | 966 | Ruri-Vue | MIT License |
app/src/main/java/io/github/eh/eh/LoginActivity.kt | Singlerr | 367,322,450 | false | null | package io.github.eh.eh
import android.content.Intent
import android.os.Bundle
import android.transition.Slide
import android.view.Gravity
import android.view.Window
import androidx.appcompat.app.AppCompatActivity
import androidx.core.database.getStringOrNull
import io.github.eh.eh.asutils.IAlertDialog
import io.github.eh.eh.asutils.Utils
import io.github.eh.eh.db.LoginDatabase
import io.github.eh.eh.http.HTTPBootstrap
import io.github.eh.eh.http.HTTPContext
import io.github.eh.eh.http.HttpStatus
import io.github.eh.eh.http.StreamHandler
import io.github.eh.eh.http.bundle.RequestBundle
import io.github.eh.eh.http.bundle.ResponseBundle
import io.github.eh.eh.serverside.User
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.system.exitProcess
class LoginActivity : AppCompatActivity() {
private var instance: LoginActivity? = null
private lateinit var databaseHelper: LoginDatabase
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
with(window) {
requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
enterTransition = Slide(Gravity.RIGHT)
}
setContentView(R.layout.activity_login)
instance = this
databaseHelper = LoginDatabase(this, "session", null, 1)
if (databaseHelper.sessionExists()) {
var cursor = databaseHelper.select()
cursor.moveToFirst()
var id = cursor.getStringOrNull(cursor.getColumnIndexOrThrow("id"))
var password = cursor.getStringOrNull(cursor.getColumnIndexOrThrow("password"))
if (id != null && password != null) {
val bootstrap: HTTPBootstrap = HTTPBootstrap.builder()
.port(Env.HTTP_PORT)
.host(Env.API_URL)
.streamHandler(object : StreamHandler {
override fun onWrite(outputStream: HTTPContext) {
val user = User()
user.userId = id
user.password = password
var req = RequestBundle()
req.setMessage(user)
outputStream.write(req)
}
override fun onRead(obj: Any?) {
if (obj is ResponseBundle) {
if (obj.responseCode == HttpStatus.SC_OK) {
var user = obj.getMessage(User::class.java)
intentSupport(user)
} else {
loginFailed()
}
}
}
}).build()
CoroutineScope(Dispatchers.IO).launch {
try {
bootstrap.submit()
} catch (e: Exception) {
e.printStackTrace()
loginFailedIO()
}
}
}
}
// login button
btn_login.setOnClickListener {
val id = etv_id.text.toString()
val pw = etv_password.text.toString()
val bootstrap: HTTPBootstrap = HTTPBootstrap.builder()
.port(Env.HTTP_PORT)
.host(Env.API_URL)
.streamHandler(object : StreamHandler {
override fun onWrite(outputStream: HTTPContext) {
val user = User()
user.userId = id
user.password = pw
var req = RequestBundle()
req.setMessage(user)
outputStream.write(req)
}
override fun onRead(obj: Any?) {
if (obj is ResponseBundle) {
if (obj.responseCode == HttpStatus.SC_OK) {
var user = obj.getMessage(User::class.java)
intentSupport(user)
databaseHelper.insertOrUpdate(id, pw)
} else {
loginFailed()
}
}
}
}).build()
CoroutineScope(Dispatchers.IO).launch {
try {
bootstrap.submit()
} catch (e: Exception) {
loginFailedIO()
}
}
}
// go to RegisterActivity
btn_moveToRegister.setOnClickListener {
val toregisterintent = Intent(this, RegisterActivity::class.java)
startActivity(toregisterintent)
}
// go to FindPassWordActivity
btn_findPassword.setOnClickListener {
val tofindpwintent = Intent(this, FindPasswordActivity::class.java)
startActivity(tofindpwintent)
}
btn_previousPage.setOnClickListener {
var dialog = IAlertDialog.Builder(instance)
.message("정말로 앱을 종료하시겠습니까?")
.title("확인")
.positiveButton("종료") { _, _ ->
run {
finishAndRemoveTask()
exitProcess(0)
}
}
.negativeButton("취소") { _, _ -> //TODO
}.create()
dialog.show()
}
}
//go to MainActivity
private fun intentSupport(user: User?) {
val tomainintent = Intent(this, MainActivity::class.java)
Utils.setEssentialData(
intent = tomainintent,
user = user,
className = this::class.java.name
)
startActivity(tomainintent)
}
//Toast message when login failed
private fun loginFailed() {
msg_error.text = "비밀번호가 일치하지 않습니다."
//Utils.showMessageBox(this,"로그인 실패","로그인 실패, 아이디와 비밀번호를 다시 확인해주세요.",AlertDialog.BUTTON_POSITIVE)
//Toast.makeText(this, "로그인 실패, 아이디와 비밀번호를 다시 확인해주세요.", Toast.LENGTH_SHORT).show()
}
private fun loginFailedIO() {
msg_error.text = "로그인을 할 수 없습니다."
}
}
| 0 | Kotlin | 0 | 0 | fa61fe1c4d5538de12c094e48c3434fd3e788928 | 6,411 | EscapeHonbab | Creative Commons Zero v1.0 Universal |
profilers/src/com/android/tools/profilers/cpu/nodemodel/SystemTraceNodeFactory.kt | phpc0de | 470,555,455 | false | null | /*
* Copyright (C) 2020 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.
*/
package com.android.tools.profilers.cpu.nodemodel
import java.util.regex.Pattern
/**
* This Factory returns instances of {@link SystemTraceNodeModel}s, guaranteeing that nodes that
* represents a same object would be mapped to a single instance.
*/
class SystemTraceNodeFactory {
// We have two possible levels of caching, based on the raw name and based on the computed one from the regex below.
// regex can get very expensive and become a hotspot, so we use nameMap to avoid it if we can.
private val canonicalMap = mutableMapOf<String, CanonicalNodeId>()
private val nodeMap = mutableMapOf<CanonicalNodeId, SystemTraceNodeModel>()
// Pattern to match names with the format Letters Number. Eg: Frame 1234
private val ID_GROUP = Pattern.compile("^([A-Za-z\\s]*)(\\d+)")
fun getNode(name: String): SystemTraceNodeModel {
val canonicalId = canonicalMap.getOrPut(name) { computeCanonicalId(name) }
return nodeMap.getOrPut(canonicalId) { SystemTraceNodeModel(canonicalId.id, canonicalId.name) }
}
private fun computeCanonicalId(name: String): CanonicalNodeId {
// We match the numbers at the end of a tag so the UI can group elements that have an incrementing number at the end as the same thing.
// This means that "Frame 1", and "Frame 2" will appear as a single element "Frame ###". This allows us to collect the stats, and
// colorize these elements as if they represent the same thing.
val matches = ID_GROUP.matcher(name)
// If we have a group 0 that is not the name then something went wrong. Fallback to the name.
if (matches.matches() && matches.group(0) == name) {
// If we find numbers in the group then instead of using the numbers use "###"
return CanonicalNodeId(matches.group(1), "${matches.group(1)}###")
}
else {
return CanonicalNodeId(name, name)
}
}
private data class CanonicalNodeId(val id: String, val name: String)
} | 0 | null | 1 | 1 | 79e20f027ca1d047b91aa7acd92fb71fa2968a09 | 2,552 | idea-android | Apache License 2.0 |
src/main/kotlin/rui/leetcode/kt/q/Q633.kt | ruislan | 307,862,179 | false | {"Kotlin": 78523} | package rui.leetcode.kt.q
class Q633 {
fun judgeSquareSum(c: Int): Boolean {
// 方法1
// 先将所有的平方都存储到hashset中
// 然后迭代hashset,找另外一个数
// 如果存在则是答案
// AC 424ms 43.9mb
// val set = HashSet<Int>()
// for (x in 0..c) {
// val y = x.toLong() * x.toLong()
// if (y > c) break
// set.add(y.toInt())
// }
// for (x in set) {
// if (set.contains(c - x)) return true
// }
// return false
// 方法2
// 利用开方,直接处理
// AC 156ms
var x: Long = 0
while (x * x <= c) {
val y = Math.sqrt(c.toDouble() - (x * x))
if (y == Math.ceil(y)) return true
x += 1
}
return false
}
} | 0 | Kotlin | 0 | 1 | 55baacd5c536864bbc82536bb60ff892cd127aa8 | 772 | leetcode-kotlin | MIT License |
app/src/main/java/com/mgpersia/androidbox/Fragment/bottomSheet/FilterOptionBottomSheetFragment.kt | mahsak01 | 596,924,815 | false | null | package com.mgpersia.androidbox.Fragment.bottomSheet
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.mgpersia.androidbox.R
import com.mgpersia.androidbox.adapter.FilterOptionItemSettingAdapter
import com.mgpersia.androidbox.common.MainContainer
import com.mgpersia.androidbox.data.model.FilterBottomSheet
import com.mgpersia.androidbox.data.model.FilterOptionBottomSheet
import com.mgpersia.androidbox.databinding.FragmentFilterOptionBottomSheetBinding
class FilterOptionBottomSheetFragment(
private val item: List<FilterBottomSheet>,
private val is_sort: Boolean,
private val index: Int,
private val eventListener: EventListener
) :
BottomSheetDialogFragment() {
private lateinit var binding: FragmentFilterOptionBottomSheetBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme)
}
@RequiresApi(Build.VERSION_CODES.N)
override fun onResume() {
super.onResume()
this.view?.isFocusableInTouchMode = true
this.view?.requestFocus()
setListener()
setInformation()
}
private fun setInformation() {
this.binding.fragmentFilterOptionBottomSheetTitleTv.text = item[index].title
binding.fragmentFilterOptionBottomSheetItemRv.layoutManager =
LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, false)
val adapter =
FilterOptionItemSettingAdapter(item[index].items, item[index].itemSelect, is_sort,
object : FilterOptionItemSettingAdapter.EventListener {
override fun click(item: FilterOptionBottomSheet) {
[email protected][[email protected]].itemSelect.add(
item.id
)
if (is_sort) {
MainContainer.setSortItems([email protected][[email protected]])
} else {
MainContainer.updateFilterItems([email protected][[email protected]])
}
eventListener.update()
}
override fun delete(item: FilterOptionBottomSheet) {
[email protected][[email protected]].itemSelect.remove(
item.id
)
if (is_sort) {
MainContainer.setSortItems([email protected][[email protected]])
} else {
MainContainer.updateFilterItems([email protected][[email protected]])
}
eventListener.update()
}
})
binding.fragmentFilterOptionBottomSheetItemRv.adapter = adapter
if (is_sort)
this.binding.fragmentFilterOptionBottomSheetNextBtn.visibility = View.GONE
}
private fun setListener() {
this.binding.fragmentFilterOptionBottomSheetCloseBtn.setOnClickListener {
dismiss()
}
this.binding.fragmentFilterOptionBottomSheetOkBtn.setOnClickListener {
dismiss()
}
this.binding.fragmentFilterOptionBottomSheetNextBtn.setOnClickListener {
if (!is_sort) {
if (index != 3) {
dismiss()
val bottomSheetDialog =
FilterOptionBottomSheetFragment(item, false, index + 1,eventListener)
bottomSheetDialog.show(requireFragmentManager(), "bottomSheetDialog")
}else{
dismiss()
val bottomSheetDialog = FilterOptionYearBottomSheetFragment(eventListener)
bottomSheetDialog.show(requireFragmentManager(), "bottomSheetDialog")
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
this.binding = FragmentFilterOptionBottomSheetBinding.inflate(
inflater,
container,
false
)
return binding.root
}
interface EventListener{
fun update()
}
} | 0 | Kotlin | 0 | 0 | 1fb772d72e14e9e05a72f9988c0c42b14773f608 | 4,928 | ArianaFilm | The Unlicense |
src/test/kotlin/io/github/verissimor/lib/jpamagicfilter/fieldtype/NumericFieldTypeTest.kt | verissimor | 444,221,850 | false | null | package io.github.verissimor.lib.jpamagicfilter.fieldtype
import io.github.verissimor.lib.jpamagicfilter.BaseTest
import org.hamcrest.Matchers.hasSize
import org.junit.jupiter.api.Test
import org.springframework.test.web.servlet.get
class NumericFieldTypeTest : BaseTest() {
@Test
fun `should filter grater than`() {
mockMvc.get("/api/users?age_gt=55")
.andExpect {
status { isOk() }
jsonPath("$", hasSize<Int>(1))
}
}
@Test
fun `should filter grater equals than`() {
mockMvc.get("/api/users?age_ge=55")
.andExpect {
status { isOk() }
jsonPath("$", hasSize<Int>(2))
}
}
}
| 0 | Kotlin | 0 | 4 | cf1ec55bc2a691c6d7d10380f0eb26910f738989 | 651 | jpa-magic-filter | Apache License 2.0 |
generator/src/main/kotlin/de/qhun/declaration_provider/generator/typescript/render/TypescriptDataTypeRenderer.kt | wartoshika | 319,145,505 | false | null | package de.qhun.declaration_provider.generator.typescript.render
import de.qhun.declaration_provider.domain.DataType
import de.qhun.declaration_provider.generator.DeclarationGeneratorOptions
internal object TypescriptDataTypeRenderer {
fun DataType.render(options: DeclarationGeneratorOptions): String {
return when (this) {
is DataType.TypeNull -> "null | undefined"
is DataType.TypeLong,
is DataType.TypeInt,
is DataType.TypeFloat,
is DataType.TypeDouble -> "number"
is DataType.TypeString -> "string"
is DataType.TypeBoolean -> "boolean"
is DataType.TypeArray -> "{ [arrayIdx: number]: any }"
is DataType.TypeObject -> "{ [objectIdx: string]: any }"
is DataType.TypeFunction -> "(...args: any[]) => any"
is DataType.TypeRef -> reference
else -> "any"
}
}
}
| 0 | Kotlin | 0 | 0 | bc26206f36ae06bdc9cb3e206b4baa22e8bcaf82 | 936 | wow-declaration-provider | MIT License |
postProcessor/src/main/kotlin/com/firelion/dslgen/DslGenCommandLineProcessor.kt | firelion9 | 455,101,893 | false | {"Kotlin": 185262} | /*
* Copyright (c) 2024 <NAME>.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file.
*/
@file:OptIn(ExperimentalCompilerApi::class)
package com.firelion.dslgen
import com.google.auto.service.AutoService
import org.jetbrains.kotlin.compiler.plugin.AbstractCliOption
import org.jetbrains.kotlin.compiler.plugin.CliOption
import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi
import org.jetbrains.kotlin.config.CompilerConfiguration
@AutoService(CommandLineProcessor::class)
class DslGenCommandLineProcessor : CommandLineProcessor {
override val pluginId: String get() = PLUGIN_ID
override val pluginOptions: Collection<AbstractCliOption> = listOf(
CliOption(
optionName = OPTION_ENABLED,
valueDescription = "<enabled>",
description = "enable DSL context classes post-processing to use default argument in exit functions",
required = false,
allowMultipleOccurrences = false
)
)
override fun processOption(option: AbstractCliOption, value: String, configuration: CompilerConfiguration) =
when (option.optionName) {
OPTION_ENABLED -> {
configuration.put(DslGenConstants.keyEnabled, value.toBoolean())
}
else -> error("unknown option ${option.optionName}")
}
companion object {
const val PLUGIN_ID = "com.firelion.dslgen"
const val OPTION_ENABLED = "allowDslDefaultArgs"
}
} | 0 | Kotlin | 0 | 0 | 7c37fec82c450078309d2d577a12b670fc798874 | 1,598 | kotlinDslGenerator | Apache License 2.0 |
amazon/cognito/client/src/main/kotlin/org/http4k/connect/amazon/cognito/action/InitiateAuth.kt | http4k | 295,641,058 | false | {"Kotlin": 1624429, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675} | package org.http4k.connect.amazon.cognito.action
import org.http4k.connect.Http4kConnectAction
import org.http4k.connect.amazon.cognito.CognitoAction
import org.http4k.connect.amazon.cognito.model.AnalyticsMetadata
import org.http4k.connect.amazon.cognito.model.AuthFlow
import org.http4k.connect.amazon.cognito.model.AuthenticationResult
import org.http4k.connect.amazon.cognito.model.ChallengeName
import org.http4k.connect.amazon.cognito.model.ClientId
import org.http4k.connect.amazon.cognito.model.Session
import org.http4k.connect.amazon.cognito.model.UserContextData
import se.ansman.kotshi.JsonSerializable
@Http4kConnectAction
@JsonSerializable
data class InitiateAuth(
val ClientId: ClientId,
val AuthFlow: AuthFlow,
val AuthParameters: Map<String, String>? = null,
val ClientMetadata: Map<String, String>? = null,
val UserContextData: UserContextData? = null,
val AnalyticsMetadata: AnalyticsMetadata? = null
) : CognitoAction<AuthInitiated>(AuthInitiated::class)
@JsonSerializable
data class AuthInitiated(
val AuthenticationResult: AuthenticationResult?,
val ChallengeName: ChallengeName?,
val ChallengeParameters: Map<String, String>?,
val Session: Session?
)
| 7 | Kotlin | 17 | 37 | 94e71e6bba87d9c79ac29f7ba23bdacd0fdf354c | 1,217 | http4k-connect | Apache License 2.0 |
spesialist-selve/src/main/kotlin/no/nav/helse/modell/vedtaksperiode/VedtaksperiodeEndret.kt | navikt | 244,907,980 | false | {"Kotlin": 2685407, "PLpgSQL": 29508, "HTML": 1741, "Dockerfile": 258} | package no.nav.helse.modell.vedtaksperiode
import com.fasterxml.jackson.databind.JsonNode
import java.util.UUID
import no.nav.helse.mediator.Kommandofabrikk
import no.nav.helse.mediator.meldinger.Vedtaksperiodemelding
import no.nav.helse.modell.person.Person
import no.nav.helse.rapids_rivers.JsonMessage
internal class VedtaksperiodeEndret(
override val id: UUID,
private val vedtaksperiodeId: UUID,
private val fødselsnummer: String,
private val json: String,
) : Vedtaksperiodemelding {
internal constructor(packet: JsonMessage): this(
id = UUID.fromString(packet["@id"].asText()),
vedtaksperiodeId = UUID.fromString(packet["vedtaksperiodeId"].asText()),
fødselsnummer = packet["fødselsnummer"].asText(),
json = packet.toJson()
)
internal constructor(jsonNode: JsonNode): this(
id = UUID.fromString(jsonNode["@id"].asText()),
vedtaksperiodeId = UUID.fromString(jsonNode["vedtaksperiodeId"].asText()),
fødselsnummer = jsonNode["fødselsnummer"].asText(),
json = jsonNode.toString()
)
override fun fødselsnummer() = fødselsnummer
override fun vedtaksperiodeId() = vedtaksperiodeId
override fun behandle(person: Person, kommandofabrikk: Kommandofabrikk) {
kommandofabrikk.iverksettOppdaterSnapshot(this)
}
override fun toJson() = json
} | 5 | Kotlin | 1 | 0 | b58ba2cae68a8f8a1299b7ee3719d20ffc191ac3 | 1,363 | helse-spesialist | MIT License |
app/src/main/kotlin/com/example/rule/dash/ui/adapters/callsadapter/InterfaceCallsAdapter.kt | 100rabhg | 756,262,852 | false | {"Kotlin": 466102, "Java": 376} | package com.example.rule.dash.ui.adapters.callsadapter
import com.example.rule.dash.ui.adapters.baseadapter.InterfaceAdapter
interface InterfaceCallsAdapter : InterfaceAdapter {
fun onLongClick(keyFileName: String, fileName: String, childName: String,position:Int)
} | 0 | Kotlin | 0 | 0 | c197f262cc913f26b8a9d2e21f713504fed4ddd1 | 272 | Rule | Apache License 2.0 |
app/src/main/java/com/duckduckgo/app/global/install/AppInstallStore.kt | ArielOSProject | 145,104,939 | true | {"Kotlin": 802845, "Java": 26650, "C++": 6912, "CMake": 2478, "Shell": 490} | /*
* Copyright (c) 2018 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.app.global.install
import android.content.Context
import android.content.SharedPreferences
import android.support.annotation.VisibleForTesting
import androidx.core.content.edit
import javax.inject.Inject
interface AppInstallStore {
var installTimestamp: Long
fun hasInstallTimestampRecorded() : Boolean
fun recordUserDeclinedBannerToSetDefaultBrowser(timestamp: Long = System.currentTimeMillis())
fun recordUserDeclinedHomeScreenCallToActionToSetDefaultBrowser(timestamp: Long = System.currentTimeMillis())
fun hasUserDeclinedDefaultBrowserBannerPreviously(): Boolean
fun hasUserDeclinedDefaultBrowserHomeScreenCallToActionPreviously(): Boolean
}
class AppInstallSharedPreferences @Inject constructor(private val context: Context) : AppInstallStore {
override var installTimestamp: Long
get() = preferences.getLong(KEY_TIMESTAMP_UTC, 0L)
set(timestamp) = preferences.edit { putLong(KEY_TIMESTAMP_UTC, timestamp) }
override fun hasInstallTimestampRecorded(): Boolean = preferences.contains(KEY_TIMESTAMP_UTC)
override fun recordUserDeclinedBannerToSetDefaultBrowser(timestamp: Long) {
preferences.edit {
putLong(KEY_TIMESTAMP_USER_DECLINED_BANNER_DEFAULT_BROWSER, timestamp)
}
}
override fun recordUserDeclinedHomeScreenCallToActionToSetDefaultBrowser(timestamp: Long) {
preferences.edit {
putLong(KEY_TIMESTAMP_USER_DECLINED_CALL_TO_ACTION_DEFAULT_BROWSER, timestamp)
}
}
override fun hasUserDeclinedDefaultBrowserBannerPreviously(): Boolean {
return preferences.contains(KEY_TIMESTAMP_USER_DECLINED_BANNER_DEFAULT_BROWSER)
}
override fun hasUserDeclinedDefaultBrowserHomeScreenCallToActionPreviously(): Boolean {
return preferences.contains(KEY_TIMESTAMP_USER_DECLINED_CALL_TO_ACTION_DEFAULT_BROWSER)
}
private val preferences: SharedPreferences
get() = context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE)
companion object {
@VisibleForTesting
const val FILENAME = "com.duckduckgo.app.install.settings"
const val KEY_TIMESTAMP_UTC = "INSTALL_TIMESTAMP_UTC"
const val KEY_TIMESTAMP_USER_DECLINED_BANNER_DEFAULT_BROWSER = "USER_DECLINED_DEFAULT_BROWSER_TIMESTAMP_UTC"
const val KEY_TIMESTAMP_USER_DECLINED_CALL_TO_ACTION_DEFAULT_BROWSER = "USER_DECLINED_DEFAULT_BROWSER_CALL_TO_ACTION_TIMESTAMP_UTC"
}
} | 0 | Kotlin | 0 | 0 | 0ee4e3a4f3fb30f1aed22a9924876fa08020089e | 3,090 | Android | Apache License 2.0 |
core/src/main/java/contacts/core/entities/cursor/PhoneCursor.kt | misha-n-ka | 428,930,484 | true | {"Kotlin": 938913} | package contacts.core.entities.cursor
import android.database.Cursor
import contacts.core.Fields
import contacts.core.PhoneField
import contacts.core.entities.Phone
/**
* Retrieves [Fields.Phone] data from the given [cursor].
*
* This does not modify the [cursor] position. Moving the cursor may result in different attribute
* values.
*/
internal class PhoneCursor(cursor: Cursor, includeFields: Set<PhoneField>) :
AbstractDataCursor<PhoneField>(cursor, includeFields) {
val type: Phone.Type? by type(Fields.Phone.Type, typeFromValue = Phone.Type::fromValue)
val label: String? by string(Fields.Phone.Label)
val number: String? by string(Fields.Phone.Number)
val normalizedNumber: String? by string(Fields.Phone.NormalizedNumber)
}
| 0 | Kotlin | 0 | 0 | 6fe3d8e21a2fb686b81a42788ee3ba046f859113 | 764 | contacts-android | Apache License 2.0 |
interactive-text/src/jvmMain/kotlin/me/okonecny/wysiwyg/FloatingToolbar.kt | konecny-ondrej | 784,920,382 | false | {"Kotlin": 202728} | package me.okonecny.wysiwyg
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.offset
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.unit.round
import me.okonecny.interactivetext.compose.MeasuringLayout
@Composable
internal fun FloatingToolbar(
editorState: WysiwygEditorState,
toolbarContent: (@Composable () -> Unit)
) {
val visualCursorRect = editorState.visualCursorRect ?: return
if (editorState.sourceCursor == null) return
MeasuringLayout(
measuredContent = {
toolbarContent()
}
) { measuredSize, constraints ->
Box(Modifier.offset {
val maxPosition = Offset(
x = constraints.maxWidth - measuredSize.width.toPx(),
y = constraints.maxHeight - measuredSize.height.toPx(),
)
val toolbarPosition = (visualCursorRect.topLeft - Offset(0f, measuredSize.height.toPx()))
Offset(
x = toolbarPosition.x.coerceIn(0f, maxPosition.x),
y = toolbarPosition.y.coerceIn(0f, maxPosition.y)
).round()
}) {
toolbarContent()
}
}
} | 0 | Kotlin | 0 | 1 | b9461fc82a2e42d6700a1c93d485c4e471fdbc2c | 1,273 | compose-markdown-editor | MIT License |
app/src/main/java/com/moon/beautygirlkotlin/common/data/service/youmei/model/Manager.kt | moonljt521 | 128,654,453 | false | null | package com.moon.beautygirlkotlin.common.data.service.youmei.model
/**
* author: jiangtao.liang
* date: On 2019-09-03 19:50
*/
open class Manager() {} | 0 | Kotlin | 3 | 9 | d679e11c834a49fe62e14444affbf234cdcaa936 | 156 | BeautyGirlKotlin | Apache License 2.0 |
java/io/jackbradshaw/otter/demo/DemoScope.kt | jack-bradshaw | 468,854,318 | false | {"Kotlin": 139153, "Starlark": 60977, "Shell": 2958, "Java": 444} | package io.jackbradshaw.otter.demo
import javax.inject.Scope
@Scope @Retention(AnnotationRetention.RUNTIME) annotation class DemoScope
| 4 | Kotlin | 0 | 7 | d51e20a4564504af6a0e95c294c3d9a4e3256232 | 137 | monorepo | MIT License |
app/src/main/java/com/words/storageapp/database/AppDatabase.kt | emmasonn | 451,215,073 | false | {"Kotlin": 311218} | package com.words.storageapp.database
import android.content.Context
import androidx.room.*
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.words.storageapp.database.model.*
import com.words.storageapp.work.SeedDatabaseWorker
@Database(
entities = [AllSkillsDbModel::class, AllSkillsFts::class,
ClientDbModel::class, CommentDbModel::class, AddressModel::class,
RecentSkillModel::class],
version = 2,
exportSchema = false
)
@TypeConverters(Converter::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun allSkillsDbDao(): AllSkillsDbDao
abstract fun clientDbDao(): ClientDbDao
abstract fun commentDao(): CommentDao
abstract fun addressDao(): AddressDao
abstract fun recentDao(): RecentDao
companion object {
@Volatile
var INSTANCE: AppDatabase? = null
fun getInstance(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
}
}
private fun buildDatabase(context: Context): AppDatabase {
return Room.databaseBuilder(context, AppDatabase::class.java, "skills_db")
.addCallback(object : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
//pre-populating the database with dummy data
val request = OneTimeWorkRequestBuilder<SeedDatabaseWorker>().build()
WorkManager.getInstance(context).enqueue(request)
}
})
.fallbackToDestructiveMigration()
.build()
}
}
} | 0 | Kotlin | 0 | 1 | 84e4a537e3f45c21cf4ba121c78006f9fab889de | 1,839 | SkillHub | Apache License 2.0 |
ParkingPermitApp/app/src/main/java/com/example/parkingpermitapp/cameraview/BoundingBoxOverlay.kt | Seeleysbay | 718,965,951 | false | {"Kotlin": 67673, "HTML": 64437, "Python": 33015, "Java": 29910, "CSS": 5521, "Dockerfile": 229} | package com.example.parkingpermitapp.cameraview
import android.util.Log
import androidx.compose.runtime.Composable
import com.example.parkingpermitapp.domain.DetectionResult
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
//********************************************************************
// Receives a DetectionResult object as an argument and uses *
// the (x,y) coordinate along with the width and height to draw *
// a bounding box over the Android View camera preview in real time. *
// Canvas size matches Camera Preview size exactly. *
//********************************************************************
@Composable
fun BoundingBoxOverlay(detectionResult: DetectionResult?) {
Canvas(modifier = Modifier.fillMaxSize())
{
if(detectionResult != null){
val canvasWidth = size.width
val canvasHeight = size.height
val scaledX = detectionResult.x * canvasWidth
val scaledY = detectionResult.y * canvasHeight
val scaledWidth = detectionResult.width * canvasWidth
val scaledHeight = detectionResult.height * canvasHeight
Log.d(
"CanvasBoxCoor",
"Canvas Box: canvasWidth=$canvasWidth, canvasHeight=$canvasHeight"
)
drawRect(
color = Color.Red,
topLeft = Offset(
scaledX - (scaledWidth / 2),
scaledY - (scaledHeight / 2)
),
size = Size(width = scaledWidth, height = scaledHeight),
style = Stroke(width = 5f)
)
}
else{
drawRect(
color = Color.Transparent,
topLeft = Offset(0f, 0f),
size = Size(width = size.width, height = size.height)
)
}
}
} | 0 | Kotlin | 0 | 0 | 4edf6552db6dd153dca2cca53916b219f51a44f9 | 2,131 | Penn-State-License-Plate-Detection-Capstone | MIT License |
codeSnippets/snippets/http2-push/src/main/kotlin/com/example/Http2PushApplication.kt | ktorio | 278,572,893 | false | null | package com.example
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.html.*
import io.ktor.server.http.*
import io.ktor.server.plugins.callloging.*
import io.ktor.server.plugins.defaultheaders.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.html.*
fun Application.main() {
install(DefaultHeaders)
install(CallLogging)
routing {
get("/") {
call.push("/style.css")
call.respondHtml {
head {
title { +"Ktor: http2-push" }
styleLink("/style.css")
}
body {
p {
+"Hello from Ktor HTTP/2 push sample application"
}
}
}
}
get("/style.css") {
call.respondText("p { color: blue }", contentType = ContentType.Text.CSS)
}
}
}
| 1 | null | 284 | 430 | 8a84c1bd73c66a6a16937482f6e52fe37dcad6fd | 945 | ktor-documentation | Apache License 2.0 |
value-object/src/test/kotlin/io/kommons/designpatterns/valueobject/HeroStatTest.kt | debop | 235,066,649 | false | null | package io.kommons.designpatterns.valueobject
import io.kommons.logging.KLogging
import org.amshove.kluent.shouldEqual
import org.amshove.kluent.shouldNotEqual
import org.junit.jupiter.api.Test
class HeroStatTest {
companion object: KLogging()
private val heroStatA = HeroStat(3, 9, 2)
private val heroStatB = HeroStat(3, 9, 2)
private val heroStatC = HeroStat(1, 2, 3)
@Test
fun `equals value object`() {
heroStatA shouldEqual heroStatB
heroStatC shouldNotEqual heroStatA
}
@Test
fun `toString value object`() {
heroStatA.toString() shouldEqual heroStatB.toString()
heroStatC.toString() shouldNotEqual heroStatA.toString()
}
} | 0 | Kotlin | 11 | 53 | c00bcc0542985bbcfc4652d0045f31e5c1304a70 | 705 | kotlin-design-patterns | Apache License 2.0 |
features/fixtures/mazerunner/jvm-scenarios/src/main/java/com/bugsnag/android/mazerunner/scenarios/OverrideToUnhandledExceptionScenario.kt | bugsnag | 2,406,783 | false | null | package com.bugsnag.android.mazerunner.scenarios
import android.content.Context
import com.bugsnag.android.Bugsnag
import com.bugsnag.android.Configuration
/**
* Generates a handled exception that is overridden so that unhandled is true.
*/
internal class OverrideToUnhandledExceptionScenario(
config: Configuration,
context: Context,
eventMetadata: String?
) : Scenario(config, context, eventMetadata) {
override fun startScenario() {
super.startScenario()
Bugsnag.startSession()
Bugsnag.notify(generateException()) {
it.isUnhandled = true
true
}
}
}
| 17 | null | 205 | 1,188 | f5fd26b3cdeda9c4d4e221f55feb982a3fd97197 | 633 | bugsnag-android | MIT License |
src/nativeMain/kotlin/me/alex_s168/kallok/LargeSegmentAllocator.kt | alex-s168 | 751,722,987 | false | {"Kotlin": 51939, "C": 1521} | package me.alex_s168.kallok
class LargeSegmentAllocator: Allocator {
private val pages = LinkedHashSet<Page>()
override fun alloc(size: Int): Allocation? {
for (p in pages) {
return p.nextSplitPage(size) ?: continue
}
val p = Page.allocate {
pages -= it
}
pages += p
return p.nextSplitPage(size)
}
} | 0 | Kotlin | 0 | 0 | 7c59abf07af1dfd277223c65aa55d8870ba76183 | 385 | kjit | Apache License 2.0 |
src/main/kotlin/io/offscale/openfoodfacts/client/models/ProductUpdateAPIV3WRITE.kt | SamuelMarks | 866,322,014 | false | {"Kotlin": 537174} | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package io.offscale.openfoodfacts.client.models
import io.offscale.openfoodfacts.client.models.PackagingComponentWRITE
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* Model for creating or updating products using the v3 version of the product update API.
*
* @param packagings The packagings object is an array of individual packaging component objects. The Packaging data document explains how packaging data is structured in Open Food Facts: https://openfoodfacts.github.io/openfoodfacts-server/dev/explain-packaging-data/
* @param packagingsAdd The packagings object is an array of individual packaging component objects. The Packaging data document explains how packaging data is structured in Open Food Facts: https://openfoodfacts.github.io/openfoodfacts-server/dev/explain-packaging-data/
* @param packagingsComplete Indicate if the packagings array contains all the packaging parts of the product. This field can be set by users when they enter or verify packaging data. Possible values are 0 or 1.
* @param lang 2 letter language code of the main language of the product (the most prominent on the packaging)
* @param quantity
* @param servingSize
* @param categoriesTags An array of categories
*/
@Serializable
data class ProductUpdateAPIV3WRITE (
/* The packagings object is an array of individual packaging component objects. The Packaging data document explains how packaging data is structured in Open Food Facts: https://openfoodfacts.github.io/openfoodfacts-server/dev/explain-packaging-data/ */
@SerialName("packagings")
val packagings: kotlin.collections.List<PackagingComponentWRITE>? = null,
/* The packagings object is an array of individual packaging component objects. The Packaging data document explains how packaging data is structured in Open Food Facts: https://openfoodfacts.github.io/openfoodfacts-server/dev/explain-packaging-data/ */
@SerialName("packagings_add")
val packagingsAdd: kotlin.collections.List<PackagingComponentWRITE>? = null,
/* Indicate if the packagings array contains all the packaging parts of the product. This field can be set by users when they enter or verify packaging data. Possible values are 0 or 1. */
@SerialName("packagings_complete")
val packagingsComplete: kotlin.Int? = null,
/* 2 letter language code of the main language of the product (the most prominent on the packaging) */
@SerialName("lang")
val lang: kotlin.String? = null,
@SerialName("quantity")
val quantity: kotlin.String? = null,
@SerialName("serving_size")
val servingSize: kotlin.String? = null,
/* An array of categories */
@SerialName("categories_tags")
val categoriesTags: kotlin.collections.List<kotlin.String>? = null
) {
}
| 0 | Kotlin | 0 | 1 | 0ba56f72b5d3ac32b20083ea70c28ca26c6bbdeb | 3,078 | openfoodfacts-kotlin-openapi | Apache License 2.0 |
app/src/test/java/ca/llamabagel/transpo/data/FakeLiveUpdatesRepositoryInjection.kt | Llamabagel | 175,222,878 | false | {"Kotlin": 191040} | package ca.llamabagel.transpo.data
import ca.llamabagel.transpo.home.data.LiveUpdatesRepository
import ca.llamabagel.transpo.utils.provideFakeCoroutinesDispatcherProvider
fun provideFakeLiveUpdatesRepository() = LiveUpdatesRepository(
createTestTripsService(createMockServer()),
getTransitDatabase(),
provideFakeCoroutinesDispatcherProvider()
) | 10 | Kotlin | 2 | 1 | 70ca00367b6cb93a8c1bd19f1a6524e093b65484 | 358 | transpo-android | MIT License |
app-base/src/main/java/com/lhwdev/selfTestMacro/repository/SelfTestManager.kt | lhwdev | 289,257,684 | false | null | package com.lhwdev.selfTestMacro.repository
import android.content.Context
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.compositionLocalOf
import com.lhwdev.selfTestMacro.api.*
import com.lhwdev.selfTestMacro.database.AppDatabase
import com.lhwdev.selfTestMacro.database.DbTestGroup
import com.lhwdev.selfTestMacro.database.DbUser
import com.lhwdev.selfTestMacro.database.DbUserGroup
import com.lhwdev.selfTestMacro.debug.DebugContext
import com.lhwdev.selfTestMacro.ui.UiContext
val LocalSelfTestManager = compositionLocalOf<SelfTestManager> { error("not provided") }
@Immutable
data class MasterUser(
val identifier: UsersIdentifier,
val birth: String,
val password: String,
val instituteInfo: InstituteInfo,
val instituteType: InstituteType
)
@Immutable
data class WizardUser(val user: User, val info: UserInfo, val master: MasterUser)
enum class SelfTestInitiator(val isFromUi: Boolean) {
userClick(isFromUi = true),
alarm(isFromUi = false)
}
interface SelfTestManager {
interface SelfTestSession : HcsSession
var context: Context
val database: AppDatabase
var debugContext: DebugContext
val schedules: SelfTestSchedules
val api: SelfTestApi
fun createAuthSession(institute: InstituteInfo): SelfTestSession
fun registerAuthSession(session: SelfTestSession, institute: InstituteInfo, mainUser: User)
fun getAuthSession(group: DbUserGroup): SelfTestSession
fun addTestGroupToDb(usersToAdd: List<WizardUser>, targetGroup: DbTestGroup?, isAllGrouped: Boolean)
suspend fun getCurrentStatus(user: DbUser): Status?
/**
* Note: [users] may not be derived from database, rather arbitrary modified data to change answer etc.
*/
suspend fun submitSelfTestNow(
uiContext: UiContext,
group: DbTestGroup,
users: List<DbUser>? = null
): List<SubmitResult>
suspend fun onSubmitSchedule(schedule: SelfTestSchedule)
fun updateSchedule(target: DbTestGroup, new: DbTestGroup)
fun onScheduleUpdated()
}
| 2 | Kotlin | 7 | 50 | 06ada78bb235a170f74c9a3f06dc9b5ea99e0a8d | 1,987 | covid-selftest-macro | Apache License 2.0 |
src/main/kotlin/me/hrrocha0/avaliaunb/views/EditarProfessorView.kt | hrrocha0 | 657,358,914 | false | null | package me.hrrocha0.avaliaunb.views
import me.hrrocha0.avaliaunb.models.pages.EditarProfessorModel
object EditarProfessorView : TemplateView<EditarProfessorModel>("editar_professor.ftl") | 0 | Kotlin | 0 | 0 | 94d09ed6fad9c0f0644998f024c327f36c3e15c7 | 188 | AvaliaUnB | MIT License |
src/main/kotlin/no/nav/syfo/kafkamottak/InntektsmeldingConsumerException.kt | navikt | 121,716,621 | false | {"Kotlin": 393985, "Dockerfile": 440} | package no.nav.syfo.kafkamottak
class InntektsmeldingConsumerException(exception: Exception) : RuntimeException(exception)
| 12 | Kotlin | 3 | 4 | a40807aa78a34f6ba6a3069ee3c8418a3d601783 | 124 | syfoinntektsmelding | MIT License |
simple/composeApp/src/commonMain/kotlin/io/github/sample/App.kt | the-best-is-best | 878,946,838 | false | {"Kotlin": 30005, "Swift": 522, "HTML": 352} | package io.github.sample
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import io.github.compose_utils.PlatformData
import io.github.compose_utils.SharedPrefs
import io.github.compose_utils.openUrl
import io.github.compose_utils.providerDispatcher
import io.github.sample.theme.AppTheme
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
internal fun App() = AppTheme {
val scope = rememberCoroutineScope()
val prefs = SharedPrefs()
val platformData = PlatformData()
Column(
modifier = Modifier
.fillMaxSize()
.windowInsetsPadding(WindowInsets.safeDrawing)
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
// use Dispatcher
ElevatedButton(onClick = {
scope.launch {
// for make method not with the same thread main
withContext(providerDispatcher().io) {}
}
}) {
Text("Use dispatcher")
}
Spacer(Modifier.height(10.dp))
ElevatedButton(onClick = {
openUrl("https://maps.app.goo.gl/qnPYcxLP9Y9Y74od8")
}) {
Text("go to google map")
}
Spacer(Modifier.height(10.dp))
ElevatedButton(onClick = {
prefs.putInt("test", 10)
}) {
Text("save in prefs")
}
Spacer(Modifier.height(10.dp))
ElevatedButton(onClick = {
val data = prefs.getInt("test", 0)
println("value prefs test is $data")
}) {
Text("get value prefs")
}
Spacer(Modifier.height(10.dp))
ElevatedButton(onClick = {
println("name: ${platformData.name}")
println("deviceName: ${platformData.deviceName}")
println("model: ${platformData.model}")
println("version: ${platformData.version}")
println("manufacturer: ${platformData.manufacturer}")
}) {
Text("get platform data")
}
}
}
| 0 | Kotlin | 0 | 0 | 246b5162c243c3477bde4d73dfe1973138efab84 | 2,715 | compose-utils | Apache License 2.0 |
app/src/main/java/io/pergasus/data/ProductId.kt | Quabynah | 122,559,374 | false | {"Java": 510220, "Kotlin": 479170} | /*
* Copyright (c) 2018. Property of Dennis Kwabena Bilson. No unauthorized duplication of this material should be made without prior permission from the developer
*/
package io.pergasus.data
import android.support.annotation.NonNull
/** For retrieving [com.google.firebase.firestore.FirebaseFirestore] */
@Suppress("UNCHECKED_CAST")
open class ProductId {
open var productId: String? = null
open fun <T : ProductId> withId(@NonNull id: String): T {
this.productId = id
return this as T
}
}
| 1 | Java | 1 | 1 | ec6e0d8326cdd4e90edd6a86d597e3e8c572145a | 525 | phoenix-master | Apache License 2.0 |
src/main/kotlin/com/github/duanwenjian/templatewebstorm/listeners/MyProjectManagerListener.kt | duanwenjian | 286,399,527 | false | null | package com.github.duanwenjian.templatewebstorm.listeners
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener
import com.github.duanwenjian.templatewebstorm.services.MyProjectService
internal class MyProjectManagerListener : ProjectManagerListener {
override fun projectOpened(project: Project) {
project.getService(MyProjectService::class.java)
}
}
| 0 | Kotlin | 0 | 0 | b56cf8fcbdf3689b55d408c0a00717ea7081bc13 | 420 | template-webstorm | Apache License 2.0 |
domain/src/main/java/com/ibenabdallah/motus/domain/model/Status.kt | ibenabdallah | 800,097,815 | false | {"Kotlin": 61508} | package com.ibenabdallah.motus.domain.model
sealed interface Status {
data object None : Status
data object Correct : Status
data object Wrong : Status
data object WrongPlace : Status
} | 0 | Kotlin | 0 | 0 | db033424b23424bc6f497209441fcf16703a6ed0 | 202 | motus | Apache License 2.0 |
android/app/src/main/kotlin/com/jiangkang/flutter_system/MainActivity.kt | Vicctoor | 278,014,458 | true | {"Dart": 232141, "Kotlin": 2739, "Ruby": 2112, "Shell": 1028, "Swift": 807, "HTML": 366, "Objective-C": 74} | package com.jiangkang.flutter_system
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.SplashScreen
class MainActivity : FlutterActivity() {
override fun provideSplashScreen(): SplashScreen? {
return LottieSplashScreen()
}
}
| 0 | null | 0 | 0 | 672920533e130e74947bcc91bdaa707e0802c419 | 283 | flutter-system | MIT License |
android/app/src/main/kotlin/com/example/homehelper/MainActivity.kt | skyneticist | 437,396,225 | false | {"HTML": 3932, "Dart": 1747, "Swift": 404, "Kotlin": 127, "Objective-C": 38} | package com.example.homehelper
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | HTML | 0 | 1 | 0019c79b5ff0224c573f0fcbe5d147fc6811e7f9 | 127 | home-helper | Apache License 2.0 |
base/lint/libs/lint-tests/src/test/java/com/android/tools/lint/helpers/DefaultJavaEvaluatorTest.kt | qiangxu1996 | 301,210,525 | false | {"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121} | /*
* Copyright (C) 2017 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.
*/
package com.android.tools.lint.helpers
import com.android.testutils.TestUtils
import com.android.tools.lint.checks.AbstractCheckTest
import com.android.tools.lint.checks.infrastructure.TestLintTask.lint
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.intellij.psi.PsiModifierListOwner
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.UVariable
import org.junit.Test
/** Most of the evaluator is tested indirectly via all the lint unit tests; this covers
* some additional specific scenarios. */
class DefaultJavaEvaluatorTest {
// Regression test for https://groups.google.com/d/msg/lint-dev/BaRimyf40tI/DpkOjMMEAQAJ
@Test
fun lookUpAnnotationsOnUastModifierLists() {
lint().files(
AbstractCheckTest.java(
"""
package foo;
@SuppressWarnings("ClassNameDiffersFromFileName")
public class MyTest {
public void myTest(@Override int something) { }
}"""
).indented()
)
.sdkHome(TestUtils.getSdk())
.issues(TestAnnotationLookupDetector.ISSUE)
.run()
.expectClean()
}
class TestAnnotationLookupDetector : Detector(), SourceCodeScanner {
companion object Issues {
val ISSUE = Issue.create(
"Order",
"Dummy test detector summary",
"Dummy test detector explanation",
Category.CORRECTNESS, 6, Severity.WARNING,
Implementation(
TestAnnotationLookupDetector::class.java,
Scope.JAVA_FILE_SCOPE
)
)
}
override fun getApplicableUastTypes(): List<Class<out UElement>>? =
listOf(UMethod::class.java, UVariable::class.java)
class AnnotationOrderVisitor(private val context: JavaContext) : UElementHandler() {
override fun visitVariable(node: UVariable) {
processAnnotations(node)
}
override fun visitMethod(node: UMethod) {
processAnnotations(node)
}
private fun processAnnotations(modifierListOwner: PsiModifierListOwner) {
context.evaluator.findAnnotationInHierarchy(modifierListOwner, "org.foo.bar")
context.evaluator.findAnnotation(modifierListOwner, "org.foo.bar")
context.evaluator.getAllAnnotations(
modifierListOwner,
true
).mapNotNull { it.qualifiedName?.split(".")?.lastOrNull() }
// This detector doesn't actually report anything; the regression test
// ensures that the above calls don't crash
}
}
override fun createUastHandler(context: JavaContext): UElementHandler? {
return AnnotationOrderVisitor(context)
}
}
}
| 1 | Java | 1 | 1 | 3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4 | 4,045 | vmtrace | Apache License 2.0 |
app/src/main/java/com/bluelzy/bluewanandroid/view/main/ui/ProjectFragment.kt | bluezzyy | 253,952,259 | false | null | package com.bluelzy.bluewanandroid.view.main.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.bluelzy.bluewanandroid.R
import com.bluelzy.bluewanandroid.base.BaseDataBindingFragment
import com.bluelzy.bluewanandroid.databinding.FragmentProjectBinding
import com.bluelzy.bluewanandroid.view.main.adapter.project.ProjectDelegateMultiAdapter
import com.bluelzy.bluewanandroid.view.main.viewmodel.ProjectViewModel
import kotlinx.android.synthetic.main.toolbar_home.view.*
import org.koin.androidx.viewmodel.ext.android.getViewModel
class ProjectFragment : BaseDataBindingFragment() {
private lateinit var binding: FragmentProjectBinding
private lateinit var viewModel: ProjectViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = binding<FragmentProjectBinding>(inflater, R.layout.fragment_project, container)
.apply {
lifecycleOwner = this@ProjectFragment
[email protected] = this
viewModel = getViewModel<ProjectViewModel>()
.apply {
(activity as MainActivity).showSpinner()
fetchProjectJson()
}
.also { [email protected] = it }
adapter = ProjectDelegateMultiAdapter()
}.root
override fun initView() {
binding.layoutToolbar.toolbar_title.text = getString(R.string.title_project)
}
override fun initViewModel() {
viewModel.projectLiveData.observe(this, Observer {
(activity as MainActivity).hideSpinner()
})
}
} | 0 | Kotlin | 1 | 2 | 9fe3084338785f951a9240ea0c135184ba84adca | 1,770 | BlueWanAndroid | Apache License 2.0 |
app/src/main/java/com/example/mytodoapp/features/database/entities/TasksGroup.kt | TrombBone | 787,097,480 | false | {"Kotlin": 156584} | package com.example.mytodoapp.features.database.entities
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
import java.util.UUID
@Parcelize
@Entity(
tableName = "groups"
)
data class TasksGroup @JvmOverloads constructor(
@PrimaryKey
@ColumnInfo(index = true)
var taskGroupID: String = UUID.randomUUID().toString(),
var groupTitle: String? = ""
) : Parcelable
| 0 | Kotlin | 0 | 1 | c8d48bb9589ac84977fd935bfb7531843287e2c8 | 487 | MyTodoApp | MIT License |
feature/src/main/java/com/thelazybattley/feature/model/currentweather/CurrentWeatherCurrent.kt | dellosaneil | 720,658,411 | false | {"Kotlin": 133379} | package com.thelazybattley.current.model.current
import com.thelazybattley.common.R
import com.thelazybattley.common.model.WeatherCondition
data class CurrentWeatherCurrent(
val apparentTemperature: Double,
val isDay: Boolean,
val precipitation: Double,
val temperature2m: Double,
val time: Long,
val windDirection10m: Int,
val windSpeed10m: Double,
val cloudCover: Int,
val surfacePressure: Double,
val relativeHumidity2m: Int,
val weatherCondition: WeatherCondition
) {
companion object {
fun dummyData() = CurrentWeatherCurrent(
apparentTemperature = 32.3,
isDay = true,
precipitation = 10.3,
temperature2m = 31.3,
time = 1703131379685L,
windDirection10m = 300,
windSpeed10m = 32.3,
cloudCover = 33,
surfacePressure = 345.2,
relativeHumidity2m = 30,
weatherCondition = WeatherCondition(
icon = R.drawable.img_light_rain,
description = "light rain"
)
)
}
}
| 0 | Kotlin | 0 | 0 | adb7ffc205a27b95b8c847ee3af6dcca373b80ca | 1,105 | weather-app | Apache License 2.0 |
app/src/main/kotlin/com/simplemobiletools/gallery/views/MySquareImageView.kt | chandanws | 102,201,578 | true | {"Kotlin": 230487} | package com.simplemobiletools.gallery.views
import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
class MySquareImageView : ImageView {
var isVerticalScrolling = true
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val spec = if (isVerticalScrolling) measuredWidth else measuredHeight
setMeasuredDimension(spec, spec)
}
}
| 0 | Kotlin | 0 | 0 | 90018b0182c2d9cbf725caa065e5b6f63f1121ff | 717 | Simple-Gallery | Apache License 2.0 |
vck/src/commonMain/kotlin/at/asitplus/wallet/lib/iso/IssuerSigned.kt | a-sit-plus | 602,578,639 | false | {"Kotlin": 1076316} | package at.asitplus.wallet.lib.iso
import at.asitplus.KmmResult.Companion.wrap
import at.asitplus.catching
import at.asitplus.signum.indispensable.cosef.CoseSigned
import kotlinx.serialization.*
/**
* Part of the ISO/IEC 18013-5:2021 standard: Data structure for mdoc request (8.3.2.1.2.1)
*/
@Serializable
data class IssuerSigned private constructor(
@SerialName("nameSpaces")
@Serializable(with = NamespacedIssuerSignedListSerializer::class)
val namespaces: Map<String, @Contextual IssuerSignedList>? = null,
@SerialName("issuerAuth")
val issuerAuth: CoseSigned,
) {
fun getIssuerAuthPayloadAsMso() = catching {
MobileSecurityObject.deserializeFromIssuerAuth(issuerAuth.payload!!).getOrThrow()
}
fun serialize() = vckCborSerializer.encodeToByteArray(this)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is IssuerSigned) return false
if (issuerAuth != other.issuerAuth) return false
if (namespaces != other.namespaces) return false
return true
}
override fun hashCode(): Int {
var result = issuerAuth.hashCode()
result = 31 * result + (namespaces?.hashCode() ?: 0)
return result
}
companion object {
fun deserialize(it: ByteArray) = kotlin.runCatching {
vckCborSerializer.decodeFromByteArray<IssuerSigned>(it)
}.wrap()
// Note: Can't be a secondary constructor, because it would have the same JVM signature as the primary one.
/**
* Ensures the serialization of this structure in [Document.issuerSigned]:
* ```
* IssuerNameSpaces = { ; Returned data elements for each namespace
* + NameSpace => [ + IssuerSignedItemBytes ]
* }
* IssuerSignedItemBytes = #6.24(bstr .cbor IssuerSignedItem)
* ```
*
* See ISO/IEC 18013-5:2021, 8.3.2.1.2.2 Device retrieval mdoc response
*/
fun fromIssuerSignedItems(
namespacedItems: Map<String, List<IssuerSignedItem>>,
issuerAuth: CoseSigned,
): IssuerSigned = IssuerSigned(
namespaces = namespacedItems.map { (namespace, value) ->
namespace to IssuerSignedList.fromIssuerSignedItems(value, namespace)
}.toMap(),
issuerAuth = issuerAuth,
)
}
} | 11 | Kotlin | 1 | 22 | 6f29a2ba84aceda63026afcfc8fd6cc0d8ccbb00 | 2,393 | vck | Apache License 2.0 |
app/src/main/java/com/zhuzichu/orange/category/viewmodel/ItemLeftViewModel.kt | qq524787275 | 191,562,693 | false | null | package com.zhuzichu.orange.category.viewmodel
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.zhuzichu.mvvm.base.ItemViewModel
import com.zhuzichu.mvvm.bean.CategoryBean
import com.zhuzichu.mvvm.databinding.command.BindingCommand
import com.zhuzichu.mvvm.global.color.ColorGlobal
class ItemLeftViewModel(
viewModel: CategoryViewModel,
val category: CategoryBean
) : ItemViewModel<CategoryViewModel>(viewModel) {
val isSelected = ObservableBoolean()
val name = ObservableField(category.main_name)
val color = ColorGlobal
val clickItem = BindingCommand<Any>({
val data = mutableListOf<ItemLeftViewModel>()
viewModel.leftList.map {
if (it is ItemLeftViewModel) {
it.isSelected.set(it.category.cid == category.cid)
data.add(it)
}
}
viewModel.leftList.update(data.toList())
viewModel.updateRight(this)
})
} | 0 | Kotlin | 2 | 2 | 79b0cd43c4f33b492cbb7e219be4547a6900d866 | 982 | orange | Apache License 2.0 |
app/src/main/java/com/covelline/reversegeocoder/di/DatabaseModule.kt | covelline | 823,999,546 | false | {"Kotlin": 80827, "Swift": 26810, "Makefile": 579} | package com.covelline.reversegeocoder.di
import android.content.Context
import com.covelline.reversegeocoder.data.GsiFeatureDatabase
import com.covelline.reversegeocoder.data.GsiFeatureDatabaseBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Provides
@Singleton
fun provideGsiFeatureDatabase(@ApplicationContext context: Context): GsiFeatureDatabase {
return GsiFeatureDatabaseBuilder(context).createGsiFeatureDatabase()
}
}
| 0 | Kotlin | 0 | 0 | e3877cd5e52d9cbcaf48482f9b3b5210f2048c56 | 679 | ReverseGeocoder | MIT License |
card/src/main/java/com/adyen/checkout/card/internal/ui/model/InstallmentOptionParams.kt | Adyen | 91,104,663 | false | null | /*
* Copyright (c) 2023 Adyen N.V.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by atef on 24/2/2023.
*/
package com.adyen.checkout.card.internal.ui.model
import android.os.Parcelable
import com.adyen.checkout.card.CardBrand
import kotlinx.parcelize.Parcelize
/**
* InstallmentOptionParams is used for defining the details of installment options.
*
* Note: All values specified in [values] must be greater than 1.
*/
internal sealed class InstallmentOptionParams : Parcelable {
abstract val values: List<Int>
abstract val includeRevolving: Boolean
/**
* @param values see [InstallmentOptionParams.values]
* @param includeRevolving see [InstallmentOptionParams.includeRevolving]
* @param cardBrand a [CardBrand] to apply the given options
*/
@Parcelize
data class CardBasedInstallmentOptions(
override val values: List<Int>,
override val includeRevolving: Boolean,
val cardBrand: CardBrand
) : InstallmentOptionParams()
/**
* @param values see [InstallmentOptionParams.values]
* @param includeRevolving see [InstallmentOptionParams.includeRevolving]
*/
@Parcelize
data class DefaultInstallmentOptions(
override val values: List<Int>,
override val includeRevolving: Boolean
) : InstallmentOptionParams()
}
| 28 | Kotlin | 59 | 96 | 1f000e27e07467f3a30bb3a786a43de62be003b2 | 1,403 | adyen-android | MIT License |
common/src/commonMain/kotlin/com/artemchep/keyguard/provider/bitwarden/usecase/PatchWatchtowerAlertCipherImpl.kt | AChep | 669,697,660 | false | {"Kotlin": 5516822, "HTML": 45876} | package com.artemchep.keyguard.provider.bitwarden.usecase
import com.artemchep.keyguard.common.io.IO
import com.artemchep.keyguard.common.io.flatten
import com.artemchep.keyguard.common.io.ioEffect
import com.artemchep.keyguard.common.io.map
import com.artemchep.keyguard.common.model.DWatchtowerAlertType
import com.artemchep.keyguard.common.model.PatchWatchtowerAlertCipherRequest
import com.artemchep.keyguard.common.usecase.PatchWatchtowerAlertCipher
import com.artemchep.keyguard.core.store.bitwarden.BitwardenCipher
import com.artemchep.keyguard.core.store.bitwarden.ignoredAlerts
import com.artemchep.keyguard.provider.bitwarden.usecase.util.ModifyCipherById
import kotlinx.datetime.Clock
import org.kodein.di.DirectDI
import org.kodein.di.instance
/**
* @author <NAME>
*/
class PatchWatchtowerAlertCipherImpl(
private val modifyCipherById: ModifyCipherById,
) : PatchWatchtowerAlertCipher {
companion object {
private const val TAG = "PatchWatchtowerAlertCipher.bitwarden"
}
constructor(directDI: DirectDI) : this(
modifyCipherById = directDI.instance(),
)
override fun invoke(
request: PatchWatchtowerAlertCipherRequest,
): IO<Boolean> = ioEffect {
val createdAt = Clock.System.now()
val cipherIds = request.patch.keys
modifyCipherById(
cipherIds,
updateRevisionDate = false,
) { model ->
var new = model
val r = request.patch[model.cipherId]
?: return@modifyCipherById new
val oldIgnoreAlerts = model.data_.ignoredAlerts
val newIgnoreAlerts = oldIgnoreAlerts
.toMutableMap()
r.entries.forEach { entry ->
val key = when (entry.key) {
DWatchtowerAlertType.WEAK_PASSWORD -> null
DWatchtowerAlertType.REUSED_PASSWORD -> BitwardenCipher.IgnoreAlertType.REUSED_PASSWORD
DWatchtowerAlertType.PWNED_PASSWORD -> BitwardenCipher.IgnoreAlertType.PWNED_PASSWORD
DWatchtowerAlertType.PWNED_WEBSITE -> BitwardenCipher.IgnoreAlertType.PWNED_WEBSITE
DWatchtowerAlertType.UNSECURE_WEBSITE -> BitwardenCipher.IgnoreAlertType.UNSECURE_WEBSITE
DWatchtowerAlertType.TWO_FA_WEBSITE -> BitwardenCipher.IgnoreAlertType.TWO_FA_WEBSITE
DWatchtowerAlertType.PASSKEY_WEBSITE -> BitwardenCipher.IgnoreAlertType.PASSKEY_WEBSITE
DWatchtowerAlertType.DUPLICATE -> BitwardenCipher.IgnoreAlertType.DUPLICATE
DWatchtowerAlertType.DUPLICATE_URIS -> BitwardenCipher.IgnoreAlertType.DUPLICATE_URIS
DWatchtowerAlertType.INCOMPLETE -> BitwardenCipher.IgnoreAlertType.INCOMPLETE
DWatchtowerAlertType.EXPIRING -> BitwardenCipher.IgnoreAlertType.EXPIRING
}
?: return@forEach
val shouldIgnore = entry.value
if (shouldIgnore) {
newIgnoreAlerts[key] = BitwardenCipher.IgnoreAlertData(
createdAt = createdAt,
)
} else {
newIgnoreAlerts.remove(key)
}
}
new = new.copy(
data_ = BitwardenCipher.ignoredAlerts.set(new.data_, newIgnoreAlerts),
)
new
}
// Report that we have actually modified the
// ciphers.
.map { changedCipherIds ->
request.patch.keys
.intersect(changedCipherIds)
.isNotEmpty()
}
}
.flatten()
}
| 66 | Kotlin | 31 | 995 | 557bf42372ebb19007e3a8871e3f7cb8a7e50739 | 3,689 | keyguard-app | Linux Kernel Variant of OpenIB.org license |
spark/src/main/kotlin/com/adevinta/spark/tokens/Shape.kt | adevinta | 598,741,849 | false | null | /*
* Copyright (c) 2023 Adevinta
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.adevinta.spark.tokens
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.CornerBasedShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.dp
import com.adevinta.spark.PreviewTheme
import com.adevinta.spark.SparkTheme
import com.adevinta.spark.tools.preview.ThemeProvider
import com.adevinta.spark.tools.preview.ThemeVariant
import androidx.compose.material3.Shapes as Material3Shapes
/**
*
* Components are grouped into shape categories based on their size. These categories provide a
* way to change multiple component values at once, by changing the category’s values.
* SparkShapes categories include:
* - Small components
* - Medium components
* - Large components
*
* @param none A shape style with 4 same-sized corners whose size are equal to [RectangleShape].
* By default app bars, navigation bars, banners, full-screen dialogs, and navigation rails use this shape.
* @param extraSmall A shape style with 4 same-sized corners whose size are bigger than
* [RectangleShape] and smaller than [SparkShapes.small]. By default autocomplete menu, select menu,
* snackbars, standard menu, and text fields use this shape.
* @param small A shape style with 4 same-sized corners whose size are bigger than
* [SparkShapes.extraSmall] and smaller than [SparkShapes.medium]. By default chips use this shape.
* @param medium A shape style with 4 same-sized corners whose size are bigger than [SparkShapes.small]
* and smaller than [SparkShapes.large]. By default cards and small FABs use this shape.
* @param large A shape style with 4 same-sized corners whose size are bigger than [SparkShapes.medium]
* and smaller than [SparkShapes.extraLarge]. By default extended FABs, FABs, and navigation drawers use
* this shape.
* @param extraLarge A shape style with 4 same-sized corners whose size are bigger than
* [SparkShapes.large] and smaller than [CircleShape]. By default large FABs, Bottom sheets, Dialogs and Time picker
* use this shape.
* @param full A shape style with 4 same-sized corners whose size are equal to [CircleShape]. By default large Badge,
* Buttons, Icon buttons, Sliders, Switches and Search bar use this shape.
*/
@Immutable
public data class SparkShapes(
val none: CornerBasedShape = RoundedCornerShape(0.dp),
val extraSmall: CornerBasedShape = RoundedCornerShape(4.0.dp),
val small: CornerBasedShape = RoundedCornerShape(8.0.dp),
val medium: CornerBasedShape = RoundedCornerShape(12.0.dp),
val large: CornerBasedShape = RoundedCornerShape(16.0.dp),
val extraLarge: CornerBasedShape = RoundedCornerShape(28.0.dp),
val full: CornerBasedShape = CircleShape,
)
public fun sparkShapes(
none: CornerBasedShape = RoundedCornerShape(0.dp),
extraSmall: CornerBasedShape = RoundedCornerShape(4.0.dp),
small: CornerBasedShape = RoundedCornerShape(8.0.dp),
medium: CornerBasedShape = RoundedCornerShape(12.0.dp),
large: CornerBasedShape = RoundedCornerShape(16.0.dp),
extraLarge: CornerBasedShape = RoundedCornerShape(28.0.dp),
full: CornerBasedShape = CircleShape,
): SparkShapes = SparkShapes(
none = none,
extraSmall = extraSmall,
small = small,
medium = medium,
large = large,
extraLarge = extraLarge,
full = full,
)
public fun SparkShapes.asMaterial3Shapes(): Material3Shapes = Material3Shapes(
extraSmall = extraSmall,
small = small,
medium = medium,
large = large,
extraLarge = extraLarge,
)
/**
* CompositionLocal used to specify the default shapes for the surfaces.
*/
internal val LocalSparkShapes = staticCompositionLocalOf { SparkShapes() }
@Preview(
group = "Tokens",
name = "Shapes",
)
@Composable
internal fun ShapePreview(
@PreviewParameter(ThemeProvider::class) theme: ThemeVariant,
) {
PreviewTheme(theme) {
Row {
Column {
ShapeItem(
modifier = Modifier,
shape = SparkTheme.shapes.none,
text = "none",
)
ShapeItem(
modifier = Modifier,
shape = SparkTheme.shapes.small,
text = "small",
)
ShapeItem(
modifier = Modifier,
shape = SparkTheme.shapes.large,
text = "large",
)
}
Column {
ShapeItem(
modifier = Modifier,
shape = SparkTheme.shapes.extraSmall,
text = "extraSmall",
)
ShapeItem(
modifier = Modifier,
shape = SparkTheme.shapes.medium,
text = "medium",
)
ShapeItem(
modifier = Modifier,
shape = SparkTheme.shapes.extraLarge,
text = "extraLarge",
)
}
}
ShapeItem(
modifier = Modifier,
shape = SparkTheme.shapes.full,
text = "full",
)
}
}
@Composable
private fun ShapeItem(
shape: Shape,
text: String,
modifier: Modifier = Modifier,
) {
Surface(
modifier = modifier
.size(96.dp)
.padding(8.dp),
shadowElevation = 6.dp,
tonalElevation = 6.dp,
shape = shape,
) {
Box(contentAlignment = Alignment.Center) {
Text(
text = text,
style = SparkTheme.typography.caption,
)
}
}
}
| 53 | null | 10 | 34 | d73939162dcdafcff931820704a416761f214ee8 | 7,475 | spark-android | MIT License |
app/src/main/java/com/azhar/resepmasakan/model/ModelIngredients.kt | AzharRivaldi | 353,561,154 | false | null | package com.azhar.resepmasakan.model
/**
* Created by <NAME> on 16-03-2021
*/
class ModelIngredients {
var strIngredient: String? = null
} | 0 | Kotlin | 5 | 17 | ec329de03fcae22d952ecfc21cd4e0003d68f09d | 146 | Resep-Masakan-Indonesia | Apache License 2.0 |
apps/etterlatte-behandling/src/main/kotlin/grunnlagsendring/doedshendelse/kontrollpunkt/DoedshendelseKontrollpunkt.kt | navikt | 417,041,535 | false | {"Kotlin": 5618023, "TypeScript": 1317735, "Handlebars": 21854, "Shell": 10666, "HTML": 1776, "Dockerfile": 745, "CSS": 598} | package no.nav.etterlatte.grunnlagsendring.doedshendelse.kontrollpunkt
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.annotation.JsonTypeName
import no.nav.etterlatte.grunnlagsendring.doedshendelse.kontrollpunkt.DoedshendelseKontrollpunkt.DuplikatGrunnlagsendringsHendelse
import no.nav.etterlatte.grunnlagsendring.doedshendelse.kontrollpunkt.DoedshendelseKontrollpunkt.EpsHarSakIGjenny
import no.nav.etterlatte.libs.common.sak.Sak
import java.util.UUID
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "kode")
@JsonIgnoreProperties(ignoreUnknown = true)
sealed class DoedshendelseKontrollpunkt {
abstract val kode: String
abstract val beskrivelse: String
abstract val sendBrev: Boolean
abstract val opprettOppgave: Boolean
abstract val avbryt: Boolean
@JsonTypeName("AVDOED_LEVER_I_PDL")
data object AvdoedLeverIPDL : DoedshendelseKontrollpunkt() {
override val kode = "AVDOED_LEVER_I_PDL"
override val beskrivelse: String = "Avdød lever i PDL"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = false
override val avbryt: Boolean = true
}
@JsonTypeName("BARN_HAR_BP")
data object BarnHarBarnepensjon : DoedshendelseKontrollpunkt() {
override val kode = "BARN_HAR_BP"
override val beskrivelse: String = "Barn har barnepensjon"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = false
override val avbryt: Boolean = true
}
@JsonTypeName("BARN_HAR_UFOERE")
data object BarnHarUfoereTrygd : DoedshendelseKontrollpunkt() {
override val kode = "BARN_HAR_UFOERE"
override val beskrivelse: String = "Barnet har uføretrygd"
override val sendBrev: Boolean = true
override val opprettOppgave: Boolean = false
override val avbryt: Boolean = false
}
@JsonTypeName("KRYSSENDE_YTELSE_I_PESYS")
data object KryssendeYtelseIPesysEps : DoedshendelseKontrollpunkt() {
override val kode = "KRYSSENDE_YTELSE_I_PESYS"
override val beskrivelse: String = "Den berørte(EPS) har uføretrygd eller alderspensjon i Pesys"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = false
override val avbryt: Boolean = true
}
@JsonTypeName("AVDOED_HAR_D_NUMMER")
data object AvdoedHarDNummer : DoedshendelseKontrollpunkt() {
override val kode = "AVDOED_HAR_D_NUMMER"
override val beskrivelse: String = "Den avdøde har D-nummer"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = true
override val avbryt: Boolean = false
}
@JsonTypeName("EPS_HAR_DOEDSDATO")
data object EpsHarDoedsdato : DoedshendelseKontrollpunkt() {
override val kode = "EPS_HAR_DOEDSDATO"
override val beskrivelse: String = "Eps har dødsdato"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = false
override val avbryt: Boolean = true
}
@JsonTypeName("EPS_KAN_HA_ALDERSPENSJON")
data object EpsKanHaAlderspensjon : DoedshendelseKontrollpunkt() {
override val kode = "EPS_KAN_HA_ALDERSPENSJON"
override val beskrivelse: String = "Eps kan ha alderspensjon"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = false
override val avbryt: Boolean = true
}
@JsonTypeName("EPS_SKILT_SISTE_5_OG_GIFT_I_15")
data object EpsHarVaertSkiltSiste5OgGiftI15 : DoedshendelseKontrollpunkt() {
override val kode = "EPS_SKILT_SISTE_5_OG_GIFT_I_15"
override val beskrivelse: String = "Eps er skilt siste 5 år og gift i 15"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = true
override val avbryt: Boolean = false
}
@JsonTypeName("EPS_SKILT_SISTE_5_UKJENT_GIFTEMAAL_VARIGHET")
data object EpsHarVaertSkiltSiste5MedUkjentGiftemaalLengde : DoedshendelseKontrollpunkt() {
override val kode = "EPS_SKILT_SISTE_5_UKJENT_GIFTEMAAL_VARIGHET"
override val beskrivelse: String = "Eps er skilt siste 5 år med ukjent lengde på giftermål"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = true
override val avbryt: Boolean = false
}
@JsonTypeName("AVDOED_HAR_UTVANDRET")
data object AvdoedHarUtvandret : DoedshendelseKontrollpunkt() {
override val kode = "AVDOED_HAR_UTVANDRET"
override val beskrivelse: String = "Den avdøde har utvandret"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = true
override val avbryt: Boolean = false
}
@JsonTypeName("ANNEN_FORELDER_IKKE_FUNNET")
data object AnnenForelderIkkeFunnet : DoedshendelseKontrollpunkt() {
override val kode = "ANNEN_FORELDER_IKKE_FUNNET"
override val beskrivelse: String = "Klarer ikke finne den andre forelderen automatisk"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = true
override val avbryt: Boolean = false
}
@JsonTypeName("SAMTIDIG_DOEDSFALL")
data object SamtidigDoedsfall : DoedshendelseKontrollpunkt() {
override val kode = "SAMTIDIG_DOEDSFALL"
override val beskrivelse: String = "Personen har mistet begge foreldrene samtidig"
override val sendBrev: Boolean = true
override val opprettOppgave: Boolean = true
override val avbryt: Boolean = false
}
@JsonTypeName("EPS_HAR_SAK_I_GJENNY")
data class EpsHarSakIGjenny(val sak: Sak) : DoedshendelseKontrollpunkt() {
override val kode = "EPS_HAR_SAK_I_GJENNY"
override val beskrivelse: String = "Det eksisterer allerede en sak på EPS i Gjenny"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = false
override val avbryt: Boolean = true
}
@JsonTypeName("ANNULERT_DOEDSHENDELSE_PDL")
data class DuplikatGrunnlagsendringsHendelse(
val grunnlagsendringshendelseId: UUID,
val oppgaveId: UUID?,
) :
DoedshendelseKontrollpunkt() {
override val kode = "DUPLIKAT_GRUNNLAGSENDRINGSHENDELSE"
override val beskrivelse: String = "Det finnes en duplikat grunnlagsendringshendelse"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = false
override val avbryt: Boolean = true
}
@JsonTypeName("DOEDSHENDELSE_ER_ANNULLERT")
data object DoedshendelseErAnnullert : DoedshendelseKontrollpunkt() {
override val kode = "ANNULERT_DOEDSHENDELSE_PDL"
override val beskrivelse: String = "Dødshendelsen ble annulert i PDL"
override val sendBrev: Boolean = false
override val opprettOppgave: Boolean = false
override val avbryt: Boolean = true
}
}
fun List<DoedshendelseKontrollpunkt>.finnSak(): Sak? {
return this.filterIsInstance<EpsHarSakIGjenny>().firstOrNull()?.sak
}
fun List<DoedshendelseKontrollpunkt>.finnOppgaveId(): UUID? {
return this.filterIsInstance<DuplikatGrunnlagsendringsHendelse>().firstOrNull()?.oppgaveId
}
| 25 | Kotlin | 0 | 6 | e84b73f3decfa2cadfb02364fbd71ca96efbd948 | 7,348 | pensjon-etterlatte-saksbehandling | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.