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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wallet/wallet-app/src/main/kotlin/co/nilin/opex/wallet/app/controller/PaymentGatewayController.kt
|
opexdev
| 370,411,517
| false
| null |
package co.nilin.opex.wallet.app.controller
import co.nilin.opex.common.OpexError
import co.nilin.opex.wallet.app.dto.PaymentCurrency
import co.nilin.opex.wallet.app.dto.PaymentDepositRequest
import co.nilin.opex.wallet.app.dto.PaymentDepositResponse
import co.nilin.opex.wallet.core.inout.TransferCommand
import co.nilin.opex.wallet.core.model.Amount
import co.nilin.opex.wallet.core.spi.CurrencyService
import co.nilin.opex.wallet.core.spi.TransferManager
import co.nilin.opex.wallet.core.spi.WalletManager
import co.nilin.opex.wallet.core.spi.WalletOwnerManager
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.math.BigDecimal
@RestController
@RequestMapping("/payment")
class PaymentGatewayController(
val transferManager: TransferManager,
val currencyService: CurrencyService,
val walletManager: WalletManager,
val walletOwnerManager: WalletOwnerManager
) {
@PostMapping("/internal/deposit")
suspend fun paymentDeposit(@RequestBody request: PaymentDepositRequest): PaymentDepositResponse {
val receiverWalletType = "main"
val convertedAmount = when (request.currency) {
PaymentCurrency.RIALS -> (request.amount / BigDecimal.valueOf(10)).toLong()
PaymentCurrency.TOMAN -> request.amount.toLong()
}
val currency = currencyService.getCurrency("IRT") ?: throw OpexError.CurrencyNotFound.exception()
val sourceOwner = walletOwnerManager.findWalletOwner(walletOwnerManager.systemUuid)
?: throw OpexError.WalletOwnerNotFound.exception()
val sourceWallet = walletManager.findWalletByOwnerAndCurrencyAndType(sourceOwner, "main", currency)
?: walletManager.createWallet(sourceOwner, Amount(currency, BigDecimal.ZERO), currency, "main")
val receiverOwner = walletOwnerManager.findWalletOwner(request.userId)
?: walletOwnerManager.createWalletOwner(request.userId, "not set", "")
val receiverWallet = walletManager.findWalletByOwnerAndCurrencyAndType(
receiverOwner,
receiverWalletType,
currency
) ?: walletManager.createWallet(
receiverOwner,
Amount(currency, BigDecimal.ZERO),
currency,
receiverWalletType
)
val command = transferManager.transfer(
TransferCommand(
sourceWallet,
receiverWallet,
Amount(sourceWallet.currency, convertedAmount.toBigDecimal()),
request.description,
request.reference,
"DEPOSIT",
emptyMap()
)
)
return PaymentDepositResponse(true)
}
}
| 30
| null |
22
| 51
|
fedf3be46ee7fb85ca7177ae91b13dbc6f2e8a73
| 2,884
|
core
|
MIT License
|
data/slack-jackson-dto/src/main/kotlin/com/kreait/slack/api/contract/jackson/group/channels/Archive.kt
|
karora2
| 225,497,585
| true
|
{"Kotlin": 1205090, "Shell": 935}
|
package com.kreait.slack.api.contract.jackson.group.channels
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.kreait.slack.api.contract.jackson.util.JacksonDataClass
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "ok",
visible = true)
@JsonSubTypes(
JsonSubTypes.Type(value = SuccessfulChannelArchiveResponse::class, name = "true"),
JsonSubTypes.Type(value = ErrorChannelArchiveResponse::class, name = "false")
)
@JacksonDataClass
sealed class ChannelArchiveResponse constructor(@JsonProperty("ok") open val ok: Boolean)
/**
* Success-response of this request.
*
* @property ok will be true
*/
@JacksonDataClass
data class SuccessfulChannelArchiveResponse constructor(override val ok: Boolean)
: ChannelArchiveResponse(ok) {
companion object
}
/**
* Failure-response of this request
*
* @property ok will be false
* @property error contains the error description
*/
@JacksonDataClass
data class ErrorChannelArchiveResponse constructor(override val ok: Boolean,
@JsonProperty("error") val error: String)
: ChannelArchiveResponse(ok) {
companion object
}
/**
* Archives a channel.
*
* @property channel the channel-id you want to archive
* @see [Slack Api Method](https://api.slack.com/methods/channels.archive)
*/
@JacksonDataClass
data class ChannelsArchiveRequest constructor(@JsonProperty("channel") val channel: String) {
companion object
}
| 0
| null |
0
| 0
|
a46b9fcf8317d576133a4b1b4e64b89f6b3b1ca2
| 1,641
|
slack-spring-boot-starter
|
MIT License
|
glance/glance-appwidget-testing/samples/src/main/java/androidx/glance/appwidget/testing/samples/IsolatedGlanceComposableTestSamples.kt
|
androidx
| 256,589,781
| false
|
{"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
|
/*
* Copyright 2023 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 androidx.glance.appwidget.testing.samples
import androidx.annotation.Sampled
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.glance.GlanceModifier
import androidx.glance.LocalSize
import androidx.glance.appwidget.testing.unit.runGlanceAppWidgetUnitTest
import androidx.glance.layout.Column
import androidx.glance.layout.Row
import androidx.glance.layout.Spacer
import androidx.glance.layout.fillMaxSize
import androidx.glance.layout.width
import androidx.glance.semantics.semantics
import androidx.glance.semantics.testTag
import androidx.glance.testing.unit.hasTestTag
import androidx.glance.testing.unit.hasText
import androidx.glance.text.Text
import org.junit.Test
@Sampled
@Suppress("unused")
fun isolatedGlanceComposableTestSamples() {
class TestSample {
@Test
fun statusContent_statusFalse_outputsPending() = runGlanceAppWidgetUnitTest {
provideComposable { StatusRow(status = false) }
onNode(hasTestTag("status-text")).assert(hasText("Pending"))
}
@Test
fun statusContent_statusTrue_outputsFinished() = runGlanceAppWidgetUnitTest {
provideComposable { StatusRow(status = true) }
onNode(hasTestTag("status-text")).assert(hasText("Finished"))
}
@Test
fun header_smallSize_showsShortHeaderText() = runGlanceAppWidgetUnitTest {
setAppWidgetSize(DpSize(width = 50.dp, height = 100.dp))
provideComposable { StatusRow(status = false) }
onNode(hasTestTag("header-text")).assert(hasText("MyApp"))
}
@Test
fun header_largeSize_showsLongHeaderText() = runGlanceAppWidgetUnitTest {
setAppWidgetSize(DpSize(width = 150.dp, height = 100.dp))
provideComposable { StatusRow(status = false) }
onNode(hasTestTag("header-text")).assert(hasText("MyApp (Last order)"))
}
@Composable
fun WidgetContent(status: Boolean) {
Column {
Header()
Spacer()
StatusRow(status)
}
}
@Composable
fun Header() {
val width = LocalSize.current.width
Row(modifier = GlanceModifier.fillMaxSize()) {
Text(
text =
if (width > 50.dp) {
"MyApp (Last order)"
} else {
"MyApp"
},
modifier = GlanceModifier.semantics { testTag = "header-text" }
)
}
}
@Composable
fun StatusRow(status: Boolean) {
Row(modifier = GlanceModifier.fillMaxSize()) {
Text(
text = "Status",
)
Spacer(modifier = GlanceModifier.width(10.dp))
Text(
text =
if (status) {
"Pending"
} else {
"Finished"
},
modifier = GlanceModifier.semantics { testTag = "status-text" }
)
}
}
}
}
| 29
|
Kotlin
|
1011
| 5,321
|
98b929d303f34d569e9fd8a529f022d398d1024b
| 3,929
|
androidx
|
Apache License 2.0
|
jacodb-core/src/main/jooq/org/utbot/jacodb/impl/storage/jooq/tables/Annotationvalues.kt
|
UnitTestBot
| 491,176,077
| false
| null |
/*
* Copyright 2022 UnitTestBot contributors (utbot.org)
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
/*
* This file is generated by jOOQ.
*/
package org.jacodb.impl.storage.jooq.tables
import org.jacodb.impl.storage.jooq.tables.records.AnnotationvaluesRecord
import org.jooq.Field
import org.jooq.ForeignKey
import org.jooq.Name
import org.jooq.Record
import org.jooq.Row8
import org.jooq.Schema
import org.jooq.Table
import org.jooq.TableField
import org.jooq.TableOptions
import org.jooq.UniqueKey
import org.jooq.impl.DSL
import org.jooq.impl.Internal
import org.jooq.impl.SQLDataType
import org.jooq.impl.TableImpl
/**
* This class is generated by jOOQ.
*/
@Suppress("UNCHECKED_CAST")
open class Annotationvalues(
alias: Name,
child: Table<out Record>?,
path: ForeignKey<out Record, AnnotationvaluesRecord>?,
aliased: Table<AnnotationvaluesRecord>?,
parameters: Array<Field<*>?>?
): TableImpl<AnnotationvaluesRecord>(
alias,
org.jacodb.impl.storage.jooq.DefaultSchema.DEFAULT_SCHEMA,
child,
path,
aliased,
parameters,
DSL.comment(""),
TableOptions.table()
) {
companion object {
/**
* The reference instance of <code>AnnotationValues</code>
*/
val ANNOTATIONVALUES = Annotationvalues()
}
/**
* The class holding records for this type
*/
override fun getRecordType(): Class<AnnotationvaluesRecord> = AnnotationvaluesRecord::class.java
/**
* The column <code>AnnotationValues.id</code>.
*/
val ID: TableField<AnnotationvaluesRecord, Long?> = createField(DSL.name("id"), SQLDataType.BIGINT, this, "")
/**
* The column <code>AnnotationValues.annotation_id</code>.
*/
val ANNOTATION_ID: TableField<AnnotationvaluesRecord, Long?> = createField(DSL.name("annotation_id"), SQLDataType.BIGINT.nullable(false), this, "")
/**
* The column <code>AnnotationValues.name</code>.
*/
val NAME: TableField<AnnotationvaluesRecord, String?> = createField(DSL.name("name"), SQLDataType.VARCHAR(256).nullable(false), this, "")
/**
* The column <code>AnnotationValues.ref_annotation_id</code>.
*/
val REF_ANNOTATION_ID: TableField<AnnotationvaluesRecord, Long?> = createField(DSL.name("ref_annotation_id"), SQLDataType.BIGINT, this, "")
/**
* The column <code>AnnotationValues.kind</code>.
*/
val KIND: TableField<AnnotationvaluesRecord, Int?> = createField(DSL.name("kind"), SQLDataType.INTEGER, this, "")
/**
* The column <code>AnnotationValues.value</code>.
*/
val VALUE: TableField<AnnotationvaluesRecord, String?> = createField(DSL.name("value"), SQLDataType.CLOB, this, "")
/**
* The column <code>AnnotationValues.class_symbol</code>.
*/
val CLASS_SYMBOL: TableField<AnnotationvaluesRecord, Long?> = createField(DSL.name("class_symbol"), SQLDataType.BIGINT, this, "")
/**
* The column <code>AnnotationValues.enum_value</code>.
*/
val ENUM_VALUE: TableField<AnnotationvaluesRecord, Long?> = createField(DSL.name("enum_value"), SQLDataType.BIGINT, this, "")
private constructor(alias: Name, aliased: Table<AnnotationvaluesRecord>?): this(alias, null, null, aliased, null)
private constructor(alias: Name, aliased: Table<AnnotationvaluesRecord>?, parameters: Array<Field<*>?>?): this(alias, null, null, aliased, parameters)
/**
* Create an aliased <code>AnnotationValues</code> table reference
*/
constructor(alias: String): this(DSL.name(alias))
/**
* Create an aliased <code>AnnotationValues</code> table reference
*/
constructor(alias: Name): this(alias, null)
/**
* Create a <code>AnnotationValues</code> table reference
*/
constructor(): this(DSL.name("AnnotationValues"), null)
constructor(child: Table<out Record>, key: ForeignKey<out Record, AnnotationvaluesRecord>): this(Internal.createPathAlias(child, key), child, key, ANNOTATIONVALUES, null)
override fun getSchema(): Schema = org.jacodb.impl.storage.jooq.DefaultSchema.DEFAULT_SCHEMA
override fun getPrimaryKey(): UniqueKey<AnnotationvaluesRecord> =
org.jacodb.impl.storage.jooq.keys.PK_ANNOTATIONVALUES
override fun getKeys(): List<UniqueKey<AnnotationvaluesRecord>> = listOf(org.jacodb.impl.storage.jooq.keys.PK_ANNOTATIONVALUES)
override fun getReferences(): List<ForeignKey<AnnotationvaluesRecord, *>> = listOf(
org.jacodb.impl.storage.jooq.keys.FK_ANNOTATIONVALUES_ANNOTATIONS_2,
org.jacodb.impl.storage.jooq.keys.FK_ANNOTATIONVALUES_ANNOTATIONS_1,
org.jacodb.impl.storage.jooq.keys.FK_ANNOTATIONVALUES_SYMBOLS_1,
org.jacodb.impl.storage.jooq.keys.FK_ANNOTATIONVALUES_SYMBOLS_2
)
private lateinit var _fkAnnotationvaluesAnnotations_2: org.jacodb.impl.storage.jooq.tables.Annotations
private lateinit var _fkAnnotationvaluesAnnotations_1: org.jacodb.impl.storage.jooq.tables.Annotations
private lateinit var _fkAnnotationvaluesSymbols_1: Symbols
private lateinit var _fkAnnotationvaluesSymbols_2: Symbols
fun fkAnnotationvaluesAnnotations_2(): org.jacodb.impl.storage.jooq.tables.Annotations {
if (!this::_fkAnnotationvaluesAnnotations_2.isInitialized)
_fkAnnotationvaluesAnnotations_2 = org.jacodb.impl.storage.jooq.tables.Annotations(
this,
org.jacodb.impl.storage.jooq.keys.FK_ANNOTATIONVALUES_ANNOTATIONS_2
)
return _fkAnnotationvaluesAnnotations_2;
}
fun fkAnnotationvaluesAnnotations_1(): org.jacodb.impl.storage.jooq.tables.Annotations {
if (!this::_fkAnnotationvaluesAnnotations_1.isInitialized)
_fkAnnotationvaluesAnnotations_1 = org.jacodb.impl.storage.jooq.tables.Annotations(
this,
org.jacodb.impl.storage.jooq.keys.FK_ANNOTATIONVALUES_ANNOTATIONS_1
)
return _fkAnnotationvaluesAnnotations_1;
}
fun fkAnnotationvaluesSymbols_1(): Symbols {
if (!this::_fkAnnotationvaluesSymbols_1.isInitialized)
_fkAnnotationvaluesSymbols_1 = Symbols(this,
org.jacodb.impl.storage.jooq.keys.FK_ANNOTATIONVALUES_SYMBOLS_1
)
return _fkAnnotationvaluesSymbols_1;
}
fun fkAnnotationvaluesSymbols_2(): Symbols {
if (!this::_fkAnnotationvaluesSymbols_2.isInitialized)
_fkAnnotationvaluesSymbols_2 = Symbols(this,
org.jacodb.impl.storage.jooq.keys.FK_ANNOTATIONVALUES_SYMBOLS_2
)
return _fkAnnotationvaluesSymbols_2;
}
override fun `as`(alias: String): Annotationvalues = Annotationvalues(DSL.name(alias), this)
override fun `as`(alias: Name): Annotationvalues = Annotationvalues(alias, this)
/**
* Rename this table
*/
override fun rename(name: String): Annotationvalues = Annotationvalues(DSL.name(name), null)
/**
* Rename this table
*/
override fun rename(name: Name): Annotationvalues = Annotationvalues(name, null)
// -------------------------------------------------------------------------
// Row8 type methods
// -------------------------------------------------------------------------
override fun fieldsRow(): Row8<Long?, Long?, String?, Long?, Int?, String?, Long?, Long?> = super.fieldsRow() as Row8<Long?, Long?, String?, Long?, Int?, String?, Long?, Long?>
}
| 22
| null |
7
| 7
|
e3df0f19858d502ea974d97be9ec7b93aed9207a
| 7,930
|
jacodb
|
Apache License 2.0
|
app/src/main/java/com/harissabil/meakanu/ui/home/HomeFragment.kt
|
harissabil
| 674,502,207
| false
|
{"Kotlin": 134092}
|
package com.harissabil.meakanu.ui.home
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.PopupMenu
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.harissabil.meakanu.R
import com.harissabil.meakanu.data.local.entity.PlantEntity
import com.harissabil.meakanu.databinding.FragmentHomeBinding
import com.harissabil.meakanu.helper.MoreClicked
import com.harissabil.meakanu.helper.deleteImage
import com.harissabil.meakanu.ui.ViewModelFactory
class HomeFragment : Fragment(), MoreClicked {
private var _binding: FragmentHomeBinding? = null
private val homeViewModel by viewModels<HomeViewModel> {
ViewModelFactory.getInstance(requireActivity())
}
private lateinit var historyListAdapter: HistoryListAdapter
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as AppCompatActivity?)!!.setSupportActionBar(binding.toolbar)
(activity as AppCompatActivity?)!!.supportActionBar!!.setDisplayShowTitleEnabled(false)
historyListAdapter = HistoryListAdapter(this)
binding.rvHistory.setHasFixedSize(false)
binding.rvHistory.layoutManager = LinearLayoutManager(requireContext())
binding.rvHistory.isNestedScrollingEnabled = false
binding.rvHistory.adapter = historyListAdapter
binding.rvHistory.adapter?.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
val menuHost: MenuHost = requireActivity()
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.toolbar_option_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.action_about -> {
findNavController().navigate(
R.id.action_navigation_home_to_aboutFragment
)
true
}
else -> false
}
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
binding.cvBanner.setOnClickListener {
homeViewModel.clickBanner()
}
homeViewModel.getLatest().observe(viewLifecycleOwner) { history ->
if (!history.isNullOrEmpty()) {
historyListAdapter.submitList(history)
binding.rvHistory.visibility = View.VISIBLE
binding.tvNoHistory.visibility = View.GONE
} else {
binding.tvNoHistory.visibility = View.VISIBLE
binding.rvHistory.visibility = View.GONE
}
}
homeViewModel.count.observe(viewLifecycleOwner) {
if (it == 10) {
Toast.makeText(
requireContext(),
"Beautiful isn't it?",
Toast.LENGTH_SHORT
).show()
homeViewModel.resetCount()
}
}
binding.cvScan.setOnClickListener {
binding.cvScan.findNavController().navigate(R.id.action_navigation_home_to_scanFragment)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun popUpMenu(view: View, plant: PlantEntity) {
val popUpMenu = PopupMenu(requireContext(), view, Gravity.END)
popUpMenu.inflate(R.menu.menu_pop_up_list)
popUpMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.delete -> {
deleteDialog(plant)
true
}
else -> {
false
}
}
}
popUpMenu.show()
}
private fun deleteDialog(plant: PlantEntity) {
val builder = MaterialAlertDialogBuilder(requireContext())
builder.setTitle("Delete observation?")
builder.setMessage("Observation will be permanently removed from your device.")
builder.setPositiveButton("Delete") { _, _ ->
if (!plant.image.isNullOrBlank()) {
deleteImage(plant.image!!)
homeViewModel.delete(plant)
}
Snackbar.make(binding.root, "Observation deleted", Snackbar.LENGTH_SHORT).show()
}
builder.setNegativeButton("Cancel") { _, _ ->
}
builder.show()
}
}
| 0
|
Kotlin
|
0
| 0
|
1a071034a26cb6e11bf89b975a36f8a16e9f074c
| 5,663
|
Meakanu
|
MIT License
|
app/src/main/java/iv/nakonechnyi/gituser/ui/ItemTouchHelperAdapter.kt
|
gembrilus
| 231,839,047
| false
| null |
package iv.nakonechnyi.gituser.ui
interface ItemTouchHelperAdapter {
fun onItemDelete(position: Int)
}
| 0
|
Kotlin
|
0
| 0
|
c91b1d787e33958cf4963b32671718dcc6018c07
| 109
|
geekhub2020-GitUser
|
MIT License
|
recorder-core/src/main/java/me/shetj/recorder/core/BaseRecorder.kt
|
yinyangwu
| 336,732,908
| true
|
{"Kotlin": 352777, "Java": 8224}
|
package me.shetj.recorder.core
import android.content.Context
import android.media.MediaRecorder
import android.net.Uri
import android.util.Log
import me.shetj.player.PlayerListener
import java.io.File
import kotlin.math.sqrt
abstract class BaseRecorder {
private val TAG = this.javaClass.simpleName
//region 录音的方式 /来源 Record Type
enum class RecorderType {
SIM, //
MIX
}
enum class AudioSource(var type: Int) {
MIC(MediaRecorder.AudioSource.MIC),
VOICE_COMMUNICATION(MediaRecorder.AudioSource.VOICE_COMMUNICATION)
}
/**
* MONO(1), //单声道
* STEREO(2) //双声道
*/
enum class AudioChannel(var type: Int) {
MONO(1), //单声道
STEREO(2) //双声道
}
//endregion Record Type
//region 录音的状态,声音和时间
protected var mVolume: Int = 0
var isRecording = false
protected set
//当前状态
var state = RecordState.STOPPED
protected set
//录制时间
var duration = 0L
protected set
var isPause: Boolean = false
private var isDebug = false
//endregion 录音的状态和时间
//region public method 公开的方法
abstract val realVolume: Int
//设置是否使用耳机配置方式
abstract fun setContextToPlugConfig(context: Context): BaseRecorder
abstract fun setContextToVolumeConfig(context: Context): BaseRecorder
//设置输出路径
abstract fun setOutputFile(outputFile: String, isContinue: Boolean = false): BaseRecorder
//设置输出路径
abstract fun setOutputFile(outputFile: File, isContinue: Boolean = false): BaseRecorder
//设置录音监听
abstract fun setRecordListener(recordListener: RecordListener?): BaseRecorder
//设置权限监听
abstract fun setPermissionListener(permissionListener: PermissionListener?): BaseRecorder
//设计背景音乐的url,本地的
abstract fun setBackgroundMusic(url: String): BaseRecorder
/**
* 设计背景音乐的url,网络(Internet) 或者 本地
*/
abstract fun setBackgroundMusic(context: Context,uri: Uri,header:MutableMap<String,String>?): BaseRecorder
//设置背景音乐的监听
abstract fun setBackgroundMusicListener(listener: PlayerListener): BaseRecorder
//初始Lame录音输出质量
abstract fun setMp3Quality(mp3Quality: Int): BaseRecorder
//设置比特率,关系声音的质量
abstract fun setMp3BitRate(mp3BitRate: Int): BaseRecorder
//设置采样率
abstract fun setSamplingRate(rate: Int): BaseRecorder
//初始最大录制时间 和提醒时间 remind = maxTime - remindDiffTime
abstract fun setMaxTime(maxTime: Int, remindDiffTime: Int? = null): BaseRecorder
//设置增强系数
abstract fun setWax(wax: Float): BaseRecorder
//设置背景声音大小
abstract fun setVolume(volume: Float): BaseRecorder
//开始录音
abstract fun start()
//停止录音
abstract fun stop()
//重新开始录音
abstract fun onResume()
//替换输出文件
abstract fun updateDataEncode(outputFilePath: String)
//暂停录音
abstract fun onPause()
//开始播放音乐
abstract fun startPlayMusic()
//是否在播放音乐
abstract fun isPauseMusic(): Boolean
//暂停背景音乐
abstract fun pauseMusic()
//重新播放背景音乐
abstract fun resumeMusic()
//重置
abstract fun onReset()
//结束释放
abstract fun onDestroy()
//endregion public method
//region 计算真正的时间,如果过程中有些数据太小,就直接置0,防止噪音
fun setDebug(isDebug: Boolean): BaseRecorder {
this.isDebug = isDebug
return this
}
protected fun calculateRealVolume(buffer: ShortArray, readSize: Int) {
var sum = 0.0
for (i in 0 until readSize) {
// 这里没有做运算的优化,为了更加清晰的展示代码
sum += (buffer[i] * buffer[i]).toDouble()
}
if (readSize > 0) {
val amplitude = sum / readSize
mVolume = sqrt(amplitude).toInt()
if (mVolume < 5) {
for (i in 0 until readSize) {
buffer[i] = 0
}
}
}
}
protected fun calculateRealVolume(buffer: ByteArray) {
val shorts = BytesTransUtil.bytes2Shorts(buffer)
val readSize = shorts.size
calculateRealVolume(shorts, readSize)
}
protected fun logInfo(info: String) {
if (isDebug) {
Log.d(TAG, info)
}
}
//endregion 计算真正的时间,如果过程中有些数据太小,就直接置0,防止噪音
}
| 0
| null |
0
| 0
|
863f0ed65b8a751cd16f3c79f55cda0c382ad76d
| 4,176
|
Mp3Recorder
|
MIT License
|
core/src/main/java/com/flyview/core/utils/DecomposeUtils.kt
|
DmiMukh
| 676,402,705
| false
|
{"Kotlin": 288475, "Java": 130379}
|
package com.flyview.core.utils
import com.arkivanov.decompose.ComponentContext
import com.arkivanov.decompose.value.Value
import com.arkivanov.essenty.instancekeeper.InstanceKeeper
import com.arkivanov.essenty.lifecycle.Lifecycle
import com.arkivanov.essenty.lifecycle.doOnDestroy
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
fun <T : Any> Value<T>.toStateFlow(lifecycle: Lifecycle): StateFlow<T> {
val state = MutableStateFlow(this.value)
if (lifecycle.state != Lifecycle.State.DESTROYED) {
val observer = { value: T -> state.value = value }
subscribe(observer)
lifecycle.doOnDestroy {
unsubscribe(observer)
}
}
return state
}
fun ComponentContext.componentCoroutineScope(): CoroutineScope {
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
if (lifecycle.state != Lifecycle.State.DESTROYED) {
lifecycle.doOnDestroy {
scope.cancel()
}
} else {
scope.cancel()
}
return scope
}
/**
* Creates a coroutine scope tied to Decompose lifecycle. A scope is canceled when a component is destroyed.
*/
val ComponentContext.componentScope: CoroutineScope
get() {
val scope = (instanceKeeper.get(ComponentScopeKey) as? CoroutineScopeWrapper)?.scope
if (scope != null) return scope
val newScope = lifecycle.coroutineScope()
instanceKeeper.put(ComponentScopeKey, CoroutineScopeWrapper(newScope))
return newScope
}
private object ComponentScopeKey
private class CoroutineScopeWrapper(val scope: CoroutineScope) : InstanceKeeper.Instance {
override fun onDestroy() {
// nothing
}
}
fun Lifecycle.coroutineScope(): CoroutineScope {
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
if (this.state != Lifecycle.State.DESTROYED) {
this.doOnDestroy {
scope.cancel()
}
} else {
scope.cancel()
}
return scope
}
| 0
|
Kotlin
|
0
| 0
|
5c184121116c08abe217946ba7da27804c232edb
| 2,182
|
PharmMobile
|
MIT License
|
chapter-final/app/src/main/java/com/example/learnwithme/data/datasource/character/remote/rickandmorty/dto/CharacterInfoDTO.kt
|
fsalom
| 677,505,777
| false
|
{"Kotlin": 288407}
|
package com.example.learnwithme.data.datasource.character.remote.rickandmorty.dto
import com.example.learnwithme.domain.entity.Pagination
import com.google.gson.annotations.SerializedName
data class CharactersInfoDTO(
@SerializedName("info") val info: PaginationDTO? = PaginationDTO(),
@SerializedName("results") val results : List<CharacterDTO> = listOf()
)
data class PaginationDTO(
@SerializedName("count") var count : Int? = 0,
@SerializedName("pages") var pages : Int? = 0,
@SerializedName("next") var next : String? = "null",
@SerializedName("prev") var prev : String? = ""
)
| 0
|
Kotlin
|
0
| 0
|
364d2274c1b945be9d09b554c85aeed1a8783325
| 612
|
android-compose-chapters
|
MIT License
|
app/src/main/java/es/upm/bienestaremocional/data/database/AppDatabase.kt
|
Emotional-Wellbeing
| 531,973,820
| false
| null |
package es.upm.bienestaremocional.data.database
import androidx.room.Database
import androidx.room.RoomDatabase
import es.upm.bienestaremocional.data.database.dao.AppDAO
import es.upm.bienestaremocional.data.database.entity.LastUpload
import es.upm.bienestaremocional.data.database.entity.PHQ
import es.upm.bienestaremocional.data.database.entity.PSS
import es.upm.bienestaremocional.data.database.entity.QuestionnaireRound
import es.upm.bienestaremocional.data.database.entity.UCLA
/**
* Instance of app database
*/
@Database(
entities = [
QuestionnaireRound::class,
PHQ::class,
PSS::class,
UCLA::class,
LastUpload::class
],
version = 1,
exportSchema = false
)
abstract class AppDatabase : RoomDatabase()
{
abstract fun appDao(): AppDAO
}
| 0
|
Kotlin
|
0
| 1
|
1f579af1073a4a8ac99011b0a881a5dcfb424821
| 802
|
App
|
Apache License 2.0
|
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/activity/coin_collect/CoinCollectGallerySettleNotify.kt
|
Anime-Game-Servers
| 642,871,918
| false
|
{"Kotlin": 1651536}
|
package org.anime_game_servers.multi_proto.gi.data.activity.coin_collect
import org.anime_game_servers.core.base.Version.GI_3_3_0
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.annotations.proto.CommandType.*
import org.anime_game_servers.core.base.annotations.proto.ProtoCommand
@AddedIn(GI_3_3_0)
@ProtoCommand(NOTIFY)
internal interface CoinCollectGallerySettleNotify {
var isNewRecord: Boolean
var levelId: Int
var multistagePlayIndex: Int
var coinCollectNum: Int
var coinCollectTime: Int
var coinTotalNum: Int
}
| 0
|
Kotlin
|
2
| 6
|
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
| 596
|
anime-game-multi-proto
|
MIT License
|
app/src/main/java/com/example/newsappwithcompose/domain/usecase/app_entry/AppEntryUseCases.kt
|
shirinvn
| 724,400,509
| false
|
{"Kotlin": 99787}
|
package com.example.newsappwithcompose.domain.usecase.app_entry
data class AppEntryUseCases(
val readAppEntry: ReadAppEntry,
val saveAppEntry: SaveAppEntry
)
| 0
|
Kotlin
|
0
| 0
|
20071c9a768e28a98636a1ea9b227c36bb60e654
| 167
|
NewsAppWithCompose
|
MIT License
|
cupertino-icons-extended/src/commonMain/kotlin/io/github/alexzhirkevich/cupertino/icons/outlined/Tshirt.kt
|
alexzhirkevich
| 636,411,288
| false
|
{"Kotlin": 5215549, "Ruby": 2329, "Swift": 2101, "HTML": 2071, "Shell": 868}
|
/*
* Copyright (c) 2023-2024. Compose Cupertino project and open source contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.github.alexzhirkevich.cupertino.icons.outlined
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import io.github.alexzhirkevich.cupertino.icons.CupertinoIcons
public val CupertinoIcons.Outlined.Tshirt: ImageVector
get() {
if (_tshirt != null) {
return _tshirt!!
}
_tshirt = Builder(name = "Tshirt", defaultWidth = 30.9801.dp, defaultHeight = 25.6992.dp,
viewportWidth = 30.9801f, viewportHeight = 25.6992f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(9.5405f, 25.6992f)
lineTo(21.4467f, 25.6992f)
curveTo(23.4623f, 25.6992f, 24.728f, 24.4453f, 24.7631f, 22.4414f)
lineTo(24.9155f, 11.0039f)
lineTo(27.7163f, 11.6484f)
curveTo(28.8413f, 11.9062f, 29.5678f, 11.4375f, 29.8608f, 10.2773f)
lineTo(30.892f, 6.1172f)
curveTo(31.185f, 4.9688f, 30.7397f, 4.1719f, 29.6616f, 3.7148f)
lineTo(21.5053f, 0.2344f)
curveTo(20.8959f, -0.0352f, 20.4858f, -0.0117f, 19.9819f, 0.2227f)
curveTo(18.4584f, 0.9492f, 17.2163f, 1.3242f, 15.4936f, 1.3242f)
curveTo(13.7592f, 1.3242f, 12.5288f, 0.9492f, 10.9936f, 0.2227f)
curveTo(10.5014f, -0.0117f, 10.0795f, -0.0352f, 9.4702f, 0.2344f)
lineTo(1.3256f, 3.7148f)
curveTo(0.2358f, 4.1719f, -0.1978f, 4.9688f, 0.0834f, 6.1172f)
lineTo(1.1264f, 10.2773f)
curveTo(1.4077f, 11.4375f, 2.1342f, 11.9062f, 3.2709f, 11.6484f)
lineTo(6.0717f, 11.0039f)
lineTo(6.2241f, 22.4414f)
curveTo(6.2475f, 24.4453f, 7.5131f, 25.6992f, 9.5405f, 25.6992f)
close()
moveTo(9.5639f, 23.8945f)
curveTo(8.6147f, 23.8945f, 8.0405f, 23.3086f, 8.0288f, 22.3477f)
lineTo(7.8647f, 9.2813f)
curveTo(7.8647f, 9.0f, 7.642f, 8.8008f, 7.3256f, 8.8711f)
lineTo(3.2241f, 9.7852f)
curveTo(3.0014f, 9.832f, 2.8491f, 9.7383f, 2.8022f, 9.5508f)
lineTo(1.8764f, 5.8594f)
curveTo(1.8061f, 5.5664f, 1.8881f, 5.4609f, 2.1225f, 5.3672f)
lineTo(10.5483f, 1.7695f)
curveTo(12.1186f, 2.6016f, 13.642f, 3.0234f, 15.4936f, 3.0234f)
curveTo(17.3452f, 3.0234f, 18.8569f, 2.6016f, 20.4389f, 1.7695f)
lineTo(28.8647f, 5.3672f)
curveTo(29.0873f, 5.4609f, 29.1811f, 5.5664f, 29.1108f, 5.8594f)
lineTo(28.1733f, 9.5508f)
curveTo(28.1264f, 9.7383f, 27.9858f, 9.832f, 27.7631f, 9.7852f)
lineTo(23.6616f, 8.8711f)
curveTo(23.3334f, 8.8008f, 23.1225f, 9.0f, 23.1225f, 9.2813f)
lineTo(22.9584f, 22.3477f)
curveTo(22.9467f, 23.3086f, 22.3725f, 23.8945f, 21.4233f, 23.8945f)
close()
moveTo(15.4936f, 6.5391f)
curveTo(18.2592f, 6.5391f, 20.7084f, 4.5703f, 21.2241f, 1.8516f)
lineTo(19.5131f, 1.1016f)
curveTo(19.267f, 3.1758f, 17.5092f, 4.7344f, 15.4936f, 4.7344f)
curveTo(13.4663f, 4.7344f, 11.7202f, 3.1758f, 11.4741f, 1.1016f)
lineTo(9.7631f, 1.8516f)
curveTo(10.267f, 4.5703f, 12.7163f, 6.5391f, 15.4936f, 6.5391f)
close()
}
}
.build()
return _tshirt!!
}
private var _tshirt: ImageVector? = null
| 18
|
Kotlin
|
31
| 848
|
54bfbb58f6b36248c5947de343567903298ee308
| 4,847
|
compose-cupertino
|
Apache License 2.0
|
compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalChainedScope.kt
|
JakeWharton
| 99,388,807
| false
| null |
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.resolve.scopes
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.DescriptorWithDeprecation
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.scopes.utils.takeSnapshot
import org.jetbrains.kotlin.util.collectionUtils.getFirstClassifierDiscriminateHeaders
import org.jetbrains.kotlin.util.collectionUtils.getFromAllScopes
import org.jetbrains.kotlin.util.collectionUtils.listOfNonEmptyScopes
import org.jetbrains.kotlin.utils.Printer
class LexicalChainedScope private constructor(
parent: LexicalScope,
override val ownerDescriptor: DeclarationDescriptor,
override val isOwnerDescriptorAccessibleByLabel: Boolean,
override val implicitReceiver: ReceiverParameterDescriptor?,
override val kind: LexicalScopeKind,
// NB. Here can be very special subtypes of MemberScope (e.g., DeprecatedMemberScope).
// Please, do not leak them outside of LexicalChainedScope, because other parts of compiler are not ready to work with them
private val memberScopes: Array<MemberScope>,
@Deprecated("This value is temporary hack for resolve -- don't use it!")
val isStaticScope: Boolean = false
) : LexicalScope {
override val parent = parent.takeSnapshot()
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean) =
getFromAllScopes(memberScopes) { it.getContributedDescriptors() }
override fun getContributedClassifier(name: Name, location: LookupLocation) =
getFirstClassifierDiscriminateHeaders(memberScopes) { it.getContributedClassifier(name, location) }
override fun getContributedClassifierIncludeDeprecated(name: Name, location: LookupLocation): DescriptorWithDeprecation<ClassifierDescriptor>? {
val (firstClassifier, isFirstDeprecated) = memberScopes.firstNotNullOfOrNull {
it.getContributedClassifierIncludeDeprecated(name, location)
} ?: return null
if (!isFirstDeprecated) return DescriptorWithDeprecation.createNonDeprecated(firstClassifier)
// Slow-path: try to find the same classifier, but without deprecation
for (scope in memberScopes) {
val (descriptor, isDeprecated) = scope.getContributedClassifierIncludeDeprecated(name, location) ?: continue
if (descriptor == firstClassifier && !isDeprecated) return DescriptorWithDeprecation.createNonDeprecated(descriptor)
}
return DescriptorWithDeprecation.createDeprecated(firstClassifier)
}
override fun getContributedVariables(name: Name, location: LookupLocation) =
getFromAllScopes(memberScopes) { it.getContributedVariables(name, location) }
override fun getContributedFunctions(name: Name, location: LookupLocation) =
getFromAllScopes(memberScopes) { it.getContributedFunctions(name, location) }
override fun toString(): String = kind.toString()
override fun printStructure(p: Printer) {
p.println(
this::class.java.simpleName, ": ", kind, "; for descriptor: ", ownerDescriptor.name,
" with implicitReceiver: ", implicitReceiver?.value ?: "NONE", " {"
)
p.pushIndent()
for (scope in memberScopes) {
scope.printScopeStructure(p)
}
p.print("parent = ")
parent.printStructure(p.withholdIndentOnce())
p.popIndent()
p.println("}")
}
override fun definitelyDoesNotContainName(name: Name): Boolean {
return memberScopes.all { it.definitelyDoesNotContainName(name) }
}
override fun recordLookup(name: Name, location: LookupLocation) {
memberScopes.forEach { it.recordLookup(name, location) }
}
companion object {
@JvmOverloads
fun create(
parent: LexicalScope,
ownerDescriptor: DeclarationDescriptor,
isOwnerDescriptorAccessibleByLabel: Boolean,
implicitReceiver: ReceiverParameterDescriptor?,
kind: LexicalScopeKind,
vararg memberScopes: MemberScope?,
isStaticScope: Boolean = false
): LexicalScope =
LexicalChainedScope(
parent, ownerDescriptor, isOwnerDescriptorAccessibleByLabel, implicitReceiver, kind,
listOfNonEmptyScopes(*memberScopes).toTypedArray(),
isStaticScope
)
}
}
| 181
| null |
5748
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 5,221
|
kotlin
|
Apache License 2.0
|
src/commonMain/kotlin/com/sunnychung/lib/multiplatform/kdatetime/KDateTimeFormat.kt
|
sunny-chung
| 692,666,572
| false
| null |
package com.sunnychung.lib.multiplatform.kdatetime
import com.sunnychung.lib.multiplatform.kdatetime.KGregorianCalendar.dayOfWeek
/**
* Formats:
*
* Symbol Meaning Examples
* ------ ------- --------
* y year 2023; 23
* M month 7; 07
* d day of month 9; 09; 31
*
* H hour (0~23) 0; 00; 18
* h hour (1~12) 6; 06; 10
* m minute 4; 04; 58
* s second 5; 05; 59
* l millisecond 12; 120; 123
*
* aa am/pm am; pm
* AA AM/PM AM; PM
* e Day of week. 0=Sun, 6=Sat. 1
* E Day of week. Mon
*
* Z Time zone offset or 'Z' Z; +08:00
* z Time zone offset +00:00; +08:00
*
* ' Literal '
*/
class KDateTimeFormat(val pattern: String) {
var weekDayNames = WEEKDAY_NAMES
set(value) {
if (value.size != 7) throw IllegalArgumentException("`weekDayNames` must be a list of 7 string elements")
field = value.toList()
}
enum class FormatTokenType(val hasLengthLimit: Boolean = true, val allowedLengths: List<Int> = listOf()) {
Literial(hasLengthLimit = false),
Year(allowedLengths = listOf(2, 4)),
Month(allowedLengths = listOf(1, 2)),
DayOfMonth(allowedLengths = listOf(1, 2)),
Hour_0_23(allowedLengths = listOf(1, 2)),
Hour_1_12(allowedLengths = listOf(1, 2)),
Minute(allowedLengths = listOf(1, 2)),
Second(allowedLengths = listOf(1, 2)),
Millisecond(allowedLengths = listOf(1, 2, 3)),
ampm(allowedLengths = listOf(2)),
AMPM(allowedLengths = listOf(2)),
DayOfWeekNumber(allowedLengths = listOf(1)),
DayOfWeek(allowedLengths = listOf(1)),
TimeZoneOffsetOrZ(allowedLengths = listOf(1)),
TimeZoneOffset(allowedLengths = listOf(1)),
}
data class FormatToken(val type: FormatTokenType, val length: Int, val literal: String? = null)
val tokens: List<FormatToken>
init {
val tokens = mutableListOf<FormatToken>()
var isConsumingLiteral = false
var literal = StringBuilder()
var type: FormatTokenType? = null
var prevType: FormatTokenType? = null
var length = 0
fun addPrevToken() {
prevType?.let { prevType ->
if (prevType.hasLengthLimit && !prevType.allowedLengths.contains(length)) {
throw IllegalArgumentException("Invalid length of the token type $prevType. Allowed length: ${prevType.allowedLengths}; actual length: $length")
}
val token = if (prevType == FormatTokenType.Literial) {
FormatToken(type = prevType, length = literal.length, literal = literal.toString())
} else {
FormatToken(type = prevType, length = length)
}
tokens += token
}
}
pattern.forEach {
var ignoreCurrentChar = false
if (isConsumingLiteral && it != '\'') {
type = FormatTokenType.Literial
} else if (it == '\'') {
type = FormatTokenType.Literial
isConsumingLiteral = !isConsumingLiteral
ignoreCurrentChar = true
} else {
type = when (it) {
'y' -> FormatTokenType.Year
'M' -> FormatTokenType.Month
'd' -> FormatTokenType.DayOfMonth
'H' -> FormatTokenType.Hour_0_23
'h' -> FormatTokenType.Hour_1_12
'm' -> FormatTokenType.Minute
's' -> FormatTokenType.Second
'l' -> FormatTokenType.Millisecond
'a' -> FormatTokenType.ampm
'A' -> FormatTokenType.AMPM
'e' -> FormatTokenType.DayOfWeekNumber
'E' -> FormatTokenType.DayOfWeek
'Z' -> FormatTokenType.TimeZoneOffsetOrZ
'z' -> FormatTokenType.TimeZoneOffset
else -> FormatTokenType.Literial
}
}
if (type == prevType) {
++length
} else {
addPrevToken()
prevType = type
literal.clear()
length = 1
}
if (!ignoreCurrentChar && type == FormatTokenType.Literial) {
literal.append(it)
}
}
prevType = type
addPrevToken()
this.tokens = tokens.toList()
}
fun format(datetime: KDateTimeFormattable): String {
val localDateTime = datetime
val localDate by lazy {
if (datetime is KZonedInstant) {
datetime.datePart()
} else {
KGregorianCalendar.utcDateFromTimestamp(localDateTime.toMilliseconds())
}
}
val s = StringBuilder()
tokens.forEach {
when (it.type) {
FormatTokenType.Literial -> s.append(it.literal)
FormatTokenType.Year -> s.append(localDate.year.toString().substring(if (it.length == 2) 2 else 0))
FormatTokenType.Month -> s.append(localDate.month.toString().padStart(it.length, '0'))
FormatTokenType.DayOfMonth -> s.append(localDate.day.toString().padStart(it.length, '0'))
FormatTokenType.Hour_0_23 -> s.append(localDateTime.hourPart().toString().padStart(it.length, '0'))
FormatTokenType.Hour_1_12 -> {
val halfHour = localDateTime.hourPart() % 12
s.append((if (halfHour == 0) 12 else halfHour).toString().padStart(it.length, '0'))
}
FormatTokenType.Minute -> s.append(localDateTime.minutePart().toString().padStart(it.length, '0'))
FormatTokenType.Second -> s.append(localDateTime.secondPart().toString().padStart(it.length, '0'))
FormatTokenType.Millisecond -> s.append(localDateTime.millisecondPart().toString().padStart(3, '0').trimEnd('0').padEnd(it.length, '0'))
FormatTokenType.ampm -> s.append(if (localDateTime.hourPart() < 12) "am" else "pm")
FormatTokenType.AMPM -> s.append(if (localDateTime.hourPart() < 12) "AM" else "PM")
FormatTokenType.DayOfWeekNumber -> s.append(localDate.dayOfWeek())
FormatTokenType.DayOfWeek -> s.append(weekDayNames[localDate.dayOfWeek()])
FormatTokenType.TimeZoneOffsetOrZ -> when (datetime) {
is KZonedInstant -> s.append(datetime.zoneOffset.toDisplayString())
is KInstant -> s.append("Z")
else -> throw UnsupportedOperationException("${datetime::class.simpleName} has no timezone support")
}
FormatTokenType.TimeZoneOffset -> when (datetime) {
is KZonedInstant -> s.append(datetime.zoneOffset.toDisplayString(isDisplayZ = false))
is KInstant -> s.append("+00:00")
else -> throw UnsupportedOperationException("${datetime::class.simpleName} has no timezone support")
}
}
}
return s.toString()
}
protected fun validateForFullValidParser() {
val tokenTypesList = tokens.map { it.type }
.filter { it != FormatTokenType.Literial }
val tokenTypesSet = tokenTypesList.toSet()
if (tokenTypesSet.size != tokenTypesList.size) {
throw IllegalArgumentException("A parser cannot have repeated fields")
}
if (!tokenTypesSet.containsAll(PARSER_COMPULSORY_INPUT_TYPES)) {
throw IllegalArgumentException("Missing compulsory fields in the pattern")
}
if (tokenTypesSet.contains(FormatTokenType.Hour_0_23)) {
if (tokenTypesSet.contains(FormatTokenType.Hour_1_12) || tokenTypesSet.contains(FormatTokenType.AMPM) || tokenTypesSet.contains(FormatTokenType.ampm)) {
throw IllegalArgumentException("Cannot contain contradicting fields in the pattern")
}
} else if (tokenTypesSet.contains(FormatTokenType.Hour_1_12)) {
if (!tokenTypesSet.contains(FormatTokenType.AMPM) && !tokenTypesSet.contains(FormatTokenType.ampm)) {
throw IllegalArgumentException("Missing compulsory fields in the pattern")
}
} else {
throw IllegalArgumentException("Missing compulsory fields in the pattern")
}
}
protected fun parseAmPm(input: String): Int {
return when (input.lowercase()) {
"am" -> AM
"pm" -> PM
else -> throw ParseDateTimeException()
}
}
fun parseToKZonedDateTime(input: String): KZonedDateTime {
validateForFullValidParser()
var year: Int? = null
var month: Int? = null
var dayOfMonth: Int? = null
var hour: Int? = null
var minute: Int? = null
var second: Int? = null
var millisecond: Int? = null
var amPm: Int? = null // am = 0, pm = 1
var zoneOffset: KZoneOffset? = null
var startIndex = 0
tokens.forEach { token ->
val inputSubstring = input.substring(startIndex, startIndex + token.length)
var length = token.length
if (token.type == FormatTokenType.Literial) {
if (inputSubstring != token.literal!!) {
throw ParseDateTimeException()
}
startIndex += length
return@forEach // skip because no field to input
}
try {
when (token.type) {
FormatTokenType.Year -> {
year = inputSubstring.toInt()
if (token.length == 2) {
year = year!! + if (year!! >= 70) 1900 else 2000
}
}
FormatTokenType.Month -> month = inputSubstring.toInt()
FormatTokenType.DayOfMonth -> dayOfMonth = inputSubstring.toInt()
FormatTokenType.Hour_0_23 -> hour = inputSubstring.toInt()
FormatTokenType.Hour_1_12 -> hour = inputSubstring.toInt()
FormatTokenType.Minute -> minute = inputSubstring.toInt()
FormatTokenType.Second -> second = inputSubstring.toInt()
FormatTokenType.Millisecond -> millisecond = inputSubstring.toInt()
FormatTokenType.ampm -> amPm = parseAmPm(inputSubstring)
FormatTokenType.AMPM -> amPm = parseAmPm(inputSubstring)
FormatTokenType.TimeZoneOffsetOrZ -> {
val longerSubstring = input.substring(startIndex)
length = if (longerSubstring.startsWith("Z")) {
1
} else if (longerSubstring.startsWith("UTC")) {
3
} else {
"+00:00".length
}
zoneOffset = try {
KZoneOffset.parseFrom(longerSubstring.substring(0, length))
} catch (e: IllegalArgumentException) {
throw ParseDateTimeException(e.message)
}
}
else -> {}
}
} catch (e: NumberFormatException) {
throw ParseDateTimeException(e.message)
}
startIndex += length
}
if (!(1..12).contains(month)) {
throw ParseDateTimeException()
}
if (amPm != null) {
if (!(1..12).contains(hour)) {
throw ParseDateTimeException()
}
if (amPm == AM) {
if (hour == 12) hour = 0
} else if (amPm == PM) {
hour = (hour!! + 12) % 24
}
}
return try {
KZonedDateTime(
year = year!!,
month = month!!,
day = dayOfMonth!!,
hour = hour ?: 0,
minute = minute ?: 0,
second = second ?: 0,
millisecond = millisecond ?: 0,
zoneOffset = zoneOffset!!
)
} catch (e: IllegalArgumentException) {
throw ParseDateTimeException(e.message)
}
}
@Deprecated("Use parseToKZonedDateTime(String).toKZonedInstant() instead")
fun parseToKZonedInstant(input: String): KZonedInstant {
return parseToKZonedDateTime(input).toKZonedInstant()
}
@Deprecated("Use parseToKZonedDateTime(String).toKZonedInstant().dropZoneOffset() instead")
fun parseToKInstant(input: String): KInstant {
val instantWithZone = parseToKZonedInstant(input = input)
return instantWithZone.dropZoneOffset()
}
companion object {
val ISO8601_DATETIME = KDateTimeFormat("yyyy-MM-dd'T'HH:mm:ssZ")
val FULL = KDateTimeFormat("yyyy-MM-dd'T'HH:mm:ss.lllZ")
// order of the list matters
val ISO8601_FORMATS = listOf(FULL, ISO8601_DATETIME)
val IOS_DATE_FORMATS = listOf(FULL, ISO8601_DATETIME, KDateTimeFormat("yyyy-MM-dd'T'HH:mmZ"))
val WEEKDAY_NAMES = listOf("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
internal val PARSER_COMPULSORY_INPUT_TYPES = setOf(
FormatTokenType.Year,
FormatTokenType.Month,
FormatTokenType.DayOfMonth,
FormatTokenType.Minute,
// FormatTokenType.Second,
FormatTokenType.TimeZoneOffsetOrZ
)
private val AM = 0
private val PM = 1
}
}
| 0
| null |
1
| 7
|
f8d85325febfabbe6c3917f0e192aae3cd6b14c2
| 14,116
|
kdatetime-multiplatform
|
MIT License
|
data/src/test/kotlin/com/fuzzyfunctors/reductions/data/deal/DealInfoResponseGeneration.kt
|
torresmi
| 123,222,268
| false
|
{"Kotlin": 99677, "Shell": 392}
|
package com.fuzzyfunctors.reductions.data.deal
import com.appmattus.kotlinfixture.kotlinFixture
import com.fuzzyfunctors.reductions.test.util.arb
import com.fuzzyfunctors.reductions.test.util.fake
import io.kotest.property.Arb
object DealInfoResponseGeneration {
val baseFixture = kotlinFixture {
property(DealInfoResponse.GameInfo::salePrice) {
fake { money.amount(1..60) }
}
property(DealInfoResponse.GameInfo::retailPrice) {
fake { money.amount(1..60) }
}
}
private fun saleFixture(
salePrice: String,
retailPrice: String
) = baseFixture.new {
property(DealInfoResponse.GameInfo::salePrice) { salePrice }
property(DealInfoResponse.GameInfo::retailPrice) { retailPrice }
}
val onSale = saleFixture(salePrice = "20.00", retailPrice = "60.00")
.invoke<DealInfoResponse>()
val notOnSale = saleFixture(salePrice = "60.00", retailPrice = "60.00")
.invoke<DealInfoResponse>()
private fun steamFixture(
appId: String?,
ratingPercent: String?,
ratingCount: String?,
ratingText: String?,
onSteam: Boolean
) = baseFixture.new {
property(DealInfoResponse.GameInfo::steamAppID) { appId }
property(DealInfoResponse.GameInfo::steamRatingPercent) { ratingPercent }
property(DealInfoResponse.GameInfo::steamRatingCount) { ratingCount }
property(DealInfoResponse.GameInfo::steamRatingText) { ratingText }
property(DealInfoResponse.GameInfo::steamworks) { if (onSteam) "1" else "0" }
}
val onSteam = steamFixture(
appId = "1",
ratingPercent = "100",
ratingCount = "1",
ratingText = "good",
onSteam = true
).invoke<DealInfoResponse>()
val notOnSteam = steamFixture(
appId = null,
ratingPercent = null,
ratingCount = null,
ratingText = null,
onSteam = false
).invoke<DealInfoResponse>()
private fun metacriticFixture(
score: String?,
link: String?
) = baseFixture.new {
property(DealInfoResponse.GameInfo::metacriticScore) { score }
property(DealInfoResponse.GameInfo::metacriticLink) { link }
}
val onMetacritic = metacriticFixture(score = "100", link = "www.metacritic.com")
.invoke<DealInfoResponse>()
val notOnMetacritic = metacriticFixture(score = null, link = null)
.invoke<DealInfoResponse>()
val edgeCases = listOf(
onSale,
notOnSale,
onSteam,
notOnSteam,
onMetacritic,
notOnMetacritic
)
fun arb(): Arb<DealInfoResponse> = arb(*edgeCases.toTypedArray())
}
| 16
|
Kotlin
|
0
| 3
|
8dbba04c463a5ccf02a0c1d4c73e9195abbf2891
| 2,706
|
reductions-android
|
Apache License 2.0
|
js/js.translator/testData/box/coroutines/suspendFunctionalInterface.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// IGNORE_BACKEND: JS
inline fun <reified T> handle(s: T): String {
return "${T::class}"
}
fun check(got: String, expected: String): String? {
if (got != expected) {
return "Failed; expected $expected, got $got"
}
return null
}
fun box(): String {
val s0: suspend () -> Unit = {}
check(handle(s0), "class SuspendFunction0")?.let { return it }
val s1: suspend (String) -> Unit = {}
check(handle(s1), "class SuspendFunction1")?.let { return it }
val s7: suspend (Any, Any, Any, Any, Any, Any, Any) -> Unit = { _, _, _, _, _, _, _ -> }
check(handle(s7), "class SuspendFunction7")?.let { return it }
val s15: suspend (Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) -> Unit
= { _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ -> }
check(handle(s15), "class SuspendFunction15")?.let { return it }
return "OK"
}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 909
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/eth/rochsolid/slack/blocks/models/blocks/Image.kt
|
vince-grondin
| 776,334,728
| false
|
{"Kotlin": 155300}
|
package eth.rochsolid.slack.blocks.models.blocks
import eth.rochsolid.slack.blocks.models.compositionobjects.Text
import kotlinx.serialization.SerialName
/**
* Displays an image.
*
* Examples:
* - An image block using `image_url` ([view this in Block Kit Builder](https://api.slack.com/tools/block-kit-builder?blocks=%5B%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%22type%22%3A%20%22image%22%2C%0A%20%20%20%20%20%20%22title%22%3A%20%7B%0A%20%20%20%20%20%20%20%20%22type%22%3A%20%22plain_text%22%2C%0A%20%20%20%20%20%20%20%20%22text%22%3A%20%22Please%20enjoy%20this%20photo%20of%20a%20kitten%22%0A%20%20%20%20%20%20%7D%2C%0A%20%20%20%20%20%20%22block_id%22%3A%20%22image4%22%2C%0A%20%20%20%20%20%20%22image_url%22%3A%20%22http%3A%2F%2Fplacekitten.com%2F500%2F500%22%2C%0A%20%20%20%20%20%20%22alt_text%22%3A%20%22An%20incredibly%20cute%20kitten.%22%0A%20%20%20%20%7D%0A%5D))
* ```json
* {
* "type": "image",
* "title": {
* "type": "plain_text",
* "text": "Please enjoy this photo of a kitten"
* },
* "block_id": "image4",
* "image_url": "http://placekitten.com/500/500",
* "alt_text": "An incredibly cute kitten."
* }
* ```
* - An image block using `slack_file` with a `url`
* ```json
* {
* "type": "image",
* "title": {
* "type": "plain_text",
* "text": "This image block contains a reference to a Slack image file."
* },
* "block_id": "image4",
* "slack_file": {
* "url": "https://files.slack.com/files-pri/T0123456-F0123456/xyz.png"
* },
* "alt_text": "Slack file object."
* }
* ```
* - An image block using `slack_file` with a `id`:
* ```json
* {
* "type": "image",
* "title": {
* "type": "plain_text",
* "text": "This image block contains a reference to a Slack image file."
* },
* "block_id": "image4",
* "slack_file": {
* "id": "F0123456",
* },
* "alt_text": "Slack file object."
* }
* ```
*/
sealed class Image : Block(type = Type.IMAGE) {
abstract val altText: String
abstract val title: Text.PlainText?
data class Url(
/**
* A unique identifier for a block. If not specified, a block_id will be generated by the Slack API.
* You can use this [blockID] when you receive an interaction payload to identify the source of the action.
* Maximum length for this field is 255 characters. [blockID] should be unique for each message and each iteration
* of a message. If a message is updated, use a new [blockID].
*/
@SerialName("block_id")
override val blockID: BlockID?,
/**
* A plain-text summary of the image. This should not contain any markup.
* Maximum length for this field is 2000 characters.
*/
@SerialName("alt_text")
override val altText: String,
/**
* The URL for a publicly hosted image.
* You must provide either an image_url or slack_file. Maximum length for this field is 3000 characters.
*/
@SerialName("image_url")
val imageUrl: String?,
/**
* An optional title for the image in the form.
* Maximum length for the text in this field is 2000 characters.
*/
override val title: Text.PlainText?
) : Image()
/**
* A [Slack image file object](https://api.slack.com/reference/block-kit/composition-objects#slack_file) that
* defines the source of the image.
*/
data class SlackFile(
/**
* A unique identifier for a block. If not specified, a block_id will be generated by the Slack API.
* You can use this [blockID] when you receive an interaction payload to identify the source of the action.
* Maximum length for this field is 255 characters. [blockID] should be unique for each message and each iteration
* of a message. If a message is updated, use a new [blockID].
*/
@SerialName("block_id")
override val blockID: BlockID?,
/**
* A plain-text summary of the image. This should not contain any markup.
* Maximum length for this field is 2000 characters.
*/
@SerialName("alt_text")
override val altText: String,
/**
* An optional title for the image in the form.
* Maximum length for the text in this field is 2000 characters.
*/
override val title: Text.PlainText?
) : Image()
}
| 5
|
Kotlin
|
0
| 0
|
5dd4160761767a03d1b210f58e0cb9246abbf9aa
| 4,435
|
kotlin-slack-blocks-builder
|
MIT License
|
sync/sync-internal/src/main/java/com/duckduckgo/sync/internal/InternalSyncFeature.kt
|
duckduckgo
| 78,869,127
| false
| null |
/*
* Copyright (c) 2023 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.sync.internal
import android.content.Context
import android.content.Intent
import com.duckduckgo.di.scopes.AppScope
import com.duckduckgo.internal.features.api.InternalFeaturePlugin
import com.duckduckgo.sync.impl.ui.SyncInitialSetupActivity
import com.squareup.anvil.annotations.ContributesMultibinding
import javax.inject.Inject
@ContributesMultibinding(AppScope::class)
class InternalSyncFeature @Inject constructor(private val context: Context) : InternalFeaturePlugin {
override fun internalFeatureTitle(): String {
return context.getString(R.string.syncSettingsTitle)
}
override fun internalFeatureSubtitle(): String {
return context.getString(R.string.syncSettingsSubtitle)
}
override fun onInternalFeatureClicked(activityContext: Context) {
activityContext.startActivity(Intent(activityContext, SyncInitialSetupActivity::class.java))
}
}
| 67
| null |
901
| 3,823
|
6415f0f087a11a51c0a0f15faad5cce9c790417c
| 1,520
|
Android
|
Apache License 2.0
|
repeated-dislikes/src/main/kotlin/org/jesperancinha/repeateddislikes/bad/services/Service.kt
|
jesperancinha
| 369,597,921
| false
|
{"Kotlin": 164376, "Java": 100076, "Makefile": 2102, "Dockerfile": 266, "Shell": 192}
|
package org.jesperancinha.repeateddislikes.bad.services
import org.jesperancinha.repeateddislikes.bad.dao.*
import org.jesperancinha.repeateddislikes.bad.dtos.toDto
import org.springframework.stereotype.Service
@Service
class BadDislikeService(
val userRepository: BadUserRepository,
val receiptRepository: BadReceiptRepository,
val shopRepository: BadShopRepository
) {
fun getAllUsers() = userRepository.findAll().map { it.toDto() }
fun getAllReceipts() = receiptRepository.findAll()
fun getAllShops() = shopRepository.findAll()
}
| 1
|
Kotlin
|
0
| 3
|
68f27c8647c5313a5870326c36344113bc2577ac
| 560
|
jeorg-spring-master-test-drives
|
Apache License 2.0
|
performance/performance/src/main/java/com/emergetools/test/utils/perfetto/PerfettoUtils.kt
|
EmergeTools
| 645,957,551
| false
|
{"Kotlin": 255570}
|
package com.emergetools.test.utils.perfetto
import androidx.benchmark.perfetto.ExperimentalPerfettoTraceProcessorApi
import androidx.benchmark.perfetto.PerfettoTraceProcessor
import androidx.benchmark.perfetto.Row
/**
* While these are available in PerfettoTraceProcessor, they're marked as internal to the library
* group, preventing us from leveraging them.
* These are simply a copy of those at 1.2.0-beta05, slightly modified to avoid naming confusion and
* for a few custom helpers. Original source:
* https://github.com/androidx/androidx/blob/f6df7df4bb215d31187a32dea874edd43eb9506f/benchmark/benchmark-macro/src/main/java/androidx/benchmark/perfetto/PerfettoTraceProcessor.kt#L241
*/
@OptIn(ExperimentalPerfettoTraceProcessorApi::class)
fun PerfettoTraceProcessor.Session.querySpans(
spanNames: List<String>,
packageName: String?,
): List<Slice> {
val spansWhereClause = spanNames
.joinToString(
separator = " OR ",
prefix = if (packageName == null) {
"("
} else {
"(process.name LIKE \"$packageName\" OR process.name LIKE \"$packageName:%\") AND ("
},
postfix = ")"
) {
"slice.name LIKE \"$it\""
}
val syncSpanInnerJoins = if (packageName != null) {
"""
INNER JOIN thread_track on slice.track_id = thread_track.id
INNER JOIN thread USING(utid)
INNER JOIN process USING(upid)
""".trimMargin()
} else {
""
}
// Async spans are written to a different "track" (process_track)
// than standard Trace spans (thread_track).
val asyncSpanInnerJoins = if (packageName != null) {
"""
INNER JOIN process_track on slice.track_id = process_track.id
INNER JOIN process USING(upid)
""".trimMargin()
} else {
""
}
return query(
query = """
SELECT slice.name,ts,dur
FROM slice
$syncSpanInnerJoins
WHERE $spansWhereClause
UNION
SELECT slice.name,ts,dur
FROM slice
$asyncSpanInnerJoins
WHERE $spansWhereClause
""".trimMargin()
).toSlices()
}
data class Slice(
val name: String,
val ts: Long,
val dur: Long,
) {
val durMs: Long = dur / NANOS_IN_MS
companion object {
const val NANOS_IN_MS = 1_000_000
}
}
@OptIn(ExperimentalPerfettoTraceProcessorApi::class)
internal fun Sequence<Row>.toSlices(): List<Slice> = map {
Slice(name = it.string("name"), ts = it.long("ts"), dur = it.long("dur"))
}.toList()
| 3
|
Kotlin
|
1
| 9
|
8174b9c6e2d7791e01363aabd4d287736bfa38c4
| 2,431
|
emerge-android
|
Apache License 2.0
|
app/src/main/java/com/speakoutall/users/UsersListAdapter.kt
|
kpchandora
| 240,494,122
| false
| null |
package com.speakoutall.users
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.speakoutall.R
import com.speakoutall.auth.UsersItem
import com.speakoutall.extensions.gone
import com.speakoutall.extensions.loadImage
import com.speakoutall.extensions.visible
import com.speakoutall.utils.AppPreference
import kotlinx.android.synthetic.main.item_users_list.view.*
class UsersListAdapter(private val usersList: ArrayList<UsersItem>) :
RecyclerView.Adapter<UsersListAdapter.UsersListViewHolder>() {
var mListener: OnUserClickListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UsersListViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.item_users_list, parent, false)
return UsersListViewHolder(view).also {
it.mListener = mListener
}
}
override fun getItemCount() = usersList.size
override fun onBindViewHolder(holder: UsersListViewHolder, position: Int) {
holder.bind(usersList[position])
}
override fun onBindViewHolder(
holder: UsersListViewHolder,
position: Int,
payloads: MutableList<Any>
) {
if (payloads.isNotEmpty()) {
(payloads[0] as UsersItem).let {
holder.bind(it)
return
}
}
super.onBindViewHolder(holder, position, payloads)
}
fun showFollowing(userId: String) {
usersList.forEachIndexed { index, userMiniDetails ->
if (userMiniDetails.userId == userId) {
userMiniDetails.isFollowedBySelf = true
notifyItemChanged(index, userMiniDetails)
}
}
}
fun showFollow(userId: String) {
usersList.forEachIndexed { index, userMiniDetails ->
if (userMiniDetails.userId == userId) {
userMiniDetails.isFollowedBySelf = false
notifyItemChanged(index, userMiniDetails)
}
}
}
class UsersListViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
var mListener: OnUserClickListener? = null
init {
view.cv_follow.setOnClickListener {
val user = view.tag as UsersItem
if (user.isFollowedBySelf!!) {
mListener?.onUnFollowClick(user)
} else {
user.isFollowedBySelf = true
showFollowing()
mListener?.onFollowClick(user)
}
}
view.fl_profile.setOnClickListener {
val user = view.tag as UsersItem
mListener?.onUserClick(user, view.item_users_list_profile_iv)
}
view.ll_details.setOnClickListener {
val user = view.tag as UsersItem
mListener?.onUserClick(user, view.item_users_list_profile_iv)
}
}
fun bind(user: UsersItem) {
view.apply {
tag = user
item_users_list_profile_iv.transitionName = user.userId
item_users_list_profile_iv.loadImage(
user.photoUrl,
placeholder = R.drawable.ic_account_circle_grey,
makeRound = true
)
item_users_list_username_tv.text = user.username
item_users_list_name_tv.text = user.name
if (user.isFollowedBySelf == null || user.userId == AppPreference.getUserId()) {
cv_follow.gone()
} else {
cv_follow.visible()
if (user.isFollowedBySelf!!) {
showFollowing()
} else {
showFollow()
}
}
}
}
private fun showFollow() {
view.tv_follow.text = view.context.getString(R.string.follow)
view.tv_follow.background =
ContextCompat.getDrawable(view.context, R.drawable.dr_follow_bg)
view.tv_follow.setTextColor(ContextCompat.getColor(view.context, R.color.colorFollowBgText))
}
private fun showFollowing() {
view.tv_follow.text = view.context.getString(R.string.following)
view.tv_follow.background =
ContextCompat.getDrawable(view.context, R.drawable.dr_unfollow_bg)
view.tv_follow.setTextColor(ContextCompat.getColor(view.context, R.color.colorFollowingBgText))
}
}
}
| 3
|
Kotlin
|
1
| 2
|
ec63b19e86d4204721316299fbd70facae9a328a
| 4,698
|
speak-out
|
MIT License
|
feature-matchingcards/src/main/java/com/rumosoft/feature_memorygame/infrastructure/di/RepositoryModule.kt
|
Rviewer-Challenges
| 492,594,104
| false
|
{"Kotlin": 72614}
|
package com.rumosoft.feature_memorygame.infrastructure.di
import com.rumosoft.feature_memorygame.data.repository.MatchingCardsRepositoryImpl
import com.rumosoft.feature_memorygame.data.repository.TimerRepositoryImpl
import com.rumosoft.feature_memorygame.domain.repo_interfaces.MatchingCardsRepository
import com.rumosoft.feature_memorygame.domain.repo_interfaces.TimerRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds
@Singleton
abstract fun bindMatchingCardsRepository(
cardsRepository: MatchingCardsRepositoryImpl
): MatchingCardsRepository
@Binds
@Singleton
abstract fun bindTimerRepository(
timerRepository: TimerRepositoryImpl
): TimerRepository
}
| 0
|
Kotlin
|
0
| 0
|
9590cbb8cd589ba11ab703e20f0de1448e1186da
| 902
|
kslH9nF4ZJcayHVA49Vf
|
MIT License
|
app-tracking-protection/vpn-impl/src/test/java/com/duckduckgo/mobile/android/app/tracking/AppTrackerDetectorTest.kt
|
duckduckgo
| 78,869,127
| false
| null |
/*
* Copyright (c) 2022 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.mobile.android.app.tracking
import com.duckduckgo.mobile.android.vpn.dao.VpnAppTrackerBlockingDao
import com.duckduckgo.mobile.android.vpn.processor.requestingapp.AppNameResolver
import com.duckduckgo.mobile.android.vpn.processor.tcp.tracker.AppTrackerRecorder
import com.duckduckgo.mobile.android.vpn.trackers.*
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
class AppTrackerDetectorTest {
private val appTrackerRepository: AppTrackerRepository = mock()
private val appNameResolver: AppNameResolver = mock()
private val appTrackerRecorder: AppTrackerRecorder = mock()
private val vpnAppTrackerBlockingDao: VpnAppTrackerBlockingDao = mock()
private lateinit var appTrackerDetector: AppTrackerDetector
@Before
fun setup() {
whenever(appNameResolver.getAppNameForPackageId(APP_ORIGINATING_APP.packageId)).thenReturn(APP_ORIGINATING_APP)
whenever(appNameResolver.getAppNameForPackageId(AppNameResolver.OriginatingApp.unknown().packageId))
.thenReturn(AppNameResolver.OriginatingApp.unknown())
appTrackerDetector = RealAppTrackerDetector(
appTrackerRepository,
appNameResolver,
appTrackerRecorder,
vpnAppTrackerBlockingDao,
)
}
@Test
fun whenEvaluateThirdPartyTrackerThenReturnTracker() {
whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID))
.thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER))
whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId)
whenever(vpnAppTrackerBlockingDao.getRuleByTrackerDomain(TEST_APP_TRACKER.hostname)).thenReturn(null)
assertEquals(
AppTrackerDetector.AppTracker(
TEST_APP_TRACKER.hostname,
APP_UID,
TEST_APP_TRACKER.owner.displayName,
APP_ORIGINATING_APP.packageId,
APP_ORIGINATING_APP.appName,
),
appTrackerDetector.evaluate(TEST_APP_TRACKER.hostname, APP_UID),
)
}
@Test
fun whenEvaluateThirdPartyTrackerFromUnknownAppThenReturnNull() {
val packageId = AppNameResolver.OriginatingApp.unknown().packageId
whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, packageId))
.thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER))
whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(packageId)
whenever(vpnAppTrackerBlockingDao.getRuleByTrackerDomain(TEST_APP_TRACKER.hostname)).thenReturn(null)
assertNull(appTrackerDetector.evaluate(TEST_APP_TRACKER.hostname, APP_UID))
}
@Test
fun whenEvaluateThirdPartyTrackerFromDdgAppThenReturnNull() {
// This test case is just in case we pass the DDG traffic through the VPN. Our app doesn't embed trackers but web trackers might be detected
// as app trackers.
val packageId = "com.duckduckgo.mobile"
whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, packageId))
.thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER))
whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(packageId)
whenever(vpnAppTrackerBlockingDao.getRuleByTrackerDomain(TEST_APP_TRACKER.hostname)).thenReturn(null)
assertNull(appTrackerDetector.evaluate(TEST_APP_TRACKER.hostname, APP_UID))
}
@Test
fun whenEvaluateThirdPartyTrackerInExclusionListThenReturnTrackerNull() {
val packageId = APP_PACKAGE_ID
whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, packageId))
.thenReturn(AppTrackerType.ThirdParty(TEST_APP_TRACKER))
whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId)
whenever(vpnAppTrackerBlockingDao.getRuleByTrackerDomain(TEST_APP_TRACKER.hostname)).thenReturn(
AppTrackerExceptionRule(TEST_APP_TRACKER.hostname, listOf(packageId)),
)
assertNull(appTrackerDetector.evaluate(TEST_APP_TRACKER.hostname, APP_UID))
}
@Test
fun whenEvaluateFirstPartyTrackerThenReturnNull() {
whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID))
.thenReturn(AppTrackerType.FirstParty(TEST_APP_TRACKER))
whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId)
whenever(vpnAppTrackerBlockingDao.getRuleByTrackerDomain(TEST_APP_TRACKER.hostname)).thenReturn(null)
assertNull(appTrackerDetector.evaluate(TEST_APP_TRACKER.hostname, APP_UID))
}
fun whenEvaluateNonTrackerThenReturnNull() {
whenever(appTrackerRepository.findTracker(TEST_APP_TRACKER.hostname, APP_PACKAGE_ID)).thenReturn(AppTrackerType.NotTracker)
whenever(appNameResolver.getPackageIdForUid(APP_UID)).thenReturn(APP_ORIGINATING_APP.packageId)
whenever(vpnAppTrackerBlockingDao.getRuleByTrackerDomain(TEST_APP_TRACKER.hostname)).thenReturn(null)
assertNull(appTrackerDetector.evaluate(TEST_APP_TRACKER.hostname, APP_UID))
}
companion object {
private const val APP_UID = 55
private const val APP_PACKAGE_ID = "com.app.name"
private val APP_ORIGINATING_APP = AppNameResolver.OriginatingApp(APP_PACKAGE_ID, "testApp")
private val TEST_APP_TRACKER = AppTracker(
hostname = "api2.branch.com",
trackerCompanyId = 0,
owner = TrackerOwner(
name = "Branch",
displayName = "Branch",
),
app = TrackerApp(0, 0.0),
isCdn = false,
)
}
}
| 57
| null |
894
| 3,397
|
51b26f6e0e694cabc213b1857f244caae995362f
| 6,452
|
Android
|
Apache License 2.0
|
app/src/main/java/com/gifft/di/PerAppScope.kt
|
SIDOVSKY
| 265,333,377
| false
| null |
package com.gifft.di
import javax.inject.Scope
@Scope
@Retention(value = AnnotationRetention.RUNTIME)
annotation class PerApp
| 0
|
Kotlin
|
0
| 1
|
890f89317d59dff6dac6435fe1aaf26637ad2f29
| 128
|
Gifft
|
Apache License 2.0
|
android/app/src/main/kotlin/ca/etsmtl/applets/etsmobile/presentation/github/GitHubContributorsFragment.kt
|
ApplETS
| 159,037,998
| false
| null |
package ca.etsmtl.applets.etsmobile.presentation.github
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import ca.etsmtl.applets.etsmobile.R
import ca.etsmtl.applets.etsmobile.extension.applyAppTheme
import ca.etsmtl.applets.etsmobile.extension.toLiveData
import ca.etsmtl.applets.etsmobile.extension.toast
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_github_contributors.rvGitHubContributors
import kotlinx.android.synthetic.main.fragment_github_contributors.swipeRefreshLayoutGitHubContributors
import presentation.GitHubContributorsViewModel
import javax.inject.Inject
/**
* Created by Sonphil on 02-10-19.
*/
class GitHubContributorsFragment : DaggerFragment() {
private val viewModel by lazy {
ViewModelProviders.of(this, viewModelFactory).get(GitHubContributorsViewModel::class.java)
}
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private val adapter = GitHubContributorsRecyclerViewAdapter()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_github_contributors, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
setupSwipeRefreshLayout()
subscribeUI()
viewModel.fetchContributors()
}
private fun setupSwipeRefreshLayout() {
swipeRefreshLayoutGitHubContributors.applyAppTheme(requireContext())
swipeRefreshLayoutGitHubContributors.setOnRefreshListener {
viewModel.refreshContributors()
}
}
private fun setupRecyclerView() {
rvGitHubContributors.adapter = adapter
}
private fun subscribeUI() {
viewModel.contributors
.openSubscription()
.toLiveData()
.observe(this, Observer { contributors ->
if (contributors != null) {
adapter.items = contributors
}
})
viewModel.showLoading
.openSubscription()
.toLiveData()
.observe(this, Observer { showLoading ->
swipeRefreshLayoutGitHubContributors.isRefreshing = showLoading
})
viewModel.errorMessage
.openSubscription()
.toLiveData()
.observe(this, Observer { message ->
context?.toast(message)
})
}
}
| 66
|
Kotlin
|
4
| 13
|
c4c5c86a54fe16e19a5f7eeea3a0dfb7076207ad
| 2,752
|
Notre-Dame-v3
|
Apache License 2.0
|
test/src/me/anno/tests/game/simslike/SimsBuildControls.kt
|
AntonioNoack
| 456,513,348
| false
|
{"Kotlin": 10912545, "C": 236426, "Java": 6754, "Lua": 4496, "C++": 3070, "GLSL": 2698}
|
package me.anno.tests.game.simslike
import me.anno.engine.ui.render.RenderView
import me.anno.language.translation.NameDesc
import me.anno.ui.base.buttons.TextButton
import me.anno.ui.base.components.AxisAlignment
class SimsBuildControls(controls: SimsControls, rv: RenderView) : SimsControlBase(controls, rv) {
init {
add(TextButton(NameDesc("Play"), style)
.addLeftClickListener {
// switch to play mode
sceneView.editControls = controls.playControls
controls.playControls.rotationTarget.set(rotationTarget)
}
.apply {
alignmentX = AxisAlignment.MAX
alignmentY = AxisAlignment.MAX
})
// todo inventory-like build selection menu
}
// different modes:
// todo implement these modes:
// - place tiles
// - place walls
// - edit terrain
// - place furniture
// - place items
enum class BuildMode {
TILES_PLACING,
WALLS_PLACING,
TERRAIN_EDIT,
DECORATING,
DELETING
}
}
| 0
|
Kotlin
|
3
| 24
|
013af4d92e0f89a83958008fbe1d1fdd9a10e992
| 1,101
|
RemsEngine
|
Apache License 2.0
|
src/main/kotlin/me/nashiroaoi/democracy/command/MessageCommandFactory.kt
|
hisuie08
| 376,214,881
| false
| null |
package me.nashiroaoi.democracy.command
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent
class MessageCommandFactory(event : GuildMessageReceivedEvent){
init {
if(event.message.mentionedUsers.contains(event.jda.selfUser)){
val message = event.message.contentDisplay
.replace(Regex("@${event.jda.selfUser.name}(\\s*)"),"")
when{
message.startsWith("register")-> register(event,message)
}
}
}
private fun register(event : GuildMessageReceivedEvent,message:String){
}
}
| 0
|
Kotlin
|
0
| 0
|
49dcf1a6ca4d59c63873094a4e5d182ad55e114a
| 633
|
indirect-democracy-bot
|
MIT License
|
app/src/main/java/com/muzamil/rickamortywithpaging3/domain/entity/Location.kt
|
Muzamilabdallah
| 588,921,381
| false
| null |
package com.muzamil.rickamortywithpaging3.domain.entity
data class Location(
val name: String?,
val dimension:String?
)
| 0
|
Kotlin
|
0
| 3
|
7f3fc51a15021f457cc2db5d0aea881cc636e0b5
| 128
|
rickAMortyWithPaging3
|
MIT License
|
common/src/main/java/ru/aasmc/petfinder/common/utils/CoroutineDispatchersProvider.kt
|
aasmc
| 407,974,629
| false
|
{"Kotlin": 171701}
|
package ru.aasmc.petfinder.common.utils
import javax.inject.Inject
class CoroutineDispatchersProvider @Inject constructor() : DispatchersProvider
| 0
|
Kotlin
|
0
| 0
|
00f5122bfb476f3b6037fd4f2a6f696f0d2461d3
| 147
|
PetFinder
|
The Unlicense
|
app/src/main/java/com/halilkrkn/chatchef/navigation/graphs/SetupBottomBarNavGraph.kt
|
halilkrkn
| 801,687,576
| false
|
{"Kotlin": 114335}
|
package com.halilkrkn.chatchef.navigation.graphs
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.halilkrkn.chatchef.navigation.util.AuthScreen
import com.halilkrkn.chatchef.navigation.util.BottomBarNavigationScreen
import com.halilkrkn.chatchef.navigation.util.Graph
import com.halilkrkn.chatchef.presentation.ChatGptScreen.ChatGptScreen
import com.halilkrkn.chatchef.presentation.FavoriteScreen.FavoriteScreen
import com.halilkrkn.chatchef.presentation.loginScreen.ForgotPasswordScreen
import com.halilkrkn.chatchef.presentation.loginScreen.LoginScreen
import com.halilkrkn.chatchef.presentation.loginScreen.SignUpScreen
@Composable
fun SetupBottomBarNavGraph(
navController: NavHostController,
modifier: Modifier = Modifier,
) {
NavHost(
navController = navController,
startDestination = BottomBarNavigationScreen.ChatGptBottomBarNavigation.route,
route = Graph.BOTTOMBAR,
modifier = modifier
) {
composable(route = BottomBarNavigationScreen.ChatGptBottomBarNavigation.route) {
ChatGptScreen(navController = navController)
}
composable(route = BottomBarNavigationScreen.FavoriteBottomBarNavigation.route) {
FavoriteScreen()
}
composable(route = AuthScreen.Login.route){
LoginScreen(navController = navController)
}
composable(route = AuthScreen.Register.route){
SignUpScreen(navController = navController)
}
composable(route = AuthScreen.ForgotPasswordScreen.route){
ForgotPasswordScreen(navController = navController)
}
}
}
| 0
|
Kotlin
|
5
| 0
|
d995d1a5aa596f0a50bcf6c5e08c61461b941c09
| 1,805
|
Papara-Group-Project
|
Apache License 2.0
|
app/src/main/java/uk/co/sentinelweb/cuer/app/backup/BackupFileManager.kt
|
sentinelweb
| 220,796,368
| false
| null |
package uk.co.sentinelweb.cuer.app.backup
import android.content.Context
import android.os.Build
import kotlinx.coroutines.withContext
import kotlinx.datetime.toJavaLocalDateTime
import uk.co.sentinelweb.cuer.app.backup.version.ParserFactory
import uk.co.sentinelweb.cuer.app.db.init.DatabaseInitializer.Companion.DEFAULT_PLAYLIST_TEMPLATE
import uk.co.sentinelweb.cuer.app.db.repository.*
import uk.co.sentinelweb.cuer.app.db.repository.file.ImageFileRepository
import uk.co.sentinelweb.cuer.app.db.repository.file.ImageFileRepository.Companion.REPO_SCHEME
import uk.co.sentinelweb.cuer.app.orchestrator.OrchestratorContract
import uk.co.sentinelweb.cuer.core.ext.getFileName
import uk.co.sentinelweb.cuer.core.providers.CoroutineContextProvider
import uk.co.sentinelweb.cuer.core.providers.TimeProvider
import uk.co.sentinelweb.cuer.core.wrapper.LogWrapper
import uk.co.sentinelweb.cuer.domain.MediaDomain
import uk.co.sentinelweb.cuer.domain.PlaylistDomain
import uk.co.sentinelweb.cuer.domain.backup.BackupFileModel
import uk.co.sentinelweb.cuer.domain.creator.PlaylistItemCreator
import uk.co.sentinelweb.cuer.domain.ext.serialise
import uk.co.sentinelweb.cuer.net.mappers.TimeStampMapper
import java.io.File
import java.io.FileOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream
class BackupFileManager constructor(
private val channelRepository: ChannelDatabaseRepository,
private val mediaRepository: MediaDatabaseRepository,
private val playlistRepository: PlaylistDatabaseRepository,
private val playlistItemRepository: PlaylistItemDatabaseRepository,
private val contextProvider: CoroutineContextProvider,
private val parserFactory: ParserFactory,
private val playlistItemCreator: PlaylistItemCreator,
private val timeProvider: TimeProvider,
private val timeStampMapper: TimeStampMapper,
private val imageFileRepository: ImageFileRepository,
private val context: Context,
private val log: LogWrapper,
) {
init {
log.tag(this)
}
private fun makeFileName(): String {
val device = Build.MODEL.replace(" ", "_")
val timeStamp = timeStampMapper.mapDateTimeSimple(
timeProvider.localDateTime().toJavaLocalDateTime()
)
return "v$VERSION-$timeStamp-cuer_backup-$device.zip"
}
suspend fun makeBackupZipFile(): File = withContext(contextProvider.IO) {
val f = File(context.cacheDir, makeFileName())
try {
val out = ZipOutputStream(FileOutputStream(f))
val e = ZipEntry(DB_FILE_JSON)
out.putNextEntry(e)
val playlists = playlistRepository.loadList(OrchestratorContract.AllFilter()).data!!
val jsonDataBytes = backupDataJson(playlists).toByteArray()
out.write(jsonDataBytes, 0, jsonDataBytes.size)
out.closeEntry()
playlists
.map { listOf(it.image, it.thumb) }
.flatten()
.mapNotNull { it }
.filter { it.url.startsWith(REPO_SCHEME) }
.distinct()
.forEach {
imageFileRepository.loadImage(it)?.apply {
val imgEntry = ZipEntry(it.url.getFileName())
out.putNextEntry(imgEntry)
out.write(this, 0, this.size)
out.closeEntry()
}
}
out.close()
} catch (t: Throwable) {
log.e("Error backing up", t)
}
f
}
private suspend fun backupDataJson(playlists: List<PlaylistDomain>) =
withContext(contextProvider.IO) {
BackupFileModel(
version = 3,
medias = listOf(),
playlists = playlists
).serialise()
}
suspend fun restoreData(data: String): Boolean = withContext(contextProvider.IO) {
val backupFileModel = parserFactory.create(data).parse(data)
if (backupFileModel.version == 3) {
return@withContext mediaRepository.deleteAll()
.takeIf { it.isSuccessful }
?.let { channelRepository.deleteAll() }
?.takeIf { it.isSuccessful }
?.let { playlistRepository.deleteAll() }
?.takeIf { it.isSuccessful }
?.let {
backupFileModel.medias.chunked(CHUNK_SIZE)
.map { mediaRepository.save(it) }
.reduce { acc: RepoResult<List<MediaDomain>>, result: RepoResult<List<MediaDomain>> ->
RepoResult.Composite<List<MediaDomain>>(
acc.isSuccessful && result.isSuccessful,
result.data?.let { acc.data?.plus(it) }
)
}
}
?.takeIf { it.isSuccessful }
?.data
?.let { savedMedias ->
val idLookup = savedMedias.map { it.platformId to it }.toMap()
playlistRepository.save(
backupFileModel.playlists.map {
it.copy(
items = it.items.map {
it.copy(
media = idLookup.get(it.media.platformId)
?: throw IllegalArgumentException("media ID lookup failed: ${it.media.platformId}")
)
}
)
}
)
}
?.takeIf { it.isSuccessful }
?.isSuccessful
?: false
} else {
return@withContext mediaRepository.deleteAll()
.takeIf { it.isSuccessful }
?.let { channelRepository.deleteAll() }
?.takeIf { it.isSuccessful }
?.let { mediaRepository.save(backupFileModel.medias) }
?.takeIf { it.isSuccessful }
?.let { playlistRepository.deleteAll() }
?.takeIf { it.isSuccessful }
?.let {
playlistRepository.save(backupFileModel.playlists).let {
if (it.isSuccessful && it.data?.filter { it.default }?.size ?: 0 == 0) {
playlistRepository.save(DEFAULT_PLAYLIST_TEMPLATE)
} else it
}
}
?.takeIf { it.isSuccessful }
?.let {
playlistRepository
.loadList(OrchestratorContract.DefaultFilter())
.takeIf { it.isSuccessful && it.data?.size ?: 0 > 0 }
?.let { defPlaylistResult ->
val orderBase = timeProvider.currentTimeMillis()
backupFileModel.medias.mapIndexedNotNull { idx, item ->
defPlaylistResult.data?.get(0)?.let { defPlist ->
playlistItemCreator.buildPlayListItem(
item,
defPlist,
orderBase + (idx * 1000)
)
}
}.let {
playlistItemRepository.save(it)
}.isSuccessful
} ?: true
} ?: false
}
}
suspend fun restoreDataZip(f: File): Boolean = withContext(contextProvider.IO) {
imageFileRepository.removeAll(false)
ZipFile(f).use { zip ->
zip.entries().asSequence().forEach { entry ->
zip.getInputStream(entry).use { input ->
when (entry.name) {
DB_FILE_JSON -> {
restoreData(input.readBytes().decodeToString())
}
else -> { // assume image
File(imageFileRepository._dir.path, entry.name).outputStream()
.use { output ->
input.copyTo(output)
}
}
}
}
}
}
true
}
companion object {
const val VERSION = 3
const val CHUNK_SIZE = 400
const val DB_FILE_JSON = "database.json"
}
}
| 59
|
Kotlin
|
0
| 0
|
e9b3baf857c9e08eb21444291e8c4f8b8ca0838d
| 8,701
|
cuer
|
Apache License 2.0
|
src/main/kotlin/com/bbs/bookabus/config/SecurityConfig.kt
|
linoop
| 850,366,071
| false
|
{"Kotlin": 22601}
|
package com.bbs.bookabus.config
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
@Suppress("DEPRECATION")
@Configuration
@EnableWebSecurity
class SecurityConfig {
@Bean
fun passwordEncoder(): PasswordEncoder = BCryptPasswordEncoder()
@Bean
fun authenticationManager(authenticationConfiguration: AuthenticationConfiguration): AuthenticationManager {
return authenticationConfiguration.authenticationManager
}
@Bean
fun filterChain(http: HttpSecurity, jwtRequestFilter: JwtRequestFilter): SecurityFilterChain {
http.csrf().disable()
.authorizeHttpRequests {
it.requestMatchers("/api/authentication/**", "/api/bus/**").permitAll()
.anyRequest().authenticated()
}.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter::class.java)
return http.build()
}
}
| 0
|
Kotlin
|
0
| 0
|
f5343403f8139edf045cc381af5a979f6296d331
| 1,755
|
Bus-Booking-System
|
MIT License
|
core_library_common/src/commonMain/kotlin/net/apptronic/core/context/lifecycle/LifecycleStageDefinition.kt
|
apptronicnet
| 264,405,837
| false
| null |
package net.apptronic.core.context.lifecycle
fun lifecycleStage(name: String): LifecycleStageDefinition {
return LifecycleStageDefinition(name)
}
class LifecycleStageDefinition internal constructor(val name: String) {
override fun equals(other: Any?): Boolean {
return this === other
}
override fun hashCode(): Int {
return name.hashCode()
}
override fun toString(): String {
return "LifecycleStageDefinition[$name]/${hashCode()}"
}
}
| 2
|
Kotlin
|
0
| 6
|
5320427ddc9dd2393f01e75564dab126fdeaac72
| 492
|
core
|
MIT License
|
Manga/app/src/main/java/nhdphuong/com/manga/supports/ServiceGenerator.kt
|
Extraacc1
| 225,183,379
| false
|
{"Text": 1, "Ignore List": 1, "Markdown": 1, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Proguard": 1, "JSON": 1, "Kotlin": 116, "XML": 75, "Java": 2}
|
package nhdphuong.com.manga.supports
import android.text.TextUtils
import com.google.gson.GsonBuilder
import nhdphuong.com.manga.gson.GsonUTCDateAdapter
import nhdphuong.com.manga.gson.SerializationExclusionStrategy
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.Date
import java.util.concurrent.TimeUnit
/*
* Created by nhdphuong on 3/24/18.
*/
object ServiceGenerator {
private val mRetrofitBuilder = Retrofit.Builder().addConverterFactory(
GsonConverterFactory.create(
GsonBuilder()
.addSerializationExclusionStrategy(SerializationExclusionStrategy())
.registerTypeAdapter(Date::class.java, GsonUTCDateAdapter())
.create()
)
)
private var mRetrofit: Retrofit? = null
private val mLoggingInterceptor = HttpLoggingInterceptor().setLevel(
HttpLoggingInterceptor.Level.BODY
)
private val mHttpClientBuilder = OkHttpClient.Builder().addInterceptor(mLoggingInterceptor)
.connectTimeout(30000, TimeUnit.MILLISECONDS)
.readTimeout(30000, TimeUnit.MILLISECONDS)
.writeTimeout(30000, TimeUnit.MILLISECONDS)
private var mBaseUrl: String? = null
fun setBaseUrl(baseUrl: String) {
if (!TextUtils.equals(mBaseUrl, baseUrl)) {
mBaseUrl = baseUrl
mRetrofitBuilder.baseUrl(mBaseUrl!!)
mRetrofit = mRetrofitBuilder.build()
}
}
fun setInterceptor(interceptor: Interceptor?) {
mHttpClientBuilder.interceptors().clear()
mHttpClientBuilder.addInterceptor(mLoggingInterceptor)
if (interceptor != null && !mHttpClientBuilder.interceptors().contains(interceptor)) {
mHttpClientBuilder.addInterceptor(interceptor)
}
mRetrofitBuilder.client(mHttpClientBuilder.build())
mRetrofit = mRetrofitBuilder.build()
}
fun <S> createService(serviceClass: Class<S>): S {
return mRetrofit!!.create(serviceClass)
}
}
| 0
| null |
0
| 0
|
48e861bfd9cc9f812207f061ab1d8ecaea720d3a
| 2,185
|
H-Manga
|
MIT License
|
app/src/main/java/com/example/instadon/MainActivity.kt
|
srivathsanvenkateswaran
| 338,275,760
| false
| null |
package com.example.instadon
import android.content.ContentValues
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.instadon.daos.PostDao
import com.example.instadon.models.Post
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import kotlinx.coroutines.tasks.await
import java.lang.Exception
class MainActivity : AppCompatActivity(), IPostAdapter {
private lateinit var adapter: PostAdapter
private lateinit var postDao: PostDao
private lateinit var auth: FirebaseAuth
private var db = FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setSupportActionBar(toolbar)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
addNewPostFloatingActionButton.setOnClickListener{
val intent = Intent(this, AddNewPostActivity::class.java)
startActivity(intent)
}
setUpRecyclerView()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.app_bar_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.googleSignOutMenu -> confirmGoogleSignOut()
}
return super.onOptionsItemSelected(item)
}
private fun googleSignOut(){
Toast.makeText(this, "Signing out...", Toast.LENGTH_LONG).show()
auth = Firebase.auth
auth.signOut()
val intent = Intent(this, SignInActivity::class.java)
startActivity(intent)
}
private fun confirmGoogleSignOut() {
// Implement the Logic to sign out from Google here.
val confirmSignOutDialogBox = AlertDialog.Builder(this)
.setTitle("Confirm SignOut?")
.setMessage("Do you want to Sign Out from this Account?")
.setIcon(R.drawable.signout_alert_dialogue_icon)
.setPositiveButton("Sign Out"){ _, _ ->
googleSignOut()
}
.setNegativeButton("Cancel"){ _, _ ->
Toast.makeText(this, "Sign Out denied...", Toast.LENGTH_LONG).show()
}
.create()
.show()
}
private fun setUpRecyclerView() {
postDao = PostDao()
val postCollection = postDao.postCollection
val query = postCollection.orderBy("createdAt", Query.Direction.DESCENDING)
val recyclerViewOptions = FirestoreRecyclerOptions.Builder<Post>().setQuery(query, Post::class.java).build()
adapter = PostAdapter(recyclerViewOptions, this)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
}
override fun onStart() {
super.onStart()
adapter.startListening()
}
override fun onStop() {
super.onStop()
adapter.stopListening()
}
override fun onLiked(postID: String) {
postDao.updateLikes(postID)
}
override fun onDeleted(postId: String) {
GlobalScope.launch {
auth = Firebase.auth
val currentUserId = auth.currentUser!!.uid
val post = postDao.getPostById(postId).await().toObject(Post::class.java)!!
val createdById = post.createdBy.userId
if(currentUserId == createdById){
withContext(Dispatchers.Main){
val confirmDeleteDialog = android.app.AlertDialog.Builder(this@MainActivity)
.setTitle("Confirm Deleting This Post")
.setMessage("Do you want to delete this post?\nWarning: You can't undo this action..")
.setPositiveButton("Delete"){ _, _ ->
postDao.deletePost(postId)
}
.setNegativeButton("Cancel"){ _, _ ->
Toast.makeText(this@MainActivity, "Cancelled delete action", Toast.LENGTH_LONG).show()
}
.create()
.show()
}
}
}
}
override fun editPost(postID: String) {
val intent = Intent(this, EditPostActivity::class.java)
intent.putExtra("postId", postID)
startActivity(intent)
}
}
| 0
|
Kotlin
|
0
| 0
|
d7c6c6770e18b2d04daf016d4becca95270b8a92
| 5,154
|
InstaDon
|
Apache License 2.0
|
src/test/kotlin/uk/gov/justice/digital/hmpps/nomisprisonerapi/helper/builders/OffenderCaseNote.kt
|
ministryofjustice
| 444,895,409
| false
|
{"Kotlin": 2982892, "PLSQL": 319433, "Dockerfile": 1112}
|
package uk.gov.justice.digital.hmpps.nomisprisonerapi.helper.builders
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Component
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.NoteSourceCode
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.OffenderBooking
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.OffenderCaseNote
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.Staff
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.TaskSubType
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.TaskType
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.repository.OffenderCaseNoteRepository
import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.repository.ReferenceCodeRepository
import java.time.LocalDateTime
@DslMarker
annotation class OffenderCaseNoteDslMarker
@NomisDataDslMarker
interface OffenderCaseNoteDsl
@Component
class OffenderCaseNoteBuilderFactory(
private val repository: OffenderCaseNoteBuilderRepository,
) {
fun builder(): OffenderCaseNoteBuilder {
return OffenderCaseNoteBuilder(repository)
}
}
@Component
class OffenderCaseNoteBuilderRepository(
private val repository: OffenderCaseNoteRepository,
private val taskTypeRepository: ReferenceCodeRepository<TaskType>,
private val taskSubTypeRepository: ReferenceCodeRepository<TaskSubType>,
) {
fun save(casenote: OffenderCaseNote): OffenderCaseNote =
repository.saveAndFlush(casenote)
fun lookupTaskType(code: String): TaskType =
taskTypeRepository.findByIdOrNull(TaskType.pk(code))!!
fun lookupTaskSubType(code: String): TaskSubType =
taskSubTypeRepository.findByIdOrNull(TaskSubType.pk(code))!!
}
class OffenderCaseNoteBuilder(
private val repository: OffenderCaseNoteBuilderRepository,
) : OffenderCaseNoteDsl {
private lateinit var casenote: OffenderCaseNote
fun build(
offenderBooking: OffenderBooking,
caseNoteType: String,
caseNoteSubType: String,
date: LocalDateTime,
author: Staff,
caseNoteText: String?,
amendmentFlag: Boolean,
noteSourceCode: NoteSourceCode,
): OffenderCaseNote = OffenderCaseNote(
offenderBooking = offenderBooking,
occurrenceDate = date.toLocalDate(),
occurrenceDateTime = date,
caseNoteType = repository.lookupTaskType(caseNoteType),
caseNoteSubType = repository.lookupTaskSubType(caseNoteSubType),
author = author,
agencyLocation = offenderBooking.location,
caseNoteText = caseNoteText,
amendmentFlag = amendmentFlag,
noteSourceCode = noteSourceCode,
dateCreation = date.toLocalDate(),
timeCreation = date,
)
.let { repository.save(it) }
.also { casenote = it }
}
| 1
|
Kotlin
|
2
| 0
|
ed55a6daf0b396dfc82584d460e11ce3e66f232a
| 2,706
|
hmpps-nomis-prisoner-api
|
MIT License
|
cockroachdb-dialect/src/test/kotlin/com/faire/sqldelight/dialects/cockroachdb/CockroachDBFixturesTest.kt
|
Faire
| 658,801,175
| false
| null |
/**
* Copyright 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.faire.sqldelight.dialects.cockroachdb
import app.cash.sqldelight.dialects.postgresql.PostgresqlTestFixtures
import com.alecstrong.sql.psi.test.fixtures.FixturesTest
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.io.File
@RunWith(Parameterized::class)
class CockroachDBFixturesTest(name: String, fixtureRoot: File) : FixturesTest(name, fixtureRoot) {
override val replaceRules = arrayOf(
"INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT" to "SERIAL NOT NULL PRIMARY KEY",
"AUTOINCREMENT" to "",
"?1" to "?",
"?2" to "?",
"BLOB" to "TEXT",
"id TEXT GENERATED ALWAYS AS (2) UNIQUE NOT NULL" to "id TEXT GENERATED ALWAYS AS (2) STORED UNIQUE NOT NULL",
"'(', ')', ',', '.', <binary like operator real>, BETWEEN or IN expected, got ','"
to "'#-', '(', ')', ',', '.', <binary like operator real>, <jsona binary operator real>, <jsonb boolean operator real>, '@@', BETWEEN or IN expected, got ','",
)
override fun setupDialect() {
CockroachDBDialect().setup()
}
companion object {
private val excludedAnsiFixtures = listOf(
// Excluded since we're not validating indices when dropping them.
"index-migration",
// Excluded since we're not validating indices when creating them.
"create-table-validation-failures",
// Excluded since we're not validating indices when creating them.
"create-if-not-exists",
// Excluded since we're not validating indices when creating them.
"create-index-collision",
)
// Used by Parameterized JUnit runner reflectively.
@Parameterized.Parameters(name = "{0}")
@JvmStatic
fun parameters(): List<Array<out Any>> {
val extraAnsiFixtures = ansiFixtures
.filter { (it[0] as String) !in excludedAnsiFixtures }
return CockroachDBTestFixtures.fixtures +
PostgresqlTestFixtures.fixtures +
extraAnsiFixtures
}
}
}
| 2
| null |
1
| 14
|
36e458e6f08d4fe947b11c7aa7481863d5d6d84f
| 2,535
|
sqldelight-cockroachdb-dialect
|
Apache License 2.0
|
item/src/main/java/com/pyamsoft/fridge/item/ItemAdd.kt
|
pyamsoft
| 175,992,414
| false
| null |
/*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.fridge.entry
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.tooling.preview.Preview
import com.google.accompanist.insets.navigationBarsPadding
@Composable
fun EntryAdd(
modifier: Modifier = Modifier,
bottomNavHeight: Int,
onAddClicked: () -> Unit,
onHeightMeasured: (Int) -> Unit,
) {
val density = LocalDensity.current
val bottomNavHeightDp =
remember(density, bottomNavHeight) { density.run { bottomNavHeight.toDp() } }
Row(
modifier =
modifier
.navigationBarsPadding(bottom = true)
.padding(bottom = bottomNavHeightDp)
.onSizeChanged { onHeightMeasured(it.height) },
verticalAlignment = Alignment.CenterVertically,
) {
Spacer(
modifier = Modifier.weight(1F),
)
FloatingActionButton(
onClick = onAddClicked,
) {
Icon(
imageVector = Icons.Filled.Add,
contentDescription = "Add New",
)
}
}
}
@Preview
@Composable
private fun PreviewEntryAdd() {
Surface {
EntryAdd(
bottomNavHeight = 0,
onAddClicked = {},
onHeightMeasured = {},
)
}
}
| 6
| null |
2
| 6
|
c2cadba9366ebd71d4a224945d76ba71d5bf7784
| 2,357
|
fridgefriend
|
Apache License 2.0
|
src/me/anno/fonts/FontManager.kt
|
AntonioNoack
| 456,513,348
| false
| null |
package me.anno.fonts
import me.anno.cache.AsyncCacheData
import me.anno.cache.CacheData
import me.anno.cache.CacheSection
import me.anno.cache.LRUCache
import me.anno.fonts.FontStats.getTextGenerator
import me.anno.fonts.FontStats.queryInstalledFonts
import me.anno.fonts.keys.FontKey
import me.anno.fonts.keys.TextCacheKey
import me.anno.gpu.GFX
import me.anno.gpu.drawing.GFXx2D
import me.anno.gpu.texture.ITexture2D
import me.anno.gpu.texture.Texture2DArray
import me.anno.maths.Maths.ceilDiv
import me.anno.utils.types.Booleans.toInt
import me.anno.utils.types.Strings.isBlank2
import org.apache.logging.log4j.LogManager
import kotlin.math.exp
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.min
import kotlin.math.round
import kotlin.math.roundToInt
object FontManager {
val TextCache = CacheSection("Text")
val TextSizeCache = CacheSection("TextSize")
private val LOGGER = LogManager.getLogger(FontManager::class)
private const val textureTimeout = 10_000L
private val fonts = HashMap<FontKey, TextGenerator>()
val fontSet by lazy {
queryInstalledFonts().toSortedSet()
}
fun getFontSizeIndex(fontSize: Float): Int = max(0, round(100.0 * ln(fontSize)).toInt())
fun getAvgFontSize(fontSizeIndex: Int): Float = exp(fontSizeIndex * 0.01f)
fun limitWidth(
font: Font,
text: CharSequence,
widthLimit: Int,
heightLimit: Int
): Int {
return if (widthLimit < 0 || widthLimit >= GFX.maxTextureSize || font.size < 1f) GFX.maxTextureSize
else {
val size0 = getSize(font, text, GFX.maxTextureSize, heightLimit, false)
val w = GFXx2D.getSizeX(size0)
if (w <= widthLimit) return size0
val step = max(1, font.size.toInt())
min(w, (widthLimit + step / 2) / step * step)
}
}
fun limitHeight(font: Font, heightLimit: Int): Int {
val fontHeight = font.size // roughly, not exact!
val spaceBetweenLines = spaceBetweenLines(fontHeight)
// val height = (fontHeight + spaceBetweenLines) * lineCount - spaceBetweenLines
// val lineCount = ceil((heightLimit - spaceBetweenLines) / (fontHeight + spaceBetweenLines)).toInt()
val effLineHeight = font.sizeInt + spaceBetweenLines
return ceilDiv(heightLimit, effLineHeight)
}
fun limitHeight(
font: Font,
text: CharSequence,
widthLimit2: Int,
heightLimit: Int
): Int {
return if (heightLimit < 0 || heightLimit >= GFX.maxTextureSize) GFX.maxTextureSize
else {
val size0 = getSize(font, text, widthLimit2, GFX.maxTextureSize, false)
val h = GFXx2D.getSizeY(size0)
limitHeight(font, min(h, heightLimit))
}
}
fun getSize(key: TextCacheKey, async: Boolean): Int {
val data = TextSizeCache.getEntry(key, 100_000, async) {
val awtFont = getFont(it)
val wl = if (it.widthLimit < 0) GFX.maxTextureSize else min(it.widthLimit, GFX.maxTextureSize)
val hl = if (it.heightLimit < 0) GFX.maxTextureSize else min(it.heightLimit, GFX.maxTextureSize)
CacheData(awtFont.calculateSize(it.text, wl, hl))
} as? CacheData<*>
return data?.value as? Int ?: -1
}
fun getSize(
font: Font,
text: CharSequence,
widthLimit: Int,
heightLimit: Int,
async: Boolean
): Int {
if (text.isEmpty()) return GFXx2D.getSize(0, font.sizeInt)
return getSize(TextCacheKey.getKey(font, text, widthLimit, heightLimit, false), async)
}
fun getBaselineY(
font: Font
): Float {
// val f = getFont(font)
// why ever...
// Consolas example:
// font size 40
// best value: 17/18
// ascent: 30
// descent: 10
return -font.size * 17f / 40f
}
fun getTextCacheKey(
font: Font,
text: String,
widthLimit: Int,
heightLimit: Int
): TextCacheKey? {
if (text.isBlank2()) return null
val fontSize = font.size
val fontSizeIndex = getFontSizeIndex(fontSize)
val sub = fontSizeIndex * 8 + font.isItalic.toInt(4) + font.isBold.toInt(2)
val wl = if (widthLimit < 0) GFX.maxTextureSize else min(widthLimit, GFX.maxTextureSize)
val hl = if (heightLimit < 0) GFX.maxTextureSize else min(heightLimit, GFX.maxTextureSize)
val wl2 = limitWidth(font, text, wl, hl)
val hl2 = limitHeight(font, text, wl2, hl)
val fontName = font.name
return TextCacheKey(text, fontName, sub, wl2, hl2)
}
fun getTexture(
font: Font, text: String,
widthLimit: Int, heightLimit: Int, async: Boolean
): ITexture2D? {
return getTexture(font, text, widthLimit, heightLimit, textureTimeout, async)
}
fun getTexture(
font: Font, text: String,
widthLimit: Int, heightLimit: Int,
timeoutMillis: Long, async: Boolean
): ITexture2D? {
val wl = if (widthLimit < 0) GFX.maxTextureSize else min(widthLimit, GFX.maxTextureSize)
val hl = if (heightLimit < 0) GFX.maxTextureSize else min(heightLimit, GFX.maxTextureSize)
val key = getTextCacheKey(font, text, wl, hl) ?: return null
return getTexture(key, timeoutMillis, async)
}
private val asciiTexLRU = LRUCache<Font, Texture2DArray>(16)
fun getASCIITexture(font: Font): Texture2DArray {
val prev = asciiTexLRU[font]
if (prev is Texture2DArray && prev.isCreated()) {
return prev
}
val entry = TextCache.getEntry(font, textureTimeout, false) { key ->
val entry = AsyncCacheData<Texture2DArray>()
getFont(key).generateASCIITexture(false, entry)
entry
} as AsyncCacheData<*>
entry.waitForGFX()
val curr = entry.value as Texture2DArray
asciiTexLRU[font] = curr
return curr
}
fun getTexture(cacheKey: TextCacheKey, async: Boolean): ITexture2D? {
return getTexture(cacheKey, textureTimeout, async)
}
fun getTexture(cacheKey: TextCacheKey, timeoutMillis: Long, async: Boolean): ITexture2D? {
// must be sync:
// - textures need to be available
// - Java/Windows is not thread-safe
if (cacheKey.text.isBlank2()) return null
val entry = TextCache.getEntry(cacheKey, timeoutMillis, async) { key ->
val font2 = getFont(key)
val wl = if (key.widthLimit < 0) GFX.maxTextureSize else min(key.widthLimit, GFX.maxTextureSize)
val hl = if (key.heightLimit < 0) GFX.maxTextureSize else min(key.heightLimit, GFX.maxTextureSize)
val entry = AsyncCacheData<ITexture2D>()
font2.generateTexture(key.text, wl, hl, key.isGrayscale(), entry)
entry
} as? AsyncCacheData<*>
if (!async) entry?.waitForGFX()
return entry?.value as? ITexture2D
}
fun getFont(key: TextCacheKey): TextGenerator =
getFont(key.fontName, getAvgFontSize(key.fontSizeIndex()), key.isBold(), key.isItalic())
fun getFont(font: Font): TextGenerator =
getFont(font.name, font.size, font.isBold, font.isItalic)
fun getFont(name: String, fontSize: Float, bold: Boolean, italic: Boolean): TextGenerator {
val fontSizeIndex = getFontSizeIndex(fontSize)
return getFont(name, fontSizeIndex, bold, italic)
}
private fun getFont(
name: String,
fontSizeIndex: Int,
bold: Boolean,
italic: Boolean
): TextGenerator {
val key = FontKey(name, fontSizeIndex, bold, italic)
return fonts.getOrPut(key) {
getTextGenerator(key)
}
}
fun spaceBetweenLines(fontSize: Float) = (0.5f * fontSize).roundToInt()
}
| 0
| null |
3
| 24
|
63377c2e684adf187a31af0f4e5dd0bfde1d050e
| 7,859
|
RemsEngine
|
Apache License 2.0
|
kotlin.web.demo.server/examples/Kotlin in Action/Chapter 3/3.5/2_1_ParsePath.kt
|
arrow-kt
| 117,599,238
| false
| null |
package cc.stevenyin.actioninkotlin.chapter03._03_09
fun parsePath(path: String) {
val directory = path.substringBeforeLast("/")
val fullName = path.substringAfterLast("/")
val fileName = fullName.substringBeforeLast(".")
val extension = path.substringAfterLast(".")
println("Dir: $directory, name: $fileName, ext: $extension")
}
fun main(args: Array<String>) {
parsePath("/Users/yole/kotlin-book/chapter.adoc")
}
| 2
| null |
2
| 7
|
7165d9568d725c9784a1e7525f35bab93241f292
| 425
|
try.arrow-kt.io
|
Apache License 2.0
|
app/src/main/java/com/puntogris/recap/feature_recap/presentation/recap_detail/RecapFragment.kt
|
puntogris
| 398,389,151
| false
| null |
package com.puntogris.recap.feature_recap.presentation.recap_detail
import android.content.Intent
import android.text.Html
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.puntogris.recap.NavigationDirections
import com.puntogris.recap.R
import com.puntogris.recap.core.presentation.base.BaseBindingFragment
import com.puntogris.recap.core.utils.Resource
import com.puntogris.recap.core.utils.actionOrLogin
import com.puntogris.recap.core.utils.setupBackgroundAndFontColors
import com.puntogris.recap.core.utils.showSnackBar
import com.puntogris.recap.databinding.FragmentRecapBinding
import com.puntogris.recap.feature_recap.domain.model.isApproved
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class RecapFragment : BaseBindingFragment<FragmentRecapBinding>(R.layout.fragment_recap) {
private val viewModel: RecapViewModel by viewModels()
private val args: RecapFragmentArgs by navArgs()
override fun initializeViews() {
binding.fragment = this
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = viewModel
subscribeRecapState()
setupNavigation()
}
private fun subscribeRecapState() {
viewModel.recapState.observe(viewLifecycleOwner) {
when (it) {
is Resource.Error -> {
}
is Resource.Success -> {
viewModel.updateRecap(it.data)
binding.recapHeader.viewStub?.apply {
layoutResource = if (it.data.isApproved()) {
R.layout.recap_detail_header
} else {
R.layout.rate_recap_header
}
inflate()
}
}
}
}
}
private fun setupNavigation() {
with(binding.toolbar) {
setNavigationOnClickListener {
findNavController().navigateUp()
}
setOnMenuItemClickListener {
when (it.itemId) {
R.id.action_report -> actionOrLogin(viewModel.isUserLoggedIn()) {
val recapId = args.recap?.id ?: args.recapId!!
val action =
RecapFragmentDirections.actionRecapFragmentToReportRecapDialog(recapId)
findNavController().navigate(action)
}
}
true
}
}
}
private fun navigateToProfile() {
val action = NavigationDirections.actionGlobalUserFragment(viewModel.recap.value.uid)
findNavController().navigate(action)
}
fun onFavoriteClicked() {
actionOrLogin(viewModel.isUserLoggedIn()) {
showSnackBar("Agregado a favoritos")
}
}
fun onLikedClicked() {
actionOrLogin(viewModel.isUserLoggedIn()) {
showSnackBar("Te gusto este recap.")
}
}
fun onRateClicked() {
actionOrLogin(viewModel.isUserLoggedIn()) {
val action =
RecapFragmentDirections.actionRecapFragmentToSelectRatingDialog(viewModel.recap.value.id)
findNavController().navigate(action)
}
}
fun onShareClicked() {
val share = Intent.createChooser(Intent().apply {
action = Intent.ACTION_SEND
type = "text/plain"
putExtra(Intent.EXTRA_TITLE, getString(R.string.share_recap_intent_title))
putExtra(Intent.EXTRA_TEXT, viewModel.recap.value.deepLink)
}, null)
startActivity(share)
}
}
| 0
|
Kotlin
|
0
| 0
|
960f3f6f3c876289cfc6e7edc76778af05dcdcd0
| 3,738
|
recap
|
MIT License
|
compiler/backend/src/org/jetbrains/kotlin/codegen/range/CallIntrinsicRangeValue.kt
|
JakeWharton
| 99,388,807
| false
| null |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.codegen.range
import org.jetbrains.kotlin.codegen.ExpressionCodegen
import org.jetbrains.kotlin.codegen.range.inExpression.CallBasedInExpressionGenerator
import org.jetbrains.kotlin.codegen.range.inExpression.InExpressionGenerator
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCallWithAssert
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
abstract class CallIntrinsicRangeValue(protected val rangeCall: ResolvedCall<out CallableDescriptor>) : RangeValue {
protected abstract fun isIntrinsicInCall(resolvedCallForIn: ResolvedCall<out CallableDescriptor>): Boolean
protected abstract fun createIntrinsicInExpressionGenerator(
codegen: ExpressionCodegen,
operatorReference: KtSimpleNameExpression,
resolvedCall: ResolvedCall<out CallableDescriptor>
): InExpressionGenerator
override fun createInExpressionGenerator(codegen: ExpressionCodegen, operatorReference: KtSimpleNameExpression): InExpressionGenerator {
val resolvedCall = operatorReference.getResolvedCallWithAssert(codegen.bindingContext)
return if (isIntrinsicInCall(resolvedCall))
createIntrinsicInExpressionGenerator(codegen, operatorReference, resolvedCall)
else
CallBasedInExpressionGenerator(codegen, operatorReference)
}
}
| 181
| null |
5748
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 2,052
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/kenkoro/taurus/client/feature/orders/data/remote/api/CutOrderRemoteApiImpl.kt
|
kenkoro
| 746,982,789
| false
|
{"Kotlin": 272290, "JavaScript": 64}
|
package com.kenkoro.taurus.client.feature.orders.data.remote.api
import com.kenkoro.taurus.client.feature.orders.data.remote.dto.ActualCutOrdersQuantityDto
import com.kenkoro.taurus.client.feature.orders.data.remote.dto.CutOrderDto
import com.kenkoro.taurus.client.feature.orders.data.remote.dto.NewCutOrderDto
import com.kenkoro.taurus.client.feature.shared.Urls
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.headers
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.request.url
import io.ktor.http.ContentType
import io.ktor.http.contentType
class CutOrderRemoteApiImpl(
private val client: HttpClient,
) : CutOrderRemoteApi {
override suspend fun addNewCutOrder(
dto: NewCutOrderDto,
token: String,
): CutOrderDto =
client.post {
url(Urls.ADD_NEW_CUT_ORDER)
setBody(dto)
contentType(ContentType.Application.Json)
headers {
append("Authorization", "Bearer $token")
}
}.body<CutOrderDto>()
override suspend fun getActualCutOrdersQuantity(
orderId: Int,
token: String,
): ActualCutOrdersQuantityDto =
client.get {
url("${Urls.GET_ACTUAL_CUT_ORDERS_QUANTITY}/$orderId")
contentType(ContentType.Application.Json)
headers {
append("Authorization", "Bearer $token")
}
}.body<ActualCutOrdersQuantityDto>()
}
| 4
|
Kotlin
|
0
| 4
|
f14526cccbf81ab247cae532709efe57b63b71f5
| 1,445
|
taurus
|
Apache License 2.0
|
marvel-api/src/main/java/com/botob/marvelapi/client/models/TextObject.kt
|
boriguen
| 456,050,617
| false
| null |
/**
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: Cable
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.botob.marvelapi.client.models
/**
*
* @param type The canonical type of the text object (e.g. solicit text, preview text, etc.).
* @param language The IETF language tag denoting the language the text object is written in.
* @param text The text.
*/
data class TextObject (
/* The canonical type of the text object (e.g. solicit text, preview text, etc.). */
val type: String? = null,
/* The IETF language tag denoting the language the text object is written in. */
val language: String? = null,
/* The text. */
val text: String? = null
) {
}
| 0
|
Kotlin
|
0
| 0
|
e231f1d23df3fd9fa69732fa204e6f3031c55d62
| 910
|
marvel-comics-android-app
|
MIT License
|
app/src/main/java/com/grupo2/elorchat/data/database/dao/MessageDao.kt
|
AgerAlPe
| 741,038,643
| false
|
{"Kotlin": 163323}
|
package com.grupo2.elorchat.data.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.grupo2.elorchat.data.database.entities.MessageEntity
@Dao
interface MessageDao {
@Query("SELECT * FROM message_table")
suspend fun getAllMessage():List<MessageEntity>
@Query("SELECT * FROM message_table where id = :userId")
suspend fun getAllUserMessage(userId:Int):List<MessageEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(message: List<MessageEntity>)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertMessage(messageEntity: MessageEntity)
}
| 0
|
Kotlin
|
0
| 0
|
04453137a7e9021fca0103aef81709533020a03e
| 707
|
Reto2_DAM2_PMDM
|
MIT License
|
app/src/main/java/com/grupo2/elorchat/data/database/dao/MessageDao.kt
|
AgerAlPe
| 741,038,643
| false
|
{"Kotlin": 163323}
|
package com.grupo2.elorchat.data.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.grupo2.elorchat.data.database.entities.MessageEntity
@Dao
interface MessageDao {
@Query("SELECT * FROM message_table")
suspend fun getAllMessage():List<MessageEntity>
@Query("SELECT * FROM message_table where id = :userId")
suspend fun getAllUserMessage(userId:Int):List<MessageEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(message: List<MessageEntity>)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertMessage(messageEntity: MessageEntity)
}
| 0
|
Kotlin
|
0
| 0
|
04453137a7e9021fca0103aef81709533020a03e
| 707
|
Reto2_DAM2_PMDM
|
MIT License
|
platform/testbed/src/integrationTest/kotlin/io/hamal/testbed/admin/SqliteAdminTest.kt
|
hamal-io
| 622,870,037
| false
|
{"Kotlin": 1744717, "C": 1398401, "TypeScript": 54320, "C++": 40651, "Lua": 36419, "Makefile": 11728, "Java": 7564, "CMake": 2881, "JavaScript": 1532, "HTML": 694, "Shell": 456, "CSS": 118}
|
package io.hamal.testbed.admin
import io.hamal.admin.AdminConfig
import io.hamal.bridge.BridgeConfig
import io.hamal.core.CoreConfig
import io.hamal.core.config.BackendBasePath
import io.hamal.runner.RunnerConfig
import org.junit.jupiter.api.DisplayName
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT
import org.springframework.context.annotation.Bean
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.context.ActiveProfiles
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
@SpringBootTest(
webEnvironment = DEFINED_PORT,
properties = [
"server.port=8053",
"io.hamal.runner.admin.host=http://localhost:8053",
"io.hamal.runner.api.host=http://localhost:8053",
"io.hamal.runner.bridge.host=http://localhost:8053"
], classes = [
AdminTestConfig::class,
CoreConfig::class,
AdminConfig::class,
BridgeConfig::class,
RunnerConfig::class
]
)
@DirtiesContext
@DisplayName("admin - sqlite")
@ActiveProfiles(value = ["test", "admin", "sqlite"])
internal class SqliteAdminHamalTest : BaseAdminTest() {
final override val adminSdk = rootAdminSdk(8053)
final override val testPath: Path = Paths.get("src", "integrationTest", "resources", "admin")
@Bean
fun backendBasePath() = BackendBasePath("/tmp/hamal/test-sqlite/${UUID.randomUUID()}")
}
| 6
|
Kotlin
|
0
| 0
|
6c7f5cc645ba67fb85df20d9a5d2e18372a012f4
| 1,499
|
hamal
|
Creative Commons Zero v1.0 Universal
|
client/src/main/kotlin/tech/figure/validationoracle/client/domain/serialization/CosmWasmUintToBigIntegerDeserializer.kt
|
FigureTechnologies
| 559,039,293
| false
| null |
package tech.figure.validationoracle.client.domain.serialization
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import java.math.BigInteger
/**
* Deserializes a CosmWasm Uint value in a response JSON payload to a [BigInteger], assuming it is a quoted integer.
*/
class CosmWasmUintToBigIntegerDeserializer : JsonDeserializer<BigInteger>() {
/**
* This is a deserializer for Cosmwasm's Uint types (they include wrappers for most unsigned rust integer types).
* The value is returned as a double-quoted numeric value, so simply invoking toBigIntegerOrNull is sufficient
* for deserialization.
*/
override fun deserialize(p: JsonParser?, ctxt: DeserializationContext?): BigInteger? = p
?.text
?.toBigIntegerOrNull()
}
| 5
|
Kotlin
|
0
| 0
|
335991532991cb227344c5db5bdfffa0131738a7
| 877
|
validation-oracle-libs
|
Apache License 2.0
|
modules/domain/sources/assembly/RaptorAggregateComponent.kt
|
fluidsonic
| 246,018,343
| false
| null |
package io.fluidsonic.raptor.domain
import io.fluidsonic.raptor.*
import io.fluidsonic.raptor.di.*
import kotlin.collections.set
import kotlin.reflect.*
import kotlin.reflect.full.*
public class RaptorAggregateComponent<
Aggregate : RaptorAggregate<Id, Command, Change>,
Id : RaptorAggregateId,
Command : RaptorAggregateCommand<Id>,
Change : RaptorAggregateChange<Id>,
> internal constructor(
private val aggregateClass: KClass<Aggregate>, // FIXME use KTypes
private val changeClass: KClass<Change>,
private val commandClass: KClass<Command>,
private val discriminator: String,
private val factory: RaptorAggregateFactory<Aggregate, Id>,
private val idClass: KClass<Id>,
private val individual: Boolean,
private val topLevelScope: RaptorAssemblyInstallationScope,
) : RaptorComponent.Base<RaptorAggregateComponent<Aggregate, Id, Command, Change>>(RaptorDomainPlugin) {
private val changeDefinitions: MutableMap<KClass<out Change>, RaptorAggregateChangeDefinition<Id, out Change>> = hashMapOf()
private val commandDefinitions: MutableMap<KClass<out Command>, RaptorAggregateCommandDefinition<Id, out Command>> = hashMapOf()
private var projectionDefinition: RaptorAggregateProjectionDefinition<*, *, Change>? = null
@RaptorDsl
public fun change(discriminator: String, changeClass: KClass<out Change>) {
check(!changeDefinitions.containsKey(changeClass)) { "Cannot define change $changeClass multiple times." }
check(changeDefinitions.values.none { it.discriminator == discriminator }) {
"Cannot define multiple changes with the same discriminator: $discriminator."
}
changeDefinitions[changeClass] = RaptorAggregateChangeDefinition(
changeClass = changeClass,
discriminator = discriminator,
)
}
@RaptorDsl
public fun command(commandClass: KClass<out Command>) {
check(!commandDefinitions.containsKey(commandClass)) { "Cannot define command $commandClass multiple times." }
commandDefinitions[commandClass] = RaptorAggregateCommandDefinition(commandClass = commandClass)
}
internal fun complete() =
RaptorAggregateDefinition(
aggregateClass = aggregateClass,
changeClass = changeClass,
changeDefinitions = changeDefinitions.values.toHashSet(),
commandClass = commandClass,
commandDefinitions = commandDefinitions.values.toHashSet(),
discriminator = discriminator,
factory = factory,
idClass = idClass,
isIndividual = individual,
projectionDefinition = projectionDefinition,
)
@RaptorInternalApi // FIXME
@RaptorDsl
public fun <Projection : RaptorAggregateProjection<Id>> _project(
projectionClass: KClass<Projection>, projectorFactory: () -> RaptorAggregateProjector.Incremental<Projection, *, Change>,
) {
check(!individual) { "Can't register a projector for an individual aggregate." }
check(this.projectionDefinition == null) { "Cannot set multiple projector factories for aggregate $aggregateClass." }
this.projectionDefinition =
RaptorAggregateProjectionDefinition(
factory = projectorFactory as () -> RaptorAggregateProjector.Incremental<RaptorAggregateProjection<RaptorAggregateProjectionId>, RaptorAggregateProjectionId, RaptorAggregateChange<RaptorAggregateProjectionId>>,
idClass = idClass as KClass<RaptorAggregateProjectionId>,
projectionClass = projectionClass as KClass<RaptorAggregateProjection<RaptorAggregateProjectionId>>,
) as RaptorAggregateProjectionDefinition<*, *, Change>
with(topLevelScope) { // FIXME remove hack
optional(RaptorDIPlugin) {
// transactions { // FIXME
di.provide<RaptorAggregateProjectionLoader<RaptorAggregateProjection<*>, RaptorAggregateProjectionId>>(
RaptorAggregateProjectionLoader::class.createType(
listOf(
KTypeProjection.invariant(projectionClass.starProjectedType),
KTypeProjection.invariant(this@RaptorAggregateComponent.idClass.starProjectedType),
)
)
) {
// FIXME Improve.
// FIXME (context as RaptorTransactionContext)
context.projectionLoader(this@RaptorAggregateComponent.idClass)
}
// }
}
}
}
}
@RaptorDsl
public inline fun <reified Command : RaptorAggregateCommand<*>> RaptorAssemblyQuery<RaptorAggregateComponent<*, *, in Command, *>>.command() {
each {
command(Command::class)
}
}
@RaptorDsl
public fun <Event : RaptorAggregateChange<*>>
RaptorAssemblyQuery<RaptorAggregateComponent<*, *, *, in Event>>.change(
discriminator: String,
eventClass: KClass<Event>,
) {
each {
change(discriminator, eventClass)
}
}
@RaptorDsl
public inline fun <reified Event : RaptorAggregateChange<*>>
RaptorAssemblyQuery<RaptorAggregateComponent<*, *, *, in Event>>.change(
discriminator: String,
) {
change(discriminator, Event::class)
}
@OptIn(RaptorInternalApi::class) // FIXME remove
@RaptorDsl
public fun <Projection : RaptorAggregateProjection<Id>, Id : RaptorAggregateProjectionId, Event : RaptorAggregateChange<Id>>
RaptorAssemblyQuery<RaptorAggregateComponent<out RaptorAggregate<Id, *, Event>, Id, *, Event>>.project(
projectionClass: KClass<Projection>,
projectorFactory: () -> RaptorAggregateProjector.Incremental<Projection, Id, Event>,
) {
each {
_project(projectionClass, projectorFactory)
}
}
@RaptorDsl
public inline fun <reified Projection : RaptorAggregateProjection<Id>, Id : RaptorAggregateProjectionId, Event : RaptorAggregateChange<Id>>
RaptorAssemblyQuery<RaptorAggregateComponent<out RaptorAggregate<Id, *, Event>, Id, *, Event>>.project(
noinline projectorFactory: () -> RaptorAggregateProjector.Incremental<Projection, Id, Event>,
) {
project(Projection::class, projectorFactory)
}
| 0
|
Kotlin
|
2
| 6
|
aa106d096b700d6eadbcf9ef5df8ec102f7a3fac
| 5,591
|
raptor
|
Apache License 2.0
|
app/src/main/java/com/parseus/codecinfo/data/codecinfo/profilelevels/MVCProfileLevels.kt
|
Parseus
| 139,889,241
| false
| null |
@file:Suppress("EnumEntryName", "unused")
package com.parseus.codecinfo.data.codecinfo.profilelevels
enum class MVCProfiles(val value: Int) {
MVCProfileStereoHigh(0x01),
MVCProfileMultiViewHigh(0x02),
MVCProfileMax(0x7FFFFFFF);
companion object {
fun from(findValue: Int): String? = values().find { it.value == findValue }?.name
}
}
enum class MVCLevels (val value: Int) {
MVCLevel1(0x01),
MVCLevel1b(0x02),
MVCLevel11(0x04),
MVCLevel12(0x08),
MVCLevel13(0x10),
MVCLevel2(0x20),
MVCLevel21(0x40),
MVCLevel22(0x80),
MVCLevel3(0x100),
MVCLevel31(0x200),
MVCLevel32(0x400),
MVCLevel4(0x800),
MVCLevel41(0x1000),
MVCLevel42(0x2000),
MVCLevel5(0x4000),
MVCLevel51(0x8000),
MVCLevelMax(0x7FFFFFFF);
companion object {
fun from(findValue: Int): String? = values().find { it.value == findValue }?.name
}
}
| 2
| null |
14
| 88
|
4cfc0d3cc3c75167718bdaebac2c4881ad9aeb4a
| 917
|
codecinfo
|
Apache License 2.0
|
core/database/src/main/kotlin/io/github/edwinchang24/salvage/database/model/ItemEntity.kt
|
EdwinChang24
| 653,775,661
| false
| null |
package io.github.edwinchang24.salvage.core.database.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import io.github.edwinchang24.salvage.core.model.Item
import kotlinx.datetime.Instant
@Entity(tableName = "items")
data class ItemEntity(
@PrimaryKey
val id: String,
val name: String?,
val url: String,
val description: String?,
val timeAdded: Instant,
val timePublished: Instant?
)
fun ItemEntity.asExternalModel() = Item(
id = id,
name = name,
url = url,
description = description,
timeAdded = timeAdded,
timePublished = timePublished
)
| 5
|
Kotlin
|
0
| 0
|
b4511321f3da3763c54207a2ee07c84c6055788c
| 612
|
salvage
|
MIT License
|
core/database/src/main/java/com/hellguy39/hellnotes/core/database/converter/LabelConverter.kt
|
HellGuy39
| 572,830,054
| false
| null |
package com.hellguy39.hellnotes.core.database.converter
import androidx.room.TypeConverter
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import java.lang.reflect.ParameterizedType
class LabelConverter {
private val moshi = Moshi.Builder().build()
private val type: ParameterizedType =
Types.newParameterizedType(
List::class.java,
Long::class.javaObjectType,
)
private val jsonAdapter: JsonAdapter<List<Long>> = moshi.adapter(type)
@TypeConverter
fun fromLabelList(list: List<Long>?): String? {
return jsonAdapter.toJson(list)
}
@TypeConverter
fun toLabelList(jsonStr: String?): List<Long>? {
return jsonStr?.let { jsonAdapter.fromJson(jsonStr) }
}
}
| 2
|
Kotlin
|
0
| 9
|
548d59c0f641df6e1f3ddd9c220904631ca5351b
| 803
|
HellNotes
|
Apache License 2.0
|
app/src/main/java/za/co/varsitycollege/st10204772/opsc7312_poe/ClientID.kt
|
Allana-Morris
| 849,370,322
| false
|
{"Kotlin": 161039}
|
package za.co.varsitycollege.st10204772.opsc7312_poe
object ClientID {
const val CLIENT_ID = "eb9b8af983d94603adaa1d212cf58980"
const val REDIRECT_URI = "myapp://callback"
const val REDIRECT_URI2 = "myapp://callback2"
const val CLIENT_SECRET = "<KEY>"
const val app_client_id = "905988466931-7dgl1beg0omvj4k1r0ct11sos1eghgsv.apps.googleusercontent.com"
const val server_client_id = "905988466931-udtk2slaq94ti7dspdvferlbca4n6o0m.apps.googleusercontent.com"
}
| 0
|
Kotlin
|
0
| 1
|
9f1f78dd5bee8c360759465f1e6802ed08c32865
| 492
|
OPSC7312_POE
|
MIT License
|
bungee/src/main/kotlin/catmoe/fallencrystal/moefilter/network/limbo/netty/LimboDecoder.kt
|
CatMoe
| 638,486,044
| false
| null |
/*
* Copyright 2023. CatMoe / FallenCrystal
*
* 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 catmoe.fallencrystal.moefilter.network.limbo.netty
import catmoe.fallencrystal.moefilter.network.bungee.pipeline.MoeChannelHandler
import catmoe.fallencrystal.moefilter.network.common.ExceptionCatcher
import catmoe.fallencrystal.moefilter.network.limbo.handler.LimboHandler
import catmoe.fallencrystal.moefilter.network.limbo.handler.MoeLimbo
import catmoe.fallencrystal.moefilter.network.limbo.listener.LimboListener
import catmoe.fallencrystal.moefilter.network.limbo.packet.common.Unknown
import catmoe.fallencrystal.moefilter.network.limbo.packet.protocol.Protocol
import catmoe.fallencrystal.translation.utils.version.Version
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToMessageDecoder
@Suppress("MemberVisibilityCanBePrivate")
class LimboDecoder(var version: Version?) : MessageToMessageDecoder<ByteBuf>() {
var mappings = Protocol.HANDSHAKING.serverBound.registry[version ?: Version.min]
var handler: LimboHandler? = null
fun switchVersion(version: Version, state: Protocol) {
this.version=version
mappings = state.serverBound.registry[version]
MoeLimbo.debug("Decoder state changed. Version: ${version.name} State: ${state.name}")
}
override fun decode(ctx: ChannelHandlerContext, byteBuf: ByteBuf, out: MutableList<Any>?) {
if (!ctx.channel().isActive) return
val byteMessage = ByteMessage(byteBuf)
val id = byteMessage.readVarInt()
// Unreached code? May just state == null?
/*
if (id == 0x00 && (handler?.state ?: Protocol.HANDSHAKING) == Protocol.HANDSHAKING) { MoeChannelHandler.sentHandshake.put(handler!!.channel, true) }
else if (MoeChannelHandler.sentHandshake.getIfPresent(handler!!.channel) != true) throw InvalidPacketException("No valid handshake packet received")
*/
val packet = mappings?.getPacket(id)
if (packet == null) {
LimboListener.handleReceived(Unknown(id), handler)
if (mappings == null) {
MoeLimbo.debug("Failed to decode incoming packet ${"0x%02X".format(id)}: Mappings is empty")
throw NullPointerException("Mappings cannot be null!")
}
MoeLimbo.debug("Unknown incoming packet ${"0x%02X".format(id)}. Ignoring.")
return
}
// Unreached code?
val version = if (this.version == null || this.version == Version.UNDEFINED) Version.V1_7_6 else this.version
// Try-catch 语句已被删除 因为对于某些异常解码的抛出可以直接顺着exception Caught方法直接切断连接并列入黑名单
// 进行数据包调试时首选打开debug模式
packet.decode(byteMessage, ctx.channel(), version)
LimboListener.handleReceived(packet, handler)
MoeLimbo.debug("Decoding ${"0x%02X".format(id)} packet with ${byteBuf.readableBytes()} bytes length")
MoeLimbo.debug(packet.toString())
ctx.fireChannelRead(packet)
MoeChannelHandler.sentHandshake.put(handler!!.channel, true)
}
@Suppress("OVERRIDE_DEPRECATION")
override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) { ExceptionCatcher.handle(ctx.channel(), cause) }
}
| 3
| null |
0
| 21
|
005d12d9e304f4e872559888ff2f9bcf2d40ba3e
| 3,777
|
MoeFilter
|
Apache License 2.0
|
feature/main/src/test/kotlin/com/masselis/tpmsadvanced/feature/main/interfaces/composable/VehicleKindLocationTest.kt
|
VincentMasselis
| 501,773,706
| false
| null |
package com.masselis.tpmsadvanced.feature.main.interfaces.composable
import com.masselis.tpmsadvanced.data.vehicle.model.SensorLocation.Axle.FRONT
import com.masselis.tpmsadvanced.data.vehicle.model.SensorLocation.FRONT_LEFT
import com.masselis.tpmsadvanced.data.vehicle.model.SensorLocation.Side.LEFT
import com.masselis.tpmsadvanced.data.vehicle.model.Vehicle.Kind.Location.Axle
import com.masselis.tpmsadvanced.data.vehicle.model.Vehicle.Kind.Location.Side
import com.masselis.tpmsadvanced.data.vehicle.model.Vehicle.Kind.Location.Wheel
import org.junit.Test
import kotlin.test.assertEquals
internal class VehicleKindLocationTest {
/**
* I need `Location` to be explicit when `toString()` is called to ensure that the keys used
* by the method `viewModel(key="")` are valid.
*/
@Test
fun toStringTest() {
assertEquals("Axle(axle=FRONT)", "${Axle(FRONT)}")
assertEquals("Side(side=LEFT)", "${Side(LEFT)}")
assertEquals("Wheel(location=FRONT_LEFT)", "${Wheel(FRONT_LEFT)}")
}
}
| 8
| null |
3
| 9
|
27a1e9ca7317fce45b3a8a15855fb86493214fac
| 1,037
|
TPMS-advanced
|
Apache License 2.0
|
src/main/java/video/api/client/api/notifications/NotificationExtensions.kt
|
apivideo
| 428,690,200
| false
| null |
package video.api.uploader.api.notifications
import android.content.Context
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
fun NotificationCompat.Builder.setStyle(
context: Context,
@DrawableRes notificationIconResourceId: Int,
@ColorRes notificationColorResourceId: Int
): NotificationCompat.Builder = apply {
setSmallIcon(notificationIconResourceId)
color = ContextCompat.getColor(context, notificationColorResourceId)
}
| 2
| null |
1
| 18
|
f1470b622258bb182f8ab65ad2be3b923133997e
| 559
|
api.video-android-client
|
MIT License
|
acc2/src/main/java/com/angcyo/acc2/action/ScrollBackwardAction.kt
|
angcyo
| 229,037,615
| false
| null |
package com.angcyo.acc2.action
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat
import com.angcyo.acc2.control.AccControl
import com.angcyo.acc2.control.log
import com.angcyo.acc2.parse.HandleResult
import com.angcyo.acc2.parse.arg
import com.angcyo.acc2.parse.toLog
import com.angcyo.library.ex.*
/**
*
* Email:<EMAIL>
* @author angcyo
* @date 2021/02/01
* Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved.
*/
class ScrollBackwardAction : BaseAction() {
/**记录一下滚动前第一个child节点的文本信息,
* 可以用来判断滚动之后界面是否变化了
* 列表对应的是每一个滚动目标的node
* */
val headerNodeTextList = mutableListOf<String>()
override fun interceptAction(control: AccControl, action: String): Boolean {
return action.startsWith(Action.ACTION_SCROLL_BACKWARD)
}
fun targetNode(
node: AccessibilityNodeInfoCompat,
action: String
): AccessibilityNodeInfoCompat? {
return if (action.arg(Action.ACTION_SCROLL_BACKWARD)?.contains(Action.PARENT) == true) {
node.getScrollableParent()
} else {
node
}
}
override fun runAction(
control: AccControl,
nodeList: List<AccessibilityNodeInfoCompat>?,
action: String
): HandleResult = handleResult {
headerNodeTextList.clear()
nodeList?.forEach { node ->
headerNodeTextList.add(node.firstChild()?.contactChildText() ?: "")
//如果滚动到头部了, 会滚动失败
val targetNode = targetNode(node, action)
val result = targetNode?.scrollBackward() == true
success = success || result
if (result) {
addNode(targetNode ?: node)
}
control.log("向后滚动:$result ↓\n${(targetNode ?: node).toLog(isShowDebug())}")
}
}
var _lastNodeChildText: String? = null
/**将节点滚动到底部*/
fun scrollToHeader(node: AccessibilityNodeInfoCompat, wait: Long = 160) {
_lastNodeChildText = node.contactChildText()
if (node.scrollBackward()) {
//滚动成功
sleep(wait)
val text = node.contactChildText()
if (_lastNodeChildText == text) {
//内容一样, 到底了
return
}
scrollToHeader(node)
}
}
/**滚动后, 节点的文本是否改变*/
fun isScrollNodeTextChange(oldText: String?): Boolean {
return headerNodeTextList.lastOrNull() != oldText
}
}
| 0
| null |
6
| 5
|
83f761e205ed6ce510599bf92ceafc508f5645e7
| 2,430
|
UICore
|
MIT License
|
src/main/kotlin/com/openmeteo/api/common/units/LengthUnit.kt
|
open-meteo
| 524,706,191
| false
|
{"Kotlin": 145141}
|
package com.openmeteo.api.common.units
import kotlinx.serialization.SerialName
enum class LengthUnit {
@SerialName("metric")
Metric,
@SerialName("imperial")
Imperial,
}
| 6
|
Kotlin
|
1
| 20
|
c342acd53559fe92b54821d6603709fee645e2d0
| 188
|
open-meteo-api-kotlin
|
MIT License
|
compose/src/main/java/androidx/compose/foundation/layout/samples/ConstraintLayoutSample.kt
|
Gurupreet
| 293,232,977
| false
| null |
/*
* Copyright 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 androidx.compose.foundation.layout.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.layout.ConstraintLayout
import androidx.compose.foundation.layout.ConstraintSet
import androidx.compose.foundation.layout.Dimension
import androidx.compose.foundation.layout.atMost
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.unit.dp
@Sampled
@Composable
fun DemoInlineDSL() {
ConstraintLayout {
val (text1, text2, text3) = createRefs()
Text(
"Text1",
Modifier.constrainAs(text1) {
start.linkTo(text2.end, margin = 20.dp)
}
)
Text(
"Text2",
Modifier.constrainAs(text2) {
centerTo(parent)
}
)
val barrier = createBottomBarrier(text1, text2)
Text(
"This is a very long text",
Modifier.constrainAs(text3) {
top.linkTo(barrier, margin = 20.dp)
centerHorizontallyTo(parent)
width = Dimension.preferredWrapContent.atMost(40.dp)
}
)
}
}
@Sampled
@Composable
fun DemoConstraintSet() {
ConstraintLayout(
ConstraintSet {
val text1 = createRefFor("text1")
val text2 = createRefFor("text2")
val text3 = createRefFor("text3")
constrain(text1) {
start.linkTo(text2.end, margin = 20.dp)
}
constrain(text2) {
centerTo(parent)
}
val barrier = createBottomBarrier(text1, text2)
constrain(text3) {
top.linkTo(barrier, margin = 20.dp)
centerHorizontallyTo(parent)
width = Dimension.preferredWrapContent.atMost(40.dp)
}
}
) {
Text("Text1", Modifier.layoutId("text1"))
Text("Text2", Modifier.layoutId("text2"))
Text("This is a very long text", Modifier.layoutId("text3"))
}
}
| 1
| null |
1
| 6
|
1c2fa962d0ebda96326ab69d4af15671989c9583
| 2,752
|
Jetpack-Compose-Playground
|
MIT License
|
android/src/main/java/com/reactnativekeyboardcontroller/listeners/FocusedInputObserver.kt
|
kirillzyusko
| 482,596,054
| false
|
{"TypeScript": 229506, "Kotlin": 94688, "Swift": 26093, "Objective-C++": 18452, "JavaScript": 11819, "Objective-C": 9581, "Ruby": 6670, "Java": 902, "Shell": 149, "C": 103}
|
package com.reactnativekeyboardcontroller.listeners
import android.text.TextWatcher
import android.view.View.OnLayoutChangeListener
import android.view.ViewTreeObserver.OnGlobalFocusChangeListener
import com.facebook.react.bridge.Arguments
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.UIManagerHelper
import com.facebook.react.views.textinput.ReactEditText
import com.facebook.react.views.view.ReactViewGroup
import com.reactnativekeyboardcontroller.events.FocusedInputLayoutChangedEvent
import com.reactnativekeyboardcontroller.events.FocusedInputLayoutChangedEventData
import com.reactnativekeyboardcontroller.events.FocusedInputTextChangedEvent
import com.reactnativekeyboardcontroller.extensions.addOnTextChangedListener
import com.reactnativekeyboardcontroller.extensions.dispatchEvent
import com.reactnativekeyboardcontroller.extensions.dp
import com.reactnativekeyboardcontroller.extensions.emitEvent
import com.reactnativekeyboardcontroller.extensions.parentScrollViewTarget
import com.reactnativekeyboardcontroller.extensions.rootView
import com.reactnativekeyboardcontroller.extensions.screenLocation
import com.reactnativekeyboardcontroller.traversal.FocusedInputHolder
import com.reactnativekeyboardcontroller.traversal.ViewHierarchyNavigator
val noFocusedInputEvent = FocusedInputLayoutChangedEventData(
x = 0.0,
y = 0.0,
width = 0.0,
height = 0.0,
absoluteX = 0.0,
absoluteY = 0.0,
target = -1,
parentScrollViewTarget = -1,
)
class FocusedInputObserver(val view: ReactViewGroup, private val context: ThemedReactContext?) {
// constructor variables
private val surfaceId = UIManagerHelper.getSurfaceId(view)
// state variables
private var lastFocusedInput: ReactEditText? = null
private var lastEventDispatched: FocusedInputLayoutChangedEventData = noFocusedInputEvent
private var textWatcher: TextWatcher? = null
// listeners
private val layoutListener =
OnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
this.syncUpLayout()
}
private val textListener: (String) -> Unit = { text ->
syncUpLayout()
context.dispatchEvent(
view.id,
FocusedInputTextChangedEvent(
surfaceId,
view.id,
text = text,
),
)
}
private val focusListener = OnGlobalFocusChangeListener { oldFocus, newFocus ->
// unfocused or focused was changed
if (newFocus == null || oldFocus != null) {
lastFocusedInput?.removeOnLayoutChangeListener(layoutListener)
lastFocusedInput?.removeTextChangedListener(textWatcher)
lastFocusedInput = null
}
if (newFocus is ReactEditText) {
lastFocusedInput = newFocus
newFocus.addOnLayoutChangeListener(layoutListener)
this.syncUpLayout()
textWatcher = newFocus.addOnTextChangedListener(textListener)
FocusedInputHolder.set(newFocus)
val allInputFields = ViewHierarchyNavigator.getAllInputFields(context?.rootView)
val currentIndex = allInputFields.indexOf(newFocus)
context.emitEvent(
"KeyboardController::focusDidSet",
Arguments.createMap().apply {
putInt("current", currentIndex)
putInt("count", allInputFields.size)
},
)
}
// unfocused
if (newFocus == null) {
dispatchEventToJS(noFocusedInputEvent)
}
}
init {
view.viewTreeObserver.addOnGlobalFocusChangeListener(focusListener)
}
fun syncUpLayout() {
val input = lastFocusedInput ?: return
val (x, y) = input.screenLocation
val event = FocusedInputLayoutChangedEventData(
x = input.x.dp,
y = input.y.dp,
width = input.width.toFloat().dp,
height = input.height.toFloat().dp,
absoluteX = x.toFloat().dp,
absoluteY = y.toFloat().dp,
target = input.id,
parentScrollViewTarget = input.parentScrollViewTarget,
)
dispatchEventToJS(event)
}
fun destroy() {
view.viewTreeObserver.removeOnGlobalFocusChangeListener(focusListener)
}
private fun dispatchEventToJS(event: FocusedInputLayoutChangedEventData) {
if (event != lastEventDispatched) {
lastEventDispatched = event
context.dispatchEvent(
view.id,
FocusedInputLayoutChangedEvent(
surfaceId,
view.id,
event = event,
),
)
}
}
}
| 20
|
TypeScript
|
46
| 1,213
|
b44d70b254e60b0e9f1a192815b46c0ed376d046
| 4,374
|
react-native-keyboard-controller
|
MIT License
|
app/src/main/java/com/bawp/freader/model/SaleInfo.kt
|
pdichone
| 424,016,512
| false
| null |
package com.bawp.freader.model
data class SaleInfo(
val buyLink: String,
val country: String,
val isEbook: Boolean,
val listPrice: ListPrice,
val offers: List<Offer>,
val retailPrice: RetailPriceX,
val saleability: String
)
| 1
| null |
27
| 40
|
65a270a07498f5286ff1341761ec0346ac4b5529
| 252
|
JetAReader
|
Apache License 2.0
|
basick/src/main/java/com/mozhimen/basick/elemk/android/os/cons/CEnvironment.kt
|
mozhimen
| 353,952,154
| false
| null |
package com.mozhimen.basick.elemk.android.os.cons
import android.os.Environment
import androidx.annotation.RequiresApi
/**
* @ClassName CEnvironment
* @Description TODO
* @Author Mozhimen / Kolin Zhao
* @Date 2023/9/8 18:33
* @Version 1.0
*/
object CEnvironment {
val DIRECTORY_MUSIC = Environment.DIRECTORY_MUSIC
val DIRECTORY_PODCASTS = Environment.DIRECTORY_PODCASTS
val DIRECTORY_RINGTONES = Environment.DIRECTORY_RINGTONES
val DIRECTORY_ALARMS = Environment.DIRECTORY_ALARMS
val DIRECTORY_NOTIFICATIONS = Environment.DIRECTORY_NOTIFICATIONS
val DIRECTORY_PICTURES = Environment.DIRECTORY_PICTURES
val DIRECTORY_MOVIES = Environment.DIRECTORY_MOVIES
val DIRECTORY_DOWNLOADS = Environment.DIRECTORY_DOWNLOADS
val DIRECTORY_DCIM = Environment.DIRECTORY_DCIM
val DIRECTORY_DOCUMENTS = Environment.DIRECTORY_DOCUMENTS
val MEDIA_MOUNTED = Environment.MEDIA_MOUNTED
@JvmStatic
@RequiresApi(CVersCode.V_29_10_Q)
fun getDirectoryScreenShots(): String =
Environment.DIRECTORY_SCREENSHOTS
@JvmStatic
@RequiresApi(CVersCode.V_29_10_Q)
fun getDirectoryAudioBooks(): String =
Environment.DIRECTORY_AUDIOBOOKS
@JvmStatic
@RequiresApi(CVersCode.V_31_12_S)
fun getDirectoryRecordings(): String =
Environment.DIRECTORY_RECORDINGS
}
| 1
| null |
7
| 118
|
0827d9f88c83e7be5302b58a33584c226bd12742
| 1,333
|
SwiftKit
|
Apache License 2.0
|
app/src/main/java/com/xatryx/aegisapp/application/AppCore.kt
|
xatryx
| 372,538,724
| false
| null |
package com.xatryx.aegisapp.application
import android.app.Application
import com.xatryx.aegisapp.repository.DiscordRepository
import com.xatryx.aegisapp.util.OFuelInstance
import com.xatryx.aegisapp.viewmodel.CommonDiscordViewModel
import org.kodein.di.*
import org.kodein.di.android.x.androidXModule
class AppCore : Application(), DIAware {
override val di: DI by DI.lazy {
import(androidXModule(this@AppCore))
bind { singleton { OFuelInstance.init() } }
bind { singleton { DiscordRepository(instance()) } }
bind { singleton { CommonDiscordViewModel(instance()) } }
}
}
| 0
|
Kotlin
|
0
| 0
|
894183f604dad4965d2263d0f78c412ae833af44
| 614
|
kotlin-android-AegisApp
|
MIT License
|
compose/foundation/foundation/src/test/kotlin/androidx/compose/foundation/text/selection/SelectionAdjustmentTest.kt
|
JetBrains
| 351,708,598
| 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
*
* 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 androidx.compose.foundation.text.selection
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.MultiParagraph
import androidx.compose.ui.text.TextLayoutInput
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.util.packInts
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
@SmallTest
@RunWith(JUnit4::class)
class SelectionAdjustmentTest {
@Test
fun adjustment_None_noAdjustment() {
val textLayoutResult = mockTextLayoutResult(text = "hello world")
val rawSelection = TextRange(0, 5)
val adjustedSelection = SelectionAdjustment.None.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = true,
previousSelectionRange = null
)
assertThat(adjustedSelection).isEqualTo(rawSelection)
}
@Test
fun adjustment_Character_notCollapsed_noAdjustment() {
val textLayoutResult = mockTextLayoutResult(text = "hello world")
val rawSelection = TextRange(0, 3)
val adjustedSelection = SelectionAdjustment.Character.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = true,
previousSelectionRange = null
)
assertThat(adjustedSelection).isEqualTo(rawSelection)
}
@Test
fun adjustment_Character_collapsedNotReversed_returnOneCharSelectionNotReversed() {
val textLayoutResult = mockTextLayoutResult(text = "hello")
// The end offset is moving towards the start offset, which makes the new raw text range
// collapsed.
// After the adjustment, at least one character should be selected.
// Since the previousTextRange is not reversed, the adjusted TextRange should
// also be not reversed.
// Based the above rules, adjusted text range should be [1, 2)
val rawSelection = TextRange(1, 1)
val previousSelection = TextRange(1, 2)
val isStartHandle = false
val adjustedSelection = SelectionAdjustment.Character.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedSelection).isEqualTo(TextRange(1, 2))
}
@Test
fun adjustment_Character_collapsedReversed_returnOneCharSelectionReversed() {
val textLayoutResult = mockTextLayoutResult(text = "hello")
val rawSelection = TextRange(2, 2)
val previousTextRange = TextRange(2, 1)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.Character.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = previousTextRange
)
assertThat(adjustedTextRange).isEqualTo(TextRange(2, 1))
}
@Test
fun adjustment_Character_collapsedNotReversed_returnOneUnicodeSelectionNotReversed() {
val textLayoutResult = mockTextLayoutResult(text = "hi\uD83D\uDE00")
// After the adjustment, the complete unicode should be selected instead of a single
// character that is only part of the unicode.
val rawSelection = TextRange(2, 2)
val previousSelection = TextRange(2, 4)
val isStartHandle = false
val adjustedSelection = SelectionAdjustment.Character.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedSelection).isEqualTo(TextRange(2, 4))
}
@Test
fun adjustment_Character_collapsedReversed_returnOneUnicodeSelectionReversed() {
val textLayoutResult = mockTextLayoutResult(text = "hi\uD83D\uDE00")
val rawSelection = TextRange(4, 4)
val previousTextRange = TextRange(4, 2)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.Character.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = previousTextRange
)
assertThat(adjustedTextRange).isEqualTo(TextRange(4, 2))
}
@Test
fun adjustment_Character_collapsedNotReversed_returnOneEmojiSelectionNotReversed() {
val textLayoutResult = mockTextLayoutResult(text = "#️⃣sharp")
// After the adjustment, the unicode sequence representing the keycap # emoji should be
// selected instead of a single character/unicode that is only part of the emoji.
val rawSelection = TextRange(0, 0)
val previousSelection = TextRange(0, 3)
val isStartHandle = false
val adjustedSelection = SelectionAdjustment.Character.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedSelection).isEqualTo(TextRange(0, 3))
}
@Test
fun adjustment_Character_collapsedReversed_returnOneEmojiSelectionReversed() {
val textLayoutResult = mockTextLayoutResult(text = "#️⃣sharp")
val rawSelection = TextRange(3, 3)
val previousTextRange = TextRange(3, 0)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.Character.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = previousTextRange
)
assertThat(adjustedTextRange).isEqualTo(TextRange(3, 0))
}
@Test
fun adjustment_Word_collapsed() {
val textLayoutResult = mockTextLayoutResult(
text = "<NAME>",
wordBoundaries = listOf(TextRange(0, 5), TextRange(6, 11))
)
val rawSelection = TextRange(1, 1)
val adjustedTextRange = SelectionAdjustment.Word.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = false,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 5))
}
@Test
fun adjustment_Word_collapsed_onStartBoundary() {
val textLayoutResult = mockTextLayoutResult(
text = "<NAME>",
wordBoundaries = listOf(TextRange(0, 5), TextRange(6, 11))
)
val rawSelection = TextRange(6, 6)
val adjustedTextRange = SelectionAdjustment.Word.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = false,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(6, 11))
}
@Test
fun adjustment_Word_collapsed_onEndBoundary() {
val textLayoutResult = mockTextLayoutResult(
text = "<NAME>",
wordBoundaries = listOf(TextRange(0, 5), TextRange(6, 11))
)
val rawSelection = TextRange(5, 5)
val adjustedTextRange = SelectionAdjustment.Word.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = false,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 5))
}
@Test
fun adjustment_Word_collapsed_zero() {
val textLayoutResult = mockTextLayoutResult(
text = "<NAME>",
wordBoundaries = listOf(TextRange(0, 5), TextRange(6, 11))
)
val rawSelection = TextRange(0, 0)
val adjustedTextRange = SelectionAdjustment.Word.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = false,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 5))
}
@Test
fun adjustment_Word_collapsed_lastIndex() {
val text = "<NAME>"
val textLayoutResult = mockTextLayoutResult(
text = text,
wordBoundaries = listOf(TextRange(0, 5), TextRange(6, 11))
)
val rawSelection = TextRange(text.lastIndex, text.lastIndex)
val adjustedTextRange = SelectionAdjustment.Word.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = false,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(6, 11))
}
@Test
fun adjustment_Word_collapsed_textLength() {
val text = "<NAME>"
val textLayoutResult = mockTextLayoutResult(
text = text,
wordBoundaries = listOf(TextRange(0, 5), TextRange(6, 11))
)
val rawSelection = TextRange(text.length, text.length)
val adjustedTextRange = SelectionAdjustment.Word.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = false,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(6, 11))
}
@Test
fun adjustment_Word_collapsed_emptyString() {
val textLayoutResult = mockTextLayoutResult(
text = "",
wordBoundaries = listOf(TextRange(0, 5), TextRange(6, 11))
)
val rawSelection = TextRange(0, 0)
val adjustedTextRange = SelectionAdjustment.Word.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = false,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 0))
}
@Test
fun adjustment_Word_notReversed() {
val textLayoutResult = mockTextLayoutResult(
text = "<NAME>",
wordBoundaries = listOf(TextRange(0, 5), TextRange(6, 11))
)
// The adjusted selection should cover the word "hello" and is not reversed.
val rawSelection = TextRange(1, 2)
val adjustedTextRange = SelectionAdjustment.Word.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = false,
previousSelectionRange = null
)
// The raw selection
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 5))
}
@Test
fun adjustment_Word_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "<NAME>",
wordBoundaries = listOf(TextRange(0, 5), TextRange(6, 11))
)
// The raw selection is reversed, so the adjusted selection should cover the word "hello"
// and is also reversed.
val rawSelection = TextRange(2, 1)
val adjustedTextRange = SelectionAdjustment.Word.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = false,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(5, 0))
}
@Test
fun adjustment_Word_crossWords() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
val rawSelection = TextRange(4, 7)
val adjustedTextRange = SelectionAdjustment.Word.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = false,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 11))
}
@Test
fun adjustment_Word_crossWords_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
val rawSelection = TextRange(7, 4)
val adjustedTextRange = SelectionAdjustment.Word.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = false,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(11, 0))
}
@Test
fun adjustment_Paragraph_collapsed() {
val textLayoutResult = mockTextLayoutResult(text = "hello world\nhello world")
val rawSelection = TextRange(14, 14)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.Paragraph.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(12, 23))
}
@Test
fun adjustment_Paragraph_collapsed_zero() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world\nhello world\nhello world\nhello world"
)
val rawSelection = TextRange(0, 0)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.Paragraph.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 11))
}
@Test
fun adjustment_Paragraph_collapsed_lastIndex() {
val text = "hello world\nhello world"
val textLayoutResult = mockTextLayoutResult(text = text)
val rawSelection = TextRange(text.lastIndex, text.lastIndex)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.Paragraph.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(12, 23))
}
@Test
fun adjustment_Paragraph_collapsed_textLength() {
val text = "hello world\nhello world"
val textLayoutResult = mockTextLayoutResult(text = text)
val rawSelection = TextRange(text.length, text.length)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.Paragraph.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(12, 23))
}
@Test
fun adjustment_Paragraph_emptyString() {
val textLayoutResult = mockTextLayoutResult(text = "")
val rawSelection = TextRange(0, 0)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.Paragraph.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 0))
}
@Test
fun adjustment_Paragraph_notReversed() {
val textLayoutResult = mockTextLayoutResult(text = "hello world\nhello world")
// The raw selection is not reversed, so the adjusted selection should cover the word
// "hello" and is not reversed either.
val rawSelection = TextRange(1, 2)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.Paragraph.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 11))
}
@Test
fun adjustment_Paragraph_reversed() {
val textLayoutResult = mockTextLayoutResult(text = "hello world\nhello world")
// The raw selection is reversed, so the adjusted selection should cover the word "hello"
// and is also reversed.
val rawSelection = TextRange(2, 1)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.Paragraph.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(11, 0))
}
@Test
fun adjustment_Paragraph_crossParagraph() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world\nhello world\nhello world\nhello world"
)
val rawSelection = TextRange(13, 26)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.Paragraph.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(12, 35))
}
@Test
fun adjustment_characterWithWordAccelerate_initialSelection() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world\nhello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
// The previous selection is null, it should use word based
// selection in this case.
val rawSelection = TextRange(3, 3)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = null
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 5))
}
@Test
fun adjustment_characterWithWordAccelerate_expandEndWithinWord() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world\nhello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
// The previous selection is [6, 7) and new selection expand the end to 8. This is
// considered in-word selection. And it will use character-wise selection
val rawSelection = TextRange(6, 8)
val previousSelection = TextRange(6, 7)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(6, 8))
}
@Test
fun adjustment_characterWithWordAccelerate_expandStartWithinWord_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world\nhello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
val rawSelection = TextRange(8, 6)
val previousSelection = TextRange(7, 6)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = -1,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(8, 6))
}
@Test
fun adjustment_characterWithWordAccelerate_expandStartWithinWord() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world\nhello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
// The previous selection is [7, 11) and new selection expand the start to 8. This is
// considered in-word selection. And it will use character-wise selection
val rawSelection = TextRange(8, 11)
val previousSelection = TextRange(7, 11)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(8, 11))
}
@Test
fun adjustment_characterWithWordAccelerate_expandEndWithinWord_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world\nhello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
val rawSelection = TextRange(11, 8)
val previousSelection = TextRange(11, 7)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(11, 8))
}
@Test
fun adjustment_characterWithWordAccelerate_expandEndOutOfWord() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
// The previous selection is [6, 11) and the new selection expand the end to 12.
// Because the previous selection end is at word boundary, it will use word selection mode.
// The end did exceed start of the next word(offset = 12), the adjusted
// selection end will be 17, which is the end of the next word.
val rawSelection = TextRange(6, 12)
val previousSelection = TextRange(6, 11)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(6, 17))
}
@Test
fun adjustment_characterWithWordAccelerate_expandStartOutOfWord_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
val rawSelection = TextRange(13, 6)
val previousSelection = TextRange(11, 6)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(17, 6))
}
@Test
fun adjustment_characterWithWordAccelerate_expandStartOutOfWord() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
// The previous selection is [6, 11) and the new selection expand the start to 5.
// Because the previous selection start is at word boundary, it will use word selection
// mode.
// The start did exceed the end of the previous word(offset = 5), the
// adjusted selection end will be 0, which is the start of the previous word.
val rawSelection = TextRange(5, 11)
val previousSelection = TextRange(6, 11)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 11))
}
@Test
fun adjustment_characterWithWordAccelerate_expandEndOutOfWord_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
// expands to first word boundary, so will select the first word.
val rawSelection = TextRange(11, 5)
val previousSelection = TextRange(11, 6)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(11, 0))
}
@Test
fun adjustment_characterWithWordAccelerate_expandEndOutOfWord_exceedThreshold() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
// The previous selection is [6, 11) and the new selection expand the end to 15.
// Because the previous selection end is at word boundary, it will use word based selection
// strategy.
// Since the 15 exceed the middle of the next word(offset: 14), the adjusted selection end
// will be 17.
val rawSelection = TextRange(6, 15)
val previousSelection = TextRange(6, 11)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(6, 17))
}
@Test
fun adjustment_characterWithWordAccelerate_expandStartOutOfWord_exceedThreshold_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
val rawSelection = TextRange(15, 6)
val previousSelection = TextRange(11, 6)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(17, 6))
}
@Test
fun adjustment_characterWithWordAccelerate_expandStartOutOfWord_exceedThreshold() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
// The previous selection is [6, 11) and the new selection expand the end to 2.
// Because the previous selection end is at word boundary, it will use word based selection
// strategy.
// Since the 2 exceed the middle of the previous word(offset: 2), the adjusted selection
// start will be 0.
val rawSelection = TextRange(2, 11)
val previousSelection = TextRange(6, 11)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 11))
}
@Test
fun adjustment_characterWithWordAccelerate_expandEndOutOfWord_exceedThreshold_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
val rawSelection = TextRange(11, 2)
val previousSelection = TextRange(11, 6)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(11, 0))
}
@Test
fun adjustment_characterWithWordAccelerate_expandEndToNextLine() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 6
)
// The text line break is as shown(underscore for space):
// hello_
// world_
// hello_
// world_
// The previous selection is [3, 4) and new selection expand the end to 8. Because offset
// 8 is at the next line, it will use word based selection strategy. And since 8 exceeds
// the middle of the next word(offset: 8), the end will be adjusted to word end: 11.
val rawSelection = TextRange(3, 8)
val previousSelection = TextRange(3, 4)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(3, 11))
}
@Test
fun adjustment_characterWithWordAccelerate_expandStartToNextLine_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 6
)
val rawSelection = TextRange(8, 3)
val previousSelection = TextRange(4, 3)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(11, 3))
}
@Test
fun adjustment_characterWithWordAccelerate_expandStartToNextLine() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 6
)
// The text line break is as shown(underscore for space):
// hello_
// world_
// hello_
// world_
// The previous selection is [6, 8) and new selection expand the start to 3. Because offset
// 3 is at the previous line, it will use word based selection strategy. And because 3
// does exceed the end of the previous word(offset: 5), the end will be adjusted to
// word start: 0.
val rawSelection = TextRange(3, 8)
val previousSelection = TextRange(7, 8)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 8))
}
@Test
fun adjustment_characterWithWordAccelerate_expandEndToNextLine_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 6
)
// expands into first word so will select first word
val rawSelection = TextRange(8, 3)
val previousSelection = TextRange(8, 7)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(8, 0))
}
@Test
fun adjustment_characterWithWordAccelerate_expandEndToNextLine_withinWord() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 8
)
// The text line break is as shown:
// hello wo
// rld hell
// o world
// The previous selection is [3, 7) and the end is expanded to 9, which is the next line.
// Because end offset is moving between lines, it will use word based selection. In this
// case the word "world" crosses 2 lines, so the candidate values for the adjusted end
// offset are 8(first character of the line) and 11(word end). Since 9 is closer to
// 11(word end), the end offset will be adjusted to 11.
val rawSelection = TextRange(3, 9)
val previousSelection = TextRange(3, 7)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(3, 11))
}
@Test
fun adjustment_characterWithWordAccelerate_expandStartToNextLine_withinWord_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 8
)
val rawSelection = TextRange(9, 3)
val previousSelection = TextRange(7, 3)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(11, 3))
}
@Test
fun adjustment_characterWithWordAccelerate_expandStartToNextLine_withinWord() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 8
)
// The text line break is as shown:
// hello wo
// rld hell
// o world
// The previous selection is [16, 17) and the start is expanded to 15, which is at the
// previous line.
// Because start offset is moving between lines, it will use word based selection. In this
// case the word "hello" crosses 2 lines. The candidate values for the adjusted start
// offset are 12(word start) and 16(last character of the line). Since we are expanding
// back, the end offset will be adjusted to the word start at 12.
val rawSelection = TextRange(15, 17)
val previousSelection = TextRange(16, 17)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(12, 17))
}
@Test
fun adjustment_characterWithWordAccelerate_expandEndToNextLine_withinWord_reverse() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 8
)
// crosses line, then uses word based selection which selects the rest of the word
val rawSelection = TextRange(17, 15)
val previousSelection = TextRange(17, 16)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(17, 12))
}
@Test
fun adjustment_characterWithWordAccelerate_shrinkEnd() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
// The previous selection is [0, 11) and new selection shrink the end to 8. In this case
// it will use character based selection strategy.
val rawSelection = TextRange(0, 8)
val previousSelection = TextRange(0, 11)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(0, 8))
}
@Test
fun adjustment_characterWithWordAccelerate_shrinkStart_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
val rawSelection = TextRange(8, 0)
val previousSelection = TextRange(11, 0)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(8, 0))
}
@Test
fun adjustment_characterWithWordAccelerate_shrinkStart() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
// The previous selection is [0, 8) and new selection shrink the start to 2. In this case
// it will use character based selection strategy.
val rawSelection = TextRange(2, 8)
val previousSelection = TextRange(0, 8)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(2, 8))
}
@Test
fun adjustment_characterWithWordAccelerate_shrinkEnd_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
)
)
val rawSelection = TextRange(8, 2)
val previousSelection = TextRange(8, 0)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(8, 2))
}
@Test
fun adjustment_characterWithWordAccelerate_shrinkEndToPrevLine() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 6
)
// The text line break is as shown(underscore for space):
// hello_
// world_
// hello_
// world_
// The previous selection is [2, 8) and new selection shrink the end to 4. Because offset
// 4 is at the previous line, it will use word based selection strategy. And the end will
// be snap to 5.
val rawSelection = TextRange(2, 4)
val previousSelection = TextRange(2, 8)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(2, 5))
}
@Test
fun adjustment_characterWithWordAccelerate_shrinkStartToPrevLine_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 6
)
val rawSelection = TextRange(4, 2)
val previousSelection = TextRange(8, 2)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(5, 2))
}
@Test
fun adjustment_characterWithWordAccelerate_shrinkStartToNextLine() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 6
)
// The text line break is as shown(underscore for space):
// hello_
// world_
// hello_
// world_
// The previous selection is [2, 8) and new selection shrink the end to 7. Because offset
// 7 is at the next line, it will use word based selection strategy. And the start will
// be snap to 6.
val rawSelection = TextRange(7, 8)
val previousSelection = TextRange(2, 8)
val isStartHandle = true
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.start,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(6, 8))
}
@Test
fun adjustment_characterWithWordAccelerate_shrinkEndToNextLine_reversed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 6
)
val rawSelection = TextRange(8, 7)
val previousSelection = TextRange(8, 2)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(8, 6))
}
@Test
fun adjustment_characterWithWordAccelerate_crossLineSelection_notCollapsed() {
val textLayoutResult = mockTextLayoutResult(
text = "hello world hello world",
wordBoundaries = listOf(
TextRange(0, 5),
TextRange(6, 11),
TextRange(12, 17),
TextRange(18, 23)
),
lineLength = 6
)
// The text line break is as shown(underscore for space):
// hello_
// world_
// hello_
// world_
// The previous selection is [6, 15) and new selection move the end to 7. Because offset
// 7 is at the previous line, it will use word based selection strategy.
// Normally, the new end will snap to the closest word boundary,
// which is 6(the word "world"'s boundaries are 6 and 11).
// However, in this specific case the selection start offset is already 6,
// adjusting the end to 6 will result in a collapsed selection [6, 6). So, it should
// move the end offset to the other word boundary which is 11 instead.
val rawSelection = TextRange(6, 7)
val previousSelection = TextRange(6, 15)
val isStartHandle = false
val adjustedTextRange = SelectionAdjustment.CharacterWithWordAccelerate.adjust(
textLayoutResult = textLayoutResult,
newRawSelectionRange = rawSelection,
previousHandleOffset = previousSelection.end,
isStartHandle = isStartHandle,
previousSelectionRange = previousSelection
)
assertThat(adjustedTextRange).isEqualTo(TextRange(6, 11))
}
private fun mockTextLayoutResult(
text: String,
wordBoundaries: List<TextRange> = listOf(),
lineLength: Int = text.length
): TextLayoutResult {
val multiParagraph = mock<MultiParagraph> {
on { getWordBoundary(any()) }.thenAnswer { invocation ->
val offset = invocation.arguments[0] as Int
val wordBoundary = wordBoundaries.find { offset in it.start..it.end }
// Workaround: Mockito doesn't work with inline class now. The packed Long is
// equal to TextRange(start, end).
packInts(wordBoundary!!.start, wordBoundary.end)
}
on { getLineForOffset(any()) }.thenAnswer { invocation ->
val offset = invocation.arguments[0] as Int
offset / lineLength
}
on { getLineStart(any()) }.thenAnswer { invocation ->
val offset = invocation.arguments[0] as Int
offset * lineLength
}
on { getLineEnd(any(), any()) }.thenAnswer { invocation ->
val offset = invocation.arguments[0] as Int
(offset + 1) * lineLength
}
}
return TextLayoutResult(
layoutInput = TextLayoutInput(
text = AnnotatedString(text = text),
style = TextStyle.Default,
placeholders = emptyList(),
maxLines = Int.MAX_VALUE,
softWrap = true,
overflow = TextOverflow.Clip,
density = Density(1f, 1f),
layoutDirection = LayoutDirection.Ltr,
fontFamilyResolver = mock(),
constraints = mock()
),
multiParagraph = multiParagraph,
size = IntSize.Zero
)
}
}
| 6
| null |
823
| 59
|
3fbd775007164912b34a1d59a923ad3387028b97
| 56,158
|
androidx
|
Apache License 2.0
|
app/src/main/java/com/example/jetmerandom/data/flight/CountryTo.kt
|
Juanmagc99
| 599,318,289
| false
| null |
package com.example.jetmerandom.data.flight
data class CountryTo(
val code: String,
val name: String
)
| 1
|
Kotlin
|
0
| 0
|
8ebb916eae5fa6cc2a20971d84b82c3c008d23aa
| 111
|
JetMeRandom
|
MIT License
|
modern-treasury-java-core/src/test/kotlin/com/moderntreasury/api/models/InvoiceListParamsTest.kt
|
Modern-Treasury
| 665,761,562
| false
|
{"Kotlin": 8813506, "Shell": 3657, "Java": 1587, "Dockerfile": 366}
|
// File generated from our OpenAPI spec by Stainless.
package com.moderntreasury.api.models
import com.moderntreasury.api.models.*
import java.time.LocalDate
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class InvoiceListParamsTest {
@Test
fun createInvoiceListParams() {
InvoiceListParams.builder()
.afterCursor("string")
.counterpartyId("string")
.dueDateEnd(LocalDate.parse("2019-12-27"))
.dueDateStart(LocalDate.parse("2019-12-27"))
.expectedPaymentId("string")
.metadata(InvoiceListParams.Metadata.builder().build())
.number("string")
.originatingAccountId("string")
.paymentOrderId("string")
.perPage(123L)
.status(InvoiceListParams.Status.DRAFT)
.build()
}
@Test
fun getQueryParams() {
val params =
InvoiceListParams.builder()
.afterCursor("string")
.counterpartyId("string")
.dueDateEnd(LocalDate.parse("2019-12-27"))
.dueDateStart(LocalDate.parse("2019-12-27"))
.expectedPaymentId("string")
.metadata(InvoiceListParams.Metadata.builder().build())
.number("string")
.originatingAccountId("string")
.paymentOrderId("string")
.perPage(123L)
.status(InvoiceListParams.Status.DRAFT)
.build()
val expected = mutableMapOf<String, List<String>>()
expected.put("after_cursor", listOf("string"))
expected.put("counterparty_id", listOf("string"))
expected.put("due_date_end", listOf("2019-12-27"))
expected.put("due_date_start", listOf("2019-12-27"))
expected.put("expected_payment_id", listOf("string"))
InvoiceListParams.Metadata.builder().build().forEachQueryParam { key, values ->
expected.put("metadata[$key]", values)
}
expected.put("number", listOf("string"))
expected.put("originating_account_id", listOf("string"))
expected.put("payment_order_id", listOf("string"))
expected.put("per_page", listOf("123"))
expected.put("status", listOf(InvoiceListParams.Status.DRAFT.toString()))
assertThat(params.getQueryParams()).isEqualTo(expected)
}
@Test
fun getQueryParamsWithoutOptionalFields() {
val params = InvoiceListParams.builder().build()
val expected = mutableMapOf<String, List<String>>()
assertThat(params.getQueryParams()).isEqualTo(expected)
}
}
| 1
|
Kotlin
|
1
| 1
|
d2b36198b9465c87dffdd553ef4bfac098a1d302
| 2,648
|
modern-treasury-java
|
MIT License
|
modules/graphql/sources-jvm/definitions/RaptorGraphArgumentDelegate.kt
|
fluidsonic
| 246,018,343
| false
| null |
package io.fluidsonic.raptor.graph
import io.fluidsonic.raptor.*
import io.fluidsonic.stdlib.*
import kotlin.properties.*
public interface RaptorGraphArgumentDelegate<out Type> : PropertyDelegateProvider<Any?, ReadOnlyProperty<Any?, Type>> {
@RaptorDsl
public fun <TransformedType> map(
// TODO Rename to transform?
transform: RaptorGraphInputScope.(value: Type) -> TransformedType,
): RaptorGraphArgumentDelegate<TransformedType>
}
@RaptorDsl
public fun <Type, TransformedType> RaptorGraphArgumentDelegate<Maybe<Type>>.mapValue(
transform: RaptorGraphInputScope.(value: Type) -> TransformedType,
): RaptorGraphArgumentDelegate<Maybe<TransformedType>> =
map { maybe -> maybe.map { transform(it) } }
@RaptorDsl
public fun <Type : Any, TransformedType> RaptorGraphArgumentDelegate<Maybe<Type?>>.mapValueIfNotNull(
transform: RaptorGraphInputScope.(value: Type) -> TransformedType?,
): RaptorGraphArgumentDelegate<Maybe<TransformedType?>> =
map { maybe -> maybe.mapIfNotNull { transform(it) } }
@RaptorDsl
public fun <Type> RaptorGraphArgumentDelegate<Type>.validate(
validate: RaptorGraphInputScope.(value: Type) -> Unit,
): RaptorGraphArgumentDelegate<Type> =
map { value -> value.also { validate(it) } }
@RaptorDsl
public fun <Type : Any, NullableType : Type?> RaptorGraphArgumentDelegate<NullableType>.validateIfNotNull(
validate: RaptorGraphInputScope.(value: Type) -> Unit,
): RaptorGraphArgumentDelegate<NullableType> =
validate { if (it != null) validate(it) }
@RaptorDsl
public fun <Type> RaptorGraphArgumentDelegate<Maybe<Type>>.validateValue(
validate: RaptorGraphInputScope.(value: Type) -> Unit,
): RaptorGraphArgumentDelegate<Maybe<Type>> =
validate { if (it.hasValue()) validate(it.get()) }
@RaptorDsl
public fun <Type : Any, NullableType : Type?> RaptorGraphArgumentDelegate<Maybe<NullableType>>.validateValueIfNotNull(
validate: RaptorGraphInputScope.(value: Type) -> Unit,
): RaptorGraphArgumentDelegate<Maybe<NullableType>> =
validateValue { if (it != null) validate(it) }
| 0
|
Kotlin
|
1
| 6
|
aa106d096b700d6eadbcf9ef5df8ec102f7a3fac
| 2,024
|
raptor
|
Apache License 2.0
|
src/main/java/com/sayzen/campfiresdk/screens/account/profile/CardInfo.kt
|
HorsePower68
| 230,018,763
| true
|
{"Kotlin": 1489208}
|
package com.sayzen.campfiresdk.screens.account.profile
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import com.dzen.campfire.api.API
import com.dzen.campfire.api.models.chat.ChatTag
import com.dzen.campfire.api.requests.accounts.RAccountsFollowsChange
import com.dzen.campfire.api.requests.accounts.RAccountsStatusSet
import com.sayzen.campfiresdk.R
import com.sayzen.campfiresdk.adapters.XAccount
import com.sayzen.campfiresdk.screens.chat.SChat
import com.sayzen.campfiresdk.screens.account.followers.SFollowers
import com.sayzen.campfiresdk.screens.account.followers.SFollows
import com.sayzen.campfiresdk.screens.account.karma.ScreenAccountKarma
import com.sayzen.campfiresdk.screens.punishments.SPunishments
import com.sayzen.campfiresdk.screens.account.rates.SRates
import com.sayzen.campfiresdk.screens.account.story.SStory
import com.sayzen.campfiresdk.controllers.ControllerApi
import com.sayzen.campfiresdk.controllers.ControllerLinks
import com.sayzen.campfiresdk.models.events.account.EventAccountBaned
import com.sayzen.campfiresdk.models.events.account.EventAccountNoteChanged
import com.sayzen.campfiresdk.models.events.account.EventAccountStatusChanged
import com.sayzen.campfiresdk.models.events.account.EventAccountsFollowsChange
import com.sayzen.campfiresdk.screens.account.black_list.SBlackList
import com.sayzen.campfiresdk.screens.account.fandoms.SAcounFandoms
import com.sayzen.campfiresdk.screens.achievements.SAchievements
import com.sayzen.campfiresdk.screens.fandoms.search.SFandomsModeration
import com.sayzen.campfiresdk.screens.account.stickers.SStickersPacks
import com.sayzen.campfiresdk.screens.activities.support.SDonate
import com.sayzen.campfiresdk.tools.ApiRequestsSupporter
import com.sup.dev.android.libs.screens.navigator.Navigator
import com.sup.dev.android.tools.ToolsResources
import com.sup.dev.android.tools.ToolsToast
import com.sup.dev.android.views.cards.Card
import com.sup.dev.android.views.views.ViewTextLinkable
import com.sup.dev.android.views.widgets.WidgetField
import com.sup.dev.java.libs.eventBus.EventBus
import com.sup.dev.java.tools.ToolsDate
import com.sup.dev.java.tools.ToolsText
class CardInfo(
private val xAccount: XAccount,
private val karma30: Long,
private val dateCreate: Long,
private val sex: Long,
private var banDate: Long,
private var isFollow: Boolean,
private var followsCount: Long,
private var followersCount: Long,
private var moderateFandomsCount: Long,
private var status: String,
private var ratesCount: Long,
private var bansCount: Long,
private var warnsCount: Long,
private var note: String,
private var fandomsCount: Long,
private var blackFandomsCount: Long,
private var blackAccountCount: Long,
private var stickersCount: Long,
private var sponsor: Boolean
) : Card(R.layout.screen_account_card_info) {
private val eventBus = EventBus
.subscribe(EventAccountsFollowsChange::class) { this.onAccountsFollowChange(it) }
.subscribe(EventAccountStatusChanged::class) { this.onEventAccountStatusChanged(it) }
.subscribe(EventAccountNoteChanged::class) { this.onEventAccountNoteChanged(it) }
.subscribe(EventAccountBaned::class) { this.onEventAccountBaned(it) }
override fun bindView(view: View) {
super.bindView(view)
val vLogin: TextView = view.findViewById(R.id.vLogin)
val vOnline: TextView = view.findViewById(R.id.vOnlineText)
val vBanText: TextView = view.findViewById(R.id.vBanText)
val vButtonsContainerDivider: View = view.findViewById(R.id.vButtonsContainerDivider)
val vButtonsContainer: ViewGroup = view.findViewById(R.id.vButtonsContainer)
val vFollow: Button = view.findViewById(R.id.vFollow)
val vMessage: Button = view.findViewById(R.id.vMessage)
val vFollowsCount: TextView = view.findViewById(R.id.vFollowsCount)
val vFollowsButton: View = view.findViewById(R.id.vFollowsButton)
val vKarmaText: TextView = view.findViewById(R.id.vKarmaText)
val vKarmaButton: View = view.findViewById(R.id.vKarmaButton)
val vAchiText: TextView = view.findViewById(R.id.vAchievementsText)
val vAchiButton: View = view.findViewById(R.id.vAchievementsButton)
val vFollowersButton: View = view.findViewById(R.id.vFollowersButton)
val vFollowersCount: TextView = view.findViewById(R.id.vFollowersCount)
val vModeratorButton: View = view.findViewById(R.id.vModeratorButton)
val vModeratorText: TextView = view.findViewById(R.id.vModeratorText)
val vModeratorCount: TextView = view.findViewById(R.id.vModeratorCount)
val vTimeText: TextView = view.findViewById(R.id.vTimeText)
val vStatus: ViewTextLinkable = view.findViewById(R.id.vStatus)
val vStatusContainer: View = view.findViewById(R.id.vStatusContainer)
val vRatesButton: View = view.findViewById(R.id.vRatesButton)
val vRatesCount: TextView = view.findViewById(R.id.vRatesCount)
val vPunishmentsButton: View = view.findViewById(R.id.vPunishmentsButton)
val vPunishmentsCount: TextView = view.findViewById(R.id.vPunishmentsCount)
val vStory: View = view.findViewById(R.id.vStory)
val vNote: ViewTextLinkable = view.findViewById(R.id.vNote)
val vBlackList: View = view.findViewById(R.id.vBlackList)
val vBlackListCount: TextView = view.findViewById(R.id.vBlackListCount)
val vStickers: View = view.findViewById(R.id.vStickers)
val vStickersCount: TextView = view.findViewById(R.id.vStickersCount)
val vFandoms: View = view.findViewById(R.id.vFandoms)
val vFandomsCount: TextView = view.findViewById(R.id.vFandomsCount)
val vSponsor: View = view.findViewById(R.id.vSponsor)
vSponsor.setOnClickListener { SDonate.instance(Navigator.TO) }
vSponsor.visibility = if(sponsor) VISIBLE else GONE
if (xAccount.isBot()) {
vOnline.text = ToolsResources.s(R.string.app_bot)
vOnline.setTextColor(ToolsResources.getColor(R.color.green_700))
} else if (!xAccount.isOnline()) {
vOnline.text = ToolsResources.sCap(R.string.app_was_online, ToolsResources.sex(sex, R.string.he_was, R.string.she_was), ToolsDate.dateToString(xAccount.getLastOnlineTime()))
vOnline.setTextColor(ToolsResources.getColor(R.color.grey_500))
} else {
vOnline.text = ToolsResources.s(R.string.app_online)
vOnline.setTextColor(ToolsResources.getColor(R.color.green_700))
}
if (banDate > ControllerApi.currentTime()) {
vBanText.text = ToolsResources.s(R.string.error_account_baned, ToolsDate.dateToString(banDate))
vBanText.visibility = VISIBLE
} else {
vBanText.visibility = GONE
}
vNote.text = note
vNote.visibility = if (note.isEmpty()) GONE else VISIBLE
vButtonsContainer.visibility = if (ControllerApi.isCurrentAccount(xAccount.accountId)) View.GONE else View.VISIBLE
vButtonsContainerDivider.visibility = if (ControllerApi.isCurrentAccount(xAccount.accountId)) View.GONE else View.VISIBLE
vFollowsCount.text = followsCount.toString()
vRatesCount.text = ratesCount.toString()
vPunishmentsCount.text = bansCount.toString() + " / " + warnsCount
vLogin.text = xAccount.name
vKarmaText.text = (karma30 / 100).toString()
vFollow.setText(if (isFollow) R.string.app_unfollow else R.string.app_follow)
vKarmaText.setTextColor(if (karma30 == 0L) ToolsResources.getColor(R.color.grey_600) else if (karma30 > 0) ToolsResources.getColor(R.color.green_700) else ToolsResources.getColor(R.color.red_700))
vAchiText.text = ToolsText.numToStringRound(xAccount.lvl / 100.0, 2)
vAchiText.setTextColor(ToolsResources.getColor(R.color.green_700))
vFollowersCount.text = "" + followersCount
vTimeText.text = "${((ControllerApi.currentTime() - dateCreate) / (1000L * 60 * 60 * 24)) + 1} ${ToolsResources.s(R.string.app_d)}"
vFandomsCount.text = "$fandomsCount"
vStickersCount.text = "$stickersCount"
vBlackListCount.text = "$blackAccountCount/$blackFandomsCount"
vStatusContainer.visibility = VISIBLE
if (status.isEmpty()) {
if (xAccount.isCurrentAccount()) vStatus.text = ToolsResources.s(R.string.profile_tap_to_change_status)
else vStatusContainer.visibility = GONE
vStatus.setTextColor(ToolsResources.getColor(R.color.grey_500))
} else {
vStatus.text = status
vStatus.setTextColor(ToolsResources.getColorAttr(R.attr.revers_color))
}
if (xAccount.isCurrentAccount()) {
vStatusContainer.setOnClickListener { changeStatus() }
} else {
vStatusContainer.setOnClickListener(null)
}
when {
xAccount.isBot() -> {
vModeratorCount.text = "-"
vModeratorText.setTextColor(ToolsResources.getColorAttr(R.attr.revers_color))
vModeratorText.setText(R.string.app_bot)
vModeratorButton.setOnClickListener(null)
}
xAccount.isProtoadmin() -> {
vModeratorCount.text = "∞"
vModeratorText.setTextColor(ToolsResources.getColor(R.color.orange_a_700))
vModeratorText.setText(R.string.app_protoadmin)
vModeratorButton.setOnClickListener(null)
}
xAccount.isAdmin() -> {
vModeratorCount.text = "∞"
vModeratorText.setTextColor(ToolsResources.getColor(R.color.red_700))
vModeratorText.setText(R.string.app_admin)
vModeratorButton.setOnClickListener(null)
}
xAccount.isModerator() -> {
vModeratorCount.text = "" + moderateFandomsCount
vModeratorText.setTextColor(ToolsResources.getColor(R.color.blue_700))
vModeratorText.setText(R.string.app_moderator)
vModeratorButton.setOnClickListener { SFandomsModeration.instance(xAccount.accountId, Navigator.TO) }
}
else -> {
vModeratorCount.text = "-"
vModeratorText.setTextColor(ToolsResources.getColor(R.color.green_700))
vModeratorText.setText(R.string.app_user)
vModeratorButton.setOnClickListener(null)
}
}
ControllerLinks.makeLinkable(vStatus)
ControllerLinks.makeLinkable(vNote)
vFollow.setOnClickListener { toggleFollows() }
vMessage.setOnClickListener { SChat.instance(ChatTag(API.CHAT_TYPE_PRIVATE, xAccount.accountId, ControllerApi.account.id), 0, true, Navigator.TO) }
vFollowsButton.setOnClickListener { Navigator.to(SFollows(xAccount.accountId, xAccount.name)) }
vFollowersButton.setOnClickListener { Navigator.to(SFollowers(xAccount.accountId, xAccount.name)) }
vRatesButton.setOnClickListener { Navigator.to(SRates(xAccount.accountId, xAccount.name)) }
vPunishmentsButton.setOnClickListener { Navigator.to(SPunishments(xAccount.accountId, xAccount.name)) }
vStory.setOnClickListener { SStory.instance(xAccount.accountId, xAccount.name, Navigator.TO) }
vAchiButton.setOnClickListener { SAchievements.instance(xAccount.accountId, xAccount.name, 0, false, Navigator.TO) }
vKarmaButton.setOnClickListener { Navigator.to(ScreenAccountKarma(xAccount.accountId, xAccount.name)) }
vStickers.setOnClickListener { Navigator.to(SStickersPacks(xAccount.accountId)) }
vBlackList.setOnClickListener { Navigator.to(SBlackList(xAccount.accountId, xAccount.name)) }
vFandoms.setOnClickListener { Navigator.to(SAcounFandoms(xAccount.accountId)) }
}
//
// EventBus
//
private fun onAccountsFollowChange(e: EventAccountsFollowsChange) {
if (xAccount.accountId == e.accountId) {
isFollow = e.isFollow
update()
}
if (ControllerApi.isCurrentAccount(xAccount.accountId)) {
followsCount += (if (e.isFollow) 1 else -1).toLong()
update()
}
}
private fun onEventAccountStatusChanged(e: EventAccountStatusChanged) {
if (e.accountId == xAccount.accountId) {
status = e.status
update()
}
}
private fun onEventAccountNoteChanged(e: EventAccountNoteChanged) {
if (e.accountId == xAccount.accountId) {
note = e.note
update()
}
}
private fun onEventAccountBaned(e: EventAccountBaned) {
if (e.accountId == xAccount.accountId) {
banDate = e.date
update()
}
}
//
// Api
//
private fun changeStatus() {
if (!xAccount.can(API.LVL_CAN_CHANGE_STATUS)) {
ToolsToast.show(R.string.error_low_lvl)
return
}
WidgetField()
.setHint(R.string.app_status)
.setAutoHideOnEnter(false)
.setLinesCount(1)
.setMax(API.ACCOUNT_STATUS_MAX_L)
.setText(status)
.setOnCancel(R.string.app_cancel)
.setOnEnter(R.string.app_change) { w, status ->
ApiRequestsSupporter.executeEnabled(w, RAccountsStatusSet(status.trim())) {
ToolsToast.show(R.string.app_done)
EventBus.post(EventAccountStatusChanged(xAccount.accountId, status.trim()))
}
}
.asSheetShow()
}
private fun toggleFollows() {
if (!isFollow)
ApiRequestsSupporter.executeProgressDialog(RAccountsFollowsChange(xAccount.accountId, !isFollow)) { _ -> eventBus.post(EventAccountsFollowsChange(xAccount.accountId, !isFollow)) }
else
ApiRequestsSupporter.executeEnabledConfirm(R.string.profile_follows_remove_confirm, R.string.app_unfollow, RAccountsFollowsChange(xAccount.accountId, !isFollow)) { eventBus.post(EventAccountsFollowsChange(xAccount.accountId, !isFollow)) }
}
}
| 0
| null |
1
| 0
|
33c46da49d3758a1a006ac660dc823d35c66baea
| 14,443
|
CampfireSDK
|
Apache License 2.0
|
src/main/java/com/sayzen/campfiresdk/screens/account/profile/CardInfo.kt
|
HorsePower68
| 230,018,763
| true
|
{"Kotlin": 1489208}
|
package com.sayzen.campfiresdk.screens.account.profile
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import com.dzen.campfire.api.API
import com.dzen.campfire.api.models.chat.ChatTag
import com.dzen.campfire.api.requests.accounts.RAccountsFollowsChange
import com.dzen.campfire.api.requests.accounts.RAccountsStatusSet
import com.sayzen.campfiresdk.R
import com.sayzen.campfiresdk.adapters.XAccount
import com.sayzen.campfiresdk.screens.chat.SChat
import com.sayzen.campfiresdk.screens.account.followers.SFollowers
import com.sayzen.campfiresdk.screens.account.followers.SFollows
import com.sayzen.campfiresdk.screens.account.karma.ScreenAccountKarma
import com.sayzen.campfiresdk.screens.punishments.SPunishments
import com.sayzen.campfiresdk.screens.account.rates.SRates
import com.sayzen.campfiresdk.screens.account.story.SStory
import com.sayzen.campfiresdk.controllers.ControllerApi
import com.sayzen.campfiresdk.controllers.ControllerLinks
import com.sayzen.campfiresdk.models.events.account.EventAccountBaned
import com.sayzen.campfiresdk.models.events.account.EventAccountNoteChanged
import com.sayzen.campfiresdk.models.events.account.EventAccountStatusChanged
import com.sayzen.campfiresdk.models.events.account.EventAccountsFollowsChange
import com.sayzen.campfiresdk.screens.account.black_list.SBlackList
import com.sayzen.campfiresdk.screens.account.fandoms.SAcounFandoms
import com.sayzen.campfiresdk.screens.achievements.SAchievements
import com.sayzen.campfiresdk.screens.fandoms.search.SFandomsModeration
import com.sayzen.campfiresdk.screens.account.stickers.SStickersPacks
import com.sayzen.campfiresdk.screens.activities.support.SDonate
import com.sayzen.campfiresdk.tools.ApiRequestsSupporter
import com.sup.dev.android.libs.screens.navigator.Navigator
import com.sup.dev.android.tools.ToolsResources
import com.sup.dev.android.tools.ToolsToast
import com.sup.dev.android.views.cards.Card
import com.sup.dev.android.views.views.ViewTextLinkable
import com.sup.dev.android.views.widgets.WidgetField
import com.sup.dev.java.libs.eventBus.EventBus
import com.sup.dev.java.tools.ToolsDate
import com.sup.dev.java.tools.ToolsText
class CardInfo(
private val xAccount: XAccount,
private val karma30: Long,
private val dateCreate: Long,
private val sex: Long,
private var banDate: Long,
private var isFollow: Boolean,
private var followsCount: Long,
private var followersCount: Long,
private var moderateFandomsCount: Long,
private var status: String,
private var ratesCount: Long,
private var bansCount: Long,
private var warnsCount: Long,
private var note: String,
private var fandomsCount: Long,
private var blackFandomsCount: Long,
private var blackAccountCount: Long,
private var stickersCount: Long,
private var sponsor: Boolean
) : Card(R.layout.screen_account_card_info) {
private val eventBus = EventBus
.subscribe(EventAccountsFollowsChange::class) { this.onAccountsFollowChange(it) }
.subscribe(EventAccountStatusChanged::class) { this.onEventAccountStatusChanged(it) }
.subscribe(EventAccountNoteChanged::class) { this.onEventAccountNoteChanged(it) }
.subscribe(EventAccountBaned::class) { this.onEventAccountBaned(it) }
override fun bindView(view: View) {
super.bindView(view)
val vLogin: TextView = view.findViewById(R.id.vLogin)
val vOnline: TextView = view.findViewById(R.id.vOnlineText)
val vBanText: TextView = view.findViewById(R.id.vBanText)
val vButtonsContainerDivider: View = view.findViewById(R.id.vButtonsContainerDivider)
val vButtonsContainer: ViewGroup = view.findViewById(R.id.vButtonsContainer)
val vFollow: Button = view.findViewById(R.id.vFollow)
val vMessage: Button = view.findViewById(R.id.vMessage)
val vFollowsCount: TextView = view.findViewById(R.id.vFollowsCount)
val vFollowsButton: View = view.findViewById(R.id.vFollowsButton)
val vKarmaText: TextView = view.findViewById(R.id.vKarmaText)
val vKarmaButton: View = view.findViewById(R.id.vKarmaButton)
val vAchiText: TextView = view.findViewById(R.id.vAchievementsText)
val vAchiButton: View = view.findViewById(R.id.vAchievementsButton)
val vFollowersButton: View = view.findViewById(R.id.vFollowersButton)
val vFollowersCount: TextView = view.findViewById(R.id.vFollowersCount)
val vModeratorButton: View = view.findViewById(R.id.vModeratorButton)
val vModeratorText: TextView = view.findViewById(R.id.vModeratorText)
val vModeratorCount: TextView = view.findViewById(R.id.vModeratorCount)
val vTimeText: TextView = view.findViewById(R.id.vTimeText)
val vStatus: ViewTextLinkable = view.findViewById(R.id.vStatus)
val vStatusContainer: View = view.findViewById(R.id.vStatusContainer)
val vRatesButton: View = view.findViewById(R.id.vRatesButton)
val vRatesCount: TextView = view.findViewById(R.id.vRatesCount)
val vPunishmentsButton: View = view.findViewById(R.id.vPunishmentsButton)
val vPunishmentsCount: TextView = view.findViewById(R.id.vPunishmentsCount)
val vStory: View = view.findViewById(R.id.vStory)
val vNote: ViewTextLinkable = view.findViewById(R.id.vNote)
val vBlackList: View = view.findViewById(R.id.vBlackList)
val vBlackListCount: TextView = view.findViewById(R.id.vBlackListCount)
val vStickers: View = view.findViewById(R.id.vStickers)
val vStickersCount: TextView = view.findViewById(R.id.vStickersCount)
val vFandoms: View = view.findViewById(R.id.vFandoms)
val vFandomsCount: TextView = view.findViewById(R.id.vFandomsCount)
val vSponsor: View = view.findViewById(R.id.vSponsor)
vSponsor.setOnClickListener { SDonate.instance(Navigator.TO) }
vSponsor.visibility = if(sponsor) VISIBLE else GONE
if (xAccount.isBot()) {
vOnline.text = ToolsResources.s(R.string.app_bot)
vOnline.setTextColor(ToolsResources.getColor(R.color.green_700))
} else if (!xAccount.isOnline()) {
vOnline.text = ToolsResources.sCap(R.string.app_was_online, ToolsResources.sex(sex, R.string.he_was, R.string.she_was), ToolsDate.dateToString(xAccount.getLastOnlineTime()))
vOnline.setTextColor(ToolsResources.getColor(R.color.grey_500))
} else {
vOnline.text = ToolsResources.s(R.string.app_online)
vOnline.setTextColor(ToolsResources.getColor(R.color.green_700))
}
if (banDate > ControllerApi.currentTime()) {
vBanText.text = ToolsResources.s(R.string.error_account_baned, ToolsDate.dateToString(banDate))
vBanText.visibility = VISIBLE
} else {
vBanText.visibility = GONE
}
vNote.text = note
vNote.visibility = if (note.isEmpty()) GONE else VISIBLE
vButtonsContainer.visibility = if (ControllerApi.isCurrentAccount(xAccount.accountId)) View.GONE else View.VISIBLE
vButtonsContainerDivider.visibility = if (ControllerApi.isCurrentAccount(xAccount.accountId)) View.GONE else View.VISIBLE
vFollowsCount.text = followsCount.toString()
vRatesCount.text = ratesCount.toString()
vPunishmentsCount.text = bansCount.toString() + " / " + warnsCount
vLogin.text = xAccount.name
vKarmaText.text = (karma30 / 100).toString()
vFollow.setText(if (isFollow) R.string.app_unfollow else R.string.app_follow)
vKarmaText.setTextColor(if (karma30 == 0L) ToolsResources.getColor(R.color.grey_600) else if (karma30 > 0) ToolsResources.getColor(R.color.green_700) else ToolsResources.getColor(R.color.red_700))
vAchiText.text = ToolsText.numToStringRound(xAccount.lvl / 100.0, 2)
vAchiText.setTextColor(ToolsResources.getColor(R.color.green_700))
vFollowersCount.text = "" + followersCount
vTimeText.text = "${((ControllerApi.currentTime() - dateCreate) / (1000L * 60 * 60 * 24)) + 1} ${ToolsResources.s(R.string.app_d)}"
vFandomsCount.text = "$fandomsCount"
vStickersCount.text = "$stickersCount"
vBlackListCount.text = "$blackAccountCount/$blackFandomsCount"
vStatusContainer.visibility = VISIBLE
if (status.isEmpty()) {
if (xAccount.isCurrentAccount()) vStatus.text = ToolsResources.s(R.string.profile_tap_to_change_status)
else vStatusContainer.visibility = GONE
vStatus.setTextColor(ToolsResources.getColor(R.color.grey_500))
} else {
vStatus.text = status
vStatus.setTextColor(ToolsResources.getColorAttr(R.attr.revers_color))
}
if (xAccount.isCurrentAccount()) {
vStatusContainer.setOnClickListener { changeStatus() }
} else {
vStatusContainer.setOnClickListener(null)
}
when {
xAccount.isBot() -> {
vModeratorCount.text = "-"
vModeratorText.setTextColor(ToolsResources.getColorAttr(R.attr.revers_color))
vModeratorText.setText(R.string.app_bot)
vModeratorButton.setOnClickListener(null)
}
xAccount.isProtoadmin() -> {
vModeratorCount.text = "∞"
vModeratorText.setTextColor(ToolsResources.getColor(R.color.orange_a_700))
vModeratorText.setText(R.string.app_protoadmin)
vModeratorButton.setOnClickListener(null)
}
xAccount.isAdmin() -> {
vModeratorCount.text = "∞"
vModeratorText.setTextColor(ToolsResources.getColor(R.color.red_700))
vModeratorText.setText(R.string.app_admin)
vModeratorButton.setOnClickListener(null)
}
xAccount.isModerator() -> {
vModeratorCount.text = "" + moderateFandomsCount
vModeratorText.setTextColor(ToolsResources.getColor(R.color.blue_700))
vModeratorText.setText(R.string.app_moderator)
vModeratorButton.setOnClickListener { SFandomsModeration.instance(xAccount.accountId, Navigator.TO) }
}
else -> {
vModeratorCount.text = "-"
vModeratorText.setTextColor(ToolsResources.getColor(R.color.green_700))
vModeratorText.setText(R.string.app_user)
vModeratorButton.setOnClickListener(null)
}
}
ControllerLinks.makeLinkable(vStatus)
ControllerLinks.makeLinkable(vNote)
vFollow.setOnClickListener { toggleFollows() }
vMessage.setOnClickListener { SChat.instance(ChatTag(API.CHAT_TYPE_PRIVATE, xAccount.accountId, ControllerApi.account.id), 0, true, Navigator.TO) }
vFollowsButton.setOnClickListener { Navigator.to(SFollows(xAccount.accountId, xAccount.name)) }
vFollowersButton.setOnClickListener { Navigator.to(SFollowers(xAccount.accountId, xAccount.name)) }
vRatesButton.setOnClickListener { Navigator.to(SRates(xAccount.accountId, xAccount.name)) }
vPunishmentsButton.setOnClickListener { Navigator.to(SPunishments(xAccount.accountId, xAccount.name)) }
vStory.setOnClickListener { SStory.instance(xAccount.accountId, xAccount.name, Navigator.TO) }
vAchiButton.setOnClickListener { SAchievements.instance(xAccount.accountId, xAccount.name, 0, false, Navigator.TO) }
vKarmaButton.setOnClickListener { Navigator.to(ScreenAccountKarma(xAccount.accountId, xAccount.name)) }
vStickers.setOnClickListener { Navigator.to(SStickersPacks(xAccount.accountId)) }
vBlackList.setOnClickListener { Navigator.to(SBlackList(xAccount.accountId, xAccount.name)) }
vFandoms.setOnClickListener { Navigator.to(SAcounFandoms(xAccount.accountId)) }
}
//
// EventBus
//
private fun onAccountsFollowChange(e: EventAccountsFollowsChange) {
if (xAccount.accountId == e.accountId) {
isFollow = e.isFollow
update()
}
if (ControllerApi.isCurrentAccount(xAccount.accountId)) {
followsCount += (if (e.isFollow) 1 else -1).toLong()
update()
}
}
private fun onEventAccountStatusChanged(e: EventAccountStatusChanged) {
if (e.accountId == xAccount.accountId) {
status = e.status
update()
}
}
private fun onEventAccountNoteChanged(e: EventAccountNoteChanged) {
if (e.accountId == xAccount.accountId) {
note = e.note
update()
}
}
private fun onEventAccountBaned(e: EventAccountBaned) {
if (e.accountId == xAccount.accountId) {
banDate = e.date
update()
}
}
//
// Api
//
private fun changeStatus() {
if (!xAccount.can(API.LVL_CAN_CHANGE_STATUS)) {
ToolsToast.show(R.string.error_low_lvl)
return
}
WidgetField()
.setHint(R.string.app_status)
.setAutoHideOnEnter(false)
.setLinesCount(1)
.setMax(API.ACCOUNT_STATUS_MAX_L)
.setText(status)
.setOnCancel(R.string.app_cancel)
.setOnEnter(R.string.app_change) { w, status ->
ApiRequestsSupporter.executeEnabled(w, RAccountsStatusSet(status.trim())) {
ToolsToast.show(R.string.app_done)
EventBus.post(EventAccountStatusChanged(xAccount.accountId, status.trim()))
}
}
.asSheetShow()
}
private fun toggleFollows() {
if (!isFollow)
ApiRequestsSupporter.executeProgressDialog(RAccountsFollowsChange(xAccount.accountId, !isFollow)) { _ -> eventBus.post(EventAccountsFollowsChange(xAccount.accountId, !isFollow)) }
else
ApiRequestsSupporter.executeEnabledConfirm(R.string.profile_follows_remove_confirm, R.string.app_unfollow, RAccountsFollowsChange(xAccount.accountId, !isFollow)) { eventBus.post(EventAccountsFollowsChange(xAccount.accountId, !isFollow)) }
}
}
| 0
| null |
1
| 0
|
33c46da49d3758a1a006ac660dc823d35c66baea
| 14,443
|
CampfireSDK
|
Apache License 2.0
|
roboquant-charts/src/test/kotlin/org/roboquant/charts/ChartTest.kt
|
neurallayer
| 406,929,056
| false
| null |
/*
* Copyright 2020-2024 Neural Layer
*
* 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 org.roboquant.charts
import org.icepear.echarts.Option
import org.junit.jupiter.api.assertDoesNotThrow
import org.roboquant.feeds.random.RandomWalkFeed
import kotlin.test.Test
import kotlin.test.assertContains
import kotlin.test.assertEquals
import kotlin.test.assertTrue
internal class ChartTest {
private class MyChart : Chart() {
init {
javascriptFunction("return p;")
}
fun reduced(size: Int): List<Int> {
val data = (1..size).toList()
return reduce(data).toList()
}
override fun getOption(): Option {
return Option()
}
}
@Test
fun test() {
val f = RandomWalkFeed.lastYears(1, 1)
val asset = f.assets.first()
val chart = PriceBarChart(f, asset)
val html = chart.renderJson()
assertTrue(html.isNotBlank())
assertEquals(700, chart.height)
assertContains(html, asset.symbol)
val chart2 = PriceBarChart(f, asset.symbol)
assertEquals(html, chart2.renderJson())
}
@Test
fun testReduced() {
val chart = MyChart()
Chart.maxSamples = 10
assertEquals(10, chart.reduced(100).size)
Chart.maxSamples = Int.MAX_VALUE
assertEquals(100, chart.reduced(100).size)
}
@Test
fun testCodeGeneration() {
val chart = MyChart()
chart.height = 123
assertDoesNotThrow {
chart.renderJson()
}
}
}
| 9
| null |
42
| 332
|
49a6f0af1a224e4f03c99b03a9894f5e2acef15d
| 2,096
|
roboquant
|
Apache License 2.0
|
samples/starter-mobile-app/src/main/kotlin/researchstack/presentation/component/Waveform.kt
|
S-ResearchStack
| 520,365,275
| false
| null |
package healthstack.kit.ui
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import healthstack.kit.theme.AppTheme
@Composable
fun Waveform(
modifier: Modifier = Modifier,
spikeColor: Color = AppTheme.colors.primary,
spikeWidth: Dp = 1.dp,
spikePadding: Dp = 1.dp,
axisColor: Color = AppTheme.colors.primaryVariant,
axisHeight: Dp = 2.dp,
amplitudes: MutableList<Int> = mutableListOf(),
move: Boolean = false,
) {
val perSpike = remember(spikeWidth, spikePadding) { spikeWidth + spikePadding }
Canvas(
modifier = Modifier
.fillMaxWidth()
.height(160.dp)
.then(modifier),
) {
drawRect(
color = axisColor,
topLeft = Offset(
x = 0F,
y = size.height / 2 - axisHeight.toPx() / 2
),
size = Size(
width = size.width,
height = axisHeight.toPx()
)
)
val maxSpikes = (size.width / perSpike.toPx()).toInt()
val toDraw = amplitudes.takeLast(maxSpikes)
val start = if (move) size.width - ((toDraw.size) * perSpike.toPx()) else
size.width - ((toDraw.size) * perSpike.toPx()) + spikePadding.toPx()
toDraw.forEachIndexed { index, amplitude ->
val normalizedAmp = (amplitude / 70)
.coerceAtMost(size.height.toInt())
.coerceAtLeast(axisHeight.toPx().toInt())
.toFloat()
drawRect(
color = spikeColor,
topLeft = Offset(
x = start + index * perSpike.toPx(),
y = size.height / 2 - normalizedAmp / 2
),
size = Size(
width = spikeWidth.toPx(),
height = normalizedAmp
),
alpha = 0.6F,
)
}
}
}
| 5
| null |
20
| 26
|
58b4b9b64623a7d2a0865307d490a59a7538d7cd
| 2,326
|
app-sdk
|
Apache License 2.0
|
common-util/src/main/kotlin/com/google/devtools/ksp/common/impl/KSNameImpl.kt
|
google
| 297,744,725
| false
| null |
package com.google.devtools.ksp.common.impl
import com.google.devtools.ksp.common.KSObjectCache
import com.google.devtools.ksp.symbol.KSName
class KSNameImpl private constructor(val name: String) : KSName {
companion object : KSObjectCache<String, KSNameImpl>() {
fun getCached(name: String) = cache.getOrPut(name) { KSNameImpl(name) }
}
override fun asString(): String {
return name
}
override fun getQualifier(): String {
return name.split(".").dropLast(1).joinToString(".")
}
override fun getShortName(): String {
return name.split(".").last()
}
}
| 370
| null |
268
| 2,854
|
a977fb96b05ec9c3e15b5a0cf32e8e7ea73ab3b3
| 620
|
ksp
|
Apache License 2.0
|
tabler-icons/src/commonMain/kotlin/compose/icons/tablericons/Rectangle.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36719092}
|
package compose.icons.tablericons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.TablerIcons
public val TablerIcons.AspectRatio: ImageVector
get() {
if (_aspectRatio != null) {
return _aspectRatio!!
}
_aspectRatio = Builder(name = "AspectRatio", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(5.0f, 5.0f)
lineTo(19.0f, 5.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 21.0f, 7.0f)
lineTo(21.0f, 17.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 19.0f, 19.0f)
lineTo(5.0f, 19.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 3.0f, 17.0f)
lineTo(3.0f, 7.0f)
arcTo(2.0f, 2.0f, 0.0f, false, true, 5.0f, 5.0f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(7.0f, 12.0f)
verticalLineToRelative(-3.0f)
horizontalLineToRelative(3.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(17.0f, 12.0f)
verticalLineToRelative(3.0f)
horizontalLineToRelative(-3.0f)
}
}
.build()
return _aspectRatio!!
}
private var _aspectRatio: ImageVector? = null
| 17
|
Kotlin
|
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 2,602
|
compose-icons
|
MIT License
|
app/src/main/kotlin/com/keygenqt/stack_2021/ui/common/CommonLoading.kt
|
keygenqt
| 367,717,930
| false
|
{"Kotlin": 131552}
|
/*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.keygenqt.kchat.modules.common.ui.compose
import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import com.keygenqt.kchat.extensions.visible
import com.keygenqt.kchat.theme.KChatTheme
@Composable
fun CommonLoading(
visibility: Boolean,
) {
ConstraintLayout(
modifier = Modifier
.fillMaxSize()
.visible(visibility)
) {
val (loading) = createRefs()
Text(
text = "Loading...",
style = MaterialTheme.typography.h6,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.padding(top = 2.dp, bottom = 2.dp, start = 8.dp, end = 4.dp)
.background(Color.Transparent)
.constrainAs(loading) {
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
)
}
}
@Preview("Light")
@Preview("Dark", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun PreviewCommonLoading() {
KChatTheme {
Surface {
CommonLoading(true)
}
}
}
| 0
|
Kotlin
|
12
| 63
|
b9b4dd4695ae744ea694d26a3c18664ef965ade2
| 2,369
|
android-GitHubViewer
|
Apache License 2.0
|
app/src/main/java/com/example/belindas_closet/data/network/auth/ForgotPasswordServiceImpl.kt
|
SeattleColleges
| 656,918,420
| false
|
{"Kotlin": 191183}
|
package com.example.belindas_closet.data.network.auth
import com.example.belindas_closet.data.network.HttpRoutes
import com.example.belindas_closet.data.network.dto.auth_dto.ForgotPasswordRequest
import com.example.belindas_closet.data.network.dto.auth_dto.ForgotPasswordResponse
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.request.url
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.util.InternalAPI
import kotlinx.serialization.json.Json
class ForgotPasswordServiceImpl(
private val client: HttpClient
) :
ForgotPasswordService {
@OptIn(InternalAPI::class)
override suspend fun forgotPassword(forgotPasswordRequest: ForgotPasswordRequest): ForgotPasswordResponse? {
return try {
val response = client.post {
url(HttpRoutes.FORGOT_PASSWORD)
header(HttpHeaders.ContentType, ContentType.Application.Json.toString())
body = Json.encodeToString(ForgotPasswordRequest.serializer(), forgotPasswordRequest)
}
response.body()
} catch (e: Exception) {
println("Error: ${e.message}")
null
}
}
}
| 3
|
Kotlin
|
6
| 9
|
641228904a5ab1a2b42bef9018dfa23de8c32f2e
| 1,288
|
belindas-closet-android
|
MIT License
|
app/src/main/java/vn/loitp/app/activity/customviews/dragview/fragment/NormalTopFragment.kt
|
tplloi
| 126,578,283
| false
| null |
package com.example.pokeapp.ui.capture
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.pokeapp.R
class CaptureScrollingFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_capture_scrolling, container, false)
}
}
| 9
| null |
4
| 6
|
b6c11ccff814d25ff368013ea6dd8a6b5d987ff1
| 511
|
basemaster
|
Apache License 2.0
|
src/main/kotlin/com/indramahkota/convention/kotlin/internal/Provider.kt
|
indramahkota
| 521,879,893
| false
|
{"Kotlin": 65624}
|
package com.indramahkota.convention.kotlin.internal
import org.gradle.api.provider.Property
internal fun <T : Any> Property<T>.setFinalValue(value: T) {
set(value)
finalizeValue()
}
| 0
|
Kotlin
|
0
| 0
|
fcac5f2bc33c0eeba6a06a18a466afd81e48631c
| 188
|
build-logic
|
MIT License
|
src/main/kotlin/com/cognifide/gradle/aem/common/instance/LocalInstanceManager.kt
|
mcgill-enterprises
| 244,752,188
| true
|
{"Kotlin": 523954, "Shell": 5281, "Batchfile": 267}
|
package com.cognifide.gradle.aem.common.instance
import com.cognifide.gradle.aem.AemExtension
import com.cognifide.gradle.aem.common.instance.action.AwaitDownAction
import com.cognifide.gradle.aem.common.instance.action.AwaitUpAction
import com.cognifide.gradle.aem.common.instance.local.*
import com.cognifide.gradle.aem.instance.LocalInstancePlugin
import com.cognifide.gradle.common.pluginProject
import com.cognifide.gradle.common.utils.onEachApply
import com.cognifide.gradle.common.utils.using
import java.io.File
import java.io.Serializable
import java.util.concurrent.TimeUnit
class LocalInstanceManager(private val aem: AemExtension) : Serializable {
private val project = aem.project
private val common = aem.common
private val logger = aem.logger
val base by lazy { aem.instanceManager }
/**
* Using local AEM instances is acceptable in any project so that lookup for project applying local instance plugin is required
* Needed to determine e.g directory in which AEM quickstart will be stored and override files.
*/
val projectDir = aem.obj.dir {
convention(aem.obj.provider {
project.pluginProject(LocalInstancePlugin.ID)?.layout?.projectDirectory ?: throw LocalInstanceException(
"Using local AEM instances requires having at least one project applying plugin '${LocalInstancePlugin.ID}'" +
" or setting property 'localInstance.projectDir'!"
)
})
aem.prop.string("localInstance.projectDir")?.let { set(project.rootProject.file(it)) }
}
/**
* Path in which local AEM instances will be stored.
*/
val rootDir = aem.obj.dir {
convention(projectDir.dir(".instance"))
aem.prop.file("localInstance.rootDir")?.let { set(it) }
}
/**
* Path for storing local AEM instances related resources.
*/
val configDir = aem.obj.dir {
convention(projectDir.dir("src/aem/localInstance"))
aem.prop.file("localInstance.configDir")?.let { set(it) }
}
/**
* Path from which e.g extra files for local AEM instances will be copied.
* Useful for overriding default startup scripts ('start.bat' or 'start.sh') or providing some files inside 'crx-quickstart'.
*/
val overrideDir = aem.obj.dir {
convention(configDir.dir("override"))
aem.prop.file("localInstance.overrideDir")?.let { set(it) }
}
/**
* Determines how instances will be created (from backup or quickstart built from the scratch).
*/
val source = aem.obj.typed<Source> {
convention(Source.AUTO)
aem.prop.string("localInstance.source")?.let { set(Source.of(it)) }
}
fun source(name: String) {
source.set(Source.of(name))
}
fun resolveFiles() {
logger.info("Resolving local instance files")
logger.info("Resolved local instance files:\n${sourceFiles.joinToString("\n")}")
}
/**
* Maximum time to wait for status script response.
*/
val scriptTimeout = aem.obj.long {
convention(TimeUnit.SECONDS.toMillis(5))
aem.prop.long("localInstance.scriptTimeout")?.let { set(it) }
}
/**
* Collection of files potentially needed to create instance
*/
val sourceFiles = aem.obj.files {
from(aem.obj.provider {
listOfNotNull(backupZip) + quickstart.files + install.files
})
}
/**
* Wildcard file name filter expression that is used to filter in which instance files properties can be injected.
*/
val expandFiles = aem.obj.strings {
convention(listOf(
"**/start.bat",
"**/stop.bat",
"**/start",
"**/stop"
))
}
/**
* Custom properties that can be injected into instance files.
*/
val expandProperties = aem.obj.map<String, Any> { convention(mapOf()) }
val quickstart by lazy { QuickstartResolver(aem) }
/**
* Configure AEM source files when creating instances from the scratch.
*/
fun quickstart(options: QuickstartResolver.() -> Unit) = quickstart.using(options)
/**
* Configure AEM backup sources.
*/
val backup by lazy { BackupManager(aem) }
fun backup(options: BackupManager.() -> Unit) = backup.using(options)
val backupZip: File?
get() {
return when (source.get()) {
Source.AUTO, Source.BACKUP_ANY -> backup.any
Source.BACKUP_LOCAL -> backup.local
Source.BACKUP_REMOTE -> backup.remote
else -> null
}
}
val install by lazy { InstallResolver(aem) }
/**
* Configure CRX packages, bundles to be pre-installed on instance(s).
*/
fun install(options: InstallResolver.() -> Unit) = install.using(options)
internal var initOptions: LocalInstance.() -> Unit = {}
/**
* Configure action to be performed only once when instance is up first time.
*/
fun init(options: LocalInstance.() -> Unit) {
this.initOptions = options
}
fun create(instance: LocalInstance) = create(listOf(instance))
fun create(instances: Collection<LocalInstance>): List<LocalInstance> {
val uncreatedInstances = instances.filter { !it.created }
if (uncreatedInstances.isEmpty()) {
logger.lifecycle("No instances to create.")
return listOf()
}
logger.info("Creating instances: ${uncreatedInstances.names}")
createBySource(uncreatedInstances)
return uncreatedInstances.filter { it.created }
}
@Suppress("ComplexMethod")
fun createBySource(instances: Collection<LocalInstance>) = when (source.get()) {
Source.AUTO -> {
val backupZip = backup.any
when {
backupZip != null -> createFromBackup(instances, backupZip)
else -> createFromScratch(instances)
}
}
Source.BACKUP_ANY -> {
val backupZip = backup.any
when {
backupZip != null -> createFromBackup(instances, backupZip)
else -> throw LocalInstanceException("Cannot create instance(s) because no backups available!")
}
}
Source.BACKUP_LOCAL -> {
val backupZip = backup.local
?: throw LocalInstanceException("Cannot create instance(s) because no local backups available!")
createFromBackup(instances, backupZip)
}
Source.BACKUP_REMOTE -> {
val backupZip = backup.remote
?: throw LocalInstanceException("Cannot create instance(s) because no remote backups available!")
createFromBackup(instances, backupZip)
}
Source.SCRATCH -> createFromScratch(instances)
null -> {}
}
fun createFromBackup(instances: Collection<LocalInstance>, backupZip: File) {
backup.restore(backupZip, rootDir.get().asFile, instances)
val missingInstances = instances.filter { !it.created }
if (missingInstances.isNotEmpty()) {
logger.info("Backup ZIP '$backupZip' does not contain all instances. Creating from scratch: ${missingInstances.names}")
createFromScratch(missingInstances)
}
common.progress(instances.size) {
instances.onEachApply {
increment("Customizing instance '$name'") {
logger.info("Customizing: $this")
customize()
logger.info("Customized: $this")
}
}
}
}
fun createFromScratch(instances: Collection<LocalInstance>) {
if (quickstart.jar == null || quickstart.license == null) {
throw LocalInstanceException("Cannot create instances due to lacking source files. " +
"Ensure having specified local instance quickstart jar & license urls.")
}
common.progress(instances.size) {
instances.onEachApply {
increment("Creating instance '$name'") {
if (created) {
logger.info(("Instance already created: $this"))
return@increment
}
logger.info("Creating: $this")
prepare()
logger.info("Created: $this")
}
}
}
}
fun destroy(instance: LocalInstance): Boolean = destroy(listOf(instance)).isNotEmpty()
fun destroy(instances: Collection<LocalInstance>): List<LocalInstance> {
val createdInstances = instances.filter { it.touched }
if (createdInstances.isEmpty()) {
logger.lifecycle("No instances to destroy.")
return listOf()
}
logger.info("Destroying instance(s): ${createdInstances.names}")
common.progress(createdInstances.size) {
createdInstances.onEachApply {
increment("Destroying '$name'") {
logger.info("Destroying: $this")
delete()
logger.info("Destroyed: $this")
}
}
}
return createdInstances
}
fun up(instance: LocalInstance, awaitUpOptions: AwaitUpAction.() -> Unit = {}) = up(listOf(instance), awaitUpOptions).isNotEmpty()
fun up(instances: Collection<LocalInstance>, awaitUpOptions: AwaitUpAction.() -> Unit = {}): List<LocalInstance> {
val downInstances = instances.filter { !it.running }
if (downInstances.isEmpty()) {
logger.lifecycle("No instances to turn on.")
return listOf()
}
common.progress(downInstances.size) {
downInstances.onEachApply {
increment("Customizing instance '$name'") {
logger.info("Customizing: $this")
customize()
logger.info("Customized: $this")
}
}
}
common.progress(downInstances.size) {
common.parallel.with(downInstances) {
increment("Starting instance '$name'") {
if (!created) {
logger.info("Instance not created, so it could not be up: $this")
return@increment
}
val status = checkStatus()
if (status == Status.RUNNING) {
logger.info("Instance already running. No need to start: $this")
return@increment
}
executeStartScript()
}
}
}
base.awaitUp(downInstances, awaitUpOptions)
common.progress(downInstances.size) {
common.parallel.with(downInstances) {
increment("Initializing instance '$name'") {
saveVersion()
if (!initialized) {
logger.info("Initializing: $this")
init(initOptions)
}
}
}
}
return downInstances
}
fun down(instance: LocalInstance, awaitDownOptions: AwaitDownAction.() -> Unit = {}) = down(listOf(instance), awaitDownOptions).isNotEmpty()
fun down(instances: Collection<LocalInstance>, awaitDownOptions: AwaitDownAction.() -> Unit = {}): List<LocalInstance> {
val upInstances = instances.filter { it.running }
if (upInstances.isEmpty()) {
logger.lifecycle("No instances to turn off.")
return listOf()
}
common.progress(upInstances.size) {
common.parallel.with(upInstances) {
increment("Stopping instance '$name'") {
if (!created) {
logger.info("Instance not created, so it could not be down: $this")
return@increment
}
val status = checkStatus()
if (status != Status.RUNNING) {
logger.info("Instance is not running (reports status '$status'). No need to stop: $this")
return@increment
}
executeStopScript()
}
}
}
base.awaitDown(upInstances, awaitDownOptions)
return upInstances
}
}
| 0
| null |
0
| 0
|
a9201d1983acd449b59590f6129cf27ba8712e38
| 12,491
|
gradle-aem-plugin
|
Apache License 2.0
|
app/src/main/java/cn/cqautotest/sunnybeach/ui/adapter/GuideAdapter.kt
|
anjiemo
| 378,095,612
| false
| null |
package com.yimulin.mobile.ui.adapter
import android.content.Context
import android.view.ViewGroup
import android.widget.ImageView
import com.yimulin.mobile.R
import com.yimulin.mobile.app.AppAdapter
/**
* author : Android 轮子哥
* github : https://github.com/getActivity/AndroidProject-Kotlin
* time : 2020/08/28
* desc : 引导页适配器
*/
class GuideAdapter constructor(context: Context) : AppAdapter<Int>(context) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder()
}
inner class ViewHolder : AppViewHolder(R.layout.guide_item) {
private val imageView: ImageView by lazy { getItemView() as ImageView }
override fun onBindView(position: Int) {
imageView.setImageResource(getItem(position))
}
}
}
| 1
| null |
18
| 95
|
a2402da1cb6af963c829a69d9783053f15d866b5
| 823
|
SunnyBeach
|
Apache License 2.0
|
app/src/main/java/cn/cqautotest/sunnybeach/ui/adapter/GuideAdapter.kt
|
anjiemo
| 378,095,612
| false
| null |
package com.yimulin.mobile.ui.adapter
import android.content.Context
import android.view.ViewGroup
import android.widget.ImageView
import com.yimulin.mobile.R
import com.yimulin.mobile.app.AppAdapter
/**
* author : Android 轮子哥
* github : https://github.com/getActivity/AndroidProject-Kotlin
* time : 2020/08/28
* desc : 引导页适配器
*/
class GuideAdapter constructor(context: Context) : AppAdapter<Int>(context) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder()
}
inner class ViewHolder : AppViewHolder(R.layout.guide_item) {
private val imageView: ImageView by lazy { getItemView() as ImageView }
override fun onBindView(position: Int) {
imageView.setImageResource(getItem(position))
}
}
}
| 1
| null |
18
| 95
|
a2402da1cb6af963c829a69d9783053f15d866b5
| 823
|
SunnyBeach
|
Apache License 2.0
|
src/main/kotlin/org/move/ide/inspections/MvNamingInspection.kt
|
pontem-network
| 279,299,159
| false
|
{"Kotlin": 2175494, "Move": 38620, "Lex": 5509, "HTML": 2114, "Java": 1275}
|
package org.move.ide.inspections
import com.intellij.codeInspection.ProblemsHolder
import org.move.lang.core.psi.*
abstract class MvNamingInspection(private val elementTitle: String) : MvLocalInspectionTool() {
override fun getDisplayName() = "$elementTitle naming convention"
override val isSyntaxOnly: Boolean = true
}
class MvConstNamingInspection : MvNamingInspection("Constant") {
override fun buildMvVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : MvVisitor() {
override fun visitConst(o: MvConst) {
val ident = o.identifier ?: return
val name = ident.text
if (!name.startsWithUpperCaseLetter()) {
holder.registerProblem(
ident,
"Invalid constant name `$name`. Constant names must start with 'A'..'Z'"
)
}
}
}
}
class MvFunctionNamingInspection : MvNamingInspection("Function") {
override fun buildMvVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : MvVisitor() {
override fun visitFunction(o: MvFunction) = checkFunctionName(o)
override fun visitSpecFunction(o: MvSpecFunction) = checkFunctionName(o)
private fun checkFunctionName(o: MvFunctionLike) {
val ident = o.nameIdentifier ?: return
val name = ident.text
if (name.startsWithUnderscore()) {
holder.registerProblem(
ident,
"Invalid function name '$name'. Function names cannot start with '_'"
)
}
}
}
}
class MvStructNamingInspection : MvNamingInspection("Struct") {
override fun buildMvVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : MvVisitor() {
override fun visitStruct(o: MvStruct) {
val ident = o.identifier ?: return
val name = ident.text
if (!name.startsWithUpperCaseLetter()) {
holder.registerProblem(
ident,
"Invalid struct name `$name`. Struct names must start with 'A'..'Z'"
)
}
}
}
}
class MvLocalBindingNamingInspection : MvNamingInspection("Local variable") {
override fun buildMvVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : MvVisitor() {
override fun visitBindingPat(o: MvBindingPat) {
// filter out constants
if (o.parent is MvConst) return
val ident = o.identifier
val name = ident.text
val trimmed = name.trimStart('_')
if (trimmed.isNotBlank() && !trimmed.startsWithLowerCaseLetter()) {
holder.registerProblem(
ident,
"Invalid local variable name `$name`. Local variable names must start with 'a'..'z'"
)
}
}
}
}
fun String.startsWithUpperCaseLetter(): Boolean = this[0].isUpperCase()
fun String.startsWithLowerCaseLetter(): Boolean = this[0].isLowerCase()
fun String.startsWithUnderscore(): Boolean = this[0] == '_'
| 8
|
Kotlin
|
7
| 69
|
51a5703d064a4b016ff2a19c2f00fe8f8407d473
| 3,116
|
intellij-move
|
MIT License
|
src/main/kotlin/no/nav/familie/ba/sak/kjerne/autovedtak/omregning/AutobrevScheduler.kt
|
navikt
| 224,639,942
| false
| null |
package no.nav.familie.ba.sak.kjerne.autovedtak.omregning
import no.nav.familie.ba.sak.config.LeaderClientService
import no.nav.familie.ba.sak.config.TaskRepositoryWrapper
import no.nav.familie.prosessering.domene.Task
import no.nav.familie.util.VirkedagerProvider
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDate
import java.time.LocalDateTime
@Component
class AutobrevScheduler(
val taskRepository: TaskRepositoryWrapper,
val leaderClientService: LeaderClientService,
) {
/**
* Denne funksjonen kjøres kl.7 den første dagen i måneden og setter triggertid på tasken til kl.8 den første virkedagen i måneden.
* For testformål kan funksjonen opprettTask også kalles direkte via et restendepunkt.
*/
@Transactional
@Scheduled(cron = "0 0 $KLOKKETIME_SCHEDULER_TRIGGES 1 * *")
fun opprettAutobrevTask() {
when (leaderClientService.isLeader()) {
true -> {
// Timen for triggertid økes med en. Det er nødvendig å sette klokkeslettet litt frem dersom den 1. i
// måneden også er en virkedag (slik at både denne skeduleren og tasken som opprettes vil kjøre på samme dato).
opprettTask(
triggerTid =
VirkedagerProvider.nesteVirkedag(
LocalDate.now().minusDays(1),
).atTime(KLOKKETIME_SCHEDULER_TRIGGES.inc(), 0),
)
}
false -> logger.info("Poden er ikke satt opp som leader - oppretter ikke task")
}
}
fun opprettTask(triggerTid: LocalDateTime = LocalDateTime.now().plusSeconds(30)) {
logger.info("Opprett månedlig task")
taskRepository.save(
Task(
type = AutobrevTask.TASK_STEP_TYPE,
payload = "",
).medTriggerTid(
triggerTid = triggerTid,
),
)
}
companion object {
private val logger = LoggerFactory.getLogger(AutobrevScheduler::class.java)
const val KLOKKETIME_SCHEDULER_TRIGGES = 6
}
}
| 9
|
Kotlin
|
1
| 9
|
ef5e22a745c17b69f0a310673155613e8703ac31
| 2,261
|
familie-ba-sak
|
MIT License
|
app/src/main/java/com/ericktijerou/jetkanto/data/local/system/SessionHelper.kt
|
ericktijerou
| 351,183,927
| 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.ericktijerou.jetkanto.data.local.system
import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.ericktijerou.jetkanto.core.EMPTY
import com.ericktijerou.jetkanto.core.ZERO
import com.ericktijerou.jetkanto.data.entity.UserModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
class SessionHelper @Inject constructor(private val context: Context) {
private val Context.userDataStore by preferencesDataStore(
name = USER_PREFERENCES_NAME
)
val session: Flow<UserModel> = context.userDataStore.data
.map { preferences ->
val userId = preferences[USER_ID_KEY] ?: EMPTY
val name = preferences[NAME_KEY] ?: EMPTY
val username = preferences[USERNAME_KEY] ?: EMPTY
val avatar = preferences[AVATAR_KEY] ?: EMPTY
val localAvatar = preferences[LOCAL_AVATAR_KEY] ?: EMPTY
val bio = preferences[BIO_KEY] ?: EMPTY
val followers = preferences[FOLLOWERS_KEY] ?: ZERO
val followed = preferences[FOLLOWED_KEY] ?: ZERO
val views = preferences[VIEWS_KEY] ?: ZERO
UserModel(
id = userId,
name = name,
username = username,
avatar = avatar,
bio = bio,
followers = followers,
followed = followed,
views = views,
localAvatarPath = localAvatar
)
}
suspend fun saveSession(userModel: UserModel) = with(userModel) {
context.userDataStore.edit { preferences ->
preferences[USER_ID_KEY] = id
preferences[NAME_KEY] = name
preferences[USERNAME_KEY] = username
preferences[AVATAR_KEY] = avatar
preferences[LOCAL_AVATAR_KEY] = localAvatarPath
preferences[BIO_KEY] = bio
preferences[FOLLOWERS_KEY] = followers
preferences[FOLLOWED_KEY] = followed
preferences[VIEWS_KEY] = views
}
}
companion object {
private const val PREF_KEY_USER_ID = "user_id"
private const val PREF_KEY_NAME = "name"
private const val PREF_KEY_USERNAME = "username"
private const val PREF_KEY_AVATAR = "avatar"
private const val PREF_KEY_LOCAL_AVATAR = "local_avatar"
private const val PREF_KEY_BIO = "bio"
private const val PREF_KEY_FOLLOWERS = "followers"
private const val PREF_KEY_FOLLOWED = "followed"
private const val PREF_KEY_VIEWS = "views"
private const val USER_PREFERENCES_NAME = "user_preferences"
private val USER_ID_KEY = stringPreferencesKey(PREF_KEY_USER_ID)
private val NAME_KEY = stringPreferencesKey(PREF_KEY_NAME)
private val USERNAME_KEY = stringPreferencesKey(PREF_KEY_USERNAME)
private val AVATAR_KEY = stringPreferencesKey(PREF_KEY_AVATAR)
private val LOCAL_AVATAR_KEY = stringPreferencesKey(PREF_KEY_LOCAL_AVATAR)
private val BIO_KEY = stringPreferencesKey(PREF_KEY_BIO)
private val FOLLOWERS_KEY = intPreferencesKey(PREF_KEY_FOLLOWERS)
private val FOLLOWED_KEY = intPreferencesKey(PREF_KEY_FOLLOWED)
private val VIEWS_KEY = intPreferencesKey(PREF_KEY_VIEWS)
}
}
| 0
|
Kotlin
|
0
| 0
|
835bfe870f0bcc47bb06ecd7450f4d3c78d141bc
| 4,131
|
jetkanto
|
Apache License 2.0
|
app/src/main/java/com/liuzhenlin/videos/Consts.kt
|
lzls
| 125,976,852
| false
| null |
/*
* Created on 2019/3/18 8:45 PM.
* Copyright © 2019–2020 刘振林. All rights reserved.
*/
@file:JvmName("Consts")
package com.liuzhenlin.videos
import androidx.core.content.ContextCompat
import com.liuzhenlin.common.Consts
/**
* @author 刘振林
*/
internal const val PROCESS_NAME_MAIN = Consts.APPLICATION_ID
internal const val PROCESS_NAME_WEB = Consts.APPLICATION_ID + ":web"
internal const val KEY_DIRECTORY_PATH = "directoryPath"
internal const val KEY_VIDEODIR = "videodir"
internal const val KEY_VIDEO = "video"
internal const val KEY_VIDEOS = "videos"
internal const val KEY_VIDEO_TITLE = "videoTitle"
internal const val KEY_VIDEO_TITLES = "videoTitles"
internal const val KEY_VIDEO_URIS = "videoURIs"
internal const val KEY_SELECTION = "index"
internal const val REQUEST_CODE_PLAY_VIDEO = 1
internal const val RESULT_CODE_PLAY_VIDEO = 1
internal const val REQUEST_CODE_PLAY_VIDEOS = 2
internal const val RESULT_CODE_PLAY_VIDEOS = 2
internal const val REQUEST_CODE_LOCAL_SEARCHED_VIDEOS_FRAGMENT = 3
internal const val RESULT_CODE_LOCAL_SEARCHED_VIDEOS_FRAGMENT = 3
internal const val REQUEST_CODE_LOCAL_FOLDED_VIDEOS_FRAGMENT = 4
internal const val RESULT_CODE_LOCAL_FOLDED_VIDEOS_FRAGMENT = 4
internal const val REQUEST_CODE_GET_PICTURE = 5
internal const val RESULT_CODE_GET_PICTURE = 5
private val _COLOR_ACCENT by lazy(LazyThreadSafetyMode.NONE) {
ContextCompat.getColor(App.getInstanceUnsafe()!!, R.color.colorAccent) }
@JvmField
internal val COLOR_ACCENT = _COLOR_ACCENT
private val _TEXT_COLOR_PRIMARY_LIGHT by lazy(LazyThreadSafetyMode.NONE) {
ContextCompat.getColor(App.getInstanceUnsafe()!!, R.color.primary_text_default_material_dark) }
@JvmField
internal val TEXT_COLOR_PRIMARY_LIGHT = _TEXT_COLOR_PRIMARY_LIGHT
private val _TEXT_COLOR_PRIMARY_DARK by lazy(LazyThreadSafetyMode.NONE) {
ContextCompat.getColor(App.getInstanceUnsafe()!!, R.color.primary_text_default_material_light) }
@JvmField
internal val TEXT_COLOR_PRIMARY_DARK = _TEXT_COLOR_PRIMARY_DARK
| 8
| null |
16
| 41
|
c92d874e4feb7b8ae2956afb0353ff2901546d76
| 2,000
|
Videos
|
Apache License 2.0
|
embrace-android-sdk/src/test/java/io/embrace/android/embracesdk/config/LogRemoteConfigTest.kt
|
embrace-io
| 704,537,857
| false
| null |
package io.embrace.android.embracesdk.config
import io.embrace.android.embracesdk.config.remote.LogRemoteConfig
import io.embrace.android.embracesdk.deserializeEmptyJsonString
import io.embrace.android.embracesdk.deserializeJsonFromResource
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
internal class LogRemoteConfigTest {
@Test
fun testDefaults() {
val cfg = LogRemoteConfig(null, null, null, null)
verifyDefaults(cfg)
}
@Test
fun testOverride() {
val cfg = LogRemoteConfig(
768,
50,
200,
500,
)
assertEquals(768, cfg.logMessageMaximumAllowedLength)
assertEquals(50, cfg.logInfoLimit)
assertEquals(200, cfg.logWarnLimit)
assertEquals(500, cfg.logErrorLimit)
}
@Test
fun testDeserialization() {
val cfg = deserializeJsonFromResource<LogRemoteConfig>("log_config.json")
assertEquals(768, cfg.logMessageMaximumAllowedLength)
assertEquals(50, cfg.logInfoLimit)
assertEquals(200, cfg.logWarnLimit)
assertEquals(500, cfg.logErrorLimit)
}
@Test
fun testDeserializationEmptyObj() {
val cfg = deserializeEmptyJsonString<LogRemoteConfig>()
verifyDefaults(cfg)
}
private fun verifyDefaults(cfg: LogRemoteConfig) {
assertNull(cfg.logMessageMaximumAllowedLength)
assertNull(cfg.logInfoLimit)
assertNull(cfg.logWarnLimit)
assertNull(cfg.logErrorLimit)
}
}
| 22
| null |
8
| 133
|
e5b92a8e0ed1ea64602b68ec071780369e0ea915
| 1,555
|
embrace-android-sdk
|
Apache License 2.0
|
app/src/main/java/com/yury/lebowski/navigation/NavigatiorDetailContainer.kt
|
iliailemkov
| 143,139,061
| true
|
{"Kotlin": 112583}
|
package com.yury.lebowski.navigation
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class NavigatiorDetailContainer
| 0
|
Kotlin
|
0
| 0
|
aec038962531c5c1945ce4df71f3f93c15ebd4c1
| 171
|
Lebowski
|
Creative Commons Attribution 3.0 Unported
|
src/main/kotlin/com/sauleiros/albumexplorer/infra/adapters/input/rest/models/ErrorMessage.kt
|
SaulEiros
| 833,679,357
| false
|
{"Kotlin": 24735, "Dockerfile": 270}
|
package com.sauleiros.albumexplorer.infra.adapters.input.rest.models
data class ErrorMessage(
var status: Int? = null,
var message: String? = null,
)
| 0
|
Kotlin
|
0
| 0
|
3647b87e66c72709f1352e0c958979b022189608
| 159
|
album-explorer
|
Apache License 2.0
|
src/main/kotlin/rarula/symmetricraft/area/AreaSymmetryType.kt
|
rarula
| 674,535,604
| false
| null |
package rarula.symmetricraft.area
enum class AreaSymmetryType {
POINT,
LINE
}
| 0
|
Kotlin
|
0
| 0
|
cd9f8d09bcf46847e8a3af024a45bf26a1e10ac3
| 87
|
SymmetriCraft
|
MIT License
|
Corona-Warn-App/src/androidTest/java/de/rki/coronawarnapp/ui/view/EmojiFilterTest.kt
|
corona-warn-app
| 268,027,139
| false
| null |
package de.rki.coronawarnapp.ui.view
import android.text.SpannableString
import io.kotest.matchers.shouldBe
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class EmojiFilterTest {
private val testData = mapOf<CharSequence, CharSequence?>(
"Pneumonoultramicroscopicsilicovolcanoconiosis" to null, // English
"Donaudampfschifffahrtselektrizitätenhauptbetriebswerkbauunterbeamtengesellschaft" to null, // German
"Muvaffakiyetsizleştiricileştiriveremeyebileceklerimizdenmişsinizcesine" to null, // Turkish
"Рентгеноэлектрокардиографический" to null, // Russian
"speciallægepraksisplanlægningsstabiliseringsperiode" to null, // Danish
"Непротивоконституционствувателствувайте" to null, // Bulgarian
"Dziewięćsetdziewięćdziesięciodziewięcionarodowościowego" to null, // Polish
"Pneumoultramicroscopicossilicovulcanoconiótico" to null, // Portuguese
"paraskevidékatriaphobie" to null, // French
"peruspalveluliikelaitoskuntayhtymä" to null, // Finnish
"Arquitectónicamente" to null, // Spanish
"znajneprekryštalizovávateľnejšievajúcimi" to null, // Slovak
// Swedish
"Spårvagnsaktiebolagsskensmutsskjutarefackföreningspersonalbeklädnadsmagasinsförråd-sförvaltarens" to null,
// Hungarian
"legösszetettebbszóhosszúságvilágrekorddöntéskényszerneurózistünetegyüttesmegnyilvá-nulásfejleszthetőségvizsgálataitokként" to null,
"nebeprisikiškiakopūstlapiaujančiuosiuose" to null, // Lithuanian
"וכשבהשתעשעויותיהם" to null, // Hebrew
"ηλεκτροεγκεφαλογραφήματος" to null, // Greek
"prijestolonasljednikovičičinima" to null, // Croatian
"Sünnipäevanädalalõpupeopärastlõunaväsimatus" to null, // Estonian
"أفاستسقيناكموها" to null, // Arabic,
"✌️✌️✌️✌️✌️✌️✌️✌️✌️️" to "", // Emoji,
"☕☕☕☕☕☕☕☕☕" to "", // Emoji,
)
@Test
fun filter() {
testData.forEach { (input, output) ->
EmojiFilter().filter(
input,
0,
input.length,
SpannableString(input),
0,
input.length
) shouldBe output
}
}
}
| 6
| null |
514
| 2,495
|
d3833a212bd4c84e38a1fad23b282836d70ab8d5
| 2,278
|
cwa-app-android
|
Apache License 2.0
|
app/src/main/java/com/imcys/bilibilias/base/app/App.kt
|
1250422131
| 280,332,208
| false
| null |
package com.imcys.bilibilias.base.app
import android.annotation.SuppressLint
import android.content.Context
import com.drake.brv.utils.BRV
import com.drake.statelayout.StateConfig
import com.imcys.bilibilias.R
import com.imcys.bilibilias.base.utils.DownloadQueue
import com.imcys.bilibilias.common.base.app.BaseApplication
import com.imcys.bilibilias.tool_log_export.BR
import dagger.hilt.android.HiltAndroidApp
import io.microshow.rxffmpeg.RxFFmpegInvoke
@HiltAndroidApp
class App : BaseApplication() {
override fun onCreate() {
super.onCreate()
RxFFmpegInvoke.getInstance().setDebug(false)
// BRV初始化
initBRV()
context = applicationContext()
}
private fun initBRV() {
// 初始化BindingAdapter的默认绑定ID, 如果不使用DataBinding并不需要初始化
BRV.modelId = BR.data
StateConfig.apply {
emptyLayout = com.imcys.bilibilias.common.R.layout.public_layout_empty
errorLayout = com.imcys.bilibilias.common.R.layout.public_layout_error
loadingLayout = com.imcys.bilibilias.common.R.layout.public_layout_loading
}
}
companion object {
const val appSecret = "<KEY>"
const val AppGuideVersion = "1.0"
// —————————————————————————————————————————————————
// ——————————————————B站视频模板——————————————————
val videoEntry: String by lazy {
context.getString(R.string.VideoEntry)
}
val videoIndex: String by lazy {
context.getString(R.string.VideoIndex)
}
val bangumiEntry: String by lazy {
context.getString(R.string.BangumiEntry)
}
// ——————————————————部分内置需要的上下文——————————————————
@SuppressLint("StaticFieldLeak")
lateinit var context: Context
// —————————————————————————————————————————————————
}
}
| 3
| null |
51
| 849
|
4dff7fbbcffeead83d0d3881bb3782857f08b830
| 1,856
|
bilibilias
|
Apache License 2.0
|
passwordvalidator/src/main/java/sergio/sastre/multiplying/quality/of/unittests/passwordvalidator/ui/EmailText.kt
|
sergio-sastre
| 370,679,468
| false
| null |
package sergio.sastre.multiplying.quality.of.unittests.passwordvalidator.ui
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Composable
fun EmailText(
modifier: Modifier = Modifier,
emailText: @Composable RowScope.() -> Unit,
) {
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = Icons.Default.Email,
contentDescription = null,
)
Spacer(modifier = Modifier.width(16.dp))
emailText()
}
}
@Preview(showBackground = true)
@Composable
fun Preview_EmailText() {
MaterialTheme {
EmailText(
modifier = Modifier.fillMaxWidth(),
emailText = {
Text("<EMAIL>")
}
)
}
}
| 1
|
Kotlin
|
0
| 6
|
ec6637da203e792a3e13e68382a5b575f19703a2
| 1,106
|
Multiplying_the_quality_of_unit_tests
|
MIT License
|
backend/projectionservice/src/main/kotlin/com/example/nftmarketplace/projectionservice/ProjectionServiceApplication.kt
|
majoseek
| 653,294,615
| false
|
{"Kotlin": 135268, "TypeScript": 78988, "Solidity": 23873, "Dockerfile": 1736, "HTML": 434, "CSS": 140, "JavaScript": 95}
|
package com.example.nftmarketplace.projectionservice
import com.example.nftmarketplace.events.RabbitInitializer
import com.example.nftmarketplace.events.RabbitQueueConfiguration
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Import
@Import(RabbitQueueConfiguration::class, RabbitInitializer::class)
@SpringBootApplication
class ProjectionServiceApplication
fun main(args: Array<String>) {
runApplication<ProjectionServiceApplication>(*args)
}
| 0
|
Kotlin
|
0
| 1
|
e3f2e7de44871ce3adbe2ead5759a802b3a74d38
| 563
|
NFT-Marketplace
|
MIT License
|
core/domain/src/main/java/com/example/zenn_app/core/domain/use_case/ArticleUseCase.kt
|
shxun6934
| 565,046,416
| false
| null |
package com.example.zenn_app.core.domain.use_case
import com.example.zenn_app.core.data.repository.TrendIdeaArticleRepository
import com.example.zenn_app.core.data.repository.TrendTechArticleRepository
import com.example.zenn_app.core.domain.model.TrendIdeaArticle
import com.example.zenn_app.core.domain.model.TrendTechArticle
import com.example.zenn_app.core.domain.translator.TrendIdeaArticleTranslator.asIdeaAppModel
import com.example.zenn_app.core.domain.translator.TrendTechArticleTranslator.asTechAppModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
class ArticleUseCase @Inject constructor(
private val techArticleRepository: TrendTechArticleRepository,
private val ideaArticleRepository: TrendIdeaArticleRepository
) {
fun fetchTrendTechArticles(): Flow<List<TrendTechArticle>> =
techArticleRepository.fetchTrendTechArticles().map { articles ->
articles.map { it.asTechAppModel() }
}
fun fetchTrendIdeaArticles(): Flow<List<TrendIdeaArticle>> =
ideaArticleRepository.fetchTrendIdeaArticles().map { articles ->
articles.map { it.asIdeaAppModel() }
}
}
| 0
|
Kotlin
|
0
| 0
|
39fe7187ed6d4433111bbb1b07807c1d63162fa7
| 1,190
|
android-zenn-app
|
MIT License
|
src/test/kotlin/com/google/shinyay/SpringDataMongodbGsApplicationTests.kt
|
shinyay
| 305,416,352
| false
| null |
package com.google.shinyay
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class SpringDataMongodbGsApplicationTests {
@Test
fun contextLoads() {
}
}
| 0
|
Kotlin
|
0
| 0
|
ecb5839064a135a973e45a4dd0d4d8fd177e4873
| 219
|
spring-data-mongodb-gs
|
MIT License
|
libnavigation-base/src/main/java/com/mapbox/navigation/base/trip/model/roadobject/incident/IncidentCongestion.kt
|
mapbox
| 87,455,763
| false
|
{"Kotlin": 8885438, "Makefile": 8762, "Python": 7925, "Java": 4624}
|
package com.mapbox.navigation.base.trip.model.roadobject.incident
/**
* Quantitative descriptor of congestion of [Incident].
*
* @param value quantitative descriptor of congestion. 0 to 100.
*/
class IncidentCongestion internal constructor(
val value: Int?,
) {
/**
* Indicates whether some other object is "equal to" this one.
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as IncidentCongestion
if (value != other.value) return false
return true
}
/**
* Returns a hash code value for the object.
*/
override fun hashCode(): Int {
return value.hashCode()
}
/**
* Returns a string representation of the object.
*/
override fun toString(): String {
return "IncidentCongestion(value=$value)"
}
}
| 508
|
Kotlin
|
319
| 621
|
ad73c6011348cb9b24b92a369024ca06f48845ab
| 917
|
mapbox-navigation-android
|
Apache License 2.0
|
app/src/main/java/com/deonnao/parstagram/MainActivity.kt
|
deonnao
| 515,710,532
| false
| null |
package com.deonnao.parstagram
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import com.parse.*
import java.io.File
/**
*Let the user create a post by taking a photo with their camera
*/
class MainActivity : AppCompatActivity() {
val CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1034
val photoFileName = "photo.jpg"
var photoFile: File? = null
override fun onCreate(savedInstanceState: Bundle?) {
//Within the onCreate method
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//1. Setting the description of the post
//2. A button to launch the camera to take a picture
//3. An imageview to show the picture the user has taken
//4. A button to save and send the post to our Parse server
findViewById<Button>(R.id.takePictureBtn).setOnClickListener {
//Launch camera to let user take a picture
onLaunchCamera()
}
findViewById<Button>(R.id.submitPostBtn).setOnClickListener {
//send post to the server without an image
//Get the description that they have inputted
val description = findViewById<EditText>(R.id.etDescription).text.toString()
val user = ParseUser.getCurrentUser()
if(photoFile != null) {
submitPost(description, user, photoFile!!)
} else {
Log.i(TAG, "Error submitting post")
Toast.makeText(this, "Error submitting post", Toast.LENGTH_SHORT).show()
}
}
findViewById<Button>(R.id.logoutBtn).setOnClickListener {
//logout user
ParseUser.logOut()
Log.i(TAG, "Successfully logged out!")
Toast.makeText(this, "Successfully logged out!", Toast.LENGTH_SHORT).show()
//When logged out go back to login activity
val intent = Intent(this@MainActivity, LoginActivity::class.java)
startActivity(intent)
}
queryPosts()
}
//Send a Post object to our parse server
fun submitPost(description: String, user: ParseUser, photoFile: File) {
//Create the Post object
val post = Post()
post.setDescription(description)
post.setUser(user)
post.setImage(ParseFile(photoFile))
post.saveInBackground { exception ->
if(exception != null) {
//Something has went wrong
Log.e(TAG, "Error while saving post")
exception.printStackTrace()
Toast.makeText(this, "Error while saving post", Toast.LENGTH_SHORT).show()
} else {
Log.i(TAG, "Successfully saved post")
//Reset description box and image view to be empty after submitting post
val etDescription = findViewById<EditText>(R.id.etDescription)
val ivPostImage = findViewById<ImageView>(R.id.ivPostImage)
etDescription.text.clear()
ivPostImage.setImageResource(0)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// by this point we have the camera photo on disk
val takenImage = BitmapFactory.decodeFile(photoFile!!.absolutePath)
// RESIZE BITMAP, see section below
// Load the taken image into a preview
val ivPreview: ImageView = findViewById(R.id.ivPostImage)
ivPreview!!.setImageBitmap(takenImage)
} else { // Result was a failure
Toast.makeText(this, "Error taking picture", Toast.LENGTH_SHORT).show()
}
}
}
fun onLaunchCamera() {
// create Intent to take a picture and return control to the calling application
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
// Create a File reference for future access
photoFile = getPhotoFileUri(photoFileName)
// wrap File object into a content provider
// required for API >= 24
// See https://guides.codepath.com/android/Sharing-Content-with-Intents#sharing-files-with-api-24-or-higher
if (photoFile != null) {
val fileProvider: Uri =
FileProvider.getUriForFile(this, "com.codepath.fileprovider", photoFile!!)
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider)
// If you call startActivityForResult() using an intent that no app can handle, your app will crash.
// So as long as the result is not null, it's safe to use the intent.
// If you call startActivityForResult() using an intent that no app can handle, your app will crash.
// So as long as the result is not null, it's safe to use the intent.
if (intent.resolveActivity(packageManager) != null) {
// Start the image capture intent to take photo
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
}
}
}
// Returns the File for a photo stored on disk given the fileName
fun getPhotoFileUri(fileName: String): File {
// Get safe storage directory for photos
// Use `getExternalFilesDir` on Context to access package-specific directories.
// This way, we don't need to request external read/write runtime permissions.
val mediaStorageDir =
File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), TAG)
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) {
Log.d(TAG, "failed to create directory")
}
// Return the file target for the photo based on filename
return File(mediaStorageDir.path + File.separator + fileName)
}
//Query for all posts in our server
fun queryPosts() {
// Specify which class to query
val query: ParseQuery<Post> = ParseQuery.getQuery(Post::class.java)
//Find all Post objects
query.include(Post.KEY_USER) //also include the user associated with each post
query.findInBackground(object : FindCallback<Post> {
override fun done(posts: MutableList<Post>?, e: ParseException?) {
if(e != null) {
//something has went wrong
Log.e(TAG, "Error fetching posts")
} else {
if(posts != null) {
for (post in posts) {
Log.i(TAG, "Post: " + post.getDescription() + " , username: " +
post.getUser()?.username)
}
}
}
}
})
}
companion object {
const val TAG = "MainActivity"
}
}
| 0
|
Kotlin
|
0
| 0
|
3316d80ef6ec2ca9909ae0737da3a80472fdcc4a
| 7,540
|
Parstagram
|
Apache License 2.0
|
kotlin-mui-icons/src/main/generated/mui/icons/material/BedroomParent.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/BedroomParent")
package mui.icons.material
@JsName("default")
external val BedroomParent: SvgIconComponent
| 12
| null |
5
| 983
|
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
| 190
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/org/listenbrainz/android/repository/LoginRepositoryImpl.kt
|
metabrainz
| 550,726,972
| false
| null |
package org.listenbrainz.android.repository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import org.listenbrainz.android.model.AccessToken
import org.listenbrainz.android.model.UserInfo
import org.listenbrainz.android.repository.LoginRepository.Companion.errorToken
import org.listenbrainz.android.repository.LoginRepository.Companion.errorUserInfo
import org.listenbrainz.android.service.LoginService
import org.listenbrainz.android.util.Constants.CLIENT_ID
import org.listenbrainz.android.util.Constants.CLIENT_SECRET
import org.listenbrainz.android.util.Constants.MUSICBRAINZ_AUTH_BASE_URL
import org.listenbrainz.android.util.Constants.OAUTH_REDIRECT_URI
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class LoginRepositoryImpl @Inject constructor(private val service: LoginService) : LoginRepository {
override val accessTokenFlow: MutableStateFlow<AccessToken?> = MutableStateFlow(null)
override val userInfoFlow: MutableStateFlow<UserInfo?> = MutableStateFlow(null)
override fun fetchAccessToken(code: String?) {
service.getAccessToken(
MUSICBRAINZ_AUTH_BASE_URL + "token",
code,
"authorization_code",
CLIENT_ID,
CLIENT_SECRET,
OAUTH_REDIRECT_URI
).enqueue(object : Callback<AccessToken?> {
override fun onResponse(call: Call<AccessToken?>, response: Response<AccessToken?>) {
accessTokenFlow.update { response.body() ?: errorToken }
}
override fun onFailure(call: Call<AccessToken?>, t: Throwable) {
t.printStackTrace()
accessTokenFlow.update { errorToken }
}
})
}
override fun fetchUserInfo(accessToken: String) {
service.userInfo("Bearer $accessToken").enqueue(object : Callback<UserInfo?> {
override fun onResponse(call: Call<UserInfo?>, response: Response<UserInfo?>) {
val info = response.body()
userInfoFlow.update { info ?: errorUserInfo }
}
override fun onFailure(call: Call<UserInfo?>, t: Throwable) {
t.printStackTrace()
userInfoFlow.update { errorUserInfo }
}
})
}
}
| 3
|
Kotlin
|
15
| 27
|
cb63c2b51db6715ac6f0b23d3cecc5f8df13df45
| 2,393
|
listenbrainz-android
|
Apache License 2.0
|
src/main/kotlin/net/ngaspar/urlshortener/controller/UrlEntryResource.kt
|
ngaspar
| 592,704,452
| false
| null |
package net.ngaspar.urlshortener.controller
import net.ngaspar.urlshortener.model.UrlEntry
import net.ngaspar.urlshortener.model.UrlEntryRequest
import net.ngaspar.urlshortener.service.UrlShortenerServiceDirtyImpl
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.*
import org.springframework.web.server.ResponseStatusException
@RestController
class UrlEntryResource @Autowired constructor(private val service: UrlShortenerServiceDirtyImpl){
/*
* Returns the original URL corresponding to a given hash
*/
@GetMapping("/stretch/{hash}")
fun getUrlFromHash(@PathVariable hash: String): String {
return service.fetchLongUrlByHash(hash)?.url ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "No URL exists for the hash $hash")
}
/*
* Returns the UrlEntry object corresponding to a given hash
*/
@GetMapping("/stats/{hash}")
fun getUrlStatsFromHash(@PathVariable hash: String): UrlEntry {
return service.fetchUrlEntryByHash(hash)?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "No URL exists for the hash $hash")
}
/*
* Creates and returns a new hash from a given URL, if it does not exist
* in the repository; otherwise returns existing one
*/
@PostMapping("/shrink/")
fun createOrGetHashFromUrl(@RequestBody request: UrlEntryRequest): String {
return service.fetchOrCreateShortUrl(request.url)?.hash ?: throw ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Error creating hash for URL ${request.url}")
}
}
| 0
|
Kotlin
|
0
| 0
|
7844df99de87a2a6f6aa6367e78f2d81d374157f
| 1,640
|
dkb-cf-urlshortener
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.