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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
detekt-rules/src/test/resources/cases/DataClassContainsFunctions.kt
|
devtribe
| 106,407,322
| true
|
{"Kotlin": 511659, "Groovy": 1433}
|
@file:Suppress("unused", "RedundantOverride")
package cases
data class ValidDataClass(val i: Int)
data class DataClassWithFunctions(val i: Int) { // reports 2
fun f1() {}
fun f2() {}
}
data class DataClassWithOverriddenMethods(val i: Int) {
override fun hashCode(): Int {
return super.hashCode()
}
override fun equals(other: Any?): Boolean {
return super.equals(other)
}
override fun toString(): String {
return super.toString()
}
}
class ClassWithRegularFunctions {
fun f1() {}
fun f2() {}
data class NestedDataClassWithConversionFunction(val i : Int) { // reports 1
fun toDataClassWithOverriddenMethods() = DataClassWithOverriddenMethods(i)
}
}
| 0
|
Kotlin
|
0
| 0
|
a7e20b134bd24308e36424a7aa137cbe6e12b902
| 678
|
detekt
|
Apache License 2.0
|
app/src/main/java/com/example/stocktracker/data/FavouriteList.kt
|
Zellka
| 344,874,792
| false
| null |
package com.example.stocktracker.data
import com.example.stocktracker.entity.Stock
import io.paperdb.Paper
class FavouriteList {
companion object {
fun updateItem(stockItem: Stock) {
val favouriteList = getFavouriteList()
val targetItem = favouriteList.singleOrNull { it.ticker == stockItem.ticker }
if (targetItem == null) {
favouriteList.add(stockItem)
} else {
favouriteList.remove(stockItem)
}
saveStock(favouriteList)
}
fun isFavourite(stockItem: Stock): Boolean {
val favouriteList = getFavouriteList()
return favouriteList.contains(stockItem)
}
private fun saveStock(stock: MutableList<Stock>) {
Paper.book().write("stock", stock)
}
fun getFavouriteList(): MutableList<Stock> {
return Paper.book().read("stock", mutableListOf())
}
}
}
| 0
|
Kotlin
|
1
| 0
|
b5b34e829268d8c10a87a81dd111f773baf74110
| 970
|
StockTracker
|
MIT License
|
data/src/main/java/com/ice/data/apiservice/ApiService.kt
|
Ice-crusher
| 314,906,770
| false
| null |
package com.ice.data.apiservice
import com.google.gson.JsonObject
import com.ice.data.models.HistoryJson
import com.ice.data.models.UserJson
import io.reactivex.Single
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Query
interface ApiService {
@POST("/sick")
fun sick(@Body params: HashMap<String, String>): Single<JsonObject>
@POST("/nearbyTouch")
fun nearbyTouch(@Body params: HashMap<String, String>): Single<JsonObject>
@POST("/login")
fun login(@Body params: HashMap<String, String>): Single<UserJson>
@GET("/userTouchHistory")
fun history(@Query("userId") userId: String): Single<HistoryJson>
}
| 0
|
Kotlin
|
0
| 0
|
aef777762993082de9deef705c9768018b428862
| 693
|
CovidAlert
|
Apache License 2.0
|
app/src/main/java/com/codility/customnotification/activities/MainActivity.kt
|
AndroidCodility
| 123,560,231
| false
|
{"Kotlin": 7843}
|
package com.codility.customnotification.activities
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Toast
import com.codility.customnotification.R
import com.codility.customnotification.utils.CustomNotification
import kotlinx.android.synthetic.main.activity_main.*
/**
* Created by Govind on 3/1/2018.
*/
class MainActivity : AppCompatActivity(), View.OnClickListener {
override fun onClick(p0: View?) {
when (p0!!.id) {
R.id.btNotification -> {
if (!isValidate()) {
return
}
CustomNotification().showNotification(this, edTitle.text.toString(), edMessage.text.toString())
}
R.id.btCustomNotification -> {
if (!isValidate()) {
return
}
CustomNotification().showCustomNotification(this, edTitle.text.toString(), edMessage.text.toString())
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btNotification.setOnClickListener(this)
btCustomNotification.setOnClickListener(this)
}
private fun isValidate(): Boolean {
if (edTitle.text.isEmpty()) {
showToast("Title is empty..!!")
return false
}
if (edMessage.text.isEmpty()) {
showToast("Message is empty..!!")
return false
}
return true
}
private fun showToast(msg: String) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
}
}
| 0
|
Kotlin
|
0
| 1
|
1eaf79bfe4c1f79ba124668ebc9f6b2f1e62e2dc
| 1,699
|
CustomNotification
|
MIT License
|
src/test/kotlin/BinaryFormatTest.kt
|
kropp
| 164,493,180
| false
| null |
import kotlinx.serialization.*
/*
class BinaryFormatTest {
@Serializable class Bin(val v: ByteArray)
@Test
fun empty() {
assertThat(MessagePack.pack(Bin.serializer(), Bin(ByteArray(0))), IsByteArrayEqual(byteArray(0x81, 0xa1, 0x76, 0xc4, 0x00)))
assertThat(MessagePack.parse(Bin.serializer(), byteArray(0x81, 0xa1, 0x76, 0xc4, 0x00)).v, IsByteArrayEqual(ByteArray(0)))
assertThat(MessagePack.parse(Bin.serializer(), byteArray(0x81, 0xa1, 0x76, 0xc5, 0x00, 0x00)).v, IsByteArrayEqual(ByteArray(0)))
assertThat(MessagePack.parse(Bin.serializer(), byteArray(0x81, 0xa1, 0x76, 0xc6, 0x00, 0x00, 0x00, 0x00)).v, IsByteArrayEqual(ByteArray(0)))
}
@Test
fun nonEmpty() {
val payload = byteArray(0x00, 0xff)
assertThat(MessagePack.pack(Bin.serializer(), Bin(payload)), IsByteArrayEqual(byteArray(0x81, 0xa1, 0x76, 0xc4, 0x02) + payload))
assertThat(MessagePack.parse(Bin.serializer(), byteArray(0x81, 0xa1, 0x76, 0xc4, 0x02) + payload).v, IsByteArrayEqual(payload))
assertThat(MessagePack.parse(Bin.serializer(), byteArray(0x81, 0xa1, 0x76, 0xc5, 0x00, 0x02) + payload).v, IsByteArrayEqual(payload))
assertThat(MessagePack.parse(Bin.serializer(), byteArray(0x81, 0xa1, 0x76, 0xc6, 0x00, 0x00, 0x00, 0x02) + payload).v, IsByteArrayEqual(payload))
}
}
*/
| 0
|
Kotlin
|
0
| 7
|
e19ec31ce50c40d7e8ad54dce8af24544d9cf00c
| 1,301
|
kotlinx.serialization.msgpack
|
Apache License 2.0
|
app/src/main/java/com/example/swol/ui/ExerciseSearchAdapter.kt
|
bharath-temp
| 800,681,930
| false
|
{"Kotlin": 40254}
|
package com.example.swol.ui
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.swol.R
import com.example.swol.data.Datapoint
import com.google.android.material.card.MaterialCardView
class ExerciseSearchAdapter(private var datapoints: List<Datapoint>):
RecyclerView.Adapter<ExerciseSearchAdapter.ViewHolder>() {
private var selectedPosition = RecyclerView.NO_POSITION
private var selectedItem: Datapoint? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.search_exercise_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val isSelected = position == selectedPosition
holder.bind(datapoints[position], isSelected)
holder.itemView.isSelected = position == selectedPosition
holder.itemView.setOnClickListener {
val previousSelectedPosition = selectedPosition
selectedPosition = holder.adapterPosition
selectedItem = datapoints[selectedPosition]
notifyItemChanged(previousSelectedPosition)
notifyItemChanged(selectedPosition)
}
}
fun getSelectedItem(): Datapoint? = selectedItem
fun updateExercises(newData: List<Datapoint>?) {
datapoints = newData ?: listOf()
notifyDataSetChanged()
}
override fun getItemCount(): Int = datapoints.size
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val nameTextView: TextView = view.findViewById(R.id.tv_name)
private val categoryTextView: TextView = view.findViewById(R.id.tv_category)
private val cardView: MaterialCardView = view as MaterialCardView
fun bind(exercise: Datapoint, isSelected: Boolean) {
nameTextView.text = exercise.name
categoryTextView.text = exercise.category
if (isSelected) {
cardView.setCardBackgroundColor(cardView.context.getColor(R.color.selected_item_background))
} else {
cardView.setCardBackgroundColor(cardView.context.getColor(android.R.color.transparent))
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fa9e0a6269ca885de248d426c368fa0bafa72ae0
| 2,380
|
Swol
|
MIT License
|
app/src/main/java/com/almazov/diacompanion/settings/SettingsAppType.kt
|
AndreyCKDS
| 538,835,857
| false
| null |
package com.almazov.diacompanion.settings
import android.content.SharedPreferences
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.almazov.diacompanion.R
import com.almazov.diacompanion.meal.AppTypeAdapter
import com.almazov.diacompanion.meal.FoodInMealListAdapter
import kotlinx.android.synthetic.main.fragment_settings_account.view.*
import kotlinx.android.synthetic.main.fragment_settings_app_type.*
import kotlinx.android.synthetic.main.fragment_settings_app_type.view.*
import kotlinx.android.synthetic.main.fragment_settings_app_type.view.btn_save
class SettingsAppType : Fragment(), AppTypeAdapter.InterfaceAppType {
private lateinit var sharedPreferences: SharedPreferences
private var appType: String? = "PCOS"
lateinit var adapter: AppTypeAdapter
private val appTypes = listOf(
AppType(R.string.GDMRCT,"GDMRCT", R.string.GDMRCTDescription),
AppType(R.string.GDM,"GDM", R.string.GDMDescription),
AppType(R.string.MS,"MS", R.string.MSDescription),
AppType(R.string.PCOS,"PCOS", R.string.PCOSDescription))
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
val view = inflater.inflate(R.layout.fragment_settings_app_type, container, false)
appType = sharedPreferences.getString("APP_TYPE","PCOS")
val finished: Boolean = sharedPreferences.getBoolean("ON_BOARDING_FINISHED", false)
if (finished) {
view.btn_save.setOnClickListener {
saveChanges()
findNavController().popBackStack()
}
} else {
view.btn_save.setOnClickListener {
saveChanges()
findNavController().navigate(R.id.action_settingsAppType_to_settingsAccount)
}
}
adapter = AppTypeAdapter(this, appTypes)
view.recycler_view_app_type.adapter = adapter
view.recycler_view_app_type.layoutManager = LinearLayoutManager(requireContext())
adapter.updateItems(appType!!)
return view
}
private fun saveChanges() {
sharedPreferences.edit().apply{
putString("APP_TYPE",appType)
}?.apply()
}
override fun selectAppType(position: Int) {
appType = appTypes[position].name
adapter.updateItems(appType!!)
}
override fun getCurrentAppTypePosition(position: Int) {
tv_description.setText(appTypes[position].description)
}
}
| 0
|
Kotlin
|
1
| 2
|
c74aa3c09e08abfaa500c63bdcf3941089c77972
| 2,910
|
DIACompanion
|
Creative Commons Zero v1.0 Universal
|
component-service/src/main/java/com/llj/component/service/vo/CityVo.kt
|
P79N6A
| 196,151,573
| true
|
{"C": 7521582, "Java": 2108145, "Shell": 2011215, "C++": 760737, "M4": 416795, "Kotlin": 402736, "Makefile": 379383, "Objective-C": 221330, "Roff": 192501, "Groovy": 59752, "Batchfile": 34559, "HTML": 31121, "GLSL": 23043, "sed": 17563, "CMake": 5799, "Assembly": 3886, "Python": 272}
|
package com.llj.component.service.vo
/**
* ArchitectureDemo.
* describe:
* author llj
* date 2018/10/17
*/
data class CityVo(var citySiteId: String?,
var cityName: String?,
var cityEname: String?,
var selected: Boolean,
var exhibitionCity: Int)
| 0
|
C
|
0
| 0
|
eb6a6d7c74d191e44262226f50b34a5de05fc079
| 323
|
ArchitectureDemo
|
Apache License 2.0
|
smartype-api/src/jsMain/kotlin/com.mparticle.smartype.api/MessageReceiver.kt
|
mParticle
| 263,459,744
| false
| null |
package com.mparticle.smartype.api
@JsExport
public actual external interface MessageReceiver {
@JsName("receive")
public actual fun receive(message: String)
}
| 26
| null |
4
| 38
|
153c7811914ff4909330f86a62a1805a3acdd6e2
| 169
|
smartype
|
Apache License 2.0
|
app/src/main/kotlin/com/base/di/component/AppComponent.kt
|
fachrifaul
| 121,081,350
| true
|
{"Kotlin": 33415}
|
package com.base.di.component
import android.app.Application
import android.content.res.Resources
import com.base.di.module.ApiModule
import com.base.di.module.AppModule
import com.base.di.module.OkHttpModule
import com.base.di.module.RetrofitModule
import com.base.helper.SpHelper
import com.base.util.AppSchedulerProvider
import com.burakeregar.githubsearch.api.Endpoints
import com.google.gson.Gson
import dagger.Component
import io.reactivex.disposables.CompositeDisposable
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import javax.inject.Singleton
/**
* Created by <NAME> on 19.05.2017.
* <EMAIL>
* https://github.com/burakeregar
*/
@Singleton
@Component(modules = [(AppModule::class), (RetrofitModule::class), (ApiModule::class), (OkHttpModule::class)])
interface AppComponent {
fun application(): Application
fun gson(): Gson
fun resources(): Resources
fun retrofit():Retrofit
fun endpoints():Endpoints
fun cache(): Cache
fun client(): OkHttpClient
fun loggingInterceptor(): HttpLoggingInterceptor
fun spHelper(): SpHelper
fun compositeDisposable(): CompositeDisposable
fun schedulerProvider(): AppSchedulerProvider
}
| 0
|
Kotlin
|
0
| 0
|
0e121c90e24e875877dc5d9a12e1f0334bfde120
| 1,250
|
KotlinRxMvpArchitecture
|
MIT License
|
korge-core/src/korlibs/korge/render/LineRenderBatcher.kt
|
korlibs
| 80,095,683
| false
| null |
@file:OptIn(KorgeInternal::class)
package korlibs.korge.render
import korlibs.datastructure.*
import korlibs.graphics.*
import korlibs.graphics.shader.*
import korlibs.image.color.*
import korlibs.io.async.*
import korlibs.korge.internal.*
import korlibs.korge.view.*
import korlibs.math.geom.*
import korlibs.math.geom.shape.*
import korlibs.math.geom.vector.*
import korlibs.memory.*
import kotlin.native.concurrent.*
/** Creates/gets a [LineRenderBatcher] associated to [this] [RenderContext] */
@Deprecated("USe useDebugLineRenderContext instead")
val RenderContext.debugLineRenderContext: LineRenderBatcher by Extra.PropertyThis<RenderContext, LineRenderBatcher> { LineRenderBatcher(this) }
@Suppress("DEPRECATION")
inline fun RenderContext.useLineBatcher(matrix: Matrix? = null, block: (LineRenderBatcher) -> Unit) = debugLineRenderContext.use { batcher ->
debugLineRenderContext.drawWithGlobalMatrix(matrix) {
block(batcher)
}
}
typealias DebugLineRenderContext = LineRenderBatcher
/**
* A context that allows to draw lines using [AG] (Accelerated Graphics).
*
* You should use it by calling:
*
* ctx.draw(matrix) {
* ctx.line(0, 0, 100, 100)
* ctx.line(100, 100, 0, 100)
* // ...
* }
*/
class LineRenderBatcher(
@property:KorgeInternal
val ctx: RenderContext
) {
inline fun use(block: (LineRenderBatcher) -> Unit) = ctx.useBatcher(this, block)
val beforeFlush = Signal<LineRenderBatcher>()
init {
ctx.flushers.add { flush() }
}
private val ag: AG = ctx.ag
var color: RGBA = Colors.YELLOW
companion object {
val LAYOUT = VertexLayout(DefaultShaders.a_Pos, DefaultShaders.a_Col)
val VERTEX = VertexShader {
DefaultShaders.apply {
SET(out, (u_ProjMat * u_ViewMat) * vec4(a_Pos, 0f.lit, 1f.lit))
SET(v_Col, a_Col)
}
}
val FRAGMENT = FragmentShader {
DefaultShaders.apply {
//SET(out, vec4(1f.lit, 1f.lit, 0f.lit, 1f.lit))
SET(out, v_Col)
}
}
val PROGRAM = Program(VERTEX, FRAGMENT)
}
private val vertexBuffer = AGBuffer()
private val vertexData = AGVertexArrayObject(AGVertexData(LAYOUT, vertexBuffer), isDynamic = false)
private val maxVertexCount = 1024
private val vertices = Buffer.allocDirect(6 * 4 * maxVertexCount)
@PublishedApi
internal var viewMat = Matrix4()
@PublishedApi
internal var vertexCount = 0
@PublishedApi
internal var vertexPos = 0
fun line(p0: Point, p1: Point, color0: RGBA = color, color1: RGBA = color0, m: Matrix = currentMatrix) =
line(p0.x, p0.y, p1.x, p1.y, color, color1, m)
/** Draw a line from [x0],[y0] to [x1],[y1] */
fun line(x0: Float, y0: Float, x1: Float, y1: Float, color0: RGBA = color, color1: RGBA = color0, m: Matrix = currentMatrix) {
if (vertexCount >= maxVertexCount - 2) {
flush()
}
addVertex(x0, y0, color0, m)
addVertex(x1, y1, color1, m)
}
fun line(x0: Double, y0: Double, x1: Double, y1: Double, color0: RGBA = color, color1: RGBA = color0, m: Matrix = currentMatrix) = line(x0.toFloat(), y0.toFloat(), x1.toFloat(), y1.toFloat(), color0, color1, m)
fun line(x0: Int, y0: Int, x1: Int, y1: Int, color0: RGBA = color, color1: RGBA = color0, m: Matrix = currentMatrix) = line(x0.toFloat(), y0.toFloat(), x1.toFloat(), y1.toFloat(), color0, color1, m)
fun drawVector(path: VectorPath, m: Matrix = currentMatrix) {
var lastPos = Point()
path.emitPoints2 { p, move ->
if (!move) {
line(lastPos, p, m = m)
}
lastPos = p
}
}
inline fun drawVector(m: Matrix = currentMatrix, block: VectorBuilder.() -> Unit) {
drawVector(VectorPath().apply(block), m = m)
}
inline fun drawVector(color: RGBA, m: Matrix = currentMatrix, block: VectorBuilder.() -> Unit) {
color(color) {
drawVector(m, block)
}
}
/** Prepares for drawing a set of lines with the specified [matrix]. It flushes all other contexts, and the set [matrix]. */
inline fun <T> draw(matrix: Matrix, body: () -> T): T {
ctx.flush()
return keep(this::viewMat) {
viewMat = matrix.toMatrix4()
try {
body()
} finally {
flush()
}
}
}
var blendMode: BlendMode = BlendMode.NORMAL
inline fun <T> blending(blending: BlendMode, block: () -> T): T {
val doUpdate = this.blendMode !== blending
val old = this.blendMode
try {
if (doUpdate) {
ctx.flush()
this.blendMode = blending
}
return block()
} finally {
if (doUpdate) {
ctx.flush()
}
this.blendMode = old
}
}
/** Actually flushes all the pending lines. Shouldn't be called manually. You should call the [draw] method instead. */
@KorgeInternal
fun flush() {
//println("BLENDING=$blending")
if (vertexCount > 0) {
beforeFlush(this)
vertexBuffer.upload(vertices, 0, vertexPos * 4)
ctx.updateStandardUniforms()
//projMat.setToOrtho(tempRect.setBounds(0, 0, ag.backWidth, ag.backHeight), -1f, 1f)
ag.draw(
ctx.currentFrameBuffer,
vertexData,
program = PROGRAM,
drawType = AGDrawType.LINES,
vertexCount = vertexCount,
uniformBlocks = ctx.createCurrentUniformsRef(PROGRAM),
//textureUnits = ctx.textureUnits.clone(),
blending = blendMode.factors
)
}
vertexCount = 0
vertexPos = 0
}
@PublishedApi
internal var currentMatrix: Matrix = Matrix()
inline fun <T> drawWithGlobalMatrix(matrix: Matrix?, block: () -> T): T = keep(::currentMatrix) {
if (matrix != null) currentMatrix = matrix
block()
}
private fun addVertex(x: Float, y: Float, color: RGBA = this.color, m: Matrix = currentMatrix) {
vertices.setFloat32(vertexPos + 0, m.transformX(x, y))
vertices.setFloat32(vertexPos + 1, m.transformY(x, y))
vertices.setInt32(vertexPos + 2, color.value)
vertexPos += LAYOUT.totalSize / Int.SIZE_BYTES
vertexCount++
}
inline fun color(color: RGBA, block: () -> Unit) {
val oldColor = this.color
this.color = color
try {
block()
} finally {
this.color = oldColor
}
}
}
| 464
| null |
123
| 2,497
|
1a565007ab748e00a4d602fcd78f7d4032afaf0b
| 6,710
|
korge
|
Apache License 2.0
|
app/src/main/java/com/atakan/mainclient/service/MessengerService.kt
|
atakanakin
| 677,016,019
| false
| null |
package com.atakan.mainclient.service
import android.R
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.os.Process
import android.os.RemoteException
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.lifecycle.Observer
import com.atakan.mainclient.common.Constants.CURR1
import com.atakan.mainclient.common.Constants.CURR2
import com.atakan.mainclient.common.Constants.CURR3
import com.atakan.mainclient.common.Constants.PACKAGE_NAME
import com.atakan.mainclient.common.Constants.PID
import com.atakan.mainclient.common.Constants.RATE1
import com.atakan.mainclient.common.Constants.RATE2
import com.atakan.mainclient.common.Constants.RATE3
import com.atakan.mainclient.common.Constants.TIME
import com.atakan.mainclient.common.Resource
import com.atakan.mainclient.domain.model.Currency
import com.atakan.mainclient.domain.use_case.GetCurrencyUseCase
import com.atakan.mainclient.presentation.MainActivity
import com.atakan.mainclient.presentation.currency.CurrencyViewModel
import com.atakan.mainclient.presentation.currency.screen.ServiceViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import javax.inject.Inject
@AndroidEntryPoint
class MessengerService : Service(){
@Inject
lateinit var getCurrencyUseCase: GetCurrencyUseCase
// Get viewModel instance
@Inject
lateinit var viewModel: CurrencyViewModel
@Inject
lateinit var clickViewModel: ServiceViewModel
var sendMessage: Boolean = false
private var serverMessenger: Messenger? = null
// Messenger on the client
private var clientMessenger: Messenger? = null
// Service Connection
private val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
// Called when the connection to the server service is established
serverMessenger = Messenger(service)
clientMessenger = Messenger(handler)
sendMessageToServer()
}
override fun onServiceDisconnected(name: ComponentName?) {
// Called when the connection to the server service is disconnected
serverMessenger = null
clientMessenger = null
}
}
// Handle messages from the remote service (server app)
var handler: Handler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
// Update UI with remote process info
val bundle = msg.data
//val serverClass = Serverprop(bundle.getInt(PID).toString(), bundle.getInt(
// CONNECTION_COUNT).toString())
//serverprop.serverData.postValue(serverClass)
}
}
private val clickObserver = Observer<Boolean> {
if(it){
try {
doBindService()
}
catch (e : Exception){
Log.w("MessengerError", e.toString())
val LaunchIntent = packageManager.getLaunchIntentForPackage("com.atakan.mainserver")
runBlocking {
startActivity(LaunchIntent)
delay(2000)
}
Log.w("Messenger", "Trying to wake up Server App")
try {
doBindService()
}catch (e : Exception){
Log.w("MessengerError", e.toString())
}
}
}
else{
try {
doUnbindService()
}catch (e : Exception){
// First Start
}
}
}
val apiHandler = Handler()
private val apiRunnable = object : Runnable {
override fun run() {
// Make the API call and update viewModel with the response data
Log.d("Messenger", "Fetching data from API")
val job = CoroutineScope(Dispatchers.IO).launch {
getCurrencyUseCase.invoke().collect{
when (it) {
is Resource.Success -> {
// Update viewModel with the fetched resource
viewModel.refreshData(it)
}
is Resource.Loading -> {
//
}
is Resource.Error -> {
// Handle error state if needed
println("Error: ${it.message}")
}
}
}
}
// Make sure to cancel the coroutine when the service is stopped
job.invokeOnCompletion {
if (it != null) {
Log.e("Messenger Error","Coroutine completed with an exception: ${it.message}")
} else {
//
}
}
if(sendMessage){
sendMessageToServer()
}
// Repeat this process every minute
apiHandler.postDelayed(this, 5000)
}
}
override fun onBind(p0: Intent?): IBinder? {
// ?
return null
}
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Foreground Service Channel"
val descriptionText = "Foreground service channel description"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("ForegroundServiceChannel", name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
// Start the service as a foreground service with a notification
val notification = createNotification() // Implement the createNotification() method
startForeground(2, notification)
clickViewModel.isServiceConnected.observeForever(clickObserver)
}
private fun createNotification(): Notification {
// Create and return the notification for the foreground service
// You can customize the notification as needed
// For example:
val notificationTitle = "Messenger Service"
val notificationText = "Service is running in the background"
val pendingIntent = PendingIntent.getActivity(
this,
0,
Intent(this, MainActivity::class.java).apply {
// Add the extra value for fragment identification
//putExtra("FRAGMENT_ID", R.id.navigation_messenger)
},
PendingIntent.FLAG_IMMUTABLE
)
return NotificationCompat.Builder(this, "ForegroundServiceChannel")
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setSmallIcon(R.drawable.ic_dialog_alert)
.setContentIntent(pendingIntent)
.build()
}
override fun onDestroy() {
apiHandler.removeCallbacks(apiRunnable)
doUnbindService()
clickViewModel.isServiceConnected.removeObserver(clickObserver)
// Stop the foreground service and remove the notification
stopForeground(true)
super.onDestroy()
}
// Start service according to the button
private fun doBindService(){
if(sendMessage){
Log.d("Messenger", "ALREADY connected")
return
}
// Start the server service
Intent("messenger").also { intent ->
intent.`package` = "com.atakan.mainserver"
startService(intent)
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
Log.d("Messenger", "SUCCESSFULLY connected")
sendMessage = true
}
// Stop service activity according to the button activity
private fun doUnbindService(){
if(sendMessage){
sendMessage = false
try {
unbindService(serviceConnection)
Log.d("Messenger", "SUCCESSFULLY disconnected")
}catch (e : Exception)
{
Log.w("Messenger", e.toString())
}
}
else{
try {
unbindService(serviceConnection)
} catch (e: Exception){
Log.e("Messenger", "Failed to disconnect.")
}
}
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
// Start the periodic API calls and send data if the service is bounded
apiHandler.post(apiRunnable)
return START_STICKY
}
override fun onTaskRemoved(rootIntent: Intent) {
Log.d("Messenger", "Task Removed, Restarting Service")
apiHandler.removeCallbacks(apiRunnable)
val restartServiceIntent = Intent(applicationContext, this.javaClass)
restartServiceIntent.setPackage(packageName)
startService(restartServiceIntent)
super.onTaskRemoved(rootIntent)
}
private fun sendMessageToServer(){
if (serverMessenger == null) {
// Server service connection is lost or not available
Log.e("Messenger", "Server service connection lost. Cannot send message.")
return
}
val message = Message.obtain(handler)
val bundle = Bundle()
when (val resource: Resource<Currency>? = viewModel.currencyLiveData.value) {
is Resource.Success -> {
Log.d("Messenger", "Sending Data")
val currencyData: Currency = resource.data!!
bundle.putString(CURR1, currencyData?.bpi?.USD?.code)
bundle.putString(CURR2, currencyData?.bpi?.EUR?.code)
bundle.putString(CURR3, currencyData?.bpi?.GBP?.code)
bundle.putDouble(RATE1, currencyData?.bpi?.USD?.rate_float?.toDouble()!!)
bundle.putDouble(RATE2, currencyData?.bpi?.EUR?.rate_float?.toDouble()!!)
bundle.putDouble(RATE3, currencyData?.bpi?.GBP?.rate_float?.toDouble()!!)
bundle.putString(TIME, currencyData?.time?.updated)
bundle.putString(PACKAGE_NAME, applicationContext.packageName)
bundle.putInt(PID, Process.myPid())
message.data = bundle
message.replyTo = clientMessenger //for communication to be two-way
try {
serverMessenger?.send(message)
} catch (e: RemoteException) {
e.printStackTrace()
} finally {
message.recycle()
}
}
is Resource.Loading -> {
Log.d("Messenger", "Loading")
}
is Resource.Error -> {
Log.e("Messenger", "Unexpecte error occurred.")
}
else -> {
Log.w("Messenger", "Null")
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
33db39aaa9cb827f9a3316dda3d37c33b7494af2
| 11,756
|
Client
|
MIT License
|
data/src/main/kotlin/data/tinder/like/Match.kt
|
stoyicker
| 291,049,724
| false
|
{"Java": 646382, "Kotlin": 423127, "Shell": 885}
|
package data.tinder.like
import com.squareup.moshi.Json
// A bunch of other fields come in the model. Add them as needed for tracking purposes
internal data class Match private constructor(@field:Json(name = "id") private val id: String)
| 1
| null |
1
| 1
|
fecfefd7a64dc8c9397343850b9de4d52117b5c3
| 240
|
dinger-unpublished
|
MIT License
|
core/data/src/main/java/com/tamzi/speakers/core/data/repository/OfflineFirstUserDataRepository.kt
|
tamzi
| 633,718,475
| false
| null |
/*
* 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
*
* 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.tamzi.speakers.core.data.repository
import androidx.annotation.VisibleForTesting
import com.tamzi.speakers.core.analytics.AnalyticsHelper
import com.tamzi.speakers.core.datastore.SpeakerPreferencesDataSource
import com.tamzi.speakers.core.model.data.DarkThemeConfig
import com.tamzi.speakers.core.model.data.ThemeBrand
import com.tamzi.speakers.core.model.data.UserData
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class OfflineFirstUserDataRepository @Inject constructor(
private val speakerPreferencesDataSource: SpeakerPreferencesDataSource,
private val analyticsHelper: AnalyticsHelper,
) : UserDataRepository {
override val userData: Flow<UserData> =
speakerPreferencesDataSource.userData
@VisibleForTesting
override suspend fun setFollowedTopicIds(followedTopicIds: Set<String>) =
speakerPreferencesDataSource.setFollowedTopicIds(followedTopicIds)
override suspend fun toggleFollowedTopicId(followedTopicId: String, followed: Boolean) {
speakerPreferencesDataSource.toggleFollowedTopicId(followedTopicId, followed)
analyticsHelper.logTopicFollowToggled(followedTopicId, followed)
}
override suspend fun updateNewsResourceBookmark(newsResourceId: String, bookmarked: Boolean) {
speakerPreferencesDataSource.toggleNewsResourceBookmark(newsResourceId, bookmarked)
analyticsHelper.logNewsResourceBookmarkToggled(
newsResourceId = newsResourceId,
isBookmarked = bookmarked,
)
}
override suspend fun setNewsResourceViewed(newsResourceId: String, viewed: Boolean) =
speakerPreferencesDataSource.setNewsResourceViewed(newsResourceId, viewed)
override suspend fun setThemeBrand(themeBrand: ThemeBrand) {
speakerPreferencesDataSource.setThemeBrand(themeBrand)
analyticsHelper.logThemeChanged(themeBrand.name)
}
override suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) {
speakerPreferencesDataSource.setDarkThemeConfig(darkThemeConfig)
analyticsHelper.logDarkThemeConfigChanged(darkThemeConfig.name)
}
override suspend fun setDynamicColorPreference(useDynamicColor: Boolean) {
speakerPreferencesDataSource.setDynamicColorPreference(useDynamicColor)
analyticsHelper.logDynamicColorPreferenceChanged(useDynamicColor)
}
override suspend fun setShouldHideOnboarding(shouldHideOnboarding: Boolean) {
speakerPreferencesDataSource.setShouldHideOnboarding(shouldHideOnboarding)
analyticsHelper.logOnboardingStateChanged(shouldHideOnboarding)
}
}
| 0
|
Kotlin
|
0
| 0
|
e89849386575462b23029fc1961faad1217e3ed2
| 3,250
|
speakers
|
Apache License 2.0
|
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/objs/pottery/pottery_oven.plugin.kts
|
2011Scape
| 578,880,245
| false
|
{"Kotlin": 8359518, "Dockerfile": 1354}
|
package gg.rsmod.plugins.content.objs.pottery
import gg.rsmod.plugins.content.skills.crafting.pottery.FirePotteryAction
import gg.rsmod.plugins.content.skills.crafting.pottery.PotteryData
val POTTERY_OVEN = listOf(Objs.POTTERY_OVEN, Objs.POTTERY_OVEN_11601, Objs.POTTERY_OVEN_3198, Objs.POTTERY_OVEN_4308, Objs.POTTERY_OVEN_34802, Objs.POTTERY_OVEN_5087, Objs.POTTERY_OVEN_61334)
val potteryData = PotteryData.values
val unfiredPottery = potteryData.flatMap { it.products.toList() }
POTTERY_OVEN.forEach {
on_obj_option(obj = it, option = "fire") {
handlePotteryOven(player)
}
unfiredPottery.filterNot { data -> data.fired == -1 }.forEach { unfiredUrn ->
val urn = unfiredUrn.unfired
on_item_on_obj(obj = it, item = urn) {
handlePotteryOven(player, urn)
}
}
}
fun handlePotteryOven(player: Player, itemUsed: Int? = null) {
val inventory = player.inventory
val unfiredList = mutableListOf<Int>()
if (itemUsed == null) {
val def = player.world.definitions
inventory.rawItems.filter {
it?.getName(def)?.lowercase()?.contains("(unf)") == true
|| it?.getName(def)?.contains("unfired", ignoreCase = true) == true }
.forEach {
if (!unfiredList.contains(it?.id))
unfiredList.add(it!!.id)
}
if (unfiredList.isEmpty()) {
player.message("You don't have any unfired items in your inventory.")
return
}
player.queue {
produceItemBox(*unfiredList.toIntArray(), logic = ::firePottery)
}
} else {
player.queue {
produceItemBox(itemUsed, maxItems = inventory.getItemCount(itemUsed), logic = ::firePottery)
}
}
}
fun firePottery(player: Player, item: Int, amount: Int) {
val def = PotteryData.findPotteryItemByItem(item)!!
player.queue { FirePotteryAction.firePottery(this, def, amount) }
}
| 36
|
Kotlin
|
138
| 32
|
da66bb6d68ebae531ee325b909a6536e798b1144
| 1,971
|
game
|
Apache License 2.0
|
verik-compiler/src/test/kotlin/io/verik/compiler/test/CoreDeclarationTest.kt
|
frwang96
| 269,980,078
| false
| null |
/*
* Copyright (c) 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
*
* 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 io.verik.compiler.test
import io.verik.compiler.ast.element.common.EAbstractContainerClass
import io.verik.compiler.ast.element.common.EAbstractProperty
import io.verik.compiler.ast.element.common.EDeclaration
import io.verik.compiler.ast.element.common.EFile
import io.verik.compiler.ast.element.common.EReceiverExpression
import io.verik.compiler.ast.element.sv.EAbstractContainerComponent
import io.verik.compiler.common.TreeVisitor
import io.verik.compiler.core.common.CoreDeclaration
import io.verik.compiler.main.ProjectContext
import io.verik.compiler.main.StageSequencer
import io.verik.compiler.main.StageType
import org.intellij.lang.annotations.Language
abstract class CoreDeclarationTest : BaseTest() {
fun driveCoreDeclarationTest(
coreDeclarations: List<CoreDeclaration>,
@Language("kotlin") content: String,
expected: String
) {
val projectContext = getProjectContext(content)
val stageSequence = StageSequencer.getStageSequence()
stageSequence.processUntil(projectContext, StageType.PRE_TRANSFORM)
checkCoreDeclarations(coreDeclarations, projectContext)
stageSequence.processUntil(projectContext, StageType.POST_CHECK)
projectContext.project.accept(PropertyEliminatorVisitor)
stageSequence.processAll(projectContext)
val basicPackageTextFiles = projectContext.outputContext.basicPackageTextFiles
val rootPackageTextFiles = projectContext.outputContext.rootPackageTextFiles
when {
basicPackageTextFiles.size + rootPackageTextFiles.size > 1 ->
throw IllegalArgumentException("Multiple source files generated")
basicPackageTextFiles.size + rootPackageTextFiles.size == 0 ->
throw IllegalArgumentException("No source files generated")
basicPackageTextFiles.size == 1 ->
assertOutputTextEquals(expected, basicPackageTextFiles[0])
rootPackageTextFiles.size == 1 ->
assertOutputTextEquals(expected, rootPackageTextFiles[0])
}
}
private fun checkCoreDeclarations(coreDeclarations: List<CoreDeclaration>, projectContext: ProjectContext) {
val coreDeclarationIndexerVisitor = CoreDeclarationIndexerVisitor()
projectContext.project.accept(coreDeclarationIndexerVisitor)
coreDeclarations.forEach {
assert(it in coreDeclarationIndexerVisitor.coreDeclarations) {
"Core declaration not found: ${it.signature}"
}
}
}
private class CoreDeclarationIndexerVisitor : TreeVisitor() {
val coreDeclarations = HashSet<CoreDeclaration>()
override fun visitReceiverExpression(receiverExpression: EReceiverExpression) {
super.visitReceiverExpression(receiverExpression)
val reference = receiverExpression.reference
if (reference is CoreDeclaration)
coreDeclarations.add(reference)
}
}
private object PropertyEliminatorVisitor : TreeVisitor() {
override fun visitFile(file: EFile) {
super.visitFile(file)
file.declarations = eliminateProperties(file.declarations)
}
override fun visitAbstractContainerClass(abstractContainerClass: EAbstractContainerClass) {
super.visitAbstractContainerClass(abstractContainerClass)
abstractContainerClass.declarations = eliminateProperties(abstractContainerClass.declarations)
}
override fun visitAbstractContainerComponent(abstractContainerComponent: EAbstractContainerComponent) {
super.visitAbstractContainerComponent(abstractContainerComponent)
abstractContainerComponent.declarations = eliminateProperties(abstractContainerComponent.declarations)
}
private fun eliminateProperties(declarations: ArrayList<EDeclaration>): ArrayList<EDeclaration> {
return ArrayList(declarations.filter { it !is EAbstractProperty })
}
}
}
| 0
|
Kotlin
|
1
| 7
|
a40d6195f3b57bebac813b3e5be59d17183433c7
| 4,620
|
verik
|
Apache License 2.0
|
replica-core/src/commonMain/kotlin/me/aartikov/replica/keyed/BulkOperations.kt
|
aartikov
| 438,253,231
| false
|
{"HTML": 3233987, "Kotlin": 685239, "CSS": 29063, "JavaScript": 19875}
|
package me.aartikov.replica.keyed
import me.aartikov.replica.common.InvalidationMode
import me.aartikov.replica.common.ReplicaTag
/**
* Cancels network requests in all child replicas.
*/
suspend fun <K : Any, T : Any> KeyedPhysicalReplica<K, T>.cancelAll() {
onEachReplica {
cancel()
}
}
/**
* Makes all child replicas stale.
*
* @param mode specifies how replicas behave after invalidation. See: [InvalidationMode].
*/
suspend fun <K : Any, T : Any> KeyedPhysicalReplica<K, T>.invalidateAll(
mode: InvalidationMode = InvalidationMode.RefreshIfHasObservers
) {
onEachReplica {
invalidate(mode)
}
}
/**
* Cancels network requests in child replicas with the matching tags.
*/
suspend fun <K : Any, T : Any> KeyedPhysicalReplica<K, T>.cancelByTags(
predicate: (Set<ReplicaTag>) -> Boolean
) {
if (predicate(tags)) {
cancelAll()
return
}
onEachReplica {
if (predicate(tags)) {
cancel()
}
}
}
/**
* Cancels network requests and clears data in child replicas with the matching tags.
*/
suspend fun <K : Any, T : Any> KeyedPhysicalReplica<K, T>.clearByTags(
predicate: (Set<ReplicaTag>) -> Boolean
) {
if (predicate(tags)) {
clearAll()
return
}
onEachReplica {
if (predicate(tags)) {
clear()
}
}
}
/**
* Makes child replicas with the matching tags stale.
*
* @param mode specifies how replicas behave after invalidation. See: [InvalidationMode].
*/
suspend fun <K : Any, T : Any> KeyedPhysicalReplica<K, T>.invalidateByTags(
mode: InvalidationMode = InvalidationMode.RefreshIfHasObservers,
predicate: (Set<ReplicaTag>) -> Boolean
) {
if (predicate(tags)) {
invalidateAll(mode)
return
}
onEachReplica {
if (predicate(tags)) {
invalidate(mode)
}
}
}
| 0
|
HTML
|
1
| 33
|
dc55d0cb727b6854224ceb8b1a1d0d87c7faaddf
| 1,895
|
Replica
|
MIT License
|
moshimoshi/src/main/java/com/moshimoshi/network/entities/Tokens.kt
|
fsalom
| 745,398,229
| false
|
{"Kotlin": 46372}
|
package com.moshimoshi.network.entities
import java.io.Serializable
data class Tokens (
val accessToken: Token,
val refreshToken: Token?
): Serializable
| 0
|
Kotlin
|
0
| 1
|
ec4ff937e917588ea84a932ce54365ae8e49e3a8
| 162
|
moshimoshi
|
MIT License
|
AlsatIPGAndroid/src/main/java/com/alsatpardakht/alsatipgandroid/AlsatIPG.kt
|
AlsatPardakht
| 457,700,165
| false
| null |
package com.alsatpardakht.alsatipgandroid
import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.alsatpardakht.alsatipgandroid.util.asFlow
import com.alsatpardakht.alsatipgandroid.util.getDecodedQueryValueByKey
import com.alsatpardakht.alsatipgcore.core.util.Resource
import com.alsatpardakht.alsatipgcore.data.remote.IPGServiceImpl
import com.alsatpardakht.alsatipgcore.domain.model.TashimModel
import com.alsatpardakht.alsatipgcore.domain.model.PaymentType
import com.alsatpardakht.alsatipgcore.data.remote.util.URLConstant.GO_ROUTE
import com.alsatpardakht.alsatipgcore.data.remote.util.appendQuery
import com.alsatpardakht.alsatipgcore.data.repository.IPGRepositoryImpl
import com.alsatpardakht.alsatipgcore.domain.model.PaymentSignResult
import com.alsatpardakht.alsatipgcore.domain.model.PaymentValidationResult
import com.alsatpardakht.alsatipgcore.domain.use_case.PaymentSignUseCase
import com.alsatpardakht.alsatipgcore.domain.use_case.PaymentValidationUseCase
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.features.json.*
import io.ktor.client.features.json.serializer.*
import io.ktor.client.features.logging.*
import io.ktor.client.features.logging.Logger
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
class AlsatIPG private constructor(private val httpLogging: Boolean) {
private val httpClient = HttpClient(CIO) {
if (httpLogging) install(Logging) {
logger = Logger.DEFAULT
level = LogLevel.ALL
}
install(JsonFeature) {
serializer = KotlinxSerializer()
}
}
private val iPGService = IPGServiceImpl(httpClient)
private val iPGRepository = IPGRepositoryImpl(iPGService)
private val paymentSignUseCase = PaymentSignUseCase(iPGRepository)
private val paymentValidationUseCase = PaymentValidationUseCase(iPGRepository)
private val _paymentSignStatus: MutableLiveData<PaymentSignResult> = MutableLiveData()
val paymentSignStatus: LiveData<PaymentSignResult> = _paymentSignStatus
@ExperimentalCoroutinesApi
val paymentSignStatusAsFlow = paymentSignStatus.asFlow()
private val _paymentValidationStatus: MutableLiveData<PaymentValidationResult> =
MutableLiveData()
val paymentValidationStatus: LiveData<PaymentValidationResult> = _paymentValidationStatus
@ExperimentalCoroutinesApi
val paymentValidationStatusAsFlow = paymentValidationStatus.asFlow()
companion object {
@Volatile
private var instance: AlsatIPG? = null
@JvmStatic
@Synchronized
fun getInstance(httpLogging: Boolean = false): AlsatIPG {
return instance ?: AlsatIPG(httpLogging).also {
instance = it
}
}
}
private fun sign(
Amount: Long,
Api: String,
RedirectAddress: String,
InvoiceNumber: String = "",
Type: PaymentType,
Tashim: List<TashimModel>
): LiveData<PaymentSignResult> {
CoroutineScope(Dispatchers.Default).launch {
paymentSignUseCase.execute(
Amount = Amount,
Api = Api,
InvoiceNumber = InvoiceNumber,
RedirectAddress = RedirectAddress,
Type = Type,
Tashim = Tashim
).collect {
when (it) {
is Resource.Success -> _paymentSignStatus.postValue(
PaymentSignResult(
isSuccessful = true,
url = GO_ROUTE.appendQuery("Token", it.data.Token)
)
)
is Resource.Loading -> _paymentSignStatus.postValue(PaymentSignResult(isLoading = true))
is Resource.Error -> _paymentSignStatus.postValue(PaymentSignResult(error = it.error))
}
}
}
return paymentSignStatus
}
fun signMostaghim(
Api: String,
Amount: Long,
InvoiceNumber: String,
RedirectAddress: String
) = sign(
Api = Api,
Amount = Amount,
InvoiceNumber = InvoiceNumber,
RedirectAddress = RedirectAddress,
Type = PaymentType.Mostaghim,
Tashim = emptyList()
)
fun signVaset(
Api: String,
Amount: Long,
RedirectAddress: String,
Tashim: List<TashimModel>,
InvoiceNumber: String = "",
) = sign(
Api = Api,
Amount = Amount,
InvoiceNumber = InvoiceNumber,
RedirectAddress = RedirectAddress,
Type = PaymentType.Vaset,
Tashim = Tashim
)
private fun validation(
Api: String,
tref: String,
iD: String,
iN: String,
Type: PaymentType,
PayId: String
): LiveData<PaymentValidationResult> {
CoroutineScope(Dispatchers.Default).launch {
paymentValidationUseCase.execute(
tref = tref,
iD = iD,
iN = iN,
Api = Api,
Type = Type
).collect {
when (it) {
is Resource.Success -> _paymentValidationStatus.postValue(
PaymentValidationResult(
isSuccessful = true,
data = it.data.copy(PayId = PayId)
)
)
is Resource.Loading -> _paymentValidationStatus.postValue(
PaymentValidationResult(isLoading = true)
)
is Resource.Error -> _paymentValidationStatus.postValue(
PaymentValidationResult(error = it.error)
)
}
}
}
return paymentValidationStatus
}
private fun validation(
Api: String,
data: Uri,
Type: PaymentType
) = validation(
Api = Api,
tref = data.getDecodedQueryValueByKey("tref"),
iN = data.getDecodedQueryValueByKey("iN"),
iD = data.getDecodedQueryValueByKey("iD"),
Type = Type,
PayId = data.getDecodedQueryValueByKey("PayId")
)
fun validationMostaghim(Api: String, data: Uri) = validation(
Api = Api,
data = data,
Type = PaymentType.Mostaghim
)
fun validationMostaghim(
Api: String, tref: String, iN: String, iD: String
) = validation(
Api = Api,
tref = tref,
iN = iN,
iD = iD,
Type = PaymentType.Mostaghim,
PayId = ""
)
fun validationMostaghim(
Api: String, tref: String, iN: String, iD: String, PayId: String
) = validation(
Api = Api,
tref = tref,
iN = iN,
iD = iD,
Type = PaymentType.Mostaghim,
PayId = PayId
)
fun validationVaset(Api: String, data: Uri) = validation(
Api = Api,
data = data,
Type = PaymentType.Vaset
)
fun validationVaset(
Api: String, tref: String, iN: String, iD: String
) = validation(
Api = Api,
tref = tref,
iN = iN,
iD = iD,
Type = PaymentType.Vaset,
PayId = ""
)
fun validationVaset(
Api: String, tref: String, iN: String, iD: String, PayId: String
) = validation(
Api = Api,
tref = tref,
iN = iN,
iD = iD,
Type = PaymentType.Vaset,
PayId = PayId
)
}
| 0
| null |
1
| 4
|
cb97540a9dc28730d64b9d4f136a98f8466432c5
| 7,582
|
AlsatIPGAndroid
|
MIT License
|
KotlinMultiplatform/XFullStack/composeApp/src/commonMain/kotlin/app/pages/directMessage/screen/DirectMessageScreen.kt
|
pradyotprksh
| 385,586,594
| false
|
{"Kotlin": 2713958, "Dart": 1066884, "Python": 319400, "Rust": 180589, "Swift": 147761, "C++": 113494, "CMake": 94132, "Go": 45704, "HTML": 21089, "Ruby": 12424, "C": 8043, "Shell": 5675, "PowerShell": 3045, "Nix": 2616, "Makefile": 1480, "JavaScript": 781, "CSS": 588, "Objective-C": 380, "Dockerfile": 32}
|
package app.pages.directMessage.screen
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Call
import androidx.compose.material.icons.filled.VideoCall
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import app.composables.LoadingDialogComposable
import app.composables.ProfileImageComposable
import app.pages.directMessage.viewModel.DirectMessageViewModel
import kotlinx.coroutines.launch
import utils.Localization
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun DirectMessageScreen(
directMessageViewModel: DirectMessageViewModel = viewModel { DirectMessageViewModel() },
userId: String?,
chatId: String?,
openProfileDetails: (String) -> Unit,
onNavigateBack: () -> Unit,
) {
LaunchedEffect(userId, chatId) {
directMessageViewModel.loadDetails(userId, chatId)
}
val scope = rememberCoroutineScope()
val replyFocusRequester = remember { FocusRequester() }
val snackbarHostState = remember { SnackbarHostState() }
val directMessageStateState by directMessageViewModel.directMessageStateState.collectAsState()
if (directMessageStateState.showLoading) {
LoadingDialogComposable()
}
directMessageStateState.snackBarMessage?.let { message ->
scope.launch {
val result = snackbarHostState.showSnackbar(
message = message,
actionLabel = Localization.OKAY,
duration = SnackbarDuration.Short
)
when (result) {
SnackbarResult.ActionPerformed, SnackbarResult.Dismissed -> {
directMessageViewModel.removeSnackBarMessage()
}
}
}
}
Scaffold(
topBar = {
TopAppBar(
navigationIcon = {
IconButton(
onClick = {},
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = Icons.AutoMirrored.Filled.ArrowBack.name,
)
}
},
title = {
directMessageStateState.userInfo?.let { userInfo ->
Row(
verticalAlignment = Alignment.CenterVertically,
) {
ProfileImageComposable(
profileImage = userInfo.profilePicture,
modifier = Modifier.size(30.dp),
)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = userInfo.name,
style = MaterialTheme.typography.titleMedium,
)
}
}
},
actions = {
IconButton(
onClick = {},
) {
Icon(
imageVector = Icons.Default.VideoCall,
contentDescription = Icons.Default.VideoCall.name,
)
}
IconButton(
onClick = {},
) {
Icon(
imageVector = Icons.Default.Call,
contentDescription = Icons.Default.Call.name,
)
}
}
)
}
) { paddingValues ->
val startEndPaddingModifier = Modifier.padding(
start = paddingValues.calculateStartPadding(LocalLayoutDirection.current) + 25.dp,
end = paddingValues.calculateEndPadding(LocalLayoutDirection.current) + 25.dp,
)
LazyColumn(
modifier = Modifier.fillMaxSize().padding(
top = paddingValues.calculateTopPadding(),
bottom = paddingValues.calculateBottomPadding(),
),
state = rememberLazyListState(),
) {
directMessageStateState.userInfo?.let { userInfo ->
item {
Column(
modifier = startEndPaddingModifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
) {
ProfileImageComposable(
profileImage = userInfo.profilePicture,
modifier = Modifier.size(60.dp),
)
Text(
text = userInfo.name,
style = MaterialTheme.typography.titleMedium,
)
Text(
text = userInfo.username,
style = MaterialTheme.typography.bodySmall,
)
userInfo.bio?.let { bio ->
Spacer(modifier = Modifier.height(10.dp))
Text(
text = bio,
)
}
Spacer(modifier = Modifier.height(10.dp))
Text(
text = "${userInfo.followers} ${Localization.FOLLOWERS}",
style = MaterialTheme.typography.bodySmall,
)
Spacer(modifier = Modifier.height(20.dp))
}
}
}
stickyHeader {
HorizontalDivider()
}
}
}
}
| 0
|
Kotlin
|
10
| 23
|
e003ba35035a71ba298212e56480ff6e395a6597
| 7,656
|
development_learning
|
MIT License
|
src/main/java/Version_Kotlin/SetMeal.kt
|
Bngel
| 310,322,584
| false
|
{"Java": 10799, "Kotlin": 8770}
|
package Version_Kotlin
class SetMeal(private val name: String, val price: Double, private val chicken: String, var drink: Drinks) {
override fun toString() = "SetMeal{" +
"name='" + name + '\'' +
", price=" + price +
", chicken='" + chicken + '\'' +
", drink=" + drink.javaClass.toString() +
'}'
}
| 1
| null |
1
| 1
|
ca10f9a5719acfe9fbae1dc67a705cb5d23e76f3
| 385
|
West2_2
|
Apache License 2.0
|
retroceptor-auth/src/test/java/io/github/ackeecz/retroceptor/MockedSharedPreferences.kt
|
AckeeCZ
| 178,363,424
| false
| null |
package io.github.ackeecz.retroceptor
import android.content.SharedPreferences
/**
* Mocked [SharedPreferences] used for testing.
*/
class MockedSharedPreferences : SharedPreferences, SharedPreferences.Editor {
private var values = mutableMapOf<String, Any?>()
private val tempValues = mutableMapOf<String, Any?>()
override fun edit(): SharedPreferences.Editor {
return this
}
override fun contains(key: String): Boolean {
return values.containsKey(key)
}
override fun getAll(): Map<String, *> {
return HashMap(values)
}
override fun getBoolean(key: String, defValue: Boolean): Boolean {
return if (values.containsKey(key)) {
(values[key] as Boolean)
} else defValue
}
override fun getFloat(key: String, defValue: Float): Float {
return if (values.containsKey(key)) {
(values[key] as Float).toFloat()
} else defValue
}
override fun getInt(key: String, defValue: Int): Int {
return if (values.containsKey(key)) {
(values[key] as Int).toInt()
} else defValue
}
override fun getLong(key: String, defValue: Long): Long {
return if (values.containsKey(key)) {
(values[key] as Long).toLong()
} else defValue
}
override fun getString(key: String, defValue: String?): String? {
return if (values.containsKey(key)) values[key] as String? else defValue
}
override fun getStringSet(key: String, defValues: Set<String>?): Set<String>? {
return if (values.containsKey(key)) {
values[key] as Set<String>?
} else defValues
}
override fun registerOnSharedPreferenceChangeListener(
listener: SharedPreferences.OnSharedPreferenceChangeListener
) {
throw UnsupportedOperationException()
}
override fun unregisterOnSharedPreferenceChangeListener(
listener: SharedPreferences.OnSharedPreferenceChangeListener
) {
throw UnsupportedOperationException()
}
override fun putBoolean(key: String, value: Boolean): SharedPreferences.Editor {
tempValues[key] = java.lang.Boolean.valueOf(value)
return this
}
override fun putFloat(key: String, value: Float): SharedPreferences.Editor {
tempValues[key] = value
return this
}
override fun putInt(key: String, value: Int): SharedPreferences.Editor {
tempValues[key] = value
return this
}
override fun putLong(key: String, value: Long): SharedPreferences.Editor {
tempValues[key] = value
return this
}
override fun putString(key: String, value: String?): SharedPreferences.Editor {
tempValues[key] = value
return this
}
override fun putStringSet(key: String, values: Set<String>?): SharedPreferences.Editor {
tempValues[key] = values
return this
}
override fun remove(key: String): SharedPreferences.Editor {
tempValues.remove(key)
return this
}
override fun clear(): SharedPreferences.Editor {
tempValues.clear()
return this
}
override fun commit(): Boolean {
values = tempValues.toMutableMap()
return true
}
override fun apply() {
commit()
}
}
| 1
|
Kotlin
|
0
| 2
|
5380df11f20580e55b6c622db30201f9f467c09f
| 3,326
|
retroceptor
|
Apache License 2.0
|
retroceptor-auth/src/test/java/io/github/ackeecz/retroceptor/MockedSharedPreferences.kt
|
AckeeCZ
| 178,363,424
| false
| null |
package io.github.ackeecz.retroceptor
import android.content.SharedPreferences
/**
* Mocked [SharedPreferences] used for testing.
*/
class MockedSharedPreferences : SharedPreferences, SharedPreferences.Editor {
private var values = mutableMapOf<String, Any?>()
private val tempValues = mutableMapOf<String, Any?>()
override fun edit(): SharedPreferences.Editor {
return this
}
override fun contains(key: String): Boolean {
return values.containsKey(key)
}
override fun getAll(): Map<String, *> {
return HashMap(values)
}
override fun getBoolean(key: String, defValue: Boolean): Boolean {
return if (values.containsKey(key)) {
(values[key] as Boolean)
} else defValue
}
override fun getFloat(key: String, defValue: Float): Float {
return if (values.containsKey(key)) {
(values[key] as Float).toFloat()
} else defValue
}
override fun getInt(key: String, defValue: Int): Int {
return if (values.containsKey(key)) {
(values[key] as Int).toInt()
} else defValue
}
override fun getLong(key: String, defValue: Long): Long {
return if (values.containsKey(key)) {
(values[key] as Long).toLong()
} else defValue
}
override fun getString(key: String, defValue: String?): String? {
return if (values.containsKey(key)) values[key] as String? else defValue
}
override fun getStringSet(key: String, defValues: Set<String>?): Set<String>? {
return if (values.containsKey(key)) {
values[key] as Set<String>?
} else defValues
}
override fun registerOnSharedPreferenceChangeListener(
listener: SharedPreferences.OnSharedPreferenceChangeListener
) {
throw UnsupportedOperationException()
}
override fun unregisterOnSharedPreferenceChangeListener(
listener: SharedPreferences.OnSharedPreferenceChangeListener
) {
throw UnsupportedOperationException()
}
override fun putBoolean(key: String, value: Boolean): SharedPreferences.Editor {
tempValues[key] = java.lang.Boolean.valueOf(value)
return this
}
override fun putFloat(key: String, value: Float): SharedPreferences.Editor {
tempValues[key] = value
return this
}
override fun putInt(key: String, value: Int): SharedPreferences.Editor {
tempValues[key] = value
return this
}
override fun putLong(key: String, value: Long): SharedPreferences.Editor {
tempValues[key] = value
return this
}
override fun putString(key: String, value: String?): SharedPreferences.Editor {
tempValues[key] = value
return this
}
override fun putStringSet(key: String, values: Set<String>?): SharedPreferences.Editor {
tempValues[key] = values
return this
}
override fun remove(key: String): SharedPreferences.Editor {
tempValues.remove(key)
return this
}
override fun clear(): SharedPreferences.Editor {
tempValues.clear()
return this
}
override fun commit(): Boolean {
values = tempValues.toMutableMap()
return true
}
override fun apply() {
commit()
}
}
| 1
|
Kotlin
|
0
| 2
|
5380df11f20580e55b6c622db30201f9f467c09f
| 3,326
|
retroceptor
|
Apache License 2.0
|
shared/src/commonMain/kotlin/presentation/App.kt
|
razaghimahdi
| 714,632,664
| false
| null |
package presentation
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import coil3.ImageLoader
import coil3.annotation.ExperimentalCoilApi
import coil3.compose.setSingletonImageLoaderFactory
import coil3.fetch.NetworkFetcher
import common.Context
import di.appModule
import moe.tlaster.precompose.PreComposeApp
import moe.tlaster.precompose.navigation.NavHost
import moe.tlaster.precompose.navigation.rememberNavigator
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.koin.compose.KoinApplication
import org.koin.compose.koinInject
import presentation.navigation.AppNavigation
import presentation.theme.AppTheme
import presentation.ui.main.MainNav
import presentation.ui.splash.SplashNav
@OptIn(ExperimentalCoilApi::class, ExperimentalResourceApi::class)
@Composable
internal fun App(context: Context) {
KoinApplication(application = {
modules(appModule(context))
}) {
PreComposeApp {
setSingletonImageLoaderFactory { context ->
ImageLoader.Builder(context)
.components {
add(NetworkFetcher.Factory())
}
.build()
}
AppTheme {
val navigator = rememberNavigator()
val viewModel: SharedViewModel = koinInject()
LaunchedEffect(key1 = viewModel.tokenManager.state.value.isTokenAvailable) {
if (!viewModel.tokenManager.state.value.isTokenAvailable) {
navigator.popBackStack()
navigator.navigate(AppNavigation.Splash.route)
}
}
Box(modifier = Modifier.fillMaxSize()) {
NavHost(
navigator = navigator,
initialRoute = AppNavigation.Splash.route,
) {
scene(route = AppNavigation.Splash.route) {
SplashNav(navigateToMain = {
navigator.popBackStack()
navigator.navigate(AppNavigation.Main.route)
})
}
scene(route = AppNavigation.Main.route) {
MainNav {
navigator.popBackStack()
navigator.navigate(AppNavigation.Splash.route)
}
}
}
}
}
}
}
}
| 0
| null |
9
| 97
|
6047cf13ab86a9dd74c8ea4bcba7a9771ec8ad0e
| 2,756
|
Shopping-By-KMP
|
MIT License
|
Chapter04/src/main/kotlin/com/rivuchk/packtpub/reactivekotlin/chapter04/chapter4_6.kt
|
tymicki
| 175,694,440
| true
|
{"Kotlin": 121444}
|
package com.rivuchk.packtpub.reactivekotlin.chapter04
import io.reactivex.Flowable
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription
fun main() {
Flowable.range(1, 1000)//(1)
.map { MyItem5(it) }//(2)
.observeOn(Schedulers.io())
.subscribe(object : Subscriber<MyItem5> { //(3)
override fun onSubscribe(subscription: Subscription) {
subscription.request(Long.MAX_VALUE)//(4)
}
override fun onNext(s: MyItem5?) {
runBlocking { delay(50) }
println("Subscriber received " + s!!)
}
override fun onError(e: Throwable) {
e.printStackTrace()
}
override fun onComplete() {
println("Done!")
}
})
runBlocking { delay(60000) }
}
data class MyItem5(val id: Int) {
init {
println("MyItem Created $id")
}
}
| 0
|
Kotlin
|
0
| 0
|
143e1bd1473c6da3fb3fe1b9373124052f87874d
| 1,135
|
Reactive-Programming-in-Kotlin
|
MIT License
|
app/src/debug/java/info/bati11/whenit/FlipperInitializer.kt
|
bati11
| 226,518,863
| false
| null |
package info.bati11.whenit
import android.content.Context
import com.facebook.flipper.android.AndroidFlipperClient
import com.facebook.flipper.android.utils.FlipperUtils
import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin
import com.facebook.flipper.plugins.inspector.DescriptorMapping
import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin
import com.facebook.soloader.SoLoader
object FlipperInitializer {
fun initFlipper(context: Context) {
SoLoader.init(context, false)
if (BuildConfig.DEBUG && FlipperUtils.shouldEnableFlipper(context)) {
val client = AndroidFlipperClient.getInstance(context)
client.addPlugin(InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()))
client.addPlugin(DatabasesFlipperPlugin(context))
client.start()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
2ee204baa364594c6c2909c83673b8901f8b1d81
| 866
|
whenit-android
|
Apache License 2.0
|
networksurvey/src/main/java/com/craxiom/networksurvey/ui/wifi/model/WifiSpectrum24ViewModel.kt
|
christianrowlands
| 156,117,885
| false
|
{"Java": 1326175, "Kotlin": 123425}
|
package com.craxiom.networksurvey.ui.wifi.model
import com.craxiom.networksurvey.fragments.WifiNetworkInfo
import com.craxiom.networksurvey.util.WifiUtils.START_OF_6_GHZ_RANGE
import com.patrykandpatrick.vico.core.model.LineCartesianLayerModel
/**
* The specific Wi-Fi spectrum view model implementation for the 2.4 GHz chart.
*/
class WifiSpectrum24ViewModel : AWifiSpectrumChartViewModel() {
override fun filterWifiNetworks(wifiNetworkInfoList: List<WifiNetworkInfo>): List<WifiNetworkInfo> {
return wifiNetworkInfoList.filter {
it.frequency < START_OF_6_GHZ_RANGE && it.channel.toFloat() in CHANNELS_2_4_GHZ
}
}
override fun createSeriesModel(wifiNetworkInfoList: List<WifiNetworkInfo>): LineCartesianLayerModel.Partial {
return if (wifiNetworkInfoList.isEmpty()) {
LineCartesianLayerModel.partial {
series(
CHANNELS_2_4_GHZ_CHART_VIEW,
List(CHANNELS_2_4_GHZ_CHART_VIEW.size) { WIFI_CHART_MIN })
}
} else {
createSeriesForNetworks(wifiNetworkInfoList)
}
}
override fun clearChart() {
modelProducer.tryRunTransaction {
add(LineCartesianLayerModel.partial {
series(
CHANNELS_2_4_GHZ_CHART_VIEW,
List(CHANNELS_2_4_GHZ_CHART_VIEW.size) { WIFI_CHART_MIN })
})
}
}
}
| 5
|
Java
|
25
| 95
|
866b838da2d2fd74e343d6f153ab9f869a255e4a
| 1,433
|
android-network-survey
|
Apache License 2.0
|
build-logic/convention/src/main/kotlin/pl/droidsonroids/composekit/modulegenerator/utils/SystemSeparatorProvider.kt
|
DroidsOnRoids
| 514,214,122
| false
|
{"Kotlin": 105234}
|
package pl.droidsonroids.composekit.modulegenerator.utils
import java.io.File
internal class SystemSeparatorProvider : SeparatorProvider {
override val separator: String
get() = File.separator
override val separatorChar: Char
get() = File.separatorChar
}
| 29
|
Kotlin
|
0
| 0
|
61097320067374bafc35eb333c38d8e8a4497637
| 281
|
ComposeKit
|
MIT License
|
app/src/main/java/com/example/sobes/data/database/AppDatabase.kt
|
lolka123455
| 814,186,525
| false
|
{"Kotlin": 161649}
|
package com.example.sobes.data.database
import androidx.room.Database
import androidx.room.RoomDatabase
import com.example.sobes.data.database.dao.AnswerCardDao
import com.example.sobes.data.database.dao.CardInfoDao
import com.example.sobes.data.database.entity.AnswerCardEntity
import com.example.sobes.data.database.entity.CardInfoEntity
@Database(
entities = [
AnswerCardEntity::class,
CardInfoEntity::class,
],
version = AppDatabase.DATABASE_VERSION
)
abstract class AppDatabase : RoomDatabase() {
companion object {
const val DATABASE_VERSION = 1
const val DATABASE_NAME = "app_database"
}
abstract fun answerCardDao(): AnswerCardDao
abstract fun cardInfoDao(): CardInfoDao
}
| 0
|
Kotlin
|
0
| 3
|
0012bfae25679b90c633def83584842b24509613
| 747
|
Sobes
|
Creative Commons Attribution 4.0 International
|
src/main/kotlin/com/atlassian/performance/tools/jiraperformancetests/api/AwsPluginTester.kt
|
tied
| 155,338,629
| true
|
{"Kotlin": 43376}
|
package com.atlassian.performance.tools.jiraperformancetests.api
import com.atlassian.performance.tools.aws.api.Aws
import com.atlassian.performance.tools.aws.api.Investment
import com.atlassian.performance.tools.awsinfrastructure.api.InfrastructureFormula
import com.atlassian.performance.tools.awsinfrastructure.api.VirtualUsersConfiguration
import com.atlassian.performance.tools.awsinfrastructure.api.jira.JiraFormula
import com.atlassian.performance.tools.awsinfrastructure.api.storage.JiraSoftwareStorage
import com.atlassian.performance.tools.awsinfrastructure.api.virtualusers.Ec2VirtualUsersFormula
import com.atlassian.performance.tools.infrastructure.api.app.AppSource
import com.atlassian.performance.tools.infrastructure.api.app.Apps
import com.atlassian.performance.tools.infrastructure.api.dataset.Dataset
import com.atlassian.performance.tools.infrastructure.api.virtualusers.SshVirtualUsers
import com.atlassian.performance.tools.workspace.api.RootWorkspace
import com.atlassian.performance.tools.workspace.api.TestWorkspace
import com.google.common.util.concurrent.ThreadFactoryBuilder
import java.io.File
import java.nio.file.Path
import java.time.Duration
import java.util.concurrent.Executors
@Deprecated(
message = "Use AppImpactTest or use its source as a guide how to build your custom test"
)
class AwsPluginTester(
private val aws: Aws,
private val dataset: Dataset,
outputDirectory: Path,
private val deployment: AwsJiraDeployment
) {
private val root: RootWorkspace = RootWorkspace(outputDirectory)
private val label = "Plugin Test"
fun run(
shadowJar: File,
baselineApp: AppSource,
experimentApp: AppSource,
virtualUsersConfiguration: VirtualUsersConfiguration,
jiraVersion: String
): RegressionResults {
val standaloneStabilityTest = RegressionTest(
dataset,
shadowJar,
virtualUsersConfiguration,
baselineApp,
experimentApp,
jiraVersion
)
return standaloneStabilityTest.run(
workspace = root.currentTask.isolateTest(label)
)
}
private inner class RegressionTest(
private val dataset: Dataset,
private val shadowJar: File,
private val virtualUsersConfiguration: VirtualUsersConfiguration,
private val baselineApp: AppSource,
private val experimentApp: AppSource,
private val jiraVersion: String
) {
fun run(workspace: TestWorkspace): RegressionResults {
//provisioning
val baselineLabel = baselineApp.getLabel()
val baselineTest = provisioningTest(
cohort = baselineLabel,
jira = formula(
jiraVersion,
dataset,
Apps(listOf(baselineApp))
),
feature = label,
shadowJar = shadowJar
)
val experimentLabel = experimentApp.getLabel()
val experimentCohort = if (baselineLabel == experimentLabel) {
"$experimentLabel*"
} else {
experimentLabel
}
val experimentTest = provisioningTest(
cohort = experimentCohort,
jira = formula(
jiraVersion,
dataset,
Apps(listOf(experimentApp))
),
feature = label,
shadowJar = shadowJar
)
// run tests
val executor = Executors.newFixedThreadPool(
2,
ThreadFactoryBuilder()
.setNameFormat("standalone-stability-test-thread-%d")
.build()
)
val futureBaselineResults = baselineTest.runAsync(workspace, executor, virtualUsersConfiguration)
val futureExperimentResults = experimentTest.runAsync(workspace, executor, virtualUsersConfiguration)
/// rest of the test
val rawBaselineResults = futureBaselineResults.get()
val rawExperimentResults = futureExperimentResults.get()
executor.shutdownNow()
return RegressionResults(
baseline = rawBaselineResults,
experiment = rawExperimentResults
)
}
}
private fun provisioningTest(
feature: String,
cohort: String,
jira: JiraFormula,
shadowJar: File
): ProvisioningPerformanceTest = ProvisioningPerformanceTest(
cohort = cohort,
infrastructureFormula = infrastructureFormula(
feature = feature,
jira = jira,
shadowJar = shadowJar
)
)
private fun infrastructureFormula(
feature: String,
jira: JiraFormula,
shadowJar: File
): InfrastructureFormula<SshVirtualUsers> = InfrastructureFormula(
investment = Investment(
useCase = "Catch JPT regressions in $feature",
lifespan = Duration.ofHours(1)
),
jiraFormula = jira,
virtualUsersFormula = Ec2VirtualUsersFormula(
shadowJar = shadowJar
),
aws = aws
)
private fun formula(
jiraVersion: String,
dataset: Dataset,
apps: Apps
) = deployment.createJiraFormula(
apps = apps,
application = JiraSoftwareStorage(jiraVersion),
jiraHomeSource = dataset.jiraHomeSource,
database = dataset.database
)
}
| 0
|
Kotlin
|
0
| 0
|
a4ace3fc16ae6993c21b08509e242edaaf7f459a
| 5,573
|
jira-performance-tests
|
Apache License 2.0
|
devops-boot-project/devops-boot-core/devops-schedule/devops-schedule-server/src/main/kotlin/com/tencent/devops/schedule/scheduler/monitor/JobRetryMonitor.kt
|
bkdevops-projects
| 294,058,091
| false
|
{"Kotlin": 488037, "JavaScript": 47413, "Vue": 36468, "SCSS": 7290, "HTML": 620, "Java": 559}
|
package com.tencent.devops.schedule.scheduler.monitor
import com.tencent.devops.schedule.enums.AlarmStatusEnum
import com.tencent.devops.schedule.enums.TriggerTypeEnum
import com.tencent.devops.schedule.scheduler.JobScheduler
import com.tencent.devops.schedule.utils.sleep
import com.tencent.devops.schedule.utils.terminate
import org.slf4j.LoggerFactory
import kotlin.concurrent.thread
/**
* 任务重试管理类
*/
open class JobRetryMonitor(
private val jobScheduler: JobScheduler
) {
private val jobManager = jobScheduler.getJobManager()
private lateinit var monitorThread: Thread
private var running = true
fun start() {
monitorThread = thread(
isDaemon = true,
name = "job-retry-monitor-thread"
) {
while (running) {
refresh()
sleep(10)
}
}
logger.info("startup job retry monitor success")
}
fun stop() {
running = false
terminate(monitorThread)
}
private fun refresh() {
try {
val failedLogIds = jobManager.findFailJobLogIds(BATCH_SIZE)
for(logId in failedLogIds) {
// lock log
val modifyCount = jobManager.updateAlarmStatus(
logId = logId,
old = AlarmStatusEnum.TODO.code(),
new = AlarmStatusEnum.LOCKED.code()
)
if (modifyCount < 1) {
continue
}
val log = jobManager.findJobLogById(logId)!!
val job = jobManager.findJobById(log.jobId)
val retryCount = log.workerRetryCount ?: 0
if (retryCount > 0) {
jobScheduler.trigger(
jobId = log.jobId,
triggerType = TriggerTypeEnum.RETRY,
retryCount = retryCount - 1,
shardingParam = log.workerShardingParam,
jobParam = log.jobParam
)
jobManager.updateJobLog(log)
}
val newAlarmStatus = if (job != null) {
// TODO 发送告警
logger.info("alarm success")
AlarmStatusEnum.SUCCESS
} else {
AlarmStatusEnum.IGNORED
}
jobManager.updateAlarmStatus(
logId = logId,
old = AlarmStatusEnum.LOCKED.code(),
new = newAlarmStatus.code()
)
}
} catch (e: Exception) {
if (running) {
logger.error("job retry monitor occur error: ${e.message}", e)
}
}
}
companion object {
private val logger = LoggerFactory.getLogger(JobRetryMonitor::class.java)
private const val BATCH_SIZE = 1000
}
}
| 7
|
Kotlin
|
22
| 27
|
cbff03abe5d572b09cbd486830d87cddc91b938b
| 2,939
|
devops-framework
|
MIT License
|
app/app/src/main/java/site/pixeled/tagtool/ItemFragment.kt
|
orosmatthew
| 765,328,347
| false
|
{"Kotlin": 47663, "PHP": 24101}
|
package site.pixeled.tagtool
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.navigation.findNavController
import com.anton46.collectionitempicker.CollectionPicker
import site.pixeled.tagtool.model.Item
import site.pixeled.tagtool.model.Tag
import site.pixeled.tagtool.model.TagType
class ItemFragment : Fragment() {
private var itemId: Int? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
itemId = arguments?.getInt("itemId")
}
private fun setupSaveButton(
item: Item,
buttonView: Button,
descriptionView: EditText,
tagGroupView: CollectionPicker
) {
buttonView.setOnClickListener {
ServiceClient.updateItem(
id,
item.name,
descriptionView.text.toString(),
item.codeData
)
ServiceClient.getTags().thenApply { currentTags ->
val currentItemTags = currentTags.filter { t -> t.itemId == id }
tagGroupView.items.forEach { tagGroupItem ->
val currentTag =
currentItemTags.find { t -> t.tagTypeId == tagGroupItem.id.toInt() }
if (tagGroupItem.isSelected && currentTag == null) {
ServiceClient.createTag(tagGroupItem.id.toInt(), id)
} else if (!tagGroupItem.isSelected && currentTag != null) {
ServiceClient.deleteTag(currentTag.id)
}
}
Toast.makeText(context, "Item updated", Toast.LENGTH_SHORT).show()
}
}
}
private fun initTags(
itemId: Int,
tags: Array<Tag>,
tagTypes: Array<TagType>,
tagGroupView: CollectionPicker
) {
val itemTags = tags.filter { t -> t.itemId == itemId }
tagTypes.forEach { tagType ->
val item = com.anton46.collectionitempicker.Item(
tagType.id.toString(),
tagType.name
)
item.isSelected = itemTags.find { t -> t.tagTypeId == tagType.id } != null
tagGroupView.items.add(item)
}
tagGroupView.drawItemView()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_item, container, false)
val descriptionView = view.findViewById<EditText>(R.id.SelectedItemDescription)
val tagGroupView = view.findViewById<CollectionPicker>(R.id.ItemTagGroup)
val saveButtonView = view.findViewById<Button>(R.id.SelectedItemEdit)
val itemNameView = view.findViewById<TextView>(R.id.SelectedItemName)
val deleteButtonView = view.findViewById<Button>(R.id.SelectedItemDelete)
val backButtonView = view.findViewById<Button>(R.id.BackfromItem)
itemId?.let { itemId ->
ServiceClient.getItem(itemId).thenApply { itemNullable ->
itemNullable?.let { item ->
itemNameView.text = item.name
descriptionView.setText(item.description ?: "")
setupSaveButton(item, saveButtonView, descriptionView, tagGroupView)
}
}
ServiceClient.getTags().thenApply { tags ->
ServiceClient.getTagTypes().thenApply { tagTypes ->
initTags(itemId, tags, tagTypes, tagGroupView)
}
}
deleteButtonView.setOnClickListener {
ServiceClient.deleteItem(itemId).thenApply {
view.findNavController().popBackStack()
}
}
backButtonView.setOnClickListener {
view.findNavController().navigate(R.id.action_itemFragment_to_myListFragment)
}
}
return view
}
}
| 0
|
Kotlin
|
0
| 0
|
b3cc1a7e12cb2e469d3e4a246b3997e9703fe944
| 4,191
|
tag-tool
|
MIT License
|
app/src/main/java/com/stylingandroid/weatherstation/di/ViewModelFactory.kt
|
StylingAndroid
| 134,726,407
| false
| null |
package bav.anyway.di
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
@Singleton
class ViewModelFactory
@Inject constructor(
private val viewModels: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
val provider = viewModels[modelClass]
?: viewModels.entries.first { modelClass.isAssignableFrom(it.key) }.value
return provider.get() as T
}
}
| 2
| null |
9
| 86
|
91ea578865024b9bc8957d5b8b2293a250dbe10c
| 648
|
WeatherStation
|
Apache License 2.0
|
app/src/main/java/io/horizontalsystems/bankwallet/modules/main/MainActivity.kt
|
onictech
| 194,841,610
| true
|
{"Kotlin": 797225, "Ruby": 4839}
|
package io.horizontalsystems.bankwallet.modules.main
import android.content.Intent
import android.os.Bundle
import android.security.keystore.KeyPermanentlyInvalidatedException
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import android.view.animation.AnimationUtils
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import androidx.annotation.NonNull
import androidx.core.app.ShareCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager.widget.ViewPager
import com.aurelhubert.ahbottomnavigation.AHBottomNavigation
import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.zxing.integration.android.IntentIntegrator
import io.horizontalsystems.bankwallet.BaseActivity
import io.horizontalsystems.bankwallet.R
import io.horizontalsystems.bankwallet.core.App
import io.horizontalsystems.bankwallet.core.reObserve
import io.horizontalsystems.bankwallet.core.security.EncryptionManager
import io.horizontalsystems.bankwallet.entities.Coin
import io.horizontalsystems.bankwallet.modules.backup.BackupModule
import io.horizontalsystems.bankwallet.modules.backup.BackupPresenter
import io.horizontalsystems.bankwallet.modules.fulltransactioninfo.FullTransactionInfoModule
import io.horizontalsystems.bankwallet.modules.guest.GuestModule
import io.horizontalsystems.bankwallet.modules.pin.PinModule
import io.horizontalsystems.bankwallet.modules.receive.ReceiveViewModel
import io.horizontalsystems.bankwallet.modules.receive.viewitems.AddressItem
import io.horizontalsystems.bankwallet.modules.send.ConfirmationFragment
import io.horizontalsystems.bankwallet.modules.send.QRScannerActivity
import io.horizontalsystems.bankwallet.modules.send.SendModule
import io.horizontalsystems.bankwallet.modules.send.SendViewModel
import io.horizontalsystems.bankwallet.modules.transactions.TransactionViewItem
import io.horizontalsystems.bankwallet.modules.transactions.transactionInfo.TransactionInfoViewModel
import io.horizontalsystems.bankwallet.ui.extensions.NumPadItem
import io.horizontalsystems.bankwallet.ui.extensions.NumPadItemType
import io.horizontalsystems.bankwallet.ui.extensions.NumPadItemsAdapter
import io.horizontalsystems.bankwallet.viewHelpers.DateHelper
import io.horizontalsystems.bankwallet.viewHelpers.HudHelper
import io.horizontalsystems.bankwallet.viewHelpers.LayoutHelper
import io.horizontalsystems.bankwallet.viewHelpers.TextHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.activity_dashboard.*
import kotlinx.android.synthetic.main.fragment_bottom_sheet_pay.*
import kotlinx.android.synthetic.main.fragment_bottom_sheet_receive.*
import kotlinx.android.synthetic.main.transaction_info_bottom_sheet.*
import kotlinx.android.synthetic.main.view_amount_input.*
import java.math.BigDecimal
import java.math.RoundingMode
import java.security.UnrecoverableKeyException
import java.util.concurrent.TimeUnit
class MainActivity : BaseActivity(), NumPadItemsAdapter.Listener {
private lateinit var adapter: MainTabsAdapter
private var disposable: Disposable? = null
private lateinit var receiveViewModel: ReceiveViewModel
private lateinit var sendViewModel: SendViewModel
private lateinit var transInfoViewModel: TransactionInfoViewModel
private var receiveBottomSheetBehavior: BottomSheetBehavior<View>? = null
private var sendBottomSheetBehavior: BottomSheetBehavior<View>? = null
private var txInfoBottomSheetBehavior: BottomSheetBehavior<View>? = null
private var sendInputConnection: InputConnection? = null
private val amountChangeSubject: PublishSubject<BigDecimal> = PublishSubject.create()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
try {
redirectToCorrectPage()
} catch (e: Exception) {
when (e) {
is KeyPermanentlyInvalidatedException,
is UnrecoverableKeyException -> EncryptionManager.showKeysInvalidatedAlert(this)
}
}
setTransparentStatusBar()
setContentView(R.layout.activity_dashboard)
setTopMarginByStatusBarHeight(viewPager)
adapter = MainTabsAdapter(supportFragmentManager)
viewPager.adapter = adapter
viewPager.offscreenPageLimit = 2
setSwipeEnabled(true)
LayoutHelper.getAttr(R.attr.BottomNavigationBackgroundColor, theme)?.let {
bottomNavigation.defaultBackgroundColor = it
}
bottomNavigation.accentColor = ContextCompat.getColor(this, R.color.yellow_crypto)
bottomNavigation.inactiveColor = ContextCompat.getColor(this, R.color.grey)
bottomNavigation.addItem(AHBottomNavigationItem(R.string.Balance_Title, R.drawable.bank_icon, 0))
bottomNavigation.addItem(AHBottomNavigationItem(R.string.Transactions_Title, R.drawable.transactions, 0))
bottomNavigation.addItem(AHBottomNavigationItem(R.string.Settings_Title, R.drawable.settings, 0))
bottomNavigation.titleState = AHBottomNavigation.TitleState.ALWAYS_HIDE
bottomNavigation.setUseElevation(false)
bottomNavigation.setOnTabSelectedListener { position, wasSelected ->
if (!wasSelected) {
viewPager.setCurrentItem(position, false)
}
true
}
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
if (positionOffset == 0f) {
adapter.currentItem = bottomNavigation.currentItem
}
}
override fun onPageSelected(position: Int) {
bottomNavigation.currentItem = position
}
})
val activeTab = intent?.extras?.getInt(ACTIVE_TAB_KEY)
activeTab?.let {
bottomNavigation.currentItem = it
}
disposable = App.appCloseManager.appCloseSignal.subscribe {
finishAffinity()
}
setBottomSheets()
}
private fun redirectToCorrectPage() {
if (!EncryptionManager.isDeviceLockEnabled(this)) {
EncryptionManager.showNoDeviceLockWarning(this)
finish()
} else if (!App.authManager.isLoggedIn) {
GuestModule.start(this)
finish()
} else if (!App.localStorage.iUnderstand) {
BackupModule.start(this, BackupPresenter.DismissMode.SET_PIN)
finish()
} else if(App.secureStorage.pinIsEmpty()) {
PinModule.startForSetPin(this)
finishAffinity()
}
}
private fun setBottomSheets() {
hideDim()
receiveBottomSheetBehavior = BottomSheetBehavior.from(receiveNestedScrollView)
sendBottomSheetBehavior = BottomSheetBehavior.from(sendNestedScrollView)
txInfoBottomSheetBehavior = BottomSheetBehavior.from(transactionInfoNestedScrollView)
setBottomSheet(receiveBottomSheetBehavior)
setBottomSheet(sendBottomSheetBehavior)
setBottomSheet(txInfoBottomSheetBehavior)
setReceiveDialog()
setSendDialog()
setTransactionInfoDialog()
bottomSheetDim.setOnClickListener {
receiveBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
sendBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
txInfoBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
}
}
override fun onBackPressed() = when {
txInfoBottomSheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED -> {
txInfoBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
}
receiveBottomSheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED -> {
receiveBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
}
sendBottomSheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED -> {
sendBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
}
adapter.currentItem > 0 -> {
viewPager.currentItem = 0
}
else -> super.onBackPressed()
}
override fun onResume() {
super.onResume()
sendViewModel.onViewResumed()
collapseBottomSheetsOnActivityRestore()
}
override fun onDestroy() {
disposable?.dispose()
super.onDestroy()
}
fun updateSettingsTabCounter(count: Int) {
val countText = if (count < 1) "" else "!"
val settingsTabPosition = 2
bottomNavigation.setNotification(countText, settingsTabPosition)
}
fun setSwipeEnabled(enabled: Boolean) {
viewPager.setPagingEnabled(enabled)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
if (scanResult != null && !TextUtils.isEmpty(scanResult.contents)) {
sendViewModel.delegate.onScanAddress(scanResult.contents)
}
}
override fun onItemClick(item: NumPadItem) {
when (item.type) {
NumPadItemType.NUMBER -> sendInputConnection?.commitText(item.number.toString(), 1)
NumPadItemType.DELETE -> sendInputConnection?.deleteSurroundingText(1, 0)
NumPadItemType.DOT -> {
if (editTxtAmount?.text?.toString()?.contains(".") != true) {
sendInputConnection?.commitText(".", 1)
}
}
}
}
private fun collapseBottomSheetsOnActivityRestore() {
//Collapse opened empty bottomsheet dialogs on Activity restore
if (receiveBottomSheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED && receiveTxtTitle.text.isEmpty()) {
receiveBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
}
if (sendBottomSheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED && sendTxtTitle.text.isEmpty()) {
sendBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
}
if (txInfoBottomSheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED && txInfoCoinName.text.isEmpty()) {
txInfoBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
}
}
private fun setBottomSheet(bottomSheetBehavior: BottomSheetBehavior<View>?) {
bottomSheetBehavior?.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
override fun onStateChanged(@NonNull bottomSheet: View, newState: Int) {
val enabled = newState != BottomSheetBehavior.STATE_EXPANDED
setSwipeEnabled(enabled)
if (newState == BottomSheetBehavior.STATE_EXPANDED) {
bottomSheetBehavior.isFitToContents = true
}
}
override fun onSlide(@NonNull bottomSheet: View, slideOffset: Float) {
bottomSheetDim.alpha = slideOffset
bottomSheetDim.visibility = if (slideOffset == 0f) View.GONE else View.VISIBLE
}
})
}
private fun hideDim() {
bottomSheetDim.visibility = View.GONE
bottomSheetDim.alpha = 0f
}
/***
Receive bottomsheet START
*/
private fun setReceiveDialog() {
receiveViewModel = ViewModelProviders.of(this).get(ReceiveViewModel::class.java)
receiveViewModel.showAddressLiveData.reObserve(this, showAddressObserver)
receiveViewModel.showErrorLiveData.reObserve(this, showErrorObserver)
receiveViewModel.showCopiedLiveEvent.reObserve(this, showCopiedObserver)
receiveViewModel.shareAddressLiveEvent.reObserve(this, shareAddressObserver)
btnShare.setOnClickListener { receiveViewModel.delegate.onShareClick() }
receiveAddressView.setOnClickListener { receiveViewModel.delegate.onAddressClick() }
}
fun openReceiveDialog(coinCode: String) {
receiveViewModel.init(coinCode)
receiveBottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
}
private fun closeReceiveDialog() {
receiveBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
hideDim()
}
//Receive dialog observers
private val showAddressObserver = Observer<AddressItem?> { address ->
address?.let {
receiveCoinIcon.bind(it.coin)
receiveTxtTitle.text = getString(R.string.Deposit_Title, it.coin.title)
receiveAddressView.bind(it.address)
imgQrCode.setImageBitmap(TextHelper.getQrCodeBitmapFromAddress(it.address))
}
}
private val showErrorObserver = Observer<Int?> { error ->
error?.let { HudHelper.showErrorMessage(it) }
closeReceiveDialog()
}
private val showCopiedObserver = Observer<Unit> { HudHelper.showSuccessMessage(R.string.Hud_Text_Copied, 500) }
private val shareAddressObserver = Observer<String?> { address ->
address?.let {
ShareCompat.IntentBuilder.from(this)
.setType("text/plain")
.setText(it)
.startChooser()
}
}
//End of ReceiveDialog observers
/***
Receive bottomsheet END
*/
/***
Send bottomsheet START
*/
fun openSendDialog(coinCode: String) {
editTxtAmount.setText("")
feeRateSeekbar.reset()
sendViewModel.init(coinCode)
sendBottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
disposable?.dispose()
disposable = amountChangeSubject.debounce(300, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
sendViewModel.delegate.onAmountChanged(it)
}
}
private fun closeSendDialog() {
sendBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
hideDim()
}
//SendDialog observers
private val errorLiveDataObserver = Observer<Int?> { error -> error?.let { HudHelper.showErrorMessage(it) } }
private val showConfirmationObserver = Observer<Unit> { ConfirmationFragment.show(this) }
private val dismissObserver = Observer<Unit> {
closeSendDialog()
}
private val dismissWithSuccessObserver = Observer<Unit> {
HudHelper.showSuccessMessage(R.string.Send_Success)
closeSendDialog()
}
private val pasteButtonEnabledObserver = Observer<Boolean?> { enabled ->
enabled?.let { addressInput.enablePasteButton(it) }
}
private val feeIsAdjustableObserver = Observer<Boolean?> { feeIsAdjustable ->
feeIsAdjustable?.let { feeRateSeekbar.visibility = if (it) View.VISIBLE else View.GONE }
}
private val switchButtonEnabledObserver = Observer<Boolean?> { enabled ->
enabled?.let { amountInput?.enableSwitchBtn(it) }
}
private val coinLiveDataObserver = Observer<Coin?> { coin ->
coin?.let {
sendCoinIcon.bind(it)
sendTxtTitle.text = getString(R.string.Send_Title, it.title)
}
}
private val sendButtonEnabledObserver = Observer<Boolean?> { enabled ->
enabled?.let { btnSend.isEnabled = it }
}
private val hintInfoObserver = Observer<SendModule.HintInfo> { hintInfo ->
when (hintInfo) {
is SendModule.HintInfo.Amount -> {
val hintText = when (hintInfo.amountInfo) {
is SendModule.AmountInfo.CoinValueInfo -> App.numberFormatter.format(hintInfo.amountInfo.coinValue, realNumber = true)
is SendModule.AmountInfo.CurrencyValueInfo -> App.numberFormatter.format(hintInfo.amountInfo.currencyValue)
}
amountInput?.updateInput(hint = hintText)
}
is SendModule.HintInfo.ErrorInfo -> {
val errorText: String? = when (hintInfo.error) {
is SendModule.AmountError.InsufficientBalance -> {
val balanceAmount = when (hintInfo.error.amountInfo) {
is SendModule.AmountInfo.CoinValueInfo -> App.numberFormatter.format(hintInfo.error.amountInfo.coinValue)
is SendModule.AmountInfo.CurrencyValueInfo -> App.numberFormatter.format(hintInfo.error.amountInfo.currencyValue)
}
getString(R.string.Send_Error_BalanceAmount, balanceAmount)
}
else -> null
}
amountInput?.updateInput(error = errorText)
}
null -> amountInput?.updateInput()
}
}
private val amountInfoObserver = Observer<SendModule.AmountInfo> { amountInfo ->
val amountNumber = when (amountInfo) {
is SendModule.AmountInfo.CoinValueInfo -> {
amountInput?.updateAmountPrefix(amountInfo.coinValue.coinCode)
amountInfo.coinValue.value.setScale(8, RoundingMode.HALF_EVEN)
}
is SendModule.AmountInfo.CurrencyValueInfo -> {
amountInput?.updateAmountPrefix(amountInfo.currencyValue.currency.symbol)
amountInfo.currencyValue.value.setScale(2, RoundingMode.HALF_EVEN)
}
else -> BigDecimal.ZERO
}
if (amountNumber > BigDecimal.ZERO) {
editTxtAmount.setText(amountNumber.stripTrailingZeros().toPlainString())
editTxtAmount.setSelection(editTxtAmount.text.length)
} else {
editTxtAmount.setText("")
}
}
private val addressInfoObserver = Observer<SendModule.AddressInfo> { addressInfo ->
var addressText = ""
var errorText: String? = null
addressInfo?.let {
when (it) {
is SendModule.AddressInfo.ValidAddressInfo -> {
addressText = it.address
}
is SendModule.AddressInfo.InvalidAddressInfo -> {
addressText = it.address
errorText = getString(R.string.Send_Error_IncorrectAddress)
}
}
}
addressInput.updateInput(addressText, errorText)
}
private val feeInfoObserver = Observer<SendModule.FeeInfo> { feeInfo ->
feeInfo?.let {
txtFeePrimary.visibility = if (it.error == null) View.VISIBLE else View.GONE
txtFeeSecondary.visibility = if (it.error == null) View.VISIBLE else View.GONE
feeError.visibility = if (it.error == null) View.GONE else View.VISIBLE
feeAmountWrapper.visibility = if (it.error == null) View.VISIBLE else View.GONE
feeRateSeekbar.visibility = if (it.error == null) View.VISIBLE else View.GONE
it.error?.let { erc20Error ->
feeError.text = getString(R.string.Send_ERC_Alert, erc20Error.erc20CoinCode, erc20Error.coinValue.value.toPlainString())
} ?: run {
val primaryFeeInfo = it.primaryFeeInfo
val secondaryFeeInfo = it.secondaryFeeInfo
val primaryFee = when (primaryFeeInfo) {
is SendModule.AmountInfo.CurrencyValueInfo -> App.numberFormatter.format(primaryFeeInfo.currencyValue)
is SendModule.AmountInfo.CoinValueInfo -> App.numberFormatter.format(primaryFeeInfo.coinValue)
else -> ""
}
val primaryFeeText = "${getString(R.string.Send_DialogFee)} $primaryFee"
txtFeePrimary.text = primaryFeeText
txtFeeSecondary.text = when (secondaryFeeInfo) {
is SendModule.AmountInfo.CurrencyValueInfo -> App.numberFormatter.format(secondaryFeeInfo.currencyValue)
is SendModule.AmountInfo.CoinValueInfo -> App.numberFormatter.format(secondaryFeeInfo.coinValue)
else -> ""
}
}
}
}
//Observers ends
private fun setSendDialog() {
sendViewModel = ViewModelProviders.of(this).get(SendViewModel::class.java)
sendViewModel.errorLiveData.reObserve(this, errorLiveDataObserver)
sendViewModel.showConfirmationLiveEvent.reObserve(this, showConfirmationObserver)
sendViewModel.pasteButtonEnabledLiveData.reObserve(this, pasteButtonEnabledObserver)
sendViewModel.feeIsAdjustableLiveData.reObserve(this, feeIsAdjustableObserver)
sendViewModel.dismissLiveEvent.reObserve(this, dismissObserver)
sendViewModel.dismissWithSuccessLiveEvent.reObserve(this, dismissWithSuccessObserver)
sendViewModel.switchButtonEnabledLiveData.reObserve(this, switchButtonEnabledObserver)
sendViewModel.coinLiveData.reObserve(this, coinLiveDataObserver)
sendViewModel.hintInfoLiveData.reObserve(this, hintInfoObserver)
sendViewModel.sendButtonEnabledLiveData.reObserve(this, sendButtonEnabledObserver)
sendViewModel.amountInfoLiveData.reObserve(this, amountInfoObserver)
sendViewModel.addressInfoLiveData.reObserve(this, addressInfoObserver)
sendViewModel.feeInfoLiveData.reObserve(this, feeInfoObserver)
sendInputConnection = editTxtAmount.onCreateInputConnection(EditorInfo())
val numpadAdapter = NumPadItemsAdapter(this, NumPadItemType.DOT, false)
numPadItemsRecyclerView?.adapter = numpadAdapter
numPadItemsRecyclerView?.layoutManager = GridLayoutManager(this, 3)
addressInput?.bindAddressInputInitial(
onAmpersandClick = null,
onBarcodeClick = { startScanner() },
onPasteClick = { sendViewModel.delegate.onPasteClicked() },
onDeleteClick = { sendViewModel.delegate.onDeleteClicked() }
)
editTxtAmount.showSoftInputOnFocus = false
sendInputConnection = editTxtAmount.onCreateInputConnection(EditorInfo())
btnSend.isEnabled = false
amountInput?.bindInitial(
onMaxClick = { sendViewModel.delegate.onMaxClicked() },
onSwitchClick = { sendViewModel.delegate.onSwitchClicked() }
)
btnSend.setOnClickListener { sendViewModel.delegate.onSendClicked() }
editTxtAmount.addTextChangedListener(textChangeListener)
//disables BottomSheet dragging in numpad area
numPadItemsRecyclerView?.setOnTouchListener { _, event ->
when (event?.action) {
MotionEvent.ACTION_DOWN,
MotionEvent.ACTION_UP -> false
else -> true
}
}
feeRateSeekbar.bind { progress ->
sendViewModel.delegate.onFeeSliderChange(progress)
}
}
private val textChangeListener = object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
val amountText = s?.toString() ?: ""
var amountNumber = when {
amountText != "" -> amountText.toBigDecimalOrNull() ?: BigDecimal.ZERO
else -> BigDecimal.ZERO
}
sendViewModel.decimalSize?.let {
if (amountNumber.scale() > it) {
amountNumber = amountNumber.setScale(it, RoundingMode.FLOOR)
val newString = amountNumber.toPlainString()
editTxtAmount.setText(newString)
editTxtAmount.setSelection(newString.length)
val shake = AnimationUtils.loadAnimation(applicationContext, R.anim.shake_edittext)
editTxtAmount.startAnimation(shake)
}
}
amountInput?.setMaxBtnVisible(amountText.isEmpty())
amountChangeSubject.onNext(amountNumber)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
}
private fun startScanner() {
val intentIntegrator = IntentIntegrator(this)
intentIntegrator.captureActivity = QRScannerActivity::class.java
intentIntegrator.setOrientationLocked(true)
intentIntegrator.setPrompt("")
intentIntegrator.setBeepEnabled(false)
intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
intentIntegrator.initiateScan()
}
/***
Send bottomsheet END
*/
/***
TransactionInfo bottomsheet START
*/
private fun setTransactionInfoDialog() {
transInfoViewModel = ViewModelProviders.of(this).get(TransactionInfoViewModel::class.java)
transInfoViewModel.init()
transactionIdView.setOnClickListener { transInfoViewModel.onClickTransactionId() }
txtFullInfo.setOnClickListener { transInfoViewModel.onClickOpenFillInfo() }
transInfoViewModel.showCopiedLiveEvent.observe(this, Observer {
HudHelper.showSuccessMessage(R.string.Hud_Text_Copied, 500)
})
transInfoViewModel.showFullInfoLiveEvent.observe(this, Observer { pair ->
pair?.let {
FullTransactionInfoModule.start(this, transactionHash = it.first, coin = it.second)
}
})
transInfoViewModel.transactionLiveData.observe(this, Observer { txRecord ->
txRecord?.let { txRec ->
val txStatus = txRec.status
txInfoCoinIcon.bind(txRec.coin)
fiatValue.apply {
text = txRec.currencyValue?.let { App.numberFormatter.format(it, showNegativeSign = true, canUseLessSymbol = false) }
setTextColor(resources.getColor(if (txRec.incoming) R.color.green_crypto else R.color.yellow_crypto, null))
}
coinValue.text = App.numberFormatter.format(txRec.coinValue, explicitSign = true, realNumber = true)
txInfoCoinName.text = txRec.coin.title
itemRate.apply {
txRec.rate?.let {
val rate = getString(R.string.Balance_RatePerCoin, App.numberFormatter.format(it, canUseLessSymbol = false), txRec.coin.code)
bind(title = getString(R.string.TransactionInfo_HistoricalRate), value = rate)
}
visibility = if (txRec.rate == null) View.GONE else View.VISIBLE
}
itemTime.bind(title = getString(R.string.TransactionInfo_Time), value = txRec.date?.let { DateHelper.getFullDateWithShortMonth(it) } ?: "")
itemStatus.bindStatus(txStatus)
transactionIdView.bindTransactionId(txRec.transactionHash)
itemFrom.apply {
setOnClickListener { transInfoViewModel.onClickFrom() }
visibility = if (txRec.from.isNullOrEmpty()) View.GONE else View.VISIBLE
bindAddress(title = getString(R.string.TransactionInfo_From), address = txRec.from, showBottomBorder = true)
}
itemTo.apply {
setOnClickListener { transInfoViewModel.onClickTo() }
visibility = if (txRec.to.isNullOrEmpty()) View.GONE else View.VISIBLE
bindAddress(title = getString(R.string.TransactionInfo_To), address = txRec.to, showBottomBorder = true)
}
txInfoBottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
}
})
}
fun setTransactionInfoItem(txInfoItem: TransactionViewItem) {
transInfoViewModel.setViewItem(txInfoItem)
}
/***
TransactionInfo bottomsheet END
*/
companion object {
const val ACTIVE_TAB_KEY = "active_tab"
const val SETTINGS_TAB_POSITION = 2
}
}
| 0
|
Kotlin
|
1
| 0
|
5f57e8e2d1402f0b894434cc2728d54b519cf56d
| 28,386
|
unstoppable-wallet-android
|
MIT License
|
data/src/main/java/com/yvkalume/gifapp/data/model/mapper/GifEntityMapper.kt
|
yveskalume
| 604,632,872
| false
| null |
package com.yvkalume.gifapp.data.model.mapper
import com.yvkalume.gifapp.data.model.room.GifEntity
import com.yvkalume.gifapp.data.model.server.GiphyItem
object GifEntityMapper : Mapper<GiphyItem, GifEntity>() {
override fun map(input: GiphyItem): GifEntity {
return with(input) {
GifEntity(
id = id,
title = title,
imageUrl = images.fixed_height.url,
createdAt = System.currentTimeMillis(),
updatedAt = System.currentTimeMillis()
)
}
}
}
| 0
|
Kotlin
|
0
| 11
|
56526902eec0780032393b32c386df8ebef4059b
| 568
|
gif-app
|
Apache License 2.0
|
noty-android/app/composeapp/src/main/java/dev/shreyaspatil/noty/composeapp/utils/AssistedViewModelUtils.kt
|
PatilShreyas
| 303,164,275
| false
| null |
/*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shreyaspatil.noty.composeapp.utils
import android.app.Activity
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import dagger.hilt.android.EntryPointAccessors
import dev.shreyaspatil.noty.composeapp.ui.MainActivity
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.InternalCoroutinesApi
@ExperimentalCoroutinesApi
@InternalCoroutinesApi
@Composable
inline fun <reified VM : ViewModel> assistedViewModel(
viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {
"No ViewModelStoreOwner was provided via LocalViewModelStoreOwner"
},
provideFactory: MainActivity.ViewModelFactoryProvider.() -> ViewModelProvider.Factory,
): VM {
val factory = provideFactory(assistedViewModelFactory())
return viewModel(viewModelStoreOwner, factory = factory)
}
@ExperimentalCoroutinesApi
@InternalCoroutinesApi
@Composable
fun assistedViewModelFactory() = EntryPointAccessors.fromActivity(
LocalContext.current as Activity,
MainActivity.ViewModelFactoryProvider::class.java
)
| 8
| null |
243
| 997
|
91882706db5517a33bbd4083c7a7bdb77501c64b
| 1,954
|
NotyKT
|
Apache License 2.0
|
app/src/main/kotlin/io/github/sithengineer/marvelcharacters/presentation/characterdetails/CharacterDetailsPresenter.kt
|
SithEngineer
| 118,156,101
| false
| null |
package io.github.sithengineer.marvelcharacters.presentation.characterdetails
import io.github.sithengineer.marvelcharacters.presentation.characterdetails.CharacterDetailsContract.Presenter
import io.github.sithengineer.marvelcharacters.presentation.characterdetails.CharacterDetailsContract.View
import io.github.sithengineer.marvelcharacters.usecase.GetSpecificCharacterDetails
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import timber.log.Timber
class CharacterDetailsPresenter(
private val view: View,
private val getCharacterDetailsUseCase: GetSpecificCharacterDetails,
private val ioScheduler: Scheduler,
private val viewScheduler: Scheduler,
private val characterId: Int) :
Presenter {
private lateinit var compositeSubscription: CompositeDisposable
init {
view.setPresenter(this)
}
override fun stop() {
if (!compositeSubscription.isDisposed) {
compositeSubscription.dispose()
}
Timber.d("${this.javaClass.name}::stopped()")
}
override fun start() {
Timber.d("${this.javaClass.name}::started()")
compositeSubscription = CompositeDisposable()
loadCharacterData()
handleSelectedComics()
handleSelectedRelatedLinks()
}
private fun handleSelectedRelatedLinks() {
compositeSubscription.add(
Observable.merge(arrayListOf(
view.onSelectedRelatedLinksComicLink(),
view.onSelectedRelatedLinksDetail(),
view.onSelectedRelatedLinksWiki()
)).subscribe({ url ->
view.showUrl(url)
}, { err ->
Timber.e(err)
})
)
}
private fun handleSelectedComics() {
compositeSubscription.add(
Observable.merge(
arrayListOf(
view.onSelectedComicBook(),
view.onSelectedEventsBook(),
view.onSelectedSeriesBook(),
view.onSelectedStoriesBook()
)
)
.observeOn(viewScheduler)
.subscribe({ comicBook ->
view.showComicsCovers(characterId, comicBook.comicBookType)
}, { err -> Timber.e(err) })
)
}
private fun loadCharacterData() {
view.showLoading()
val getCharacterResponse = getCharacterDetailsUseCase.execute(
GetSpecificCharacterDetails.Request(characterId))
val characterRxResponse = getCharacterResponse
.character
.observeOn(viewScheduler)
.doOnSuccess { character ->
view.showCharacterDetails(character)
}
val comicsRxResponse = getCharacterResponse
.comics
.observeOn(viewScheduler)
.doOnSuccess { comics ->
view.showCharacterComics(comics)
}
val eventsRxResponse = getCharacterResponse
.events
.observeOn(viewScheduler)
.doOnSuccess { events ->
view.showCharacterEvents(events)
}
val seriesRxResponse = getCharacterResponse
.series
.observeOn(viewScheduler)
.doOnSuccess { series ->
view.showCharacterSeries(series)
}
val storiesRxResponse = getCharacterResponse
.stories
.observeOn(viewScheduler)
.doOnSuccess { stories ->
view.showCharacterStories(stories)
}
compositeSubscription.add(
Single.merge(
arrayListOf(characterRxResponse, comicsRxResponse, eventsRxResponse, seriesRxResponse,
storiesRxResponse))
.subscribeOn(ioScheduler)
.observeOn(viewScheduler)
.subscribe(
{ _ ->
view.hideLoading()
},
{ err -> Timber.e(err) }
)
)
}
}
| 0
|
Kotlin
|
0
| 0
|
6c3826bedf71087f0eb22c398a20f480dde5b45b
| 3,780
|
MarvelCharactersApp
|
MIT License
|
src/Day10.kt
|
hoppjan
| 433,705,171
| false
|
{"Kotlin": 29015, "Shell": 338}
|
fun main() {
fun part1(input: List<String>) =
input.sumOf { line ->
line.lineScore()
}
fun part2(input: List<String>) =
input.filterNotCorrupted()
.map { it.completionScore() }
.median()
val day = "10"
val testInput = StringInputReader.read("Day${day}_test")
val input = StringInputReader.read("Day$day")
// part 1
val testSolution1 = 26397
val testOutput1 = part1(testInput)
printTestResult(1, testOutput1, testSolution1)
check(testOutput1 == testSolution1)
printResult(1, part1(input).also { check(it == 216297) })
// part 2
val testSolution2 = 288957L
val testOutput2 = part2(testInput)
printTestResult(2, testOutput2, testSolution2)
check(testOutput2 == testSolution2)
printResult(2, part2(input).also { check(it == 2165057169L) })
}
private fun String.lineScore() = analyzeBrackets(default = 0) { scoreMapPartOne[it] ?: 0 }
private fun String.completionScore(): Long =
openBrackets { openedBrackets ->
openedBrackets
.mapNotNull { scoreMapPartTwo[brackets[it]] }
.reversed()
.fold(0L) { acc, i ->
acc * 5 + i
}
}
private fun String.openBrackets(withOpenBrackets: (MutableList<Char>) -> Long) =
analyzeBrackets(withOpenBrackets) { 0L }
private fun List<String>.filterNotCorrupted() = filter { it.isNotCorrupted() }
private fun String.isNotCorrupted() = analyzeBrackets(default = true) { false }
private fun <R> String.analyzeBrackets(default: R, onUnexpected: (Char) -> R) =
analyzeBrackets({ default }, onUnexpected)
private fun <R> String.analyzeBrackets(onDefault: (MutableList<Char>) -> R, onUnexpected: (Char) -> R): R {
val opened = mutableListOf<Char>()
for (bracket in this)
when (bracket) {
in brackets ->
opened.add(bracket)
brackets[opened.lastOrNull()] ->
opened.removeLast()
else ->
return onUnexpected(bracket)
}
return onDefault(opened)
}
fun List<Long>.median() = sorted().let { it[it.size / 2] }
val brackets = mapOf(
'(' to ')',
'[' to ']',
'{' to '}',
'<' to '>',
)
val scoreMapPartOne = mapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137,
)
val scoreMapPartTwo = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4,
)
| 0
|
Kotlin
|
0
| 0
|
04f10e8add373884083af2a6de91e9776f9f17b8
| 2,434
|
advent-of-code-2021
|
Apache License 2.0
|
app/src/main/java/com/froggie/design/ui/player/PlayerFragment.kt
|
ucdevinda123
| 387,638,747
| false
| null |
package com.froggie.design.ui.player
import android.animation.Animator
import android.animation.ValueAnimator
import android.os.Bundle
import android.view.View
import android.widget.SeekBar
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.navArgs
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieComposition
import com.froggie.design.R
import com.froggie.design.databinding.FragmentPlayerBinding
import com.froggie.design.viewmodel.PlayerViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.roundToInt
@AndroidEntryPoint
class PlayerFragment : Fragment(R.layout.fragment_player) {
private lateinit var playerBinding: FragmentPlayerBinding
private val playerViewModel: PlayerViewModel by viewModels()
private val animationArgs by navArgs<PlayerFragmentArgs>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
playerBinding = FragmentPlayerBinding.bind(view)
hideAndShowLoader(true)
registerLottiePlayerListeners()
playerViewModel.loadLottieFileFromUrl(
context,
animationArgs.AnimationData.lottieUrl
)
playerViewModel.lottieComposition.observe(viewLifecycleOwner) { lottieMetaData ->
run {
onLoadLottieCompositionData(lottieMetaData)
}
}
}
private val playerAnimationListenerCallBack = object : Animator.AnimatorListener {
override fun onAnimationStart(p0: Animator?) {
togglePlayButton(true)
}
override fun onAnimationEnd(p0: Animator?) {
togglePlayButton(false)
}
override fun onAnimationCancel(p0: Animator?) {
togglePlayButton(false)
}
override fun onAnimationRepeat(p0: Animator?) {
togglePlayButton(false)
}
}
private val animateUpdateListenerCallCallback = ValueAnimator.AnimatorUpdateListener {
run {
playerBinding.playerControls.currentFrameView.text =
updateFramesAndDurationLabel(playerBinding.playerAnimation)
playerBinding.playerControls.seekBar.progress =
((it.animatedValue as Float) * playerBinding.playerControls.seekBar.max).roundToInt()
}
}
private fun minScale() = 0.05f
private fun maxScale(): Float {
val screenWidth = resources.displayMetrics.widthPixels.toFloat()
val screenHeight = resources.displayMetrics.heightPixels.toFloat()
return min(
screenWidth,
screenHeight
)
}
private val seekBarChangeListener = object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(p0: SeekBar?, progress: Int, p2: Boolean) {
val minScale = minScale()
val maxScale = maxScale()
val scale = minScale + progress / 100f * (maxScale - minScale)
playerBinding.playerAnimation.scale = scale
}
override fun onStartTrackingTouch(p0: SeekBar?) = Unit
override fun onStopTrackingTouch(p0: SeekBar?) = Unit
}
private fun registerLottiePlayerListeners() {
playerBinding.playerAnimation.addAnimatorListener(playerAnimationListenerCallBack)
playerBinding.playerAnimation.addAnimatorUpdateListener(animateUpdateListenerCallCallback)
playerBinding.playerControls.seekBar.setOnSeekBarChangeListener(seekBarChangeListener)
playerBinding.playerControls.playButton.setOnClickListener {
if (playerBinding.playerAnimation.isAnimating) {
playerBinding.playerAnimation.pauseAnimation()
togglePlayButton(false)
} else {
playerBinding.playerAnimation.resumeAnimation()
togglePlayButton(true)
}
playerBinding.playerControls.playButton.isActivated =
playerBinding.playerAnimation.isAnimating
playerBinding.playerAnimation.invalidate()
}
}
override fun onDestroyView() {
super.onDestroyView()
playerBinding.playerAnimation.removeAnimatorListener(playerAnimationListenerCallBack)
playerBinding.playerAnimation.removeUpdateListener(animateUpdateListenerCallCallback)
}
private fun onLoadLottieCompositionData(composition: LottieComposition?) {
composition ?: return
/* playerBinding.playerAnimation.setRenderMode(RenderMode.HARDWARE)
playerBinding.playerAnimation.imageAssetsFolder = "images/"*/
playerBinding.playerAnimation.enableMergePathsForKitKatAndAbove(true)
// playerBinding.playerAnimation.setCacheComposition(true)
playerBinding.playerAnimation.setComposition(composition)
hideAndShowLoader(false)
}
private fun updateFramesAndDurationLabel(animation: LottieAnimationView): String {
val currentFrame = animation.frame.toString()
val totalFrames = ("%.0f").format(animation.maxFrame)
val animationSpeed: Float = abs(animation.speed)
val totalTime = ((animation.duration / animationSpeed) / 1000.0)
val totalTimeFormatted = ("%.1f").format(totalTime)
val progress = (totalTime / 100.0) * ((animation.progress * 100.0).roundToInt())
val progressFormatted = ("%.1f").format(progress)
return "$currentFrame/$totalFrames\n$progressFormatted/$totalTimeFormatted"
}
private fun togglePlayButton(isActivated: Boolean) {
playerBinding.playerControls.playButton.isActivated = isActivated
if (isActivated) playerBinding.playerControls.playButton.setImageResource(R.drawable.ic_baseline_pause_24) else playerBinding.playerControls.playButton.setImageResource(
R.drawable.ic_baseline_play_arrow_24
)
}
private fun hideAndShowLoader(isVisible: Boolean) {
playerBinding.loadingView.isVisible = isVisible
}
}
| 0
|
Kotlin
|
0
| 1
|
87196c1f8ce41db55aade42ea76f721ff7593422
| 6,111
|
froggie-mvvm
|
Apache License 2.0
|
src/jvmMain/kotlin/dev/romainguy/kotlin/explorer/code/CodeStyle.kt
|
romainguy
| 677,575,533
| false
|
{"Kotlin": 1823030, "Lex": 42156, "Python": 11996}
|
/*
* Copyright (C) 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.romainguy.kotlin.explorer.code
data class CodeStyle(
val indent: Int = 4,
val showLineNumbers: Boolean = true,
val lineNumberWidth: Int = 4,
)
| 3
|
Kotlin
|
24
| 798
|
d42fe12f8d40b3e5b55a22032ea09aeb82397d72
| 765
|
kotlin-explorer
|
Apache License 2.0
|
core/model/src/main/java/com/hellguy39/hellnotes/core/model/AppSettings.kt
|
HellGuy39
| 572,830,054
| false
| null |
package com.hellguy39.hellnotes.core.model
data class AppSettings(
/* Security */
val isPinSetup: Boolean,
val appPin: String,
val isUseBiometric: Boolean,
) {
constructor(): this(false, "", false)
}
| 0
|
Kotlin
|
0
| 4
|
218ffb7bd5febc09248a3cb3c1995c4cd15b10c9
| 221
|
HellNotes
|
Apache License 2.0
|
src/test/kotlin/com/kalikov/game/EnemyFactoryTest.kt
|
kalikov
| 696,277,791
| false
|
{"Kotlin": 401152}
|
package com.kalikov.game
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.clearInvocations
import org.mockito.kotlin.isA
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.reset
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertTrue
class EnemyFactoryTest {
private lateinit var clock: TestClock
private lateinit var eventManager: EventManager
private lateinit var pauseManager: PauseManager
private lateinit var spriteContainer: SpriteContainer
@BeforeEach
fun beforeEach() {
clock = TestClock()
eventManager = mock()
pauseManager = mock()
spriteContainer = mock()
}
@Test
fun `should subscribe`() {
val factory = createFactory(emptyList(), emptyList())
verify(eventManager).addSubscriber(factory, setOf(TankExplosion.Destroyed::class, Tank.Hit::class))
}
@Test
fun `should iterate over positions in a loop`() {
val position1 = Point(0, 0)
val position2 = Point(10, 20)
val position3 = Point(40, 100)
val factory = createFactory(
listOf(position1, position2, position3),
emptyList()
)
assertEquals(position1, factory.nextPosition())
assertEquals(position2, factory.nextPosition())
assertEquals(position3, factory.nextPosition())
assertEquals(position1, factory.nextPosition())
}
@Test
fun `should iterate over enemies in a loop`() {
val group1 = EnemyGroupConfig(Tank.EnemyType.BASIC, 1)
val group2 = EnemyGroupConfig(Tank.EnemyType.FAST, 2)
val group3 = EnemyGroupConfig(Tank.EnemyType.BASIC, 1)
val factory = createFactory(
emptyList(),
listOf(group1, group2, group3)
)
assertEquals(group1.type, factory.nextEnemy())
assertEquals(group2.type, factory.nextEnemy())
assertEquals(group2.type, factory.nextEnemy())
assertEquals(group3.type, factory.nextEnemy())
assertEquals(group1.type, factory.nextEnemy())
}
@Test
fun `should spawn no more than limit respecting interval`() {
val factory = createFactory(
listOf(Point()),
listOf(EnemyGroupConfig(Tank.EnemyType.BASIC, 4)),
4,
)
factory.enemyCountLimit = 2
factory.update()
assertEquals(1, factory.enemyCount)
assertFalse(factory.enemyCountLimitReached)
clock.tick(1)
factory.update()
assertEquals(1, factory.enemyCount)
assertFalse(factory.enemyCountLimitReached)
clock.tick(1)
factory.update()
assertEquals(1, factory.enemyCount)
assertFalse(factory.enemyCountLimitReached)
clock.tick(1)
factory.update()
assertEquals(1, factory.enemyCount)
assertFalse(factory.enemyCountLimitReached)
clock.tick(1)
factory.update()
assertEquals(2, factory.enemyCount)
assertTrue(factory.enemyCountLimitReached)
clock.tick(1)
factory.update()
assertEquals(2, factory.enemyCount)
assertTrue(factory.enemyCountLimitReached)
clock.tick(1)
factory.update()
assertEquals(2, factory.enemyCount)
assertTrue(factory.enemyCountLimitReached)
clock.tick(1)
factory.update()
assertEquals(2, factory.enemyCount)
assertTrue(factory.enemyCountLimitReached)
clock.tick(1)
factory.update()
assertEquals(2, factory.enemyCount)
assertTrue(factory.enemyCountLimitReached)
}
@Test
fun `should not spawn when paused`() {
whenever(pauseManager.isPaused).thenReturn(true)
val factory = createFactory(
listOf(Point()),
listOf(EnemyGroupConfig(Tank.EnemyType.BASIC, 4)),
1
)
factory.update()
assertEquals(0, factory.enemyCount)
clock.tick(1)
factory.update()
assertEquals(0, factory.enemyCount)
clock.tick(1)
factory.update()
assertEquals(0, factory.enemyCount)
}
@Test
fun `should stop creation when no more enemies left`() {
val positions = listOf(Point(0, 0), Point(10, 20), Point(40, 100))
val group1 = EnemyGroupConfig(Tank.EnemyType.BASIC, 1)
val group2 = EnemyGroupConfig(Tank.EnemyType.FAST, 2)
val group3 = EnemyGroupConfig(Tank.EnemyType.BASIC, 1)
val factory = createFactory(
positions,
listOf(group1, group2, group3),
1
)
factory.flashingIndices = emptySet()
factory.update()
verifyEnemyCreated(group1.type, positions[0])
reset(eventManager, spriteContainer)
clock.tick(1)
factory.update()
verifyEnemyCreated(group2.type, positions[1])
reset(eventManager, spriteContainer)
clock.tick(1)
factory.update()
verifyEnemyCreated(group2.type, positions[2])
reset(eventManager, spriteContainer)
clock.tick(1)
factory.update()
verifyEnemyCreated(group3.type, positions[0])
reset(eventManager, spriteContainer)
clock.tick(1)
factory.update()
verify(spriteContainer, never()).addSprite(any())
}
@Test
fun `should create enemy`() {
val position = Point(1, 2)
val factory = createFactory(
listOf(position),
listOf(EnemyGroupConfig(Tank.EnemyType.BASIC, 4))
)
assertEquals(0, factory.enemyCount)
factory.update()
verifyEnemyCreated(Tank.EnemyType.BASIC, position)
assertEquals(1, factory.enemyCount)
}
@Test
fun `should create flashing enemies in order`() {
val position = Point()
val factory = createFactory(
listOf(position),
listOf(EnemyGroupConfig(Tank.EnemyType.BASIC, 7)),
1
)
factory.flashingIndices = setOf(3, 5, 6)
factory.enemyCountLimit = 7
factory.update()
verifyEnemyCreated(Tank.EnemyType.BASIC, position)
reset(eventManager)
clock.tick(1)
factory.update()
verifyEnemyCreated(Tank.EnemyType.BASIC, position)
reset(eventManager)
clock.tick(1)
factory.update()
verifyEnemyCreated(Tank.EnemyType.BASIC, position, true)
reset(eventManager)
clock.tick(1)
factory.update()
verifyEnemyCreated(Tank.EnemyType.BASIC, position)
reset(eventManager)
clock.tick(1)
factory.update()
verifyEnemyCreated(Tank.EnemyType.BASIC, position, true)
reset(eventManager)
clock.tick(1)
factory.update()
verifyEnemyCreated(Tank.EnemyType.BASIC, position, true)
reset(eventManager)
clock.tick(1)
factory.update()
verifyEnemyCreated(Tank.EnemyType.BASIC, position)
}
@Test
fun `should track destroyed enemies`() {
val factory = createFactory(
listOf(Point(1, 2)),
listOf(EnemyGroupConfig(Tank.EnemyType.BASIC, 1))
)
factory.update()
assertEquals(1, factory.enemyCount)
val tank = verifyEnemyCreated()
val explosion = mockTankExplosion(eventManager, tank = tank)
factory.notify(TankExplosion.Destroyed(explosion))
assertEquals(0, factory.enemyCount)
}
@Test
fun `should notify when last enemy is destroyed`() {
val factory = createFactory(
listOf(Point()),
listOf(EnemyGroupConfig(Tank.EnemyType.BASIC, 1))
)
factory.update()
assertEquals(1, factory.enemyCount)
val tank = verifyEnemyCreated()
val explosion = mockTankExplosion(eventManager, tank = tank)
factory.notify(TankExplosion.Destroyed(explosion))
verify(eventManager).fireEvent(EnemyFactory.LastEnemyDestroyed)
}
@Test
fun `should not notify when destroyed enemy is not the last due to more to create`() {
val factory = createFactory(
listOf(Point()),
listOf(EnemyGroupConfig(Tank.EnemyType.BASIC, 2))
)
factory.update()
val tank = verifyEnemyCreated()
val explosion = mockTankExplosion(eventManager, tank = tank)
factory.notify(TankExplosion.Destroyed(explosion))
verify(eventManager, never()).fireEvent(EnemyFactory.LastEnemyDestroyed)
}
@Test
fun `should not notify when destroyed enemy is not the last due to left on the field`() {
val factory = createFactory(
listOf(Point()),
listOf(EnemyGroupConfig(Tank.EnemyType.BASIC, 2)),
1
)
factory.update()
val tank = verifyEnemyCreated()
clock.tick(1)
factory.update()
assertEquals(0, factory.enemiesToCreateCount)
val explosion = mockTankExplosion(eventManager, tank = tank)
factory.notify(TankExplosion.Destroyed(explosion))
verify(eventManager, never()).fireEvent(EnemyFactory.LastEnemyDestroyed)
}
@Test
fun `should return enemiesToCreateCount correctly`() {
val factory = createFactory(
listOf(Point()),
listOf(EnemyGroupConfig(Tank.EnemyType.BASIC, 3)),
1
)
assertEquals(3, factory.enemiesToCreateCount)
factory.update()
assertEquals(2, factory.enemiesToCreateCount)
clock.tick(1)
factory.update()
assertEquals(1, factory.enemiesToCreateCount)
clock.tick(1)
factory.update()
assertEquals(0, factory.enemiesToCreateCount)
}
@Test
fun `should spawn new tank immediately after tank is destroyed`() {
val factory = createFactory(
listOf(Point()),
listOf(EnemyGroupConfig(Tank.EnemyType.BASIC, 3)),
10000
)
factory.enemyCountLimit = 1
factory.update()
val tank = verifyEnemyCreated()
clearInvocations(eventManager)
clock.tick(10000)
factory.update()
verify(eventManager, never()).fireEvent(isA<EnemyFactory.EnemyCreated>())
clock.tick(5000)
factory.update()
val explosion = mockTankExplosion(eventManager, tank = tank)
factory.notify(TankExplosion.Destroyed(explosion))
factory.update()
verifyEnemyCreated()
}
private fun verifyEnemyCreated(
type: Tank.EnemyType,
position: Point,
flashing: Boolean = false
): Tank {
val event = captureEnemyCreated()
val tank = event.enemy
assertEquals(type, tank.enemyType)
assertEquals(position, tank.position)
assertIs<TankStateAppearing>(tank.state)
assertFalse(tank.isPlayer)
assertEquals(flashing, event.isFlashing)
return tank
}
private fun verifyEnemyCreated(): Tank {
return captureEnemyCreated().enemy
}
private fun captureEnemyCreated(): EnemyFactory.EnemyCreated {
val captor = argumentCaptor<EnemyFactory.EnemyCreated>()
verify(eventManager).fireEvent(captor.capture())
return captor.firstValue
}
private fun createFactory(
positions: List<Point>,
enemies: List<EnemyGroupConfig>,
interval: Int = 3000
): EnemyFactory {
return EnemyFactory(
eventManager,
mock(),
pauseManager,
spriteContainer,
positions,
clock,
enemies,
interval
)
}
}
| 0
|
Kotlin
|
0
| 0
|
a2964b0e473f7e49a013f6d3d24303f51a79cbf0
| 11,906
|
battle-city
|
MIT License
|
src/main/kotlin/no/nav/k9/los/integrasjon/audit/AuditLogger.kt
|
navikt
| 238,874,021
| false
|
{"Kotlin": 1605106, "JavaScript": 741, "Shell": 659, "Dockerfile": 343, "PLpgSQL": 167}
|
package no.nav.k9.los.integrasjon.audit
import no.nav.k9.los.Configuration
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class Auditlogger constructor(
val configuration: Configuration,
val isEnabled: Boolean = configuration.auditEnabled(),
val defaultVendor: String = configuration.auditVendor(),
val defaultProduct: String = configuration.auditProduct()
) {
fun logg(auditdata: Auditdata) {
if (isEnabled) {
auditLogger.info(auditdata.toString())
}
}
companion object {
private val auditLogger: Logger = LoggerFactory.getLogger("auditLogger")
}
}
| 9
|
Kotlin
|
0
| 0
|
f433261d48ead37dc6ad19be0333db471b484590
| 630
|
k9-los-api
|
MIT License
|
statistics/statistics-impl/src/main/java/com/duckduckgo/app/statistics/config/StatisticsLibraryConfig.kt
|
duckduckgo
| 78,869,127
| false
| null |
/*
* Copyright (c) 2021 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.app.statistics.config
import com.duckduckgo.appbuildconfig.api.AppBuildConfig
/**
* If you want to configure the statistics library, have your app extend this listener
* and implement the different methods.
* The library will check through the application context.
*/
interface StatisticsLibraryConfig {
fun shouldFirePixelsAsDev(): Boolean
}
class DefaultStatisticsLibraryConfig(private val appBuildConfig: AppBuildConfig) : StatisticsLibraryConfig {
override fun shouldFirePixelsAsDev(): Boolean {
return appBuildConfig.isDebug
}
}
| 67
| null |
901
| 3,823
|
6415f0f087a11a51c0a0f15faad5cce9c790417c
| 1,183
|
Android
|
Apache License 2.0
|
src/main/java/com/arman/kotboy/core/io/input/Controller.kt
|
coenvk
| 182,844,893
| false
|
{"Kotlin": 327296, "Batchfile": 143}
|
package com.arman.kotboy.core.io.input
import com.arman.kotboy.core.io.Joypad
import java.awt.event.KeyEvent
abstract class Controller : InputHandler {
protected abstract val bindings: MutableList<Keybinding>
final override fun keyPressed(e: KeyEvent) {
val key = getKey(e)
key?.let { buttonListener?.onPress(it) }
}
final override fun keyReleased(e: KeyEvent) {
val key = getKey(e)
key?.let { buttonListener?.onRelease(it) }
}
private fun getKey(e: KeyEvent): Joypad.Key? {
bindings.forEach {
if (it.keyCode == e.keyCode) {
return it.button
}
}
return null
}
}
| 0
|
Kotlin
|
2
| 3
|
709efa50a0b176d7ed8aefe4db0f35f173472de2
| 692
|
KotBoy
|
MIT License
|
app/src/main/java/net/appitiza/workmanager/ui/activities/admin/SetSalaryActivity.kt
|
appitiza
| 131,850,434
| false
| null |
package net.appitiza.workmanager.ui.activities.admin
import android.app.ProgressDialog
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.text.TextUtils
import android.view.View
import android.widget.AdapterView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.SetOptions
import kotlinx.android.synthetic.main.activity_set_salary.*
import kotlinx.android.synthetic.main.item_toolbar.*
import net.appitiza.workmanager.R
import net.appitiza.workmanager.adapter.AdminSpnrUserAdapter
import net.appitiza.workmanager.constants.Constants
import net.appitiza.workmanager.model.UserListdata
import net.appitiza.workmanager.ui.activities.BaseActivity
import net.appitiza.workmanager.ui.activities.interfaces.UserClick
import net.appitiza.workmanager.utils.PreferenceHelper
import net.appitiza.workmanager.utils.Utils
import java.util.*
class SetSalaryActivity : BaseActivity(), UserClick {
private var isLoggedIn by PreferenceHelper(Constants.PREF_KEY_IS_USER_LOGGED_IN, false)
private var displayName by PreferenceHelper(Constants.PREF_KEY_IS_USER_DISPLAY_NAME, "")
private var useremail by PreferenceHelper(Constants.PREF_KEY_IS_USER_EMAIL, "")
private var userpassword by PreferenceHelper(Constants.PREF_KEY_IS_USER_PASSWORD, "")
private var usertype by PreferenceHelper(Constants.PREF_KEY_IS_USER_USER_TYPE, "")
private var mAuth: FirebaseAuth? = null
private lateinit var db: FirebaseFirestore
private var mProgress: ProgressDialog? = null
private lateinit var mUserList: ArrayList<UserListdata>
private lateinit var userAdapter: AdminSpnrUserAdapter
private var user: UserListdata? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_set_salary)
setActionbar()
initializeFireBase()
getUser()
setClick()
}
private fun setActionbar() {
val toolbar: Toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
if (getSupportActionBar() != null) {
tv_title.text = getString(R.string.set_salary)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
toolbar.setNavigationOnClickListener { onBackPressed() }
}
private fun initializeFireBase() {
mUserList = arrayListOf()
mProgress = ProgressDialog(this)
mAuth = FirebaseAuth.getInstance()
db = FirebaseFirestore.getInstance()
}
private fun setClick() {
tv_admin_salary_set.setOnClickListener { setSalary(et_admin_salary.text.toString()) }
spnr_admin_salary_to.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
user = mUserList[position]
}
}
}
private fun getUser() {
mProgress?.setTitle(getString(R.string.app_name))
mProgress?.setMessage(getString(R.string.getting_site))
mProgress?.setCancelable(false)
mProgress?.show()
db.collection(Constants.COLLECTION_USER)
.whereEqualTo(Constants.USER_TYPE, "user")
.get()
.addOnCompleteListener { fetchall_task ->
mProgress?.dismiss()
if (fetchall_task.isSuccessful) {
for (document in fetchall_task.result) {
val data = UserListdata()
data.emailId = document.data[Constants.USER_EMAIL].toString()
data.username = document.data[Constants.USER_DISPLAY_NAME].toString()
mUserList.add(data)
}
userAdapter = AdminSpnrUserAdapter(this, mUserList, this)
spnr_admin_salary_to.adapter = userAdapter
mProgress?.dismiss()
} else {
Utils.showDialog(this, fetchall_task.exception?.message.toString())
}
}
}
private fun setSalary(amount: String) {
if (validation(amount)) {
mProgress?.setTitle(getString(R.string.app_name))
mProgress?.setMessage(getString(R.string.sending_notification))
mProgress?.setCancelable(false)
mProgress?.show()
// Sign in success, update UI with the signed-in user's information
val map = HashMap<String, Any>()
map[Constants.USER_SALARY] = amount
db.collection(Constants.COLLECTION_USER)
.document(user?.emailId.toString())
.set(map, SetOptions.merge())
.addOnCompleteListener { send_task ->
if (send_task.isSuccessful) {
mProgress!!.dismiss()
Utils.showDialog(this, getString(R.string.salary_set_done))
et_admin_salary.setText("")
} else {
mProgress!!.hide()
Utils.showDialog(this, send_task.exception?.message.toString())
}
}
} else {
Utils.showDialog(this, "Please fill all details")
}
}
private fun validation(amount: String): Boolean {
return if (TextUtils.isEmpty(amount)) {
showValidationWarning(getString(R.string.title_missing))
false
} else if (TextUtils.isEmpty(user?.emailId.toString())) {
showValidationWarning(getString(R.string.user_missing))
false
} else {
true
}
}
override fun onUserClick(data: UserListdata) {
}
}
| 2
| null |
3
| 5
|
adab092ddb838726cfbf24390728665effea2abf
| 6,097
|
workmanager
|
The Unlicense
|
src/chapter1/section3/ex44_TextEditorBuffer.kt
|
hb44
| 360,857,712
| true
|
{"Kotlin": 1262005}
|
package chapter1.section3
import edu.princeton.cs.algs4.Stack
import extensions.readInt
import extensions.readString
import extensions.safeCall
import java.security.InvalidParameterException
class Buffer {
//控制台无法打印Char,所以用一个字符长度的String代替
private val firstHalfStack = Stack<String>()
private val secondHalfStack = Stack<String>()
fun insert(char: String) {
if (char.length > 1) {
throw InvalidParameterException("Not a character")
}
firstHalfStack.push(char)
}
fun delete(): String {
return firstHalfStack.pop()
}
fun left(k: Int) {
repeat(k) {
secondHalfStack.push(firstHalfStack.pop())
}
}
fun right(k: Int) {
repeat(k) {
firstHalfStack.push(secondHalfStack.pop())
}
}
fun size() = firstHalfStack.size() + secondHalfStack.size()
fun site() = firstHalfStack.size()
fun output(): Iterator<String> {
left(site())
return secondHalfStack.iterator()
}
}
fun main() {
println("Please input command:")
println("0: exit, 1: insert, 2: delete, 3: left, 4: right, 5: size, 6: site, 7: output")
val buffer = Buffer()
while (true) {
safeCall {
val command = readInt("command: ")
when (command) {
0 -> return
1 -> {
val value = readString("insert value: ")
if (value.length > 1) {
println("Please enter a character")
} else {
buffer.insert(value)
}
}
2 -> {
buffer.delete()
println("has delete")
}
3 -> {
buffer.left(readInt("left value: "))
}
4 -> {
buffer.right(readInt("right value: "))
}
5 -> {
println("buffer.size = ${buffer.size()}")
}
6 -> {
println("buffer.site = ${buffer.site()}")
}
7 -> {
print("buffer output: ")
buffer.output().forEach {
print(it)
print(" ")
}
println()
}
else -> {
}
}
}
}
}
| 0
| null |
0
| 0
|
5664f07094df80ed3cff0c7f5c981f6fe9d5523b
| 2,500
|
Algorithms-4th-Edition-in-Kotlin
|
MIT License
|
photofilterssdk/src/main/java/com/zomato/photofilters/imageprocessors/ImageProcessor.kt
|
PaulHost
| 207,349,609
| false
| null |
package com.zomato.photofilters.imageprocessors
import android.graphics.Bitmap
object ImageProcessor {
fun applyCurves(rgb: IntArray, red: IntArray, green: IntArray, blue: IntArray, inputImage: Bitmap): Bitmap {
val width = inputImage.width
val height = inputImage.height
var pixels = IntArray(width * height)
inputImage.getPixels(pixels, 0, width, 0, 0, width, height)
pixels = NativeImageProcessor.applyRGBCurve(pixels, rgb, width, height)
pixels = NativeImageProcessor.applyChannelCurves(pixels, red, green, blue, width, height)
try {
inputImage.setPixels(pixels, 0, width, 0, 0, width, height)
} finally {
return inputImage
}
}
fun doBrightness(value: Int, inputImage: Bitmap): Bitmap {
val width = inputImage.width
val height = inputImage.height
val pixels = IntArray(width * height)
inputImage.getPixels(pixels, 0, width, 0, 0, width, height)
NativeImageProcessor.doBrightness(pixels, value, width, height)
inputImage.setPixels(pixels, 0, width, 0, 0, width, height)
return inputImage
}
fun doContrast(value: Float, inputImage: Bitmap): Bitmap {
val width = inputImage.width
val height = inputImage.height
val pixels = IntArray(width * height)
inputImage.getPixels(pixels, 0, width, 0, 0, width, height)
NativeImageProcessor.doContrast(pixels, value, width, height)
inputImage.setPixels(pixels, 0, width, 0, 0, width, height)
return inputImage
}
fun doColorOverlay(depth: Int, red: Float, green: Float, blue: Float, inputImage: Bitmap): Bitmap {
val width = inputImage.width
val height = inputImage.height
val pixels = IntArray(width * height)
inputImage.getPixels(pixels, 0, width, 0, 0, width, height)
NativeImageProcessor.doColorOverlay(pixels, depth, red, green, blue, width, height)
inputImage.setPixels(pixels, 0, width, 0, 0, width, height)
return inputImage
}
fun doSaturation(inputImage: Bitmap, level: Float): Bitmap {
val width = inputImage.width
val height = inputImage.height
val pixels = IntArray(width * height)
inputImage.getPixels(pixels, 0, width, 0, 0, width, height)
NativeImageProcessor.doSaturation(pixels, level, width, height)
inputImage.setPixels(pixels, 0, width, 0, 0, width, height)
return inputImage
}
}
| 1
| null |
1
| 1
|
3a17296a90df11bbc36cbaddf84a1794301673a2
| 2,518
|
AndroidPhotoFilters
|
Apache License 2.0
|
src/main/kotlin/com/github/kerubistan/kerub/model/User.kt
|
kerubistan
| 19,528,622
| false
| null |
package com.github.kerubistan.kerub.model
data class User(
val userName: String,
val quota: Quota? = null
)
| 109
|
Kotlin
|
4
| 14
|
99cb43c962da46df7a0beb75f2e0c839c6c50bda
| 112
|
kerub
|
Apache License 2.0
|
app/src/main/java/com/example/todoapp/feature_todo/presentation/todo_new_update/TodoNewUpdateScreen.kt
|
litvinnik1
| 754,164,981
| false
|
{"Kotlin": 84982}
|
package com.example.todoapp.feature_todo.presentation.todo_new_update
import android.annotation.SuppressLint
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Save
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.example.todoapp.R
import com.example.todoapp.core.presentation.components.ArchivedButton
import com.example.todoapp.core.presentation.components.CompleteButton
import com.example.todoapp.core.presentation.components.DeleteButton
import com.example.todoapp.core.presentation.components.getTodoColors
import com.example.todoapp.core.util.ContentDescription
import com.example.todoapp.core.util.NewUpdateStrings
import com.example.todoapp.core.util.TodoListStrings
import com.example.todoapp.feature_todo.presentation.todo_new_update.components.HintTextField
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@ExperimentalMaterial3Api
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TodoNewUpdateScreen(
navController: NavController,
viewModel: TodoNewUpdateViewModel = hiltViewModel()
) {
val state = viewModel.state.value
val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
val todoColors = getTodoColors(todo = state.todo)
val configuration = LocalConfiguration.current
val isPortrait =
configuration.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT
val topBarHeight = if(isPortrait) 64.dp else 0.dp
val horizontalPadding = 16.dp
val verticalPadding = if(isPortrait) 16.dp else 2.dp
LaunchedEffect(key1 = true) {
viewModel.eventFlow.collectLatest { event ->
when (event) {
TodoNewUpdateViewModel.UiEvent.Back -> {
navController.navigateUp()
}
TodoNewUpdateViewModel.UiEvent.SaveTodo -> {
navController.navigateUp()
}
is TodoNewUpdateViewModel.UiEvent.ShowSnackbar -> {
snackbarHostState.showSnackbar(
message = event.message
)
}
}
}
}
Scaffold(
floatingActionButton = {
if (!isPortrait) {
FloatingActionButton(
onClick = {
viewModel.onEvent(TodoNewUpdateEvent.SaveTodo)
},
shape = CircleShape,
containerColor = MaterialTheme.colorScheme.primary
) {
Icon(
imageVector = Icons.Default.Save,
contentDescription = ContentDescription.SAVE_TODO,
tint = MaterialTheme.colorScheme.onPrimary
)
}
}
},
topBar = {
if (isPortrait) {
CenterAlignedTopAppBar(
title = {
Text(
text = TodoListStrings.TODO_LIST,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onPrimary
)
},
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
containerColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.7f),
scrolledContainerColor = MaterialTheme.colorScheme.primary,
navigationIconContentColor = MaterialTheme.colorScheme.onPrimary,
titleContentColor = MaterialTheme.colorScheme.onPrimary,
actionIconContentColor = MaterialTheme.colorScheme.onPrimary
),
navigationIcon = {
IconButton(
onClick = {
viewModel.onEvent(TodoNewUpdateEvent.Back)
},
modifier = Modifier.padding(start = 8.dp)
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = ContentDescription.BACK,
tint = MaterialTheme.colorScheme.onPrimary
)
}
},
actions = {},
scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
)
}
},
bottomBar = {
if (isPortrait) {
BottomAppBar(
actions = {
CompleteButton(
onCompleteClick = {
viewModel.onEvent(TodoNewUpdateEvent.ToggleCompleted)
},
color = todoColors.checkColor,
completed = state.todo.completed
)
ArchivedButton(
onArchivedClick = {
viewModel.onEvent(TodoNewUpdateEvent.ToggleArchived)
}
)
DeleteButton(
onDeleteClick = {
scope.launch {
val confirm = snackbarHostState.showSnackbar(
message = NewUpdateStrings.CONFIRM_DELETE,
actionLabel = NewUpdateStrings.YES
)
if (confirm == SnackbarResult.ActionPerformed) {
viewModel.onEvent(TodoNewUpdateEvent.Delete)
}
}
}
)
},
floatingActionButton = {
FloatingActionButton(
onClick = {
viewModel.onEvent(TodoNewUpdateEvent.SaveTodo)
},
shape = CircleShape,
containerColor = MaterialTheme.colorScheme.primary
) {
Icon(
imageVector = Icons.Default.Save,
contentDescription = ContentDescription.SAVE_TODO,
tint = MaterialTheme.colorScheme.onPrimary
)
}
},
containerColor = MaterialTheme.colorScheme.background.copy(alpha = 0.5f)
)
}
},
snackbarHost = { SnackbarHost(hostState = snackbarHostState)}
) { padding ->
Box(
contentAlignment = Alignment.TopStart,
modifier = Modifier
.fillMaxSize()
.background(color = todoColors.backgroundColor)
) {
Column(
modifier = Modifier
.padding(top = topBarHeight)
.fillMaxSize()
){
HintTextField(
text = state.todo.title,
hint = NewUpdateStrings.TITLE_HINT,
textColor = todoColors.textColor,
onValueChange = {
viewModel.onEvent(TodoNewUpdateEvent.EnteredTitle(it))
},
onFocusChange = {
viewModel.onEvent(TodoNewUpdateEvent.ChangedTitleFocus(it))
},
isHintVisible = state.isTitleHintVisible,
singleLine = true,
fontSize = 40.sp,
modifier = Modifier.padding(
horizontal = horizontalPadding,
vertical = verticalPadding
)
)
Spacer(modifier = Modifier.height(verticalPadding))
HintTextField(
text = state.todo.description,
hint = NewUpdateStrings.DESCRIPTION_HINT,
textColor = todoColors.textColor,
onValueChange = {
viewModel.onEvent(TodoNewUpdateEvent.EnteredDescription(it))
},
onFocusChange = {
viewModel.onEvent(TodoNewUpdateEvent.ChangedDescriptionFocus(it))
},
isHintVisible = state.isDescriptionHintVisible,
singleLine = false,
modifier = Modifier
.fillMaxHeight()
.padding(
horizontal = horizontalPadding,
vertical = verticalPadding
)
)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
04dc760bf01ebfcc91efa8ef67719ab4d608e15b
| 11,236
|
TodoApp
|
Apache License 2.0
|
src/main/kotlin/io/github/oxisto/reticulated/ast/expression/ConditionalExpression.kt
|
AndHager
| 244,382,209
| true
|
{"Kotlin": 276598, "ANTLR": 26984, "Python": 2008}
|
/*
* Copyright (c) 2020, <NAME> and <NAME>. All rights reserved.
*
* 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.oxisto.reticulated.ast.expression
import io.github.oxisto.reticulated.ast.CouldNotParseException
import io.github.oxisto.reticulated.ast.expression.booleanops.BaseBooleanOp
import io.github.oxisto.reticulated.ast.expression.booleanops.OrTest
/**
* This class represents a conditional_expression
* It´s EBNF representation is:
* conditional_expression ::= or_test ["if" or_test "else" expression]
* [see: https://docs.python.org/3/reference/expressions.html#conditional-expressions]
*/
class ConditionalExpression(val orTest: BaseBooleanOp, val orTestOptional: OrTest?, val expressionOptional: Expression?): Expression() {
init {
if(orTestOptional == null){
if(expressionOptional != null){
throw CouldNotParseException()
}
}else{
if(expressionOptional == null){
throw CouldNotParseException()
}
}
}
override fun isCall(): Boolean {
return false
}
override fun toString(): String {
var result = "ConditionalExpression(" + System.lineSeparator() +
"\torTest=$orTest"
if(orTestOptional != null){
result += " if orTest=$orTestOptional else expression=$expressionOptional"
}
result += System.lineSeparator() + ")"
return result
}
}
| 0
|
Kotlin
|
0
| 0
|
95b24f52e1c2e37c004048e1e8274885b3fa08ed
| 1,909
|
reticulated-python
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/hmpps/nomisprisonerapi/jpa/AdjudicationIncidentRepairs.kt
|
ministryofjustice
| 444,895,409
| false
| null |
package uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa
import jakarta.persistence.Column
import jakarta.persistence.Embeddable
import jakarta.persistence.EmbeddedId
import jakarta.persistence.Entity
import jakarta.persistence.FetchType
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import jakarta.persistence.Table
import org.hibernate.Hibernate
import org.hibernate.annotations.JoinColumnOrFormula
import org.hibernate.annotations.JoinColumnsOrFormulas
import org.hibernate.annotations.JoinFormula
import java.io.Serializable
import java.math.BigDecimal
@Embeddable
class AdjudicationIncidentRepairId(
@Column(name = "AGENCY_INCIDENT_ID", nullable = false)
var agencyIncidentId: Long,
@Column(name = "REPAIR_SEQ", nullable = false)
var repairSequence: Int,
) : Serializable
@Entity
@Table(name = "AGENCY_INCIDENT_REPAIRS")
class AdjudicationIncidentRepair(
@EmbeddedId
val id: AdjudicationIncidentRepairId,
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "AGENCY_INCIDENT_ID", insertable = false, updatable = false)
val incident: AdjudicationIncident,
@Column(name = "COMMENT_TEXT")
val comment: String? = null,
@Column(name = "REPAIR_COST")
val repairCost: BigDecimal? = null,
@ManyToOne
@JoinColumnsOrFormulas(
value = [
JoinColumnOrFormula(
formula = JoinFormula(
value = "'" + AdjudicationRepairType.REPAIR_TYPE + "'",
referencedColumnName = "domain",
),
), JoinColumnOrFormula(column = JoinColumn(name = "REPAIR_TYPE", referencedColumnName = "code", nullable = true)),
],
)
val type: AdjudicationRepairType,
@Column(name = "CREATE_USER_ID", insertable = false, updatable = false)
val createUsername: String = "",
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || Hibernate.getClass(this) != Hibernate.getClass(other)) return false
other as AdjudicationIncidentRepair
return id == other.id
}
override fun hashCode(): Int = javaClass.hashCode()
}
| 1
|
Kotlin
|
0
| 0
|
9d941b432a73cebd4fcb3107a2a0330fe3d20391
| 2,067
|
hmpps-nomis-prisoner-api
|
MIT License
|
app/src/main/java/com/letter/days/utils/AnniversaryUtil.kt
|
NevermindZZT
| 164,197,780
| false
| null |
package com.letter.days.utils
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.*
import android.view.Gravity
import com.letter.days.database.AppDatabase
import com.letter.days.database.entity.AnniversaryEntity
/**
* 纪念日工具
*
* @author Letter(<EMAIL>)
* @since 1.0.0
*/
/**
* 获取纪念日日期字符串文本
* @param anniversary AnniversaryEntity? 纪念日
* @param format String 日期格式
* @param lunarFormat String 农历日期格式
* @return String? 日期字符串文本
*/
fun getDateString(anniversary: AnniversaryEntity?,
format: String = "%s/%s/%s",
lunarFormat: String = "%s %s %s") =
anniversary?.getDateString(format, lunarFormat)
/**
* 纪念日获取类型文本
* @param anniversary AnniversaryEntity? 纪念日
* @return String? 类型文本
*/
fun getTypeText(anniversary: AnniversaryEntity?) =
anniversary?.getTypeText()
/**
* 获取纪念日天数文本
* @param anniversary AnniversaryEntity? 纪念日
* @return String? 天数文本
*/
fun getDayText(anniversary: AnniversaryEntity?) =
anniversary?.getDayText()
/**
* 获取纪念日下一次时间
* @param anniversary AnniversaryEntity? 纪念日
* @return Int? 下一次时间
*/
fun getNextTime(anniversary: AnniversaryEntity?) =
anniversary?.getNextTime()
/**
* 获取进度条Drawable
* @param anniversary AnniversaryEntity? 纪念日
* @return Drawable? Drawable
*/
fun getProgressDrawable(anniversary: AnniversaryEntity?): Drawable? {
if (anniversary == null) {
return null
}
val backDrawable = ColorDrawable(Color.TRANSPARENT)
val gradientDrawable = GradientDrawable()
gradientDrawable.setColor(anniversary.color)
val clipDrawable = ClipDrawable(gradientDrawable, Gravity.START, ClipDrawable.HORIZONTAL)
val drawable = LayerDrawable(arrayOf(backDrawable, clipDrawable))
drawable.setId(0, android.R.id.background)
drawable.setId(1, android.R.id.progress)
return drawable
}
/**
* 获取最近的纪念日
* @param context Context context
* @return AnniversaryEntity? 最近的纪念日
*/
suspend fun getClosestAnniversary(context: Context): AnniversaryEntity? {
val anniversaries = AppDatabase.instance(context.applicationContext)
.anniversaryDao()
.getAll().toMutableList()
anniversaries.sortBy {
val nextTime = it.getNextTime()
if (nextTime < 0) 367 else nextTime
}
return anniversaries[0]
}
| 0
|
Kotlin
|
1
| 9
|
641bc9587bc8edbe569653c3242cb08fc7bfc071
| 2,311
|
Days
|
MIT License
|
src/main/kotlin/de/megonno/cannibalkitchen/inventory/MInventory.kt
|
Megonno
| 822,249,651
| false
|
{"Kotlin": 60118}
|
package de.megonno.cannibalkitchen.inventory
import de.megonno.cannibalkitchen.inventory.gui.MGui
import net.kyori.adventure.text.Component
import org.bukkit.entity.Player
import org.bukkit.event.inventory.InventoryCloseEvent
import org.bukkit.inventory.InventoryHolder
abstract class MInventory<I : MInventory<I>>(
val name: Component, var mGui: MGui? = null, val tags: MutableMap<String, String> = mutableMapOf()
) : InventoryHolder {
abstract val mInventoryFunctionHandler: MInventoryFunctionHandler<I>?
abstract fun open(player: Player)
abstract fun close(player: Player, reason: InventoryCloseEvent.Reason = InventoryCloseEvent.Reason.PLUGIN)
abstract fun update()
}
| 0
|
Kotlin
|
0
| 0
|
142780e92e341162492c67658afa427f8008c050
| 697
|
CannibalKitchen
|
MIT License
|
source-code/final-project/app/src/main/java/com/droidcon/destress/History.kt
|
droidcon-academy
| 675,493,475
| false
| null |
package com.droidcon.destress
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.droidcon.destress.domain.RelaxEvent
import com.droidcon.destress.domain.RelaxType
import com.droidcon.destress.domain.testList
@Composable
fun History(events: List<RelaxEvent>) {
val focusCount = events.count { it.type == RelaxType.DeepFocus }
val breathCount = events.size - focusCount
Text("You completed $focusCount focus events and $breathCount breath events")
}
@Preview
@Composable
fun PreviewHistory() {
History(testList)
}
| 0
|
Kotlin
|
0
| 1
|
8ba0697a013a3130fd0ed4223bd014e848b96941
| 624
|
android-cbc-compose-canvas-draw-animate
|
Apache License 2.0
|
app/src/main/java/com/example/c323p6notes/NotesFragment.kt
|
kuzeybektas
| 703,330,136
| false
|
{"Kotlin": 14608}
|
package com.example.c323p6notes
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.example.c323p6notes.databinding.FragmentNotesBinding
class NotesFragment :Fragment(){
val TAG = "NotesFragment"
private var _binding:FragmentNotesBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//variables
_binding = FragmentNotesBinding.inflate(inflater, container, false)
val view = binding.root
val application = requireNotNull(this.activity).application
val dao = NoteDatabase.getInstance(application).noteDao
val viewModelFactory = NotesViewModelFactory(dao)
val viewModel = ViewModelProvider(this, viewModelFactory)
.get(NotesViewModel::class.java)
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
//access variable to access clicked note
fun notesClicked(noteId:Long){
viewModel.onNoteClicked(noteId)
}
//delete note if "yes" is pressed from dialog
fun yesPressed(noteId:Long){
Log.d(TAG, "in yesPressed(): noteId = $noteId")
viewModel.deleteById(noteId)
}
//show dialog when delete button is clicked
fun deleteClicked(noteId:Long){
ConfirmDeleteDialogFragment(noteId, ::yesPressed).show(childFragmentManager,
ConfirmDeleteDialogFragment.TAG)
}
//adapter
val adapter = NoteItemAdapter(::notesClicked, ::deleteClicked)
binding.RecycleV.adapter = adapter
//observe notes
viewModel.notes.observe(viewLifecycleOwner, Observer{
it?.let{
adapter.submitList(it)
}
})
//navigate to clicked note
viewModel.navigateToNote.observe(viewLifecycleOwner, Observer { noteId->
noteId?.let{
val action = NotesFragmentDirections
.actionNotesFragmentToEditNoteFragment(noteId)
this.findNavController().navigate(action)
viewModel.onNoteNavigated()
}
})
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 0
|
b6216bfb9fb5adf1948d4b0d9bc2590d1baa4424
| 2,636
|
NotesApp
|
Apache License 2.0
|
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/mechanics/run/RunEnergy.kt
|
AlterRSPS
| 421,831,790
| false
| null |
package gg.rsmod.plugins.content.mechanics.run
import gg.rsmod.game.model.bits.INFINITE_VARS_STORAGE
import gg.rsmod.game.model.bits.InfiniteVarsType
import gg.rsmod.game.model.timer.TimerKey
import gg.rsmod.game.model.entity.Player
import gg.rsmod.plugins.api.EquipmentType
import gg.rsmod.plugins.api.Skills
import gg.rsmod.plugins.api.ext.hasStorageBit
import gg.rsmod.plugins.api.ext.sendRunEnergy
import gg.rsmod.plugins.api.ext.setVarp
import gg.rsmod.plugins.api.ext.toggleVarp
/**
* @author Tom <<EMAIL>>
*/
object RunEnergy {
val RUN_DRAIN = TimerKey()
/**
* Reduces run energy depletion by 70%
*/
val STAMINA_BOOST = TimerKey("stamina_boost", tickOffline = false)
const val RUN_ENABLED_VARP = 173
fun toggle(p: Player) {
if (p.runEnergy >= 1.0) {
p.toggleVarp(RUN_ENABLED_VARP)
} else {
p.setVarp(RUN_ENABLED_VARP, 0)
p.message("You don't have enough run energy left.")
}
}
fun drain(p: Player) {
if (p.isRunning() && p.hasMoveDestination()) {
if (!p.hasStorageBit(INFINITE_VARS_STORAGE, InfiniteVarsType.RUN)) {
val weight = Math.max(0.0, p.weight)
var decrement = (Math.min(weight, 64.0) / 100.0) + 0.64
if (p.timers.has(STAMINA_BOOST)) {
decrement *= 0.3
}
p.runEnergy = Math.max(0.0, (p.runEnergy - decrement))
if (p.runEnergy <= 0) {
p.varps.setState(RUN_ENABLED_VARP, 0)
}
p.sendRunEnergy(p.runEnergy.toInt())
}
} else if (p.runEnergy < 100.0 && p.lock.canRestoreRunEnergy()) {
var recovery = (8.0 + (p.getSkills().getCurrentLevel(Skills.AGILITY) / 6.0)) / 100.0
if (isWearingFullGrace(p)) {
recovery *= 1.3
}
p.runEnergy = Math.min(100.0, (p.runEnergy + recovery))
p.sendRunEnergy(p.runEnergy.toInt())
}
}
private fun isWearingFullGrace(p: Player): Boolean =
p.equipment[EquipmentType.HEAD.id]?.id ?: -1 in GRACEFUL_HOODS &&
p.equipment[EquipmentType.CAPE.id]?.id ?: -1 in GRACEFUL_CAPE &&
p.equipment[EquipmentType.CHEST.id]?.id ?: -1 in GRACEFUL_TOP &&
p.equipment[EquipmentType.LEGS.id]?.id ?: -1 in GRACEFUL_LEGS &&
p.equipment[EquipmentType.GLOVES.id]?.id ?: -1 in GRACEFUL_GLOVES &&
p.equipment[EquipmentType.BOOTS.id]?.id ?: -1 in GRACEFUL_BOOTS
private val GRACEFUL_HOODS = intArrayOf(11850, 13579, 13591, 13603, 13615, 13627, 13667, 21061)
private val GRACEFUL_CAPE = intArrayOf(11852, 13581, 13593, 13605, 13617, 13629, 13669, 21064)
private val GRACEFUL_TOP = intArrayOf(11854, 13583, 13595, 13607, 13619, 13631, 13671, 21067)
private val GRACEFUL_LEGS = intArrayOf(11856, 13585, 13597, 13609, 13621, 13633, 13673, 21070)
private val GRACEFUL_GLOVES = intArrayOf(11858, 13587, 13599, 13611, 13623, 13635, 13675, 21073)
private val GRACEFUL_BOOTS = intArrayOf(11860, 13589, 13601, 13613, 13625, 13637, 13677, 21076)
}
| 8
| null |
29
| 20
|
a46e00462ac1943cdf3460e03595e1f383c32b91
| 3,194
|
Alter
|
Apache License 2.0
|
app/src/main/java/com/faigenbloom/familybudget/ui/register/RegisterPage.kt
|
ZakharchenkoWork
| 706,155,222
| false
|
{"Kotlin": 746176}
|
@file:OptIn(ExperimentalMaterial3Api::class)
package com.faigenbloom.familybudget.ui.register
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.faigenbloom.familybudget.R
import com.faigenbloom.familybudget.common.BaseButton
import com.faigenbloom.familybudget.common.BaseTextField
import com.faigenbloom.familybudget.common.StripeBar
import com.faigenbloom.familybudget.common.TextFieldType
import com.faigenbloom.familybudget.common.TopBar
import com.faigenbloom.familybudget.common.ui.Loading
import com.faigenbloom.familybudget.common.ui.dialogs.FailureDialog
import com.faigenbloom.familybudget.ui.theme.FamillySpandingsTheme
@Composable
fun RegisterPage(
state: RegisterPageState,
onBack: () -> Unit,
) {
Column {
TopBar(
startIcon = R.drawable.icon_arrow_back,
onStartIconCLicked = onBack,
)
StripeBar(textId = R.string.registration)
Spacer(modifier = Modifier.size(80.dp))
Column(
modifier = Modifier.padding(horizontal = 16.dp),
) {
FamilyNameFields(state = state)
CommonFields(state = state)
PrivacyPolicy(onClick = state.onPrivacyPolicyClicked)
BaseButton(
modifier = Modifier.padding(top = 16.dp),
textRes = R.string.registration,
isEnabled = state.isRegistrationEnabled,
onClick = state.onRegisterClicked,
)
}
}
FailureDialog(
isShown = state.migrationErrorDialogState.isShown,
text = stringResource(R.string.settings_family_migration_family_not_found),
onHideDialog = state.migrationErrorDialogState.onHideDialog,
)
val isLoading by remember { state.isLoading }
Loading(isShown = isLoading)
}
@Composable
private fun FamilyNameFields(state: RegisterPageState) {
if (state.isForFamily) {
Text(
modifier = Modifier
.fillMaxWidth(),
text = stringResource(id = R.string.joining_family, state.familyNameText),
color = MaterialTheme.colorScheme.onBackground,
style = MaterialTheme.typography.titleMedium,
)
} else {
BaseTextField(
modifier = Modifier
.fillMaxWidth(),
labelId = R.string.family_name,
text = state.familyNameText,
errorTextId = R.string.family_name_error,
isError = state.familyNameError,
textFieldType = TextFieldType.Normal,
onTextChange = state.onFamilyNameChanged,
)
}
BaseTextField(
modifier = Modifier.fillMaxWidth(),
labelId = R.string.surname,
text = state.surNameText,
textFieldType = TextFieldType.Normal,
onTextChange = state.onSurNameChanged,
)
}
@Composable
private fun CommonFields(state: RegisterPageState) {
BaseTextField(
modifier = Modifier
.fillMaxWidth(),
labelId = R.string.name,
text = state.nameText,
errorTextId = R.string.name_error,
isError = state.nameError,
textFieldType = TextFieldType.Normal,
onTextChange = state.onNameChanged,
)
BaseTextField(
modifier = Modifier
.fillMaxWidth(),
labelId = R.string.email,
text = state.emailText,
errorTextId = R.string.email_error,
isError = state.emailError,
textFieldType = TextFieldType.Email,
onTextChange = state.onEmailChanged,
)
BaseTextField(
modifier = Modifier
.fillMaxWidth(),
labelId = R.string.password,
text = state.passwordText,
errorTextId = R.string.password_error,
isError = state.passwordError,
textFieldType = TextFieldType.Password,
onTextChange = state.onPasswordChanged,
)
}
@Composable
private fun PrivacyPolicy(
onClick: () -> Unit,
) {
val annotatedString = buildAnnotatedString {
withStyle(style = SpanStyle(color = MaterialTheme.colorScheme.onPrimary)) {
append("${stringResource(id = R.string.privacy_policy_start)} ")
}
pushStringAnnotation(tag = "", annotation = "")
withStyle(style = SpanStyle(color = MaterialTheme.colorScheme.secondary)) {
append(stringResource(id = R.string.privacy_policy_end))
}
pop()
}
ClickableText(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
text = annotatedString,
style = MaterialTheme.typography.bodyMedium,
onClick = { onClick() },
)
}
@Preview(showBackground = true)
@Composable
private fun RegisterPagePreview() {
FamillySpandingsTheme {
Surface {
RegisterPage(
state = RegisterPageState(
emailText = Mock.loginText,
nameText = Mock.nameText,
familyNameText = Mock.familyNameText,
passwordText = <PASSWORD>,
nameError = false,
familyNameError = false,
registerError = false,
passwordError = false,
emailError = false,
isRegistrationEnabled = false,
isSameFamilyName = true,
onEmailChanged = {},
onPasswordChanged = {},
onNameChanged = {},
onFamilyNameChanged = {},
onSameFamilyNameSwitched = {},
onPrivacyPolicyClicked = {},
onRegisterClicked = {},
isForFamily = false,
surNameText = "",
onSurNameChanged = {},
),
onBack = {},
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e81fa66d6afd5b79d3299583a73378c3ee1463ca
| 6,741
|
FamilyBudget
|
Apache License 2.0
|
zcash-android-wallet-app/app/src/main/java/cash/z/android/wallet/vo/WalletTransaction.kt
|
gmale
| 151,591,683
| false
| null |
package cash.z.android.wallet.vo
import cash.z.android.wallet.R
import androidx.annotation.ColorRes
import java.math.BigDecimal
data class WalletTransaction(val status: WalletTransactionStatus, val timestamp: Long, val amount: BigDecimal)
enum class WalletTransactionStatus(@ColorRes val color: Int) {
SENT(R.color.colorPrimary),
RECEIVED(R.color.colorAccent);
}
| 1
|
Kotlin
|
1
| 1
|
689a9a522b4087bbf2573e1e704f6d11451def28
| 374
|
zcash-android-wallet-poc
|
Apache License 2.0
|
items/src/commonMain/kotlin/dev/garage/items/platform.kt
|
vchernyshov
| 255,430,518
| false
| null |
package dev.garage.items
expect fun platform(): String
| 0
|
Kotlin
|
1
| 5
|
76c84cdf7a14805c8d436224ce5bf32a2acccef1
| 55
|
kmp-items
|
MIT License
|
app/src/main/java/com/learning/photoshow/core/routers/Routing.kt
|
ramzyhassan44
| 358,888,621
| false
| null |
package com.learning.photoshow.core.routers
const val LISTING_PHOTOS_ROUTER = "LISTING_PHOTOS_ROUTER"
const val VIEWING_PHOTO_ROUTER = "VIEWING_PHOTO_ROUTER"
const val MAIN_SCREEN_ROUTER = "MAIN_SCREEN_ROUTER"
| 0
|
Kotlin
|
0
| 0
|
93004bd8e795235985180a8f0e92d5886065a4b7
| 210
|
photos-show
|
Apache License 2.0
|
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/PlayerSkipBack.kt
|
walter-juan
| 868,046,028
| false
|
{"Kotlin": 20416825}
|
package com.woowla.compose.icon.collections.tabler.tabler.outline
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.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
public val OutlineGroup.PlayerSkipBack: ImageVector
get() {
if (_playerSkipBack != null) {
return _playerSkipBack!!
}
_playerSkipBack = Builder(name = "PlayerSkipBack", 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 = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(20.0f, 5.0f)
verticalLineToRelative(14.0f)
lineToRelative(-12.0f, -7.0f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 5.0f)
lineToRelative(0.0f, 14.0f)
}
}
.build()
return _playerSkipBack!!
}
private var _playerSkipBack: ImageVector? = null
| 0
|
Kotlin
|
0
| 1
|
b037895588c2f62d069c724abe624b67c0889bf9
| 1,911
|
compose-icon-collections
|
MIT License
|
platforms/intellij/skate/src/main/kotlin/foundry/intellij/skate/modeltranslator/GenerateTranslatorBodyAction.kt
|
slackhq
| 481,715,971
| false
|
{"Kotlin": 1071858, "Shell": 11199, "HTML": 1503, "Swift": 207}
|
/*
* Copyright (C) 2023 Slack Technologies, LLC
*
* 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 foundry.intellij.skate.modeltranslator
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import foundry.intellij.skate.SkateBundle
import foundry.intellij.skate.modeltranslator.helper.TranslatorHelper
import foundry.intellij.skate.modeltranslator.model.TranslatorBundle
import foundry.intellij.skate.tracing.SkateSpanBuilder
import foundry.intellij.skate.tracing.SkateTracingEvent
import foundry.intellij.skate.util.getTraceReporter
import foundry.intellij.skate.util.isTracingEnabled
import java.time.Instant
class GenerateTranslatorBodyAction(private val bundle: TranslatorBundle) : IntentionAction {
override fun getText() = SkateBundle.message("skate.modelTranslator.description")
override fun getFamilyName() = text
override fun isAvailable(project: Project, editor: Editor?, psiFile: PsiFile?) = true
override fun startInWriteAction() = true
override fun invoke(project: Project, editor: Editor?, psiFile: PsiFile?) {
val startTimestamp = Instant.now()
val body = TranslatorHelper.generateBody(bundle)
if (body != null) {
bundle.element.bodyBlockExpression?.replace(body) ?: LOG.warn("Body block expression is null")
if (project.isTracingEnabled()) {
sendUsageTrace(project, startTimestamp)
}
} else {
LOG.warn("Generated body is null")
}
}
private fun sendUsageTrace(project: Project, startTimestamp: Instant) {
val skateSpanBuilder =
SkateSpanBuilder().apply {
addTag("event", SkateTracingEvent.ModelTranslator.MODEL_TRANSLATOR_GENERATED)
}
project
.getTraceReporter()
.createPluginUsageTraceAndSendTrace(
"model_translator",
startTimestamp,
skateSpanBuilder.getKeyValueList(),
)
}
companion object {
private val LOG: Logger = Logger.getInstance(GenerateTranslatorBodyAction::class.java)
}
}
| 26
|
Kotlin
|
20
| 430
|
8228e72ef7f76a283df544793a8b9f68adceda46
| 2,645
|
foundry
|
Apache License 2.0
|
app/src/main/java/luyao/box/App.kt
|
Everglowzz
| 194,373,759
| false
|
{"Java": 197768, "Kotlin": 60334}
|
package luyao.box
import android.app.Application
import android.content.Context
import kotlin.properties.Delegates
/**
* Created by luyao
* on 2018/12/29 13:33
*/
class App : Application() {
companion object {
var CONTEXT: Context by Delegates.notNull()
}
override fun onCreate() {
super.onCreate()
CONTEXT = applicationContext
}
}
| 1
|
Java
|
1
| 2
|
892181baeef49be4eb53f785348ce3fc1b9aa7f3
| 380
|
Box-master
|
Apache License 2.0
|
avro4k-core/src/test/kotlin/com/sksamuel/avro4k/schema/URLSchemaTest.kt
|
chriswk
| 240,206,852
| true
|
{"Kotlin": 259873, "Shell": 87}
|
@file:UseSerializers(URLSerializer::class)
package com.sksamuel.avro4k.schema
import com.sksamuel.avro4k.Avro
import com.sksamuel.avro4k.serializer.URLSerializer
import io.kotlintest.shouldBe
import io.kotlintest.specs.FunSpec
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers
import java.net.URL
class URLSchemaTest : FunSpec({
test("accept URL as String") {
@Serializable
data class Test(val b: URL)
val schema = Avro.default.schema(Test.serializer())
val expected = org.apache.avro.Schema.Parser().parse(javaClass.getResourceAsStream("/url.json"))
schema shouldBe expected
}
test("accept nullable URL as String union") {
@Serializable
data class Test(val b: URL?)
val schema = Avro.default.schema(Test.serializer())
val expected = org.apache.avro.Schema.Parser().parse(javaClass.getResourceAsStream("/url_nullable.json"))
schema shouldBe expected
}
})
| 0
|
Kotlin
|
0
| 0
|
a5d321fd74c6c981038c3563420360465eb878ff
| 971
|
avro4k
|
Apache License 2.0
|
app/src/main/java/com/example/wikipedia_test/Fragment/Fragment_Profile.kt
|
prvsa2003
| 636,592,976
| false
| null |
package com.example.wikipedia_test.Fragment
import android.app.Activity.RESULT_OK
import android.app.Dialog
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Interpolator
import android.graphics.Paint
import android.graphics.Shader
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.PopupMenu
import androidx.fragment.app.Fragment
import com.example.wikipedia_test.R
import com.example.wikipedia_test.databinding.FragmentProfileBinding
import com.google.android.material.floatingactionbutton.FloatingActionButton
const val SELECT_IMAGE_REQUEST_CODE = 100
const val TAKE_PICTURE_REQUEST_CODE = 200
class Fragment_Profile : Fragment() {
private lateinit var binding: FragmentProfileBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = FragmentProfileBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.fabmain.setOnClickListener {
showPopupMenu(view)
}
binding.btnedit.setOnClickListener {
//دریافت مقادیر فعلی
val fullname = binding.txtfullname.text.toString()
val ID = binding.txtid.text.toString()
val number = binding.txtNUMBER.text.toString()
val email = binding.txtEmail.text.toString()
//ایجاد یک دیالوگ
val dialog = Dialog(requireContext())
dialog.setContentView(R.layout.dialog_edit)
val titleedittext: EditText = dialog.findViewById(R.id.dialog_edt_fullname)
titleedittext.setText(fullname)
val txtid: EditText = dialog.findViewById(R.id.dialog_edt_id)
txtid.setText(ID)
val txtnumber: EditText = dialog.findViewById(R.id.dialog_edt_number)
txtnumber.setText(number)
val txtemail: EditText = dialog.findViewById(R.id.dialog_edt_email)
txtemail.setText(email)
//ست ان کلیک لیستنر برای دکمه ی دان
val save: Button = dialog.findViewById(R.id.dialog_update_btn_done)
save.setOnClickListener {
//ذخیره ی مقادیر جدید
val newName = titleedittext.text.toString()
val newid = txtid.text.toString()
val newnumber = txtnumber.text.toString()
val newemail = txtemail.text.toString()
// پاس دادن مقادیر جدید به جای مقادیر قدیمی
binding.txtfullname.text = newName
binding.txtid.text = newid
binding.txtNUMBER.text = newnumber
binding.txtEmail.text = newemail
dialog.dismiss()
}
dialog.show()
}
}
private fun showPopupMenu(view: View) {
val fab: FloatingActionButton = binding.fabmain
val popup = PopupMenu(context, fab)
popup.inflate(R.menu.popup_menu)
popup.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.select_image -> {
selectImage()
true
}
R.id.take_picture -> {
takePicture()
true
}
else -> false
}
}
popup.show()
}
private fun selectImage() {
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent, SELECT_IMAGE_REQUEST_CODE)
}
private fun takePicture() {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, TAKE_PICTURE_REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
when (requestCode) {
SELECT_IMAGE_REQUEST_CODE -> {
val uri = data?.data
if (uri != null) {
val bitmap = BitmapFactory.decodeStream(
requireContext().contentResolver.openInputStream(uri)
)
binding.imgDetail.setImageBitmap(bitmap)
}
}
TAKE_PICTURE_REQUEST_CODE -> {
val bitmap = data?.extras?.get("data") as? Bitmap
if (bitmap != null) {
binding.imgDetail.setImageBitmap(bitmap)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
cf9d437b38929dd74b3846f57841d09cfdbceedc
| 5,079
|
wikipedia
|
MIT License
|
app/src/main/java/com/bitvolper/yogazzz/presentation/mybody/Utility.kt
|
sheikh-20
| 746,115,322
| false
|
{"Kotlin": 979402}
|
package com.bitvolper.yogazzz.presentation.mybody
import java.util.Calendar
import kotlin.math.ceil
import kotlin.math.pow
fun kgToLb(kg: Double): Double {
val lbsPerKg = 2.20462
val lb = kg * lbsPerKg
return ceil(lb * 100) / 100
}
fun lbToKg(lb: Double): Double {
val kgPerLb = 0.453592
val kg = lb * kgPerLb
return ceil(kg * 100) / 100
}
fun calculateAgeFromMilliseconds(milliseconds: Long): Int {
val currentDate = Calendar.getInstance()
val birthDate = Calendar.getInstance().apply {
timeInMillis = milliseconds
}
var age = currentDate.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR)
if (currentDate.get(Calendar.DAY_OF_YEAR) < birthDate.get(Calendar.DAY_OF_YEAR)) {
age--
}
return age
}
fun cmToFeet(heightCm: Int): Double {
return (heightCm / 30.48).round(1)
}
private fun Double.round(decimals: Int): Double {
val multiplier = 10.0.pow(decimals)
return kotlin.math.round(this * multiplier) / multiplier
}
fun feetToCm(feet: Double): Int {
return (feet * 30.48).toInt() // 1 foot = 30.48 centimeters
}
| 0
|
Kotlin
|
1
| 0
|
1afb7abb3932d9c4fc1d7b9371221fcc96061b34
| 1,101
|
YogaApp
|
The Unlicense
|
wearable/src/main/java/de/mulambda/slantedwatchface/ConfigActivity.kt
|
mu-lambda
| 324,634,748
| false
| null |
/*
* Copyright (c) 2021 - present The Slanted Watch Face Authors
*
* 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 de.mulambda.slantedwatchface
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.support.wearable.complications.*
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Switch
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.wear.widget.WearableRecyclerView
import java.util.concurrent.Executors
class ConfigActivity : Activity() {
companion object {
val REQUESTS_COMPLICATIONS = Complications.RANGE
private fun requestCodeOf(complicationId: Int) =
if (complicationId in Complications.RANGE) complicationId
else throw UnsupportedOperationException("complicationId = $complicationId")
const val REQUEST_PICK_COLOR_THEME = Complications.BOTTOM + 1
const val REQUEST_PICK_HOURS_COLOR = Complications.BOTTOM + 2
const val REQUEST_PICK_MINUTES_COLOR = Complications.BOTTOM + 3
const val REQUEST_PICK_SECONDS_COLOR = Complications.BOTTOM + 4
const val REQUEST_PICK_DATE_COLOR = Complications.BOTTOM + 5
const val REQUEST_PICK_TYPEFACE = Complications.BOTTOM + 6
object MenuItems {
const val PREVIEW = 0
const val COLOR_THEME = 1
const val IS_24H = 2
const val HANDEDNESS = 3
const val TYPEFACE = 4
const val RESET_SETTINGS = 5
}
}
private lateinit var sharedPreferences: SharedPreferences
private lateinit var configMenu: WearableRecyclerView
private lateinit var adapter: Adapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sharedPreferences = applicationContext.getSharedPreferences(
getString(R.string.preference_file_key),
Context.MODE_PRIVATE
)
setContentView(R.layout.config_activity)
adapter = Adapter()
configMenu = findViewById(R.id.config_menu)
configMenu.layoutManager = LinearLayoutManager(this)
configMenu.apply {
isEdgeItemsCenteringEnabled = true
setHasFixedSize(true)
adapter = this@ConfigActivity.adapter
}
}
override fun onDestroy() {
super.onDestroy()
adapter.destroy()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
Log.i(TAG(), "onActivityResult: requestCode=${requestCode} resultCode =${resultCode}")
if (resultCode != RESULT_OK) return
when (requestCode) {
REQUEST_PICK_COLOR_THEME -> {
if (data?.hasExtra(ColorSelectionActivity.RESULT) == true) {
adapter.updateColorTheme(data.getIntExtra(ColorSelectionActivity.RESULT, 0))
}
}
in REQUESTS_COMPLICATIONS -> adapter.updateComplications()
REQUEST_PICK_HOURS_COLOR -> updateIndividualColor(Settings.HOURS_COLOR, data)
REQUEST_PICK_MINUTES_COLOR -> updateIndividualColor(Settings.MINUTES_COLOR, data)
REQUEST_PICK_SECONDS_COLOR -> updateIndividualColor(Settings.SECONDS_COLOR, data)
REQUEST_PICK_DATE_COLOR -> updateIndividualColor(Settings.DATE_COLOR, data)
REQUEST_PICK_TYPEFACE -> updateTypeface(Settings.TYPEFACE, data)
}
}
private fun updateIndividualColor(binding: Settings.Binding<Int>, data: Intent?) {
if (data?.hasExtra(ColorSelectionActivity.RESULT) == true) {
val color = data.getIntExtra(ColorSelectionActivity.RESULT, 0)
with(sharedPreferences.edit()) {
binding.put(this, color)
when (binding) {
Settings.HOURS_COLOR -> {
Settings.COMPLICATION_TEXT_COLOR.put(this, color)
Settings.AM_PM_COLOR.put(this, color)
}
Settings.MINUTES_COLOR ->
Settings.COMPLICATION_ICON_COLOR.put(this, color)
}
apply()
}
}
}
private fun updateTypeface(binding: Settings.Binding<String>, data: Intent?) {
Log.i(TAG(), "updateTypeface")
if (data?.hasExtra(TypefaceSelectionActivity.TYPEFACE) == true) {
val typeface =
data.getStringExtra(TypefaceSelectionActivity.TYPEFACE)
?: Typefaces.DEFAULT.displayName
Log.i(TAG(), "typeface=${typeface}")
with(sharedPreferences.edit()) {
binding.put(this, typeface)
apply()
}
}
}
inner class Adapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val mProviderInfoRetriever: ProviderInfoRetriever =
ProviderInfoRetriever(
this@ConfigActivity,
Executors.newCachedThreadPool()
).apply { init() }
private lateinit var preview: WatchFacePreview
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
when (viewType) {
MenuItems.PREVIEW ->
return PreviewViewHolder(parent).also {
preview = it.view.apply {
onComplicationIdClick = ::selectComplication
onColorSettingClick = ::selectColor
}
}
MenuItems.HANDEDNESS ->
return HandednessViewHolder(parent)
MenuItems.IS_24H ->
return Is24HViewHolder(parent)
MenuItems.COLOR_THEME ->
return ColorThemeViewHolder(parent)
MenuItems.TYPEFACE ->
return SetTypefaceViewHolder(parent)
MenuItems.RESET_SETTINGS ->
return ResetSettingsViewHolder(parent)
}
throw UnsupportedOperationException()
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder.itemViewType) {
MenuItems.PREVIEW -> {
updateComplications()
return
}
MenuItems.COLOR_THEME, MenuItems.RESET_SETTINGS,
MenuItems.HANDEDNESS, MenuItems.IS_24H, MenuItems.TYPEFACE -> return
}
throw UnsupportedOperationException()
}
fun updateComplications() {
mProviderInfoRetriever.retrieveProviderInfo(
object : ProviderInfoRetriever.OnProviderInfoReceivedCallback() {
override fun onProviderInfoReceived(
complicationId: Int,
info: ComplicationProviderInfo?
) {
preview.setComplication(complicationId, info)
}
},
ComponentName(this@ConfigActivity, WatchFaceService::class.java),
*Complications.RANGE.toList().toIntArray()
)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
mProviderInfoRetriever.release()
super.onDetachedFromRecyclerView(recyclerView)
}
override fun getItemCount(): Int {
return 6
}
override fun getItemViewType(position: Int): Int = position
fun destroy() {
mProviderInfoRetriever.release()
}
fun updateColorTheme(color: Int?) {
Log.i(TAG(), "updateColorTheme: color = $color")
if (color == null) return
val newVeneer = Veneer
.fromSharedPreferences(sharedPreferences, assets, false)
.withColorScheme(color)
with(sharedPreferences.edit()) {
newVeneer.put(this)
apply()
}
}
}
private fun selectColor(binding: Settings.Binding<Int>) {
val requestCode = when (binding) {
Settings.HOURS_COLOR -> REQUEST_PICK_HOURS_COLOR
Settings.MINUTES_COLOR -> REQUEST_PICK_MINUTES_COLOR
Settings.SECONDS_COLOR -> REQUEST_PICK_SECONDS_COLOR
Settings.DATE_COLOR -> REQUEST_PICK_DATE_COLOR
else -> throw UnsupportedOperationException("$binding")
}
startActivityForResult(
Intent(this@ConfigActivity, ColorSelectionActivity::class.java)
.putExtra(ColorSelectionActivity.NAME, getString(binding.stringId))
.putExtra(
ColorSelectionActivity.ORIGINAL_COLOR,
binding.get(sharedPreferences)
),
requestCode
)
}
inner class ColorThemeViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.color_theme, parent, false)
), View.OnClickListener {
private val button: Button = itemView.findViewById(R.id.color_theme_button)
init {
button.setOnClickListener(this)
// dataButton.setCompoundDrawablesWithIntrinsicBounds(iconId, 0, 0, 0)
}
override fun onClick(v: View?) {
startActivityForResult(
Intent(this@ConfigActivity, ColorSelectionActivity::class.java)
.putExtra(ColorSelectionActivity.NAME, button.text)
.putExtra(
ColorSelectionActivity.ORIGINAL_COLOR,
Settings.HOURS_COLOR.get(sharedPreferences)
),
REQUEST_PICK_COLOR_THEME
)
}
}
inner class SetTypefaceViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.set_typeface, parent, false)
), View.OnClickListener {
init {
itemView.setOnClickListener(this)
}
override fun onClick(v: View?) {
startActivityForResult(
Intent(this@ConfigActivity, TypefaceSelectionActivity::class.java)
.putExtra(
TypefaceSelectionActivity.TYPEFACE,
Settings.TYPEFACE.get(sharedPreferences)
),
REQUEST_PICK_TYPEFACE
)
}
}
inner class PreviewViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.preview, parent, false)
) {
val view: WatchFacePreview = itemView.findViewById(R.id.preview)
}
inner class ResetSettingsViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.reset_settings, parent, false)
), View.OnClickListener {
init {
itemView.setOnClickListener(this)
}
override fun onClick(v: View?) {
with(sharedPreferences.edit()) {
Settings.applyDefault(this)
apply()
}
}
}
inner class HandednessViewHolder(
parent: ViewGroup,
) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.handedness, parent, false)
), View.OnClickListener, SharedPreferences.OnSharedPreferenceChangeListener {
@SuppressLint("UseSwitchCompatOrMaterialCode") // TOD0(#14)
private val switch: Switch = itemView.findViewById(R.id.handedness)
init {
itemView.setOnClickListener(this)
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
updateCurrentState()
}
private fun updateCurrentState() {
switch.setCompoundDrawablesWithIntrinsicBounds(
when (isOnRightHand(sharedPreferences)) {
true -> R.drawable.ic_watch_right_hand
false -> R.drawable.ic_watch_left_hand
},
0, 0, 0
)
switch.isChecked = isOnRightHand(sharedPreferences)
}
private fun isOnRightHand(sharedPreferences: SharedPreferences): Boolean =
!Settings.LEFT_HANDED.get(sharedPreferences)
override fun onClick(v: View?) {
Log.i(TAG(), "onClick")
val leftHanded = Settings.LEFT_HANDED.get(sharedPreferences)
with(sharedPreferences.edit()) {
Settings.LEFT_HANDED.put(this, !leftHanded)
apply()
}
}
override fun onSharedPreferenceChanged(
sharedPreferences: SharedPreferences?,
key: String?
) = updateCurrentState()
}
inner class Is24HViewHolder(
parent: ViewGroup,
) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.is24h, parent, false)
), View.OnClickListener, SharedPreferences.OnSharedPreferenceChangeListener {
@SuppressLint("UseSwitchCompatOrMaterialCode") // TOD0(#14)
private val switch: Switch = itemView.findViewById(R.id.is24h)
init {
itemView.setOnClickListener(this)
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
updateCurrentState()
}
private fun updateCurrentState() {
switch.isChecked = Settings.IS24H.get(sharedPreferences)
}
override fun onClick(v: View?) {
Log.i(TAG(), "onClick")
val is24h = Settings.IS24H.get(sharedPreferences)
with(sharedPreferences.edit()) {
Settings.IS24H.put(this, !is24h)
apply()
}
}
override fun onSharedPreferenceChanged(
sharedPreferences: SharedPreferences?,
key: String?
) = updateCurrentState()
}
private fun selectComplication(complicationId: Int) {
this@ConfigActivity.startActivityForResult(
ComplicationHelperActivity.createProviderChooserHelperIntent(
this,
ComponentName(this, WatchFaceService::class.java),
complicationId,
ComplicationData.TYPE_SHORT_TEXT
),
requestCodeOf(complicationId)
)
}
}
| 4
|
Kotlin
|
0
| 0
|
bacacff454fe792d6ab03aa3da715e829650730c
| 15,252
|
slantedWatchface
|
Apache License 2.0
|
app/src/main/java/com/pyamsoft/tickertape/setting/SettingsViewState.kt
|
pyamsoft
| 371,196,339
| false
| null |
package com.pyamsoft.tickertape.setting
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.pyamsoft.pydroid.arch.UiViewState
import com.pyamsoft.tickertape.core.ActivityScope
import javax.inject.Inject
interface SettingsViewState : UiViewState {
val topBarOffset: Int
}
@ActivityScope
internal class MutableSettingsViewState @Inject internal constructor() : SettingsViewState {
override var topBarOffset by mutableStateOf(0)
}
| 5
|
Kotlin
|
0
| 2
|
79edd1bb2fbc7d462da55709c1c5879ca37510fd
| 523
|
tickertape
|
Apache License 2.0
|
app/src/main/java/com/pyamsoft/tickertape/setting/SettingsViewState.kt
|
pyamsoft
| 371,196,339
| false
| null |
package com.pyamsoft.tickertape.setting
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.pyamsoft.pydroid.arch.UiViewState
import com.pyamsoft.tickertape.core.ActivityScope
import javax.inject.Inject
interface SettingsViewState : UiViewState {
val topBarOffset: Int
}
@ActivityScope
internal class MutableSettingsViewState @Inject internal constructor() : SettingsViewState {
override var topBarOffset by mutableStateOf(0)
}
| 5
|
Kotlin
|
0
| 2
|
79edd1bb2fbc7d462da55709c1c5879ca37510fd
| 523
|
tickertape
|
Apache License 2.0
|
tmp/arrays/youTrackTests/9205.kt
|
DaniilStepanov
| 228,623,440
| false
|
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
|
// Original bug: KT-15775
@Target(AnnotationTarget.TYPE)
annotation class A
val fn: (@A Int) -> Unit = null!!
val test1 = fn // ': (Int) -> Unit', should be: ': (@A Int) -> Unit'
| 1
| null |
1
| 1
|
602285ec60b01eee473dcb0b08ce497b1c254983
| 181
|
bbfgradle
|
Apache License 2.0
|
core/src/main/kotlin/com/osmp4j/features/HighwayFeatureFactory.kt
|
fleonhard
| 199,824,414
| false
| null |
package com.osmp4j.features
import com.osmp4j.data.Highway
import com.osmp4j.data.Node
import com.osmp4j.data.osm.elements.OSMNode
import com.osmp4j.data.osm.features.OSMHighway
import com.osmp4j.extensions.isFeature
import com.osmp4j.features.core.ExtendNodeFeatureFactory
import com.osmp4j.features.core.Neo4jType
object HighwayFeatureFactory : ExtendNodeFeatureFactory<Highway, Node>(NodeFeatureFactory) {
override fun isType(osmNode: OSMNode) = osmNode.isFeature(OSMHighway)
override fun typeName() = "highway"
override fun fromOSM(value: OSMNode) = Highway(
id = value.id,
lat = value.lat,
lon = value.lon,
version = value.version,
timestamp = value.timestamp,
uid = value.uid
)
override fun fromCSV(tokens: List<String>) = Highway(
id = tokens[0].toLong(),
lat = tokens[1].toDouble(),
lon = tokens[2].toDouble(),
version = tokens[3].toInt(),
timestamp = tokens[4],
uid = tokens[5].toLong()
)
override fun getExtensionHeader() = listOf<String>()
override fun getExtensionTypes() = listOf<Neo4jType>()
override fun getExtensionValues(obj: Highway) = listOf<Any>()
override fun getExtensionLabel() = "Highway"
}
| 1
|
Kotlin
|
0
| 0
|
93d04a3a1dd2597eb2ce2646139efa82b563d389
| 1,305
|
osmp4j
|
Apache License 2.0
|
src/test/kotlin/com/news/app/auth/UserServiceTest.kt
|
shohelasad
| 700,488,693
| false
|
{"Kotlin": 57166, "Dockerfile": 158}
|
package com.news.app.auth
import com.news.app.dto.AuthRequest
import com.news.app.dto.RegisterRequest
import com.news.app.entity.User
import com.news.app.exception.RegisteredException
import com.news.app.repository.UserRepository
import com.news.app.security.JwtService
import com.news.app.service.UserService
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.test.context.ActiveProfiles
import java.util.*
@ActiveProfiles("test")
class UserServiceTest {
@Mock
private lateinit var userRepository: UserRepository
@Mock
private lateinit var passwordEncoder: PasswordEncoder
@Mock
private lateinit var jwtService: JwtService
@Mock
private lateinit var authenticationManager: AuthenticationManager
@InjectMocks
private lateinit var userService: UserService
@BeforeEach
fun setUp() {
MockitoAnnotations.initMocks(this)
}
@Test
fun testRegisterWithUser() {
val registerRequest = RegisterRequest("<EMAIL>", "testuser", "<PASSWORD>")
`when`(userRepository.findByUsernameOrEmail(registerRequest.username, registerRequest.email)).thenReturn(User())
assertThrows(RegisteredException::class.java) {
userService.register(registerRequest)
}
}
@Test
fun testAuthenticate() {
val authRequest = AuthRequest("testuser", "password")
val user = User(
email = "<EMAIL>",
username = "testuser",
password = "<PASSWORD>"
)
`when`(userRepository.findByUsername(authRequest.username)).thenReturn(user)
`when`(jwtService.generateToken(user)).thenReturn("test_token")
val authResponse = userService.authenticate(authRequest)
assertEquals("test_token", authResponse.token)
}
@Test
fun testAuthenticateWithInvalidUser() {
val authRequest = AuthRequest("testuser", "password")
`when`(userRepository.findByUsername(authRequest.username)).thenReturn(null)
val exception = assertThrows<NullPointerException> {
userService.authenticate(authRequest)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5e210befb088e93389100d37e6121298580a687f
| 2,652
|
Kotlin-Rest-APIs
|
MIT License
|
yeventbus/src/main/java/com/lewis_v/yeventbus/YEventHandle.kt
|
lewis-v
| 154,311,397
| false
| null |
package com.lewis_v.yeventbus
class YEventHandle : IEventHandle {
/**
* 发布消息
* @param observable
* @param data
* @param <T>
* @throws InterruptedException
</T> */
override fun <T : Any> postEvent(observable: YObservable, data: T) {
handle(observable, data)
}
/**
* 在当前程处理
* @param observable
* @param data
* @param <T>
</T> */
private fun <T : Any> handle(observable: YObservable, data: T) {
observable.postEvent(data)
}
}
| 0
| null |
0
| 1
|
bc448ec5226e2c071c0b55e7de38c9d5a3ec0cef
| 520
|
YEventBus2
|
Apache License 2.0
|
app/src/main/java/musicboxd/android/data/remote/api/musicbrainz/model/artist/MusicBrainzArtistData.kt
|
MusicBoxd
| 793,151,068
| false
|
{"Kotlin": 532615}
|
package musicboxd.android.data.remote.api.musicbrainz.model.artist
import kotlinx.serialization.Serializable
@Serializable
data class MusicBrainzArtistData(
val relations: List<Relation>
)
| 0
|
Kotlin
|
0
| 2
|
499f56faeaf6208982b618ef75743e6c4d4e829a
| 194
|
android
|
MIT License
|
microapp/news/src/main/java/bruhcollective/itaysonlab/jetisoft/microapp/news/ui/OuterNavigation.kt
|
iTaysonLab
| 525,967,051
| false
|
{"Kotlin": 203833}
|
package bruhcollective.itaysonlab.microapp.library.ui
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.navigation.NavHostController
import bruhcollective.itaysonlab.microapp.core.Destinations
@Immutable
internal class OuterNavigation(
private val controller: NavHostController,
private val destinations: Destinations
) {
}
internal val LocalOuterNavigation = staticCompositionLocalOf<OuterNavigation> { error("LocalOuterNavigation for this microapp is not defined!") }
| 0
|
Kotlin
|
0
| 13
|
f651cfc692852c378c9cd3b4e41d8aa1b5a76eb5
| 546
|
jetisoft
|
Apache License 2.0
|
src/test/kotlin/com/virusbear/beanstalkt/operation/ListTubeUsedOperationTest.kt
|
virusbear
| 697,417,178
| false
|
{"Kotlin": 59390, "Java": 195}
|
package com.virusbear.beanstalkt.operation
import com.virusbear.beanstalkt.response.UsingResponse
import com.virusbear.beanstalkt.writePacketAsText
import kotlinx.coroutines.runBlocking
import kotlin.test.*
class ListTubeUsedOperationTest {
@Test
fun write() = runBlocking {
val op = ListTubeUsedOperation()
val packet = op.writePacketAsText()
assertEquals("list-tube-used\r\n", packet)
}
@Test
fun read() = runBlocking {
val tube = "default"
val op = ListTubeUsedOperation()
val response = UsingResponse(tube)
op.read(response)
val using = op.await()
assertEquals(tube, using)
}
}
| 0
|
Kotlin
|
0
| 0
|
a045a7abdf351366e742a8d12b95172be28c1d39
| 685
|
beanstalkt
|
Apache License 2.0
|
server/src/main/kotlin/com/kamelia/hedera/rest/file/DTO.kt
|
Black-Kamelia
| 492,280,011
| false
| null |
@file:UseSerializers(UUIDSerializer::class)
package com.kamelia.hedera.rest.file
import com.kamelia.hedera.rest.core.DTO
import com.kamelia.hedera.rest.core.pageable.PageDTO
import com.kamelia.hedera.util.UUIDSerializer
import com.kamelia.hedera.util.uuid
import java.util.UUID
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers
fun File.toRepresentationDTO(): FileRepresentationDTO = FileRepresentationDTO(
uuid,
code,
name,
mimeType,
size,
visibility.toString(),
ownerId
)
/**
* DTO used to transfer upload update details.
*
* **Front -> Back**
*/
@Serializable
data class FileUpdateDTO(
val name: String? = null,
val visibility: FileVisibility? = null,
) : DTO
/**
* DTO used to transfer upload details to front.
*
* **Back -> Front**
*/
@Serializable
data class FileRepresentationDTO(
val id: UUID,
val code: String,
val name: String,
val mimeType: String,
val size: Long,
val visibility: String,
val ownerId: UUID,
) : DTO
@Serializable
data class FilePageDTO(
val page: PageDTO<FileRepresentationDTO>,
) : DTO
| 3
|
Kotlin
|
0
| 9
|
23b16a0000769665d1d97a54dc8459935edfdb50
| 1,133
|
Hedera
|
Apache License 2.0
|
app/src/main/java/com/test/restaurant/data/model/ServiceArea.kt
|
Imranseu17
| 481,709,159
| false
| null |
package com.test.restaurant.data.model
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
data class ServiceArea (
@JsonProperty("code" ) var serviceAreaCode : String? ,
@JsonProperty("name" ) var serviceAreaName : String?
){
constructor():this("","")
override fun toString(): String {
return "ServiceArea(serviceAreaCode=$serviceAreaCode, serviceAreaName=$serviceAreaName)"
}
}
| 0
|
Kotlin
|
1
| 0
|
fdb3b766622ee6116246ed8d6019f10923ac71ff
| 507
|
ShopApplication
|
Apache License 2.0
|
javalin/src/main/java/io/javalin/http/HandlerType.kt
|
tipsy
| 87,012,358
| false
| null |
/*
* Javalin - https://javalin.io
* Copyright 2017 <NAME>
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.http
import io.javalin.core.util.Header
import javax.servlet.http.HttpServletRequest
enum class HandlerType {
GET, POST, PUT, PATCH, DELETE, HEAD, TRACE, CONNECT, OPTIONS, BEFORE, AFTER, INVALID;
fun isHttpMethod() = when (this) {
GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH -> true
else -> false
}
companion object {
private val methodMap = values().map { it.toString() to it }.toMap()
fun fromServletRequest(httpRequest: HttpServletRequest): HandlerType {
val key = httpRequest.getHeader(Header.X_HTTP_METHOD_OVERRIDE) ?: httpRequest.method
return methodMap[key.toUpperCase()] ?: INVALID
}
}
}
| 8
| null |
488
| 5,665
|
aef72d2a09773b688a646dbe9c47845c9a6da497
| 870
|
javalin
|
Apache License 2.0
|
src/me/anno/utils/structures/arrays/DirtyCharSequence.kt
|
AntonioNoack
| 456,513,348
| false
| null |
package me.anno.utils.structures.arrays
/**
* a [CharSequence], which does no proper character conversion; it is meant for
* coloring programming code only, and should not be used for String generation
* */
class DirtyCharSequence(val base: IntSequence, val i0: Int = 0, val i1: Int = base.length) : CharSequence {
override val length: Int = i1 - i0
override fun get(index: Int): Char = base[i0 + index].toChar()
fun firstOrNull() = base.getOrNull(i0)?.toChar()
override fun subSequence(startIndex: Int, endIndex: Int): CharSequence {
return DirtyCharSequence(base, i0 + startIndex, i0 + endIndex)
}
override fun toString(): String {
val builder = StringBuilder(length)
// could be optimized
for (index in i0 until i1) {
builder.append(Character.toChars(base[index]))
}
return builder.toString()
}
}
| 0
|
Kotlin
|
3
| 9
|
94bc7c74436aa567ec3c19f386dd67af0f1ced00
| 897
|
RemsEngine
|
Apache License 2.0
|
core/commonTest/src/contract/map/ImmutableMapTest.kt
|
SebastianAigner
| 359,509,020
| true
|
{"Kotlin": 562446}
|
/*
* Copyright 2016-2019 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
package tests.contract.map
import kotlinx.collections.immutable.*
import tests.contract.collectionBehavior
import tests.contract.compare
import tests.contract.mapBehavior
import tests.contract.setBehavior
import tests.stress.IntWrapper
import kotlin.test.*
class ImmutableHashMapTest : ImmutableMapTest() {
override fun <K, V> immutableMapOf(vararg pairs: Pair<K, V>): PersistentMap<K, V> = persistentHashMapOf(*pairs)
override fun <K, V> testBuilderToPersistentMap(builder: PersistentMap.Builder<K, V>) {
assertNotSame(builder.build(), builder.toPersistentMap(), "toPersistent shouldn't call build()")
}
@Test fun putAllElements() {
run {
val x = immutableMapOf<String, Int>() + (11..200).map { "$it" to it }
compareMaps(x.toMap(), x.putAll(immutableMapOf()))
compareMaps(x.toMap(), immutableMapOf<String, Int>().putAll(x))
}
run {
val x = immutableMapOf<Int, Int>() + (11..200).map { it to it }
val y = immutableMapOf<Int, Int>() + (120..400).map { it to it }
compareMaps(x.toMap() + y.toMap(), x.putAll(y))
}
run {
val x = immutableMapOf<String, Int>() + (11..200).map { "$it" to it }
val y = immutableMapOf<String, Int>() + (120..400).map { "$it" to it }
compareMaps(x.toMap() + y.toMap(), x.putAll(y))
}
run {
val x = immutableMapOf<IntWrapper, Int>() + (11..200).map { IntWrapper(it, it % 30) to it }
val y = immutableMapOf<IntWrapper, Int>() + (120..400).map { IntWrapper(it, it % 30) to it }
compareMaps(x.toMap() + y.toMap(), x.putAll(y))
compareMaps(y.toMap() + x.toMap(), y.putAll(x))
}
run {
val bcase = (1..2000).toList() // to preserve reference equality
val left = immutableMapOf<String, Int>() + bcase.map { "$it" to it }
assertSame(left, left + left)
assertSame(left, left + immutableMapOf())
}
}
@Test fun putAllElementsFromBuilder() {
val builder1 = immutableMapOf<String, Int>().builder()
val builder2 = immutableMapOf<String, Int>().builder()
val expected = mutableMapOf<String, Int>()
for(i in 300..400) {
builder1.put("$i", i)
expected.put("$i", i)
}
for(i in 0..200) {
builder2.put("$i", i)
expected.put("$i", i)
}
builder1.putAll(builder2)
// make sure we work with current state of builder2, not previous
compareMaps(expected, builder1)
builder2.put("200", 1000)
// make sure we can't modify builder1 through builder2
compareMaps(expected, builder1)
// make sure builder builds correct map
compareMaps(expected, builder1.build())
}
}
class ImmutableOrderedMapTest : ImmutableMapTest() {
override fun <K, V> immutableMapOf(vararg pairs: Pair<K, V>): PersistentMap<K, V> = persistentMapOf(*pairs)
override fun <K, V> compareMaps(expected: Map<K, V>, actual: Map<K, V>) = compare(expected, actual) { mapBehavior(ordered = true) }
override fun <K, V> testBuilderToPersistentMap(builder: PersistentMap.Builder<K, V>) {
assertSame(builder.build(), builder.toPersistentMap(), "toPersistent should call build()")
}
@Test fun iterationOrder() {
var map = immutableMapOf("x" to null, "y" to 1).toPersistentMap()
compare(setOf("x", "y"), map.keys) { setBehavior(ordered = true) }
map += "x" to 1
compare(setOf("x", "y"), map.keys) { setBehavior(ordered = true) }
map = map.remove("x")
map += "x" to 2
compare(setOf("y", "x"), map.keys) { setBehavior(ordered = true) }
compare(listOf(1, 2), map.values) { collectionBehavior(ordered = true) }
compare(mapOf("y" to 1, "x" to 2).entries, map.entries) { setBehavior(ordered = true) }
}
@Test fun keyHashCodeChanged() {
val changing = mutableSetOf("ok")
val persistent: PersistentMap<Any, Any> = immutableMapOf("constant" to "fixed", changing to "modified")
assertEquals(1, persistent.keys.filter { it === changing }.size)
changing.add("break iteration")
assertFailsWith<ConcurrentModificationException> { persistent.keys.filter { it === changing } }
}
@Test fun builderKeyHashCodeChanged() {
val changing = mutableSetOf("ok")
val builder: PersistentMap.Builder<Any, Any> = immutableMapOf<Any, Any>().builder().apply {
putAll(listOf("constant" to "fixed", changing to "modified"))
}
assertEquals(1, builder.filter { it.key === changing }.size)
changing.add("break iteration")
assertFailsWith<ConcurrentModificationException> { builder.filter { it.key === changing } }
}
}
abstract class ImmutableMapTest {
abstract fun <K, V> immutableMapOf(vararg pairs: Pair<K, V>): PersistentMap<K, V>
abstract fun <K, V> testBuilderToPersistentMap(builder: PersistentMap.Builder<K, V>)
open fun <K, V> compareMaps(expected: Map<K, V>, actual: Map<K, V>) = compareMapsUnordered(expected, actual)
fun <K, V> compareMapsUnordered(expected: Map<K, V>, actual: Map<K, V>) = compare(expected, actual) { mapBehavior(ordered = false) }
@Test fun empty() {
val empty1 = immutableMapOf<Int, String>()
val empty2 = immutableMapOf<String, Int>()
assertEquals<ImmutableMap<*, *>>(empty1, empty2)
assertEquals(mapOf<Int, String>(), empty1)
assertSame<ImmutableMap<*, *>>(empty1, empty2)
compareMaps(emptyMap(), empty1)
}
@Test fun ofPairs() {
val map0 = mapOf("x" to 1, "y" to null, null to 2)
val map1 = immutableMapOf("x" to 1, "y" to null, null to 2)
val map2 = immutableMapOf("x" to 1, "y" to null, null to 2)
compareMaps(map0, map1)
compareMaps(map1, map2)
}
@Test fun toImmutable() {
val original = mapOf("x" to 1, "y" to null, null to 2)
val immOriginal = original.toImmutableMap()
compareMaps(original, immOriginal)
val map = HashMap(original) // copy
var immMap = map.toPersistentMap()
val immMap2 = immMap.toImmutableMap()
assertSame(immMap2, immMap)
compareMapsUnordered(original, immMap)
compareMapsUnordered(map, immMap)
map.remove(null)
assertNotEquals<Map<*, *>>(map, immMap)
immMap = immMap.remove(null)
assertEquals<Map<*, *>>(map, immMap) // problem
}
@Test fun putElements() {
var map = immutableMapOf<String, Int?>().toPersistentMap()
map = map.put("x", 0)
map = map.put("x", 1)
map = map.putAll(arrayOf("x" to null))
map = map + ("y" to null)
map += "y" to 1
assertEquals(mapOf("x" to null, "y" to 1), map)
map += map
map += map.map { it.key + "!" to it.value }
assertEquals(map.size, map.entries.size)
assertEquals(mapOf("x" to null, "y" to 1, "x!" to null, "y!" to 1), map)
}
@Test fun putEqualButNotSameValue() {
data class Value<T>(val value: T)
val map = immutableMapOf("x" to Value(1))
val newValue = Value(1)
val newMap = map.put("x", newValue)
assertNotSame(map, newMap)
assertEquals(map, newMap)
val sameMap = newMap.put("x", newValue)
assertSame(newMap, sameMap)
}
@Test fun removeElements() {
val map = immutableMapOf("x" to 1, null to "x").toPersistentMap()
fun <K, V> assertEquals(expected: Map<out K, V>, actual: Map<out K, V>) = kotlin.test.assertEquals(expected, actual)
assertEquals(mapOf("x" to 1), map.remove(null))
assertEquals(mapOf("x" to 1), map.remove(null, "x"))
assertEquals(map, map.remove("x", 2))
assertEquals(emptyMap(), map.clear())
assertEquals(emptyMap(), map.remove("x").remove(null))
}
@Test
fun removeCollection() {
val map = immutableMapOf(0 to "a", 1 to "B", 2 to "c")
val newMap = map - setOf(2) - sequenceOf(1)
assertEquals(mapOf(0 to "a"), newMap)
}
@Test fun removeMatching() {
val map = immutableMapOf(0 to "a", 1 to "B", 2 to "c")
val newMap = map.mutate { it.entries.removeAll { it.key % 2 == 0 } }
assertEquals(mapOf(1 to "B"), newMap)
}
@Test fun builder() {
val builder = immutableMapOf<Char, Int?>().builder()
"abcxaxyz12".associateTo(builder) { it to it.toInt() }
val map = builder.build()
assertEquals<Map<*, *>>(map, builder)
assertSame(map, builder.build(), "Building the same list without modifications")
val map2 = builder.toImmutableMap()
assertSame(map2, map, "toImmutable calls build()")
testBuilderToPersistentMap(builder)
with(map) {
testMutation { put('K', null) }
testMutation { putAll("kotlin".associate { it to 0 }) }
testMutation { this['a'] = null }
testMutation { remove('x') }
testMutation { clear() }
testMutation { entries.remove(null as Any?) }
}
}
fun <K, V> PersistentMap<K, V>.testMutation(operation: MutableMap<K, V>.() -> Unit) {
val mutable = HashMap(this) as MutableMap<K, V>
val builder = this.builder()
operation(mutable)
operation(builder)
compareMapsUnordered(mutable, builder)
compareMapsUnordered(mutable, builder.build())
}
@Test fun noOperation() {
immutableMapOf<Int, String>().toPersistentMap().testNoOperation({ clear() }, { clear() })
val map = immutableMapOf("x" to 1, null to "x").toPersistentMap()
with(map) {
testNoOperation({ remove("y") }, { remove("y") })
testNoOperation({ remove("x", 2) }, { remove("x", 2) })
testNoOperation({ put("x", 1) }, { put("x", 1) }) // does not hold
testNoOperation({ putAll(this) }, { putAll(this) }) // does not hold
testNoOperation({ putAll(emptyMap()) }, { putAll(emptyMap()) })
}
}
fun <K, V> PersistentMap<K, V>.testNoOperation(persistent: PersistentMap<K, V>.() -> PersistentMap<K, V>, mutating: MutableMap<K, V>.() -> Unit) {
val result = this.persistent()
val buildResult = this.mutate(mutating)
// Ensure non-mutating operations return the same instance
assertSame(this, result)
assertSame(this, buildResult)
}
@Test
fun covariantTyping() {
val mapNothing = immutableMapOf<Nothing, Nothing>()
val mapSI: PersistentMap<String, Int> = mapNothing + ("x" to 1)
val mapSNI: PersistentMap<String, Int?> = mapSI + mapOf("y" to null)
val mapANA: PersistentMap<Any, Any?> = mapSNI + listOf(1 to "x")
assertEquals<Map<*, *>>(mapOf(1 to "x", "x" to 1, "y" to null), mapANA)
}
}
| 0
| null |
0
| 0
|
75ed654e34e7111a076d87b8c075fd140e6b4cf7
| 11,132
|
kotlinx.collections.immutable
|
Apache License 2.0
|
plot-core/src/commonTest/kotlin/org/jetbrains/letsPlot/core/plot/base/pos/PosTest.kt
|
JetBrains
| 176,771,727
| false
| null |
/*
* Copyright (c) 2023. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package org.jetbrains.letsPlot.core.plot.base.pos
import jetbrains.datalore.base.assertion.assertEquals
import org.jetbrains.letsPlot.commons.geometry.DoubleVector
import org.jetbrains.letsPlot.core.plot.base.Aesthetics
import org.jetbrains.letsPlot.core.plot.base.BogusContext
import org.jetbrains.letsPlot.core.plot.base.PositionAdjustment
import org.jetbrains.letsPlot.core.plot.base.aes.AestheticsBuilder
import org.jetbrains.letsPlot.core.commons.data.SeriesUtil
open class PosTest {
private val doubleComparisonPrecision = 1e-9
protected fun compareWithExpectedOffsets(
xValues: List<Double?>,
yValues: List<Double?>,
groupValues: List<Int>? = null,
expectedYOffsets: List<Double?>,
posConstructor: (Aesthetics) -> PositionAdjustment,
messageBeginning: String
) {
val aes = buildAesthetics(xValues, yValues, groupValues)
val pos = posConstructor(aes)
for (i in 0 until aes.dataPointCount()) {
val p = aes.dataPointAt(i)
if (!SeriesUtil.allFinite(p.x(), p.y())) continue
val translatedPoint = pos.translate(DoubleVector(p.x()!!, p.y()!!), p,
org.jetbrains.letsPlot.core.plot.base.BogusContext
)
assertEquals(
expectedYOffsets[i],
translatedPoint.y,
doubleComparisonPrecision,
"$messageBeginning at $i-th point $translatedPoint."
)
}
}
private fun buildAesthetics(
xValues: List<Double?>,
yValues: List<Double?>,
groupValues: List<Int>?
): Aesthetics {
val builder = AestheticsBuilder(xValues.size)
.x(AestheticsBuilder.list(xValues))
.y(AestheticsBuilder.list(yValues))
if (groupValues != null) builder.group(AestheticsBuilder.list(groupValues))
return builder.build()
}
}
| 93
| null |
51
| 889
|
2fb1fe8e812ed0b84cd32954331a76775e75d4d2
| 2,058
|
lets-plot
|
MIT License
|
plot-core/src/commonTest/kotlin/org/jetbrains/letsPlot/core/plot/base/pos/PosTest.kt
|
JetBrains
| 176,771,727
| false
| null |
/*
* Copyright (c) 2023. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package org.jetbrains.letsPlot.core.plot.base.pos
import jetbrains.datalore.base.assertion.assertEquals
import org.jetbrains.letsPlot.commons.geometry.DoubleVector
import org.jetbrains.letsPlot.core.plot.base.Aesthetics
import org.jetbrains.letsPlot.core.plot.base.BogusContext
import org.jetbrains.letsPlot.core.plot.base.PositionAdjustment
import org.jetbrains.letsPlot.core.plot.base.aes.AestheticsBuilder
import org.jetbrains.letsPlot.core.commons.data.SeriesUtil
open class PosTest {
private val doubleComparisonPrecision = 1e-9
protected fun compareWithExpectedOffsets(
xValues: List<Double?>,
yValues: List<Double?>,
groupValues: List<Int>? = null,
expectedYOffsets: List<Double?>,
posConstructor: (Aesthetics) -> PositionAdjustment,
messageBeginning: String
) {
val aes = buildAesthetics(xValues, yValues, groupValues)
val pos = posConstructor(aes)
for (i in 0 until aes.dataPointCount()) {
val p = aes.dataPointAt(i)
if (!SeriesUtil.allFinite(p.x(), p.y())) continue
val translatedPoint = pos.translate(DoubleVector(p.x()!!, p.y()!!), p,
org.jetbrains.letsPlot.core.plot.base.BogusContext
)
assertEquals(
expectedYOffsets[i],
translatedPoint.y,
doubleComparisonPrecision,
"$messageBeginning at $i-th point $translatedPoint."
)
}
}
private fun buildAesthetics(
xValues: List<Double?>,
yValues: List<Double?>,
groupValues: List<Int>?
): Aesthetics {
val builder = AestheticsBuilder(xValues.size)
.x(AestheticsBuilder.list(xValues))
.y(AestheticsBuilder.list(yValues))
if (groupValues != null) builder.group(AestheticsBuilder.list(groupValues))
return builder.build()
}
}
| 93
| null |
51
| 889
|
2fb1fe8e812ed0b84cd32954331a76775e75d4d2
| 2,058
|
lets-plot
|
MIT License
|
core/src/main/java/co/com/lafemmeapp/core/domain/use_cases/specialist/DeleteSOSActivationDateUseCase.kt
|
Informatica-Empresarial
| 106,600,201
| false
| null |
package co.com.lafemmeapp.core.domain.use_cases.specialist
import co.com.lafemmeapp.core.domain.use_cases.UseCase
import co.com.lafemmeapp.dataprovider.Constants
import co.com.lafemmeapp.dataprovider.repo.interfaces.IRepositoryFactory
import io.reactivex.Observable
import io.reactivex.Scheduler
import javax.inject.Inject
/**
* Created by oscargallon on 6/9/17.
*/
class DeleteSOSActivationDateUseCase(mSubscribeOnScheduler: Scheduler,
mObserverOnScheduler: Scheduler) :
UseCase<Boolean, Void?>(mSubscribeOnScheduler, mObserverOnScheduler) {
@Inject
lateinit var mRepositoryFactory: IRepositoryFactory
override fun buildUseCaseObservable(params: Void?): Observable<Boolean> {
return Observable.create {
emitter ->
mRepositoryFactory.valuesRepository
.deleteKey(Constants.SOS_ACTIVATION_TIME)
emitter.onNext(true)
emitter.onComplete()
}
}
}
| 1
| null |
1
| 1
|
486ab3eab99e9a06e70e32d1cbe34a9fa5a7fd81
| 992
|
AppAndroid
|
Apache License 2.0
|
app/src/main/java/com/ant/app/ui/main/favorites/FavoritesFragment.kt
|
toaderandrei
| 786,415,615
| false
|
{"Kotlin": 212047, "Java": 376}
|
package com.ant.app.ui.main.favorites
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.ant.app.databinding.FragmentFavoritesBinding
import com.ant.app.ui.main.base.NavigationFragment
import com.ant.common.extensions.doOnSizeChange
import com.ant.common.extensions.observe
import com.ant.epoxy.extensions.init
import com.ant.models.entities.MovieData
import com.ant.models.entities.TvShow
import com.ant.models.model.FavoritesState
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class FavoritesFragment : NavigationFragment<FavoritesViewModel, FragmentFavoritesBinding>() {
override val viewModel: FavoritesViewModel by viewModels()
@Inject
internal lateinit var controller: FavoritesEpoxyController
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initControllerCallbacks()
initBindings()
}
fun initControllerCallbacks() {
controller.callbacks = object : FavoritesEpoxyController.Callbacks {
override fun onTvSeriesItemClicked(viewHolderId: Long, item: TvShow) {
showTvSeriesDetailsScreen(item)
}
override fun onMoviesItemClicked(viewHolderId: Long, item: MovieData) {
showMovieDetailsScreen(item)
}
}
with(viewModel) {
viewModel.refresh()
stateAsFlow.observe(viewLifecycleOwner, ::renderModels)
}
}
private fun renderModels(favoritesState: FavoritesState?) {
favoritesState?.let {
controller.state = it
binding.state = it
}
}
fun initBindings() {
with(binding) {
logger.d("initialize bindings")
favoritesRv.init(controller)
favoritesAppBar.doOnSizeChange {
favoritesRv.updatePadding(top = it.height)
// todo - verify and test this.
favoritesSwipeRefresh.setProgressViewOffset(
true, 0, it.height + favoritesSwipeRefresh.progressCircleDiameter
)
true
}
favoritesSwipeRefresh.setOnRefreshListener {
viewModel.refresh()
favoritesSwipeRefresh.postOnAnimation {
favoritesSwipeRefresh.isRefreshing = false
}
}
}
}
override fun createViewBinding(
inflater: LayoutInflater, container: ViewGroup?
): FragmentFavoritesBinding {
return FragmentFavoritesBinding.inflate(inflater, container, false)
}
override fun getThisFragment(): Fragment {
return this@FavoritesFragment
}
private fun showMovieDetailsScreen(movieData: MovieData) {
findNavController().navigate(FavoritesFragmentDirections.toMovieDetails(movieData.id))
}
private fun showTvSeriesDetailsScreen(tvShow: TvShow) {
findNavController().navigate(FavoritesFragmentDirections.toTvshowDetails(tvShow.id))
}
}
| 1
|
Kotlin
|
0
| 0
|
b7691975f404ee834a4567cf6dfbdea77086aeb2
| 3,308
|
popular-movies-kt
|
MIT License
|
src/main/kotlin/org/xpathqs/driver/navigation/impl/Loadable.kt
|
xpathqs
| 366,703,320
| false
| null |
package org.xpathqs.driver.navigation.impl
import org.xpathqs.core.selector.block.Block
import org.xpathqs.driver.extensions.isHidden
import org.xpathqs.driver.extensions.waitForVisible
import org.xpathqs.driver.log.Log
import org.xpathqs.driver.navigation.base.ILoadable
import org.xpathqs.driver.navigation.util.Loading
import org.xpathqs.driver.navigation.util.LoadingParser
import java.time.Duration
open class Loadable(private val block: Block) : ILoadable {
private var isLoading = false
override val loading: Loading by lazy {
if(!isLoading) {
isLoading = true
(block as? ILoadable)?.loading
} else {
LoadingParser(block).parse()
} ?: LoadingParser(block).parse()
}
override fun waitForLoad(duration: Duration) {
Log.action("Ожидаем Загрузки страницы") {
if(loading.loadSelector != null) {
loading.loadSelector!!.waitForVisible(duration)
} else if(loading.loadSelectors.isNotEmpty()) {
loading.loadSelectors.forEach {
if(it.isHidden) {
it.waitForVisible()
}
}
} else {
Log.warning("No Load Selector defined")
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
ddd2c5b04ac454a3eef608396501e74c2b162e6c
| 1,299
|
driver
|
MIT License
|
rtmp/src/main/java/com/pedro/rtmp/fork/bitrateadjuster/NetworkStateManager.kt
|
marcin-adamczewski
| 252,785,785
| true
|
{"Java": 980006, "Kotlin": 292958, "GLSL": 40954}
|
package com.pedro.rtmp.fork.bitrateadjuster
import android.content.Context
import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback
import android.net.Network
import android.net.NetworkRequest
import android.os.Build
import android.telephony.TelephonyManager
import android.util.Log
import androidx.annotation.RequiresApi
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
class NetworkStateManager(context: Context) {
interface NetworkTypeListener {
fun onNetworkChanged(networkType: NetworkType)
}
private val connectivityManager: ConnectivityManager = context.applicationContext
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
var listener: NetworkTypeListener? = null
init {
val networkCallback: NetworkCallback = object : NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
Log.d(TAG, "onAvailable")
notifyNetworkChanged()
}
// Keep in mind that onLost callback will be called also when switching from WiFi to Cellular.
override fun onLost(network: Network) {
super.onLost(network)
Log.d(TAG, "onLost")
notifyNetworkChanged()
}
}
val networkRequest = NetworkRequest.Builder().build()
connectivityManager.registerNetworkCallback(networkRequest, networkCallback)
}
private fun notifyNetworkChanged() {
if (listener != null) {
listener!!.onNetworkChanged(networkType())
}
}
private fun networkType(): NetworkType {
val activeNetworkInfo = connectivityManager.activeNetworkInfo
if (activeNetworkInfo == null || !activeNetworkInfo.isConnected) {
return NetworkType.NO_CONNECTION
}
return when (activeNetworkInfo.type) {
ConnectivityManager.TYPE_WIFI -> NetworkType.WIFI
ConnectivityManager.TYPE_MOBILE -> if (activeNetworkInfo.subtype == TelephonyManager.NETWORK_TYPE_LTE) {
NetworkType.FOUR_G
} else {
NetworkType.THREE_G
}
else -> NetworkType.OTHER
}
}
companion object {
private const val TAG = "NetworkStateManager"
}
}
| 2
|
Java
|
1
| 1
|
88c2cc76d2a76aa667e27b84e755cb8c03eee1ee
| 2,364
|
rtmp-rtsp-stream-client-java
|
Apache License 2.0
|
app/src/main/java/org/stepic/droid/storage/dao/CourseDaoImpl.kt
|
Ahmad-Saleem
| 109,315,434
| false
| null |
package org.stepic.droid.storage.dao
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import org.stepic.droid.mappers.toDbUrl
import org.stepic.droid.mappers.toVideoUrls
import org.stepic.droid.model.*
import org.stepic.droid.storage.structure.DbStructureCachedVideo
import org.stepic.droid.storage.structure.DbStructureEnrolledAndFeaturedCourses
import org.stepic.droid.storage.structure.DbStructureVideoUrl
import org.stepic.droid.util.DbParseHelper
import org.stepic.droid.util.transformToCachedVideo
import java.util.*
import javax.inject.Inject
class CourseDaoImpl @Inject
constructor(
openHelper: SQLiteDatabase,
private val cachedVideoDao: IDao<CachedVideo>,
private val externalVideoUrlIDao: IDao<DbVideoUrl>,
private val tableName: String)
: DaoBase<Course>(openHelper) {
public override fun parsePersistentObject(cursor: Cursor): Course {
val course = Course()
val indexId = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.COURSE_ID)
val indexSummary = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.SUMMARY)
val indexCover = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.COVER_LINK)
val indexIntro = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.INTRO_LINK_VIMEO)
val indexTitle = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.TITLE)
val indexLanguage = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.LANGUAGE)
val indexBeginDateSource = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.BEGIN_DATE_SOURCE)
val indexBeginDate = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.BEGIN_DATE)
val indexEndDate = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.END_DATE)
val indexLastDeadline = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.LAST_DEADLINE)
val indexDescription = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.DESCRIPTION)
val indexInstructors = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.INSTRUCTORS)
val indexRequirements = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.REQUIREMENTS)
val indexEnrollment = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.ENROLLMENT)
val indexSection = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.SECTIONS)
val indexWorkload = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.WORKLOAD)
val indexCourseFormat = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.COURSE_FORMAT)
val indexTargetAudience = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.TARGET_AUDIENCE)
val indexCertificate = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.CERTIFICATE)
val indexIntroVideoId = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.INTRO_VIDEO_ID)
val indexSlug = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.SLUG)
val indexScheduleLink = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.SCHEDULE_LINK)
val indexScheduleLongLink = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.SCHEDULE_LONG_LINK)
val indexLastStepId = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.LAST_STEP_ID)
val indexIsActive = cursor.getColumnIndex(DbStructureEnrolledAndFeaturedCourses.Column.IS_ACTIVE)
course.lastStepId = cursor.getString(indexLastStepId)
course.certificate = cursor.getString(indexCertificate)
course.workload = cursor.getString(indexWorkload)
course.courseFormat = cursor.getString(indexCourseFormat)
course.targetAudience = cursor.getString(indexTargetAudience)
course.setId(cursor.getLong(indexId))
course.summary = cursor.getString(indexSummary)
course.cover = cursor.getString(indexCover)
course.intro = cursor.getString(indexIntro)
course.title = cursor.getString(indexTitle)
course.language = cursor.getString(indexLanguage)
course.beginDateSource = cursor.getString(indexBeginDateSource)
course.lastDeadline = cursor.getString(indexLastDeadline)
course.description = cursor.getString(indexDescription)
course.instructors = DbParseHelper.parseStringToLongArray(cursor.getString(indexInstructors))
course.requirements = cursor.getString(indexRequirements)
course.enrollment = cursor.getInt(indexEnrollment)
course.sections = DbParseHelper.parseStringToLongArray(cursor.getString(indexSection))
course.introVideoId = cursor.getLong(indexIntroVideoId)
course.slug = cursor.getString(indexSlug)
course.scheduleLink = cursor.getString(indexScheduleLink)
course.scheduleLongLink = cursor.getString(indexScheduleLongLink)
course.beginDate = cursor.getString(indexBeginDate)
course.endDate = cursor.getString(indexEndDate)
var isActive = true
try {
isActive = cursor.getInt(indexIsActive) > 0
} catch (exception: Exception) {
//it can be null before migration --> default active
}
course.setActive(isActive)
return course
}
public override fun getContentValues(course: Course): ContentValues {
val values = ContentValues()
values.put(DbStructureEnrolledAndFeaturedCourses.Column.LAST_STEP_ID, course.lastStepId)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.COURSE_ID, course.courseId)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.SUMMARY, course.summary)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.COVER_LINK, course.cover)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.INTRO_LINK_VIMEO, course.intro)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.TITLE, course.title)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.LANGUAGE, course.language)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.BEGIN_DATE_SOURCE, course.beginDateSource)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.LAST_DEADLINE, course.lastDeadline)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.DESCRIPTION, course.description)
val instructorsParsed = DbParseHelper.parseLongArrayToString(course.instructors)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.INSTRUCTORS, instructorsParsed)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.REQUIREMENTS, course.requirements)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.ENROLLMENT, course.enrollment)
val sectionsParsed = DbParseHelper.parseLongArrayToString(course.sections)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.SECTIONS, sectionsParsed)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.WORKLOAD, course.workload)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.COURSE_FORMAT, course.courseFormat)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.TARGET_AUDIENCE, course.targetAudience)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.CERTIFICATE, course.certificate)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.SLUG, course.slug)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.SCHEDULE_LINK, course.scheduleLink)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.SCHEDULE_LONG_LINK, course.scheduleLongLink)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.BEGIN_DATE, course.beginDate)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.END_DATE, course.endDate)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.IS_ACTIVE, course.isActive)
val video = course.introVideo
if (video != null) {
values.put(DbStructureEnrolledAndFeaturedCourses.Column.INTRO_VIDEO_ID, video.id)
}
return values
}
public override fun getDbName() = tableName
public override fun getDefaultPrimaryColumn() = DbStructureEnrolledAndFeaturedCourses.Column.COURSE_ID
public override fun getDefaultPrimaryValue(persistentObject: Course) = persistentObject.courseId.toString()
override fun get(whereColumnName: String, whereValue: String): Course? {
val course = super.get(whereColumnName, whereValue)
addInnerObjects(course)
return course
}
override fun getAllWithQuery(query: String, whereArgs: Array<String>?): List<Course> {
val courseList = super.getAllWithQuery(query, whereArgs)
for (course in courseList) {
addInnerObjects(course)
}
return courseList
}
private fun addInnerObjects(course: Course?) {
if (course == null) return
val video = cachedVideoDao.get(DbStructureCachedVideo.Column.VIDEO_ID, course.introVideoId.toString())
if (video != null) {
val dbVideoUrls = externalVideoUrlIDao
.getAll(DbStructureVideoUrl.Column.videoId, course.introVideoId.toString())
val videoUrls = dbVideoUrls.toVideoUrls()
course.introVideo = transformCachedVideoToRealVideo(video, videoUrls)
}
}
override fun insertOrUpdate(persistentObject: Course?) {
super.insertOrUpdate(persistentObject)
if (persistentObject != null && persistentObject.introVideo != null) {
val video = persistentObject.introVideo
val cachedVideo = video.transformToCachedVideo() //it is cached, but not stored video.
cachedVideoDao.insertOrUpdate(cachedVideo)
//add all urls for video
val videoUrlList = video.urls
if (videoUrlList.isNotEmpty()) {
externalVideoUrlIDao.remove(DbStructureVideoUrl.Column.videoId, video.id.toString())
videoUrlList.forEach { videoUrl ->
externalVideoUrlIDao.insertOrUpdate(videoUrl.toDbUrl(video.id))
}
}
}
}
//// FIXME: 17.02.16 refactor this hack
private fun transformCachedVideoToRealVideo(cachedVideo: CachedVideo?, videoUrls: List<VideoUrl>?): Video? {
var realVideo: Video? = null
if (cachedVideo != null) {
realVideo = Video()
realVideo.id = cachedVideo.videoId
realVideo.thumbnail = cachedVideo.thumbnail
val resultUrls: List<VideoUrl>
if (videoUrls != null && !videoUrls.isEmpty()) {
resultUrls = videoUrls
} else {
val videoUrl = VideoUrl()
videoUrl.url = cachedVideo.url
videoUrl.quality = cachedVideo.quality
resultUrls = ArrayList<VideoUrl>()
resultUrls.add(videoUrl)
}
realVideo.urls = resultUrls
}
return realVideo
}
}
| 1
| null |
1
| 1
|
899e5a2eab833bfaf2e9da232f7174691eb6d134
| 11,238
|
stepik-android
|
Apache License 2.0
|
plugin/src/main/kotlin/io/github/thomo/valuestable/printer/HtmlGenerator.kt
|
thomo
| 562,283,258
| false
|
{"Kotlin": 16187}
|
package io.github.thomo.valuestable.printer
import io.github.thomo.valuestable.model.ValueCollector
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class HtmlGenerator : Generator {
override fun generate(collector: ValueCollector) = mutableListOf(
"""
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
body {font-family: Arial, sans-serif;}
h1 {color: #333;}
table {border-collapse: collapse; width: 100%;}
th, td {border: 1px solid #ddd; padding: 8px; text-align: left;}
th {background-color: #f2f2f2;}
</style>
</head>
""".trimIndent(),
"<body><h1>Values</h1><p>generated at " + LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + "</p>",
"<table>"
) + generateTableHead() + "<tbody>" + generateTableRows(collector) +
"</tbody></table></body></html>"
fun generateTableHead() =
"<thead><tr><th>key</th><th>values</th></tr></thead>"
fun generateTableRows(collector: ValueCollector) =
collector.keys().map { key -> "<tr>" + generateTableRow(key, collector) + "</tr>" }
fun generateTableRow(key: String, collector: ValueCollector): String {
val names = collector.getNames()
return "<td>$key</td><td>" +
collector.getValues(key)
.mapIndexed { index, v -> names[index] + ": " + (v ?: if (index == 0) "<i>(n.d.)</i>" else "<i>default</i>") }
.joinToString("<br/>", postfix = "</td>")
}
override fun fileExtension() = "html"
}
| 0
|
Kotlin
|
0
| 0
|
9c9fa8f57f7f8c80192ce0e52aa6ebf943d1f242
| 1,567
|
valuestable
|
MIT License
|
common/common-compose/src/commonMain/kotlin/ru/alexgladkov/common/compose/helpers/ModelsGenerator.kt
|
AlexGladkov
| 409,687,153
| false
| null |
package ru.alexgladkov.common.compose.helpers
fun generateProducts(count: Int): List<DataModel> = ArrayList<DataModel>().apply {
for (i in 0..count) {
add(DataModel(id = i.toString(), title = "Product #$i"))
}
}
fun generateCities(count: Int): List<DataModel> = ArrayList<DataModel>().apply {
for (i in 0..count) {
add(DataModel(id = i.toString(), title = "City #$i"))
}
}
data class DataModel(
val id: String,
val title: String
)
| 3
|
Kotlin
|
2
| 58
|
be24a83ed944510078417936f9846f2e521a896f
| 473
|
Odyssey
|
MIT License
|
app/src/main/java/org/simple/clinic/sync/SyncSetup.kt
|
simpledotorg
| 132,515,649
| false
| null |
package org.simple.clinic.sync
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import org.simple.clinic.sync.indicator.SyncIndicatorStatusCalculator
import javax.annotation.CheckReturnValue
import javax.inject.Inject
class SyncSetup @Inject constructor(
private val syncScheduler: SyncScheduler,
private val syncIndicatorStatusCalculator: SyncIndicatorStatusCalculator,
private val dataSyncOnApproval: IDataSyncOnApproval
) {
@CheckReturnValue
fun run(): Disposable {
return CompositeDisposable().apply {
addAll(
dataSyncOnApproval.sync(),
syncScheduler.schedule().subscribe(),
syncIndicatorStatusCalculator.updateSyncResults()
)
}
}
}
| 4
| null |
73
| 236
|
ff699800fbe1bea2ed0492df484777e583c53714
| 754
|
simple-android
|
MIT License
|
app/src/main/java/com/hot/pocketdoctor/presentation/medication/MedicineRequestDTO.kt
|
DSCHUFS
| 449,558,792
| false
|
{"Kotlin": 138363}
|
package com.hot.pocketdoctor.presentation.medication
import com.google.gson.annotations.SerializedName
data class MedicineRequestDTO (
@SerializedName("medicine_name") val medicineName : String,
)
| 1
|
Kotlin
|
1
| 2
|
f1939b678d0758bab9477a24f4b5b6ebfafacd4b
| 202
|
Solution-Challenge-2022-Pocket-Doctor-App
|
MIT License
|
channels/jaicp/src/test/kotlin/com/justai/jaicf/channel/jaicp/channels/JaicpNativeChannelTests.kt
|
just-ai
| 246,869,336
| false
| null |
package com.justai.jaicf.channel.jaicp.channels
import com.justai.jaicf.BotEngine
import com.justai.jaicf.channel.jaicp.JaicpBaseTest
import com.justai.jaicf.channel.jaicp.JaicpTestChannel
import com.justai.jaicf.channel.jaicp.ScenarioFactory
import com.justai.jaicf.channel.jaicp.ScenarioFactory.echoWithAction
import com.justai.jaicf.channel.jaicp.dto.TelephonySwitchMethod
import com.justai.jaicf.channel.jaicp.dto.TelephonySwitchReply
import com.justai.jaicf.channel.jaicp.dto.bargein.BargeInMode
import com.justai.jaicf.channel.jaicp.dto.bargein.BargeInTrigger
import com.justai.jaicf.channel.jaicp.reactions.telephony
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class JaicpNativeChannelTests : JaicpBaseTest() {
@Test
fun `001 webhooks should answer chatapi`() {
val channel = JaicpTestChannel(echoBot, ChatApiChannel)
val response = channel.process(requestFromResources)
assertEquals(responseFromResources, response.jaicp)
}
@Test
fun `002 webhooks should answer chatwidget`() {
val channel = JaicpTestChannel(echoBot, ChatWidgetChannel)
val response = channel.process(requestFromResources)
assertEquals(responseFromResources, response.jaicp)
}
@Test
fun `003 webhooks should answer telephony`() {
val channel = JaicpTestChannel(echoBot, TelephonyChannel)
val response = channel.process(requestFromResources)
assertEquals(responseFromResources, response.jaicp)
}
@Test
// @Disabled("fix later")
fun `004 webhooks should answer telephony with bargeIn`() {
val bot = BotEngine(
echoWithAction {
reactions.telephony?.say(
"You said: ${request.input} from ${reactions::class.simpleName}",
bargeIn = true
)
reactions.telephony?.bargeIn(mode = BargeInMode.FORCED, trigger = BargeInTrigger.INTERIM, 101)
}
)
val channel = JaicpTestChannel(bot, TelephonyChannel)
val response = channel.process(requestFromResources)
assertEquals(responseFromResources, response.jaicp)
}
@Test
fun `005 webhooks should answer telephony with default transfer`() {
val bot = BotEngine(
ScenarioFactory.echoWithAction {
reactions.say("You said: ${request.input} from ${reactions::class.simpleName}")
reactions.telephony?.transferCall("79123456789")
}
)
val channel = JaicpTestChannel(bot, TelephonyChannel)
val response = channel.process(requestFromResources)
Assertions.assertEquals(responseFromResources, response.jaicp)
}
@Test
fun `006 webhooks should answer telephony with REFER transfer`() {
val bot = BotEngine(
ScenarioFactory.echoWithAction {
reactions.say("You said: ${request.input} from ${reactions::class.simpleName}")
reactions.telephony?.transferCall(
TelephonySwitchReply(
phoneNumber = "79123456789",
method = TelephonySwitchMethod.REFER
)
)
}
)
val channel = JaicpTestChannel(bot, TelephonyChannel)
val response = channel.process(requestFromResources)
Assertions.assertEquals(responseFromResources, response.jaicp)
}
@Test
fun `007 webhooks should answer telephony with INVITE transfer`() {
val bot = BotEngine(
ScenarioFactory.echoWithAction {
reactions.say("You said: ${request.input} from ${reactions::class.simpleName}")
reactions.telephony?.transferCall(
TelephonySwitchReply(
phoneNumber = "79123456789",
method = TelephonySwitchMethod.INVITE
)
)
}
)
val channel = JaicpTestChannel(bot, TelephonyChannel)
val response = channel.process(requestFromResources)
Assertions.assertEquals(responseFromResources, response.jaicp)
}
@Test
fun `008 webhooks should answer telephony with sip URI`() {
val bot = BotEngine(
ScenarioFactory.echoWithAction {
reactions.say("You said: ${request.input} from ${reactions::class.simpleName}")
reactions.telephony?.transferCall(
TelephonySwitchReply(
sipUri = "<EMAIL>"
)
)
}
)
val channel = JaicpTestChannel(bot, TelephonyChannel)
val response = channel.process(requestFromResources)
Assertions.assertEquals(responseFromResources, response.jaicp)
}
}
private val echoBot = BotEngine(
echoWithAction {
reactions.say("You said: ${request.input} from ${reactions::class.simpleName}")
}
)
| 21
| null |
39
| 241
|
cc076db73e03bf89db2ab94e7f48c8736735706b
| 5,035
|
jaicf-kotlin
|
Apache License 2.0
|
app/src/main/java/com/costular/marvelheroes/data/repository/datasource/MarvelHeroesDataSource.kt
|
jventor
| 138,651,450
| true
|
{"Kotlin": 42550}
|
package com.costular.marvelheroes.data.repository.datasource
import com.costular.marvelheroes.domain.model.MarvelHeroEntity
import io.reactivex.Single
interface MarvelHeroesDataSource {
fun getMarvelHeroesList(): Single<List<MarvelHeroEntity>>
}
| 0
|
Kotlin
|
0
| 0
|
ca9409ca793cbf10fa3bb4c32789057b042ca1b6
| 255
|
marvel-super-heroes
|
MIT License
|
src/test/kotlin/sprint/EndpointTest.kt
|
chaseberry
| 39,609,649
| false
| null |
package sprint
import edu.csh.chase.sprint.buildEndpoint
import org.junit.Test
import org.junit.Assert.*
class EndpointTest {
@Test fun testBuildEndpoint() {
val base = "https://google.com/"
val endpoint = "test"
assertEquals("https://google.com/test", buildEndpoint(base, endpoint))
assertNotEquals("https://google.comtest", buildEndpoint(base, endpoint))
}
}
| 1
|
Kotlin
|
0
| 6
|
e5afddd198da894afb455a25793e4d47dcf7c041
| 405
|
sprint
|
Apache License 2.0
|
src/main/java/com/ecwid/maleorang/method/v3_0/eCommerceStores/carts/cartLines/GetCartLinesMethod.kt
|
nikolai-tenev
| 70,156,034
| true
|
{"Kotlin": 101475, "Java": 18725}
|
package com.ecwid.maleorang.method.v3_0.eCommerceStores.carts.cartLines
import com.ecwid.maleorang.MailchimpMethod
import com.ecwid.maleorang.MailchimpObject
import com.ecwid.maleorang.annotation.*
import com.ecwid.maleorang.method.v3_0.eCommerceStores.carts.LineInfo
/**
* [Get information about a cart’s line items.](http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/carts/lines/#read-get_ecommerce_stores_store_id_carts_cart_id_lines)
*/
@Method(httpMethod = HttpMethod.GET, version = APIVersion.v3_0, path = "/ecommerce/stores/{store_id}/carts/{cart_id}/lines")
class GetCartLinesMethod(
@JvmField
@PathParam
val store_id: String,
@JvmField
@PathParam
val cart_id: String
) : MailchimpMethod<GetCartLinesMethod.Response>() {
@JvmField
@QueryStringParam
var fields: String? = null
@JvmField
@QueryStringParam
var exclude_fields: String? = null
@JvmField
@QueryStringParam
var count: Int? = null
@JvmField
@QueryStringParam
var offset: Int? = null
class Response : MailchimpObject() {
@JvmField
@Field
var store_id: String? = null
@JvmField
@Field
var cart_id: String? = null
@JvmField
@Field
var lines: List<LineInfo>? = null
@JvmField
@Field
var total_items: Int? = null
}
}
| 0
|
Kotlin
|
0
| 0
|
ce61feb7567d4364e9daa7156b3553ef4e07b54d
| 1,424
|
maleorang
|
Apache License 2.0
|
src/main/java/io/javalin/rendering/template/JavalinPebble.kt
|
javalin
| 504,307,498
| false
| null |
/*
* Javalin - https://javalin.io
* Copyright 2017 <NAME>
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.rendering.template
import com.mitchellbosecke.pebble.PebbleEngine
import com.mitchellbosecke.pebble.loader.ClasspathLoader
import io.javalin.http.Context
import io.javalin.rendering.FileRenderer
import io.javalin.rendering.util.RenderingDependency.PEBBLE
import io.javalin.rendering.util.Util
import java.io.StringWriter
class JavalinPebble @JvmOverloads constructor(
private var pebbleEngine: PebbleEngine = defaultPebbleEngine()
) : FileRenderer {
init {
Util.throwIfNotAvailable(PEBBLE)
}
override fun render(filePath: String, model: Map<String, Any?>, context: Context): String {
val compiledTemplate = pebbleEngine.getTemplate(filePath)
val stringWriter = StringWriter()
compiledTemplate.evaluate(stringWriter, model)
return stringWriter.toString()
}
companion object {
private fun defaultPebbleEngine() = PebbleEngine.Builder()
.loader(ClasspathLoader())
.strictVariables(false)
.build()
}
}
| 4
| null |
7
| 8
|
041f533903041f4d9e5f6e402ec1f3418c160993
| 1,183
|
javalin-rendering
|
Apache License 2.0
|
src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/event/Stopwatch.kt
|
rhdunn
| 62,201,764
| false
|
{"Kotlin": 8262637, "XQuery": 996770, "HTML": 39377, "XSLT": 6853}
|
/*
* Copyright (C) 2019 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.core.event
import com.intellij.openapi.application.ApplicationManager
import java.util.concurrent.Future
abstract class Stopwatch {
private var startTime: Long = 0
private var endTime: Long = 0
val elapsedTime: Long
get() = endTime - startTime
fun start(interval: Long): Future<*> = ApplicationManager.getApplication().executeOnPooledThread {
startTime = System.nanoTime()
while (isRunning()) {
ApplicationManager.getApplication().invokeLater {
if (isRunning()) {
endTime = System.nanoTime()
onInterval()
}
}
Thread.sleep(interval)
}
}
abstract fun isRunning(): Boolean
abstract fun onInterval()
}
| 49
|
Kotlin
|
9
| 25
|
d8d460d31334e8b2376a22f3832a20b2845bacab
| 1,410
|
xquery-intellij-plugin
|
Apache License 2.0
|
shared/src/wasmJsMain/kotlin/util/ImageLoader.kt
|
mbakgun
| 629,040,507
| false
|
{"Kotlin": 63999, "Ruby": 2296, "Swift": 771, "HTML": 453, "Shell": 228}
|
package util
import com.seiko.imageloader.ImageLoader
import com.seiko.imageloader.component.setupDefaultComponents
import com.seiko.imageloader.intercept.bitmapMemoryCacheConfig
import com.seiko.imageloader.intercept.imageMemoryCacheConfig
import com.seiko.imageloader.intercept.painterMemoryCacheConfig
actual fun generateImageLoader(): ImageLoader {
return ImageLoader {
components {
setupDefaultComponents()
}
interceptor {
bitmapMemoryCacheConfig {
maxSize(32 * 1024 * 1024)
}
imageMemoryCacheConfig {
maxSize(50)
}
painterMemoryCacheConfig {
maxSize(50)
}
}
}
}
| 2
|
Kotlin
|
19
| 220
|
d953d6d5478229c3548742f1ad3e441425b8a12b
| 742
|
midjourney-images-compose-multiplatform
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.