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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/irancell/nwg/ios/util/constants/GroupType.kt
|
afshin1394
| 755,443,887
| false
|
{"Kotlin": 803604}
|
package com.irancell.nwg.ios.util.constants
const val MAIN = 1
const val INNER = 2
const val PROBLEMATIC = 3
| 0
|
Kotlin
|
0
| 0
|
23a544780da643c4fa190bbe48d3bd9aa5673d88
| 109
|
Audit
|
MIT License
|
app/src/main/java/com/ecommerce/shopdaily/presentation/screens/main/shop/components/CategoryProduct.kt
|
milosursulovic
| 591,296,419
| false
|
{"Kotlin": 203950}
|
package com.ecommerce.shopdaily.presentation.screens.main.shop.components
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Favorite
import androidx.compose.material.icons.outlined.FavoriteBorder
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.ecommerce.shopdaily.domain.model.product.Product
import com.ecommerce.shopdaily.presentation.common.components.product.*
import com.ecommerce.shopdaily.presentation.screens.main.MainViewModel
@Composable
fun CategoryProduct(
viewModel: MainViewModel,
product: Product,
onProductClick: (Product) -> Unit,
onFavoriteClick: (Product) -> Unit,
onDeleteFavoriteClick: (Product) -> Unit
) {
val found = viewModel.favoritesState.favorites?.find { indexedProduct ->
indexedProduct.productId == product.productId && indexedProduct.category == product.category
}
Box(modifier = Modifier.fillMaxSize()) {
Card(
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.clickable { onProductClick(product) },
shape = RoundedCornerShape(20.dp),
elevation = 5.dp
) {
Row(
modifier = Modifier.background(color = MaterialTheme.colors.secondary),
verticalAlignment = Alignment.CenterVertically
) {
CardImage(
modifier = Modifier
.weight(1f)
.fillMaxSize(), product.image
)
Column(
modifier = Modifier
.weight(2f)
.fillMaxSize()
.padding(10.dp),
verticalArrangement = Arrangement.SpaceEvenly
) {
ProductTitle(product = product)
ProductSubtitle(product = product)
ProductRating(product = product)
ProductPrice(product = product)
}
}
}
CircularButton(
modifier = Modifier
.height(40.dp)
.width(40.dp)
.align(Alignment.BottomEnd)
.offset(x = 0.dp, y = 5.dp),
iconModifier = Modifier
.width(25.dp)
.height(25.dp),
icon = if (found != null) Icons.Outlined.Favorite else Icons.Outlined.FavoriteBorder,
tint = if (found != null) MaterialTheme.colors.primary else MaterialTheme.colors.onSecondary,
onClick = {
if (found != null) {
onDeleteFavoriteClick(product)
} else {
onFavoriteClick(product)
}
},
iconDrawable = null
)
}
}
| 33
|
Kotlin
|
0
| 0
|
a79e27bf415c223f5c4880635674e91579e0ec7d
| 3,222
|
shop-daily
|
MIT License
|
src/main/kotlin/com/imran/api/controllers/AuthController.kt
|
imran94
| 800,413,385
| false
|
{"Kotlin": 37483}
|
package com.imran.api.controllers
import com.imran.api.mail.EmailService
import com.imran.api.models.Role
import com.imran.api.models.User
import com.imran.api.models.UserToken
import com.imran.api.payload.request.LoginRequest
import com.imran.api.payload.request.RefreshTokenRequest
import com.imran.api.payload.request.RegistrationRequest
import com.imran.api.payload.response.ErrorResponse
import com.imran.api.payload.response.LoginResponse
import com.imran.api.payload.response.RegisterResponse
import com.imran.api.repos.UserRepository
import com.imran.api.repos.UserTokenRepository
import com.imran.api.security.JwtTokenService
import com.imran.api.security.JwtUserDetailsService
import jakarta.validation.Valid
import org.apache.commons.lang3.RandomStringUtils
import org.apache.commons.lang3.time.DateUtils
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.Calendar
@RestController
@RequestMapping("/auth")
class AuthController(
private val userRepo: UserRepository,
private val userTokenRepo: UserTokenRepository,
private val jwtUserDetailsService: JwtUserDetailsService,
private val jwtTokenService: JwtTokenService,
private val emailService: EmailService
) {
val passwordEncoder = BCryptPasswordEncoder()
@PostMapping("/register")
fun register(
@Valid @RequestBody request: RegistrationRequest
): ResponseEntity<Any>{
if ((request.role == Role.CUSTOMER && request.customer == null)
|| (request.role == Role.EMPLOYEE && request.employee == null)) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(ErrorResponse("Data for the selected role cannot be null"))
}
val user = User(
email = request.email,
username = request.username,
password = passwordEncoder.encode(request.password),
role = request.role
// ,
// customer = request.customer,
// employee = request.employee
)
userRepo.save(user)
emailService.sendEmail(
user.email,
"Verify your Email",
"Thank you for signing up for the app, ${user.username}"
)
return ResponseEntity.ok(user)
// return ResponseEntity.status(HttpStatus.CREATED)
// .body(
// RegisterResponse(
// user.id!!,
// user.email,
// user.username
// )
// )
}
@PostMapping("/authenticate")
fun login(@Valid @RequestBody loginDetails: LoginRequest)
: ResponseEntity<Any> {
val user: User = userRepo.findByUsername(loginDetails.username!!)
?: userRepo.findByEmail(loginDetails.username!!)
?: return ResponseEntity(ErrorResponse("Username not found"), HttpStatus.UNAUTHORIZED)
if (!passwordEncoder.matches(loginDetails.password, user.password)) {
return ResponseEntity(ErrorResponse("Incorrect password"), HttpStatus.UNAUTHORIZED)
}
val userDetails = jwtUserDetailsService.loadUserByUsername(user.username)
val accessToken = jwtTokenService.generateToken(userDetails)
val refreshToken = RandomStringUtils.randomAlphanumeric(30)
val userToken = UserToken(
accessToken,
refreshToken,
LocalDateTime.now().plusMinutes(2),
user
)
userTokenRepo.save(userToken)
return ResponseEntity.ok(
LoginResponse(
user.email,
user.username,
accessToken,
refreshToken,
userToken.expiresAt
)
)
}
@PostMapping("/refresh-token")
fun refreshToken(@Valid @RequestBody request: RefreshTokenRequest)
: ResponseEntity<Any> {
val userToken = userTokenRepo.findByRefreshToken(request.refreshToken)
?: return ResponseEntity(ErrorResponse("Token not found"), HttpStatus.UNAUTHORIZED)
val userDetails = jwtUserDetailsService.loadUserByUsername(userToken.user.username)
userToken.accessToken = jwtTokenService.generateToken(userDetails)
userToken.expiresAt = LocalDateTime.now().plusHours(2)
userTokenRepo.save(userToken)
return ResponseEntity.ok(
LoginResponse(
userToken.user.email,
userToken.user.username,
userToken.accessToken,
userToken.refreshToken,
userToken.expiresAt
)
)
}
}
| 0
|
Kotlin
|
0
| 0
|
6544e4194335c4ee386dd6296ebe5f8990959117
| 5,037
|
spring-boot-api
|
Apache License 2.0
|
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/Mdb.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36756847}
|
package compose.icons.lineawesomeicons
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 compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.Mdb: ImageVector
get() {
if (_mdb != null) {
return _mdb!!
}
_mdb = Builder(name = "Mdb", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp, viewportWidth
= 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(1.0801f, 9.0f)
lineTo(0.0801f, 21.0f)
lineTo(2.0879f, 21.0f)
lineTo(2.6445f, 14.3047f)
lineTo(5.3223f, 21.0f)
lineTo(6.6777f, 21.0f)
lineTo(9.3555f, 14.3047f)
lineTo(9.9121f, 21.0f)
lineTo(11.9199f, 21.0f)
lineTo(10.9199f, 9.0f)
lineTo(9.3223f, 9.0f)
lineTo(6.0f, 17.3086f)
lineTo(2.6777f, 9.0f)
lineTo(1.0801f, 9.0f)
close()
moveTo(14.0f, 9.0f)
lineTo(14.0f, 21.0f)
lineTo(16.0f, 21.0f)
curveTo(19.3016f, 21.0f, 22.0f, 18.3016f, 22.0f, 15.0f)
curveTo(22.0f, 11.6984f, 19.3016f, 9.0f, 16.0f, 9.0f)
lineTo(14.0f, 9.0f)
close()
moveTo(24.0f, 9.0f)
lineTo(24.0f, 14.0f)
lineTo(24.0f, 16.0f)
lineTo(24.0f, 21.0117f)
lineTo(28.4941f, 21.0117f)
curveTo(30.4186f, 21.0117f, 32.0f, 19.4303f, 32.0f, 17.5059f)
curveTo(32.0f, 16.236f, 31.2772f, 15.1642f, 30.2559f, 14.5488f)
curveTo(30.6921f, 13.965f, 31.0f, 13.2785f, 31.0f, 12.5f)
curveTo(31.0f, 10.5788f, 29.4212f, 9.0f, 27.5f, 9.0f)
lineTo(24.0f, 9.0f)
close()
moveTo(16.0f, 11.0f)
curveTo(18.2204f, 11.0f, 20.0f, 12.7796f, 20.0f, 15.0f)
curveTo(20.0f, 17.2204f, 18.2204f, 19.0f, 16.0f, 19.0f)
lineTo(16.0f, 11.0f)
close()
moveTo(26.0f, 11.0f)
lineTo(27.5f, 11.0f)
curveTo(28.3408f, 11.0f, 29.0f, 11.6592f, 29.0f, 12.5f)
curveTo(29.0f, 13.3408f, 28.3408f, 14.0f, 27.5f, 14.0f)
lineTo(26.0f, 14.0f)
lineTo(26.0f, 11.0f)
close()
moveTo(26.0f, 16.0f)
lineTo(27.5f, 16.0f)
lineTo(28.4941f, 16.0f)
curveTo(29.3377f, 16.0f, 30.0f, 16.6623f, 30.0f, 17.5059f)
curveTo(30.0f, 18.3494f, 29.3377f, 19.0117f, 28.4941f, 19.0117f)
lineTo(26.0f, 19.0117f)
lineTo(26.0f, 16.0f)
close()
}
}
.build()
return _mdb!!
}
private var _mdb: ImageVector? = null
| 15
|
Kotlin
|
20
| 460
|
651badc4ace0137c5541f859f61ffa91e5242b83
| 3,545
|
compose-icons
|
MIT License
|
ktor-crud-exposed-dao/backend/src/main/kotlin/com/onlyteo/sandbox/routes/GreetingRoutes.kt
|
onlyteo
| 798,100,309
| false
|
{"Kotlin": 269831, "TypeScript": 53023, "HTML": 46287, "CSS": 12071, "Shell": 627, "Dockerfile": 305}
|
package com.onlyteo.sandbox.routes
import com.onlyteo.sandbox.model.Person
import com.onlyteo.sandbox.service.GreetingService
import io.ktor.server.application.call
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.get
import io.ktor.server.routing.post
fun Route.greetingRoutes(greetingService: GreetingService) {
get("/api/greetings") {
val name = requireNotNull(call.parameters["name"]) { "Missing name parameter" }
val greetings = greetingService.findGreetings(name)
call.respond(greetings)
}
post("/api/greetings") {
val person = call.receive<Person>()
val greeting = greetingService.getGreeting(person)
call.respond(greeting)
}
}
| 0
|
Kotlin
|
0
| 0
|
e110b1cfaba2a5052c3758e912336295afa98e19
| 796
|
ktor-sandbox
|
Apache License 2.0
|
wallet-sdk/src/main/java/io/arcblock/walletkit/bean/CallBackResult.kt
|
ArcBlock
| 470,418,674
| false
| null |
package io.arcblock.walletkit.bean
import android.os.Parcel
import android.os.Parcelable
/**
*
* █████╗ ██████╗ ██████╗██████╗ ██╗ ██████╗ ██████╗██╗ ██╗
* ██╔══██╗██╔══██╗██╔════╝██╔══██╗██║ ██╔═══██╗██╔════╝██║ ██╔╝
* ███████║██████╔╝██║ ██████╔╝██║ ██║ ██║██║ █████╔╝
* ██╔══██║██╔══██╗██║ ██╔══██╗██║ ██║ ██║██║ ██╔═██╗
* ██║ ██║██║ ██║╚██████╗██████╔╝███████╗╚██████╔╝╚██████╗██║ ██╗
* ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝
* Author : ${EMAIL}
* Time : 2019-06-14
* Edited By :
* Edited Time :
* Description : Wallet App call back data
**/
const val RESULT_SUCCESS = 0
const val ERROR_WALLET = 100
const val ERROR_FORGE = 200
const val DATATYPE_HASH = 1
const val DATATYPE_CLAIM = 2
class CallBackResult(
val resultCode: Int,
val dataJson: String?,
val dataType: Int,
val errorInfo: String?
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readInt(),
parcel.readString(),
parcel.readInt(),
parcel.readString()
) {
}
fun verifyResult(): Boolean{
return true
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(resultCode)
parcel.writeString(dataJson)
parcel.writeInt(dataType)
parcel.writeString(errorInfo)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<CallBackResult> {
override fun createFromParcel(parcel: Parcel): CallBackResult {
return CallBackResult(parcel)
}
override fun newArray(size: Int): Array<CallBackResult?> {
return arrayOfNulls(size)
}
}
}
| 3
|
Kotlin
|
0
| 0
|
032105bd4ed9bbe4b484a3458eca67a875139f6f
| 1,685
|
did-wallet-sdk-android
|
Apache License 2.0
|
src/main/kotlin/com/broc/mcmod/McMod.kt
|
Brochu
| 795,748,209
| false
|
{"Kotlin": 12263, "Java": 1956}
|
package com.broc.mcmod
import net.fabricmc.api.ModInitializer
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents
import net.fabricmc.fabric.api.event.player.AttackBlockCallback
import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup
//import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents
import net.fabricmc.fabric.api.registry.FuelRegistry
import net.minecraft.block.AbstractBlock
import net.minecraft.block.Block
import net.minecraft.item.BlockItem
import net.minecraft.item.Item
//import net.minecraft.item.ItemGroups
import net.minecraft.item.ItemStack
import net.minecraft.registry.Registry
import net.minecraft.registry.Registries
import net.minecraft.text.Text
import net.minecraft.util.ActionResult
import net.minecraft.util.Identifier
import org.slf4j.LoggerFactory
object McMod : ModInitializer {
private val logger = LoggerFactory.getLogger("mcmod")
private val shop = DailyShop()
private val my_item = Registry.register(
Registries.ITEM,
Identifier("tutorial", "custom_item"),
CustomItem(Item.Settings().maxCount(16))
)
private val my_block = Registry.register(
Registries.BLOCK,
Identifier("tutorial", "shop_block"),
ShopBlock(AbstractBlock.Settings.create().strength(1.0f), shop)
)
private val shop_item = Registry.register(
Registries.ITEM,
Identifier("tutorial", "shop_item"),
BlockItem(my_block, Item.Settings())
)
override fun onInitialize() {
FuelRegistry.INSTANCE.add(my_item, 300)
// Add to current Item Group
//ItemGroupEvents.modifyEntriesEvent(ItemGroups.BUILDING_BLOCKS).register {
// content -> content.add(my_item)
//}
// Create new custom Item Group
val group = FabricItemGroup.builder()
.icon { ItemStack(my_item) }
.displayName(Text.translatable("itemGroup.tutorial.test_group"))
.entries { _, entries -> entries.add(my_item); entries.add(shop_item) }
.build()
Registry.register(
Registries.ITEM_GROUP,
Identifier("tutorial", "test_group"),
group
)
AttackBlockCallback.EVENT.register reg@{ player, world, _, pos, _ ->
val state = world.getBlockState(pos)
if (state.isToolRequired && !player.isSpectator && player.mainHandStack.isEmpty) {
player.damage(world.damageSources.magic(), 1.0f)
}
return@reg ActionResult.PASS
}
ServerLifecycleEvents.SERVER_STARTED.register reg@ { server ->
val props = server.saveProperties.mainWorldProperties
val currentHour = (props.timeOfDay / 1000) % 24
shop.init(currentHour.toInt())
logger.warn("DailyShop initialize complete")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
844766e08a2abe6f20ae535b732a5ad2b8860728
| 2,612
|
McMod
|
Apache License 2.0
|
grpc-order-management-service/src/main/kotlin/com/ribbontek/ordermanagement/repository/product/ProductRepository.kt
|
ribbontek
| 834,289,255
| false
|
{"Kotlin": 424897, "Shell": 26370, "HTML": 1565, "Dockerfile": 557, "PLpgSQL": 398}
|
package com.ribbontek.ordermanagement.repository.product
import com.ribbontek.ordermanagement.exception.NotFoundException
import com.ribbontek.ordermanagement.repository.abstracts.AdminEntityDeleteRepository
import com.ribbontek.shared.specdsl.equal
import com.ribbontek.shared.specdsl.get
import com.ribbontek.shared.specdsl.greaterThan
import com.ribbontek.shared.specdsl.greaterThanOrEqualTo
import com.ribbontek.shared.specdsl.isFalse
import com.ribbontek.shared.specdsl.isNotNull
import com.ribbontek.shared.specdsl.isNull
import com.ribbontek.shared.specdsl.join
import com.ribbontek.shared.specdsl.lessThanOrEqualTo
import com.ribbontek.shared.specdsl.like
import com.ribbontek.shared.specdsl.or
import com.ribbontek.shared.specdsl.where
import jakarta.persistence.criteria.CriteriaQuery
import jakarta.persistence.criteria.JoinType.INNER
import org.springframework.data.jpa.domain.Specification
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
import java.math.BigDecimal
import java.util.UUID
@Repository
interface ProductRepository : AdminEntityDeleteRepository<ProductEntity>, JpaSpecificationExecutor<ProductEntity> {
fun findByRequestId(requestId: UUID): ProductEntity?
@Query(
"""
select product from ProductEntity product
left join fetch product.discount discount
where product.id in (:ids)
"""
)
fun findEagerByIdIn(ids: List<Long>): List<ProductEntity>
}
fun ProductRepository.expectOneByRequestId(requestId: UUID): ProductEntity {
return findByRequestId(requestId) ?: throw NotFoundException("Could not find product with requestId $requestId")
}
object ProductEntitySpecs {
fun hasTitle(title: String?): Specification<ProductEntity>? =
title?.let {
ProductEntity::title.equal(it)
}
fun hasTitleLike(title: String?): Specification<ProductEntity>? =
title?.let {
ProductEntity::title.like("%$it%")
}
fun hasDescriptionLike(description: String?): Specification<ProductEntity>? =
description?.let {
ProductEntity::description.like("%$it%")
}
fun hasDeleted(deleted: Boolean?): Specification<ProductEntity>? =
deleted?.let {
ProductEntity::deleted.equal(it)
}
fun hasStock(hasStock: Boolean?): Specification<ProductEntity>? =
hasStock?.let {
if (it) ProductEntity::quantity.greaterThan(0) else ProductEntity::quantity.equal(0)
}
fun hasDiscount(hasDiscount: Boolean?): Specification<ProductEntity>? =
hasDiscount?.let {
if (it) ProductEntity::discount.isNotNull() else ProductEntity::discount.isNull()
}
fun hasPriceRangeStart(priceRangeStart: BigDecimal?): Specification<ProductEntity>? =
priceRangeStart?.let {
ProductEntity::price.greaterThanOrEqualTo(priceRangeStart)
}
fun hasPriceRangeEnd(priceRangeEnd: BigDecimal?): Specification<ProductEntity>? =
priceRangeEnd?.let {
ProductEntity::price.lessThanOrEqualTo(priceRangeEnd)
}
fun hasCategoryCode(categoryCode: String?): Specification<ProductEntity>? =
categoryCode?.let {
where {
it.joins.firstOrNull { join -> join.attribute.name == "category" && join.joinType.name == "INNER" }
?.get(CategoryEntity::code)?.let { equal(it, categoryCode) }
?: equal(it.join(ProductEntity::category).get(CategoryEntity::code), categoryCode)
}
}
fun joinCategory(): Specification<ProductEntity> =
Specification { root, criteriaQuery, criteriaBuilder ->
if (!criteriaQuery.isCount()) {
root.fetch<ProductEntity, CategoryEntity>(ProductEntity::category.name, INNER)
}
criteriaBuilder.conjunction()
}
fun hasKeywordIn(keywords: List<String>?): Specification<ProductEntity>? =
keywords?.let {
or(keywords.map(::hasKeyword))
}
fun hasKeyword(keyword: String?): Specification<ProductEntity>? =
keyword?.let {
or(
ProductEntity::description.like("%$keyword%"),
ProductEntity::title.like("%$keyword%")
)
}
fun notDeleted(): Specification<ProductEntity> = ProductEntity::deleted.isFalse()
private fun CriteriaQuery<*>.isCount(): Boolean =
resultType == Long::class.javaObjectType || resultType == Long::class.javaPrimitiveType
}
| 0
|
Kotlin
|
0
| 0
|
bf1562b2e915dd0dc98d4623c624fc60ab317770
| 4,624
|
grpc-course
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsresettlementpassportapi/data/interventionsapi/CRSAppointmentsDTO.kt
|
ministryofjustice
| 665,659,688
| false
|
{"Kotlin": 1341601, "Dockerfile": 1771}
|
package uk.gov.justice.digital.hmpps.hmppsresettlementpassportapi.data.interventionsapi
import com.fasterxml.jackson.annotation.JsonProperty
data class CRSAppointmentsDTO(
val crn: String,
val referral: List<ReferralAppointment>?,
)
data class ReferralAppointment(
@JsonProperty("referral_number")
val referralNumber: String,
@JsonProperty("intervention_title")
val interventionTitle: String,
@JsonProperty("appointment")
val appointment: List<CRSAppointment>,
)
data class CRSAppointment(
@JsonProperty("appointment_id")
val appointmentId: String,
@JsonProperty("appointment_date_time")
val appointmentDateTime: String?,
@JsonProperty("appointment_duration_in_minutes")
val appointmentDurationInMinutes: Int,
@JsonProperty("superseded_indicator")
val supersededIndicator: Boolean,
@JsonProperty("appointment_delivery_first_address_line")
val appointmentDeliveryFirstAddressLine: String,
@JsonProperty("appointment_delivery_second_address_line")
val appointmentDeliverySecondAddressLine: String,
@JsonProperty("appointment_delivery_town_city")
val appointmentDeliveryTownCity: String,
@JsonProperty("appointment_delivery_county")
val appointmentDeliveryCounty: String,
@JsonProperty("appointment_delivery_postcode")
val appointmentDeliveryPostCode: String,
)
| 0
|
Kotlin
|
2
| 1
|
e9ed7ceecdffd708a772698c98b368c5f1684ad1
| 1,317
|
hmpps-resettlement-passport-api
|
MIT License
|
app/src/main/java/com/example/counter/ui/home/HomeFragment.kt
|
LLuthfiY
| 307,921,665
| false
| null |
package com.example.counter.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.counter.R
class HomeFragment : Fragment() {
private lateinit var homeViewModel: HomeViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
setHasOptionsMenu(true);
val root = inflater.inflate(R.layout.fragment_home, container, false)
val textView: TextView = root.findViewById(R.id.text_home)
val add_button = root.findViewById<Button>(R.id.add_counter)
val remove_button = root.findViewById<Button>(R.id.remove_counter)
add_button.setOnClickListener {
var angka = textView.text.toString().toInt();
angka += 1
textView.text = angka.toString()
}
remove_button.setOnClickListener {
var angka = textView.text.toString().toInt();
angka -= 1
textView.text = angka.toString()
}
return root
}
}
| 0
|
Kotlin
|
0
| 0
|
d3df8916e75c8e77a958cfb1ddc2ac74df60e80b
| 1,411
|
counter
|
MIT License
|
app/src/main/java/com/dramtar/dogfreinds/data/local/LocalDataSource.kt
|
Dramtar
| 478,211,143
| false
| null |
package com.dramtar.dogfreinds.data.local
import androidx.paging.PagingSource
import kotlinx.coroutines.flow.Flow
/**
* Created by Dramtar on 15.03.2022
*/
interface LocalDataSource {
// User Table
fun getUsers(): PagingSource<Int, UserEntity>
suspend fun saveUsers(users: List<UserEntity>)
suspend fun saveUser(user: UserEntity)
fun getUserByID(id: Int): Flow<UserEntity?>
suspend fun lastUpdateUser(): Long
suspend fun deleteUserByEmail(email: String)
suspend fun deleteUser(user: UserEntity)
suspend fun deleteAllUsers()
suspend fun updateUser(user: UserEntity)
// Dog table
suspend fun insertDog(dogEntity: DogEntity)
suspend fun getDogByEmail(email: String): DogEntity?
suspend fun getAllDogs(): List<DogEntity>
}
| 0
|
Kotlin
|
0
| 0
|
72fc7789662bfbf61abb0511453dce8059e1f23c
| 792
|
DogFriends
|
The Unlicense
|
core/data/src/main/java/com/velosobr/core/data/auth/AuthInfoMapper.kt
|
velosobr
| 800,204,024
| false
|
{"Kotlin": 97413}
|
package com.velosobr.core.data.auth
import com.velosobr.core.domain.AuthInfo
fun AuthInfo.toSerializable(): AuthInfoSerializable {
return AuthInfoSerializable(
accessToken = accessToken,
refreshToken = refreshToken,
userId = userId
)
}
fun AuthInfoSerializable.toAuthInfo(): AuthInfo {
return AuthInfo(
accessToken = accessToken,
refreshToken = refreshToken,
userId = userId
)
}
| 0
|
Kotlin
|
0
| 0
|
7a8dd8800d09f730613997c9e4822f73cef60269
| 447
|
go-run
|
MIT License
|
src/main/kotlin/fr/netsah/photoServ/pojo/UserInfoDto.kt
|
KaratsuFr
| 85,851,648
| false
|
{"Kotlin": 26845, "JavaScript": 11871, "HTML": 6439, "CSS": 186}
|
package fr.netsah.photoServ.pojo
data class UserInfoDto(var username : String = "", var password : String = "", var mail: String? = null)
| 0
|
Kotlin
|
0
| 0
|
336b024994082fc119d7b57a43b1bcd20b2c5cbc
| 140
|
kyori
|
MIT License
|
app/src/main/java/com/hohoanghai/weatherforecast/ui/detail/DetailFragment.kt
|
hhhai0304
| 837,168,132
| false
|
{"Kotlin": 30842}
|
package com.hohoanghai.weatherforecast.ui.detail
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.hohoanghai.weatherforecast.R
import com.hohoanghai.weatherforecast.databinding.FragmentDetailBinding
import com.hohoanghai.weatherforecast.ui.detail.viewmodel.DetailViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
class DetailFragment : Fragment() {
private val viewModel: DetailViewModel by viewModel()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding = FragmentDetailBinding.inflate(inflater)
binding.lifecycleOwner = this
binding.viewModel = viewModel
binding.apply {
toolbar.setNavigationOnClickListener {
findNavController().navigate(R.id.listFragment)
}
btnRetry.setOnClickListener {
viewModel!!.getCurrentWeather()
}
}
val city = DetailFragmentArgs.fromBundle(requireArguments()).selectedCity
viewModel.getCurrentWeather(city)
return binding.root
}
}
| 0
|
Kotlin
|
0
| 0
|
befe5d576c686d3692c6c85b71ae33fc8551faea
| 1,300
|
WeatherForecast
|
MIT License
|
app/src/main/java/com/ryanhtech/vocabulario/tools/quiz/QuizPlay.kt
|
Ryanhtech
| 445,900,317
| false
|
{"Kotlin": 414071}
|
/*
* Copyright 2021-2022 Ryanhtech Labs
*
* 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.ryanhtech.vocabulario.tools.quiz
import android.content.Context
import com.ryanhtech.vocabulario.tools.collection.CollectionWord
import com.ryanhtech.vocabulario.tools.collection.wordpointers.CollectionWordContentManager
class QuizPlay(words: List<CollectionWord>) {
private val mWordsToPass: MutableList<CollectionWord> = words.toMutableList()
fun getRandomWord(): CollectionWord {
val randomIndex = (0..mWordsToPass.size).random()
val chosenWord = mWordsToPass[randomIndex]
mWordsToPass.removeAt(randomIndex) // Remove the word because we played it
return chosenWord
}
companion object {
fun cookInstance(context: Context): QuizPlay {
/**
* Cook an instance of QuizPlay. We cook it because
* we proceed to the instantiation by ourselves, like
* a chef cooking his cake. He doesn't get it from nowhere,
* instead, he makes it himself (good chefs do).
*/
// Ingredient #1: word pointers
// We get the word pointers from the CollectionWordContentManager.
val pointers = CollectionWordContentManager.listPointersAndContent(context)
// Then, we select the words to put in the quiz. For that, call our friend
// QuizContentSelector.
var pickedWords: List<CollectionWord>? = null
try {
pickedWords = CollectionWordContentManager.convertWordPointerListToWordList(
QuizContentSelector.pickAdaptedWords(pointers))
} catch (e: IllegalStateException) {
// Pass for now...
}
if (pickedWords == null) throw NullPointerException(
"pickedWords is null; cannot give burned cake to waiter (an IllegalStateException " +
"has been thrown from QuizContentSelector.pickAdaptedWords(pointers))\n" +
"Technical info: context = $context\npointers = $pointers")
return QuizPlay(pickedWords)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
0822b13273167e0db581b42ebf6f8219e8f509d7
| 2,686
|
vocabulario
|
Apache License 2.0
|
stream-chat-android-offline/src/main/java/io/getstream/chat/android/offline/repository/database/converter/internal/MapConverter.kt
|
GetStream
| 177,873,527
| false
|
{"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229}
|
/*
* Copyright (c) 2014-2022 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* 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.chat.android.offline.repository.database.converter.internal
import androidx.room.TypeConverter
import com.squareup.moshi.adapter
import io.getstream.chat.android.offline.repository.domain.channel.member.internal.MemberEntity
import io.getstream.chat.android.offline.repository.domain.channel.userread.internal.ChannelUserReadEntity
internal class MapConverter {
@OptIn(ExperimentalStdlibApi::class)
private val stringMapAdapter = moshi.adapter<Map<String, String>>()
@OptIn(ExperimentalStdlibApi::class)
private val intMapAdapter = moshi.adapter<Map<String, Int>>()
@OptIn(ExperimentalStdlibApi::class)
private val channelUserReadMapAdapter = moshi.adapter<Map<String, ChannelUserReadEntity>>()
@OptIn(ExperimentalStdlibApi::class)
private val memberEntityMapAdapter = moshi.adapter<Map<String, MemberEntity>>()
@TypeConverter
fun readMapToString(someObjects: Map<String, ChannelUserReadEntity>?): String? {
return channelUserReadMapAdapter.toJson(someObjects)
}
@TypeConverter
fun stringToReadMap(data: String?): Map<String, ChannelUserReadEntity>? {
if (data.isNullOrEmpty() || data == "null") {
return mutableMapOf()
}
return channelUserReadMapAdapter.fromJson(data)
}
@TypeConverter
fun memberMapToString(someObjects: Map<String, MemberEntity>?): String? {
return memberEntityMapAdapter.toJson(someObjects)
}
@TypeConverter
fun stringToMemberMap(data: String?): Map<String, MemberEntity>? {
if (data.isNullOrEmpty() || data == "null") {
return emptyMap()
}
return memberEntityMapAdapter.fromJson(data)
}
@TypeConverter
fun stringToMap(data: String?): Map<String, Int>? {
if (data.isNullOrEmpty() || data == "null") {
return mutableMapOf()
}
return intMapAdapter.fromJson(data)
}
@TypeConverter
fun mapToString(someObjects: Map<String, Int>?): String? {
return intMapAdapter.toJson(someObjects)
}
@TypeConverter
fun stringToStringMap(data: String?): Map<String, String>? {
if (data.isNullOrEmpty() || data == "null") {
return mutableMapOf()
}
return stringMapAdapter.fromJson(data)
}
@TypeConverter
fun stringMapToString(someObjects: Map<String, String>?): String? {
return stringMapAdapter.toJson(someObjects)
}
}
| 24
|
Kotlin
|
273
| 1,451
|
8e46f46a68810d8086c48a88f0fff29faa2629eb
| 3,079
|
stream-chat-android
|
FSF All Permissive License
|
detektive/src/test/kotlin/cash/detektive/javacompat/AnnotatePublicApisWithJvmOverloadsTest.kt
|
cashapp
| 113,107,217
| false
|
{"Kotlin": 3843790, "TypeScript": 232251, "Java": 83564, "JavaScript": 5073, "Shell": 3462, "HTML": 1536, "CSS": 58}
|
package cash.detektive.javacompat
import cash.detektive.javacompat.AnnotatePublicApisWithJvmOverloads.ElementType
import io.github.detekt.parser.DetektPomModel
import io.github.detekt.test.utils.compileForTest
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.internal.CompilerResources
import io.gitlab.arturbosch.detekt.rules.KotlinCoreEnvironmentTest
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import io.gitlab.arturbosch.detekt.test.getContextForPaths
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.com.intellij.mock.MockProject
import org.jetbrains.kotlin.com.intellij.openapi.diagnostic.Logger
import org.jetbrains.kotlin.com.intellij.pom.PomModel
import org.jetbrains.kotlin.config.CompilerConfigurationKey
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactoryImpl
import org.jetbrains.kotlin.utils.PrintingLogger
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
import java.io.File
@KotlinCoreEnvironmentTest
internal class AnnotatePublicApisWithJvmOverloadsTest(private val env: KotlinCoreEnvironment) {
@BeforeEach
fun setUp() {
}
@Test
fun testAutoCorrect() {
(env.project as MockProject).registerService(PomModel::class.java, DetektPomModel(env.project))
env.configuration.add(CompilerConfigurationKey(Config.AUTO_CORRECT_KEY), true)
val languageVersionSettings = env.configuration.languageVersionSettings
val ktFile = compileForTest(
File("src/test/kotlin/cash/detektive/javacompat/TestCode.kt").toPath()
)
AnnotatePublicApisWithJvmOverloads(TestConfig(Config.AUTO_CORRECT_KEY to true)).visitFile(
ktFile,
env.getContextForPaths(listOf(ktFile)),
CompilerResources(languageVersionSettings, DataFlowValueFactoryImpl(languageVersionSettings))
)
val modifiedContents = ktFile.viewProvider.contents
assertThat(modifiedContents).contains(
"class TestCode @JvmOverloads constructor(val things: List<String> = emptyList())"
)
assertThat(modifiedContents).contains("@JvmOverloads\n fun doIt")
}
@ParameterizedTest
@MethodSource("errorTestCases")
fun reportsError(testCase: ErrorTestCase) {
val findings =
AnnotatePublicApisWithJvmOverloads(Config.empty).compileAndLintWithContext(env, testCase.code)
assertThat(findings).hasSize(1)
with(findings[0]) {
assertThat(issue.severity).isEqualTo(Severity.Defect)
assertThat(issue.id).isEqualTo("AnnotatePublicApisWithJvmOverloads")
assertThat(entity.signature).contains(testCase.elementName)
assertThat(message).contains(
"Public ${testCase.elementType.name.lowercase()} '${testCase.elementName}' " +
"with default arguments, but without @JvmOverloads annotation"
)
}
}
@ParameterizedTest
@MethodSource("noErrorTestCases")
fun doesntReportsError(testCase: NoErrorTestCase) {
val findings =
AnnotatePublicApisWithJvmOverloads(Config.empty).compileAndLintWithContext(env, testCase.code)
assertThat(findings).hasSize(0)
}
companion object {
data class ErrorTestCase(
val description: String,
val elementType: ElementType,
val elementName: String,
val code: String
)
private var defaultLoggerFactory = Logger.getFactory()
@BeforeAll
@JvmStatic
fun beforeAll() {
Logger.setFactory { PrintingLogger(System.out) }
}
@AfterAll
@JvmStatic
fun afterAll() {
Logger.setFactory(defaultLoggerFactory)
}
@JvmStatic
fun errorTestCases() = listOf(
ErrorTestCase(
description = "Public function with any default arguments, but without @JvmOverloads",
elementType = ElementType.FUNCTION,
elementName = "doIt",
code = """
class A {
public fun doIt(x: String = "", y: Int) {}
}
"""
),
ErrorTestCase(
description = "Public constructor with any default arguments, but without @JvmOverloads",
elementType = ElementType.CONSTRUCTOR,
elementName = "Subject",
code = """
class Subject(x: String = "", y: Int) {}
"""
)
)
data class NoErrorTestCase(val description: String, val code: String)
@JvmStatic
fun noErrorTestCases() = listOf(
//Functions
NoErrorTestCase(
description = "Public function without default arguments",
code = """
class A {
public fun doIt(x: String, y: Int) {}
}
"""
),
NoErrorTestCase(
description = "Public function with default arguments and with @JvmOverloads",
code = """
class A {
@JvmOverloads
public fun doIt(x: String = "", y: Int) {}
}
"""
),
NoErrorTestCase(
description = "Private function with default arguments",
code = """
class A {
private fun doIt(x: String = "", y: Int) {}
}
"""
),
NoErrorTestCase(
description = "Protected function with default arguments",
code = """
class A {
protected fun doIt(x: String = "", y: Int) {}
}
"""
),
NoErrorTestCase(
description = "Public function in an interface",
code = """
interface A {
fun doIt(x: String = "")
}
"""
),
NoErrorTestCase(
description = "Public function in a private class",
code = """
private class A {
fun doIt(x: String = "") = {}
}
"""
),
//Constructors
NoErrorTestCase(
description = "Public constructor annotated with javax Inject",
code = """
import jakarta.inject.Inject
class Subject @Inject constructor(x: String = "", y: Int) {}
"""
),
NoErrorTestCase(
description = "Public constructor annotated with jakarta Inject",
code = """
import jakarta.inject.Inject
class Subject @Inject constructor(x: String = "", y: Int) {}
"""
),
NoErrorTestCase(
description = "Public constructor annotated with guice Inject",
code = """
import jakarta.inject.Inject
class Subject @Inject constructor(x: String = "", y: Int) {}
"""
),
NoErrorTestCase(
description = "Public constructor without default arguments",
code = """
class Subject(x: String, y: Int) {}
"""
),
NoErrorTestCase(
description = "Public annotation constructor with default arguments and without @JvmOverloads",
code = """
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class Authenticated(
val services: Array<String> = [],
val capabilities: Array<String> = []
)
"""
),
NoErrorTestCase(
description = "Public constructor with default arguments and with @JvmOverloads",
code = """
class Subject @JvmOverloads constructor(x: String, y: Int = 0) {}
"""
),
NoErrorTestCase(
description = "Private constructor with default arguments, but without @JvmOverloads",
code = """
class Subject private constructor(x: String, y: Int = 0) {}
"""
),
NoErrorTestCase(
description = "Internal class constructor with default arguments, but without @JvmOverloads",
code = """
internal class Subject constructor(x: String, y: Int = 0) {}
"""
)
)
}
}
| 169
|
Kotlin
|
169
| 400
|
13dcba0c4e69cc2856021270c99857e7e91af27d
| 8,053
|
misk
|
Apache License 2.0
|
src/chapter5/section1/ex19_RandomCALicensePlates.kt
|
w1374720640
| 265,536,015
| false
|
{"Kotlin": 1373556}
|
package chapter5.section1
import extensions.random
/**
* 随机的加利福尼亚州车牌号
* 编写一个静态方法randomPlatesCA,接受一个整型参数N并返回一个含有N个字符串的数组,
* 每个字符串都是与本节的示例类似的加利福尼亚州的车牌号。
*/
fun ex19_RandomCALicensePlates(N: Int): Array<String> {
return Array(N) {
val stringBuilder = StringBuilder()
stringBuilder.append(random(10))
repeat(3) {
// 生成随机大写字母
stringBuilder.append(random('A'.toInt(), 'Z'.toInt() + 1).toChar())
}
repeat(3) {
stringBuilder.append(random(10))
}
stringBuilder.toString()
}
}
fun main() {
val N = 20
val array = ex19_RandomCALicensePlates(N)
println(array.joinToString(separator = "\n"))
}
| 0
|
Kotlin
|
1
| 6
|
879885b82ef51d58efe578c9391f04bc54c2531d
| 699
|
Algorithms-4th-Edition-in-Kotlin
|
MIT License
|
src/kotlin/mati/advancedgdx/assets/FontLoader.kt
|
matiuri
| 48,175,334
| false
| null |
/**
* Copyright 2015 Matías Steinberg
*
* 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 mati.advancedgdx.assets
import com.badlogic.gdx.assets.AssetDescriptor
import com.badlogic.gdx.assets.AssetLoaderParameters
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.assets.loaders.AsynchronousAssetLoader
import com.badlogic.gdx.assets.loaders.FileHandleResolver
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter
import mati.advancedgdx.assets.FontLoader.FontLoaderParameter
/**
* This class creates a [BitmapFont]. You shouldn't do anything with this, but you must create a [FontLoaderParameter]
* with the [FreeTypeFontGenerator] file name and a [FreeTypeFontParameter]. If you are in Kotlin, you can set the
* fields of the [FreeTypeFontParameter] with a lambda.
*
* To load the [FreeTypeFontGenerator], you'll have to queue it:
*
* astManager.queue("«name of your generator»", "«path to your ttf»", FreeTypeFontGenerator::class)
*
* Then, you'll have to queue a [BitmapFont]:
*
* astManager.queue("«name of your font»", "«a single path»", BitmapFont::class,
* FontLoaderParameter(astManager.get("«alias of the ttf»")) { it.color = ...
* /*Set all the properties here.*/
* })
*
* Note: the path won't be used, but must be unique so that the [AssetManager] can get exactly the font you want,
* because it uses the path as identifier.
*
* Remember: In Java, *::class* must be written as *.class*. Also, you can't use lambdas, so you'll have to use the
* default non-arguments constructor and set the properties manually.
*/
public class FontLoader(resolver: FileHandleResolver)
: AsynchronousAssetLoader<BitmapFont, FontLoaderParameter>(resolver) {
override fun loadSync(manager: AssetManager?, fileName: String?, file: FileHandle?,
parameter: FontLoaderParameter?): BitmapFont? {
if (parameter == null) throw IllegalArgumentException("Parameter mustn't be null")
val generator: FreeTypeFontGenerator = manager!![parameter.path, FreeTypeFontGenerator::class.java]
return generator.generateFont(parameter.param)
}
override fun loadAsync(manager: AssetManager?, fileName: String?, file: FileHandle?,
parameter: FontLoaderParameter?) {
if (parameter == null) throw IllegalArgumentException("Parameter mustn't be null")
}
override fun getDependencies(fileName: String?, file: FileHandle?, parameter: FontLoaderParameter?)
: com.badlogic.gdx.utils.Array<AssetDescriptor<out Any>>? {
val deps: com.badlogic.gdx.utils.Array<AssetDescriptor<out Any>> = com.badlogic.gdx.utils.Array()
deps.add(AssetDescriptor<FreeTypeFontGenerator>(parameter?.path, FreeTypeFontGenerator::class.java))
return deps
}
/**
* You must pass an instance of this class to the [AssetLoader]
*/
public class FontLoaderParameter() : AssetLoaderParameters<BitmapFont>() {
public var path: String = ""
public var param: FreeTypeFontParameter = FreeTypeFontParameter()
public constructor(path: String, fun_: (FreeTypeFontParameter) -> Unit) : this() {
this.path = path
fun_(param)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3bf28bbfb70c7693ac7ed2db361c7410376a98e7
| 3,803
|
AdvancedGDX
|
Apache License 2.0
|
app/src/main/java/com/iolll/kit/xidingRv/RVDis2.kt
|
liuyouth
| 185,177,615
| false
|
{"Java": 96198, "Kotlin": 62821}
|
package com.iolll.ki
import android.graphics.Canvas
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.iolll.kit.Utils
import com.iolll.kit.xidingRv.Title
import com.iolll.kit.xidingRv.TopBarCallBack
import com.iolll.kit.xidingRv.VirtualFamily
import com.iolll.liubo.bottomrecyclerdialog.DensityUtils
import com.safframework.log.L
/**
* 因为是提前让view 置顶 所以采用的是 判断屏幕上第二个view 的顶部距离
* Created by LiuBo on 2019-05-23.
*/
class RVDis2(
val items: List<Any>,
private val toolbar: LinearLayout,
private val layout: LinearLayout,
private val root: TextView,
private var layoutManage: LinearLayoutManager,
private var virtualFamily: VirtualFamily,
private var onTopBarCallBack: TopBarCallBack,
private val callBack: HeaderCallBack<Title>
) : RecyclerView.ItemDecoration() {
private var headerPosition: Int = -1
var toTop: Int = 0
val headerHeight = DensityUtils.dp2px(Utils.getContext(), 50f)
val headerBottomY = DensityUtils.dp2px(Utils.getContext(), 100f)
val toolbarBottomY = DensityUtils.dp2px(Utils.getContext(), 50f)
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDrawOver(c, parent, state)
val firstPos = layoutManage.findFirstVisibleItemPosition()
val secondPos = layoutManage.findFirstVisibleItemPosition() + 1
val endPos = layoutManage.findLastVisibleItemPosition()
val fristHeaderPos = virtualFamily.childParentPosition(firstPos)
val secondHeaderPos = virtualFamily.childParentPosition(secondPos)
println("endPos $endPos header $fristHeaderPos SePos$secondPos header $secondHeaderPos")
if (firstPos == 0) {
val view = layoutManage.findViewByPosition(firstPos)
if(null!=view) {
toTop = -view.top
L.e("第一个 toTop$toTop toolbarBottomY$toolbarBottomY")
if (toTop<=(headerBottomY*3)){
toolbar.translationY = -toolbarBottomY.toFloat()
toolbar.visibility = View.GONE
}else {
toolbar.visibility = View.VISIBLE
toolbar.translationY = 0f
}
}
}else{
if (endPos < secondPos) {
// 即 该页面只有一个view 的情况
} else {
// 目前方法只有置顶类型处于第二view 才会进去流程
println(" se$secondPos isHeader${isHeader(items[secondPos])} ")
if (isHeader(items[secondPos])) {
val view = layoutManage.findViewByPosition(secondPos)
with(view) {
if (this != null) {
toTop = top
// val transY = (-headerBottomY - toTop).toFloat()
println("headerBottomY ${headerBottomY} toolbarBottomY ${toolbarBottomY} top$top height$height toTop ${toTop}")
if (toTop <= headerBottomY) {
if (toTop <= toolbarBottomY) {
secondTitleTouchedToolbar(view!!,
getTitle(secondHeaderPos), toTop.toFloat(),
if (fristHeaderPos != -1) (items[fristHeaderPos] as Title) else null,
layout, toolbar, callBack
)
} else {
secondTitleTouchedHeader(
items[secondPos] as Title, toTop.toFloat(),
if (fristHeaderPos != -1) (items[fristHeaderPos] as Title) else null,
layout, toolbar, callBack
)
}
} else {
// 处理第二个view 没有 滑动到 置顶区域的情况
// 获取第一个view 的 置顶类型 进行显示
val firstTitlePos = virtualFamily.childParentPosition(firstPos)
if (-1 != fristHeaderPos) {
if (isHeader(items[firstTitlePos])) {
secondTitleUntouchedHeader(
items[firstTitlePos] as Title,
toTop.toFloat(),
items[virtualFamily.childParentPosition(firstTitlePos)] as Title,
layout,
toolbar,
callBack
)
} else {
layout.visibility = View.INVISIBLE
toolbar.visibility = View.INVISIBLE
}
} else {
layout.visibility = View.INVISIBLE
toolbar.visibility = View.INVISIBLE
}
}
}
// view == null 的情况不会出现 在上面判断了边界
}
} else {
if (-1 != fristHeaderPos)
if (isHeader(items[fristHeaderPos])) {
L.e("fristHeaderPos $fristHeaderPos isHeader ${isHeader(items[fristHeaderPos])} firstPos $firstPos ")
val view = layoutManage.findViewByPosition(firstPos)
if (null != view) {
val ti = getTitle(fristHeaderPos)
if (null != ti) {
if (ti.isHeader) {
// view.top.toFloat()-headerHeight
if (ti.isTop) {
toolbar.translationY = 0f
toolbar.visibility = View.VISIBLE
// 投递数据
//修复位置错位
layout.translationY = (-headerHeight).toFloat()
layout.visibility = View.VISIBLE
} else {
layout.translationY = 0f
layout.visibility = View.VISIBLE
}
}
}
}
} else {
layout.visibility = View.INVISIBLE
toolbar.visibility = View.INVISIBLE
}
// layout.visibility = View.INVISIBLE
// toolbar.visibility = View.INVISIBLE
// 非置顶类型处于第二位置 并且在 限定范围外
}
}
}
}
/**
* 此处的title 是 frist的Group数据 和 headerTitle 一样
* 第二view Title 未接触 Header 固定状态
*/
fun secondTitleUntouchedHeader(
title: Title,
y: Float,
headerTitle: Title,
headerView: View,
toolBar: View,
callBack: HeaderCallBack<Title>
) {
L.e("secondTitleUntouchedHeader ")
if (null != headerTitle) {
callBack.onHeaderCallBack(headerTitle)
headerView.visibility = View.VISIBLE
} else {
headerView.visibility = View.INVISIBLE
}
if (headerTitle.isTop) {
// toolBar.translationY = if (headerTitle.isTop) y + toolbarBottomY else 0f
toolBar.translationY = 0f
headerView.translationY = (-headerHeight).toFloat()
} else {
toolBar.translationY = 0f
headerView.translationY = 0f
}
}
/**
* title 是 第二个的数据
* headertitle 是当前吸顶的数据
* 第二view Title 接触 Header
*/
fun secondTitleTouchedHeader(
title: Title,
y: Float,
headerTitle: Title?,
headerView: View,
toolBar: View,
callBack: HeaderCallBack<Title>
) {
L.e("secondTitleTouchedHeader ")
if (null != headerTitle) {
callBack.onHeaderCallBack(headerTitle)
headerView.visibility = View.VISIBLE
} else {
headerView.visibility = View.INVISIBLE
}
if (title.isHeader) {
if (title.isTop) {
// 当两个top 相同时
if (headerTitle?.name == title.name)
if (headerTitle.isTop) {
toolbar.translationY = (-headerHeight).toFloat()
}
if (headerTitle?.isTop == true) {
headerView.translationY = (-headerHeight).toFloat()
} else {
if (null == headerTitle) {
toolBar.translationY = (-headerHeight).toFloat()
} else {
headerView.translationY = y - headerHeight * 2
toolBar.translationY = 0f
}
}
} else {
if (headerTitle?.isTop == true) {
headerView.translationY = (-headerHeight).toFloat()
} else {
headerView.translationY = y - headerHeight * 2
toolBar.translationY = 0f
}
}
}
}
/**
*
* 第二view Title 接触 Toolbar
*/
fun secondTitleTouchedToolbar(
view:View,
title: Title?,
y: Float,
headerTitle: Title?,
headerView: View,
toolBar: View,
callBack: HeaderCallBack<Title>
) {
if (null != title) {
callBack.onHeaderCallBack(title)
headerView.visibility = View.VISIBLE
} else {
headerView.visibility = View.INVISIBLE
}
L.e("secondTitleTouchedToolbar ${title?.isTop == true} $title yy $y headerTitle$headerTitle")
if (title?.isTop == true) {
// toolBar.visibility = View.INVISIBLE
// y == 150 toolbarBottomY ==headerHeight== 150 y - headerHeight = 0
// y == 140 150 y - 150 = -10
toolBar.translationY = y - toolbarBottomY
headerView.translationY = y - headerHeight
onTopBarCallBack.callback(headerView,toolbarBottomY-y,title)
// 当两个istop 数据 相同时
if (headerTitle?.name ?: "" == title.name)
if (headerTitle?.isTop == true) {
toolbar.translationY = (-headerHeight).toFloat()
}
} else {
toolbar.translationY = 0f
headerView.translationY = 0f
}
}
// 首先是 距离维度的判断
/**
* 第二view Title 未接触 Header 固定状态
* 第二view Title 接触 Header
* 第二view Title 接触 Toolbar
* 第二view Title 滑过 Toolbar 固定状态 等于 第一个 因为第二view换view了
*/
// 以下的是 距离的问题
// 然后事当前 header 置顶类型判断
/**
* 是子类
* 是title
* 是置顶
*/
// 然后事第二view 判断
/**
* 是子类
* 是title
* 是置顶
*/
/**
* 3*3*4 36 种场景
*
*/
private fun setHeaderData(data: String): String {
// layout.visibility = if (isEmpty(data)) View.INVISIBLE else View.VISIBLE
return data
}
interface HeaderCallBack<T> {
fun onHeaderCallBack(t: T)
}
public fun isHeader(any: Any): Boolean {
return if (any is Title) {
return any.isHeader
} else false
}
public fun isTop(any: Any): Boolean {
return if (any is Title) {
return any.isTop
} else false
}
fun getTitle(index: Int): Title? {
return if (index != -1) {
items[index] as Title
} else null
}
}
| 1
| null |
1
| 1
|
1dedc210a01c81dce4485dd2f1a369f42a952a7e
| 12,204
|
IolllKit
|
Apache License 2.0
|
core/src/main/kotlin/org/kotlinq/api/PrintingConfiguration.kt
|
prestongarno
| 98,687,463
| false
|
{"Git Config": 1, "Gradle": 10, "XML": 1, "Shell": 2, "Ignore List": 1, "Batchfile": 1, "YAML": 2, "Text": 1, "Markdown": 8, "Kotlin": 130, "GraphQL": 3, "Java": 5, "ANTLR": 2, "Java Properties": 1, "INI": 1}
|
package org.kotlinq.api
/**
* Added to support different requirements by endpoints
*
* Options supported by both:
* * Quotation character
* * Escape quotation marks
* Pretty Print options:
* * Indent
*/
class PrintingConfiguration private constructor(builder: Builder) {
val pretty: Boolean = builder.pretty
val indent: String = builder.indent
val quotationCharacter = builder.quotationCharacter
val argumentSeparator = builder.argumentSeparator
val commaSeparator = builder.commaSeparator
val spreadOnFragmentOperator = builder.spreadOnFragmentOperator
val lcurlyChar = builder.lcurlyChar
val rcurlyChar = builder.rcurlyChar
val metaStrategy = builder.metaStrategy
fun toBuilder() = Builder()
.pretty(pretty)
.indent(indent)
.quotationCharacter(quotationCharacter)
.argumentSeparator(argumentSeparator)
.commaSeparator(commaSeparator)
.spreadOnFragmentOperator(spreadOnFragmentOperator)
.lcurlyChar(lcurlyChar)
.rcurlyChar(rcurlyChar)
.metaStrategy(metaStrategy)
/**
* Builder for a [PrintingConfiguration].
*/
class Builder internal constructor() {
// TODO dedup
internal var metaStrategy: Printer.MetaStrategy = Printer.MetaStrategy.STANDARD
internal var pretty: Boolean = false
internal var indent: String = " "
internal var quotationCharacter: String = "\""
internal var argumentSeparator: String = ": "
internal var spreadOnFragmentOperator: String = "... on "
internal var commaSeparator: String = ","
internal var lcurlyChar: Char = '{'
internal var rcurlyChar: Char = '}'
fun metaStrategy(it: Printer.MetaStrategy) = apply { metaStrategy = it }
fun quotationCharacter(it: String) = apply { quotationCharacter = it }
fun pretty(it: Boolean = false) = apply { pretty = it }
fun argumentSeparator(it: String) = apply { argumentSeparator = it }
fun spreadOnFragmentOperator(it: String) = apply { spreadOnFragmentOperator = it }
fun commaSeparator(it: String) = apply { commaSeparator = it }
fun indent(it: String) = apply { indent = it }
fun lcurlyChar(it: Char) = apply { lcurlyChar = it }
fun rcurlyChar(it: Char) = apply { rcurlyChar = it }
fun build() = PrintingConfiguration(this)
}
companion object {
fun builder() = PrintingConfiguration.Builder()
/**
* Double quotations (escaped), includes __typename and ID on all objects
*/
val DEFAULT: PrintingConfiguration = builder()
.pretty(false)
.commaSeparator(",")
.spreadOnFragmentOperator("...on ")
.build()
val PRETTY = builder()
.pretty(true)
.commaSeparator("")
.spreadOnFragmentOperator("... on ")
.build()
}
}
| 1
| null |
1
| 1
|
a9e8dab66e2704aab1434f76cff7129d84494796
| 2,768
|
kotlinq
|
Apache License 2.0
|
src/main/kotlin/g2301_2400/s2319_check_if_matrix_is_x_matrix/Solution.kt
|
javadev
| 190,711,550
| false
|
{"Kotlin": 4901773, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g2301_2400.s2319_check_if_matrix_is_x_matrix
// #Easy #Array #Matrix #2023_06_30_Time_247_ms_(100.00%)_Space_39_MB_(70.00%)
class Solution {
fun checkXMatrix(grid: Array<IntArray>): Boolean {
for (i in grid.indices) {
for (j in grid[0].indices) {
if (i == j || i + j == grid.size - 1) {
if (grid[i][j] == 0) {
return false
}
} else {
if (grid[i][j] != 0) {
return false
}
}
}
}
return true
}
}
| 0
|
Kotlin
|
20
| 43
|
471d45c60f669ea1a2e103e6b4d8d54da55711df
| 636
|
LeetCode-in-Kotlin
|
MIT License
|
app/src/main/java/com/example/myfirstproject/MainActivity.kt
|
MateusLand
| 633,007,612
| false
| null |
package com.example.myfirstproject
import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
@SuppressLint("ShowToast")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnCalcular: Button = findViewById(R.id.btnCalcular)
val edtPeso: EditText = findViewById(R.id.edittext_peso)
val edtAltura: EditText = findViewById(R.id.edittext_altura)
val tvResultado: TextView = findViewById(R.id.txtMsg)
btnCalcular.setOnClickListener {
val heightStr = edtAltura.text.toString()
val weightStr = edtPeso.text.toString()
if (heightStr.isNotEmpty() && weightStr.isNotEmpty()) {
val height: Float = edtAltura.text.toString().toFloat()
val weight: Float = edtPeso.text.toString().toFloat()
val heightFinal: Float = height * height
val result: Float = weight / heightFinal
tvResultado.text = result.toString()
val intent = Intent(this, ResultActivity::class.java)
.apply {
putExtra("EXTRA_RESULT", result)
}
startActivity(intent)
} else {
Toast.makeText(this, "Fill all requested fields", Toast.LENGTH_LONG).show()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9947583372f8bc1589c8bcb36f2c015e07884598
| 1,703
|
BMI-Calculator-Android
|
The Unlicense
|
src/main/kotlin/events/SlotRenderEvents.kt
|
nea89o
| 637,563,904
| false
|
{"Kotlin": 661685, "Java": 144356, "GLSL": 2115, "Nix": 1217}
|
package moe.nea.firmament.events
import net.minecraft.client.gui.DrawContext
import net.minecraft.client.texture.Sprite
import net.minecraft.screen.slot.Slot
import net.minecraft.util.Identifier
import moe.nea.firmament.util.MC
interface SlotRenderEvents {
val context: DrawContext
val slot: Slot
val mouseX: Int
val mouseY: Int
val delta: Float
fun highlight(sprite: Sprite) {
context.drawSprite(
slot.x, slot.y, 0, 16, 16,
sprite
)
}
data class Before(
override val context: DrawContext, override val slot: Slot,
override val mouseX: Int,
override val mouseY: Int,
override val delta: Float
) : FirmamentEvent(),
SlotRenderEvents {
companion object : FirmamentEventBus<Before>()
}
data class After(
override val context: DrawContext, override val slot: Slot,
override val mouseX: Int,
override val mouseY: Int,
override val delta: Float
) : FirmamentEvent(),
SlotRenderEvents {
companion object : FirmamentEventBus<After>()
}
}
| 25
|
Kotlin
|
6
| 37
|
0357245e88be4b8cd3d0681340d9a7065361ea74
| 1,089
|
Firmament
|
Apache License 2.0
|
dao/src/main/kotlin/repositories/DaoReporterJobRepository.kt
|
eclipse-apoapsis
| 760,319,414
| false
|
{"Kotlin": 2818605, "Dockerfile": 22512, "Shell": 7009}
|
/*
* Copyright (C) 2023 The ORT Server Authors (See <https://github.com/eclipse-apoapsis/ort-server/blob/main/NOTICE>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package org.eclipse.apoapsis.ortserver.dao.repositories
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import org.eclipse.apoapsis.ortserver.dao.blockingQuery
import org.eclipse.apoapsis.ortserver.dao.entityQuery
import org.eclipse.apoapsis.ortserver.dao.tables.OrtRunDao
import org.eclipse.apoapsis.ortserver.dao.tables.ReporterJobDao
import org.eclipse.apoapsis.ortserver.dao.tables.ReporterJobsTable
import org.eclipse.apoapsis.ortserver.model.JobStatus
import org.eclipse.apoapsis.ortserver.model.ReporterJob
import org.eclipse.apoapsis.ortserver.model.ReporterJobConfiguration
import org.eclipse.apoapsis.ortserver.model.repositories.ReporterJobRepository
import org.eclipse.apoapsis.ortserver.model.util.OptionalValue
import org.jetbrains.exposed.sql.Database
class DaoReporterJobRepository(private val db: Database) : ReporterJobRepository {
override fun create(ortRunId: Long, configuration: ReporterJobConfiguration): ReporterJob = db.blockingQuery {
ReporterJobDao.new {
ortRun = OrtRunDao[ortRunId]
createdAt = Clock.System.now()
this.configuration = configuration
status = JobStatus.CREATED
}.mapToModel()
}
override fun get(id: Long): ReporterJob? = db.entityQuery { ReporterJobDao[id].mapToModel() }
override fun getForOrtRun(ortRunId: Long): ReporterJob? = db.blockingQuery {
ReporterJobDao.find { ReporterJobsTable.ortRunId eq ortRunId }.limit(1).firstOrNull()?.mapToModel()
}
override fun update(
id: Long,
startedAt: OptionalValue<Instant?>,
finishedAt: OptionalValue<Instant?>,
status: OptionalValue<JobStatus>
): ReporterJob = db.blockingQuery {
val reporterJob = ReporterJobDao[id]
startedAt.ifPresent { reporterJob.startedAt = it }
finishedAt.ifPresent { reporterJob.finishedAt = it }
status.ifPresent { reporterJob.status = it }
ReporterJobDao[id].mapToModel()
}
override fun delete(id: Long) = db.blockingQuery { ReporterJobDao[id].delete() }
}
| 0
|
Kotlin
|
2
| 6
|
ce7c9a533128bc1282e77dca2d90158e0feeaa4a
| 2,829
|
ort-server
|
Apache License 2.0
|
app/src/main/java/com/bayurf/latihan/footballschedule/mvp/main/MainView.kt
|
bayuirfan52
| 156,997,449
| false
| null |
package com.bayurf.latihan.footballschedule.mvp.main
import com.bayurf.latihan.footballschedule.data.EventItem
interface MainView {
fun showLoading()
fun hideLoading()
fun showMatch(data: List<EventItem>)
fun showFavorite(data: List<EventItem>)
fun showEmpty()
}
| 0
|
Kotlin
|
0
| 0
|
1a56385e86c266f47a1d89531c1c0b32f1f51439
| 284
|
Football-Schedule
|
Creative Commons Attribution 3.0 Unported
|
src/Day10.kt
|
fedochet
| 573,033,793
| false
| null |
private sealed interface Command
private sealed interface Assembly
private object Noop : Command, Assembly
private class AddX(val value: Int) : Command
private class Add(val value: Int) : Assembly
fun main() {
fun parseCommand(str: String): Command {
return when {
str == "noop" -> Noop
str.startsWith("addx ") -> AddX(str.removePrefix("addx ").toInt())
else -> error("Unexpected command '$str'")
}
}
fun parseAndConvertToAssembly(input: List<String>): List<Assembly> {
val initialCommands = input.map { parseCommand(it) }
val assembly = initialCommands
.flatMap {
when (it) {
is AddX -> listOf(Noop, Add(it.value))
is Noop -> listOf(it)
}
}
return assembly
}
class Executor(val assembly: List<Assembly>) {
var register = 1
private set
var cycle = 1
private set
fun nextStep() {
require(hasNext)
when (val cmd = assembly[cycle - 1]) {
is Add -> register += cmd.value
Noop -> {}
}
cycle += 1
}
val hasNext: Boolean
get() = cycle < assembly.size
}
fun part1(input: List<String>): Int {
val assembly = parseAndConvertToAssembly(input)
val recordedCycles =
listOf(20, 60, 100, 140, 180, 220)
.associateWith { 0 }
.toMutableMap()
val executor = Executor(assembly)
while (executor.hasNext) {
if (executor.cycle in recordedCycles) {
recordedCycles[executor.cycle] = executor.register
}
executor.nextStep()
}
return recordedCycles.toList().sumOf { (cycles, value) -> cycles * value }
}
fun part2(input: List<String>): String {
val assembly = parseAndConvertToAssembly(input)
val executor = Executor(assembly)
val width = 40
val height = 6
return (0 until height).joinToString(separator = System.lineSeparator()) { _ ->
(0 until width).joinToString("") { widthPos ->
val sprite = executor.register
val pixelColor: String =
if (widthPos in (sprite - 1)..(sprite + 1)) {
"#"
} else {
"."
}
executor.nextStep()
pixelColor
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
val part2 = part2(testInput)
check(part2 == """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent()
)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0
|
Kotlin
|
0
| 1
|
975362ac7b1f1522818fc87cf2505aedc087738d
| 3,251
|
aoc2022
|
Apache License 2.0
|
Plugin/convention/src/main/kotlin/plugin/convention/features/FeaturePane.kt
|
SingularityIndonesia
| 776,620,771
| false
|
{"Kotlin": 248468, "Shell": 4184, "Swift": 585, "HTML": 339, "CSS": 102}
|
/*
* Copyright (c) 2024 Singularity Indonesia (<EMAIL>)
* You are not allowed to remove the copyright. Unless you have a "free software" licence.
*/
package plugin.convention.features
import org.gradle.api.Project
import org.gradle.kotlin.dsl.dependencies
import org.jetbrains.compose.ComposePlugin
import plugin.convention.companion.androidTestImplementation
import plugin.convention.companion.debugImplementation
import plugin.convention.companion.versionCatalog
import plugin.convention.companion.withBaseAppModuleExtension
import plugin.convention.companion.withBaseExtension
import plugin.convention.companion.withKotlinMultiplatformExtension
import plugin.convention.companion.withLibraryExtension
import plugin.convention.companion.withPluginManager
class FeaturePane : ComposePlugin() {
override fun apply(project: Project) {
with(project) {
val libs = versionCatalog
withPluginManager {
apply("org.jetbrains.compose")
apply("org.jetbrains.kotlin.plugin.compose")
}
withKotlinMultiplatformExtension {
sourceSets.androidMain.dependencies {
implementation(Dependencies(project).preview)
implementation(
libs.findLibrary("androidx-activity-compose").get()
)
}
sourceSets.commonMain.dependencies {
implementation(Dependencies(project).runtime)
implementation(Dependencies(project).foundation)
implementation(Dependencies(project).material3)
implementation(Dependencies(project).ui)
implementation(Dependencies(project).components.resources)
implementation(Dependencies(project).components.uiToolingPreview)
implementation(libs.findLibrary("compose-navigation").get())
implementation(libs.findLibrary("lifecycle-viewmodel-compose").get())
implementation(libs.findLibrary("orbit-mvi-core").get())
implementation(libs.findLibrary("orbit-mvi-compose").get())
}
sourceSets.commonTest.dependencies {
implementation(libs.findLibrary("orbit-test").get())
}
}
withBaseExtension {
dependencies {
debugImplementation(libs.findLibrary("compose-ui-tooling").get())
androidTestImplementation(
libs.findLibrary("compose-ui-tooling-preview").get()
)
}
}
// configure for application module
runCatching {
withBaseAppModuleExtension {
buildFeatures {
compose = true
}
}
}
// configure for library module
runCatching {
withLibraryExtension {
buildFeatures {
compose = true
}
}
}
}
}
}
| 0
|
Kotlin
|
4
| 7
|
bce4027f12a07c683ea9e1afae78605f4f092958
| 3,202
|
SingularityBaseMobile
|
Creative Commons Zero v1.0 Universal
|
apps/etterlatte-opplysninger-fra-inntektskomponenten/src/main/kotlin/opplysninger/kilde/inntektskomponenten/InntektsKomponentenResponse.kt
|
navikt
| 417,041,535
| false
| null |
package no.nav.etterlatte.opplysninger.kilde.inntektskomponenten
import no.nav.etterlatte.libs.common.inntekt.ArbeidsInntektMaaned
import no.nav.etterlatte.libs.common.inntekt.Ident
data class InntektsKomponentenResponse(
val arbeidsInntektMaaned: List<ArbeidsInntektMaaned>?,
val ident: Ident
)
| 6
|
Kotlin
|
0
| 3
|
8d41d2e006b5df41eacef84a670bc162ed72233c
| 305
|
pensjon-etterlatte-saksbehandling
|
MIT License
|
app/src/main/java/com/jbgcomposer/newshub/db/FavoriteDao.kt
|
jhonybguerra
| 755,538,997
| false
|
{"Kotlin": 48815}
|
package com.jbgcomposer.newshub.db
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
@Dao
interface FavoriteDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsert(favoriteArticle: FavoriteArticle) : Long
@Query("SELECT * FROM articles")
fun getSavedNews(): LiveData<List<FavoriteArticle>>
@Delete
suspend fun deleteArticle(favoriteArticle: FavoriteArticle)
}
| 0
|
Kotlin
|
0
| 0
|
9ae3191cd578d20c05fa110a4bd343fa73651573
| 539
|
NewsHub
|
Apache License 2.0
|
src/main/kotlin/net/savagelabs/skyblockx/command/skyblock/cmd/CmdSbKick.kt
|
ryderbelserion
| 669,876,085
| false
| null |
package net.savagelabs.skyblockx.command.skyblock.cmd
import net.savagelabs.savagepluginx.command.Argument
import net.savagelabs.savagepluginx.command.Command
import net.savagelabs.savagepluginx.command.argument.PlayerArgument
import net.savagelabs.skyblockx.command.SCommandInfo
import net.savagelabs.skyblockx.command.SCommandRequirements
import net.savagelabs.skyblockx.command.SCommandRequirementsBuilder
import net.savagelabs.skyblockx.core.Permission
import net.savagelabs.skyblockx.core.getIPlayer
import net.savagelabs.skyblockx.core.getIPlayerByName
import net.savagelabs.skyblockx.event.IslandKickEvent
import net.savagelabs.skyblockx.persist.Message
import org.bukkit.Bukkit
class CmdSbKick : Command<SCommandInfo, SCommandRequirements>() {
init {
aliases.add("kick")
requiredArgs.add(Argument("player-to-kick", 0, PlayerArgument()))
commandRequirements = SCommandRequirementsBuilder().withPermission(Permission.ADMIN_KICKFROMISLAND).build()
}
override fun perform(info: SCommandInfo) {
val iPlayerByName = getIPlayerByName(info.args[0])
if (iPlayerByName?.getIsland() == null) {
info.message(Message.instance.genericPlayerNotAnIslandMember)
return
}
// They're not the owner so we process removing the member.
val island = iPlayerByName.getIsland()!!
if (island.getLeader() != iPlayerByName) {
if (!island.getIslandMembers(false).contains(iPlayerByName)) {
info.message(Message.instance.commandMemberKickNotFound)
return
}
island.kickMember(iPlayerByName.name)
Bukkit.getPluginManager().callEvent(IslandKickEvent(island, info.player!!.getIPlayer(), iPlayerByName))
} else {
// Theyre an island owner if we're here.
iPlayerByName.unassignIsland()
if (island.members.isEmpty()) {
island.delete()
info.message(Message.instance.commandSkyblockKickIslandDeleted)
return
}
val firstMember = island.getIslandMembers(false).first()
// just in case
firstMember.assignIsland(island)
island.leaderUUID = firstMember.uuid
info.message(Message.instance.commandSkyblockKickMemberKickedOwner, firstMember.name)
}
info.message(Message.instance.commandSkyblockKickMemberKicked, iPlayerByName.name)
}
override fun getHelpInfo(): String {
return Message.instance.commandSkyblockKickHelp
}
}
| 0
|
Kotlin
|
0
| 0
|
23e430fd51a76e22f95847520e6976e2250058b3
| 2,293
|
Skyblock
|
MIT License
|
src/main/kotlin/Domain/Teacher.kt
|
SchoolSyncAr
| 782,715,163
| false
|
{"Kotlin": 4711, "Dockerfile": 243}
|
package ar.org.schoolsync.Domain
import ar.org.schoolsync.Repositories.Entity
class Teacher (
override var id: Int,
var firstName:String,
var lastName: String,
) : Entity {
}
| 12
|
Kotlin
|
0
| 1
|
af4fd5bd2915ce84f6c512dba1ed3d0c1a2ba7ab
| 196
|
schoolsync-be
|
MIT License
|
kodein-di/src/jvmMain/kotlin/org/kodein/di/internal/DirectDIJVMImpl.kt
|
kosi-libs
| 34,046,231
| false
|
{"Kotlin": 661014, "Java": 16368}
|
package org.kodein.di.internal
import org.kodein.di.*
import org.kodein.type.TypeToken
@Suppress("UNCHECKED_CAST")
private val DIContext<*>.anyType get() = type as TypeToken<in Any>
// https://youtrack.jetbrains.com/issue/KT-61573
@Suppress("FunctionName", "EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
internal actual class DirectDIImpl actual constructor(container: DIContainer, context: DIContext<*>) : DirectDIBaseImpl(container, context),
DirectDI {
override fun <A, T : Any> AllFactories(argType: TypeToken<in A>, type: TypeToken<T>, tag: Any?): List<(A) -> T> = container.allFactories(DI.Key(context.anyType, argType, type, tag), context.value)
override fun <T : Any> AllProviders(type: TypeToken<T>, tag: Any?): List<() -> T> = container.allProviders(DI.Key(context.anyType, TypeToken.Unit, type, tag), context.value)
override fun <A, T : Any> AllProviders(argType: TypeToken<in A>, type: TypeToken<T>, tag: Any?, arg: () -> A): List<() -> T> = container.allFactories(DI.Key(context.anyType, argType, type, tag), context.value).map { it.toProvider(arg) }
override fun <T : Any> AllInstances(type: TypeToken<T>, tag: Any?): List<T> = container.allProviders(DI.Key(context.anyType, TypeToken.Unit, type, tag), context.value).map { it.invoke() }
override fun <A, T : Any> AllInstances(argType: TypeToken<in A>, type: TypeToken<T>, tag: Any?, arg: A): List<T> = container.allFactories(DI.Key(context.anyType, argType, type, tag), context.value).map { it.invoke(arg) }
}
| 5
|
Kotlin
|
172
| 3,148
|
7bf22a71b66c52e6434c72e6162377b10085567f
| 1,509
|
Kodein
|
MIT License
|
kodein-di/src/jvmMain/kotlin/org/kodein/di/internal/DirectDIJVMImpl.kt
|
kosi-libs
| 34,046,231
| false
|
{"Kotlin": 661014, "Java": 16368}
|
package org.kodein.di.internal
import org.kodein.di.*
import org.kodein.type.TypeToken
@Suppress("UNCHECKED_CAST")
private val DIContext<*>.anyType get() = type as TypeToken<in Any>
// https://youtrack.jetbrains.com/issue/KT-61573
@Suppress("FunctionName", "EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
internal actual class DirectDIImpl actual constructor(container: DIContainer, context: DIContext<*>) : DirectDIBaseImpl(container, context),
DirectDI {
override fun <A, T : Any> AllFactories(argType: TypeToken<in A>, type: TypeToken<T>, tag: Any?): List<(A) -> T> = container.allFactories(DI.Key(context.anyType, argType, type, tag), context.value)
override fun <T : Any> AllProviders(type: TypeToken<T>, tag: Any?): List<() -> T> = container.allProviders(DI.Key(context.anyType, TypeToken.Unit, type, tag), context.value)
override fun <A, T : Any> AllProviders(argType: TypeToken<in A>, type: TypeToken<T>, tag: Any?, arg: () -> A): List<() -> T> = container.allFactories(DI.Key(context.anyType, argType, type, tag), context.value).map { it.toProvider(arg) }
override fun <T : Any> AllInstances(type: TypeToken<T>, tag: Any?): List<T> = container.allProviders(DI.Key(context.anyType, TypeToken.Unit, type, tag), context.value).map { it.invoke() }
override fun <A, T : Any> AllInstances(argType: TypeToken<in A>, type: TypeToken<T>, tag: Any?, arg: A): List<T> = container.allFactories(DI.Key(context.anyType, argType, type, tag), context.value).map { it.invoke(arg) }
}
| 5
|
Kotlin
|
172
| 3,148
|
7bf22a71b66c52e6434c72e6162377b10085567f
| 1,509
|
Kodein
|
MIT License
|
bitgouel-api/src/main/kotlin/team/msg/domain/inquiry/exception/InquiryNotFoundException.kt
|
School-of-Company
| 700,741,727
| false
|
{"Kotlin": 636912, "Shell": 2040, "Dockerfile": 206}
|
package team.msg.domain.inquiry.exception
import team.msg.domain.inquiry.exception.constant.InquiryErrorCode
import team.msg.global.error.exception.BitgouelException
class InquiryNotFoundException(message: String) : BitgouelException(message, InquiryErrorCode.NOT_FOUND_INQUIRY.status)
| 3
|
Kotlin
|
0
| 17
|
c731c813d48b9121553525a2c36fba609fa6869b
| 287
|
Bitgouel-Server
|
MIT License
|
app/src/main/java/com/example/applaudochallenge/ui/navigation/components/TvShowsContent.kt
|
mauriciolima1988
| 561,894,249
| false
| null |
package com.example.applaudochallenge.ui.navigation.components
import android.widget.Toast
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.paging.compose.LazyPagingItems
import com.example.applaudochallenge.R
import com.example.applaudochallenge.data.network.LoadingUiState
import com.example.applaudochallenge.data.network.getNetworkStatus
import com.example.applaudochallenge.data.models.TvShow
import com.example.applaudochallenge.utilities.ScreenState
@Composable
internal fun TvShowsContent(
loadingUiState: LoadingUiState?,
onEmptyButtonClick: () -> Unit,
onCardClick: (Int) -> Unit,
onRefresh: () -> Unit,
onCache: (TvShow) -> Unit
) {
val context = LocalContext.current
val status = getNetworkStatus()
ScreenState<LazyPagingItems<TvShow>>(
loadingUiState = loadingUiState,
onClick = onEmptyButtonClick
) {
TvShowList(it, onRefresh, onCache) { id ->
if (status) {
onCardClick(id)
return@TvShowList
} else {
Toast.makeText(
context,
context.getString(R.string.no_connection_found),
Toast.LENGTH_LONG
).show()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d4481d5e5fcfcaf0c953fd1fe806c1aedfcdca9c
| 1,317
|
Applaudo_s_Code_Challenge_Android
|
MIT License
|
src/main/kotlin/com/shopping/domain/dto/order/response/OrderResponse.kt
|
alialbaali
| 285,645,104
| false
|
{"Kotlin": 224319}
|
package com.shopping.domain.dto.order.response
data class OrderResponse(
val orderId: String,
val addressName: String,
val cardLast4Numbers: Long,
val numberOfItems: Long,
val totalPrice: Double,
)
| 0
|
Kotlin
|
0
| 1
|
e8d003386bfff065c9a775b4a808c2d7dd9acd87
| 219
|
Shopally
|
Apache License 2.0
|
app/src/main/java/network/RetrofitInstance.kt
|
Rohith0007
| 794,859,793
| false
|
{"Kotlin": 17306}
|
package network
import EmployeeApiService
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitInstance {
private const val BASE_URL = "https://s3.amazonaws.com/sq-mobile-interview/"
val retrofit: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val api: EmployeeApiService by lazy {
retrofit.create(EmployeeApiService::class.java)
}
}
| 0
|
Kotlin
|
0
| 0
|
6c241af2410e7e47f9446d404996de4a7f114595
| 525
|
EmployeeDirectory
|
Apache License 2.0
|
core/src/commonMain/kotlin/dev/iaiabot/furuhuru/datasource/local/UserDataSource.kt
|
iaia
| 523,282,500
| false
| null |
package dev.iaiabot.furuhuru.datasource.local
internal interface UserDataSource {
fun getUserName(): String
fun saveUserName(newUserName: String)
}
| 2
|
Kotlin
|
0
| 0
|
b83cf1558a8bb906015b3cc478ab8e18e80e5a89
| 159
|
Furuhuru
|
MIT License
|
template-model-generator/src/main/kotlin/no/nav/pensjon/brev/template/dsl/helpers/SelectorModels.kt
|
navikt
| 375,334,697
| false
|
{"Kotlin": 1439579, "TypeScript": 209010, "CSS": 18391, "TeX": 12814, "Shell": 6626, "Python": 4371, "Dockerfile": 3864, "JavaScript": 1937, "HTML": 380}
|
package no.nav.pensjon.brev.template.dsl.helpers
import com.google.devtools.ksp.symbol.*
internal data class SelectorModels(private val visited: Set<KSClassDeclaration> = emptySet(), val needed: Map<KSClassDeclaration, Set<KSFile>> = emptyMap()) {
fun withVisited(decl: KSClassDeclaration): SelectorModels =
copy(visited = visited + decl)
fun withDependency(decl: KSClassDeclaration, dependency: KSFile?): SelectorModels =
if (needed.containsKey(decl)) {
withNeeded(decl, dependency)
} else {
this
}
fun withNeeded(decl: KSClassDeclaration, dependency: KSFile?): SelectorModels =
copy(needed = needed + (decl to needed.getOrDefault(decl, emptySet()) + setOfNotNull(dependency)))
fun isVisited(decl: KSClassDeclaration): Boolean =
visited.contains(decl) || needed.contains(decl)
}
| 4
|
Kotlin
|
3
| 1
|
e9d2fb87f66a57cd3f6d94d33d7dd30050968d94
| 872
|
pensjonsbrev
|
MIT License
|
adapter-bansa/src/main/kotlin/redux/api/adapters/BansaStoreAdapter.kt
|
glung
| 68,528,949
| false
| null |
package redux.api.adapters
import com.brianegan.bansa.BaseStore
import redux.api.Reducer
import redux.api.Store
class BansaStoreAdapter<S : Any>(val store: com.brianegan.bansa.Store<S>) : Store<S> {
override fun getState(): S = store.state
override fun dispatch(action: Any): Any {
store.dispatch(ActionAdapter(action))
return action
}
override fun subscribe(subscriber: Store.Subscriber): Store.Subscription {
val subscription = store.subscribe { subscriber.onStateChanged() }
return Store.Subscription { subscription.unsubscribe() }
}
override fun replaceReducer(reducer: Reducer<S>) = throw UnsupportedOperationException("not implemented")
companion object {
fun <S : Any> create(reducer: Reducer<S>, initialState: S, enhancer: Store.Enhancer?): Store<S> {
return if (enhancer != null) {
// Bansa does not support Enhancer yet.
enhancer
.enhance(object : Store.Creator {
override fun <T : Any> create(reducer: Reducer<T>, initialState: T, enhancer: Store.Enhancer?): Store<T> {
return bansaStoreAdapter(initialState, reducer)
}
})
.create(reducer, initialState)
} else {
return bansaStoreAdapter(initialState, reducer)
}
}
private fun <T : Any> bansaStoreAdapter(initialState: T, reducer: Reducer<T>): BansaStoreAdapter<T> {
val libsStore = BaseStore<T>(initialState, toLibReducer(reducer))
val store = BansaStoreAdapter(libsStore)
// TODO : Remove when fixed in lib
store.dispatch(Store.Companion.INIT)
return store
}
private fun <S : Any> toLibReducer(reducer: Reducer<S>): com.brianegan.bansa.Reducer<S>? {
return com.brianegan.bansa.Reducer<S> { state, action -> reducer.reduce(state, (action as ActionAdapter).action) }
}
}
}
class ActionAdapter(val action: Any) : com.brianegan.bansa.Action
| 0
|
Kotlin
|
1
| 1
|
37784e7729b08742118073a92908b5d5774c03e8
| 2,138
|
jvm-redux
|
MIT License
|
easylauncher/src/main/kotlin/com/project/starter/easylauncher/plugin/models/AdaptiveIcon.kt
|
usefulness
| 283,004,535
| false
| null |
package com.project.starter.easylauncher.plugin.models
import java.io.File
internal data class AdaptiveIcon(val file: File, val background: String, val foreground: String)
| 7
|
Kotlin
|
16
| 336
|
bfcec17114ec5fe6d8f54ff1ab8e8cc959637763
| 174
|
easylauncher-gradle-plugin
|
MIT License
|
app/src/main/java/top/r011/demo/rgithub/ui/home/HomeViewModel.kt
|
waylife
| 852,132,884
| false
|
{"Kotlin": 70115}
|
package top.r011.demo.rgithub.ui.home
import androidx.lifecycle.LiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import top.r011.demo.rgithub.account.UserAccount
import top.r011.demo.rgithub.data.repository.GithubRepository
import top.r011.demo.rgithub.ui.base.BaseViewModel
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val githubRepository: GithubRepository,
private val userAccount: UserAccount
) : BaseViewModel() {
// val onLoginCallback: OnLoginCallback? = null
fun logout() {
userAccount.logout()
}
fun isLogin() = userAccount.isLogin()
fun getAccessTokenLiveData(): LiveData<String?> {
return userAccount.accessToken
}
}
| 0
|
Kotlin
|
0
| 0
|
e4407d2c2483aa2773104b0cf1f25e313e235fad
| 738
|
RGithub
|
MIT License
|
app/src/main/java/com/gjapps/minilogbook/data/models/BloodGlucoseRecordModel.kt
|
gustavoja
| 812,563,129
| false
|
{"Kotlin": 58123}
|
package com.gjapps.minilogbook.data.models
import java.util.Date
data class BloodGlucoseRecordModel (val mgdlValue: Float, val date: Date)
| 0
|
Kotlin
|
0
| 0
|
43a6462442d352a3079cefdcf95adf1ed2801cda
| 140
|
minilogbook
|
Apache License 2.0
|
core-database/src/main/kotlin/io/getstream/avengerschat/core/database/AppDatabase.kt
|
GetStream
| 420,033,848
| false
|
{"Kotlin": 143313}
|
/*
* 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.avengerschat.core.database
import androidx.room.Database
import androidx.room.RoomDatabase
import io.getstream.avengerschat.core.database.entity.AvengerEntity
@Database(entities = [AvengerEntity::class], version = 1, exportSchema = true)
abstract class AppDatabase : RoomDatabase() {
abstract fun avengersDao(): AvengersDao
}
| 1
|
Kotlin
|
37
| 364
|
d712bf44d89fa342d65dc4e8b81f9aa955a9f1ce
| 969
|
AvengersChat
|
Apache License 2.0
|
app/src/main/java/com/zhangwww/newnotebook/Config.kt
|
Zhangw1998
| 382,551,686
| false
| null |
package com.zhangwww.newnotebook
/**
* @Description: app的一些基本配置信息
* @Author: Zhangwww
* @CreateDate: 2021/7/3 9:54
* @UpdateUser:
* @UpdateDate: 2021/7/3 9:54
* @UpdateRemark:
* @Version: 1.0
*/
object Config {
}
| 0
|
Kotlin
|
0
| 0
|
ee36df26f9ec9dd24d6938b19714a8af5fb2e531
| 248
|
Notebook
|
MIT License
|
icmp4a/src/main/kotlin/com/marsounjan/icmp4a/Icmp4a.kt
|
marsounjan
| 747,256,499
| false
|
{"Kotlin": 63710}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.marsounjan.icmp4a
import android.net.Network
import android.os.Build
import android.system.ErrnoException
import android.system.Os
import android.system.OsConstants
import android.system.StructPollfd
import com.marsounjan.icmp4a.Icmp.Error
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.io.FileDescriptor
import java.io.IOException
import java.net.Inet4Address
import java.net.Inet6Address
import java.net.InetAddress
import java.net.SocketException
import java.net.UnknownHostException
import java.nio.ByteBuffer
import kotlin.math.max
/**
* INTERNET CONTROL MESSAGE PROTOCOL (ICMP) for Android
*
* Since using raw sockets is not allowed on Android, this class relies on
* SOCK_DGRAM with IPPROTO_ICMP socket kind. It makes it possible to send
* ICMP_ECHO messages and receive the corresponding ICMP_ECHOREPLY messages
* without any special privileges.
*
* read more about this here:
* https://lwn.net/Articles/443051/
*/
class Icmp4a : Icmp {
private sealed class Destination {
data class IP(val ip: InetAddress) : Destination()
data class Hostname(val host: String) : Destination()
}
/**
*
*
* @return file descriptor of the new socket
*/
private fun createSocketForDestination(destination: InetAddress): FileDescriptor {
try {
val fd = when (destination) {
is Inet4Address -> Os.socket(OsConstants.AF_INET, OsConstants.SOCK_DGRAM, OsConstants.IPPROTO_ICMP)
is Inet6Address -> Os.socket(OsConstants.AF_INET6, OsConstants.SOCK_DGRAM, OsConstants.IPPROTO_ICMPV6)
else -> throw IllegalStateException("Unsupported destination address type ${destination.javaClass.canonicalName}")
}
if (!fd.valid()) throw Icmp.Error.SocketException(message = "Created file descriptor is invalid")
return fd
} catch (e: ErrnoException) {
throw Icmp.Error.SocketException(message = "Socket creation failed", cause = e)
}
}
private fun setSocketOptions(
fd: FileDescriptor
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
Os.setsockoptInt(fd, OsConstants.IPPROTO_IP, OsConstants.IP_TOS, SOCK_OPT_IPTOS_LOWDELAY)
} catch (e: ErrnoException) {
throw Icmp.Error.SocketException(message = "Failed to set IP_TOS to low delay")
}
}
}
private fun bindToNetwork(
fd: FileDescriptor,
network: Network
) {
try {
network.bindSocket(fd)
} catch (e: IOException) {
throw Icmp.Error.SocketException(message = "Failed to bind socket to specified network")
}
}
private fun newPacketSessionForDestination(destination: InetAddress, packetSize: Int): IcmpPingSession<*, *> =
when (destination) {
is Inet4Address -> IcmpV4PingSession(packetSize = packetSize)
is Inet6Address -> IcmpV6PingSession(packetSize = packetSize)
else -> throw IllegalArgumentException("Unsupported destination address type ${destination.javaClass.canonicalName}")
}
private sealed class HostnameResolutionResult {
data class Success(
val inetAddress: InetAddress
) : HostnameResolutionResult()
sealed class Failed() : HostnameResolutionResult() {
abstract val cause: Exception
class UnknownHost(override val cause: UnknownHostException) : Failed()
class SecurityError(override val cause: SecurityException) : Failed()
class Timeout(override val cause: TimeoutCancellationException) : Failed()
}
}
private suspend fun resolveIpForHost(network: Network?, hostname: String, timeoutMillis: Long): HostnameResolutionResult =
withContext(Dispatchers.IO) {
try {
if (hostname.isNotBlank()) {
withTimeout(timeoutMillis) {
HostnameResolutionResult.Success(
inetAddress = if (network != null) {
//if network specified, make sure that even the DNS resolution is done on the network!
network.getByName(hostname)
} else {
InetAddress.getByName(hostname)
}
)
}
} else {
HostnameResolutionResult.Failed.UnknownHost(cause = UnknownHostException("Cannot resolve empty host"))
}
} catch (e: UnknownHostException) {
HostnameResolutionResult.Failed.UnknownHost(cause = e)
} catch (e: SecurityException) {
HostnameResolutionResult.Failed.SecurityError(cause = e)
} catch (e: TimeoutCancellationException) {
HostnameResolutionResult.Failed.Timeout(cause = e)
}
}
private suspend fun ping(
destination: Destination,
timeoutMillis: Long,
packetSize: Int,
network: Network?
): Icmp.PingStatus =
pingInterval(
destination = destination,
count = 1,
timeoutMillis = timeoutMillis,
packetSize = packetSize,
intervalMillis = Long.MAX_VALUE,
network = network
)
.first()
private fun pingInterval(
destination: Destination,
count: Int?,
timeoutMillis: Long,
packetSize: Int,
intervalMillis: Long,
network: Network?
): Flow<Icmp.PingStatus> {
require(count == null || count > 0) { "packet count must be null (infinite ping) or > 0" }
require(timeoutMillis > 0) { "timeout must be > 0" }
require(packetSize > 0) { "packet size must be > 0" }
return callbackFlow<Icmp.PingStatus> {
val ip = when (destination) {
is Destination.IP -> destination.ip
is Destination.Hostname ->
when (val result = resolveIpForHost(
network = network,
hostname = destination.host,
timeoutMillis = timeoutMillis
)) {
is HostnameResolutionResult.Success -> result.inetAddress
is HostnameResolutionResult.Failed.UnknownHost -> {
throw Icmp.Error.UnknownHost(message = "Unknown host '${destination.host}'")
}
is HostnameResolutionResult.Failed.Timeout -> {
throw Icmp.Error.UnknownHost(message = "Failed to resolve host ${destination.host} in $timeoutMillis ms")
}
is HostnameResolutionResult.Failed.SecurityError -> {
throw Icmp.Error.UnknownHost(
message = "Security manager exists doesn't allow hostname resolution"
)
}
}
}
val fd = createSocketForDestination(destination = ip)
try {
setSocketOptions(fd)
if (network != null) bindToNetwork(fd, network)
val pollFd = StructPollfd()
pollFd.fd = fd
val eventPollIn = OsConstants.POLLIN.toShort()
val pollFds = arrayOf(pollFd)
var timestamp: Long
var millis: Long
var rc: Int
var result: Icmp.PingResult?
var sentCount = 0
var retryDelayMillis: Long
val packetSession = newPacketSessionForDestination(destination = ip, packetSize = packetSize)
val statusManager = IcmpPingStatusManager(ip = ip)
while (count == null || sentCount++ < count) {
retryDelayMillis = intervalMillis
try {
timestamp = System.currentTimeMillis()
rc = Os.sendto(fd, packetSession.nextRequest(), 0, ip, Icmp.PORT)
if (rc < 0) {
send(statusManager.update(Icmp.PingResult.Failed.IO("sendto failed with $rc")))
continue
}
while (true) {
pollFd.events = eventPollIn
rc = Os.poll(pollFds, timeoutMillis.toInt())
millis = System.currentTimeMillis() - timestamp
if (rc < 0) {
send(statusManager.update(Icmp.PingResult.Failed.IO(message = "poll failed with $rc")))
break
}
if (pollFd.revents != eventPollIn) {
send(
statusManager.update(
Icmp.PingResult.Failed.RequestTimeout(
message = "Request timeout for ${ip.hostAddress} seq $sentCount",
millis = timeoutMillis
)
)
)
//when timeout reached, do not wait the whole delay time with next request but subtract timeout time
retryDelayMillis = max(0, intervalMillis - timeoutMillis)
break
}
rc = recvfrom(fd, packetSession.packetBuffer)
if (rc < 0) {
send(statusManager.update(Icmp.PingResult.Failed.IO(message = "recvfrom failed with $rc")))
break
}
result = try {
packetSession.processResponse(
buffer = ByteBuffer.wrap(packetSession.packetBuffer, 0, rc),
packetSize = rc,
millis = millis
)
} catch (e: IcmpMessageSerializer.InvalidMessageContentException) {
throw Icmp.Error.ProtocolException(
message = "Failed to deserialize incoming packet",
cause = e
)
}
if (result != null) {
send(statusManager.update(result))
break
}
}
} catch (e: ErrnoException) {
val errIdStr = "Err: ${e.errno}"
send(statusManager.update(Icmp.PingResult.Failed.IO(message = e.message?.let { "$it ($errIdStr)" } ?: errIdStr)))
} catch (e: SocketException) {
send(statusManager.update(Icmp.PingResult.Failed.IO(message = e.message ?: "Socket Exception")))
}
delay(retryDelayMillis)
}
cancel(message = "Processed all of requested $count Echo messages")
} finally {
try {
Os.close(fd)
} catch (_: ErrnoException) {
}
}
}
.flowOn(Dispatchers.IO)
}
private fun recvfrom(fd: FileDescriptor, buffer: ByteArray): Int {
val rc = Os.recvfrom(fd, buffer, 0, buffer.size, SOCK_FLAG_MSG_DONTWAIT, null)
return if (rc == OsConstants.EMSGSIZE) {
//incoming message longer then buffer
buffer.size
} else {
rc
}
}
/**
* @throws IllegalArgumentException
* @throws Error
*/
override suspend fun ping(host: String, timeoutMillis: Long, packetSize: Int, network: Network?): Icmp.PingStatus =
ping(
destination = Destination.Hostname(host),
timeoutMillis = timeoutMillis,
packetSize = packetSize,
network = network
)
/**
* @throws IllegalArgumentException
* @throws Error
*/
override suspend fun ping(ip: InetAddress, timeoutMillis: Long, packetSize: Int, network: Network?): Icmp.PingStatus =
ping(
destination = Destination.IP(ip),
timeoutMillis = timeoutMillis,
packetSize = packetSize,
network = network
)
/**
* @throws IllegalArgumentException
* @throws Error
*/
override fun pingInterval(
host: String,
count: Int?,
timeoutMillis: Long,
packetSize: Int,
intervalMillis: Long,
network: Network?
): Flow<Icmp.PingStatus> =
pingInterval(
destination = Destination.Hostname(host),
count = count,
timeoutMillis = timeoutMillis,
packetSize = packetSize,
intervalMillis = intervalMillis,
network = network
)
/**
* @throws IllegalArgumentException
* @throws Error
*/
override fun pingInterval(
ip: InetAddress,
count: Int?,
timeoutMillis: Long,
packetSize: Int,
intervalMillis: Long,
network: Network?
): Flow<Icmp.PingStatus> =
pingInterval(
destination = Destination.IP(ip),
count = count,
timeoutMillis = timeoutMillis,
packetSize = packetSize,
intervalMillis = intervalMillis,
network = network
)
companion object {
private const val SOCK_OPT_IPTOS_LOWDELAY = 0x10
private const val SOCK_FLAG_MSG_DONTWAIT = 0x40
}
}
| 0
|
Kotlin
|
0
| 1
|
e4a064059b491f5fc3a4e6d55fba13ec0a79b2d3
| 15,292
|
icmp4a
|
Apache License 2.0
|
src/test/kotlin/days/Day3Test.kt
|
teunw
| 573,164,590
| false
| null |
package days
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.Is.`is`
import org.junit.jupiter.api.Test
class Day3Test {
private val day = Day3()
@Test
fun testPartOne() {
assertThat(day.getPriority('p'), `is`(16))
assertThat(day.getPriority('L'), `is`(38))
assertThat(day.partOne(), `is`(157))
}
@Test
fun testPartTwo() {
assertThat(day.partTwo(), `is`(70))
}
}
| 0
|
Kotlin
|
0
| 0
|
149219285efdb1a4d2edc306cc449cce19250e85
| 449
|
advent-of-code-22
|
Creative Commons Zero v1.0 Universal
|
sample/app/src/main/java/xyz/shogo/sample/lib/InfinitePagerAdapter.kt
|
ShogoTakeuchi
| 222,040,301
| false
| null |
import androidx.viewpager.widget.PagerAdapter
import android.database.DataSetObserver
import android.view.ViewGroup
import android.os.Parcelable
import android.view.View
class InfinitePagerAdapter : PagerAdapter {
private val adapter: PagerAdapter
constructor(adapter: PagerAdapter) : super() {
this.adapter = adapter
}
override fun getCount(): Int {
return if (getRealCount() == 0) 0 else Integer.MAX_VALUE
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val virtualPosition = position % getRealCount()
return adapter.instantiateItem(container, virtualPosition)
}
override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
val virtualPosition = position % getRealCount()
adapter.destroyItem(container, virtualPosition, obj)
}
override fun finishUpdate(container: ViewGroup) {
adapter.finishUpdate(container)
}
override fun isViewFromObject(view: View, obj: Any): Boolean {
return adapter.isViewFromObject(view, obj)
}
override fun restoreState(bundle: Parcelable?, classLoader: ClassLoader?) {
adapter.restoreState(bundle, classLoader)
}
override fun saveState(): Parcelable? {
return adapter.saveState()
}
override fun startUpdate(container: ViewGroup) {
adapter.startUpdate(container)
}
override fun getPageTitle(position: Int): CharSequence? {
val virtualPosition = position % getRealCount()
return adapter.getPageTitle(virtualPosition)
}
override fun getPageWidth(position: Int): Float {
return adapter.getPageWidth(position)
}
override fun setPrimaryItem(container: ViewGroup, position: Int, obj: Any) {
adapter.setPrimaryItem(container, position, obj)
}
override fun unregisterDataSetObserver(observer: DataSetObserver) {
adapter.unregisterDataSetObserver(observer)
}
override fun registerDataSetObserver(observer: DataSetObserver) {
adapter.registerDataSetObserver(observer)
}
override fun notifyDataSetChanged() {
adapter.notifyDataSetChanged()
}
override fun getItemPosition(obj: Any): Int {
return adapter.getItemPosition(obj)
}
fun getRealCount(): Int {
return adapter.count
}
}
| 0
|
Kotlin
|
0
| 0
|
1b57fcebfc8a6317a1fe8b0d428940d2dba24768
| 2,352
|
infinite-viewpager
|
MIT License
|
crypto-android/src/test/kotlin/studio/lunabee/onesafe/cryptography/android/HKDFTinkHashEngineTest.kt
|
LunabeeStudio
| 624,544,471
| false
|
{"Kotlin": 3214440, "Java": 11987, "Python": 3979}
|
/*
* Copyright (c) 2023-2024 Lunabee Studio
*
* 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.
*
* Created by Lunabee Studio / Date - 8/23/2024 - for the oneSafe6 SDK.
* Last modified 8/20/24, 10:47 AM
*/
package studio.lunabee.onesafe.cryptography.android
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.TestResult
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import java.util.Base64
class HKDFTinkHashEngineTest {
private val hkdf = HKDFTinkHashEngine(Dispatchers.Default)
private val expectedKey = Base64.getDecoder().decode("<KEY>
/**
* https://www.notion.so/lunabeestudio/Crypto-diagrams-37c478e035fc41b1b0872fb74e9eec0f#7f9bacdac66b4b9c9b5e2bacb3b3e99f
*/
@Test
fun deriveKey_stability_test(): TestResult = runTest { hkdf.deriveKey_stability_test(expectedKey) }
}
| 1
|
Kotlin
|
1
| 2
|
2f1ff3aad95c748090c695743258fe3056fc6028
| 1,354
|
oneSafe6_SDK_Android
|
Apache License 2.0
|
paging-testing/src/commonMain/kotlin/app/cash/paging/testing/LoadErrorHandler.kt
|
cashapp
| 488,572,129
| false
|
{"Kotlin": 88180}
|
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.paging.testing
import app.cash.paging.CombinedLoadStates
expect fun interface LoadErrorHandler {
fun onError(combinedLoadStates: CombinedLoadStates): ErrorRecovery
}
expect enum class ErrorRecovery {
THROW,
RETRY,
RETURN_CURRENT_SNAPSHOT,
}
| 24
|
Kotlin
|
26
| 557
|
26448f6b70ca5e0088a43eed63d3f5a08bb81798
| 886
|
multiplatform-paging
|
Apache License 2.0
|
src/main/kotlin/com/github/arusland/tgbot/BotConfig.kt
|
arusland
| 496,772,419
| false
|
{"Kotlin": 6993, "Shell": 1476}
|
package com.github.arusland.tgbot
import org.slf4j.LoggerFactory
import java.io.File
import java.io.FileInputStream
import java.util.*
/**
* Simple bot configuration
*/
class BotConfig private constructor(prop: Properties) {
private val log = LoggerFactory.getLogger(BotConfig::class.java)
private val props: Properties = prop
val botToken: String
get() = getProperty("bot.token")
private fun getProperty(key: String): String =
props.getProperty(key) ?: throw IllegalStateException("Configuration not found for key: $key")
private fun getProperty(key: String, defValue: String): String =
props.getProperty(key) ?: defValue
companion object {
fun load(fileName: File, throwOnError: Boolean = true): BotConfig {
val props = Properties()
try {
val file = fileName.canonicalFile
FileInputStream(file).use { input -> props.load(input) }
} catch (e: Exception) {
if (throwOnError) {
throw RuntimeException(e)
}
}
return BotConfig(props)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
21f5638203e07fd71483643eafbee86952754baf
| 1,159
|
tgbot
|
Apache License 2.0
|
chi-compiler/src/test/kotlin/gh/marad/chi/core/expressionast/internal/FunctionConversionsKtFnCallTest.kt
|
marad
| 424,295,144
| false
|
{"Kotlin": 316466, "Java": 241258, "ANTLR": 7061, "Batchfile": 2689}
|
package gh.marad.chi.core.expressionast.internal
import gh.marad.chi.core.Type
import gh.marad.chi.core.parser.readers.LongValue
import gh.marad.chi.core.parser.readers.ParseFnCall
import gh.marad.chi.core.parser.readers.ParseLambda
import gh.marad.chi.core.shouldBeAtom
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class FunctionConversionsKtFnCallTest {
@Test
fun `should generate function call`() {
// given
val fnCall = ParseFnCall(
name = "funcName",
function = sampleLambda,
concreteTypeParameters = listOf(intTypeRef),
arguments = listOf(LongValue(10)),
testSection
)
// when
val call = convertFnCall(defaultContext(), fnCall)
// then
call.parameters.first().shouldBeAtom("10", Type.intType)
call.callTypeParameters.first() shouldBe Type.intType
}
private val sampleLambda = ParseLambda(
formalArguments = listOf(intArg("a")),
body = emptyList(),
sectionA
)
}
| 26
|
Kotlin
|
0
| 11
|
d93f2df6472476a0de365edc5f146826ce608c58
| 1,063
|
chi-compiler-kotlin
|
MIT License
|
app/src/main/java/com/example/myapplication/MainFragment.kt
|
Abcferreira
| 539,098,359
| false
|
{"Kotlin": 2165}
|
package com.example.myapplication
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.myapplication.databinding.FragmentMainBinding
class MainFragment : Fragment() {
private var _binding: FragmentMainBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMainBinding.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
@JvmStatic
fun newInstance() = MainFragment()
}
}
| 0
|
Kotlin
|
0
| 0
|
7a59d03e7ef7cac96e68d43bbaecaa7a5a6c4e61
| 832
|
testeRepo
|
Apache License 2.0
|
openpss/src/main/kotlin/com/hanggrian/openpss/util/TreeTableColumns.kt
|
hanggrian
| 104,778,225
| false
|
{"Kotlin": 324374, "HTML": 18736, "SCSS": 7162, "CSS": 5335, "Ruby": 147}
|
package com.hanggrian.openpss.util
import com.hanggrian.openpss.Context
import javafx.scene.control.TreeTableColumn
import ktfx.stringPropertyOf
import ktfx.text.invoke
fun <T> TreeTableColumn<T, String>.stringCell(target: T.() -> Any) =
setCellValueFactory { col ->
stringPropertyOf(col.value.value.target().let { it as? String ?: it.toString() })
}
fun <T> TreeTableColumn<T, String>.numberCell(context: Context, target: T.() -> Int) {
style = "-fx-alignment: center-right;"
setCellValueFactory {
stringPropertyOf(context.numberConverter(it.value.value.target()))
}
}
| 1
|
Kotlin
|
0
| 7
|
02013488fc115de903e7775d7c6d18d83537dcac
| 609
|
openpss
|
Apache License 2.0
|
src/main/kotlin/no/nav/rekrutteringsbistand/api/autorisasjon/AzureCache.kt
|
navikt
| 214,435,826
| false
| null |
package no.nav.rekrutteringsbistand.api.autorisasjon
import org.springframework.stereotype.Component
import java.time.LocalDateTime
@Component
class AzureCache {
private val cache: HashMap<String, HashMap<String, CachedToken>> = HashMap()
fun hentOBOToken(scope: String, onBehalfOf: String): String? {
val cachetToken = cache[scope]?.get(onBehalfOf)
return if (cachetToken == null) {
null
} else {
val erFremdelesGyldigOmEttSekund = cachetToken.expires.isAfter(LocalDateTime.now().plusSeconds(1))
if (erFremdelesGyldigOmEttSekund) cachetToken.token else null
}
}
fun lagreOBOToken(scope: String, onBehalfOf: String, azureResponse: AzureResponse) {
if (cache[scope] == null) {
cache[scope] = HashMap()
}
val rettFørTokenetUtløper = LocalDateTime.now().plusSeconds(
azureResponse.expires_in.toLong() - 10
)
cache[scope]!![onBehalfOf] = CachedToken(
azureResponse.access_token,
rettFørTokenetUtløper
)
}
}
data class CachedToken(
val token: String,
val expires: LocalDateTime,
)
| 2
|
Kotlin
|
1
| 0
|
9aed18bbd7723e6f52640963755e1dcc45a0a926
| 1,176
|
rekrutteringsbistand-stilling-api
|
MIT License
|
codebase/android/feature/transactions/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/feature/transactions/add_or_edit_transaction/viewmodel/AddOrEditTransactionScreenUiVisibilityState.kt
|
Abhimanyu14
| 429,663,688
| false
|
{"Kotlin": 1454948}
|
package com.makeappssimple.abhimanyu.financemanager.android.feature.transactions.add_or_edit_transaction.viewmodel
import androidx.compose.runtime.Immutable
import com.makeappssimple.abhimanyu.financemanager.android.core.common.extensions.isNull
@Immutable
sealed class AddOrEditTransactionScreenUiVisibilityState(
val isTitleTextFieldVisible: Boolean = false,
val isDescriptionTextFieldVisible: Boolean = false,
val isCategoryTextFieldVisible: Boolean = false,
val isTransactionForRadioGroupVisible: Boolean = false,
val isTransactionTypesRadioGroupVisible: Boolean = false,
val isAccountFromTextFieldVisible: Boolean = false,
val isAccountToTextFieldVisible: Boolean = false,
val isTitleSuggestionsVisible: Boolean = false,
) {
object Expense : AddOrEditTransactionScreenUiVisibilityState(
isTitleTextFieldVisible = true,
isDescriptionTextFieldVisible = false,
isCategoryTextFieldVisible = true,
isTransactionForRadioGroupVisible = true,
isTransactionTypesRadioGroupVisible = true,
isAccountFromTextFieldVisible = true,
isAccountToTextFieldVisible = false,
isTitleSuggestionsVisible = true,
)
object Income : AddOrEditTransactionScreenUiVisibilityState(
isTitleTextFieldVisible = true,
isDescriptionTextFieldVisible = false,
isCategoryTextFieldVisible = true,
isTransactionForRadioGroupVisible = false,
isTransactionTypesRadioGroupVisible = true,
isAccountFromTextFieldVisible = false,
isAccountToTextFieldVisible = true,
isTitleSuggestionsVisible = true,
)
object Investment : AddOrEditTransactionScreenUiVisibilityState(
isTitleTextFieldVisible = true,
isDescriptionTextFieldVisible = false,
isCategoryTextFieldVisible = true,
isTransactionForRadioGroupVisible = false,
isTransactionTypesRadioGroupVisible = true,
isAccountFromTextFieldVisible = true,
isAccountToTextFieldVisible = false,
isTitleSuggestionsVisible = true,
)
object Refund : AddOrEditTransactionScreenUiVisibilityState(
isTitleTextFieldVisible = false,
isDescriptionTextFieldVisible = false,
isCategoryTextFieldVisible = false,
isTransactionForRadioGroupVisible = false,
isTransactionTypesRadioGroupVisible = false,
isAccountFromTextFieldVisible = false,
isAccountToTextFieldVisible = true,
isTitleSuggestionsVisible = false,
)
object Transfer : AddOrEditTransactionScreenUiVisibilityState(
isTitleTextFieldVisible = false,
isDescriptionTextFieldVisible = false,
isCategoryTextFieldVisible = false,
isTransactionForRadioGroupVisible = false,
isTransactionTypesRadioGroupVisible = true,
isAccountFromTextFieldVisible = true,
isAccountToTextFieldVisible = true,
isTitleSuggestionsVisible = false,
)
}
fun AddOrEditTransactionScreenUiVisibilityState?.orDefault(): AddOrEditTransactionScreenUiVisibilityState {
return if (this.isNull()) {
AddOrEditTransactionScreenUiVisibilityState.Expense
} else {
this
}
}
| 4
|
Kotlin
|
0
| 1
|
6675c0b8c951b8d6105e03c34ce88054ccc87105
| 3,202
|
finance-manager
|
Apache License 2.0
|
cinescout/media/data/remote/src/commonMain/kotlin/cinescout/media/data/remote/res/TmdbScreenplayVideosJson.kt
|
fardavide
| 280,630,732
| false
| null |
package cinescout.media.data.remote.res
import cinescout.media.domain.sample.ScreenplayVideosSample
import cinescout.screenplay.domain.sample.TmdbScreenplayIdSample
import cinescout.media.data.remote.model.GetScreenplayVideosResponse as Response
object TmdbScreenplayVideosJson {
val Avatar3 = """
{
"${Response.Id}": "${TmdbScreenplayIdSample.Avatar3.value}",
"${Response.Results}": []
}
""".trimIndent()
val BreakingBad = """
{
"${Response.Id}": "${TmdbScreenplayIdSample.BreakingBad.value}",
"${Response.Results}": [
{
"${Response.Video.Id}": "${ScreenplayVideosSample.BreakingBad.videos[0].id.value}",
"${Response.Video.Key}": "${ScreenplayVideosSample.BreakingBad.videos[0].key}",
"${Response.Video.Name}": "${ScreenplayVideosSample.BreakingBad.videos[0].title}",
"${Response.Video.Site}": "${ScreenplayVideosSample.BreakingBad.videos[0].site.name}",
"${Response.Video.Size}": "1080",
"${Response.Video.Type}": "${ScreenplayVideosSample.BreakingBad.videos[0].type.name}"
}
]
}
""".trimIndent()
val Dexter = """
{
"${Response.Id}": "${TmdbScreenplayIdSample.Dexter.value}",
"${Response.Results}": [
{
"${Response.Video.Id}": "${ScreenplayVideosSample.Dexter.videos[0].id.value}",
"${Response.Video.Key}": "${ScreenplayVideosSample.Dexter.videos[0].key}",
"${Response.Video.Name}": "${ScreenplayVideosSample.Dexter.videos[0].title}",
"${Response.Video.Site}": "${ScreenplayVideosSample.Dexter.videos[0].site.name}",
"${Response.Video.Size}": "1080",
"${Response.Video.Type}": "${ScreenplayVideosSample.Dexter.videos[0].type.name}"
}
]
}
""".trimIndent()
val Grimm = """
{
"${Response.Id}": "${TmdbScreenplayIdSample.Grimm.value}",
"${Response.Results}": [
{
"${Response.Video.Id}": "${ScreenplayVideosSample.Grimm.videos[0].id.value}",
"${Response.Video.Key}": "${ScreenplayVideosSample.Grimm.videos[0].key}",
"${Response.Video.Name}": "${ScreenplayVideosSample.Grimm.videos[0].title}",
"${Response.Video.Site}": "${ScreenplayVideosSample.Grimm.videos[0].site.name}",
"${Response.Video.Size}": "1080",
"${Response.Video.Type}": "${ScreenplayVideosSample.Grimm.videos[0].type.name}"
}
]
}
""".trimIndent()
val Inception = """
{
"${Response.Id}": "${TmdbScreenplayIdSample.Inception.value}",
"${Response.Results}": [
{
"${Response.Video.Id}": "${ScreenplayVideosSample.Inception.videos[0].id.value}",
"${Response.Video.Key}": "${ScreenplayVideosSample.Inception.videos[0].key}",
"${Response.Video.Name}": "${ScreenplayVideosSample.Inception.videos[0].title}",
"${Response.Video.Site}": "${ScreenplayVideosSample.Inception.videos[0].site.name}",
"${Response.Video.Size}": "1080",
"${Response.Video.Type}": "${ScreenplayVideosSample.Inception.videos[0].type.name}"
}
]
}
""".trimIndent()
val TheWolfOfWallStreet = """
{
"${Response.Id}": "${TmdbScreenplayIdSample.TheWolfOfWallStreet.value}",
"${Response.Results}": [
{
"${Response.Video.Id}": "${ScreenplayVideosSample.TheWolfOfWallStreet.videos[0].id.value}",
"${Response.Video.Key}": "${ScreenplayVideosSample.TheWolfOfWallStreet.videos[0].key}",
"${Response.Video.Name}": "${ScreenplayVideosSample.TheWolfOfWallStreet.videos[0].title}",
"${Response.Video.Site}": "${ScreenplayVideosSample.TheWolfOfWallStreet.videos[0].site.name}",
"${Response.Video.Size}": "1080",
"${Response.Video.Type}": "${ScreenplayVideosSample.TheWolfOfWallStreet.videos[0].type.name}"
}
]
}
""".trimIndent()
val War = """
{
"${Response.Id}": "${TmdbScreenplayIdSample.War.value}",
"${Response.Results}": []
}
""".trimIndent()
}
| 8
|
Kotlin
|
2
| 6
|
f2e3993816452afaf6c3f1e7c7a384eb9a66c06e
| 4,621
|
CineScout
|
Apache License 2.0
|
app/src/main/java/com/tasks/example/countries/api/Language.kt
|
AlexanderPlyaka
| 167,533,739
| false
| null |
package com.tasks.example.countries.api
import com.google.gson.annotations.SerializedName
data class Language(
@SerializedName("iso639_1")
val iso6391: String,
@SerializedName("iso639_2")
val iso6392: String,
@SerializedName("name")
val name: String,
@SerializedName("nativeName")
val nativeName: String
)
| 0
|
Kotlin
|
0
| 0
|
80d87cf8b1a2a2a6946c76dcb89c3e0cc8a510fd
| 339
|
Bordering-Countries
|
Apache License 2.0
|
app/src/main/java/com/juangm/randomusers/data/source/remote/retrofit/UsersService.kt
|
juangranadilla
| 182,758,014
| false
| null |
package com.juangm.randomusers.data.source.remote.retrofit
import com.juangm.randomusers.data.constants.RepositoryConstants.DEFAULT_PAGE
import com.juangm.randomusers.data.constants.RepositoryConstants.DEFAULT_PAGE_SIZE
import com.juangm.randomusers.data.constants.RepositoryConstants.DEFAULT_SEED
import com.juangm.randomusers.data.source.remote.dto.ResponseDto
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Query
interface UsersService {
@GET(" ")
fun getUsers(
@Query("page") page: Int = DEFAULT_PAGE,
@Query("results") results: Int = DEFAULT_PAGE_SIZE,
@Query("seed") seed: Int = DEFAULT_SEED
): Single<ResponseDto>
}
| 0
|
Kotlin
|
3
| 5
|
37ed5c2176b97845f6c3cb866cf1fb40f7da82b4
| 689
|
RandomUsers
|
Apache License 2.0
|
src/main/kotlin/io/emeraldpay/dshackle/upstream/finalization/FinalizationData.kt
|
drpcorg
| 509,408,072
| false
|
{"Kotlin": 1449341, "Groovy": 585772, "Java": 148989, "JavaScript": 5522, "Shell": 646, "Makefile": 497, "Dockerfile": 103}
|
package io.emeraldpay.dshackle.upstream.finalization
import io.emeraldpay.api.proto.Common
class FinalizationData(
val height: Long,
val type: FinalizationType,
) {
override fun toString(): String {
return "FinalizationData($height, ${type.toBlockRef()})"
}
override fun equals(other: Any?): Boolean {
return when (other) {
is FinalizationData -> other.height == height && other.type == type
else -> false
}
}
}
enum class FinalizationType {
UNKNOWN,
SAFE_BLOCK,
FINALIZED_BLOCK,
;
companion object {
fun fromBlockRef(v: String): FinalizationType {
return when (v) {
"safe" -> SAFE_BLOCK
"finalized" -> FINALIZED_BLOCK
else -> UNKNOWN
}
}
}
fun toProtoFinalizationType(): Common.FinalizationType {
return when (this) {
FINALIZED_BLOCK -> Common.FinalizationType.FINALIZATION_FINALIZED_BLOCK
UNKNOWN -> Common.FinalizationType.UNRECOGNIZED
SAFE_BLOCK -> Common.FinalizationType.FINALIZATION_SAFE_BLOCK
}
}
fun toBlockRef(): String {
return when (this) {
FINALIZED_BLOCK -> "finalized"
SAFE_BLOCK -> "safe"
UNKNOWN -> "unknown"
}
}
}
fun Common.FinalizationType.fromProtoType(): FinalizationType {
return when (this) {
Common.FinalizationType.FINALIZATION_UNSPECIFIED -> FinalizationType.UNKNOWN
Common.FinalizationType.FINALIZATION_SAFE_BLOCK -> FinalizationType.SAFE_BLOCK
Common.FinalizationType.FINALIZATION_FINALIZED_BLOCK -> FinalizationType.FINALIZED_BLOCK
Common.FinalizationType.UNRECOGNIZED -> FinalizationType.UNKNOWN
}
}
| 2
|
Kotlin
|
12
| 38
|
2800556ff1587ccc7f7dd0aca7a43833048f035a
| 1,783
|
dshackle
|
Apache License 2.0
|
app/src/main/java/com/example/doughnutopia/ui/theme/Type.kt
|
mahmmedn19
| 664,349,956
| false
| null |
package com.example.doughnutopia.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
displayLarge = TextStyle(
fontFamily = Inter,
fontWeight = FontWeight.Bold,
fontSize = 54.sp,
color = Pink
),
titleLarge = TextStyle(
fontFamily = Inter,
fontWeight = FontWeight.SemiBold,
fontSize = 28.sp,
color = Pink
),
titleMedium = TextStyle(
fontFamily = Inter,
fontWeight = FontWeight.SemiBold,
fontSize = 20.sp,
color = Black,
),
titleSmall = TextStyle(
fontFamily = Inter,
fontWeight = FontWeight.Medium,
fontSize = 16.sp,
color = Black
),
labelLarge = TextStyle(
fontFamily = Inter,
fontWeight = FontWeight.SemiBold,
fontSize = 18.sp,
color = Black,
),
labelMedium = TextStyle(
fontFamily = Inter,
fontWeight = FontWeight.Medium,
fontSize = 14.sp,
color = Black_60
),
labelSmall = TextStyle(
fontFamily = Inter,
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
color = Color.Gray
),
bodyLarge = TextStyle(
fontFamily = Inter,
fontWeight = FontWeight.Medium,
fontSize = 18.sp,
color = Pink_60
),
bodyMedium = TextStyle(
fontFamily = Inter,
fontWeight = FontWeight.Medium,
fontSize = 14.sp,
color = Black_60
),
bodySmall = TextStyle(
fontFamily = Inter,
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
color = Black_60
),
)
| 0
|
Kotlin
|
0
| 1
|
470d767d8762837d104ce680347a040c32ac8ef2
| 1,869
|
Doughnutopia
|
MIT License
|
examples/src/jvmMain/kotlin/com/littlekt/examples/JvmRunner.kt
|
littlektframework
| 442,309,478
| false
|
{"Kotlin": 2170511, "Java": 1717152, "C": 111391}
|
package com.littlekt.examples
import com.littlekt.Context
import com.littlekt.ContextListener
import com.littlekt.createLittleKtApp
import com.littlekt.log.Logger
/**
* @author <NAME>
* @date 4/5/2024
*/
fun main(args: Array<String>) {
if (args.isNotEmpty()) {
println("args: ${args.joinToString { it }}")
}
Logger.setLevels(Logger.Level.DEBUG)
val arg = args.firstOrNull()
val exampleInfo = if (arg == null) availableExamples["-triangle"]!! else availableExamples[arg]
if (exampleInfo == null) {
println("Unknown example: $arg")
println("Available examples:")
println(availableExamples.keys.joinToString("\n"))
return
}
val (title, example) = exampleInfo
createApp("$title Example", example)
}
private fun createApp(title: String, start: (Context) -> ContextListener) =
createLittleKtApp {
width = 960
height = 540
this.title = title
traceWgpu = false
enableWGPULogging = false
}
.start(start)
| 14
|
Kotlin
|
12
| 316
|
100c37feefcfd65038a9cba4886aeb4a7d5632dc
| 1,059
|
littlekt
|
Apache License 2.0
|
app/src/main/java/xyz/skether/radiline/domain/manager/StationsManager.kt
|
vertex13
| 172,876,100
| false
| null |
package xyz.skether.radiline.domain.manager
import xyz.skether.radiline.data.db.AppDatabase
import xyz.skether.radiline.data.db.DBStation
import xyz.skether.radiline.data.db.DBUpdateInfo
import xyz.skether.radiline.data.shoutcast.ShoutcastApi
import xyz.skether.radiline.data.shoutcast.ShoutcastError
import xyz.skether.radiline.domain.*
import xyz.skether.radiline.utils.SuspendLazy
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class StationsManager @Inject constructor(private val api: ShoutcastApi, private val db: AppDatabase) {
private val freshDuration = TimeUnit.DAYS.toMillis(1)
@Throws(ShoutcastError::class)
suspend fun getTopStations(limit: Int = 10, offset: Int = 0, forceUpdate: Boolean = false): List<Station> {
val methodName = "get_top_stations"
val updateInfo = db.updateInfoDao().getByMethodName(methodName)
val itemsNumber = limit + offset
if (!forceUpdate
&& updateInfo != null
&& updateInfo.itemsNumber >= itemsNumber
&& updateInfo.updatedAt > freshTime()
) {
// Return the local data.
return db.stationDao().getTop(limit, offset).map(::stationFromDB)
}
val response = api.getTopStations(limit, offset)
db.stationDao().insert(response.stations.map { stationResponseToDB(it, null) })
db.updateInfoDao().insert(DBUpdateInfo(methodName, itemsNumber))
return response.stations.map(::stationFromResponse)
}
@Throws(ShoutcastError::class)
suspend fun searchStations(query: String, limit: Int = 10, offset: Int = 0): List<Station> {
val response = api.searchStations(query, limit, offset)
return response.stations.map(::stationFromResponse)
}
@Throws(ShoutcastError::class)
suspend fun getStationsByGenreId(
genreId: Long, limit: Int = 10, offset: Int = 0, forceUpdate: Boolean = false
): List<Station> {
val lazyLocalData = SuspendLazy { db.stationDao().getByGenreId(genreId, limit, offset) }
if (!forceUpdate && isDataFresh(freshTime(), lazyLocalData.getValue(), limit)) {
return lazyLocalData.getValue().map(::stationFromDB)
}
return try {
val externalData = api.getStationsByGenreId(genreId, limit, offset)
db.tuneInDao().insert(externalData.tuneInList.map(::tuneResponseToDB))
db.stationDao().insert(externalData.stations.map { stationResponseToDB(it, genreId) })
externalData.stations.map(::stationFromResponse)
} catch (e: ShoutcastError) {
if (!forceUpdate && lazyLocalData.getValue().size == limit) {
lazyLocalData.getValue().map(::stationFromDB)
} else {
throw e
}
}
}
private fun freshTime(): Long = System.currentTimeMillis() - freshDuration
/**
* The [dbStations] is not fresh if at least one station is updated before the [freshTime]
* or the [dbStations]' size is not equals to [expectedSize].
*/
private fun isDataFresh(freshTime: Long, dbStations: List<DBStation>, expectedSize: Int): Boolean {
return dbStations.size == expectedSize && dbStations.find { freshTime > it.updatedAt } == null
}
}
| 0
|
Kotlin
|
1
| 2
|
ad8d16d044f16b137d5dd13f0afa9f1b511fc4c6
| 3,280
|
Radiline
|
MIT License
|
2022/kotlin/src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day24Test.kt
|
dirkgroot
| 724,049,902
| false
|
{"Kotlin": 209352, "Rust": 125553, "Clojure": 80411}
|
package nl.dirkgroot.adventofcode.year2022
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import nl.dirkgroot.adventofcode.util.input
import nl.dirkgroot.adventofcode.util.invokedWith
private fun solution1(input: String) = Valley.parse(input).let { valley ->
generateSequence(valley) { it.next() }
.takeWhile { it.map[it.destinationY][it.destinationX] != '*' }
.count()
}
private fun solution2(input: String) = Valley.parse(input).let { valley ->
val (m1, goal1) = generateSequence(valley) { it.next() }.withIndex()
.first { (_, v) -> v.map[v.destinationY][v.destinationX] == '*' }
goal1.reset(goal1.destinationY, goal1.destinationX)
val (m2, start) = generateSequence(goal1) { it.next() }.withIndex()
.first { (_, v) -> v.map[Valley.START_Y][Valley.START_X] == '*' }
start.reset(Valley.START_Y, Valley.START_X)
val (m3, _) = generateSequence(start) { it.next() }.withIndex()
.first { (_, v) -> v.map[v.destinationY][v.destinationX] == '*' }
m1 + m2 + m3
}
private class Valley(val map: Array<Array<Char>>, val blizzards: List<Blizzard>) {
val height = map.size
val width = map[0].size
val destinationY = map.lastIndex
val destinationX = map.last().lastIndex - 1
companion object {
const val START_Y = 0
const val START_X = 1
fun parse(input: String): Valley {
val lines = input.lines()
val map = lines.mapIndexed { _, line ->
line.map { c -> if (c == '#' || c == '.') c else '.' }.toTypedArray()
}.toTypedArray()
val blizzards = lines.flatMapIndexed { y, line ->
line.withIndex()
.filter { (_, v) -> v != '#' && v != '.' }
.map { (x, c) -> Blizzard(y, x, Direction.parse(c)) }
}
map[START_Y][START_X] = '*'
return Valley(map, blizzards)
}
}
fun next(): Valley {
val nextBlizzards = blizzards.map { blizzard ->
val (dy, dx) = when (blizzard.dir) {
Direction.U -> -1 to 0
Direction.D -> 1 to 0
Direction.L -> 0 to -1
Direction.R -> 0 to 1
}
val path = generateSequence(blizzard.y + dy to blizzard.x + dx) { (y, x) ->
(y + dy + height) % height to (x + dx + width) % width
}
val (newY, newX) = path.first { (y, x) -> map[y][x] != '#' }
Blizzard(newY, newX, blizzard.dir)
}
val nextMap = Array(map.size) { i -> map[i].copyOf() }
(1 until nextMap.lastIndex).forEach { y ->
(1 until nextMap[y].lastIndex).forEach { x ->
val setStar = sequenceOf(y to x - 1, y to x + 1, y - 1 to x, y + 1 to x)
.filter { (y, x) -> y >= 0 && x < width }
.any { (y, x) -> map[y][x] == '*' }
if (setStar) nextMap[y][x] = '*'
}
}
if (map[START_Y + 1][START_X] == '*') nextMap[START_Y][START_X] = '*'
if (map[destinationY - 1][destinationX] == '*') nextMap[destinationY][destinationX] = '*'
nextBlizzards.forEach { (y, x, _) -> nextMap[y][x] = '.' }
return Valley(nextMap, nextBlizzards)
}
fun reset(startY: Int, startX: Int) {
map.indices.forEach { y -> map[y].indices.forEach { x -> if (map[y][x] != '#') map[y][x] = '.' } }
map[startY][startX] = '*'
}
data class Blizzard(val y: Int, val x: Int, val dir: Direction)
enum class Direction {
U, D, L, R;
companion object {
fun parse(c: Char) = when (c) {
'^' -> U
'v' -> D
'<' -> L
'>' -> R
else -> throw IllegalArgumentException()
}
}
}
}
//===============================================================================================\\
private const val YEAR = 2022
private const val DAY = 24
class Day24Test : StringSpec({
"example part 1" { ::solution1 invokedWith exampleInput shouldBe 18 }
"part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 242 }
"example part 2" { ::solution2 invokedWith exampleInput shouldBe 54 }
"part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 720 }
})
private val exampleInput =
"""
#.######
#>>.<^<#
#.<..<<#
#>v.><>#
#<^v^^>#
######.#
""".trimIndent()
| 1
|
Kotlin
|
0
| 0
|
fe29ca58f33859150b5497fb5baa3410fa453a7c
| 4,547
|
adventofcode
|
MIT License
|
androidApp/src/main/java/com/alwinsden/finalebuild/android/RoutingControls.kt
|
xGamma-in
| 704,764,615
| false
|
{"Kotlin": 57010, "Swift": 17088, "Ruby": 1742}
|
package com.alwinsden.finalebuild.android
import androidx.compose.runtime.Composable
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.alwinsden.finalebuild.android.facilities.CarTech
@Composable
fun RoutingControl() {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "cartech") {
composable("home") { Home() }
composable("cartech") { CarTech(navController) }
}
}
| 0
|
Kotlin
|
1
| 1
|
826c23236db0960cbf85c62ca5c8b92693f5d853
| 553
|
HandyConnect
|
MIT License
|
src/main/kotlin/io/datawire/loom/core/validation/Validator.kt
|
datawire
| 92,783,521
| false
| null |
package io.datawire.loom.core.validation
import com.fasterxml.jackson.core.JsonPointer
import com.fasterxml.jackson.databind.JsonNode
abstract class Validator {
abstract fun validate(root: JsonNode)
protected fun path(path: String): JsonPointer = JsonPointer.compile(path)
}
| 0
|
Kotlin
|
0
| 0
|
b7208a9bbb673d4fa87b436c125227a55d9f2049
| 281
|
loomctl
|
Apache License 2.0
|
app/src/main/java/com/burakdemir/ExziCase/MainActivity.kt
|
brkdoc
| 763,975,208
| false
|
{"Kotlin": 31593}
|
package com.burakdemir.ExziCase
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupWithNavController
import com.burakdemir.ExziCase.databinding.ActivityMainBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private var _binding: ActivityMainBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
supportFragmentManager.findFragmentById(R.id.mainNavHostFragment)?.let { binding.bottomNavigationView.setupWithNavController(it.findNavController()) }
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 0
|
d7707166de754e129883b868fbb433c238bb12d1
| 937
|
exzi-case
|
MIT License
|
amalia-core/src/main/java/com/vicidroid/amalia/core/persistance/PersistableState.kt
|
vicidroiddev
| 171,361,804
| false
| null |
package com.vicidroid.amalia.core.persistance
import android.os.Parcelable
import androidx.lifecycle.SavedStateHandle
interface PersistableState {
var savedStateHandle: SavedStateHandle
fun <V> consumePersisted(key: String): V {
return savedStateHandle.remove(key) ?: error("$key could not be found.")
}
fun <V> consumePersistedOrDefault(key: String, defaultValue: () -> V): V {
return savedStateHandle.remove(key) ?: defaultValue.invoke()
}
fun <V> consumePersistedOrNull(key: String): V? {
return savedStateHandle.remove(key)
}
fun <V> persist(key: String, value: V) {
savedStateHandle[key] = value
}
fun persistViewState(owner: String, state: Parcelable) {
savedStateHandle[viewStateKey(owner)] = state
}
fun removeViewState(owner: String) {
savedStateHandle.remove<Any?>(viewStateKey(owner))
}
fun viewStateKey(owner: String) = "${owner}_view_state"
}
| 7
|
Kotlin
|
0
| 9
|
0a4facc243feefe3f982f7f2915ccc5541dc321b
| 969
|
amalia
|
Apache License 2.0
|
muirwik/muirwik-testapp/src/main/kotlin/com/ccfraser/muirwik/testapp/TestRadioButtons.kt
|
egorsni
| 325,822,400
| false
| null |
package com.ccfraser.muirwik.testapp
import com.ccfraser.muirwik.components.*
import com.ccfraser.muirwik.components.form.*
import com.ccfraser.muirwik.testapp.TestRadioButtons.ComponentStyles.paddingLeft12
import kotlinx.css.*
import react.*
import react.dom.br
import styled.StyleSheet
import styled.css
import styled.styledDiv
class TestRadioButtons : RComponent<RProps, TestRadioButtons.MyTestState>() {
private var radioValue: String = "a"
private var gender1Value: String = "female"
class MyTestState(var gender2Value: String) : RState
init {
state = MyTestState("male")
}
object ComponentStyles : StyleSheet("ComponentStyles", isStatic = true) {
val paddingLeft12 by css {
paddingLeft = 12.px
}
}
override fun RBuilder.render() {
// For building things that we don't want to render now (e.g. the component will render it later), we need another builder
// Update: Now you can actually pass in addAsChild as false instead.
val altBuilder = RBuilder()
mTypography("Radio options and groups")
styledDiv {
css { display = Display.inlineFlex; marginTop = 16.px }
mRadioGroup(value = radioValue, onChange = { _, value -> setState { radioValue = value } }) {
css { display = Display.inlineFlex }
mRadio(value = "a")
// The icons are more for a checkbox type control, but for fun, we shall put the star here too
mRadio(value = "b") {
attrs.icon = altBuilder.mIcon("star")
}
}
mRadioGroup(value = radioValue, onChange = { _, value -> setState { radioValue = value } }) {
css { display = Display.inlineFlex }
mFormControlLabel("With Label C", value = "c", control = altBuilder.mRadio()) { css(paddingLeft12) } // With a label it seems to need a bit of left padding
mFormControlLabel("With Label D", value = "d", control = altBuilder.mRadio()) { css(paddingLeft12) } // With a label it seems to need a bit of left padding
}
}
br {}
styledDiv {
css { display = Display.inlineFlex; marginTop = 16.px }
mFormControl(component = MFormControlComponent.fieldSet) {
css { display = Display.inlineFlex }
mFormLabel("Gender", required = true, component = "legend")
mRadioGroup(value = state.gender2Value, onChange = { _, value -> setState { gender2Value = value; println("Value: $value") } }) {
mFormControlLabel("Female", value = "female", control = altBuilder.mRadio())
mFormControlLabel("Male", value = "male", control = altBuilder.mRadio())
mFormControlLabel("Other", value = "other", control = altBuilder.mRadio())
mFormControlLabel("Disabled Option", value = "disabled", disabled = true, control = altBuilder.mRadio())
}
}
mFormControl(component = MFormControlComponent.fieldSet, required = true, error = true) {
css { display = Display.inlineFlex }
mFormLabel("Gender2", required = true, component = "legend")
mRadioGroup(value = gender1Value, name = "gender1", onChange = { _, value -> setState { gender1Value = value; println("Value: $value") } }) {
mFormControlLabel("Male", value = "male", control = altBuilder.mRadio())
mFormControlLabel("Female", value = "female", control = altBuilder.mRadio())
mFormControlLabel("Other", value = "other", control = altBuilder.mRadio())
mFormControlLabel("Disabled Option", value = "disabled", disabled = true, control = altBuilder.mRadio())
}
}
mFormControl(component = MFormControlComponent.fieldSet, required = true, error = true) {
css { display = Display.inlineFlex }
mFormLabel("Gender3", required = true, component = "legend")
mRadioGroup(value = gender1Value, name = "gender1", onChange = { _, value -> setState { gender1Value = value; println("Value: $value") } }) {
// Slightly shorthand, practically does the same as the mFormControlLabel above.
mRadioWithLabel("Male", color = MOptionColor.primary, value = "male", labelPlacement = MLabelPlacement.start)
mRadioWithLabel("Female", color = MOptionColor.primary, value = "female", labelPlacement = MLabelPlacement.start)
mRadioWithLabel("Other", color = MOptionColor.primary, value = "other", labelPlacement = MLabelPlacement.start)
mRadioWithLabel("Disabled Option", value = "disabled", disabled = true, labelPlacement = MLabelPlacement.start)
}
mTypography("Label Placement = start")
}
}
mTypography {
+"State options... gender1Value by regular var is ${gender1Value}, state.gender2Value is ${state.gender2Value}"
}
}
}
fun RBuilder.testRadioButtons() = child(TestRadioButtons::class) {}
| 0
|
Kotlin
|
0
| 0
|
fa1bfeeecd5469e4b60ca5cb82826853c31d7864
| 5,224
|
Binvest
|
MIT License
|
app/src/main/java/com/jaresinunez/bitfitpt1/FoodLogFragment.kt
|
jaresinunez
| 721,446,150
| false
|
{"Kotlin": 17416}
|
package com.jaresinunez.bitfitpt1
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jaresinunez.bitfitpt1.Constants.itemAdapter
import com.jaresinunez.bitfitpt1.databinding.ActivityMainBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* A simple [Fragment] subclass.
* Use the [FoodLogFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class FoodLogFragment : Fragment() {
private lateinit var foodItemsRecyclerView: RecyclerView
private lateinit var binding: ActivityMainBinding
private val foods = mutableListOf<DisplayItem>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Change this statement to store the view in a variable instead of a return statement
val view = inflater.inflate(R.layout.fragment_food_log, container, false)
// Add these configurations for the recyclerView and to configure the adapter
val layoutManager = LinearLayoutManager(context)
foodItemsRecyclerView = view.findViewById(R.id.food_recycler_view)
foodItemsRecyclerView.layoutManager = layoutManager
foodItemsRecyclerView.setHasFixedSize(true)
itemAdapter = ItemAdapter(
view.context,
foods
)
foodItemsRecyclerView.adapter = itemAdapter
lifecycleScope.launch {
(context?.applicationContext as ItemApplication).db.foodItemDao().getAll()
.collect { databaseList ->
val mappedList = databaseList.map { entity ->
DisplayItem(
entity.name,
entity.calories
)
}
withContext(Dispatchers.Main) {
foods.clear()
foods.addAll(mappedList)
itemAdapter.notifyDataSetChanged()
}
}
}
foodItemsRecyclerView.layoutManager = LinearLayoutManager(activity).also {
val dividerItemDecoration = DividerItemDecoration(activity, it.orientation)
foodItemsRecyclerView.addItemDecoration(dividerItemDecoration)
}
val addFoodButton = view.findViewById<Button>(R.id.add_food_button)
addFoodButton.setOnClickListener {
val intent = Intent(activity, FoodDetailsActivity::class.java)
startActivity(intent)
}
// Update the return statement to return the inflated view from above
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Call the new method within onViewCreated
}
companion object {
fun newInstance() : FoodLogFragment {
return FoodLogFragment()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
70d9f2508fd4150e1e4250ca9cbe322d7e0386a9
| 3,481
|
BitFitPt2
|
Apache License 2.0
|
EventDemo/app/src/main/java/com/example/eventsdemoapp/MainActivity.kt
|
kristiania-android-course-2021
| 330,145,998
| false
| null |
package com.example.eventsdemoapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.evgenii.jsevaluator.JsEvaluator
import com.evgenii.jsevaluator.interfaces.JsCallback
class MainActivity : AppCompatActivity(), View.OnClickListener {
var jsEvaluator: JsEvaluator? = null
var editText: EditText? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
jsEvaluator = JsEvaluator(this)
var button1 = findViewById(R.id.button1) as Button // Using typecast
var button2 = findViewById<Button>(R.id.button2) // Using generic
var button3 = findViewById<Button>(R.id.button3) // Using generic
editText = findViewById<EditText>(R.id.editText)
button2.setOnClickListener( object: View.OnClickListener{
override fun onClick(view: View?) {
showToast(view as Button)
}
})
button1.setOnClickListener { view: View ->
var expression = editText?.editableText.toString()
calculate(expression!!)
}
button3.setOnClickListener(this)
editText?.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable) {
var expression = editable.toString()
if( expression.isNotBlank() ){
var lastChar = expression.get(expression.length-1);
if(lastChar== '=') {
calculate( expression.substring(0, expression.length-1) )
}
}
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
})
}
fun calculate(expression: String) {
jsEvaluator?.evaluate(expression, object : JsCallback {
override fun onResult(result: String) {
editText?.setText(result);
}
override fun onError(errorMessage: String) {
editText?.setText(errorMessage);
}
})
}
override fun onClick(view: View?) {
//Checking id of the view
when(view?.id) {
R.id.button3 ->
showToast(view as Button)
}
}
fun showToast(button:Button?) {
//Toasts are short lived pop up messages which appear and then auto disappear
Toast.makeText(this, button?.text, Toast.LENGTH_LONG).show()
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
Log.d(this.javaClass.simpleName, event.toString())
return super.onTouchEvent(event)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.demo_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.item_headphone->
Toast.makeText(this, getString(R.string.heaphone), Toast.LENGTH_LONG).show()
R.id.item_help->
Toast.makeText(this, getString(R.string.help), Toast.LENGTH_LONG).show()
R.id.item3->
Toast.makeText(this, getString(R.string.bell_menu), Toast.LENGTH_LONG).show()
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
super.onBackPressed()
Log.d(this.javaClass.simpleName,"onBackPressed")
}
}
| 0
|
Kotlin
|
2
| 1
|
a84e0e12fc62129601a58c1016c59199371767b0
| 3,926
|
Lecture-03
|
Apache License 2.0
|
app/src/main/java/io/navendra/kwitter/KwitterLog.kt
|
navi25
| 183,168,035
| false
| null |
package io.navendra.kwitter
import android.util.Log
object KwitterLog {
fun d(message : ()->String){
Log.d("Kwitter",message.invoke())
}
}
| 0
|
Kotlin
|
0
| 0
|
f65adee2f47da4c1d288b32a35f4d3ce9d4c8916
| 159
|
Kwitter
|
MIT License
|
authorization-server/core/src/main/kotlin/mc/oauth2/providers/DelegatingAuthenticationProvider.kt
|
mchalabine
| 148,293,942
| false
|
{"Kotlin": 60578}
|
package mc.oauth2.providers
import mc.oauth2.*
import mc.oauth2.integration.AuthenticationResult
import mc.oauth2.integration.AuthenticationResult.AUTHENTICATED
import mc.oauth2.integration.AuthenticationService
import org.springframework.security.authentication.AuthenticationProvider
import org.springframework.security.authentication.AuthenticationServiceException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import kotlin.reflect.KClass
import kotlin.reflect.full.isSubclassOf
/**
* Knows how to authenticate using AuthenticationService delegate.
*
* @author <NAME>
*/
internal class DelegatingAuthenticationProvider(
private val authenticationService: AuthenticationService) : AuthenticationProvider {
@Throws(AuthenticationException::class)
override fun authenticate(authentication: Authentication): Authentication {
val principal = getPrincipal(authentication)
val credentials = getCredentials(authentication)
return authenticate(principal, credentials)
}
private fun authenticate(principal: Principal, credentials: Credentials): Authentication {
val result = authenticationService.authenticate(principal, credentials)
return authenticate(principal, credentials, result)
}
private fun authenticate(principal: Principal, credentials: Credentials,
authentication: AuthenticationResult): Authentication {
validate(authentication)
return getValidAuthenticationToken(principal, credentials)
}
private fun getValidAuthenticationToken(principal: Principal,
credentials: Credentials): Authentication {
val roles = getValidAuthenticationDesiredRoles()
return getValidAuthenticationToken(principal, credentials, roles)
}
private fun getValidAuthenticationToken(principal: Principal, credentials: Credentials,
roles: Collection<GrantedAuthority>): Authentication {
return UsernamePasswordAuthenticationToken(principal, credentials, roles)
}
private fun getValidAuthenticationDesiredRoles(): Collection<GrantedAuthority> {
return arrayListOf(SimpleGrantedAuthority("ROLE_${Roles.USER}"))
}
private fun validate(authenticationResult: AuthenticationResult) {
if (!isAuthenticated(authenticationResult)) {
throwTheOnlyExceptionAllowed()
}
}
private fun throwTheOnlyExceptionAllowed() {
throwExceptionThatMasksTheActualProblem()
}
private fun throwExceptionThatMasksTheActualProblem() {
throw AuthenticationServiceException(MSG_AUTHENTICATION_FAILURE)
}
override fun supports(authenticationJavaClass: Class<*>): Boolean {
val expected = getSupportedTokenClass()
val actual = getKotlinClass(authenticationJavaClass)
return actual.isSubclassOf(expected)
}
private fun getPrincipal(authentication: Authentication): Principal {
val principal = authentication.principal
return getPrincipal(principal)
}
private fun getPrincipal(principal: Any) = getPrincipal(principal.toString())
private fun getPrincipal(principal: String) = Principal.valueOf(principal)
private fun getKotlinClass(authentication: Class<*>) = authentication.kotlin
private fun isAuthenticated(authenticationResult: AuthenticationResult) =
AUTHENTICATED == authenticationResult
private fun getCredentials(authentication: Authentication): Credentials {
val credentials = authentication.credentials
return getCredentials(credentials)
}
private fun getCredentials(credentials: Any) = getCredentials(credentials.toString())
private fun getCredentials(credentials: String) = Credentials.valueOf(credentials)
private fun getSupportedTokenClass(): KClass<UsernamePasswordAuthenticationToken> {
return UsernamePasswordAuthenticationToken::class
}
}
| 3
|
Kotlin
|
0
| 0
|
ffb7dd85df9f1ba46cce0fbfb06d756b95c0c992
| 4,281
|
mc-oauth2-spring
|
Apache License 2.0
|
app/src/main/java/com/anmolsahi/broncoforreddit/utils/Mappers.kt
|
sahianmol1
| 680,504,355
| false
|
{"Kotlin": 348917, "Shell": 4486}
|
package com.anmolsahi.broncoforreddit.utils
import com.anmolsahi.domain.model.SavedPost
import com.anmolsahi.domain.models.RedditPost
fun RedditPost.asSavedPost() = SavedPost(
id = this.id,
subName = this.subName,
title = this.title,
description = this.description,
upVotes = this.upVotes,
comments = this.comments,
imageUrls = this.imageUrls,
postUrl = this.postUrl,
videoUrl = this.videoUrl,
gifUrl = this.gifUrl,
author = this.author,
after = this.after,
)
fun SavedPost.toRedditPost(): RedditPost = RedditPost(
id = id,
subName = subName,
title = title,
description = description,
upVotes = upVotes,
comments = comments,
imageUrls = imageUrls,
postUrl = postUrl,
videoUrl = videoUrl,
gifUrl = gifUrl,
author = author,
after = after,
)
| 6
|
Kotlin
|
1
| 1
|
66da5b4273299297a0944f89433aa2db8403d9e3
| 838
|
Bronco-for-Reddit
|
MIT License
|
inference/src/main/kotlin/io/kinference/operators/layer/recurrent/RecurrentLayer.kt
|
cybernetics
| 324,970,047
| true
|
{"Kotlin": 461291, "PureBasic": 24490}
|
package io.kinference.operators.layer.recurrent
import io.kinference.data.tensors.Tensor
abstract class RecurrentLayer(val hiddenSize: Int, val activations: List<String>, val direction: String) {
abstract fun apply(inputList: List<Tensor?>): List<Tensor?>
}
| 0
| null |
0
| 0
|
8aa3295f112353949562750b83991b7ea8b83cf2
| 264
|
kinference
|
Apache License 2.0
|
feature-startscreen/src/main/java/com/tagakov/startscreen/api/StartScreenDependencies.kt
|
Tagakov
| 138,186,459
| false
|
{"Kotlin": 28050}
|
package com.tagakov.startscreen.api
import com.tagakov.common.ComponentDependencies
import com.tagakov.common.di.Rx
import io.reactivex.Scheduler
interface StartScreenDependencies: ComponentDependencies {
fun userNameProvider(): UserNameProvider
fun startScreenNavigator(): StartScreenNavigator
@Rx.MainScheduler fun mainThread(): Scheduler
}
| 2
|
Kotlin
|
16
| 95
|
cdb03cb8a312d7fb5675b6b6e3cbbdf2e7157234
| 356
|
modules-and-dagger
|
MIT License
|
app/src/main/java/dev/rstockbridge/showstats2/api/SetlistfmApi.kt
|
rstockbridge
| 447,359,780
| false
| null |
package dev.rstockbridge.showstats2.api
import dev.rstockbridge.showstats2.api.models.SetlistData
import java.io.IOException
object SetlistfmApi : DataFetcher {
private val service: SetlistfmService =
RetrofitWrapper.retrofit.create(SetlistfmService::class.java)
override suspend fun getSetlistData(userId: String, pageIndex: Int): Response<SetlistData> {
return try {
val response = service.getSetlistData(userId, pageIndex)
if (response.isSuccessful) {
Response.Success(response.body()!!)
} else {
Response.Error
}
} catch (e: IOException) {
Response.Failure(e)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b0c9ee71928484ae8585ce12ed942142a62a5600
| 711
|
ShowStats2
|
MIT License
|
src/desktopMain/kotlin/io/Http.kt
|
raychenon
| 364,913,895
| false
| null |
@file:JvmName("HttpClientBuilder")
package io
import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.features.json.*
import okhttp3.OkHttpClient
actual fun buildHttpClient(): HttpClient {
val okHttpClient = OkHttpClient.Builder().build()
return HttpClient(OkHttp) {
install(JsonFeature) {
serializer = defaultSerializer()
}
engine {
preconfigured = okHttpClient
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4d8bb3c55a6f958bf3e499464fd2ec5b6a3d1c63
| 466
|
httpie.kt
|
MIT License
|
app/src/test/java/au/com/mealplanner/mealplanner/feature/main/WeeklyPlanActivityPresenterTest.kt
|
jess-leung
| 123,775,089
| false
|
{"Kotlin": 35798}
|
package au.com.mealplanner.mealplanner.feature.main
import au.com.mealplanner.mealplanner.data.db.dao.PlannedMealDao.PlannedMealWithMeal
import au.com.mealplanner.mealplanner.data.db.repository.PlannedMealRepository
import au.com.mealplanner.mealplanner.data.model.DayOfWeek.MONDAY
import au.com.mealplanner.mealplanner.testUtil.TestMealPlannerScheduler
import io.reactivex.Flowable
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
import org.mockito.Mockito.*
class WeeklyPlanActivityPresenterTest {
private lateinit var presenter: WeeklyPlanActivityPresenter
private lateinit var weeklyPlanView: WeeklyPlanView
private lateinit var plannedMealRepository: PlannedMealRepository
@Before
fun setUp() {
plannedMealRepository = Mockito.mock(PlannedMealRepository::class.java)
weeklyPlanView = mock(WeeklyPlanView::class.java)
presenter = WeeklyPlanActivityPresenter(plannedMealRepository, TestMealPlannerScheduler())
presenter.setView(weeklyPlanView)
}
@Test
fun shouldGoToAddMeal() {
presenter.goToAddMealActivity(MONDAY)
verify(weeklyPlanView).goToAddMeal(MONDAY)
}
@Test
fun shouldGetMealsGivenDayOfWeek() {
val plannedMealWithMeal = PlannedMealWithMeal()
plannedMealWithMeal.meal_name = "Teriyaki Chicken"
plannedMealWithMeal.day_of_week = "MONDAY"
plannedMealWithMeal.meal_type = "BREAKFAST"
val plannedMeals = arrayListOf(plannedMealWithMeal)
`when`(plannedMealRepository.getPlannedMeals()).thenReturn(Flowable.just(plannedMeals))
presenter.getAllPlannedMeals()
verify(plannedMealRepository).getPlannedMeals()
verify(weeklyPlanView).updateWeeklyMealPlan(plannedMeals)
}
}
| 0
|
Kotlin
|
0
| 0
|
114eceb65b5efbed4e985b1f7c0d1d675fd16bc2
| 1,777
|
meal-planner
|
Apache License 2.0
|
buildSrc/src/main/kotlin/Android.kt
|
atecaorg
| 483,473,306
| false
| null |
@file:Suppress("SpellCheckingInspection")
/**
* Created by dronpascal on 26.04.2022.
*/
object Android {
const val appId = "com.ateca"
const val minSdk = 23
const val targetSdk = 31
const val compileSdk = 31
const val versionCode = 1
const val versionName = "0.0.1"
const val buildTools = "30.0.3"
const val debugIdSuffix = ".dev"
}
| 1
|
Kotlin
|
0
| 3
|
aca913f87263d6eac4a8925c74e6e801729ba6bf
| 368
|
Ateca
|
Apache License 2.0
|
app/src/main/java/com/example/androidweather/mvi/MviIntent.kt
|
KwunHeiChan
| 328,347,388
| false
| null |
package com.example.androidweather.mvi
/**
* Immutable object which represent an view's intent.
*/
interface MviIntent
| 0
|
Kotlin
|
1
| 0
|
aaf1753e16aaa0bbf844323d317b752ca9582444
| 121
|
android-weather
|
Apache License 2.0
|
android-nsd-flow/src/main/java/de/aroio/library/nsd/flow/discovery/DiscoveryListenerFlow.kt
|
aroio
| 340,172,384
| false
| null |
package de.aroio.library.nsd.flow.discovery
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
import de.aroio.library.nsd.flow.DiscoveryStartFailed
import de.aroio.library.nsd.flow.DiscoveryStopFailed
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.ProducerScope
import kotlinx.coroutines.channels.sendBlocking
@ExperimentalCoroutinesApi
internal data class DiscoveryListenerFlow(
private val producerScope: ProducerScope<DiscoveryEvent>,
) : NsdManager.DiscoveryListener {
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
producerScope.sendBlocking(DiscoveryEvent.DiscoveryServiceFound(service = serviceInfo))
}
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {
producerScope.channel.close(DiscoveryStopFailed(serviceType, errorCode))
}
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {
producerScope.channel.close(DiscoveryStartFailed(serviceType, errorCode))
}
override fun onDiscoveryStarted(serviceType: String) {
producerScope.sendBlocking(DiscoveryEvent.DiscoveryStarted(registeredType = serviceType))
}
override fun onDiscoveryStopped(serviceType: String) {
producerScope.sendBlocking(DiscoveryEvent.DiscoveryStopped(serviceType = serviceType))
producerScope.channel.close()
}
override fun onServiceLost(service: NsdServiceInfo) {
producerScope.sendBlocking(DiscoveryEvent.DiscoveryServiceLost(service = service))
}
}
| 1
|
Kotlin
|
0
| 2
|
b66d32929f354fcb99b4ffb1f001b927bf265312
| 1,566
|
android-nsd-flow
|
Apache License 2.0
|
src/main/kotlin/relativity/math/WorldLine.kt
|
AlexanderScherbatiy
| 323,309,804
| false
| null |
package relativity.math
fun worldLineFromVelocity(
position: RelativityVector = ZeroRelativityVector,
velocity: SpaceVector = ZeroSpaceVector,
time: Double = 1.0,
): WorldLine {
val end = position + RelativityVector(time, time * velocity.x)
return WorldLine(start = position, end = end)
}
fun worldLineFromLength(
length: Double,
position: RelativityVector = ZeroRelativityVector,
velocity: SpaceVector = ZeroSpaceVector,
): WorldLine {
val end = position + RelativityVector(length / velocity.x, length)
return WorldLine(start = position, end = end)
}
data class WorldLine(val start: RelativityVector, val end: RelativityVector) {
private val v = end - start
/**
* start1 + s1 * v1 = start2 + s2 * v2
* start1 - start2 = - s1 * v1 + s2 * v2
* ds = -s1 * v1 + s2 * v2
*/
infix fun intersect(other: WorldLine): RelativityVector {
val ds = this.start - other.start
val b1 = ds.t
val b2 = ds.x
val a11 = -this.v.t
val a21 = -this.v.x
val a12 = other.v.t
val a22 = other.v.x
val det = determinant(a11, a12, a21, a22)
val det1 = determinant(b1, a12, b2, a22)
val s1 = det1 / det
return this.start + s1 * this.v
}
private fun determinant(a11: Double, a12: Double, a21: Double, a22: Double): Double = a11 * a22 - a12 * a21
}
| 0
|
Kotlin
|
0
| 0
|
ec9ced9d11bfc988755b496ec7234926dd83c249
| 1,396
|
RelativityTheoryShapes
|
MIT License
|
solar/src/main/java/com/chiksmedina/solar/bold/like/HeartLock.kt
|
CMFerrer
| 689,442,321
| false
|
{"Kotlin": 36591890}
|
package com.chiksmedina.solar.bold.like
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
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 com.chiksmedina.solar.bold.LikeGroup
val LikeGroup.HeartLock: ImageVector
get() {
if (_heartLock != null) {
return _heartLock!!
}
_heartLock = Builder(
name = "HeartLock", 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 = EvenOdd
) {
moveTo(6.25f, 7.2892f)
verticalLineTo(7.0f)
curveTo(6.25f, 5.191f, 6.7965f, 3.7253f, 7.8518f, 2.7155f)
curveTo(8.9015f, 1.711f, 10.3582f, 1.25f, 12.0f, 1.25f)
curveTo(13.6418f, 1.25f, 15.0985f, 1.711f, 16.1482f, 2.7155f)
curveTo(17.2036f, 3.7253f, 17.75f, 5.191f, 17.75f, 7.0f)
verticalLineTo(7.2892f)
curveTo(19.634f, 7.9875f, 21.0f, 9.8733f, 21.0f, 12.0992f)
curveTo(21.0f, 15.9375f, 18.0316f, 18.1516f, 15.5044f, 20.0368f)
curveTo(15.2417f, 20.2327f, 14.9838f, 20.4251f, 14.7344f, 20.6154f)
curveTo(13.8f, 21.3285f, 12.9f, 22.0f, 12.0f, 22.0f)
curveTo(11.1f, 22.0f, 10.2f, 21.3285f, 9.2656f, 20.6154f)
curveTo(9.0162f, 20.4251f, 8.7583f, 20.2327f, 8.4957f, 20.0368f)
curveTo(5.9684f, 18.1516f, 3.0f, 15.9375f, 3.0f, 12.0992f)
curveTo(3.0f, 9.8733f, 4.366f, 7.9875f, 6.25f, 7.2892f)
close()
moveTo(7.75f, 7.0f)
curveTo(7.75f, 5.4953f, 8.1973f, 4.4609f, 8.8889f, 3.7992f)
curveTo(9.586f, 3.1321f, 10.6294f, 2.75f, 12.0f, 2.75f)
curveTo(13.3706f, 2.75f, 14.414f, 3.1321f, 15.1112f, 3.7992f)
curveTo(15.8027f, 4.4609f, 16.25f, 5.4953f, 16.25f, 7.0f)
verticalLineTo(7.0013f)
curveTo(14.8849f, 6.9686f, 13.3895f, 7.533f, 12.0f, 8.9306f)
curveTo(10.6105f, 7.533f, 9.1151f, 6.9686f, 7.75f, 7.0013f)
verticalLineTo(7.0f)
close()
moveTo(12.0f, 11.25f)
curveTo(12.4142f, 11.25f, 12.75f, 11.5858f, 12.75f, 12.0f)
verticalLineTo(14.5f)
curveTo(12.75f, 14.9142f, 12.4142f, 15.25f, 12.0f, 15.25f)
curveTo(11.5858f, 15.25f, 11.25f, 14.9142f, 11.25f, 14.5f)
verticalLineTo(12.0f)
curveTo(11.25f, 11.5858f, 11.5858f, 11.25f, 12.0f, 11.25f)
close()
}
}
.build()
return _heartLock!!
}
private var _heartLock: ImageVector? = null
| 0
|
Kotlin
|
0
| 0
|
3414a20650d644afac2581ad87a8525971222678
| 3,332
|
SolarIconSetAndroid
|
MIT License
|
app/src/main/java/com/example/moviedb/di/RepositoryModule.kt
|
rootsavaris
| 454,421,632
| false
| null |
package com.example.moviedb.di
import com.example.moviedb.data.ILocalDataSource
import com.example.moviedb.data.IRemoteDataSource
import com.example.moviedb.data.IRepository
import com.example.moviedb.data.Repository
import com.example.moviedb.domain.mapper.MovieMapper
import com.example.moviedb.framework.database.LocalDataSource
import com.example.moviedb.framework.network.MovieServiceApi
import com.example.moviedb.framework.network.RemoteDataSource
import org.koin.dsl.module
val repositoryModule = module {
factory { provideLocalDataSource() }
factory { provideRemoteDataSource(get(), get()) }
single { provideRepository(get(), get()) }
}
fun provideRepository(iLocalDataSource: ILocalDataSource, iRemoteDataSource: IRemoteDataSource): IRepository {
return Repository(iLocalDataSource, iRemoteDataSource)
}
fun provideLocalDataSource(): ILocalDataSource {
return LocalDataSource()
}
fun provideRemoteDataSource(moviesServiceApi: MovieServiceApi, movieMapper: MovieMapper): IRemoteDataSource {
return RemoteDataSource(moviesServiceApi, movieMapper)
}
| 0
|
Kotlin
|
0
| 0
|
5689265eb121e084796d0321c2d5399ebe12daa7
| 1,086
|
ListMoviesDB
|
Apache License 2.0
|
src/main/kotlin/Coroutines.kt
|
welly87
| 291,587,161
| false
| null |
package com.github.jasync.mysql.example
import com.github.jasync.sql.db.Configuration
import com.github.jasync.sql.db.Connection
import com.github.jasync.sql.db.QueryResult
import com.github.jasync.sql.db.general.ArrayRowData
import com.github.jasync.sql.db.pool.ConnectionPool
import com.github.jasync.sql.db.pool.PoolConfiguration
import com.github.jasync.sql.db.postgresql.pool.PostgreSQLConnectionFactory
import kotlinx.coroutines.experimental.future.await
import kotlinx.coroutines.experimental.launch
import mu.KotlinLogging
import java.util.concurrent.TimeUnit
private val logger = KotlinLogging.logger {}
fun main(args: Array<String>)
{
val poolConfiguration = PoolConfiguration(
100, // maxObjects
TimeUnit.MINUTES.toMillis(15), // maxIdle
10_000, // maxQueueSize
TimeUnit.SECONDS.toMillis(30) // validationInterval
)
val connection: Connection = ConnectionPool(
PostgreSQLConnectionFactory(
Configuration(
username = "postgres",
password = "<PASSWORD>",
host = "localhost",
port = 5432,
database = "tutorial"
)), poolConfiguration
)
connection.connect().get()
launch {
val queryResult = connection.sendPreparedStatementAwait("select * from conditions limit 2")
println((queryResult.rows!![0] as ArrayRowData).columns.toList())
}
launch {
val future = connection.sendPreparedStatement("select * from conditions limit 2")
val queryResult = future.await()
println((queryResult.rows!![0] as ArrayRowData).columns.toList())
}
connection.disconnect().get()
}
suspend fun Connection.sendPreparedStatementAwait(query: String, values: List<Any> = emptyList()): QueryResult =
this.sendPreparedStatement(query, values).await()
| 0
|
Kotlin
|
0
| 0
|
afcfc935f91e61fb1b492c92d77fcdcfadce9e41
| 1,865
|
scifin-timescaledb
|
Apache License 2.0
|
tools/src/main/kotlin/pw/binom/material/PathResolver.kt
|
caffeine-mgn
| 223,796,620
| false
| null |
package pw.binom.material
/**
* Material file provider
*/
interface PathResolver {
fun getFiles(packageName: String): Collection<FSElement>?
fun getFile(path: String): MaterialSource?
fun getPackage(path: String): MaterialPackage?
}
interface MaterialSource : FSElement {
fun getSource(): String
}
interface MaterialPackage : FSElement
interface FSElement {
val path: String
}
| 6
|
Kotlin
|
0
| 4
|
e673acfcb20e2d62d8e68c43d395731bd9d9d882
| 402
|
mogot
|
Apache License 2.0
|
app/src/main/java/com/journiapp/stampapplication/presentation/view/StampActivity.kt
|
sairam1592
| 782,791,391
| false
|
{"Kotlin": 42500}
|
package com.journiapp.stampapplication.presentation.view
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.journiapp.stampapplication.common.DataSingleton
import com.journiapp.stampapplication.data.network.NetworkUtil
import com.journiapp.stampapplication.R
import com.journiapp.stampapplication.common.SharedPrefHelper
import com.journiapp.stampapplication.presentation.view.adapter.StampAdapter
import com.journiapp.stampapplication.model.API
import com.journiapp.stampapplication.model.LoginRequest
import com.journiapp.stampapplication.model.ProfileResponse
import com.journiapp.stampapplication.model.Stamp
import com.journiapp.stampapplication.model.StampRequest
import com.journiapp.stampapplication.model.StampResponse
import com.journiapp.stampapplication.model.UserInformation
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
/** Main screen. Shows stamps added by the user. */
class StampActivity : AppCompatActivity() {
var api: API? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// TODO: Refactor to compose
// setContent {
// MaterialTheme {
// // Compose view
// }
// }
setContentView(R.layout.activity_stamp)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
toolbar.title = "Stamps"
setSupportActionBar(toolbar)
val sharedPrefHelper = SharedPrefHelper(applicationContext)
api = NetworkUtil.providesRetrofit(applicationContext).create(API::class.java)
val user = sharedPrefHelper.loadUserInfoJson()
if (user == null) {
// Note: Programmatic login to speed things up, but we would need a proper login screen
val loginRequest = LoginRequest(
email = "<EMAIL>",
password = "<PASSWORD>"
)
/*api!!.login(loginRequest).enqueue(object : Callback<ProfileResponse> {
override fun onResponse(call: Call<ProfileResponse>, response: Response<ProfileResponse>) {
var userInfo = UserInformation()
NetworkUtil.getCookieString(response.headers())?.let { user?.sessionCookie = it }
sharedPrefHelper.saveUserInfo(userInfo)
bindStamps(response.body()!!.stamps)
addStamp()
}
override fun onFailure(call: Call<ProfileResponse>, t: Throwable) {
TODO("Handle failure")
}
})*/
} else {
/*api!!.getProfile().enqueue(object : Callback<ProfileResponse> {
override fun onResponse(call: Call<ProfileResponse>, response: Response<ProfileResponse>) {
bindStamps(response.body()!!.stamps)
// addStamp()
}
override fun onFailure(call: Call<ProfileResponse>, t: Throwable) {
}
})*/
}
findViewById<Button>(R.id.btn_search).setOnClickListener { openSearch() }
}
override fun onResume() {
super.onResume()
// addStamp()
}
fun bindStamps(stamp: List<Stamp>) {
var adapter = StampAdapter()
adapter.stamps = stamp
val rvStamps = findViewById<RecyclerView>(R.id.rv_stamps)
rvStamps.layoutManager = GridLayoutManager(applicationContext, 2)
rvStamps.adapter = adapter
adapter.notifyDataSetChanged()
}
/* fun addStamp() {
if (DataSingleton.countryCode == null) return
val request = StampRequest(
countryCode = DataSingleton.countryCode!!,
create = System.currentTimeMillis()
)
DataSingleton.countryCode = null
api!!.postStamp(request).enqueue(object : Callback<StampResponse> {
override fun onResponse(call: Call<StampResponse>, response: Response<StampResponse>) {
api!!.getProfile().enqueue(object : Callback<ProfileResponse> {
override fun onResponse(call: Call<ProfileResponse>, response: Response<ProfileResponse>) {
bindStamps(response.body()!!.stamps)
addStamp()
}
override fun onFailure(call: Call<ProfileResponse>, t: Throwable) {
}
})
}
override fun onFailure(call: Call<StampResponse>, t: Throwable) {
}
})
}*/
fun openSearch() {
startActivity(Intent(this, SearchActivity::class.java))
}
}
| 0
|
Kotlin
|
0
| 1
|
9696eca982c191143b98909c878ec25248525b8c
| 4,871
|
journi-android-stamp-challenge
|
Apache License 2.0
|
CountryApp/src/main/java/com/slee/country/api/CountriesApi.kt
|
sunglee413
| 377,619,239
| false
| null |
package com.slee.country.api
import com.slee.country.data.Country
import io.reactivex.Single
import retrofit2.Response
import javax.inject.Inject
class CountriesApi @Inject constructor(private val countriesService: CountriesService) {
fun getAllCountries(): Single<Response<List<Country>>> = countriesService.getAll()
}
| 0
|
Kotlin
|
0
| 0
|
4ad4d49effe7044da76c1bbaa832a32f5e74634a
| 328
|
CountryInfo
|
Apache License 2.0
|
app/src/main/java/com/jun/chatgpt/ui/main/api/ApiKeyEditDialog.kt
|
Jun19
| 609,916,083
| false
| null |
package com.jun.chatgpt.ui.main.api
import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.jun.chatgpt.R
import com.jun.template.common.Constants
import com.jun.template.common.GlobalConfig
import com.jun.template.common.extension.toast
/**
* api编辑dialog
*
* @author Jun
* @time 2023/3/12
*/
@Composable
fun ApiKeyEditDialog(onCancel: () -> Unit, onFirm: (String) -> Unit) {
var apiKey = ""
val ctx = LocalContext.current
AlertDialog(
onDismissRequest = { onCancel.invoke() },
title = { Text(text = stringResource(id = R.string.change_key)) },
text = {
DialogContent() {
apiKey = it
}
},
confirmButton = {
Button(onClick = {
if (apiKey.isEmpty()) {
ctx.toast(R.string.dialog_api_empty_tips)
return@Button
}
onFirm.invoke(apiKey)
}) {
Text(text = stringResource(id = R.string.dialog_confirm))
}
},
dismissButton = {
Button(onClick = {
onCancel.invoke()
}) {
Text(text = stringResource(id = R.string.dialog_cancel))
}
},
)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun DialogContent(onChangeText: (String) -> Unit) {
var text by remember { mutableStateOf(GlobalConfig.apiKey) }
val ctx = LocalContext.current
Column() {
Text(text = stringResource(id = R.string.recommend_content))
Spacer(modifier = Modifier.padding(10.dp))
Text(
modifier = Modifier
.clickable {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(Constants.APPLY_URL)
ctx.startActivity(intent)
},
text = stringResource(id = R.string.apply), color = MaterialTheme.colorScheme.primary,
fontSize = 15.sp,
textDecoration = TextDecoration.Underline
)
Spacer(modifier = Modifier.padding(10.dp))
TextField(
value = text,
onValueChange = {
text = it
onChangeText.invoke(text)
},
modifier = Modifier
.fillMaxWidth()
.padding(),
)
}
}
@Preview
@Composable
fun ApiKeyEditDialogPreview() {
ApiKeyEditDialog({}, {})
}
| 0
|
Kotlin
|
0
| 6
|
76690da48f2440cfa5ecb4e2b200e1cf6407683e
| 3,099
|
ChatGPT-App
|
MIT License
|
src/jsMain/kotlin/com/fgrutsch/pf/components/PFCard.kt
|
fgrutsch
| 697,150,309
| false
|
{"Kotlin": 58319, "HTML": 328}
|
package com.fgrutsch.pf.components
import androidx.compose.runtime.Composable
import com.fgrutsch.pf.PFClasses
import com.fgrutsch.pf.PFComponent
import com.fgrutsch.pf.pfc
import org.jetbrains.compose.web.dom.AttrBuilderContext
import org.jetbrains.compose.web.dom.ContentBuilder
import org.jetbrains.compose.web.dom.Div
import org.w3c.dom.HTMLDivElement
@Composable
fun PFCard(
classes: PFClasses = null,
attrs: AttrBuilderContext<HTMLDivElement>? = null,
content: ContentBuilder<HTMLDivElement>? = null,
) = Div(attrs.pfc(PFComponent.CARD, classes), content = content)
@Composable
fun PFCardBody(
classes: PFClasses = null,
attrs: AttrBuilderContext<HTMLDivElement>? = null,
content: ContentBuilder<HTMLDivElement>? = null,
) = Div(attrs.pfc(PFComponent.CARD_BODY, classes), content = content)
| 0
|
Kotlin
|
0
| 2
|
f2584c807e362fb2c3faad74e623ced568738a87
| 824
|
kotlin-compose-for-web
|
Apache License 2.0
|
sample/src/main/java/cn/nekocode/kotgo/sample/presentation/main/MeiziPresenter.kt
|
wangchang163
| 53,552,234
| true
|
{"Kotlin": 33572, "Python": 8369, "Java": 111}
|
package cn.nekocode.kotgo.sample.presentation.main
import cn.nekocode.kotgo.component.presentation.Presenter
import cn.nekocode.kotgo.component.util.LifecycleContainer
import cn.nekocode.kotgo.component.util.onUIInLifecycle
import cn.nekocode.kotgo.sample.data.dto.Meizi
import cn.nekocode.kotgo.sample.data.model.MeiziModel
/**
* Created by nekocode on 2015/11/20.
*/
class MeiziPresenter(val view: MeiziPresenter.ViewInterface): Presenter(view) {
interface ViewInterface: LifecycleContainer {
fun refreshMeizis(meizis: List<Meizi>)
}
fun getMeizis() {
MeiziModel.getMeizis(50, 1).onUIInLifecycle(view) {
view.refreshMeizis(it)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a562db11ed5e91af7300772fd6079d6813fe2cf8
| 691
|
kotgo
|
Apache License 2.0
|
test/src/commonMain/kotlin/com/rouge41/kmm/compose/test/demos/LazyColumnDemo.kt
|
cl3m
| 327,994,833
| false
| null |
package com.rouge41.kmm.compose.test.demos
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
internal fun LazyColumnDemo() {
val items = (1..25).map { "Line $it" }
androidx.compose.foundation.lazy.LazyColumn(modifier = Modifier.fillMaxSize()) {
item {
Text("Single\nWith\nMultiple\nLines")
}
item {
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus dui erat, consequat eget felis malesuada, gravida pellentesque massa. Suspendisse id aliquet ex. Praesent diam dui, consectetur et orci eu, interdum cursus tortor. Aenean quis laoreet lectus, quis consectetur orci. Quisque ac diam varius, malesuada lacus varius, semper nulla. Ut vitae faucibus justo. Fusce nibh tortor, pulvinar viverra urna et, porttitor viverra ipsum. Proin et lacus ac leo lacinia tempus. Suspendisse dictum tortor nec efficitur faucibus.")
}
items(items) {
Text(it)
Divider()
}
}
}
| 0
|
Kotlin
|
31
| 571
|
28336a846d0717d0464890d65552273410cd006a
| 1,204
|
multiplatform-compose
|
Apache License 2.0
|
app/src/main/java/com/sample/myapplication/api/ApiService.kt
|
Rajeshtechgeek
| 297,889,548
| false
|
{"Kotlin": 44192}
|
package com.sample.myapplication.api
import com.sample.myapplication.BuildConfig
import com.sample.myapplication.api.country.CountryResponse
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.logging.HttpLoggingInterceptor.Level
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
/**
* Used to connect to the Country API to fetch countries
*/
interface ApiService {
@GET("rest/v2/all ")
suspend fun getCountries(): CountryResponse
companion object {
private var instance: ApiService? = null
/**
* This method returns single instance of [ApiService]
*
* @return [ApiService] instance
*/
fun getInstance(): ApiService {
if (instance == null) { // Single Checked
synchronized(ApiService::class.java) {
if (instance == null) { // Double checked
instance = create()
}
}
}
return instance!!
}
private fun create(): ApiService {
val logger = HttpLoggingInterceptor().apply { level = Level.BASIC }
val client = OkHttpClient.Builder()
.addInterceptor(logger)
.build()
return Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::class.java)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7973cba7223b22f1e68408f49ebf94f2ce0507ce
| 1,614
|
Country-listing-app
|
Apache License 2.0
|
services/service-user/src/main/kotlin/io/github/rafaeljpc/alura/kafka/ecommerce/service/user/User.kt
|
rafaeljpc
| 337,831,493
| false
| null |
package io.github.rafaeljpc.alura.kafka.ecommerce.service.user
data class User(
val uuid: String,
val email: String,
)
| 0
|
Kotlin
|
0
| 0
|
b68e2660fe4bec33dab396f505b8f1907eadb902
| 128
|
alura-kafka
|
Apache License 2.0
|
app/src/main/java/com/gggames/hourglass/utils/rx/scheduler/SchedulerProvider.kt
|
giladgotman
| 252,945,764
| false
| null |
package com.idagio.app.core.utils.rx.scheduler
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class SchedulerProvider
constructor() : BaseSchedulerProvider {
override fun computation(): Scheduler {
return Schedulers.computation()
}
override fun io(): Scheduler {
return Schedulers.io()
}
override fun ui(): Scheduler {
return AndroidSchedulers.mainThread()
}
}
| 25
|
Kotlin
|
0
| 0
|
0f0fa11fbe1131387148e4d6d1b7d85c23d6e5f0
| 496
|
celebs
|
MIT License
|
src/main/kotlin/no/fdk/dataset/preview/model/Preview.kt
|
Informasjonsforvaltning
| 426,257,371
| false
|
{"Kotlin": 46599, "Java": 743, "Dockerfile": 632}
|
package no.fdk.dataset.preview.model
data class Preview(val table: Table?, val plain: Plain?)
| 1
|
Kotlin
|
0
| 0
|
ace34f688cba7f0ee42ee8e13dc46090777fb9c7
| 95
|
fdk-dataset-preview-service
|
Apache License 2.0
|
app/src/main/java/com/chandrabhan/robutest/adapter/ProductAdapter.kt
|
Chandrabhanaher
| 393,673,241
| false
| null |
package com.chandrabhan.robutest.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Filter
import android.widget.Filterable
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import com.bumptech.glide.Glide
import com.chandrabhan.robutest.R
import com.chandrabhan.robutest.models.ResponseData
import java.util.ArrayList
class ProductAdapter(
private val context: Context,
private var productList: MutableList<ResponseData>
) : RecyclerView.Adapter<ProductAdapter.ItemViewHolder>(){
var filerResult: List<ResponseData> = productList
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
return ItemViewHolder(
LayoutInflater.from(context).inflate(R.layout.product_items, parent, false)
)
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val items = productList[position]
holder.textId.text = items.id
if(items.images.isEmpty()){
Glide.with(context).load(R.drawable.ic_logo).into(holder.imageView)
}else{
Glide.with(context).load(items.images).into(holder.imageView)
}
holder.txtName.text = items.name
holder.txtPrice.text = items.price.toString()
}
override fun getItemCount(): Int {
return filerResult.size
}
class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
@BindView(R.id.textId)
lateinit var textId: TextView
@BindView(R.id.imageView)
lateinit var imageView: ImageView
@BindView(R.id.txtName)
lateinit var txtName: TextView
@BindView(R.id.txtPrice)
lateinit var txtPrice: TextView
init {
ButterKnife.bind(this, itemView)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3f3715cd9823ac362b1dad7b6c52db5cc78a0554
| 1,986
|
RobuTest
|
MIT License
|
app/src/main/java/ru/shadowsparky/messenger/response_utils/Attachments.kt
|
shadowsparky
| 148,388,054
| false
| null |
package ru.shadowsparky.messenger.response_utils
interface Attachments
| 0
|
Kotlin
|
0
| 0
|
c9c14e5226c692dbdcea559806263a4cea78b1ac
| 71
|
vk-messenger-two
|
The Unlicense
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.