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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
library-res/src/main/kotlin/com/wsdydeni/library_view/banner/BannerAdapter.kt
|
wsdydeni
| 294,493,450
| false
| null |
package com.wsdydeni.library_view.banner
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.wsdydeni.library_res.R
const val MAX_VALUE = 500
class BannerAdapter : RecyclerView.Adapter<BannerAdapter.MyViewHolder>() {
private var _onClick : ((String) -> Unit)? = null
fun setOnClickListener(listener: (String) -> Unit) {
_onClick = listener
}
private var mList = arrayListOf<BannerInfo>()
fun setData(list: List<BannerInfo>) {
mList.clear()
mList.addAll(list)
notifyDataSetChanged()
}
fun getListSize() : Int = mList.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder =
MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_banner, parent, false))
override fun getItemCount(): Int = if (mList.size > 1) { MAX_VALUE } else { mList.size }
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val realPosition = if(mList.size == 0) { 0 } else{ (position - 1 + mList.size) % mList.size }
val image = holder.itemView.findViewById<ImageView>(R.id.banner_image)
Glide.with(holder.itemView.context).load(mList[realPosition].imagePath)
.placeholder(R.drawable.item_banner_placeholder).dontAnimate().into(image)
holder.itemView.setOnClickListener {
_onClick?.invoke(mList[realPosition].url)
}
}
class MyViewHolder(view: View) : RecyclerView.ViewHolder(view)
}
| 1
|
Kotlin
|
1
| 5
|
e908db6bcf7cefa43500cc334c07c0bcc655819a
| 1,641
|
WanAndroid
|
MIT License
|
erc20/api/src/main/kotlin/com/rarible/protocol/erc20/api/service/token/Erc20Service.kt
|
NFTDroppr
| 418,665,809
| true
|
{"Kotlin": 2329156, "Scala": 37343, "Shell": 6001, "HTML": 547}
|
package com.rarible.protocol.erc20.api.service.token
import com.rarible.core.common.convert
import com.rarible.core.contract.model.ContractType
import com.rarible.ethereum.contract.service.ContractService
import com.rarible.protocol.dto.Erc20TokenDto
import com.rarible.protocol.erc20.api.exceptions.TokenNotFoundException
import org.springframework.core.convert.ConversionService
import org.springframework.stereotype.Component
import scalether.domain.Address
@Component
class Erc20Service(
private val conversionService: ConversionService,
private val contractService: ContractService
) {
suspend fun get(token: Address): Erc20TokenDto {
return contractService
.get(token)
.takeIf { it.type == ContractType.ERC20_TOKEN }
?.let { conversionService.convert<Erc20TokenDto>(it) }
?: throw TokenNotFoundException(token)
}
}
| 0
|
Kotlin
|
0
| 1
|
b1efdaceab8be95429befe80ce1092fab3004d18
| 894
|
ethereum-indexer
|
MIT License
|
src/main/kotlin/utils/ResultSetUtils.kt
|
SergeyHSE7
| 391,639,787
| false
| null |
package utils
import Column
import Entity
import Table
import java.sql.ResultSet
import kotlin.reflect.full.createInstance
internal fun <E : Entity> ResultSet.getEntity(table: Table<E>, lazy: Boolean): E {
val entity: E = table.entityClass.createInstance()
val columnNames = table.columns.map { it.name }.toHashSet()
with(metaData) {
(1..columnCount)
.filter { getTableName(it) == table.tableName && getColumnName(it) in columnNames }
.forEach { colIndex ->
setProp(entity, table.columns.first { it.name == getColumnName(colIndex) }, colIndex, lazy)
}
}
return entity
}
private fun <E : Entity, T> ResultSet.setProp(entity: E, column: Column<E, T>, columnIndex: Int, lazy: Boolean) {
val prop = column.property
if (column.refTable != null) {
val index = column.getValue(this, columnIndex) as? Int ?: return
val obj = if (lazy) column.refTable!!.entityClass.createInstance().apply { id = index }
else getEntity(column.refTable!!, false).also { column.refTable!!.cache.add(it, true) }
@Suppress("UNCHECKED_CAST")
prop.set(entity, obj as T)
} else prop.set(entity, column.getValue(this, columnIndex))
}
inline fun <T> ResultSet.map(func: ResultSet.() -> T?): List<T> {
val list = mutableListOf<T?>()
while (next()) list.add(func(this))
return list.mapNotNull { it }
}
| 0
|
Kotlin
|
1
| 1
|
01c23e02a5ede73647c5f4fc1cdefb8014b700c1
| 1,418
|
Kotlin-ORM
|
Apache License 2.0
|
app/src/main/java/com/frogobox/admobsample/ui/fragment/MainFragment.kt
|
msoftware
| 384,331,734
| true
|
{"Kotlin": 48122}
|
package com.frogobox.admobsample.ui.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.frogobox.admobsample.R
import com.frogobox.admobsample.base.BaseFragment
import com.frogobox.admobsample.databinding.FragmentMainBinding
/**
* A simple [Fragment] subclass.
*/
class MainFragment : BaseFragment<FragmentMainBinding>() {
override fun setupViewBinding(
inflater: LayoutInflater,
container: ViewGroup?
): FragmentMainBinding {
return FragmentMainBinding.inflate(inflater, container, false)
}
}
| 0
| null |
0
| 0
|
0d6f4ceffa70e6b31be24bf4375d91affbefe272
| 658
|
frogo-admob
|
Apache License 2.0
|
RxUI/src/main/java/com/tamsiree/rxui/view/loadingview/style/MultiplePulseRing.kt
|
Tamsiree
| 69,093,112
| false
| null |
package com.tamsiree.rxui.view.loadingview.style
import com.tamsiree.rxui.view.loadingview.sprite.Sprite
import com.tamsiree.rxui.view.loadingview.sprite.SpriteContainer
/**
* @author tamsiree
*/
class MultiplePulseRing : SpriteContainer() {
override fun onCreateChild(): Array<Sprite?>? {
return arrayOf(
PulseRing(),
PulseRing(),
PulseRing())
}
override fun onChildCreated(vararg sprites: Sprite?) {
for (i in 0 until sprites.size) {
sprites[i]?.setAnimationDelay(200 * (i + 1))
}
}
}
| 70
| null |
2855
| 12,025
|
fa5f88c24594a562c2a9047c40ceeb94de297428
| 591
|
RxTool
|
Apache License 2.0
|
mf/contracts/src/main/kotlin/ch/maxant/kdc/mf/contracts/boundary/query/ContractQueryResource.kt
|
maxant
| 174,798,779
| false
|
{"YAML": 21, "Text": 1, "Ignore List": 24, "Markdown": 25, "Shell": 4, "PlantUML": 4, "Maven POM": 25, "JSON": 21, "HTML": 28, "Java": 88, "Java Properties": 12, "XML": 4, "JavaScript": 68, "SQL": 49, "Dockerfile": 1, "CSS": 5, "INI": 4, "JSON with Comments": 3, "Browserslist": 1, "EditorConfig": 1, "Kotlin": 143}
|
package ch.maxant.kdc.mf.contracts.boundary.query
import ch.maxant.kdc.mf.contracts.adapter.DiscountSurcharge
import ch.maxant.kdc.mf.contracts.adapter.DiscountsSurchargesAdapter
import ch.maxant.kdc.mf.contracts.entity.ComponentEntity
import ch.maxant.kdc.mf.contracts.entity.ContractEntity
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ArrayNode
import io.smallrye.graphql.api.Context
import io.vertx.ext.web.RoutingContext
import org.eclipse.microprofile.graphql.*
import org.eclipse.microprofile.metrics.MetricUnits
import org.eclipse.microprofile.metrics.annotation.Timed
import org.eclipse.microprofile.rest.client.inject.RestClient
import org.jboss.logging.Logger
import java.math.BigDecimal
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import javax.inject.Inject
import javax.persistence.EntityManager
/**
* <pre>
query {
#aggregate { => uses a default value instead of providing one as follows:
aggregate(id: "77c1917d-2061-42e6-9631-78f10cbae161") {
# corresponds to the tolerant reader pattern, in that you only
# fetch data you really want - you MUST specify every field
# that you want to read
contract {
id
createdAt
createdAtFormattedByServer
contractState
createdAtFormattedByClient(pattern: "MMMM dd, YYYY")
discountsAddedInNewLocationInTree {
definitionId
}
components(definitionIdFilter:"Milk") {
id
parentId
productId
configs {key, value}
componentDefinitionId
}
}
# the following two were attempts to load data generically, but
# GraphQL doesnt seem to support that or wildcards
#
# discountsSurchargesArrayNode
# discountsSurchargesString
#
# so we load this data and have to provide the schema / write DTOs
discountsSurchargesDto {
componentId addedManually definitionId value
}
}
}
* </pre>
* see https://download.eclipse.org/microprofile/microprofile-graphql-1.0.3/microprofile-graphql.html#graphql_and_rest
* http://localhost:8080/graphql/schema.graphql
* http://localhost:8080/graphql-ui
*/
@GraphQLApi
class ContractQueryResource(
@Inject var em: EntityManager,
@Inject var om: ObjectMapper,
@Inject var context: Context,
@Inject var routingContext: RoutingContext
) {
@Inject
@RestClient // bizarrely this doesnt work with constructor injection
lateinit var discountsSurchargesAdapter: DiscountsSurchargesAdapter
private val log = Logger.getLogger(this.javaClass)
@Query("aggregate")
@Description("Get a contract by it's ID, without the cache")
@Timed(unit = MetricUnits.MILLISECONDS)
//@Secure // access the token via this.routingContext.request().headers()
fun findContractById(@Name("id") @DefaultValue("77c1917d-2061-42e6-9631-78f10cbae161") id: UUID): ContractAggregate {
log.info("getting contract $id with context.arguments ${context.arguments.map { "${it.key}->${it.value}" }}")
val discountsSurchargesArrayNode = discountsSurchargesAdapter.getByContractIdAsArrayNode(id)
val discountsSurchargesString = discountsSurchargesAdapter.getByContractIdAsString(id)
val discountsSurchargesDto = discountsSurchargesAdapter.getByContractIdAsDto(id)
return ContractAggregate(em.find(ContractEntity::class.java, id), discountsSurchargesArrayNode,
discountsSurchargesString, discountsSurchargesDto)
}
// adds a field called "discountsAddedInNewLocationInTree" to the entity
fun discountsAddedInNewLocationInTree(@Source contract: ContractEntity): List<DiscountSurcharge> =
discountsSurchargesAdapter.getByContractIdAsDto(contract.id).filter { it.value < BigDecimal.ZERO }
// adds a formatted field to the entity
@DateFormat(value = "dd MMM yyyy")
fun createdAtFormattedByServer(@Source contract: ContractEntity): LocalDateTime =
contract.createdAt
// adds a field to the entity, using the pattern supplied by the client
fun createdAtFormattedByClient(@Name("pattern") pattern: String, @Source contract: ContractEntity): String =
contract.createdAt.format(DateTimeFormatter.ofPattern(pattern))
@Query("components")
fun components(@Source contract: ContractEntity, @Name("definitionIdFilter") definitionIdFilter: String): List<Component> {
// val entities = ComponentEntity.Queries.selectByContractId(em, contract.id)
val entities = em.createQuery("select c from ComponentEntity c where c.contractId = :contractId")
.setParameter("contractId", contract.id)
.resultList as List<ComponentEntity> // avoid named query, and cast because of this: https://quarkusio.zulipchat.com/#narrow/stream/187030-users/topic/Hibernate.2FGraphQL.20SRGQL012000.3A.20Data.20Fetching.20Error
return entities
.filter { Regex(definitionIdFilter).matches((it).componentDefinitionId) }
.map { Component(om, it) }
}
}
@Type("Aggregate") // used to rename a class
data class ContractAggregate(
@NonNull val contract: ContractEntity?, // if the server dishes up null, the client gets an error!
// not necessary: @ToScalar(Scalar.String::class)
val discountsSurchargesArrayNode: ArrayNode,
val discountsSurchargesString: String,
val discountsSurchargesDto: List<DiscountSurcharge>
)
| 3
|
Kotlin
|
2
| 4
|
59c965b4635cfc2589fe187f69797d5273f93cca
| 5,593
|
kafka-data-consistency
|
MIT License
|
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/EmojiNatureSharp.kt
|
karakum-team
| 387,062,541
| false
|
{"Kotlin": 2961484, "TypeScript": 2249, "JavaScript": 1167, "HTML": 724, "CSS": 86}
|
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/EmojiNatureSharp")
package mui.icons.material
@JsName("default")
external val EmojiNatureSharp: SvgIconComponent
| 0
|
Kotlin
|
5
| 35
|
d12f6b1ad1b215ad7d3d9f27e24d48ada9b7fe2d
| 196
|
mui-kotlin
|
Apache License 2.0
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/TrainStationBuilding.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.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.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.TrainStationBuilding: ImageVector
get() {
if (_trainStationBuilding != null) {
return _trainStationBuilding!!
}
_trainStationBuilding = Builder(name = "TrainStationBuilding", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(23.392f, 9.478f)
lineToRelative(-1.306f, -1.306f)
curveToRelative(-0.744f, -0.745f, -1.774f, -1.172f, -2.828f, -1.172f)
horizontalLineToRelative(-2.26f)
curveToRelative(0.0f, -1.405f, -0.597f, -2.754f, -1.637f, -3.7f)
curveToRelative(-0.573f, -0.521f, -1.257f, -0.896f, -1.991f, -1.106f)
curveToRelative(-0.119f, -0.035f, -0.247f, -0.046f, -0.37f, -0.072f)
verticalLineToRelative(-1.122f)
curveToRelative(0.0f, -0.552f, -0.447f, -1.0f, -1.0f, -1.0f)
reflectiveCurveToRelative(-1.0f, 0.448f, -1.0f, 1.0f)
verticalLineToRelative(1.122f)
curveToRelative(-0.125f, 0.026f, -0.256f, 0.037f, -0.378f, 0.073f)
curveToRelative(-0.731f, 0.209f, -1.413f, 0.584f, -1.985f, 1.104f)
curveToRelative(-1.04f, 0.946f, -1.637f, 2.295f, -1.637f, 3.7f)
horizontalLineToRelative(-2.26f)
curveToRelative(-1.054f, 0.0f, -2.084f, 0.427f, -2.828f, 1.172f)
lineToRelative(-1.306f, 1.306f)
curveToRelative(-0.593f, 0.592f, -0.768f, 1.475f, -0.447f, 2.249f)
curveToRelative(0.172f, 0.416f, 0.474f, 0.743f, 0.841f, 0.966f)
verticalLineToRelative(7.808f)
curveToRelative(0.0f, 1.93f, 1.57f, 3.5f, 3.5f, 3.5f)
horizontalLineToRelative(0.715f)
curveToRelative(1.536f, 0.0f, 2.785f, -1.25f, 2.785f, -2.785f)
verticalLineToRelative(-0.215f)
curveToRelative(0.0f, -1.2f, 0.532f, -2.326f, 1.459f, -3.089f)
curveToRelative(0.94f, -0.775f, 2.131f, -1.072f, 3.357f, -0.831f)
curveToRelative(1.845f, 0.36f, 3.184f, 2.099f, 3.184f, 4.135f)
curveToRelative(0.0f, 1.536f, 1.249f, 2.785f, 2.785f, 2.785f)
horizontalLineToRelative(0.715f)
curveToRelative(1.93f, 0.0f, 3.5f, -1.57f, 3.5f, -3.5f)
verticalLineToRelative(-7.809f)
curveToRelative(0.366f, -0.223f, 0.667f, -0.549f, 0.839f, -0.965f)
curveToRelative(0.32f, -0.774f, 0.146f, -1.656f, -0.447f, -2.249f)
close()
moveTo(3.327f, 9.586f)
curveToRelative(0.375f, -0.375f, 0.883f, -0.586f, 1.414f, -0.586f)
horizontalLineToRelative(3.26f)
curveToRelative(0.552f, 0.0f, 1.0f, -0.448f, 1.0f, -1.0f)
verticalLineToRelative(-1.001f)
curveToRelative(0.0f, -1.656f, 1.343f, -2.999f, 2.999f, -2.999f)
horizontalLineToRelative(0.0f)
curveToRelative(1.657f, 0.0f, 3.0f, 1.344f, 2.999f, 3.001f)
verticalLineToRelative(0.999f)
curveToRelative(0.0f, 0.552f, 0.448f, 1.0f, 1.0f, 1.0f)
horizontalLineToRelative(3.26f)
curveToRelative(0.53f, 0.0f, 1.039f, 0.211f, 1.414f, 0.586f)
lineToRelative(1.306f, 1.306f)
lineToRelative(-0.045f, 0.108f)
lineTo(2.065f, 11.0f)
lineToRelative(-0.045f, -0.108f)
lineToRelative(1.306f, -1.306f)
close()
moveTo(19.5f, 22.0f)
horizontalLineToRelative(-0.715f)
curveToRelative(-0.433f, 0.0f, -0.785f, -0.352f, -0.785f, -0.785f)
curveToRelative(0.0f, -2.99f, -2.019f, -5.555f, -4.801f, -6.098f)
curveToRelative(-1.795f, -0.354f, -3.622f, 0.105f, -5.012f, 1.25f)
curveToRelative(-1.39f, 1.145f, -2.187f, 2.834f, -2.187f, 4.633f)
verticalLineToRelative(0.215f)
curveToRelative(0.0f, 0.433f, -0.353f, 0.785f, -0.785f, 0.785f)
horizontalLineToRelative(-0.715f)
curveToRelative(-0.827f, 0.0f, -1.5f, -0.673f, -1.5f, -1.5f)
verticalLineToRelative(-7.5f)
horizontalLineToRelative(18.0f)
verticalLineToRelative(7.5f)
curveToRelative(0.0f, 0.827f, -0.673f, 1.5f, -1.5f, 1.5f)
close()
moveTo(10.5f, 7.0f)
curveToRelative(0.0f, -0.828f, 0.672f, -1.5f, 1.5f, -1.5f)
reflectiveCurveToRelative(1.5f, 0.672f, 1.5f, 1.5f)
reflectiveCurveToRelative(-0.672f, 1.5f, -1.5f, 1.5f)
reflectiveCurveToRelative(-1.5f, -0.672f, -1.5f, -1.5f)
close()
}
}
.build()
return _trainStationBuilding!!
}
private var _trainStationBuilding: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 5,822
|
icons
|
MIT License
|
app/src/main/kotlin/com/github/premnirmal/ticker/model/RefreshWorker.kt
|
SasikumarN
| 282,930,233
| true
|
{"Kotlin": 359263}
|
package com.github.premnirmal.ticker.model
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.github.premnirmal.ticker.components.Injector
import com.github.premnirmal.ticker.isNetworkOnline
import javax.inject.Inject
class RefreshWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
companion object {
const val TAG = "RefreshWorker"
}
@Inject internal lateinit var stocksProvider: IStocksProvider
init {
Injector.appComponent.inject(this)
}
override suspend fun doWork(): Result {
if (applicationContext.isNetworkOnline()) {
val result = stocksProvider.fetch()
if (result.hasError) {
return Result.retry()
} else {
return Result.success()
}
} else {
stocksProvider.scheduleSoon()
return Result.retry()
}
}
}
| 0
| null |
0
| 0
|
4d77621f9e210c936f810e259e6779634a018d19
| 902
|
StockTicker
|
MIT License
|
app/src/main/java/com/lbg/project/domain/usecase/GetFavCatsUseCase.kt
|
PC-Wipro
| 696,757,421
| false
|
{"Java": 429337, "Kotlin": 100932}
|
package com.lbg.project.domain.usecase
import com.lbg.project.data.NetworkResult
import com.lbg.project.data.models.mappers.CatDataModel
import com.lbg.project.domain.repositories.CatsRepository
import com.lbg.project.utils.Constants
import kotlinx.coroutines.flow.Flow
class GetFavCatsUseCase(private val catDetailsRepo: CatsRepository) {
suspend fun execute(): Flow<NetworkResult<List<CatDataModel>>> {
return catDetailsRepo.fetchFavouriteCats(
Constants.SUB_ID
)
}
}
| 0
|
Kotlin
|
0
| 1
|
a7523671ce0cb940cc682018357c96014d6f2da6
| 509
|
LBG
|
Apache License 2.0
|
LABA5kt/src/parserPack/StringParser.kt
|
deadxraver
| 778,738,033
| false
|
{"Text": 3, "Gradle": 4, "Shell": 2, "Batchfile": 2, "Java Properties": 3, "Java": 221, "INI": 3, "XML": 27, "Ignore List": 4, "JAR Manifest": 1, "Kotlin": 48, "CSS": 4, "HTML": 85, "JavaScript": 9, "Markdown": 2}
|
package parserPack
import exceptionsPack.EmptyStringException
object StringParser {
/**
* Parses the input string by removing leading and trailing whitespaces,
* and collapsing multiple consecutive whitespaces into a single space.
*
* @param line the input string to be parsed
* @return the parsed string
*/
@Throws(EmptyStringException::class)
fun parse(line: String): String {
var line1 = line.trim { it <= ' ' }
if (line1.isEmpty()) throw EmptyStringException()
while (line1.contains(" ")) line1 = line1.replace(" {2}".toRegex(), " ")
return line1
}
}
| 0
|
Java
|
0
| 0
|
3f262f3175c7142487f8d225e4aac85f8f197d77
| 643
|
Programming
|
MIT License
|
app/src/main/java/com/example/dessertclicker/data/DessertUiState.kt
|
mirvn
| 609,463,590
| false
| null |
package com.example.dessertclicker.data
import androidx.annotation.DrawableRes
data class DessertUiState(
val currentIndex: Int = 0,
val dessertSold: Int = 0,
val revenue: Int = 0,
val currentPrice: Int = Datasource.dessertList[currentIndex].price,
@DrawableRes val dessertImage: Int = Datasource.dessertList[currentIndex].imageId
)
| 0
|
Kotlin
|
0
| 0
|
9b12d90f5ce1fcdacf6bec0e788fce94b81dd0c8
| 355
|
DessertClicker
|
Apache License 2.0
|
src/ad/kata/hangman/oo/Host.kt
|
andrej-dyck
| 252,646,491
| true
|
{"Kotlin": 39732, "Java": 3408}
|
package ad.kata.hangman.oo
import ad.kata.hangman.kotlinExtensions.runningFold
import ad.kata.hangman.kotlinExtensions.takeWithFirst
interface Host {
fun take(guesses: Guesses, maxMisses: MaxMisses): Sequence<GameEvent>
}
class ComputerHost(
private val chooseWord: () -> Word
) : Host {
constructor(word: Word) : this(chooseWord = { word })
constructor(words: Words) : this(words::random)
override fun take(guesses: Guesses, maxMisses: MaxMisses) =
guesses.runningFold(
GameStarted(newSecretWord(), maxMisses) as GameEvent
) { event: GameEvent, guess: Guess ->
event.takeOr(guess) { throw IllegalStateException("game over") }
}.takeWithFirst {
it is GameOver
}
private fun newSecretWord() = chooseWord().toSecret()
}
| 0
|
Kotlin
|
0
| 0
|
b519b29b4657a78a0d33fd61eba6a2b58b89bb33
| 817
|
kata-hangman
|
MIT License
|
src/main/kotlin/herbaccara/prevent/timelimit/annotation/GlobalPreventTimeLimit.kt
|
herbaccara
| 625,821,033
| false
| null |
package herbaccara.prevent.timelimit.annotation
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class GlobalPreventTimeLimit(val value: String)
| 0
|
Kotlin
|
0
| 0
|
f0659e36d15c6203f5200211dde6f9487e5b6d47
| 236
|
spring-boot-starter-prevent
|
MIT License
|
app/src/androidTest/java/br/com/paulosalvatore/movilenext_day4_robotpattern/robot/BaseTestRobot.kt
|
paulosalvatore
| 159,811,073
| false
| null |
package br.com.paulosalvatore.movilenext_day4_robotpattern.robot
import android.support.test.espresso.Espresso.onData
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.ViewInteraction
import android.support.test.espresso.action.ViewActions
import android.support.test.espresso.assertion.ViewAssertions
import android.support.test.espresso.matcher.ViewMatchers
import android.support.test.espresso.matcher.ViewMatchers.withId
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.anything
open class BaseTestRobot {
fun fillEditText(resId: Int, text: String) = onView(withId(resId)).perform(
ViewActions.replaceText(text),
ViewActions.closeSoftKeyboard()
)
fun clickButton(resId: Int) =
onView((withId(resId))).perform(ViewActions.click())
fun textView(resId: Int) =
onView(withId(resId))
fun matchText(viewInteraction: ViewInteraction, text: String) =
viewInteraction.check(ViewAssertions.matches(ViewMatchers.withText(text)))
fun matchText(resId: Int, text: String) = matchText(textView(resId), text)
// Para usos futuros, caso necessário
fun clickListItem(listRes: Int, position: Int) {
onData(anything())
.inAdapterView(allOf(withId(listRes)))
.atPosition(position).perform(ViewActions.click())
}
}
| 0
|
Kotlin
|
0
| 0
|
4852f600aa54772a59a68429f8bbc28176c89c9a
| 1,375
|
MovileNext_Day4_RobotPattern
|
MIT License
|
bitcoin/src/main/java/com/brentpanther/bitcoinwidget/CoinEntry.kt
|
hwki
| 8,993,387
| false
| null |
package com.brentpanther.bitcoinwidget
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class CoinEntry(
val id: String,
val name: String,
val symbol: String,
val coin: Coin,
val iconUrl: String? = null
) : Parcelable {
fun getFullIconUrl() = if (iconUrl == null) null else "https://assets.coingecko.com/coins/images/$iconUrl"
}
| 4
| null |
52
| 79
|
b375b94494cb9ef9b2bda5fea89248dd4fe5e2d3
| 386
|
SimpleBitcoinWidget
|
MIT License
|
src/cn/ancono/math/calculus/Calculus.kt
|
140378476
| 105,762,795
| false
|
{"Java": 1912158, "Kotlin": 1243514}
|
/**
*
*/
package cn.ancono.math.calculus
import cn.ancono.math.algebra.DecomposedPoly
import cn.ancono.math.algebra.IPolynomial
import cn.ancono.math.algebra.PolynomialUtil
import cn.ancono.math.algebra.SinglePoly
import cn.ancono.math.discrete.combination.CombUtils
import cn.ancono.math.function.AbstractSVPFunction
import cn.ancono.math.function.SVFunction
import cn.ancono.math.function.SVPFunction
import cn.ancono.math.function.invoke
import cn.ancono.math.numberModels.Fraction
import cn.ancono.math.numberModels.Multinomial
import cn.ancono.math.numberModels.Term
import cn.ancono.math.numberModels.api.RealCalculator
import cn.ancono.math.numberModels.api.plus
import cn.ancono.math.numberModels.expression.DerivativeHelper
import cn.ancono.math.numberModels.expression.ExprCalculator
import cn.ancono.math.numberModels.expression.Expression
import cn.ancono.math.numberModels.expression.Node
import cn.ancono.math.numberModels.structure.Polynomial
import java.util.function.DoubleUnaryOperator
import kotlin.math.abs
object Calculus {
/**
* A utility class for some calculus calculations. This class
* @author liyicheng
*/
private const val default_division: Long = 10000000
/**
* Computes the integral of the function by using small rectangles to compute a
* approximation. The function must be dimmed in `[a,b]`. The accuracy of the
* result will be based on the `delta` given, while the function itself will
* influence the accuracy of the result.
* @param fx the function
* @param a the starting of the area
* @param b the ending of the area
* @param delta the width of small intervals, positive
* @return integral
*/
@JvmStatic
fun integralApproximationLinear(fx: DoubleUnaryOperator, a: Double, b: Double, delta: Double): Double {
if (delta < 0) {
throw IllegalArgumentException("delta < 0")
}
if (a > b) {
throw IllegalArgumentException("a > b")
}
return integralApp0(fx, a, b, delta)
}
/**
* Computes the integral of the function by using small rectangles to compute a
* approximation. The function must be dimmed in `[a,b]`. This method will
* divide the whole interval averagely to `division` parts and computes all of them.
* @param fx the function
* @param a the starting of the area
* @param b the ending of the area
* @param division the number of intervals to divide
* @return integral
*/
@JvmStatic
@JvmOverloads
fun integralApproximationLinear(fx: DoubleUnaryOperator, a: Double, b: Double, division: Long = default_division): Double {
if (division < 0) {
throw IllegalArgumentException("division < 0")
}
if (a > b) {
throw IllegalArgumentException("a > b")
}
val delta = (b - a) / division
return integralApp0(fx, a, b, delta)
}
private fun integralApp0(fx: DoubleUnaryOperator, a: Double, b: Double, delta: Double): Double {
var x = a
var `in` = 0.0
`in` += fx.applyAsDouble(x)
while (true) {
x += delta
if (x >= b) {
break
}
`in` += 2 * fx.applyAsDouble(x)
}
`in` += fx.applyAsDouble(b)
`in` /= 2.0
`in` *= delta
return `in`
}
/**
* Computes the integral of the function by using the Simpson formula.
* @param fx the function
* @param a the starting of the area
* @param b the ending of the area
* @param n the parameter determining the accuracy of this method, the bigger this argument is, the longer time
* this method will take and the result will be more accurate.
* @return integral
*/
@JvmStatic
@JvmOverloads
fun integralApproximationSimpson(fx: DoubleUnaryOperator, a: Double, b: Double, n: Long = default_division): Double {
if (n <= 0) {
throw IllegalArgumentException("n < 0")
}
if (a > b) {
throw IllegalArgumentException("a > b")
}
var `in` = 0.0
var x = a
val delta = (b - a) / 2.0 / n.toDouble()
`in` += fx.applyAsDouble(x)
for (i in 0 until n) {
x += delta
`in` += 4 * fx.applyAsDouble(x)
x += delta
`in` += 2 * fx.applyAsDouble(x)
}
`in` += fx.applyAsDouble(b)
`in` /= 3.0
`in` *= delta
return `in`
}
/**
* Returns the derivation of a single variable polynomial function.
* @param f
* @return
*/
@JvmStatic
fun <T> derivation(f: SVPFunction<T>): AbstractSVPFunction<T> {
@Suppress("UNCHECKED_CAST")
val cns = arrayOfNulls<Any>(f.degree) as Array<T>
val mc = f.calculator
for (i in 1..f.degree) {
//(Ax^i)' = iA*x^(i-1)
cns[i - 1] = mc.multiplyLong(f.get(i), i.toLong())
}
return AbstractSVPFunction.valueOf(mc, *cns)
}
/**
* Returns the derivation of a polynomial.
*/
@JvmStatic
fun <T> derivation(f: IPolynomial<T>, mc: RealCalculator<T>): IPolynomial<T> {
if (f is Polynomial) {
return f.derivative()
}
return Polynomial.fromPolynomial(f, mc).derivative()
}
/**
* Returns the integration of a single variable polynomial function.
* @param f
* @return
*/
@JvmStatic
fun <T> integrate(f: SVPFunction<T>): AbstractSVPFunction<T> {
@Suppress("UNCHECKED_CAST")
val cns = arrayOfNulls<Any>(f.degree + 2) as Array<T>
val mc = f.calculator
for (i in 0..f.degree) {
//(Ax^(i+1))' = (i+1)*Ax^i
cns[i + 1] = mc.divideLong(f.get(i), (i + 1).toLong())
}
cns[0] = mc.zero
return AbstractSVPFunction.valueOf(mc, *cns)
}
/**
* Approximately computes the derivative of the given function [f] at the point of [x]. This method
* only chooses another point near the given point by [delta] and calculates the slope of the line
* passes through the two points.
*/
@JvmStatic
fun derivativeApproximately(f: SVFunction<Double>, x: Double, delta: Double = DEFAULT_DELTA): Double {
val y1 = f(x)
val y2 = f(x + delta)
return (y2 - y1) / delta
}
const val DEFAULT_DELTA: Double = 0.00000001
const val DEFAULT_RANGE: Double = 10000.0
/**
* Finds one root of the given single-variable function using Newton-Raphson method.
* This method will return only if the delta of two iterations is smaller than the given
* [rootDelta], and it will return null if the root cannot be find. There are several situations
* where the method will assume the root cannot be found.
* 1. The difference of adjacent x values cannot satisfy [rootDelta] even after [maxIterateTimes].
* 2. The difference of adjacent x values exceeds [maxSearchRange].
* 3. The derivative computed occurs to be 0.
*/
@JvmStatic
fun findRoot(f: SVFunction<Double>,
initialX: Double,
deriveDelta: Double = DEFAULT_DELTA,
rootDelta: Double = DEFAULT_DELTA,
maxSearchRange: Double = DEFAULT_RANGE,
maxIterateTimes: Int = 25): Double? {
//x_next = x - f(x)/f'(x)
var x = initialX
repeat(maxIterateTimes) {
val nextX = x - f(x) / derivativeApproximately(f, x, deriveDelta)
if (nextX.isNaN() || nextX.isInfinite()) {
return null
}
val d = abs(x - nextX)
if (d <= rootDelta) {
return nextX
} else if (d > maxSearchRange) {
//failed
return null
}
x = nextX
}
return null
}
/**
* Computes the derivation of the given expression without performing any simplification.
*/
@JvmStatic
fun Expression.derivation(variableName: String = "x"): Expression {
val root = this.root
return Expression(DerivativeHelper.derivativeNode(root, variableName))
}
/**
* Returns the total differential of the given expression without performing any simplification.
*/
@JvmStatic
fun Expression.totalDifferential(vararg variableNames: String): Expression {
val set = hashSetOf(*variableNames)
val root = this.root
val diffs = ArrayList<Node>(set.size)
for (name in set) {
diffs += DerivativeHelper.derivativeNode(root, name)
}
val nroot = Node.wrapNodeAM(true, diffs)
return Expression(nroot)
}
/**
* Determines whether the given list of expressions as differentials can compose
* a total differential of the same variables. It is required that the names of variables in
* the given list of are distinct.
*/
fun composeTotalDifferential(partialDiffs: List<Pair<Expression, String>>,
mc: ExprCalculator = ExprCalculator.instance): Boolean {
for (p1 in partialDiffs) {
for (p2 in partialDiffs) {
if (p1 === p2) {
//the same
continue
}
if (p1.second == p2.second) {
throw IllegalArgumentException("Variable name duplicated:${p1.second}")
}
var diff1 = p1.first.derivation(p2.second)
var diff2 = p2.first.derivation(p1.second)
diff1 = mc.simplify(diff1)
diff2 = mc.simplify(diff2)
if (!mc.isEqual(diff1, diff2)) {
return false
}
}
}
return true
}
/**
* Computes the derivation of the multinomial.
* @param expr the Multinomial
* @param variableName the name of the variable
* @return the derivation of the multinomial
*/
@JvmStatic
fun derivation(expr: Multinomial, variableName: String = "x"): Multinomial {
return Multinomial.fromTerms(expr.terms.map { derivation(it, variableName) })
}
/**
* Computes the derivation of the term.
*/
@JvmStatic
fun derivation(term: Term, variableName: String = "x"): Term {
return if (term.containsChar(variableName)) {
val t0 = Term.singleChar(variableName)
val t1 = term.divide(t0)
val t2 = t1.multiply(Term.valueOf(term.getCharacterPower(variableName)))
t2
} else {
Term.ZERO
}
}
fun taylorSeriesSeq(expr: Expression, variableName: String = "x", point: Expression = Expression.ZERO,
mc: ExprCalculator = ExprCalculator.instance)
: Sequence<Expression> = sequence {
var n = 0
var deno = 1L
var f = expr
while (true) {
val nume = mc.substitute(f, variableName, point)
val coe = mc.divideLong(nume, deno)
yield(coe)
n++
deno *= n
f = mc.differential(f, variableName)
}
}
// fun taylorSeries
fun taylorSeries(expr: Expression, variableName: String = "x",
point: Expression = Expression.ZERO, degree: Int = 3,
mc: ExprCalculator = ExprCalculator.instance): Polynomial<Expression> {
var re = Polynomial.zero(mc)
var f = expr
for (n in 0..degree) {
val nume = mc.substitute(f, variableName, point)
val deno = CombUtils.factorial(n)
val coe = mc.divideLong(nume, deno)
var t = Polynomial.binomialPower(point, n, mc)
t = t.multiply(coe)
re += t
f = mc.differential(f, variableName)
}
return re
}
fun <T> integrate(p: Polynomial<T>): Polynomial<T> {
return p.integration()
}
/**
* Make substitute for `ax^2+bx+c`.
* Returns the substituted polynomial a*u^2 +(4ac-b^2)/4a and u = x + b/2a
*/
private fun makeSubstitute(a: Expression, b: Expression, c: Expression, mc: ExprCalculator)
: Pair<Polynomial<Expression>, Polynomial<Expression>> {
// if(mc.isZero(a)){
// println("?")
// }
val t2 = mc.run { b / a / 2 }
val sub = Polynomial.of(mc, t2, mc.one)
// a (x + b/2a)^2 +(4ac-b^2)/4a
val t = mc.run { c - t2 * t2 }
val re = Polynomial.of(mc, t, mc.zero, a)
return re to sub
}
/**
* Returns the result of integrating a polynomial in the denominator part that has the degree of 1 or 2.
* If the degree of the polynomial is two, it must not have real roots.
*/
fun integrationDeno(deno: SinglePoly<Expression>, mc: ExprCalculator = ExprCalculator.instance,
variableName: String = "x"): Expression {
val d = deno.base
if (deno.pow == 1) {
when (d.degree) {
1 -> {
// 1/(ax+b)
// > ln(ax+b)/a
return mc.run { ln(Expression.fromPolynomialE(d, variableName)) / d.get(1) }
}
2 -> {
// 1/(ax^2+bx+c)
// 1/( ax^2 + c)
val a = d[2]
val b = d[1]
val c = d[0]
return intDeno2(a, b, c, mc, variableName)
}
}
throw ArithmeticException("Not supported: $d")
// return Expression(ln(deno.base))
}
if (d.degree == 1) {
// 1/(ax+b)^n
// > -1/(a(n-1)(ax+b)^(n-1))
val p = Expression.fromPolynomialE(d, variableName)
val nMinus1 = Expression.fromTerm(Term.valueOf(deno.pow - 1L))
return mc.run {
-mc.reciprocal(d[1] * nMinus1 * exp(p, nMinus1))
}
}
if (d.degree != 2) {
throw ArithmeticException("Not supported: $d")
}
//use step integration
if (!mc.isZero(d[1])) {
val (re, sub) = makeSubstitute(d[2], d[1], d[0], mc)
val subRe = integrationDeno(SinglePoly(null, re, deno.pow))
return mc.substitute(subRe, variableName, Expression.fromPolynomialE(sub, variableName))
}
val (p, q, sign) = getPQ(d[2], d[0], mc)
val result = integrationDeno2Pow(p, q, deno.pow, mc, variableName)
return if (deno.pow % 2 == 1) {
mc.multiply(result, sign)
} else {
result
}
}
/**
* Computes the integration of
* > 1/(p^2*x^2+q^2)^n
*/
fun integrationDeno2Pow(p: Expression, q: Expression, n: Int, mc: ExprCalculator, variableName: String = "x"): Expression {
if (n == 1) {
return intDeno2PQ(p, q, mc, variableName)
}
val x = Expression.fromTerm(Term.singleChar(variableName))
val q2 = mc.multiply(q, q)
val poly = mc.run { p * p * x * x + q2 } // p^2*x^2+q^2
// formula:
// I_n = 1/2(n-1)q^2 * ( (2n-3)I_(n-1) + x / (p^2*x^2+q^2)^(n-1) )
var inte = intDeno2PQ(p, q, mc, variableName)
var polyT = poly //(p^2*x^2+q^2)^(n-1)
for (i in 2..n) {
val iMinusOne = Expression.fromTerm(Term.valueOf(i - 1L))
val coe = mc.run { mc.reciprocal(iMinusOne * 2 * q2) }
val twoIMinus3 = Expression.fromTerm(Term.valueOf(2L * i - 3))
val prev = inte
val backPart = mc.run { x / polyT }
polyT = mc.multiply(polyT, poly)
inte = mc.run { coe * (twoIMinus3 * prev + backPart) }
}
return inte
}
private fun getPQ(a: Expression, c: Expression, mc: ExprCalculator): Array<Expression> {
val p: Expression
val q: Expression
val sign: Expression
if (mc.compare(a, mc.zero) < 0) {
p = mc.squareRoot(mc.negate(a))
q = mc.squareRoot(mc.negate(c))
sign = mc.negate(mc.one)
} else {
p = mc.squareRoot(a)
q = mc.squareRoot(c)
sign = mc.one
}
return arrayOf(p, q, sign)
}
/**
* Returns the integration of
* > 1/(p^2*x^2+q^2)
*/
fun intDeno2PQ(p: Expression, q: Expression, mc: ExprCalculator, variableName: String = "x"): Expression {
return mc.run { arctan(p / q * Expression.fromTerm(Term.singleChar(variableName))) / (p * q) }
}
fun intDeno2(a: Expression, b: Expression, c: Expression, mc: ExprCalculator, variableName: String): Expression {
return if (mc.isZero(b)) {
val (p, q, sign) = getPQ(a, c, mc)
// 1/pq * arctan( p/q * x)
mc.multiply(sign, intDeno2PQ(p, q, mc, variableName))
} else {
val (re, sub) = makeSubstitute(a, b, c, mc)
val subRe = integrationDeno(SinglePoly(re), mc, variableName)
mc.substitute(subRe, variableName, Expression.fromPolynomialE(sub, variableName))
}
}
fun intDeno1(a: Expression, b: Expression, mc: ExprCalculator, variableName: String = "x"): Expression {
// 1/(ax+b)
// > ln(ax+b)/a
return mc.run { ln(Expression.fromPolynomialE(Polynomial.of(mc, b, a), variableName)) / a }
}
/**
* Returns the integration of the form of
* > (Ax+B) / (ax^2+bx+c)^n
*/
fun intFrac2Pow(nume: Polynomial<Expression>,
deno: SinglePoly<Expression>,
mc: ExprCalculator, variableName: String = "x"): Expression {
// substitute first and
if (nume.degree > 2) {
throw ArithmeticException("Not supported: $nume")
}
val d = deno.base
if (mc.isZero(d[1])) {
return integrationFrac2Pow0(nume[1], nume[0], d[2], d[0], deno.pow, mc, variableName)
}
val a = d[2]
val b = d[1]
val c = d[0]
val (nDeno, sub) = makeSubstitute(a, b, c, mc)
val nNume = nume.substitute(Polynomial.of(mc, mc.negate(sub[0]), mc.one))// sub nume
val reSub = integrationFrac2Pow0(nNume[1], nNume[0], nDeno[2], nDeno[0], deno.pow, mc, variableName)
return mc.substitute(reSub, variableName, Expression.fromPolynomialE(sub, variableName))
}
/**
* Returns the integration of
* > (ax+b) / (p^2*x^2+q^2)
*/
fun integrationFrac2Pow0(a: Expression, b: Expression,
p: Expression, q: Expression, n: Int,
mc: ExprCalculator,
variableName: String): Expression {
val x = mc.multiply(a, integrationFrac2SingleX(p, q, n, mc, variableName))
val y = mc.multiply(b, integrationDeno2Pow(mc.squareRoot(p), mc.squareRoot(q), n, mc, variableName))
return mc.add(x, y)
}
/**
* Integration of x/(px^2+q)^n
*/
private fun integrationFrac2SingleX(p: Expression, q: Expression, pow: Int, mc: ExprCalculator, variableName: String): Expression {
val deno = SinglePoly(null, Polynomial.of(mc, q, p), pow)
val reX2 = integrationDeno(deno, mc, variableName)
val x2 = Expression.fromTerm(Term.characterPower(variableName, Fraction.TWO))
return mc.divideLong(mc.substitute(reX2, variableName, x2), 2L)
}
private fun integrationFracSingle(nume: Polynomial<Expression>,
deno: SinglePoly<Expression>,
mc: ExprCalculator, variableName: String): Expression {
return if (deno.base.degree == 2) {
intFrac2Pow(nume, deno, mc, variableName)
} else {
val t = integrationDeno(deno, mc, variableName)
mc.multiply(nume[0], t)
}
}
/**
* Integrates the fraction. It is required that the denominator is decomposed.
*/
fun intFrac(nume: Polynomial<Expression>, deno: DecomposedPoly<Expression>,
mc: ExprCalculator, variableName: String): Expression {
val (q, r) = nume.divideAndRemainder(deno.expanded)
val partA = Expression.fromPolynomialE(integrate(q), variableName)
val partials = PolynomialUtil.partialFraction(r, deno)
var partB = mc.zero
for ((n, d) in partials) {
val term = if (d.base.degree == 2) {
intFrac2Pow(n, d, mc, variableName)
} else {
mc.multiply(n[0], integrationDeno(d, mc, variableName))
}
partB = mc.add(partB, term)
}
return mc.add(partA, partB)
}
/**
* Computes the integration of a rational function.
*/
fun intRational(nume: Polynomial<Long>, deno: Polynomial<Long>, mc: ExprCalculator, variableName: String = "x")
: Expression {
val decomposed = PolynomialUtil.decomposeInt(deno)
val eNume = nume.mapTo(mc, java.util.function.Function { x -> Expression.valueOf(x) })
val eDeno = decomposed.map(mc, Expression::valueOf)
return intFrac(eNume, eDeno, mc, variableName)
}
}
| 1
|
Java
|
1
| 6
|
02c2984c10a95fcf60adcb510b4bf111c3a773bc
| 21,273
|
Ancono
|
MIT License
|
common/src/main/kotlin/net/wiredtomato/burgered/api/data/burger/BurgerStackables.kt
|
wired-tomato
| 835,870,549
| false
|
{"Kotlin": 122997, "Java": 4742}
|
package net.wiredtomato.burgered.api.data.burger
import com.mojang.serialization.Codec
import com.mojang.serialization.codecs.RecordCodecBuilder
import net.minecraft.core.registries.BuiltInRegistries
import net.minecraft.world.item.Item
import net.wiredtomato.burgered.api.StatusEffectEntry
import net.wiredtomato.burgered.api.event.LivingEntityEvents
import net.wiredtomato.burgered.init.BurgeredRegistries
import net.wiredtomato.burgered.util.byNameCodec
import org.jetbrains.annotations.ApiStatus.Internal
import java.util.*
data class BurgerStackable(
val item: Item,
val hunger: Int,
val saturation: Float,
val modelHeight: Double = 1.0,
val statusEffects: List<StatusEffectEntry> = listOf(),
val customName: Optional<String> = Optional.empty(),
val eatEvent: Optional<BurgerStackableEatCallback> = Optional.empty()
) {
companion object {
val CODEC: Codec<BurgerStackable> = RecordCodecBuilder.create { builder ->
builder.group(
BuiltInRegistries.ITEM.byNameCodec().fieldOf("item").forGetter(BurgerStackable::item),
Codec.INT.fieldOf("hunger").orElse(0).forGetter(BurgerStackable::hunger),
Codec.FLOAT.fieldOf("saturation").orElse(0f).forGetter(BurgerStackable::saturation),
Codec.DOUBLE.fieldOf("modelHeight").orElse(1.0).forGetter(BurgerStackable::modelHeight),
StatusEffectEntry.CODEC.listOf().fieldOf("statusEffects").orElse(listOf()).forGetter(BurgerStackable::statusEffects),
Codec.STRING.optionalFieldOf("customName").forGetter(BurgerStackable::customName),
BurgeredRegistries.EAT_EVENT.byNameCodec().optionalFieldOf("eatEvent").forGetter(BurgerStackable::eatEvent),
).apply(builder, ::BurgerStackable)
}
}
}
fun interface BurgerStackableEatCallback : LivingEntityEvents.EatCallback
@Internal object BurgerStackables : MutableList<BurgerStackable> by mutableListOf()
| 0
|
Kotlin
|
0
| 0
|
d945b34ecbf62bef9234f101a4cdf7ce504a1fa9
| 1,971
|
burgered
|
MIT License
|
app/src/main/java/com/luca020400/classiperlo/classes/DataItem.kt
|
luca020400
| 217,863,723
| false
| null |
package com.luca020400.classiperlo.classes
import androidx.annotation.Keep
@Keep
data class DataItem(val name: String, val url: Url)
| 0
|
Kotlin
|
0
| 1
|
f43b17111a810fe9b9d5ccfa4ce9d15367b6b862
| 135
|
Classiperlo
|
Apache License 2.0
|
lib/modules/http/volley/src/main/java/dev/pthomain/android/dejavu/volley/DejaVuVolleyBuilder.kt
|
pthomain
| 95,957,187
| false
|
{"Kotlin": 562195}
|
package dev.pthomain.android.dejavu.volley
import dev.pthomain.android.dejavu.configuration.ExtensionBuilder
import dev.pthomain.android.glitchy.core.interceptor.error.NetworkErrorPredicate
import org.koin.core.module.Module
import org.koin.dsl.koinApplication
import org.koin.dsl.module
class DejaVuVolleyBuilder<E> internal constructor()
: ExtensionBuilder<DejaVuVolleyBuilder<E>, DejaVuVolley<E>>
where E : Throwable,
E : NetworkErrorPredicate {
private var parentModules: List<Module>? = null
private val module = module {
single { VolleyObservable.Factory<E>(get(), get(), get()) }
}
override fun accept(modules: List<Module>) = apply {
parentModules = modules
}
/**
* Returns an instance of DejaVu.
*/
override fun build(): DejaVuVolley<E> {
val parentModules = this.parentModules
?: throw IllegalStateException("This builder needs to call DejaVuBuilder::extend")
return koinApplication {
modules(parentModules + module)
}.koin.run {
DejaVuVolley(get())
}
}
}
| 1
|
Kotlin
|
7
| 12
|
6e82c422293f1ed54f3522d6df94c5948116a79a
| 1,128
|
dejavu
|
Apache License 2.0
|
app/src/main/java/com/taro/aimentor/theme/ThemeManager.kt
|
Gear61
| 623,306,992
| false
| null |
package com.taro.aimentor.theme
import androidx.appcompat.app.AppCompatDelegate
object ThemeManager {
fun applyTheme(themeMode: Int) {
when (themeMode) {
ThemeMode.LIGHT -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
ThemeMode.DARK -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
ThemeMode.FOLLOW_SYSTEM -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
}
}
| 0
|
Kotlin
|
3
| 29
|
6f934528a942329112ad65f22b23ea48e1095f48
| 512
|
ai-mentor-android
|
Apache License 2.0
|
app/src/main/java/com/animestudios/animeapp/tools/BaseViewHolder.kt
|
Sozo-app
| 702,850,697
| false
|
{"Kotlin": 789146}
|
package com.animestudios.animeapp.tools
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.animestudios.animeapp.model.Message
abstract class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
abstract fun bind(item: Message)
}
| 0
|
Kotlin
|
5
| 22
|
50c65f924489bb94632b40ab840a15377e846686
| 285
|
Sozo
|
MIT License
|
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/haptics/arguments/HapticsInvalidArgumentException.kt
|
derekstavis
| 184,342,737
| false
| null |
package abi44_0_0.expo.modules.haptics.arguments
import abi44_0_0.expo.modules.core.errors.CodedException
class HapticsInvalidArgumentException internal constructor(message: String?) : CodedException(message) {
override fun getCode(): String {
return "E_HAPTICS_INVALID_ARGUMENT"
}
}
| 1
| null |
1
| 2
|
e377f0cd22db5cd7feb8e80348cd7064db5429b1
| 294
|
expo
|
MIT License
|
src/main/kotlin/fr/marstech/xenodrive/service/MinioService.kt
|
alkaphreak
| 697,183,111
| false
|
{"Kotlin": 9048, "Shell": 234}
|
package fr.marstech.xenodrive.service
import io.minio.GetObjectResponse
import io.minio.MinioClient
import io.minio.ObjectWriteResponse
import io.minio.Result
import io.minio.messages.Item
import java.nio.file.Path
interface MinioService {
fun connect(): MinioClient
fun downloadFile(remoteFilePath: String): GetObjectResponse?
fun uploadFile(
localFilePath: Path,
remoteFilePath: Path,
contentType: String? = null
): ObjectWriteResponse?
fun remove()
fun listDirectory(remoteDirectoryPath: Path? = null): List<Result<Item>>
}
| 0
|
Kotlin
|
0
| 1
|
1470fca44767115b5cdf628873693e808cd94b44
| 581
|
marstech-xeno-drive
|
MIT License
|
app/src/main/java/com/ntxdroid/spacex/feature/mission/MissionsAdapter.kt
|
alwarren
| 195,475,619
| false
| null |
package com.ntxdroid.spacex.feature.mission
import android.graphics.Color
import android.graphics.PorterDuff
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.ntxdroid.spacex.R
import com.ntxdroid.spacex.core.extension.repeatUntilSize
import com.ntxdroid.spacex.core.extension.colorList
import com.ntxdroid.spacex.core.platform.AbstractListRecycler
import kotlinx.android.synthetic.main.mission_card.view.*
/**
* Created by <NAME> on 1/31/2019.
*/
class MissionsAdapter : AbstractListRecycler<MissionView>() {
override fun layoutId() = R.layout.mission_card
override fun createViewHolder(view: View) = MissionViewHolder(view, collection.size)
class MissionViewHolder(itemView: View, size: Int): RecyclerView.ViewHolder(itemView), Binder<MissionView> {
private val colors = itemView.colorList().repeatUntilSize(size)
override fun bind(data: MissionView, clickListener: (MissionView) -> Unit) {
itemView.missionInitial.apply {
text = data.missionName[0].toString()
background.setColorFilter(Color.parseColor(colors[layoutPosition]),
PorterDuff.Mode.SRC_OVER)
}
itemView.missionName.text = data.missionName
itemView.missionInitial.text = data.missionName[0].toString()
itemView.manufacturers.text = data.manufacturers.joinToString(", ")
itemView.setOnClickListener { clickListener(data) }
}
}
}
| 0
|
Kotlin
|
1
| 1
|
0c904a6e086d9ad0dd56231c2e5ef6469d5ec39c
| 1,498
|
AndroidXMVVMDemo
|
MIT License
|
arcgis-android-toolkit/src/main/java/com/esri/arcgisruntime/toolkit/scalebar/style/renderer/DualUnitLineRenderer.kt
|
Esri
| 12,741,334
| false
|
{"Kotlin": 357736, "Java": 60473}
|
/*
* Copyright 2019 Esri
*
* 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.valentingrigorean.arcgis_maps_flutter.toolkit.scalebar.style.renderer
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import com.esri.arcgisruntime.UnitSystem
import com.esri.arcgisruntime.geometry.LinearUnit
import com.valentingrigorean.arcgis_maps_flutter.toolkit.extension.asDistanceString
import com.valentingrigorean.arcgis_maps_flutter.toolkit.extension.calculateBestLength
import com.valentingrigorean.arcgis_maps_flutter.toolkit.extension.selectLinearUnit
import com.valentingrigorean.arcgis_maps_flutter.toolkit.scalebar.LINEAR_UNIT_FEET
import com.valentingrigorean.arcgis_maps_flutter.toolkit.scalebar.LINEAR_UNIT_METERS
import com.valentingrigorean.arcgis_maps_flutter.toolkit.scalebar.SHADOW_OFFSET_PIXELS
import com.valentingrigorean.arcgis_maps_flutter.toolkit.scalebar.style.Style
import com.valentingrigorean.arcgis_maps_flutter.toolkit.scalebar.style.Style.DUAL_UNIT_LINE
/**
* Renders a [DUAL_UNIT_LINE] style scalebar.
*
* @see Style.DUAL_UNIT_LINE
*
* @since 100.5.0
*/
class DualUnitLineRenderer : ScalebarRenderer() {
override val isSegmented: Boolean = false
override fun drawScalebar(
canvas: Canvas,
left: Float,
top: Float,
right: Float,
bottom: Float,
distance: Double,
displayUnits: LinearUnit,
unitSystem: UnitSystem,
lineWidthPx: Int,
cornerRadiusPx: Int,
textSizePx: Int,
fillColor: Int,
alternateFillColor: Int,
shadowColor: Int,
lineColor: Int,
textPaint: Paint,
displayDensity: Float
) {
// Calculate scalebar length in the secondary units
val secondaryBaseUnits = if (unitSystem == UnitSystem.METRIC) LINEAR_UNIT_FEET else LINEAR_UNIT_METERS
val fullLengthInSecondaryUnits = displayUnits.convertTo(secondaryBaseUnits, distance)
// Reduce the secondary units length to make it a nice number
var secondaryUnitsLength = calculateBestLength(fullLengthInSecondaryUnits, secondaryBaseUnits)
val lineDisplayLength = right - left
val xPosSecondaryTick =
left + (lineDisplayLength * secondaryUnitsLength / fullLengthInSecondaryUnits).toFloat()
// Change units if secondaryUnitsLength is too big a number in the base units
val secondaryUnitSystem = if (unitSystem == UnitSystem.METRIC) UnitSystem.IMPERIAL else UnitSystem.METRIC
val secondaryDisplayUnits = selectLinearUnit(secondaryUnitsLength, secondaryUnitSystem)
if (secondaryDisplayUnits != secondaryBaseUnits) {
secondaryUnitsLength = secondaryBaseUnits.convertTo(secondaryDisplayUnits, secondaryUnitsLength)
}
val verticalTextSpace = textSizePx + textPaint.fontMetrics.bottom
// Create Paint for drawing the lines
with(paint) {
reset()
style = Paint.Style.STROKE
strokeWidth = lineWidthPx.toFloat()
strokeCap = Paint.Cap.ROUND
strokeJoin = Paint.Join.ROUND
// Create a path to draw the line and the ticks
linePath.let { linePath ->
val yPosLine = ((top + verticalTextSpace) + (bottom)) / 2
linePath.reset()
linePath.moveTo(left, top + verticalTextSpace)
linePath.lineTo(left, bottom) // draw big tick at left
linePath.moveTo(xPosSecondaryTick, yPosLine) // move to top of secondary tick
linePath.lineTo(xPosSecondaryTick, bottom) // draw secondary tick
linePath.moveTo(left, yPosLine) // move to start of horizontal line
linePath.lineTo(right, yPosLine) // draw the line
linePath.lineTo(right, top + verticalTextSpace) // draw tick at right
linePath.setLastPoint(right, top + verticalTextSpace)
// Create a copy of the line path to be the path of its shadow, offset slightly from the line path
val shadowPath = Path(linePath)
shadowPath.offset(SHADOW_OFFSET_PIXELS, SHADOW_OFFSET_PIXELS)
// Draw the shadow
color = shadowColor
canvas.drawPath(shadowPath, this)
// Draw the line and the ticks
color = lineColor
canvas.drawPath(linePath, this)
// Draw the primary units label above the tick at the right hand end
var yPosText = top + textSizePx
textPaint.textAlign = Paint.Align.RIGHT
canvas.drawText(distance.asDistanceString(), right, yPosText, textPaint)
textPaint.textAlign = Paint.Align.LEFT
canvas.drawText(' ' + displayUnits.abbreviation, right, yPosText, textPaint)
// Draw the secondary units label below its tick
yPosText = bottom + textSizePx
textPaint.textAlign = Paint.Align.RIGHT
canvas.drawText(secondaryUnitsLength.asDistanceString(), xPosSecondaryTick, yPosText, textPaint)
textPaint.textAlign = Paint.Align.LEFT
canvas.drawText(' ' + secondaryDisplayUnits.abbreviation, xPosSecondaryTick, yPosText, textPaint)
}
}
}
override fun calculateExtraSpaceForUnits(displayUnits: LinearUnit?, textPaint: Paint): Float {
return calculateWidthOfUnitsString(displayUnits, textPaint)
}
}
| 2
|
Kotlin
|
40
| 51
|
045728b96672b70ff3bec61ec99d15d066538ff7
| 6,051
|
arcgis-runtime-toolkit-android
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/CircleHalf.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.CircleHalf: ImageVector
get() {
if (_circleHalf != null) {
return _circleHalf!!
}
_circleHalf = Builder(name = "CircleHalf", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(14.0f, 24.0f)
horizontalLineToRelative(-2.0f)
curveTo(5.38f, 24.0f, 0.0f, 18.62f, 0.0f, 12.0f)
reflectiveCurveTo(5.38f, 0.0f, 12.0f, 0.0f)
horizontalLineToRelative(2.0f)
verticalLineTo(24.0f)
close()
moveTo(11.0f, 3.06f)
curveTo(6.51f, 3.55f, 3.0f, 7.38f, 3.0f, 12.0f)
reflectiveCurveToRelative(3.51f, 8.45f, 8.0f, 8.94f)
verticalLineTo(3.06f)
close()
}
}
.build()
return _circleHalf!!
}
private var _circleHalf: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 1,771
|
icons
|
MIT License
|
src/main/kotlin/com/tuk/oriddle/user/application/port/out/SaveUserPort.kt
|
Team-Oriddle
| 731,663,342
| false
|
{"Kotlin": 152977}
|
package com.tuk.oriddle.user.application.port.out
import com.tuk.oriddle.user.adapter.out.persistence.UserJpaEntity
import com.tuk.oriddle.user.domain.User
interface SaveUserPort {
fun saveUser(user: User): UserJpaEntity
}
| 2
|
Kotlin
|
1
| 0
|
4fed5e20ba1c0bc9c24bb32d9436c8cc995a2335
| 228
|
oriddle-backend
|
MIT License
|
bot/connector-web/src/main/kotlin/channel/ChannelDAO.kt
|
theopenconversationkit
| 84,538,053
| false
|
{"Kotlin": 6173880, "TypeScript": 1286450, "HTML": 532576, "Python": 376720, "SCSS": 79512, "CSS": 66318, "Shell": 12085, "JavaScript": 1849}
|
/*
* Copyright (C) 2017/2021 e-voyageurs technologies
*
* 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 ai.tock.bot.connector.web.channel
internal interface ChannelDAO {
fun listenChanges(listener: ChannelEvent.Handler)
fun handleMissedEvents(appId: String, recipientId: String, handler: ChannelEvent.Handler)
fun save(channelEvent: ChannelEvent)
}
| 163
|
Kotlin
|
127
| 475
|
890f69960997ae9146747d082d808d92ee407fcb
| 879
|
tock
|
Apache License 2.0
|
app/src/main/java/com/example/jikgong/view/main/pay/PaymentFragment.kt
|
KT-Beak-Ho
| 735,902,125
| false
|
{"Kotlin": 8629}
|
package com.example.jikgong.view.main.pay
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.jikgong.R
class PaymentFragment : Fragment() {
// TODO: Rename and change types of parameters
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_payment, container, false)
}
}
| 0
|
Kotlin
|
3
| 0
|
1c4c2f4e8082bab3f794a3e40dbea12cb118032f
| 728
|
Front_end
|
MIT License
|
app/src/main/java/com/paulo/placar/MainActivity.kt
|
PauloFerreira-S
| 294,962,439
| false
| null |
package com.paulo.placar
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var intent = intent
var time1 = intent.getStringExtra("Time1")
var time2 = intent.getStringExtra("Time2")
textView.text = time1.toString()
textView2.text = time2.toString()
//Botões do time A
btn_a3.setOnClickListener(){
a_tres_pontos()
}
btn_a2.setOnClickListener(){
a_dois_pontos()
}
btn_a1.setOnClickListener(){
a_um_pontos()
}
btn_an1.setOnClickListener(){
a_neg_pontos()
}
//Botões do time B
btn_b3.setOnClickListener(){
b_tres_pontos()
}
btn_b2.setOnClickListener(){
b_dois_pontos()
}
btn_b1.setOnClickListener(){
b_um_pontos()
}
btn_bn1.setOnClickListener(){
b_neg_pontos()
}
btn_reset.setOnClickListener {
reset()
}
btn_finalizar.setOnClickListener(){
finalizar()
}
}
fun a_tres_pontos(){
var pont = txt_aplacar.text.toString().toInt() + 3
txt_aplacar.text = pont.toString()
}
fun a_dois_pontos(){
var pont = txt_aplacar.text.toString().toInt() + 2
txt_aplacar.text = pont.toString()
}
fun a_um_pontos(){
var pont = txt_aplacar.text.toString().toInt() + 1
txt_aplacar.text = pont.toString()
}
fun a_neg_pontos(){
var pont = txt_aplacar.text.toString().toInt()
if (pont >= 1){
pont--
txt_aplacar.text = pont.toString()
}
}
fun b_tres_pontos(){
var pont = txt_bplacar.text.toString().toInt() + 3
txt_bplacar.text = pont.toString()
}
fun b_dois_pontos(){
var pont = txt_bplacar.text.toString().toInt() + 2
txt_bplacar.text = pont.toString()
}
fun b_um_pontos(){
var pont = txt_bplacar.text.toString().toInt() + 1
txt_bplacar.text = pont.toString()
}
fun b_neg_pontos(){
var pont = txt_bplacar.text.toString().toInt()
if (pont >= 1){
pont--
txt_bplacar.text = pont.toString()
}
}
fun reset(){
var pont:String = "0"
txt_aplacar.text = pont
txt_bplacar.text = pont
}
fun finalizar(){
var time1 = intent.getStringExtra("Time1")
var time2 = intent.getStringExtra("Time2")
var placar1 = txt_aplacar.text.toString().toInt()
var placar2 = txt_bplacar.text.toString().toInt()
val intent = Intent(this@MainActivity, Activity2::class.java)
intent.putExtra("Placar1", placar1)
intent.putExtra("Placar2", placar2)
intent.putExtra("Time2", time2)
intent.putExtra("Time1", time1)
startActivity(intent)
}
}
| 0
|
Kotlin
|
0
| 0
|
cf8dd7a0b5f1771887120cf7cb53ca122dbc3dfe
| 3,194
|
Placar
|
MIT License
|
app/src/main/java/com/app/upload_file/ui/upload_files/UploadFileActivity.kt
|
thanhit93
| 459,072,267
| false
| null |
package com.app.upload_file.ui.upload_files
import android.Manifest
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.FirebaseStorage
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_upload_file.*
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.view.View
import android.provider.OpenableColumns
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.single.DialogOnDeniedPermissionListener
import com.karumi.dexter.listener.single.PermissionListener
import com.karumi.dexter.listener.PermissionDeniedResponse
import com.karumi.dexter.listener.PermissionGrantedResponse
import com.karumi.dexter.Dexter
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import com.karumi.dexter.listener.PermissionRequest
import android.widget.Toast
import com.app.upload_file.R
class UploadFileActivity : AppCompatActivity() {
private val RESULT_IMAGE = 10
lateinit var fileNameList: ArrayList<String>
lateinit var fileDoneList: ArrayList<String>
lateinit var mAdapter: UploadListAdapter
lateinit var mStorageReference: StorageReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_upload_file)
fileNameList = ArrayList()
fileDoneList = ArrayList()
mAdapter = UploadListAdapter(fileNameList, fileDoneList)
recycler_upload!!.layoutManager = LinearLayoutManager(this)
recycler_upload.setHasFixedSize(true)
recycler_upload.adapter = mAdapter
mStorageReference = FirebaseStorage.getInstance().reference
// set on-click listener
btnUpload.setOnClickListener {
requestPermission()
val intent = Intent()
intent.type = "image/*"
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(intent, "Select Picture"), RESULT_IMAGE)
}
}
@SuppressLint("NotifyDataSetChanged")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RESULT_IMAGE && resultCode == RESULT_OK) {
if (data?.clipData != null) {
//Toast.makeText(this, "Selected Multiple Files", Toast.LENGTH_SHORT).show();
val totalItems = data.clipData!!.itemCount
for (i in 0 until totalItems) {
val fileUri = data.clipData!!.getItemAt(i).uri
val fileName = getFileName(fileUri)
fileNameList.add(fileName)
fileDoneList.add("Uploading")
mAdapter.notifyDataSetChanged()
val fileToUpload = mStorageReference.child("Images").child(fileName)
fileToUpload.putFile(fileUri)
.addOnSuccessListener { //Toast.makeText(MainActivity.this, "Done", Toast.LENGTH_SHORT).show();
fileDoneList.removeAt(i)
fileDoneList.add(i, "Done")
mAdapter.notifyDataSetChanged()
}
}
} else if (data?.data != null) {
Toast.makeText(this, "Selected Single File", Toast.LENGTH_SHORT).show()
}
}
}
private fun getFileName(uri: Uri): String {
var result: String? = null
if (uri.scheme.equals("content")) {
val cursor: Cursor? = contentResolver.query(uri, null, null, null, null)
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
}
} finally {
cursor?.close()
}
}
if (result == null) {
result = uri.path
val cut = result!!.lastIndexOf('/')
if (cut != -1) {
result = result.substring(cut + 1)
}
}
return result
}
private fun showSettingsDialog() {
val builder: AlertDialog.Builder = AlertDialog.Builder(this@UploadFileActivity)
builder.setTitle("Need Permissions")
builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.")
builder.setPositiveButton("GO TO SETTINGS") { dialog, which ->
dialog.cancel()
openSettings()
}
builder.setNegativeButton("Cancel"
) { dialog, which -> dialog.cancel() }
builder.show()
}
private fun openSettings() {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", packageName, null)
intent.data = uri
startActivityForResult(intent, 101)
}
private fun requestPermission() {
Dexter.withContext(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(object : PermissionListener {
override fun onPermissionGranted(permissionGrantedResponse: PermissionGrantedResponse) {}
override fun onPermissionDenied(permissionDeniedResponse: PermissionDeniedResponse) {
val dialogPermissionListener: PermissionListener = DialogOnDeniedPermissionListener.Builder
.withContext(this@UploadFileActivity)
.withTitle("Read External Storage permission")
.withMessage("Read External Storage permission is needed")
.withButtonText(android.R.string.ok)
.withIcon(R.mipmap.ic_launcher)
.build()
// Intent permIntent = new Intent();
// permIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
// Uri uri = Uri.fromParts("package",getPackageName(),null);
// permIntent.setData(uri);
// startActivity(permIntent);
}
override fun onPermissionRationaleShouldBeShown(
permissionRequest: PermissionRequest?,
permissionToken: PermissionToken
) {
permissionToken.continuePermissionRequest()
}
}).check()
}
}
| 0
|
Kotlin
|
0
| 0
|
8775ab01083bb8ea5fb4204438908767a177ba6a
| 6,755
|
multiple_upload_firebase
|
MIT License
|
build-logic/convention/src/main/kotlin/AndroidLibraryComposeConventionPlugin.kt
|
atomgomba
| 754,770,216
| false
|
{"Kotlin": 209676}
|
import com.android.build.api.dsl.LibraryExtension
import com.ekezet.othello.configureAndroidCompose
import com.ekezet.othello.configureAndroidKoinCompose
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.getByType
class AndroidLibraryComposeConventionPlugin : Plugin<Project> {
override fun apply(target: Project) {
with(target) {
with(pluginManager) {
apply("com.android.library")
}
val extension = extensions.getByType<LibraryExtension>()
configureAndroidCompose(extension)
configureAndroidKoinCompose(extension)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
072786ee50a61d5dc6acca65dd65306c5c6ab1ee
| 661
|
othello
|
Apache License 2.0
|
app/src/main/java/com/thewizrd/simpleweather/services/AppUpdaterWorker.kt
|
jonnypjohnston
| 371,908,311
| false
| null |
package com.thewizrd.simpleweather.services
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.SystemClock
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.work.*
import com.thewizrd.shared_resources.preferences.FeatureSettings
import com.thewizrd.shared_resources.utils.Colors
import com.thewizrd.shared_resources.utils.Logger
import com.thewizrd.simpleweather.LaunchActivity
import com.thewizrd.simpleweather.R
import com.thewizrd.simpleweather.updates.InAppUpdateManager
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
class AppUpdaterWorker(context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) {
companion object {
private const val TAG = "AppUpdaterWorker"
// Sets an ID for the notification
private const val NOT_CHANNEL_ID = "SimpleWeather.appupdates"
@JvmStatic
fun registerWorker(context: Context) {
val context = context.applicationContext
enqueueWork(context)
}
private fun enqueueWork(context: Context) {
val context = context.applicationContext
Logger.writeLine(Log.INFO, "%s: Requesting work; workExists: %s", TAG, isWorkScheduled(context).toString())
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.setRequiresCharging(false)
.build()
val updateRequest = PeriodicWorkRequest.Builder(AppUpdaterWorker::class.java, 1, TimeUnit.DAYS)
.setConstraints(constraints)
.addTag(TAG)
.build()
WorkManager.getInstance(context)
.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP, updateRequest)
Logger.writeLine(Log.INFO, "%s: Work enqueued", TAG)
}
private fun isWorkScheduled(context: Context): Boolean {
val context = context.applicationContext
val workMgr = WorkManager.getInstance(context)
var statuses: List<WorkInfo>? = null
try {
statuses = workMgr.getWorkInfosForUniqueWork(TAG).get()
} catch (ignored: ExecutionException) {
} catch (ignored: InterruptedException) {
}
if (statuses?.isNullOrEmpty() == true) return false
var running = false
for (workStatus in statuses) {
running = (workStatus.state == WorkInfo.State.RUNNING
|| workStatus.state == WorkInfo.State.ENQUEUED)
}
return running
}
private fun getLaunchUpdatesIntent(context: Context): PendingIntent {
val i = Intent(context.applicationContext, LaunchActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
return PendingIntent.getActivity(context.applicationContext, 0, i, PendingIntent.FLAG_UPDATE_CURRENT)
}
}
override suspend fun doWork(): Result {
Logger.writeLine(Log.INFO, "%s: Work started", TAG)
// Creates instance of the manager.
val appUpdateManager = InAppUpdateManager.create(applicationContext)
if (appUpdateManager.checkIfUpdateAvailable()) {
if (appUpdateManager.updatePriority > 3 && !FeatureSettings.isUpdateAvailable()) {
// Notify user of update availability
val mNotifyMgr = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
initChannel(mNotifyMgr)
val mNotif = NotificationCompat.Builder(applicationContext, NOT_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_error_white)
.setContentTitle(applicationContext.getString(R.string.prompt_update_title))
.setContentText(applicationContext.getString(R.string.prompt_update_available))
.setContentIntent(getLaunchUpdatesIntent(applicationContext))
.setColor(Colors.SIMPLEBLUE)
.setAutoCancel(true)
mNotifyMgr.notify((SystemClock.uptimeMillis() + appUpdateManager.updatePriority).toInt(), mNotif.build())
}
}
return Result.success()
}
private fun initChannel(mNotifyMgr: NotificationManager) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
var mChannel = mNotifyMgr.getNotificationChannel(NOT_CHANNEL_ID)
// "App Updates"
val notchannel_name = applicationContext.resources.getString(R.string.not_channel_update_title)
if (mChannel == null) {
mChannel = NotificationChannel(NOT_CHANNEL_ID, notchannel_name, NotificationManager.IMPORTANCE_LOW)
}
mChannel.name = notchannel_name
// Configure the notification channel.
mChannel.setShowBadge(true)
mChannel.enableLights(false)
mChannel.enableVibration(false)
mNotifyMgr.createNotificationChannel(mChannel)
}
}
}
| 1
| null |
1
| 1
|
e07dd52b9fd66456bcefa6b14641f3637bc6c8ac
| 5,504
|
Microsoft-SimpleWeather-Android
|
Apache License 2.0
|
viewpagerdotsindicator/src/main/java/com/tbuonomo/viewpagerdotsindicator/ViewPagerWrapper.kt
|
kibotu
| 166,256,629
| false
| null |
package com.tbuonomo.viewpagerdotsindicator
import android.database.DataSetObserver
import androidx.viewpager.widget.ViewPager
class ViewPagerWrapper(private val viewPager: ViewPager) : ViewPagerInterface {
override val hasAdapter: Boolean
get() = viewPager.adapter != null
override val count: Int
get() = viewPager.adapter?.count ?: 0
override val currentItem: Int
get() = viewPager.currentItem
override fun setCurrentItem(position: Int, smoothScroll: Boolean) {
viewPager.setCurrentItem(position, smoothScroll)
}
override fun removeOnPageChangeListener(onPageChangeListenerHelper: OnPageChangeListenerHelper) {
viewPager.removeOnPageChangeListener(onPageChangeListenerHelper)
}
override fun addOnPageChangeListener(onPageChangeListenerHelper: OnPageChangeListenerHelper) {
viewPager.addOnPageChangeListener(onPageChangeListenerHelper)
}
override fun registerDataSetObserver(dataSetObserver: DataSetObserver) {
viewPager.adapter?.registerDataSetObserver(dataSetObserver)
}
}
| 1
| null |
1
| 1
|
54d7a9653a9ba04fd94871ae43046a7691193b89
| 1,084
|
dotsindicator
|
Apache License 2.0
|
browser-kotlin/src/jsMain/kotlin/web/xhr/XMLHttpRequestResponseType.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6149909}
|
// Automatically generated - do not modify!
@file:Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.xhr
// language=JavaScript
@JsName("""(/*union*/{none: '', arraybuffer: 'arraybuffer', blob: 'blob', document: 'document', json: 'json', text: 'text'}/*union*/)""")
sealed external interface XMLHttpRequestResponseType {
companion object {
val none: XMLHttpRequestResponseType
val arraybuffer: XMLHttpRequestResponseType
val blob: XMLHttpRequestResponseType
val document: XMLHttpRequestResponseType
val json: XMLHttpRequestResponseType
val text: XMLHttpRequestResponseType
}
}
| 0
|
Kotlin
|
6
| 26
|
3fcfd2c61da8774151cf121596e656cc123b37db
| 686
|
types-kotlin
|
Apache License 2.0
|
app/src/main/java/com/xily/kotlinweather/model/bean/BusBean.kt
|
Xily9
| 137,105,320
| false
|
{"Kotlin": 167408}
|
package com.xily.kotlinweather.model.bean
class BusBean {
var position: Int = 0
var status: Int = 0
var message: String? = null
}
| 0
|
Kotlin
|
0
| 1
|
30693906d3855fc115ba398f561c81478d38cd23
| 143
|
KotlinWeather
|
MIT License
|
data/src/main/java/com/example/data/models/login/LoginRequestModel.kt
|
meghdadya
| 776,918,286
| false
|
{"Kotlin": 85745}
|
package com.example.data.models.login
import com.google.gson.annotations.SerializedName
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
data class LoginRequestModel(
@SerializedName("identifier")
val identifier: String,
@SerializedName("method")
val method: String,
@SerializedName("password")
val password: String
)
| 0
|
Kotlin
|
0
| 0
|
a0b7cd489ee3e85e1197b90d8b08eb94a9c7901c
| 378
|
OryAuthentication
|
Apache License 2.0
|
itemviewmodel/withFXproperties/src/main/kotlin/no/tornadofx/fxsamples/withfxproperties/controller/PersonController.kt
|
vfishv
| 227,888,628
| true
|
{"Kotlin": 39605}
|
package no.tornadofx.fxsamples.withfxproperties.controller
import javafx.collections.FXCollections
import no.tornadofx.fxsamples.withfxproperties.model.Person
import no.tornadofx.fxsamples.withfxproperties.model.PersonModel
import no.tornadofx.fxsamples.withfxproperties.model.PhoneNumber
import tornadofx.Controller
class PersonController : Controller() {
val persons = FXCollections.observableArrayList<Person>()
val selectedPerson = PersonModel()
init {
// Add some test persons for the demo
persons.add(Person(42, "<NAME>", listOf(PhoneNumber("47", "33349700"), PhoneNumber("47", "333943222"))))
persons.add(Person(43, "<NAME>", listOf(PhoneNumber("1", "312 213 21"))))
}
}
| 0
|
Kotlin
|
0
| 0
|
1e499faaca5762312aaad18668f8d04605f890a5
| 720
|
tornadofx-samples
|
Apache License 2.0
|
First Departament/Object Oriented Programming/src/Person.kt
|
Itzdan0ul
| 759,624,005
| false
|
{"Kotlin": 10516}
|
open class Person(name: String, lastname: String, gender: String, height: Float) {
var name: String = name
var lastname: String = lastname
var gender: String = gender
var height: Float = height
}
| 0
|
Kotlin
|
0
| 0
|
3fada7bbc680c658b55c0a95441ab6f229e372aa
| 212
|
mobile-programming
|
MIT License
|
src/main/kotlin/com/we2cat/utils/StringUtils.kt
|
ErosHel
| 335,270,211
| false
| null |
package com.we2cat.utils
/**
* Created by hel on 2020/12/21 14:46
*/
/**
* 将大写字母根据指定分隔符转换
*/
fun parseAssignByUppercase(text: String, assign: Char): String =
StringBuilder().let { sb ->
text.forEachIndexed { index, c ->
when {
index == 0 -> {
sb.append(c.lowercase())
}
c.code in 65..90 -> sb.append("${assign}${c + 32}")
else -> sb.append(c)
}
}
sb.toString()
}
/**
* 根据指定分隔符转换为大写
*/
fun parseUppercaseByAssign(text: String, assign: Char): String =
StringBuilder().let { sb ->
var i = 0
while (i < text.length) {
if (text[i].code in 65..90)
return@let text.lowercase()
if (text[i] == assign) {
val c = text[++i]
if (c.code in 97..122)
sb.append(c - 32)
else sb.append(c)
} else sb.append(text[i])
i++
}
sb.toString()
}
/**
* 拼接字符串
*/
fun join(vararg str: String): String {
val sb = StringBuilder()
str.forEach { sb.append(it) }
return sb.toString()
}
| 1
|
Kotlin
|
0
| 7
|
64a56dfe47d6dc2f1a4c1652e3d889d7a69c9d06
| 1,186
|
we2cat
|
Apache License 2.0
|
ont/src/main/java/at/rtr/rmbt/android/ui/activity/MeasurementActivity.kt
|
specure
| 436,159,986
| false
| null |
/*
*
* 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 at.rtr.rmbt.android.ui.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.WindowManager
import androidx.core.content.res.ResourcesCompat
import at.rtr.rmbt.android.R
import at.rtr.rmbt.android.databinding.ActivityMeasurementBinding
import at.rtr.rmbt.android.di.viewModelLazy
import at.rtr.rmbt.android.ui.dialog.SimpleDialog
import at.rtr.rmbt.android.ui.fragment.BasicResultFragment
import at.rtr.rmbt.android.ui.fragment.BasicResultFragment.DataLoadedListener
import at.rtr.rmbt.android.ui.fragment.SimpleResultsListFragment
import at.specure.test.TestUuidType
import at.rtr.rmbt.android.util.listen
import at.rtr.rmbt.android.viewmodel.MeasurementViewModel
import at.specure.data.entity.LoopModeRecord
import at.specure.data.entity.LoopModeState
import at.specure.info.TransportType
import at.specure.location.LocationState
import at.specure.measurement.MeasurementState
import timber.log.Timber
private const val CODE_CANCEL = 0
private const val CODE_ERROR = 1
class MeasurementActivity : BaseActivity(), SimpleDialog.Callback {
private val viewModel: MeasurementViewModel by viewModelLazy()
private lateinit var binding: ActivityMeasurementBinding
private var resultFragment: BasicResultFragment? = null
var loopMedianValuesReloadNeeded = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMeasurementBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.state = viewModel.state
viewModel.connectivityInfoLiveData.listen(this) {
val imageDrawableId = when (it?.transportType) {
TransportType.WIFI -> R.drawable.image_home_wifi
TransportType.CELLULAR -> R.drawable.image_home_cellular
TransportType.ETHERNET -> R.drawable.image_home_ethernet
else -> R.drawable.image_home
}
binding.image.setImageDrawable(
ResourcesCompat.getDrawable(resources, imageDrawableId, applicationContext.theme)
)
}
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
binding.buttonCancel.setOnClickListener { onCrossIconClicked() }
viewModel.measurementFinishLiveData.listen(this) {
Timber.d("MeasurementViewModel finished activity = listened $it")
finishActivity(it)
}
viewModel.measurementCancelledLiveData.listen(this) {
Timber.d("MeasurementViewModel cancelled activity = listened $it")
cancelMeasurement()
}
viewModel.measurementErrorLiveData.listen(this) {
SimpleDialog.Builder()
.messageText(R.string.test_dialog_error_text)
.positiveText(R.string.input_setting_dialog_ok)
.cancelable(false)
.show(supportFragmentManager, CODE_ERROR)
}
viewModel.downloadGraphSource.listen(this) {
if (viewModel.state.measurementState.get() == MeasurementState.DOWNLOAD) {
binding.speedLine.addGraphItems(it)
}
}
viewModel.uploadGraphSource.listen(this) {
if (viewModel.state.measurementState.get() == MeasurementState.UPLOAD) {
binding.speedLine.addGraphItems(it)
}
}
viewModel.activeNetworkLiveData.listen(this) {
if (it != null) {
viewModel.state.networkInfo.set(it)
viewModel.state.isConnected.set(true)
} else {
viewModel.state.networkInfo.set(null)
viewModel.state.isConnected.set(false)
}
}
viewModel.qosProgressLiveData.listen(this) {
// todo qos progress
// binding.measurementBottomView?.qosProgressContainer?.update(it)
}
viewModel.loopUuidLiveData.listen(this) { loopUUID ->
if (loopUUID != null) {
viewModel.loopProgressLiveData.observe(this@MeasurementActivity) { loopRecord ->
onLoopRecordChanged(loopRecord)
}
}
}
viewModel.timeToNextTestElapsedLiveData.listen(this) {
binding.blockLoopWaiting.textNextTime.text = it
}
viewModel.locationStateLiveData.listen(this) {
viewModel.state.gpsEnabled.set(it == LocationState.ENABLED)
}
viewModel.resultWaitingToBeSentLiveData.listen(this) {
if (!it) {
showBasicResultsFragment()
}
}
Timber.d("Measurement state loop create: ${viewModel.state.measurementState.get()?.name}")
viewModel.state.loopModeRecord.get()?.testsPerformed?.let { viewModel.state.setLoopProgress(it, viewModel.config.loopModeNumberOfTests) }
// viewModel.qosProgressLiveData.value?.let { binding.measurementBottomView?.qosProgressContainer?.update(it) }
}
private fun finishActivity(measurementFinished: Boolean) {
if (measurementFinished) {
if (viewModel.state.isLoopModeActive.get()) {
if (viewModel.state.loopModeRecord.get()?.status == LoopModeState.FINISHED || viewModel.state.loopModeRecord.get()?.status == LoopModeState.CANCELLED) {
finish()
LoopFinishedActivity.start(this)
}
} else {
finish()
viewModel.testUUID?.let {
if (viewModel.state.measurementState.get() == MeasurementState.FINISH)
ResultsActivity.start(this, it, ResultsActivity.ReturnPoint.HOME)
}
}
}
}
private fun cancelMeasurement() {
if (viewModel.state.isLoopModeActive.get() && (viewModel.state.loopModeRecord.get()?.status == LoopModeState.FINISHED || viewModel.state.loopModeRecord.get()?.status == LoopModeState.CANCELLED)) {
LoopFinishedActivity.start(this)
} else {
finishAffinity()
HomeActivity.startWithFragment(
this,
HomeActivity.Companion.HomeNavigationTarget.HOME_FRAGMENT_TO_SHOW
)
}
}
private fun onLoopRecordChanged(loopRecord: LoopModeRecord?) {
Timber.d(
"TestPerformed: ${loopRecord?.testsPerformed} \nloop mode status: ${loopRecord?.status} \nLoop local uuid: ${loopRecord?.localUuid}\nLoop remote uuid: ${loopRecord?.uuid}\nviewModel: ${viewModel.state.measurementState.get()}"
)
Timber.d("local loop UUID to read loop data: ${viewModel.loopUuidLiveData.value}")
viewModel.state.setLoopRecord(loopRecord)
loopRecord?.testsPerformed?.let { testsPerformed ->
viewModel.state.setLoopProgress(
testsPerformed,
viewModel.config.loopModeNumberOfTests
)
}
binding.blockLoopWaiting.textNextDistance.text = viewModel.state.loopNextTestDistanceMeters.get()
loopRecord?.status?.let { status ->
when (status) {
LoopModeState.IDLE -> {
showBasicResultsFragment()
}
LoopModeState.RUNNING -> {
resultFragment?.let { supportFragmentManager.beginTransaction().remove(resultFragment!!).commitNow() }
resultFragment = null
}
else -> {
} // do nothing
}
}
if (loopRecord?.testsPerformed != null && loopRecord.testsPerformed >= 2 && loopMedianValuesReloadNeeded) {
Timber.d("Loading median values on Loop record changed")
loopMedianValuesReloadNeeded = false
viewModel.initializeLoopData(loopRecord.localUuid)
val loopUUID = viewModel.state.loopModeRecord.get()?.uuid
Timber.d("Loop UUID to load median values (already loaded): $loopUUID")
loopUUID?.let {
viewModel.loadMedianValues(it, this)
if (!viewModel.medianLiveData.hasObservers()) {
viewModel.medianLiveData.observe(this) { medians ->
if (medians != null) {
viewModel.state.setMedianValues(medians)
Timber.d("median values: $medians")
}
}
}
}
}
if (loopRecord?.status == LoopModeState.FINISHED || loopRecord?.status == LoopModeState.CANCELLED) {
finishActivity(true)
}
}
private fun showBasicResultsFragment() {
Timber.d("history test result Show fragment: ${viewModel.state.loopModeRecord.get()?.status == LoopModeState.IDLE}, ${resultFragment == null}, ${viewModel.resultWaitingToBeSentLiveData.value == false}")
if (viewModel.state.loopModeRecord.get()?.status == LoopModeState.IDLE && resultFragment == null && viewModel.resultWaitingToBeSentLiveData.value == false) {
viewModel.state.loopModeRecord.get()?.uuid?.let {
resultFragment = BasicResultFragment.newInstance(it, TestUuidType.LOOP_UUID, true)
(resultFragment as BasicResultFragment).onDataLoadedListener = object : DataLoadedListener {
override fun onDataLoaded() {
val resultListFragment = SimpleResultsListFragment.newInstance(it, false)
supportFragmentManager.beginTransaction()
.replace(binding.resultListContainer.id, resultListFragment as SimpleResultsListFragment).commitNow()
}
}
supportFragmentManager.beginTransaction().replace(binding.resultContainer.id, resultFragment as BasicResultFragment).commitNow()
}
}
}
override fun onDialogPositiveClicked(code: Int) {
if (code == CODE_CANCEL) {
viewModel.cancelMeasurement()
}
// finish activity for in both cases
finish()
}
override fun onDialogNegativeClicked(code: Int) {
// Do nothing
}
override fun onStart() {
super.onStart()
Timber.d("MeasurementViewModel START")
viewModel.attach(this)
}
override fun onStop() {
super.onStop()
try {
viewModel.medianLiveData.removeObservers(this)
} catch (e: UninitializedPropertyAccessException) {
Timber.w(e.localizedMessage)
}
viewModel.detach(this)
}
override fun onBackPressed() {
onCrossIconClicked()
}
override fun onResume() {
super.onResume()
loopMedianValuesReloadNeeded = true
viewModel.loadMedianValues(viewModel.state.loopModeRecord.get()?.uuid, this)
Timber.d("Loop median uuid: ${viewModel.state.loopModeRecord.get()?.uuid}")
Timber.d("MeasurementViewModel RESUME")
}
private fun onCrossIconClicked() {
SimpleDialog.Builder()
.messageText(R.string.title_cancel_measurement)
.positiveText(R.string.text_cancel_measurement)
.negativeText(R.string.text_continue_measurement)
.cancelable(false)
.show(supportFragmentManager, CODE_CANCEL)
}
companion object {
fun start(context: Context) {
val intent = Intent(context, MeasurementActivity::class.java)
context.startActivity(intent)
}
}
}
| 0
|
Kotlin
|
1
| 0
|
20a185fb151138ade36b93a297576d07b32f7f66
| 12,155
|
ont-android-kotlin
|
Apache License 2.0
|
app/src/main/java/ru/ozh/android/recycler/decorator/sample/list/decor/ParallaxDecor.kt
|
ozh-dev
| 193,144,003
| false
|
{"Kotlin": 84727}
|
package ru.ozh.android.recycler.decorator.sample.list.decor
import android.content.Context
import android.graphics.*
import android.view.View
import androidx.annotation.DrawableRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.graphics.drawable.toBitmap
import androidx.recyclerview.widget.RecyclerView
import ru.ozh.android.recycler.decorator.lib.Decorator
class ParallaxDecor(
context: Context,
@DrawableRes resId: Int
) : Decorator.ViewHolderDecor {
private val image: Bitmap? = AppCompatResources.getDrawable(context, resId)?.toBitmap()
override fun draw(
canvas: Canvas,
view: View,
recyclerView: RecyclerView,
state: RecyclerView.State
) {
val offset = view.top / 3
image?.let { btm ->
canvas.drawBitmap(
btm,
Rect(0, offset, btm.width, view.height + offset),
Rect(view.left, view.top, view.right, view.bottom),
null
)
}
}
}
| 1
|
Kotlin
|
19
| 92
|
c3718d6a58a5712933d4e92ce333b4fb57e262b2
| 1,037
|
recycler-decorator-library-sample
|
Apache License 2.0
|
shared/src/commonMain/kotlin/App.kt
|
mathieuTrunet
| 707,676,776
| false
|
{"Kotlin": 20830, "Swift": 580, "Shell": 228}
|
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import views.IngredientSelectionScreen
@Composable
internal fun App() {
MaterialTheme {
IngredientSelectionScreen()
}
}
| 0
|
Kotlin
|
0
| 0
|
0abc808eec127c8c5bffa49365e2e509645f6aa4
| 310
|
tp-expertise-mobile
|
Apache License 2.0
|
src/test/kotlin/g1801_1900/s1814_count_nice_pairs_in_an_array/SolutionTest.kt
|
javadev
| 190,711,550
| false
|
{"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g1801_1900.s1814_count_nice_pairs_in_an_array
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun countNicePairs() {
assertThat(Solution().countNicePairs(intArrayOf(42, 11, 1, 97)), equalTo(2))
}
@Test
fun countNicePairs2() {
assertThat(Solution().countNicePairs(intArrayOf(13, 10, 35, 24, 76)), equalTo(4))
}
}
| 0
|
Kotlin
|
20
| 43
|
e8b08d4a512f037e40e358b078c0a091e691d88f
| 471
|
LeetCode-in-Kotlin
|
MIT License
|
project/module-runtime/src/main/kotlin/net/artemisia/runtime/compiler/objects/module/VisitorObject.kt
|
TheFloodDragon
| 729,364,851
| false
|
{"Kotlin": 69253}
|
package net.artemisia.runtime.compiler.objects.module
import net.artemisia.runtime.compiler.Object
class VisitorObject(val type: VisitorType, val obj: VisitObject, val index: Int) : Object() {
enum class VisitorType(val i: Byte) {
PUBLIC(0x01),
PRIVATE(0x02),
PROTECTED(0x03),
ALREADY(0x04)
}
enum class VisitObject(val i: Byte) {
VARIABLE(0x11),
FUNCTION(0x02),
CLASS(0x03)
}
override fun toByte(): ByteArray {
val array = createArray()
array.add(type.i)
array.add(obj.i)
array.add(index.toByte())
return array.toByteArray()
}
}
| 0
|
Kotlin
|
0
| 1
|
507c4b14fe8ff8dde024b6c9327486fb0effc25e
| 655
|
Script-Artemisia
|
MIT License
|
app/src/main/java/com/akhbulatov/wordkeeper/presentation/ui/global/base/BaseFragment.kt
|
akhbulatov
| 65,332,258
| false
|
{"Kotlin": 94207}
|
package com.akhbulatov.wordkeeper.presentation.ui.global.base
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
abstract class BaseFragment(@LayoutRes contentLayoutId: Int) : Fragment(contentLayoutId)
| 0
|
Kotlin
|
0
| 2
|
5706a65649e5c114f6b18f93b0c582ab1594cae3
| 228
|
wordkeeper
|
Apache License 2.0
|
shared/repositories/features/movies/sources/src/commonMain/kotlin/com/santukis/repositories/movies/sources/SaveMovieDetailDataSource.kt
|
santukis
| 541,433,358
| false
|
{"Kotlin": 208617, "Swift": 9316, "Ruby": 1968}
|
package com.santukis.repositories.movies.sources
import com.santukis.entities.movies.Movie
interface SaveMovieDetailDataSource {
suspend fun saveMovie(movie: Movie): Movie
}
| 0
|
Kotlin
|
0
| 2
|
89d549ffde38f09bacec84a09c3eba56a45830d0
| 180
|
CleanArchitectureKMM
|
Apache License 2.0
|
firefly-net/src/main/kotlin/com/fireflysource/net/http/server/impl/AsyncHttpServerConnectionListener.kt
|
hypercube1024
| 3,458,429
| false
|
{"PowerShell": 2, "Maven POM": 8, "Ignore List": 3, "Text": 3, "YAML": 2, "Markdown": 1, "Java": 498, "Kotlin": 183, "INI": 3, "Shell": 2, "XML": 6, "CMake": 1, "C++": 3, "C": 1, "HTML": 2}
|
package com.fireflysource.net.http.server.impl
import com.fireflysource.common.annotation.NoArg
import com.fireflysource.common.concurrent.exceptionallyCompose
import com.fireflysource.common.sys.Result
import com.fireflysource.net.http.common.codec.URIUtils
import com.fireflysource.net.http.common.exception.BadMessageException
import com.fireflysource.net.http.common.model.HttpStatus
import com.fireflysource.net.http.server.HttpServerConnection
import com.fireflysource.net.http.server.HttpServerRequest
import com.fireflysource.net.http.server.RouterManager
import com.fireflysource.net.http.server.RoutingContext
import com.fireflysource.net.http.server.impl.router.AsyncRouter
import com.fireflysource.net.http.server.impl.router.AsyncRoutingContext
import com.fireflysource.net.tcp.TcpConnection
import com.fireflysource.net.websocket.server.WebSocketManager
import com.fireflysource.net.websocket.server.WebSocketServerConnectionHandler
import java.net.InetSocketAddress
import java.util.concurrent.CompletableFuture
import java.util.function.BiFunction
import java.util.function.Function
/**
* @author <NAME>
*/
@NoArg
class AsyncHttpServerConnectionListener(
private val routerManager: RouterManager,
private val onHeaderComplete: Function<RoutingContext, CompletableFuture<Void>>,
private val onException: BiFunction<RoutingContext?, Throwable, CompletableFuture<Void>>,
private val onRouterNotFound: Function<RoutingContext, CompletableFuture<Void>>,
private val onRouterComplete: Function<RoutingContext, CompletableFuture<Void>>,
private val webSocketManager: WebSocketManager,
private val onAcceptHttpTunnel: Function<HttpServerRequest, CompletableFuture<Boolean>>,
private val onAcceptHttpTunnelHandshakeResponse: Function<RoutingContext, CompletableFuture<Void>>,
private val onRefuseHttpTunnelHandshakeResponse: Function<RoutingContext, CompletableFuture<Void>>,
private val onHttpTunnelHandshakeComplete: BiFunction<TcpConnection, InetSocketAddress, CompletableFuture<Void>>
) : HttpServerConnection.Listener.Adapter() {
override fun onHeaderComplete(ctx: RoutingContext): CompletableFuture<Void> {
return onHeaderComplete.apply(ctx)
}
override fun onHttpRequestComplete(ctx: RoutingContext): CompletableFuture<Void> {
if (ctx.response.isCommitted) return Result.DONE
val results = routerManager.findRouters(ctx)
val asyncCtx = ctx as AsyncRoutingContext
val iterator = results.iterator()
return if (iterator.hasNext()) {
val result = iterator.next()
asyncCtx.routerMatchResult = result
asyncCtx.routerIterator = iterator
(result.router as AsyncRouter).getHandler()
.apply(ctx)
.thenCompose { handleRouterComplete(ctx) }
.exceptionallyCompose { handleRouterException(ctx, it) }
} else handleRouterNotFound(ctx)
}
override fun onException(ctx: RoutingContext?, e: Throwable): CompletableFuture<Void> {
return onException.apply(ctx, e)
}
override fun onWebSocketHandshake(ctx: RoutingContext): CompletableFuture<WebSocketServerConnectionHandler> {
val path = URIUtils.canonicalPath(ctx.uri.decodedPath)
val handler = webSocketManager.findWebSocketHandler(path)
val future = CompletableFuture<WebSocketServerConnectionHandler>()
if (handler != null) {
future.complete(handler)
} else {
future.completeExceptionally(
BadMessageException(
HttpStatus.BAD_REQUEST_400,
"The websocket handler is not register"
)
)
}
return future
}
override fun onAcceptHttpTunnel(request: HttpServerRequest): CompletableFuture<Boolean> {
return onAcceptHttpTunnel.apply(request)
}
override fun onAcceptHttpTunnelHandshakeResponse(context: RoutingContext): CompletableFuture<Void> {
return onAcceptHttpTunnelHandshakeResponse.apply(context)
}
override fun onRefuseHttpTunnelHandshakeResponse(context: RoutingContext): CompletableFuture<Void> {
return onRefuseHttpTunnelHandshakeResponse.apply(context)
}
override fun onHttpTunnelHandshakeComplete(connection: TcpConnection, address: InetSocketAddress): CompletableFuture<Void> {
return onHttpTunnelHandshakeComplete.apply(connection, address)
}
private fun handleRouterNotFound(ctx: RoutingContext): CompletableFuture<Void> {
return onRouterNotFound.apply(ctx)
}
private fun handleRouterException(ctx: RoutingContext, e: Throwable): CompletableFuture<Void> {
return onException.apply(ctx, e)
}
private fun handleRouterComplete(ctx: RoutingContext): CompletableFuture<Void> {
return onRouterComplete.apply(ctx)
}
}
| 1
|
Java
|
112
| 295
|
e4774ba7726a08afbe97a7ee8d7343bc9df671de
| 4,884
|
firefly
|
Apache License 2.0
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/util/PushButton.kt
|
titanium-knights
| 497,469,289
| false
|
{"Java": 288466, "Kotlin": 2495}
|
package org.firstinspires.ftc.teamcode.util
import org.firstinspires.ftc.teamcode.teleop.PassdionComponent
import org.firstinspires.ftc.teamcode.teleop.PassdionOpMode
class PushButton(val readState: () -> Boolean): PassdionComponent {
var previousState: Boolean = false
var currentState: Boolean = readState()
val isPressed: Boolean get() {
return currentState && !previousState
}
fun update() {
previousState = currentState
currentState = readState()
}
override fun init(opMode: PassdionOpMode) {}
override fun initLoop(opMode: PassdionOpMode) {}
override fun start(opMode: PassdionOpMode) {}
override fun update(opMode: PassdionOpMode) {
update()
}
override fun cleanup(opMode: PassdionOpMode) {}
}
class ToggleButton(readState: () -> Boolean): PassdionComponent {
val pushButton = PushButton(readState)
var isActive = false
fun update() {
if (pushButton.isPressed) {
isActive = !isActive
}
pushButton.update()
}
override fun init(opMode: PassdionOpMode) {}
override fun initLoop(opMode: PassdionOpMode) {}
override fun start(opMode: PassdionOpMode) {}
override fun update(opMode: PassdionOpMode) {
update()
}
override fun cleanup(opMode: PassdionOpMode) {}
}
| 1
| null |
1
| 1
|
a570b84a21c1ef122404c5d2665b3bea30936229
| 1,334
|
team-a-2021-2022
|
MIT License
|
data/local/src/main/java/com/hari/tmdb/local/mappers/mappers.kt
|
HariKulhari06
| 255,623,659
| false
|
{"Gradle Kotlin DSL": 4, "Java Properties": 2, "Gradle": 18, "Shell": 1, "Text": 1, "Ignore List": 14, "Batchfile": 1, "Markdown": 1, "INI": 13, "Proguard": 14, "Kotlin": 256, "XML": 175, "Java": 5, "JSON": 3}
|
package com.hari.tmdb.local.mappers
import com.hari.tmdb.model.mapper.IndexedMapper
import com.hari.tmdb.model.mapper.Mapper
import com.uwetrottmann.tmdb2.entities.BaseTvShow
import com.uwetrottmann.tmdb2.entities.TvShowResultsPage
fun <F, T> Mapper<F, T>.forLists(): suspend (List<F>) -> List<T> {
return { list -> list.map { item -> map(item) } }
}
fun <F, T> IndexedMapper<F, T>.forLists(): suspend (List<F>) -> List<T> {
return { list -> list.mapIndexed { index, item -> map(index, item) } }
}
fun <F, T1, T2> pairMapperOf(
firstMapper: Mapper<F, T1>,
secondMapper: Mapper<F, T2>
): suspend (List<F>) -> List<Pair<T1, T2>> {
return { from ->
from.map { firstMapper.map(it) to secondMapper.map(it) }
}
}
fun <F, T1, T2> pairMapperOf(
firstMapper: Mapper<F, T1>,
secondMapper: IndexedMapper<F, T2>
): suspend (List<F>) -> List<Pair<T1, T2>> {
return { from ->
from.mapIndexed { index, value ->
firstMapper.map(value) to secondMapper.map(index, value)
}
}
}
fun <F, T> Mapper<F, T>.toLambda(): suspend (F) -> T {
return { map(it) }
}
fun <T> unwrapTmdbShowResults(
f: suspend (List<BaseTvShow>) -> List<T>
): suspend (TvShowResultsPage) -> List<T> = {
f(it.results ?: emptyList())
}
| 0
|
Kotlin
|
1
| 5
|
c3b94cc6e65882b23e904ba479466a6897b920cc
| 1,279
|
tmdb_app
|
MIT License
|
examples/KExasolExample.kt
|
badoo
| 307,729,424
| false
| null |
abstract class KExasolExample {
val credentials: KExasolTestCredentials
init {
credentials = KExasolTestCredentials(
dsn = System.getenv("EXAHOST") ?: "localhost",
user = System.getenv("EXAUID") ?: "SYS",
password = System.getenv("EXAPWD") ?: "<PASSWORD>",
schema = System.getenv("EXASCHEMA") ?: "KEXASOL_TEST"
)
}
data class KExasolTestCredentials(
val dsn: String,
val user: String,
val password: String,
val schema: String
)
}
| 0
|
Kotlin
|
0
| 9
|
fa958c6a751f01eb93426b7be2c3b4598467f58c
| 549
|
kexasol
|
Apache License 2.0
|
app/src/main/java/com/ibtikar/mvvm_starter_koin_coroutines/ui/base/ViewState.kt
|
KhaledSherifSayed
| 375,848,364
| false
| null |
package com.ibtikar.mvvm_starter_koin_coroutines.ui.base
import com.ibtikar.mvvm_starter_koin_coroutines.utils.erros.ApplicationException
/**
* Created by Meslmawy on 6/10/2021
*/
abstract class ViewState {
object Initial : ViewState()
data class Loading(val loading: Boolean) : ViewState()
data class Error(val exception: ApplicationException) : ViewState()
abstract class Loaded<out T>(val r: T) : ViewState()
object Empty : ViewState()
}
| 0
|
Kotlin
|
0
| 0
|
701fcea68ed7da29416c850495b632751ed31e53
| 465
|
NY-Times-Popular-Articles
|
The Unlicense
|
app/src/main/java/com/devdaniel/marvelapp/domain/usecase/CharactersUC.kt
|
Cerverussz
| 534,818,141
| false
|
{"Kotlin": 112667}
|
package com.devdaniel.marvelapp.domain.usecase
import com.devdaniel.marvelapp.domain.common.Result
import com.devdaniel.marvelapp.domain.model.Character
import com.devdaniel.marvelapp.domain.repository.CharactersRepository
import kotlinx.coroutines.flow.Flow
class CharactersUC(private val charactersRepository: CharactersRepository) {
suspend fun getRemoteCharacters(): Result<List<Character>> =
charactersRepository.getCharacters()
fun getLocalCharacters(): Flow<List<Character>> = charactersRepository.getLocalCharacters()
}
| 0
|
Kotlin
|
1
| 0
|
1b0ca033cd11b712a9b8f3080c0731fcd9622832
| 548
|
MarvelApp
|
MIT License
|
plugin/src/main/kotlin/com/github/bric3/excalidraw/actions/OpenDeveloperToolsAction.kt
|
bric3
| 376,308,974
| false
|
{"Kotlin": 81246, "TypeScript": 14127, "JavaScript": 1128, "HTML": 838, "CSS": 648}
|
package com.github.bric3.excalidraw.actions
import com.github.bric3.excalidraw.debugMode
import com.github.bric3.excalidraw.findEditor
import com.intellij.ide.actions.CloseAction
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.util.Key
class OpenDeveloperToolsAction : DumbAwareAction() {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = debugMode
}
override fun actionPerformed(e: AnActionEvent) {
// Fails if called a second time
// https://youtrack.jetbrains.com/issue/IDEA-285655/Selenium-Get-com.intellij.util.IncorrectOperationException-on-reopen-Developer-Tools-in-PageObjectGenerator
val editor = e.findEditor() ?: return
if (HAS_OPEN_DEVTOOLS.get(editor) == true) {
// Workaround for IDEA-285655 to try recycling editor
MessageDialogBuilder.okCancel(
"Cannot reopen devtools, need to re-open this file (due to IDEA-285655)",
"Do you want to close this editor?"
).let {
if (it.ask(editor.component)) {
e.getData(CloseAction.CloseTarget.KEY)?.close()
}
}
} else {
editor.viewController.openDevTools()
HAS_OPEN_DEVTOOLS.set(editor, true)
}
}
companion object {
val HAS_OPEN_DEVTOOLS = Key<Boolean>("excalidraw.HAS_OPEN_DEVTOOLS")
}
}
| 26
|
Kotlin
|
12
| 78
|
171023fc7a3c4b502857bc83f7f7cbf75cc3ba8c
| 1,682
|
excalidraw-jetbrains-plugin
|
MIT License
|
src/main/kotlin/org/move/lang/core/psi/ext/MvLitExpr.kt
|
pontem-network
| 279,299,159
| false
| null |
package org.move.lang.core.psi.ext
import com.intellij.psi.PsiElement
import org.move.lang.MvElementTypes.HEX_INTEGER_LITERAL
import org.move.lang.core.psi.MvLitExpr
val MvLitExpr.hexIntegerLiteral: PsiElement?
get() =
this.findFirstChildByType(HEX_INTEGER_LITERAL)
| 8
|
Kotlin
|
15
| 51
|
dbf98888e0fc900a5bcfce8c8e7834ad9d34dc4b
| 280
|
intellij-move
|
MIT License
|
demo/composeApp/src/iosMain/kotlin/ovh/plrapps/mapcompose/demo/ui/screens/RotationDemo.ios.kt
|
p-lr
| 777,977,251
| false
|
{"Kotlin": 270653}
|
package ovh.plrapps.mapcompose.demo.ui.screens
import androidx.compose.runtime.Composable
import cafe.adriel.voyager.core.model.rememberScreenModel
import cafe.adriel.voyager.core.screen.Screen
import ovh.plrapps.mapcompose.demo.viewmodels.RotationVM
actual object RotationDemo : Screen {
@Composable
override fun Content() {
val screenModel = rememberScreenModel { RotationVM() }
RotationCommonUi(screenModel)
}
}
| 8
|
Kotlin
|
4
| 10
|
62a0975976f250208abb62e5add7736eea538bd0
| 445
|
MapComposeMP
|
Apache License 2.0
|
app/src/main/java/com/breezeiksindustries/features/location/model/ShopDurationResponse.kt
|
DebashisINT
| 863,536,151
| false
|
{"Kotlin": 15890094, "Java": 1030472}
|
package com.breezeiksindustries.features.location.model
import com.breezeiksindustries.base.BaseResponse
/**
* Created by Pratishruti on 28-11-2017.
*/
class ShopDurationResponse:BaseResponse()
| 0
|
Kotlin
|
0
| 0
|
77cc3b80d20adbe55363e1825240b8e2c6a44cf3
| 197
|
IKSIndustries
|
Apache License 2.0
|
src/serverMain/kotlin/money/tegro/market/contract/op/collection/ChangeOwnerOp.kt
|
TegroTON
| 491,519,429
| false
|
{"Kotlin": 198445, "HTML": 3914, "JavaScript": 2388, "Dockerfile": 242}
|
package money.tegro.market.contract.op.collection
import org.ton.block.MsgAddress
import org.ton.cell.CellBuilder
import org.ton.cell.CellSlice
import org.ton.tlb.TlbCodec
import org.ton.tlb.TlbConstructor
import org.ton.tlb.loadTlb
import org.ton.tlb.storeTlb
data class ChangeOwnerOp(
val query_id: ULong,
val new_owner: MsgAddress
) : CollectionOp {
companion object : TlbCodec<ChangeOwnerOp> by ChangeOwnerOpConstructor {
@JvmStatic
fun tlbCodec(): TlbConstructor<ChangeOwnerOp> = ChangeOwnerOpConstructor
}
}
private object ChangeOwnerOpConstructor : TlbConstructor<ChangeOwnerOp>(
schema = "change_owner#00000003 query_id:uint64 owner:MsgAddress = InternalMsgBody;"
) {
override fun storeTlb(cellBuilder: CellBuilder, value: ChangeOwnerOp) {
cellBuilder.apply {
storeUInt64(value.query_id)
storeTlb(MsgAddress, value.new_owner)
}
}
override fun loadTlb(cellSlice: CellSlice): ChangeOwnerOp = cellSlice.run {
ChangeOwnerOp(
query_id = loadUInt64(),
new_owner = loadTlb(MsgAddress),
)
}
}
| 11
|
Kotlin
|
4
| 0
|
bd82acf423a4d4e1a00c3eac6347aa7cf18eee5f
| 1,129
|
TON-Marketplace-NFT-All
|
MIT License
|
appcues/src/main/java/com/appcues/ui/ExperienceRenderer.kt
|
appcues
| 413,524,565
| false
| null |
package com.appcues.ui
import com.appcues.AppcuesConfig
import com.appcues.SessionMonitor
import com.appcues.analytics.AnalyticsTracker
import com.appcues.analytics.ExperienceLifecycleTracker
import com.appcues.analytics.track
import com.appcues.data.AppcuesRepository
import com.appcues.data.model.Experience
import com.appcues.data.model.ExperiencePriority.NORMAL
import com.appcues.data.model.ExperienceTrigger
import com.appcues.data.model.RenderContext
import com.appcues.statemachine.Action.EndExperience
import com.appcues.statemachine.Action.StartExperience
import com.appcues.statemachine.Action.StartStep
import com.appcues.statemachine.Error
import com.appcues.statemachine.Error.RenderContextNotActive
import com.appcues.statemachine.State
import com.appcues.statemachine.State.Idling
import com.appcues.statemachine.StateMachine
import com.appcues.statemachine.StepReference
import com.appcues.util.ResultOf
import com.appcues.util.ResultOf.Failure
import com.appcues.util.ResultOf.Success
import kotlinx.coroutines.flow.SharedFlow
import org.koin.core.component.KoinScopeComponent
import org.koin.core.component.get
import org.koin.core.component.inject
import org.koin.core.scope.Scope
internal class ExperienceRenderer(
override val scope: Scope,
) : KoinScopeComponent {
// lazy prop inject here to avoid circular dependency with AnalyticsTracker
// AnalyticsTracker > AnalyticsQueueProcessor > ExperienceRenderer(this) > AnalyticsTracker
private val repository by inject<AppcuesRepository>()
private val sessionMonitor by inject<SessionMonitor>()
private val config by inject<AppcuesConfig>()
private val analyticsTracker by inject<AnalyticsTracker>()
private val experienceTracker by inject<ExperienceLifecycleTracker>()
private val slots: HashMap<RenderContext, StateMachine> = hashMapOf()
fun getStateFlow(renderContext: RenderContext): SharedFlow<State>? {
return slots[renderContext]?.stateFlow
}
fun getState(renderContext: RenderContext): State? {
return slots[renderContext]?.state
}
/**
* returns true/false whether the experience is was started
*/
suspend fun show(experience: Experience): Boolean = with(experience) {
var canShow = config.interceptor?.canDisplayExperience(experience.id) ?: true
// if there is an active experiment, and we should not show this experience (control group), then
// track the analytics for experiment_entered, but ensure we exit early. This should be checked before
// we dismiss any current experience below.
if (experiment?.group == "control") {
analyticsTracker.track(experiment)
canShow = false
}
if (!canShow) return false
val stateMachine = slots.getOrCreateStateMachine(renderContext)
if (stateMachine.checkPriority(this)) {
return when (stateMachine.handleAction(EndExperience(markComplete = false, destroyed = false))) {
is Success -> show(this) // re-invoke show on the new experience now after dismiss
is Failure -> false // dismiss failed - can't continue
}
}
// track an experiment_entered analytic, if exists, since we know it is not in the control group at this point
experiment?.let { analyticsTracker.track(it) }
when (stateMachine.handleAction(StartExperience(this))) {
is Success -> true
is Failure -> false
}
}
private fun HashMap<RenderContext, StateMachine>.getOrCreateStateMachine(renderContext: RenderContext): StateMachine {
return get(renderContext) ?: run {
get<StateMachine>()
.also { put(renderContext, it) }
.also { experienceTracker.start(it) }
}
}
private fun StateMachine.checkPriority(newExperience: Experience): Boolean {
// "event_trigger" or "forced" experience priority is NORMAL, "screen_view" is low -
// if an experience is currently showing and the new experience coming in is normal priority
// then it replaces whatever is currently showing - i.e. an "event_trigger" experience will
// supersede a "screen_view" triggered experience - per Appcues standard behavior
return newExperience.priority == NORMAL && state != Idling
}
suspend fun show(qualifiedExperiences: List<Experience>): Boolean {
if (qualifiedExperiences.isEmpty()) {
// If given an empty list of qualified experiences, complete with a success because this function has completed without error.
// This function only recurses on a non-empty case, so this block only applies to the initial external call.
return true
}
val success = show(qualifiedExperiences.first())
if (!success) {
val remainingExperiences = qualifiedExperiences.drop(1)
if (remainingExperiences.isNotEmpty()) {
// fallback logic - try the next remaining experience, if available
return show(remainingExperiences)
}
}
return success
}
suspend fun show(experienceId: String, trigger: ExperienceTrigger): Boolean {
if (!sessionMonitor.checkSession("cannot show Experience $experienceId")) return false
repository.getExperienceContent(experienceId, trigger)?.let {
return show(it)
}
return false
}
suspend fun show(renderContext: RenderContext, stepReference: StepReference) {
slots[renderContext]?.handleAction(StartStep(stepReference))
}
suspend fun preview(experienceId: String): Boolean {
repository.getExperiencePreview(experienceId)?.let {
return show(it)
}
return false
}
fun stop() {
slots.values.forEach { it.stop() }
}
suspend fun dismiss(renderContext: RenderContext, markComplete: Boolean, destroyed: Boolean): ResultOf<State, Error> {
return slots[renderContext]?.handleAction(EndExperience(markComplete, destroyed)) ?: Failure(RenderContextNotActive(renderContext))
}
}
| 2
|
Kotlin
|
1
| 9
|
944511391b720bf387f86b795630b532b5e1e516
| 6,168
|
appcues-android-sdk
|
MIT License
|
appcues/src/main/java/com/appcues/ui/ExperienceRenderer.kt
|
appcues
| 413,524,565
| false
| null |
package com.appcues.ui
import com.appcues.AppcuesConfig
import com.appcues.SessionMonitor
import com.appcues.analytics.AnalyticsTracker
import com.appcues.analytics.ExperienceLifecycleTracker
import com.appcues.analytics.track
import com.appcues.data.AppcuesRepository
import com.appcues.data.model.Experience
import com.appcues.data.model.ExperiencePriority.NORMAL
import com.appcues.data.model.ExperienceTrigger
import com.appcues.data.model.RenderContext
import com.appcues.statemachine.Action.EndExperience
import com.appcues.statemachine.Action.StartExperience
import com.appcues.statemachine.Action.StartStep
import com.appcues.statemachine.Error
import com.appcues.statemachine.Error.RenderContextNotActive
import com.appcues.statemachine.State
import com.appcues.statemachine.State.Idling
import com.appcues.statemachine.StateMachine
import com.appcues.statemachine.StepReference
import com.appcues.util.ResultOf
import com.appcues.util.ResultOf.Failure
import com.appcues.util.ResultOf.Success
import kotlinx.coroutines.flow.SharedFlow
import org.koin.core.component.KoinScopeComponent
import org.koin.core.component.get
import org.koin.core.component.inject
import org.koin.core.scope.Scope
internal class ExperienceRenderer(
override val scope: Scope,
) : KoinScopeComponent {
// lazy prop inject here to avoid circular dependency with AnalyticsTracker
// AnalyticsTracker > AnalyticsQueueProcessor > ExperienceRenderer(this) > AnalyticsTracker
private val repository by inject<AppcuesRepository>()
private val sessionMonitor by inject<SessionMonitor>()
private val config by inject<AppcuesConfig>()
private val analyticsTracker by inject<AnalyticsTracker>()
private val experienceTracker by inject<ExperienceLifecycleTracker>()
private val slots: HashMap<RenderContext, StateMachine> = hashMapOf()
fun getStateFlow(renderContext: RenderContext): SharedFlow<State>? {
return slots[renderContext]?.stateFlow
}
fun getState(renderContext: RenderContext): State? {
return slots[renderContext]?.state
}
/**
* returns true/false whether the experience is was started
*/
suspend fun show(experience: Experience): Boolean = with(experience) {
var canShow = config.interceptor?.canDisplayExperience(experience.id) ?: true
// if there is an active experiment, and we should not show this experience (control group), then
// track the analytics for experiment_entered, but ensure we exit early. This should be checked before
// we dismiss any current experience below.
if (experiment?.group == "control") {
analyticsTracker.track(experiment)
canShow = false
}
if (!canShow) return false
val stateMachine = slots.getOrCreateStateMachine(renderContext)
if (stateMachine.checkPriority(this)) {
return when (stateMachine.handleAction(EndExperience(markComplete = false, destroyed = false))) {
is Success -> show(this) // re-invoke show on the new experience now after dismiss
is Failure -> false // dismiss failed - can't continue
}
}
// track an experiment_entered analytic, if exists, since we know it is not in the control group at this point
experiment?.let { analyticsTracker.track(it) }
when (stateMachine.handleAction(StartExperience(this))) {
is Success -> true
is Failure -> false
}
}
private fun HashMap<RenderContext, StateMachine>.getOrCreateStateMachine(renderContext: RenderContext): StateMachine {
return get(renderContext) ?: run {
get<StateMachine>()
.also { put(renderContext, it) }
.also { experienceTracker.start(it) }
}
}
private fun StateMachine.checkPriority(newExperience: Experience): Boolean {
// "event_trigger" or "forced" experience priority is NORMAL, "screen_view" is low -
// if an experience is currently showing and the new experience coming in is normal priority
// then it replaces whatever is currently showing - i.e. an "event_trigger" experience will
// supersede a "screen_view" triggered experience - per Appcues standard behavior
return newExperience.priority == NORMAL && state != Idling
}
suspend fun show(qualifiedExperiences: List<Experience>): Boolean {
if (qualifiedExperiences.isEmpty()) {
// If given an empty list of qualified experiences, complete with a success because this function has completed without error.
// This function only recurses on a non-empty case, so this block only applies to the initial external call.
return true
}
val success = show(qualifiedExperiences.first())
if (!success) {
val remainingExperiences = qualifiedExperiences.drop(1)
if (remainingExperiences.isNotEmpty()) {
// fallback logic - try the next remaining experience, if available
return show(remainingExperiences)
}
}
return success
}
suspend fun show(experienceId: String, trigger: ExperienceTrigger): Boolean {
if (!sessionMonitor.checkSession("cannot show Experience $experienceId")) return false
repository.getExperienceContent(experienceId, trigger)?.let {
return show(it)
}
return false
}
suspend fun show(renderContext: RenderContext, stepReference: StepReference) {
slots[renderContext]?.handleAction(StartStep(stepReference))
}
suspend fun preview(experienceId: String): Boolean {
repository.getExperiencePreview(experienceId)?.let {
return show(it)
}
return false
}
fun stop() {
slots.values.forEach { it.stop() }
}
suspend fun dismiss(renderContext: RenderContext, markComplete: Boolean, destroyed: Boolean): ResultOf<State, Error> {
return slots[renderContext]?.handleAction(EndExperience(markComplete, destroyed)) ?: Failure(RenderContextNotActive(renderContext))
}
}
| 2
|
Kotlin
|
1
| 9
|
944511391b720bf387f86b795630b532b5e1e516
| 6,168
|
appcues-android-sdk
|
MIT License
|
app/src/main/kotlin/com/polendina/knounce/presentation/flashcard/viewmodel/FlashCardViewModelMock.kt
|
xquilt
| 695,183,007
| false
|
{"Kotlin": 171841}
|
package com.polendina.knounce.presentation.flashcard.viewmodel
import android.os.CountDownTimer
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.polendina.knounce.data.database.Word
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
class FlashCardViewModelMock: FlashCardViewModel, ViewModel() {
private val _words: List<Word> = listOf("more", "gaben", "Wie lange whonst du", "ich", "hai", "kanka", "gestern", "gaben", "ich", "hai")
// .run { if (emptyWords) take(0) else this }
.map {Word(
title = it,
loaded = true
)
}
override val words: SnapshotStateList<Word> = mutableStateListOf()
fun insertWord(word: Word): Job = viewModelScope.launch { }
override fun loadWords(): Job = viewModelScope.launch {
viewModelScope.launch { loadWords() }
}
fun removeWord(wordTitle: String): Job = viewModelScope.launch { }
override var elapsedSeconds by mutableLongStateOf(listOf(0L, 2034L, 60234L, 4234L).random())
init {
object: CountDownTimer(30000, 1000) {
override fun onFinish() { }
override fun onTick(millisUntilFinished: Long) {
elapsedSeconds = millisUntilFinished / 1000
}
}.start()
}
}
| 0
|
Kotlin
|
0
| 0
|
9facf3d3770d2e98e942de0b6dbf35d8b0aea1d5
| 1,547
|
knounce
|
MIT License
|
src/test/kotlin/com/graphscout/ApplicationTest.kt
|
sztojkatamas
| 668,778,024
| false
| null |
package com.graphscout
import com.graphscout.plugins.*
import io.ktor.client.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.testing.*
import kotlinx.serialization.json.Json
private val jsonBuilder = Json {
prettyPrint = true
isLenient = true
}
class ApplicationTest {
private fun configTestApplicationAndReturnClient(builder: ApplicationTestBuilder): HttpClient {
builder.application {
configureSerialization()
configureHTTP()
configureSecurity()
configureRouting()
}
return builder.createClient { install(ContentNegotiation) { json(jsonBuilder) } }
}
}
| 0
|
Kotlin
|
0
| 0
|
a312899426723452e42964a8c71d4d28582e26a6
| 717
|
GraphScout
|
MIT License
|
app/src/main/java/com/necatisozer/analytics/app/MainActivity.kt
|
necatisozer
| 269,077,626
| false
| null |
package com.necatisozer.analytics.app
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity(R.layout.activity_main)
| 0
|
Kotlin
|
1
| 5
|
86de1c363d04c9ed33d75bcbeebdad43d10f2488
| 151
|
kotlin-analytics
|
MIT License
|
core/src/test/kotlin/net/corda/core/node/VersionTest.kt
|
jeffzfw
| 88,832,828
| true
|
{"Kotlin": 2373890, "Java": 133475, "Groovy": 25986, "Shell": 289, "Batchfile": 106}
|
package net.corda.core.node
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.Test
class VersionTest {
@Test
fun `parse valid non-SNAPSHOT string`() {
assertThat(Version.parse("1.2")).isEqualTo(Version(1, 2, null, false))
}
@Test
fun `parse valid SNAPSHOT string`() {
assertThat(Version.parse("2.23-SNAPSHOT")).isEqualTo(Version(2, 23, null, true))
}
@Test
fun `parse string with just major number`() {
assertThatThrownBy {
Version.parse("2")
}.isInstanceOf(IllegalArgumentException::class.java)
}
@Test
fun `parse string with unknown qualifier`() {
assertThatThrownBy {
Version.parse("2.3-TEST")
}.isInstanceOf(IllegalArgumentException::class.java)
}
@Test
fun `parses patch version`() {
assertThat(Version.parse("0.1.2")).isEqualTo(Version(0, 1, 2, false))
}
@Test
fun `parses snapshot patch version`() {
assertThat(Version.parse("0.1.2-SNAPSHOT")).isEqualTo(Version(0, 1, 2, true))
}
}
| 0
|
Kotlin
|
0
| 0
|
d2d7cbc9ecfc2b5255d2602a792631cffc09ece3
| 1,130
|
corda
|
Apache License 2.0
|
app/src/main/java/com/unilim/iut/truckers/controleur/SynchronisationControleur.kt
|
paul-rezzonico
| 690,680,634
| false
|
{"Kotlin": 65802}
|
package com.unilim.iut.truckers.controleur
import android.util.Log
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
class SynchronisationControleur {
private lateinit var executeur: ScheduledExecutorService
private var intervalleMinutes: Long = 5
private val tache = Runnable {
Log.d("TruckerService", "Synchronisation des messages")
}
fun changerIntervalle(intervalle: Long): Boolean {
this.intervalleMinutes = intervalle
return true
}
/**
* Cette méthode permet de lancer la synchronisation à intervalle régulier
* return void
*/
fun miseEnPlaceSynchronisation() {
executeur = Executors.newScheduledThreadPool(1)
executeur.scheduleAtFixedRate(tache, 0, intervalleMinutes, TimeUnit.MINUTES)
}
/**
* Cette méthode permet d'arrêter la synchronisation
* return void
*/
fun arreterSynchronisation() {
executeur.shutdown()
}
}
| 0
|
Kotlin
|
1
| 0
|
30c9df058be2d3247b4d77be320cadbd021bc0d4
| 1,033
|
truckers
|
The Unlicense
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/sagemaker/CfnModelPackagePropsDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.sagemaker
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.sagemaker.CfnModelPackageProps
@Generated
public fun buildCfnModelPackageProps(initializer: @AwsCdkDsl
CfnModelPackageProps.Builder.() -> Unit): CfnModelPackageProps =
CfnModelPackageProps.Builder().apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
e08d201715c6bd4914fdc443682badc2ccc74bea
| 426
|
aws-cdk-kt
|
Apache License 2.0
|
app/src/main/java/com/puntogris/posture/ui/reminders/configuration/ReminderItemViewHolder.kt
|
puntogris
| 398,388,678
| false
| null |
package com.puntogris.posture.ui.reminders.configuration
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.puntogris.posture.databinding.ReminderItemVhBinding
import com.puntogris.posture.utils.ReminderUi
class ReminderItemViewHolder(private val binding: ReminderItemVhBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(
reminderItem: ReminderUi.Item,
clickListener: (ReminderUi) -> Unit,
isLastItem: Boolean
) {
binding.textViewItemName.setText(reminderItem.title)
binding.textViewItemDescription.text = reminderItem.description
binding.root.setOnClickListener { clickListener(reminderItem) }
binding.viewDivider.isVisible = !isLastItem
}
companion object {
fun from(parent: ViewGroup): ReminderItemViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = ReminderItemVhBinding.inflate(layoutInflater, parent, false)
return ReminderItemViewHolder(binding)
}
}
}
| 0
|
Kotlin
|
2
| 7
|
099ba90c707c308047c43b1536f92f450f59c772
| 1,146
|
posture-reminder
|
MIT License
|
app/src/main/java/com/flatig/arknights_info/tool_ui/AboutTool.kt
|
Flatigers
| 661,241,644
| false
| null |
package com.flatig.arknights_info.tool_ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import com.flatig.arknights_info.R
import com.flatig.arknights_info.app.BaseCompatActivity
import com.flatig.arknights_info.app.SelfUpdater
class AboutTool : BaseCompatActivity() {
private lateinit var bar: PenguinBar
private lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.tool_about)
initView()
}
private fun initView() {
bar = findViewById(R.id.tool_about_bar)
bar.setTitle(resources.getString(R.string.about_name))
button = findViewById(R.id.tool_about_button)
button.setOnClickListener {
SelfUpdater().checkSelfUpdate()
}
}
}
| 0
|
Kotlin
|
0
| 1
|
fb6afa7b2df69c3fc8d8d97a0e7f244190010dfd
| 876
|
Arknithts-Info
|
MIT License
|
app/src/main/java/ceui/lisa/repo/SearchIllustRepo.kt
|
ylnbznz
| 381,658,739
| true
|
{"Java Properties": 2, "Gradle": 6, "Shell": 1, "Markdown": 5, "Git Attributes": 1, "Batchfile": 1, "Text": 2, "Ignore List": 5, "XML": 313, "YAML": 2, "INI": 1, "Proguard": 4, "Java": 413, "Kotlin": 69, "JSON": 1, "CSS": 1}
|
package ceui.lisa.repo
import android.text.TextUtils
import ceui.lisa.core.FilterMapper
import ceui.lisa.core.RemoteRepo
import ceui.lisa.http.Retro
import ceui.lisa.model.ListIllust
import ceui.lisa.utils.PixivOperate
import ceui.lisa.viewmodel.SearchModel
import io.reactivex.Observable
import io.reactivex.functions.Function
class SearchIllustRepo(
var keyword: String?,
var sortType: String?,
var searchType: String?,
var starSize: String?,
var isPopular: Boolean
) : RemoteRepo<ListIllust>() {
private var filterMapper: FilterMapper? = null
override fun initApi(): Observable<ListIllust> {
return if (isPopular) {
Retro.getAppApi().popularPreview(token(), keyword)
} else {
PixivOperate.insertSearchHistory(keyword, 0)
Retro.getAppApi().searchIllust(
token(),
keyword + if (TextUtils.isEmpty(starSize)) "" else " $starSize",
sortType,
searchType
)
}
}
override fun initNextApi(): Observable<ListIllust> {
return Retro.getAppApi().getNextIllust(token(), nextUrl)
}
override fun mapper(): Function<in ListIllust, ListIllust> {
if (this.filterMapper == null) {
this.filterMapper = FilterMapper().enableFilterStarSize()
}
return this.filterMapper!!
}
fun update(searchModel: SearchModel, pop: Boolean) {
keyword = searchModel.keyword.value
sortType = searchModel.sortType.value
searchType = searchModel.searchType.value
starSize = searchModel.starSize.value
isPopular = pop
this.filterMapper?.updateStarSizeLimit(this.getStarSizeLimit())
}
fun getStarSizeLimit(): Int {
if (TextUtils.isEmpty(this.starSize)) {
return 0
}
val match = Regex("""\d+""").find(starSize!!)
if (match != null) {
return match.value.toInt()
}
return 0
}
}
| 1
| null |
0
| 0
|
f8021c68fb656ba6f1d1d6c406feb99419bf312a
| 2,004
|
Pixiv-Shaft
|
MIT License
|
app/src/main/java/id/asep/salesproject/di/NetworkModule.kt
|
isMail1229
| 333,321,634
| false
| null |
package id.asep.salesproject.di
import com.haroldadmin.cnradapter.NetworkResponseAdapterFactory
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import id.asep.salesproject.utils.Constants
import okhttp3.Call
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
private const val TIMEOUT = 30L
@Singleton
@Provides
fun provideHttpLoggerInterceptor(): HttpLoggingInterceptor {
return HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
}
@Singleton
@Provides
fun provideCallFactory(httpLoggingInterceptor: HttpLoggingInterceptor): Call.Factory {
return OkHttpClient.Builder()
.addNetworkInterceptor(httpLoggingInterceptor)
.writeTimeout(TIMEOUT, TimeUnit.SECONDS)
.readTimeout(TIMEOUT, TimeUnit.SECONDS)
.build()
}
@Singleton
@Provides
fun provideRetrofit(
httpLogingInterceptor: Call.Factory
): Retrofit {
return Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.callFactory(httpLogingInterceptor)
.addConverterFactory(MoshiConverterFactory.create())
.addCallAdapterFactory(NetworkResponseAdapterFactory())
.build()
}
}
| 0
|
Kotlin
|
0
| 0
|
cba316fc6c751f152235b594ba69ae3a811eb80e
| 1,617
|
SalesProject
|
Apache License 2.0
|
app/src/main/java/com/shid/mangalist/data/repository/DetailAnimeRepository.kt
|
theshid
| 328,045,410
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 62, "XML": 71, "Java": 7, "JSON": 3}
|
package com.shid.mangalist.data.repository
import com.shid.mangalist.data.local.db.AnimeDatabase
import com.shid.mangalist.data.remote.RemoteDataSource
import com.shid.mangalist.data.remote.network.ApiServices
import com.shid.mangalist.data.remote.response.detail.CharactersListResponse
import com.shid.mangalist.data.remote.response.detail.DetailAnimeResponse
import com.shid.mangalist.data.remote.response.detail.Promo
import com.shid.mangalist.data.remote.response.main_response.AnimeListResponse
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DetailAnimeRepository @Inject constructor(
private val remoteDataSource: RemoteDataSource
):DetailRepository {
companion object {
@Volatile
private var instance: DetailAnimeRepository? = null
fun getInstance(remoteData: RemoteDataSource): DetailAnimeRepository =
instance ?: synchronized(this) {
instance ?: DetailAnimeRepository(remoteData)
}
}
override suspend fun getDetailAnime(id: Int): DetailAnimeResponse {
lateinit var animeDetail: DetailAnimeResponse
remoteDataSource.getDetailAnime(id, object : RemoteDataSource.GetDetailCallback {
override fun onAnimeReceived(anime: DetailAnimeResponse) {
animeDetail = anime
}
})
return animeDetail
}
override suspend fun getCharacters(id: Int): List<CharactersListResponse> {
lateinit var charactersResult: List<CharactersListResponse>
remoteDataSource.getCharacters(id, object : RemoteDataSource.GetCharactersCallback {
override fun onCharactersReceived(characters: List<CharactersListResponse>) {
charactersResult = characters
}
})
return charactersResult
}
override suspend fun getVideos(id: Int): List<Promo> {
lateinit var videosResult: List<Promo>
remoteDataSource.getVideos(id, object : RemoteDataSource.GetVideosCallback {
override fun onVideosReceived(videos: List<Promo>) {
videosResult = videos
}
})
return videosResult
}
}
| 0
|
Kotlin
|
0
| 0
|
78137587fc10208798e3733e7e497aeadc2a0d47
| 2,178
|
MangaList
|
The Unlicense
|
raft-base/src/main/java/top/dreamlike/base/raft/RaftStatus.kt
|
dreamlike-ocean
| 505,124,997
| false
|
{"Kotlin": 84864, "Java": 6524}
|
package top.dreamlike.base.raft
enum class RaftStatus {
follower,
candidate,
lead
}
| 0
|
Kotlin
|
0
| 3
|
5b9600e859e52b1d689fe2c1c6e600b5a248aaac
| 96
|
raft-kt
|
MIT License
|
kt/godot-library/src/main/kotlin/godot/gen/godot/AnimatableBody3D.kt
|
utopia-rise
| 289,462,532
| false
| null |
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import godot.common.interop.VoidPtr
import godot.core.TypeManager
import godot.core.VariantParser.BOOL
import godot.core.VariantParser.NIL
import godot.core.memory.TransferContext
import kotlin.Boolean
import kotlin.Int
import kotlin.Suppress
import kotlin.Unit
import kotlin.jvm.JvmName
/**
* An animatable 3D physics body. It can't be moved by external forces or contacts, but can be moved
* manually by other means such as code, [AnimationMixer]s (with [AnimationMixer.callbackModeProcess]
* set to [AnimationMixer.ANIMATION_CALLBACK_MODE_PROCESS_PHYSICS]), and [RemoteTransform3D].
* When [AnimatableBody3D] is moved, its linear and angular velocity are estimated and used to
* affect other physics bodies in its path. This makes it useful for moving platforms, doors, and other
* moving objects.
*/
@GodotBaseType
public open class AnimatableBody3D : StaticBody3D() {
/**
* If `true`, the body's movement will be synchronized to the physics frame. This is useful when
* animating movement via [AnimationPlayer], for example on moving platforms. Do **not** use together
* with [PhysicsBody3D.moveAndCollide].
*/
public final inline var syncToPhysics: Boolean
@JvmName("syncToPhysicsProperty")
get() = isSyncToPhysicsEnabled()
@JvmName("syncToPhysicsProperty")
set(`value`) {
setSyncToPhysics(value)
}
public override fun new(scriptIndex: Int): Unit {
callConstructor(ENGINECLASS_ANIMATABLEBODY3D, scriptIndex)
}
public final fun setSyncToPhysics(enable: Boolean): Unit {
TransferContext.writeArguments(BOOL to enable)
TransferContext.callMethod(ptr, MethodBindings.setSyncToPhysicsPtr, NIL)
}
public final fun isSyncToPhysicsEnabled(): Boolean {
TransferContext.writeArguments()
TransferContext.callMethod(ptr, MethodBindings.isSyncToPhysicsEnabledPtr, BOOL)
return (TransferContext.readReturnValue(BOOL) as Boolean)
}
public companion object
internal object MethodBindings {
public val setSyncToPhysicsPtr: VoidPtr =
TypeManager.getMethodBindPtr("AnimatableBody3D", "set_sync_to_physics", 2586408642)
public val isSyncToPhysicsEnabledPtr: VoidPtr =
TypeManager.getMethodBindPtr("AnimatableBody3D", "is_sync_to_physics_enabled", 36873697)
}
}
| 49
| null |
45
| 634
|
ac2a1bd5ea931725e2ed19eb5093dea171962e3f
| 2,726
|
godot-kotlin-jvm
|
MIT License
|
Software/Application/app/src/main/java/hr/unizg/foi/chorlist/models/responses/ItemResponse.kt
|
ttomasicc
| 596,167,102
| false
| null |
package hr.unizg.foi.chorlist.models.responses
import com.google.gson.annotations.SerializedName
data class ItemResponse(
val id: Long,
@SerializedName("id_shopping_list")
val idShoppingList: Long,
val description: String
)
| 0
|
Kotlin
|
0
| 0
|
3846e88e42872f6c26c3de9b85feb6169d0b3660
| 241
|
chorlist-app
|
MIT License
|
app/src/main/java/com/technorapper/boiler/di/scopes/BindingScoped.kt
|
HaneetGH
| 228,811,463
| false
| null |
package com.technorapper.boiler.di.scopes
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import javax.inject.Scope
@Scope
@kotlin.annotation.Retention
@Target(
AnnotationTarget.ANNOTATION_CLASS,
AnnotationTarget.CLASS,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER
)
annotation class BindingScoped
| 1
|
Kotlin
|
5
| 9
|
14abab83d47749ebe8ca4b57b89e096b3c8c6abb
| 404
|
KotlinAndroidBase
|
Apache License 2.0
|
app/src/main/java/com/example/writeups/RecyclerViewAdapter.kt
|
SarvT
| 724,244,749
| false
|
{"Kotlin": 14357}
|
package com.example.writeups
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.tv.TvView
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class RecyclerViewAdapter(val activity: Activity, val context: Context, val ids:ArrayList<Int>, val writups:ArrayList<String>, val authors:ArrayList<String>, val titles:ArrayList<String>) : RecyclerView.Adapter<RecyclerViewAdapter.RVViewHolder>() {
class RVViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val id_view = itemView.findViewById<TextView>(R.id.id_txt)
val writup_view = itemView.findViewById<TextView>(R.id.writeup_txt)
val author_view = itemView.findViewById<TextView>(R.id.author_txt)
val title_view = itemView.findViewById<TextView>(R.id.title_txt)
val mainLayout = itemView.findViewById<LinearLayout>(R.id.mainLayout)
val anim = AnimationUtils.loadAnimation(itemView.context, R.anim.translate_ani)
init {
mainLayout.startAnimation(anim)
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RVViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.recycler_view_item, parent, false)
return RVViewHolder(view)
}
override fun onBindViewHolder(holder: RecyclerViewAdapter.RVViewHolder, position: Int) {
holder.id_view.text = ids[position].toString()
holder.writup_view.text = writups[position]
holder.author_view.text = authors[position]
holder.title_view.text = titles[position]
holder.mainLayout.setOnClickListener {
val intent = Intent(context, UpdateWriteupsActivity::class.java)
intent.putExtra("id",ids[position].toString())
intent.putExtra("title",titles[position])
intent.putExtra("writeup",writups[position])
intent.putExtra("author",authors[position])
activity.startActivityForResult(intent, 1)
}
}
override fun getItemCount(): Int {
return ids.size
}
}
| 0
|
Kotlin
|
0
| 0
|
e9767c8e9fed5385b92d923eae0622953518d12f
| 2,341
|
Writeups
|
MIT License
|
app/src/test/java/com/daya/taha/utils/MainCoroutineRule.kt
|
daya-pangestu
| 308,078,972
| false
|
{"Kotlin": 140694}
|
package com.daya.taha.utils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.*
import org.junit.rules.TestWatcher
import org.junit.runner.Description
class MainCoroutineRule @OptIn(ExperimentalCoroutinesApi::class) constructor(
val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
) : TestWatcher() {
@OptIn(ExperimentalCoroutinesApi::class)
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(testDispatcher)
}
@OptIn(ExperimentalCoroutinesApi::class)
override fun finished(description: Description?) {
super.finished(description)
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}
}
@OptIn(ExperimentalCoroutinesApi::class)
fun MainCoroutineRule.runBlockingTest(block: suspend TestCoroutineScope.() -> Unit) {
return this.testDispatcher.runBlockingTest {
block()
}
}
/**
* Creates a new [CoroutineScope] with the rule's testDispatcher
*/
fun MainCoroutineRule.CoroutineScope(): CoroutineScope = CoroutineScope(testDispatcher)
| 0
|
Kotlin
|
0
| 1
|
a52e7e6f0c5343e491db3a1551ac183ac9f72ed8
| 1,213
|
push-notif
|
MIT License
|
app/src/main/java/com/adkdevelopment/keddit/NewsFragment.kt
|
dmytroKarataiev
| 77,378,183
| false
| null |
/*
* MIT License
*
* Copyright (c) 2016. <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.adkdevelopment.keddit
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_news.*
/**
* A placeholder fragment containing a simple view.
*/
class NewsFragment : Fragment() {
private val newsList by lazy {
news_list
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_news, container, false)
// val view = container?.inflate(R.layout.fragment_news)
// return view
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
newsList.setHasFixedSize(true)
newsList.layoutManager = LinearLayoutManager(context)
}
}
| 0
|
Kotlin
|
0
| 0
|
4768fe12721a7f9ef139f8af3cc10410d51fd084
| 2,128
|
Keddit
|
MIT License
|
MLN-Android/mlnservics/src/main/java/com/immomo/mls/util/LLog.kt
|
momotech
| 209,464,640
| false
|
{"C": 10709384, "Java": 4810073, "Objective-C": 2521606, "Lua": 419100, "Kotlin": 98796, "Shell": 33644, "FreeMarker": 29400, "Objective-C++": 11980, "CMake": 6555, "Ruby": 6494, "Makefile": 3309, "Python": 420, "C++": 191}
|
package com.immomo.mls.util
object LLog {
const val TAG_DEPENDENCE = "luadep"
@JvmStatic
fun log(obj: Any, vararg params: Any) {
LogUtil.d("lc_dep_" + obj.javaClass.name, params.fold("") { acc, s ->
"$acc $s"
})
}
@JvmStatic
fun logError(throwable: Throwable?, vararg params: Any) {
val msg = params.fold("") { acc, s ->
"$acc $s"
}
val tag = "lc_dep_"
LogUtil.e(tag, throwable?.message, msg)
}
fun logFatal(tag: String, throwable: Throwable, msg: String) {
LogUtil.e(throwable, "lc_dep_$tag $msg")
}
}
| 98
|
C
|
206
| 1,612
|
6341ff6f4db5db0400691b70b4e595bffd623b36
| 624
|
MLN
|
MIT License
|
app/src/debug/java/com/mycompany/myapp/app/RobolectricApplication.kt
|
weverb2
| 153,906,418
| true
|
{"Kotlin": 65933, "XSLT": 15519, "HTML": 8033, "Python": 2697, "Shell": 1351}
|
package com.mycompany.myapp.app
import android.annotation.SuppressLint
import android.app.Application
@SuppressLint("Registered")
class RobolectricApplication : Application()
| 0
|
Kotlin
|
0
| 0
|
23028982c89d7fbda1c714840d36b067d245f1e1
| 177
|
android-starter-project
|
Apache License 2.0
|
sample/common/src/commonMain/kotlin/com/mohamedrejeb/richeditor/sample/common/model/CustomStyle.kt
|
MohamedRejeb
| 630,584,174
| false
| null |
package com.mohamedrejeb.richeditor.sample.common
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.SpanStyle
import com.mohamedrejeb.richeditor.model.RichTextStyle
data class CustomStyle(
val color: Color,
val background: Color
): RichTextStyle {
override fun applyStyle(spanStyle: SpanStyle): SpanStyle {
return spanStyle.copy(
color = color,
background = background
)
}
}
| 26
| null |
33
| 631
|
0740e34c8fc75eceafedc2c5d9011a6fbdc4f5be
| 456
|
Compose-Rich-Editor
|
Apache License 2.0
|
src/test/kotlin/no/studentmediene/micronautazurequeue/service/AzureQueueMessageReceiverTest.kt
|
Studentmediene
| 308,722,572
| false
| null |
package no.studentmediene.micronautazurequeue.service
import com.azure.storage.queue.QueueAsyncClient
import com.azure.storage.queue.models.QueueMessageItem
import io.micronaut.context.event.ApplicationEventPublisher
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import no.studentmediene.micronautazurequeue.DummyHandler
import no.studentmediene.micronautazurequeue.configuration.AzureQueueConfiguration
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import reactor.core.publisher.Mono
internal class AzureQueueMessageReceiverTest {
private val azureQueueClient = mockk<QueueAsyncClient>()
private val eventPublisher = mockk<ApplicationEventPublisher>(relaxed = true)
private val handler = DummyHandler()
private lateinit var configuration: AzureQueueConfiguration
private lateinit var receiver: AzureQueueMessageReceiver
@BeforeEach
fun setup() {
configuration = AzureQueueConfiguration(
label = "test-queue"
).apply {
enabled = true
connectionString = "someconfigurationString"
queueName = "test-queue"
handler = "DummyHandler"
}
receiver = AzureQueueMessageReceiver(
configuration = configuration,
queueClient = azureQueueClient,
handler = handler,
eventPublisher = eventPublisher
)
handler.reset()
every { azureQueueClient.deleteMessage(any(), any()) } returns Mono.empty()
every { azureQueueClient.queueName } returns configuration.queueName
}
@Test
fun `Should notify handler of new message`() {
val testMessages = listOf(
QueueMessageItem().setMessageId("test-1").setMessageText("Test message 1").setPopReceipt("pop-1"),
QueueMessageItem().setMessageId("test-2").setMessageText("Test message 1").setPopReceipt("pop-2")
)
every { azureQueueClient.receiveMessages(any()).toIterable() } returns testMessages
receiver.receiveAndProcessMessages()
assertEquals(2, handler.receivedMessages.size)
testMessages.forEach {
verify(exactly = 1) { azureQueueClient.deleteMessage(it.messageId, it.popReceipt) }
}
}
@Test
fun `Should handle base64 encoded message`() {
val testMessage = QueueMessageItem()
.setMessageId("test-1")
.setMessageText("QmFzZTY0IGVuY29kZWQgbWVzc2FnZQ==")
.setPopReceipt("pop-1")
every { azureQueueClient.receiveMessages(any()).toIterable() } returns listOf(testMessage)
receiver.receiveAndProcessMessages()
assertEquals("Base64 encoded message", handler.receivedMessages.first())
}
@Test
fun `Should disable queue-polling when too many failures has occurred`() {
configuration.pollingFailureWaitTimeSeconds = 1
configuration.disableAfterNumberOfFails = 2
// Take a single message each time,
// because we fail by number of requests and not amount of messages polled
configuration.numberOfMessagesToPoll = 1
val failingMessages = (0..configuration.disableAfterNumberOfFails + 1)
.map {
QueueMessageItem()
.setMessageId("failing-$it")
.setMessageText("--fail-me--")
.setPopReceipt("pop-failing-$it")
}
failingMessages
.chunked(configuration.numberOfMessagesToPoll)
.forEach {
every { azureQueueClient.receiveMessages(any()).toIterable() } returns it
receiver.receiveAndProcessMessages()
}
assertFalse(configuration.enabled)
}
}
| 0
|
Kotlin
|
0
| 0
|
bfb11792e235a3731c32552354cbea62d6fbcf2a
| 3,532
|
micronaut-azurequeue
|
Apache License 2.0
|
sample-kt/src/main/java/com/example/sample_kt/Video.kt
|
cr1944
| 79,197,596
| true
|
{"Gradle": 6, "Shell": 1, "Text": 2, "Ignore List": 2, "YAML": 1, "Markdown": 1, "Java": 60, "XML": 23, "Java Properties": 1, "Kotlin": 46, "Proguard": 1}
|
package com.example.sample_kt
const val ROOT = "https://raw.githubusercontent.com/danikula/AndroidVideoCache/master/files/"
enum class Video(val url: String) {
ORANGE_1(ROOT + "orange1.mp4"),
ORANGE_2(ROOT + "orange2.mp4"),
ORANGE_3(ROOT + "orange3.mp4"),
ORANGE_4(ROOT + "orange4.mp4"),
ORANGE_5(ROOT + "orange5.mp4");
}
| 0
|
Java
|
0
| 0
|
cbe51efb790dcbc64d02f9add262c1e00df58604
| 343
|
AndroidVideoCache
|
Apache License 2.0
|
src/main/kotlin/kotlinFeedbackPlugin/state/active/LastActive.kt
|
DmitryPogrebnoy
| 276,805,622
| false
|
{"Kotlin": 119532}
|
package kotlinFeedbackPlugin.state.active
import com.intellij.openapi.project.Project
import kotlinFeedbackPlugin.show.showInactiveTimeNotificationIfPossible
import java.time.LocalDateTime
/**
* Temporary storage for information about the last user activity.
*
* @see kotlinFeedbackPlugin.track.active.EditorMouseEventTracker
* @see kotlinFeedbackPlugin.track.active.EditorTypingEventTracker
*/
object LastActive {
var lastActive: LocalDateTime = LocalDateTime.now()
internal fun trackActive(project: Project) {
showInactiveTimeNotificationIfPossible(project)
lastActive = LocalDateTime.now()
}
}
| 0
|
Kotlin
|
1
| 0
|
4228ec23417c6cbb1844cd530883433443747655
| 633
|
Kotlin-feedback-plugin
|
Apache License 2.0
|
firebase-dataconnect/connectors/src/androidTest/kotlin/com/google/firebase/dataconnect/connectors/keywords/TestKeywordsConnectorFactory.kt
|
firebase
| 146,941,185
| false
|
{"Java": 13568535, "PureBasic": 10781995, "Kotlin": 2658699, "Python": 104323, "C++": 86300, "Makefile": 21902, "Shell": 13966, "HCL": 11091, "C": 6939, "JavaScript": 5482, "Mustache": 4729, "Ruby": 2545, "AIDL": 1486, "HTML": 215}
|
/*
* Copyright 2024 Google 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
*
* 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.google.firebase.dataconnect.connectors.keywords
import com.google.firebase.FirebaseApp
import com.google.firebase.dataconnect.DataConnectSettings
import com.google.firebase.dataconnect.FirebaseDataConnect
import com.google.firebase.dataconnect.connectors.testutil.TestConnectorFactory
import com.google.firebase.dataconnect.connectors.`typealias`.KeywordsConnector
import com.google.firebase.dataconnect.connectors.`typealias`.getInstance
import com.google.firebase.dataconnect.testutil.TestDataConnectFactory
import com.google.firebase.dataconnect.testutil.TestFirebaseAppFactory
/**
* A JUnit test rule that creates instances of [KeywordsConnector] for use during testing, and
* closes their underlying [FirebaseDataConnect] instances upon test completion.
*/
class TestKeywordsConnectorFactory(
firebaseAppFactory: TestFirebaseAppFactory,
dataConnectFactory: TestDataConnectFactory
) : TestConnectorFactory<KeywordsConnector>(firebaseAppFactory, dataConnectFactory) {
override fun createConnector(firebaseApp: FirebaseApp, settings: DataConnectSettings) =
KeywordsConnector.getInstance(firebaseApp, settings)
}
| 440
|
Java
|
575
| 2,270
|
0697dd3aadd6c13d9e2d321c75173992bfbaac3b
| 1,737
|
firebase-android-sdk
|
Apache License 2.0
|
src/main/kotlin/hr/caellian/math/vector/VectorI.kt
|
Caellian
| 55,831,616
| false
| null |
package hr.caellian.math.vector
import hr.caellian.math.matrix.MatrixI
import hr.caellian.math.matrix.MatrixN
import java.nio.Buffer
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.IntBuffer
import kotlin.math.abs
import kotlin.math.roundToInt
import kotlin.math.sqrt
/**
* Vector class for double N-dimensional vectors.
*
* @param wrapped value array to create a new vector from.
*
* @author Caellian
*/
class VectorI(override var wrapped: Array<Int> = emptyArray()) : VectorN<Int>() {
/**
* Creates a new vector using given values.
*
* @param values values to create a new vector from.
* @return created vector.
*/
constructor(vararg values: Int) : this(values.toTypedArray())
/**
* Creates a new vector using given collection values.
*
* @param values collection values to create a new vector from.
* @return created vector.
*/
constructor(values: Collection<Int>) : this(values.toTypedArray())
/**
* Creates a new vector using buffer values.
*
* @param buffer buffer to create a new vector from.
* @return created vector.
*/
constructor(buffer: IntBuffer) : this((0 until buffer.capacity()).map { buffer.get() })
/**
* @return new vector with negated values.
*/
override operator fun unaryMinus(): VectorI = VectorI(Array(size) { -this[it] })
/**
* Adds two vectors together and returns resulting vector.
* In order to add to matrices together, they must be of same size.
*
* @return result of vector addition.
*/
override operator fun plus(other: VectorN<Int>): VectorI {
require(size == other.size) { "Invalid argument vector size: ${other.size}!" }
return VectorI(Array(size) { this[it] + other[it] })
}
/**
* Subtracts other vector from this one and returns resulting vector.
* In order to subtract one vector from another, both vectors must be of same size.
*
* @return result of vector subtraction.
*/
override operator fun minus(other: VectorN<Int>): VectorI {
require(size == other.size) { "Invalid argument vector size: ${other.size}!" }
return VectorI(Array(size) { this[it] - other[it] })
}
/**
* Multiplies two vectors together and returns resulting vector.
* In order to add to multiply vectors together, they must be of same size.
*
* @return result of vector multiplication.
*/
override operator fun times(other: VectorN<Int>): VectorI {
require(size == other.size) { "Invalid argument vector size: ${other.size}!" }
return VectorI(Array(size) { this[it] * other[it] })
}
/**
* Divides this vector with other and returns resulting vector.
* In order to divide one vector with another, both vectors must be of same size.
*
* @return result of vector division.
*/
override operator fun div(other: VectorN<Int>): VectorI {
require(size == other.size) { "Invalid argument vector size: ${other.size}!" }
return VectorI(Array(size) { this[it] / other[it] })
}
/**
* Performs scalar addition on this vector and returns resulting vector.
*
* @return result of vector scalar addition.
*/
override operator fun plus(value: Int): VectorI = VectorI(Array(size) { this[it] + value })
/**
* Performs scalar subtraction on this vector and returns resulting vector.
*
* @return result of scalar vector subtraction.
*/
override operator fun minus(value: Int): VectorI = VectorI(Array(size) { this[it] - value })
/**
* Performs scalar multiplication on this vector and returns resulting vector.
*
* @return result of scalar vector multiplication.
*/
override operator fun times(value: Int): VectorI = VectorI(Array(size) { this[it] * value })
/**
* Performs scalar division on this vector and returns resulting vector.
*
* @return result of scalar vector division.
*/
override operator fun div(value: Int): VectorI = VectorI(Array(size) { this[it] / value })
/**
* @return biggest value of a member of this vector.
*/
override fun max(): Int = wrapped.max() ?: 0
/**
* @return smalled value of a member of this vector.
*/
override fun min(): Int = wrapped.min() ?: 0
/**
* @return new vector containing absolute values of this vector.
*/
override fun absolute(): VectorI = VectorI(Array(size) { abs(this[it]) })
/**
* @return new vector with normalized values of this one.
*/
override fun normalized(): VectorI = this / magnitude()
/**
* @return magnitude of this vector.
*/
override fun magnitude(): Int = distanceTo(this)
/**
* Calculates distance from this to other vector.
*
* @return distance between this and other vector.
*/
override fun distanceTo(other: VectorN<Int>): Int = sqrt((this dot other).toFloat()).roundToInt()
/**
*
* @return dot product of two vectors.
*/
override fun dot(other: VectorN<Int>): Int {
require(size == other.size) { "Invalid argument vector size: ${other.size}!" }
return wrapped.zip(other.wrapped).sumBy { (a, b) -> a * b }
}
/**
* Returns cross product of this and other vector.
*
* @return cross product.
*/
override fun cross(other: VectorN<Int>): VectorI {
require(size == other.size) { "Invalid argument vector size: ${other.size}!" }
return when (size) {
3 -> VectorI(arrayOf(
this[1] * other[2] - this[2] * other[1],
this[2] * other[0] - this[0] * other[2],
this[0] * other[1] - this[1] * other[0]
))
7 -> VectorI(arrayOf(
this[1] * other[3] - this[3] * other[1] + this[2] * other[6] - this[6] * other[2] + this[4] * other[5] - this[5] * other[4],
this[2] * other[4] - this[4] * other[2] + this[3] * other[0] - this[0] * other[3] + this[5] * other[6] - this[6] * other[5],
this[3] * other[5] - this[5] * other[3] + this[4] * other[1] - this[1] * other[4] + this[6] * other[0] - this[0] * other[6],
this[4] * other[6] - this[6] * other[4] + this[5] * other[2] - this[2] * other[5] + this[0] * other[1] - this[1] * other[0],
this[5] * other[0] - this[0] * other[5] + this[6] * other[3] - this[3] * other[6] + this[1] * other[2] - this[2] * other[1],
this[6] * other[1] - this[1] * other[6] + this[0] * other[4] - this[4] * other[0] + this[2] * other[3] - this[3] * other[2],
this[0] * other[2] - this[2] * other[0] + this[1] * other[5] - this[5] * other[1] + this[3] * other[4] - this[4] * other[3]
))
else -> throw NotImplementedError("Cross product does not exist in $size-dimensional space!")
}
}
/**
* Rotates this vector using rotation matrix.
*
* @return rotated vector.
*/
override fun rotated(rotationMatrix: MatrixN<Int>): VectorI = (rotationMatrix * verticalMatrix).toVector() as VectorI
/**
* Linearly interpolates between two vectors.
*
* @return linear interpolation.
*/
override fun lerp(destination: VectorN<Int>, percent: Int): VectorI = this + (destination - this) * percent
/**
* Vertical matrix containing data of this vector.
*/
override val verticalMatrix: MatrixI by lazy { MatrixI(arrayOf(toArray()), true) }
/**
* Horizontal matrix containing data of this vector.
*/
override val horizontalMatrix: MatrixI by lazy { MatrixI(arrayOf(toArray())) }
/**
* Returns array containing vector data.
*
* @return array containing data of this vector.
*/
override fun toArray(): Array<Int> = Array(size) { wrapped[it] }
/**
* @return clone of this vector.
*/
override fun replicated(): VectorI = VectorI(toArray())
/**
* @return type supported by this class.
*/
override fun getTypeClass() = Int::class
/**
* Creates a new instance of wrapper containing given data.
*
* @param data data of new wrapper.
* @return new instance of wrapper containing argument data.
*/
override fun withData(wrapped: Array<Int>): VectorI = VectorI(wrapped)
/**
* @return [Buffer] containing data of represented object.
*/
override fun toBuffer(): Buffer {
val result = ByteBuffer.allocateDirect(wrapped.size shl 2).order(
ByteOrder.nativeOrder()).asIntBuffer()
wrapped.forEach { result.put(it) }
return result.flip()
}
}
| 1
|
Kotlin
|
1
| 3
|
130591d1848661e3c07eed46ac3b4fcf4a013cfb
| 8,783
|
Math
|
MIT License
|
plugins/kotlin/j2k/new/tests/testData/newJ2k/types/nestedArrays.kt
|
ingokegel
| 72,937,917
| false
| null |
internal object A {
fun sampleFunction(a: Array<IntArray>, b: Array<IntArray>): Array<IntArray> {
val n = a[0].size
val m = a.size
val p = b[0].size
val result = Array(m) { IntArray(p) }
for (i in 0 until m) {
for (j in 0 until p) {
for (k in 0 until n) {
result[i][j] += a[i][k] * b[k][j]
}
}
}
return result
}
}
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 454
|
intellij-community
|
Apache License 2.0
|
plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/common/plantuml/PlantUMLCodeFenceLanguageProvider.kt
|
dunno99
| 221,283,848
| false
| null |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.extensions.common.plantuml
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.lang.Language
import org.intellij.plugins.markdown.injection.CodeFenceLanguageProvider
class PlantUMLCodeFenceLanguageProvider: CodeFenceLanguageProvider {
override fun getLanguageByInfoString(infoString: String): Language? {
return when {
infoString in aliases -> PlantUMLLanguage.INSTANCE
else -> null
}
}
override fun getCompletionVariantsForInfoString(parameters: CompletionParameters): List<LookupElement> {
return aliases.map { LookupElementBuilder.create(it) }
}
companion object {
private val aliases = listOf(
"plantuml",
"puml"
)
}
}
| 1
| null |
1
| 1
|
f37a7bcddf4f66018f9cc8dbc109e0d49c3832a9
| 1,007
|
intellij-community
|
Apache License 2.0
|
aws-analytics-pinpoint/src/test/java/com/amplifyframework/analytics/pinpoint/targeting/ConstructTargetingClasses.kt
|
millsjustin
| 612,654,671
| true
|
{"Markdown": 7, "Batchfile": 3, "Shell": 7, "Gradle Kotlin DSL": 17, "Java Properties": 6, "INI": 25, "Java": 862, "Kotlin": 416, "Proguard": 2, "Ruby": 2}
|
/*
* Copyright 2016-2022 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amplifyframework.analytics.pinpoint.targeting
import android.content.Context
import android.content.SharedPreferences
import androidx.test.core.app.ApplicationProvider
import aws.sdk.kotlin.services.pinpoint.PinpointClient
import com.amplifyframework.analytics.pinpoint.internal.core.idresolver.SharedPrefsUniqueIdService
import com.amplifyframework.analytics.pinpoint.models.AndroidAppDetails
import com.amplifyframework.analytics.pinpoint.models.AndroidDeviceDetails
import com.amplifyframework.analytics.pinpoint.targeting.endpointProfile.EndpointProfile
import io.mockk.every
import io.mockk.mockk
import java.util.Locale
internal fun constructSharedPreferences(): SharedPreferences {
return ApplicationProvider.getApplicationContext<Context>().getSharedPreferences(
"preferences",
Context.MODE_PRIVATE
)
}
internal val uniqueID = "unique-id"
internal val appID = "app id"
internal val appTitle = "app title"
internal val packageName = "package name"
internal val versionCode = "1"
internal val versionName = "1.0.0"
internal val carrier = "carrier"
internal val locale = Locale.US
internal val country = "en_US"
internal val effectiveDate = 0L
internal val idService = mockk<SharedPrefsUniqueIdService>()
internal val appDetails = AndroidAppDetails(appID, appTitle, packageName, versionCode, versionName)
internal val deviceDetails = AndroidDeviceDetails(carrier = carrier, locale = locale)
internal val applicationContext = mockk<Context>()
internal fun setup() {
every { idService.getUniqueId() }.returns(uniqueID)
every { applicationContext.resources.configuration.locales[0].isO3Country }
.returns(country)
}
internal fun constructEndpointProfile(): EndpointProfile {
setup()
val endpointProfile = EndpointProfile(
idService,
appDetails,
deviceDetails,
applicationContext
)
endpointProfile.effectiveDate = effectiveDate
return endpointProfile
}
internal lateinit var pinpointClient: PinpointClient
internal fun constructPinpointClient(): PinpointClient {
pinpointClient = mockk()
return pinpointClient
}
internal fun constructTargetingClient(): TargetingClient {
setup()
val prefs = constructSharedPreferences()
return TargetingClient(
pinpointClient,
idService,
prefs,
appDetails,
deviceDetails,
applicationContext
)
}
| 0
|
Java
|
0
| 0
|
4ba3faf714d57fb0cc55ec99546c4f7b2b31dbaf
| 3,010
|
amplify-android
|
Apache License 2.0
|
mobile/src/main/java/de/lemke/nakbuch/data/HymnDataRepository.kt
|
Lemkinator
| 475,012,572
| false
| null |
package de.lemke.nakbuch.data
import de.lemke.nakbuch.data.database.*
import de.lemke.nakbuch.domain.model.BuchMode
import de.lemke.nakbuch.domain.model.Hymn
import de.lemke.nakbuch.domain.model.HymnId
import de.lemke.nakbuch.domain.model.PersonalHymn
import java.time.LocalDateTime
import javax.inject.Inject
class HymnDataRepository @Inject constructor(
private val hymnDataDao: HymnDataDao,
private val historyDao: HistoryDao,
private val sungOnDao: SungOnDao,
) {
suspend fun deleteHistory() = historyDao.deleteAll()
suspend fun getHistoryList(): List<Pair<Hymn, LocalDateTime>> = historyDao.getAll().map { historyFromDb(it) }
suspend fun addToHistoryList(hymn: Hymn, date: LocalDateTime) = historyDao.fixedInsert(historyToDb(hymn, date))
suspend fun getPersonalHymn(hymnId: HymnId): PersonalHymn = personalHymnFromDb(hymnDataDao.getPersonalHymnByHymnId(hymnId.toInt()))
suspend fun getAllPersonalHymns(): List<PersonalHymn> =
hymnDataDao.getAllPersonalHymns().map { personalHymnFromDb(it) }
suspend fun getAllPersonalHymns(buchMode: BuchMode): List<PersonalHymn> =
hymnDataDao.getAllPersonalHymns(buchMode.minId, buchMode.maxId).map { personalHymnFromDb(it) }
suspend fun setPersonalHymn(personalHymn: PersonalHymn, overwrite: Boolean = true) {
setPersonalHymnWithoutLists(personalHymn)
if (overwrite) sungOnDao.delete(personalHymn.hymn.hymnId.toInt())
sungOnDao.insert(personalHymnToSungOnDbList(personalHymn))
}
suspend fun setPersonalHymns(personalHymns: List<PersonalHymn>, overwrite: Boolean = true) {
setPersonalHymnsWithoutLists(personalHymns)
personalHymns.forEach {
if (overwrite) sungOnDao.delete(it.hymn.hymnId.toInt())
sungOnDao.insert(personalHymnToSungOnDbList(it))
}
}
private suspend fun setPersonalHymnWithoutLists(personalHymn: PersonalHymn) = hymnDataDao.upsert(personalHymnToHymnDataDb(personalHymn))
suspend fun setPersonalHymnsWithoutLists(personalHymns: List<PersonalHymn>) {
hymnDataDao.upsert(personalHymns.map { personalHymnToHymnDataDb(it) })
}
}
| 0
|
Kotlin
|
0
| 5
|
bbf45db05557a7ace6b0e9ab085cd38fca2a8e7f
| 2,151
|
NAK-Buch
|
MIT License
|
app/src/main/java/com/andrehaueisen/listadejanot/utilities/ViewsExtensions.kt
|
AndreHaueisen
| 88,384,506
| false
| null |
package com.andrehaueisen.listadejanot.utilities
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.util.TypedValue
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.TextView
import com.andrehaueisen.listadejanot.R
fun View.showSnackbar(message: String, duration: Int = Snackbar.LENGTH_INDEFINITE) {
Snackbar.make(this, message, duration)
.apply {
view.setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary))
val textView = view.findViewById<TextView>(android.support.design.R.id.snackbar_text)
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15F)
}
.show()
}
fun RecyclerView.setLayoutAnimation(animation: Int = R.anim.layout_animation_grow_from_center) {
val controller = AnimationUtils.loadLayoutAnimation(this.context, animation)
this.layoutAnimation = controller
this.scheduleLayoutAnimation()
}
fun View.setPoliticianGradeText(grade: Float, stringId: Int) {
if (grade != -1F) {
(this as TextView).text = this.resources.getString(stringId, String.format("%.1f", grade))
} else {
(this as TextView).text = this.resources.getString(stringId, resources.getString(R.string.no_grade))
}
}
| 0
|
Kotlin
|
0
| 0
|
f477e5520e5037bf019133051139adba4d61c962
| 1,391
|
TheList
|
Apache License 2.0
|
app/src/main/java/com/manday/marvel/domain/MD5Provider.kt
|
jmanday
| 301,367,076
| false
| null |
package com.manday.marvel.domain
import java.math.BigInteger
import java.security.MessageDigest
internal fun interface MD5Provider {
fun getMD5(input: String): String
}
internal val mD5Provider = MD5Provider {
require(it.isNotEmpty()) {
"The input can not be empty"
}
val md = MessageDigest.getInstance("MD5")
BigInteger(1, md.digest(it.toByteArray())).toString(16).padStart(32, '0')
}
| 7
|
Kotlin
|
0
| 0
|
e0ee0535ce4ad878bb9357b0ffcaab8aaf3f2473
| 418
|
Marvel
|
Apache License 2.0
|
kotlin/src/main/java/com/samelody/samples/kotlin/User.kt
|
belinwu
| 140,991,591
| false
|
{"Kotlin": 70895, "Java": 1117}
|
package com.samelody.samples.kotlin
class User(
val userId: String,
val name: String
)
| 0
|
Kotlin
|
0
| 2
|
dce2b98cb031df6bbf04cfc576541a2d96134b5d
| 103
|
samples
|
Apache License 2.0
|
src/main/java/com/sbg/arena/core/Arena.kt
|
SoulBeaver
| 17,563,154
| false
| null |
package com.sbg.arena.core
import com.sbg.arena.configuration.Configuration
import org.apache.logging.log4j.LogManager
import com.sbg.arena.core.procedural_content_generation.CaveGenerator
import com.sbg.arena.core.procedural_content_generation.Generator
import org.newdawn.slick.BasicGame
import org.newdawn.slick.GameContainer
import org.newdawn.slick.Graphics
import kotlin.properties.Delegates
import org.newdawn.slick.Color
import com.sbg.arena.core.level.Skin
import com.sbg.arena.core.geom.Point
import com.sbg.arena.core.geom.Rectangle
import org.newdawn.slick.state.StateBasedGame
import com.sbg.arena.core.state.MainMenuState
import com.sbg.arena.core.state.DefeatState
import com.sbg.arena.core.state.VictoryState
import com.sbg.arena.core.state.PlayerTurnState
import com.sbg.arena.core.state.EnemyTurnState
import com.google.common.eventbus.EventBus
import com.sbg.arena.core.enemy.Enemies
class Arena(val configuration: Configuration): StateBasedGame(configuration.gameTitle) {
private var logger = LogManager.getLogger(javaClass<Arena>())!!
private var levelGenerator: Generator by Delegates.notNull()
private var level: Level by Delegates.notNull()
private var levelSkin: Skin by Delegates.notNull()
private var renderer: Renderer by Delegates.notNull()
private var player: Player by Delegates.notNull()
private var enemies: Enemies by Delegates.notNull()
override fun initStatesList(gameContainer: GameContainer?) {
levelGenerator = when (configuration.levelGenerator) {
"cave" -> CaveGenerator(configuration)
else -> throw IllegalArgumentException("Generation strategy ${configuration.levelGenerator} not recognized")
}
level = levelGenerator.generate(Dimension(configuration.columns, configuration.rows))
logger.debug(level.toString())
levelSkin = Skin(configuration)
levelSkin.loadTiles()
player = Player(configuration)
level.placePlayer()
enemies = Enemies()
renderer = Renderer(configuration, level, levelSkin)
addState(MainMenuState(configuration))
addState(PlayerTurnState(configuration, level, player, enemies, renderer))
addState(EnemyTurnState(configuration, level, player, enemies, renderer))
addState(VictoryState(configuration))
addState(DefeatState(configuration))
}
}
| 0
|
Kotlin
|
0
| 0
|
6c9f35ab564ce1f5eab10b01ce932254fa76b068
| 2,393
|
Arena--7DRL-
|
Apache License 2.0
|
SmallStatusLayout/src/main/java/com/smallraw/library/smallstatuslayout/OnNotifyListener.kt
|
SmallRaw
| 248,648,347
| false
| null |
package com.smallraw.library.smallstatuslayout
fun interface OnNotifyListener<T> {
fun onNotify(statePage: T)
}
| 0
|
Kotlin
|
0
| 0
|
74e3f41ea80ecbfd1414b0899d56f4ed80e83f08
| 116
|
SmallStatusLayout
|
Apache License 2.0
|
app/src/main/java/com/lianyi/paimonsnotebook/card/service/ForegroundTest.kt
|
QooLianyi
| 435,314,581
| false
| null |
package com.lianyi.paimonsnotebook.card.service
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import com.lianyi.paimonsnotebook.R
class ForegroundTest:Service() {
private val channelId = "paimonsnootebook_channel_id_01"
private val channelName = "paimonsnootebook_channel_name_01"
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onCreate() {
getNotificationBuilder().apply {
setContentTitle("派蒙笔记本")
setContentText("前台服务测试")
setSmallIcon(R.drawable.icon_klee)
}.build().also {
startForeground(2,it)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY
}
private fun getNotificationBuilder():Notification.Builder{
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).apply {
createNotificationChannel(
NotificationChannel(channelId,channelName, NotificationManager.IMPORTANCE_HIGH)
)
}
Notification.Builder(this,channelId)
}else{
Notification.Builder(this)
}
}
}
| 1
|
Java
|
1
| 23
|
5319769a825ef05b6b28eba4a312a53a3420ce6b
| 1,475
|
PaimonsNotebook
|
Apache License 2.0
|
app/src/main/java/com/lianyi/paimonsnotebook/card/service/ForegroundTest.kt
|
QooLianyi
| 435,314,581
| false
| null |
package com.lianyi.paimonsnotebook.card.service
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import com.lianyi.paimonsnotebook.R
class ForegroundTest:Service() {
private val channelId = "paimonsnootebook_channel_id_01"
private val channelName = "paimonsnootebook_channel_name_01"
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onCreate() {
getNotificationBuilder().apply {
setContentTitle("派蒙笔记本")
setContentText("前台服务测试")
setSmallIcon(R.drawable.icon_klee)
}.build().also {
startForeground(2,it)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY
}
private fun getNotificationBuilder():Notification.Builder{
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).apply {
createNotificationChannel(
NotificationChannel(channelId,channelName, NotificationManager.IMPORTANCE_HIGH)
)
}
Notification.Builder(this,channelId)
}else{
Notification.Builder(this)
}
}
}
| 1
|
Java
|
1
| 23
|
5319769a825ef05b6b28eba4a312a53a3420ce6b
| 1,475
|
PaimonsNotebook
|
Apache License 2.0
|
app/src/main/kotlin/io/getstream/streamdraw/ui/screens/game/WordSelectionDialog.kt
|
GetStream
| 473,444,333
| false
|
{"Kotlin": 133141}
|
/*
* Copyright 2022 Stream.IO, Inc. 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.getstream.streamdraw.ui.screens.game
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.material.Card
import androidx.compose.material.Divider
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import io.getstream.streamdraw.R
import io.getstream.streamdraw.ui.components.SubtitleText
import io.getstream.streamdraw.ui.components.TitleText
import io.getstream.streamdraw.ui.theme.PrimaryColor
import timber.log.Timber
@Composable
fun WordSelectionDialog(
wordSelected: (selection: String) -> Unit,
words: List<String>
) {
Dialog(onDismissRequest = { }) {
WordSelectionDialogView(words = words, wordSelected)
}
}
@Composable
private fun WordSelectionDialogView(
words: List<String>,
wordSelected: (selection: String) -> Unit
) {
Card(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
) {
Column(
modifier = Modifier
.padding(24.dp)
.fillMaxWidth()
.wrapContentHeight()
) {
TitleText(text = stringResource(id = R.string.select_a_word))
Column(modifier = Modifier.padding(top = 18.dp)) {
words.forEach {
SubtitleText(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp),
text = it,
onClick = { wordSelected.invoke(it) }
)
Divider(color = PrimaryColor, thickness = 1.dp)
}
}
}
}
}
@Preview
@Composable
private fun DefaultPreview() {
WordSelectionDialogView(listOf("Pigeon", "Hammer", "Landslide")) { selection ->
Timber.d(selection)
}
}
| 0
|
Kotlin
|
22
| 333
|
76326e340854c9c7acd29b8df65f82a00b0679c5
| 2,803
|
stream-draw-android
|
Apache License 2.0
|
app/src/main/java/com/chuzhi/xzyx/ui/activity/WelcomeActivity.kt
|
wyh19950930
| 799,075,291
| false
|
{"Gradle": 5, "XML": 245, "Java Properties": 3, "Shell": 1, "Text": 2, "Ignore List": 5, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 9, "Kotlin": 59, "Java": 236, "Python": 2}
|
package com.chuzhi.xzyx.ui.activity
import android.Manifest
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.CountDownTimer
import android.provider.Settings
import android.view.View
import android.view.animation.AccelerateInterpolator
import com.tbruyelle.rxpermissions2.RxPermissions
import com.chuzhi.xzyx.R
import com.chuzhi.xzyx.api.AppCache
import com.chuzhi.xzyx.app.AppManager
import com.chuzhi.xzyx.app.MyApplication.Companion.getInstance
import com.chuzhi.xzyx.base.BaseActivity
import com.chuzhi.xzyx.base.BasePresenter
import com.chuzhi.xzyx.databinding.ActivityWelcomeBinding
import com.chuzhi.xzyx.ui.activity.login.LoginActivity
import com.chuzhi.xzyx.ui.bean.rc.ComputerListEntity
import com.chuzhi.xzyx.ui.presenter.WelcomePresenter
import com.chuzhi.xzyx.ui.view.WelcomeView
import com.chuzhi.xzyx.utils.*
import com.chuzhi.xzyx.utils.thread.AppExecutors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
class WelcomeActivity : BaseActivity<ActivityWelcomeBinding, WelcomePresenter>(), WelcomeView {
private var rxPermissions: RxPermissions? = null
private var permissionPop: AlertDialogIos? = null
private var animatorSet: AnimatorSet? = null
private var schedule: ScheduledFuture<*>? = null
private var jumpType = 0
override fun createPresenter(): WelcomePresenter {
return WelcomePresenter(this)
}
override fun initView() {
AppCache.getInstance().cardPath = GetFileUtil.getSDCardPath();
/*//状态栏透明
setStatusBarTransparent();
//状态栏字体颜色 true浅色 false深色
setStatusBarTextColor(false)*/
rxPermissions = RxPermissions(this)
permissionPop()
schedule = AppExecutors.getInstance().scheduledExecutor().schedule({
// jump()
}, 1510, TimeUnit.MILLISECONDS)
val alpha = PropertyValuesHolder.ofFloat("alpha", 0.3f, 1.0f)
val scaleX = PropertyValuesHolder.ofFloat("scaleX", 0.3f, 1.0f)
val scaleY = PropertyValuesHolder.ofFloat("scaleY", 0.3f, 1.0f)
val objectAnimator1 =
ObjectAnimator.ofPropertyValuesHolder(binding.llWelcomeScale, alpha, scaleX, scaleY)
// val objectAnimator2 = ObjectAnimator.ofPropertyValuesHolder(iv_logo, alpha, scaleX, scaleY)
// countDownTimer()
animatorSet = AnimatorSet()
animatorSet!!.playTogether(objectAnimator1)//, objectAnimator2
animatorSet!!.interpolator = AccelerateInterpolator()
animatorSet!!.duration = 1500
animatorSet!!.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animator: Animator) {
}
override fun onAnimationEnd(animator: Animator) {
/**
* 动画执行完毕回调
*/
if (jumpType == 0) {
jump()
}
}
override fun onAnimationCancel(animator: Animator) {
}
override fun onAnimationRepeat(animator: Animator) {
}
})
animatorSet!!.start()
binding.llWelcomeStart.setOnClickListener {
jumpType = 1
jump()
}
}
override fun initData() {
}
//倒计时的方式一
private var timer: CountDownTimer? = null
private fun countDownTimer() {
var num = 2
timer = object : CountDownTimer(num * 1000L, 1000L) {
override fun onTick(millisUntilFinished: Long) {
binding.btnWelcomeSecond.text =
(millisUntilFinished / 1000).toInt().toString() + "s"
if ((millisUntilFinished / 1000 - 1).toInt() == 0) {
// jump()
}
}
override fun onFinish() {
//有一到两秒延迟,所以把逻辑放到上面方法里
// jump()
}
}
timer?.start()
}
@SuppressLint("CheckResult")
private fun jump() {
val token = SpUtils.getSharedStringData(getInstance(), "Token")
if (token.isEmpty()) {
LoginActivity.startAction(this@WelcomeActivity)
AppManager.getAppManager().finishActivity(this@WelcomeActivity)
} else {
if (!NetworkUtils.isNetworkAvailable(this)) {
MainActivity.startAction(this@WelcomeActivity)
AppManager.getAppManager().finishActivity(this@WelcomeActivity)
} else {
presenter.userComputerList()
}
}
/*rxPermissions!!.request(
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
*//*Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION*//*
).subscribe { granted ->
if (granted) {
val token = SpUtils.getSharedStringData(getInstance(), "Token")
if (token.isEmpty()) {
LoginActivity.startAction(this@WelcomeActivity)
AppManager.getAppManager().finishActivity(this@WelcomeActivity)
} else {
MainActivity.startAction(this@WelcomeActivity)
AppManager.getAppManager().finishActivity(this@WelcomeActivity)
}
} else {
permissionPop!!.show()
}
}*/
}
private fun permissionPop() {
permissionPop = AlertDialogIos(this).builder()
.setTitle("开启权限")
.setMsg("小志云享需要访问存储、电话等相关权限以开启“设备定位等\"功能\n请在设置中开启权限")
// .setNegativeButton("取消", R.color.gray,null)
.setPositiveButton("设置", R.color.text_default, View.OnClickListener {
//跳转应用消息,间接打开应用权限设置-效率高
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri: Uri = Uri.fromParts("package", context.packageName, null)
intent.data = uri
context.startActivity(intent)
})
}
override fun onDestroy() {
super.onDestroy()
if (timer != null) {
timer!!.onFinish()
timer!!.cancel()
}
if (schedule != null) {
schedule!!.cancel(false)
}
}
//提前调用一下接口检测是否已在其他设备登录
override fun userComputerList(msg: ComputerListEntity?) {
MainActivity.startAction(this@WelcomeActivity)
AppManager.getAppManager().finishActivity(this@WelcomeActivity)
}
}
| 0
|
Java
|
0
| 0
|
7c71718a52f8da7c52e80b6ab859abbbc0c37241
| 6,907
|
Xz
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.