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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Project/app/src/main/java/org/ionproject/android/offline/models/CatalogProgrammeTermInfo.kt
|
i-on-project
| 245,234,364
| false
| null |
package org.ionproject.android.offline.models
import com.fasterxml.jackson.annotation.JsonProperty
/**
NOTE: These classes are redundant since the same result could be achieved using the
catalog programmes and catalog programme classes. However, despite using JSON properties with the
same names, the name of the values within each class changes and makes it easier to understand
the parsing code
*/
/**
* This is the Term details for the chosen programme
*
* This represents the folder of the term chosen, where we can see the files exam schedule or a timetable
*
* Each element of the array is a ProgramInfoFile, and can either be an exam schedule or a timetable
*
*/
data class CatalogProgrammeTermInfo(
@JsonProperty("tree")
var files: List<CatalogProgrammeTermInfoFile>
)
| 8
|
Kotlin
|
0
| 4
|
c18e940a10b9bcc4e3511ca7fa2c647be5db9ff2
| 796
|
android
|
Apache License 2.0
|
vgscollect/src/main/java/com/verygoodsecurity/vgscollect/view/card/validation/RegexValidator.kt
|
verygoodsecurity
| 273,198,410
| false
|
{"Kotlin": 1128775, "Python": 210}
|
package com.verygoodsecurity.vgscollect.view.card.validation
import java.util.regex.Pattern
/** @suppress */
class RegexValidator(
internal val value: String,
override val errorMsg: String = DEFAULT_ERROR_MSG
) : VGSValidator {
private var pattern: Pattern = Pattern.compile(value)
override fun isValid(content: String): Boolean {
return pattern.matcher(content).matches()
}
internal companion object {
internal const val DEFAULT_ERROR_MSG = "REGEX_VALIDATION_ERROR"
}
}
| 6
|
Kotlin
|
9
| 8
|
119d3479daccc789039e3f5d9bc08d6e7e9556e5
| 520
|
vgs-collect-android
|
MIT License
|
src/main/kotlin/com/kentrino/graphql/UserResolver.kt
|
kentrino
| 200,906,140
| false
| null |
package com.kentrino.graphql
import com.coxautodev.graphql.tools.GraphQLResolver
import com.kentrino.db.Book
import com.kentrino.db.User
class UserResolver: GraphQLResolver<User> {
private val books: List<Book> = listOf(
Book(id = 1, title = "a"),
Book(id = 2, title = "b"),
Book(id = 3, title = "c")
)
fun book(user: User): Book? {
return books.find { it.id == user.id }
}
}
| 0
|
Kotlin
|
0
| 0
|
8f02cd7cc62e14b1d955b87f5a3f1eb9b1829101
| 443
|
graphql-ktor-minimal
|
Apache License 2.0
|
src/commonTest/kotlin/me/sbntt/mpp/math/units/RadiansTests.kt
|
SBNTT
| 315,407,967
| false
| null |
package me.sbntt.mpp.math.units
import me.sbntt.mpp.math.units.Radians.Extensions.radians
import me.sbntt.mpp.math.units.Degrees.Extensions.degrees
import me.sbntt.mpp.math.extensions.comparators.*
import kotlin.math.PI
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class RadiansTests {
@Test
fun testConstructor() {
assertTrue { 4.radians.value eq 4.0 }
assertTrue { (2 * PI).radians.value eq 0.0 }
assertTrue { (3 * PI).radians.value eq PI }
assertTrue { (-PI).radians.value eq PI }
}
@Test
fun testEquals() {
assertTrue { 4.radians eq 4.radians }
assertFalse { 5.radians eq 4.radians }
}
@Test
fun testEqualsToDegrees() {
assertFalse { 4.radians eq 4.degrees }
assertTrue { PI.radians eq 180.degrees }
assertTrue { 0.3839724354387525.radians eq 22.degrees }
assertTrue { 0.39269908169872414.radians eq 22.5.degrees }
}
@Test
fun testGreaterThan() {
assertTrue { 5.radians greaterThan 4.radians }
assertFalse { 4.radians greaterThan 4.radians }
assertTrue { 5.radians gt 4.radians }
assertFalse { 4.radians gt 4.radians }
}
@Test
fun testGreaterThanDegrees() {
assertTrue { PI.radians greaterThan 179.degrees }
assertFalse { PI.radians greaterThan 180.degrees }
assertTrue { PI.radians gt 179.degrees }
assertFalse { PI.radians gt 180.degrees }
}
@Test
fun testLowerThan() {
assertTrue { 4.radians lowerThan 5.radians }
assertFalse { 4.radians lowerThan 4.radians }
assertTrue { 4.radians lt 5.radians }
assertFalse { 4.radians lt 4.radians }
}
@Test
fun testLowerThanDegrees() {
assertTrue { PI.radians lowerThan 181.degrees }
assertFalse { PI.radians lowerThan 180.degrees }
assertTrue { PI.radians lt 181.degrees }
assertFalse { PI.radians lt 180.degrees }
}
@Test
fun testGreaterOrEquals() {
assertTrue { 5.radians greaterOrEquals 4.radians }
assertTrue { 4.radians greaterOrEquals 4.radians }
assertFalse { 3.radians greaterOrEquals 4.radians }
assertTrue { 5.radians geq 4.radians }
assertTrue { 4.radians geq 4.radians }
assertFalse { 3.radians geq 4.radians }
}
@Test
fun testGreaterOrEqualsToDegrees() {
assertTrue { PI.radians greaterOrEquals 179.degrees }
assertTrue { PI.radians greaterOrEquals 180.degrees }
assertFalse { PI.radians greaterOrEquals 181.degrees }
assertTrue { PI.radians geq 179.degrees }
assertTrue { PI.radians geq 180.degrees }
assertFalse { PI.radians geq 181.degrees }
}
@Test
fun testLowerOrEquals() {
assertTrue { 4.radians lowerOrEquals 5.radians }
assertTrue { 4.radians lowerOrEquals 4.radians }
assertFalse { 4.radians lowerOrEquals 3.radians }
assertTrue { 4.radians leq 5.radians }
assertTrue { 4.radians leq 4.radians }
assertFalse { 4.radians leq 3.radians }
}
@Test
fun testLowerOrEqualsToDegrees() {
assertTrue { PI.radians lowerOrEquals 181.degrees }
assertTrue { PI.radians lowerOrEquals 180.degrees }
assertFalse { PI.radians lowerOrEquals 179.degrees }
assertTrue { PI.radians leq 181.degrees }
assertTrue { PI.radians leq 180.degrees }
assertFalse { PI.radians leq 179.degrees }
}
}
| 0
|
Kotlin
|
0
| 0
|
6047c98e730d8fdff62c21921ffea4553642a330
| 3,520
|
mpp-game-math
|
MIT License
|
libs/clock/src/main/kotlin/ClockStore.kt
|
chadmarchand
| 320,885,997
| false
| null |
package com.chadmarchand.forgeofhistory.clock
class ClockStore {
private var gameTime = 1
fun setGameTime(gameTime: Int) {
this.gameTime = gameTime
}
fun getGameTime(): Int = gameTime
}
| 5
|
Kotlin
|
0
| 0
|
c9987610ef742f47c99913faf9a98e79f70fd80e
| 213
|
forge-of-history
|
MIT License
|
src/main/kotlin/me/ferrandis/textAnalyzer/controller/AnalysisController.kt
|
ferrandisme
| 689,373,192
| false
|
{"Kotlin": 10042}
|
package me.ferrandis.textAnalyzer.controller
import me.ferrandis.textAnalyzer.model.SentimentAnalysis
import me.ferrandis.textAnalyzer.service.AnalysisService
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Flux
@RestController
class AnalysisController(var service: AnalysisService) {
@PostMapping("v1/analysis")
fun dataAnalysis(@RequestBody request: String): Flux<SentimentAnalysis> {
return service.analyze(request);
}
}
| 0
|
Kotlin
|
0
| 0
|
b300e87eac242cb925246266bb0409df21d4c1fe
| 611
|
textAnalyzer
|
MIT License
|
src/main/kotlin/com/pedrovasconcelos/beautymanager/application/commands/scheduler/UpdateAppointment.kt
|
pedronvasconcelos
| 863,271,192
| false
|
{"Kotlin": 59054, "Dockerfile": 284}
|
package com.pedrovasconcelos.beautymanager.application.commands.scheduler
import arrow.core.Either
import arrow.core.left
import com.pedrovasconcelos.beautymanager.domain.scheduler.Appointment
import com.pedrovasconcelos.beautymanager.domain.scheduler.AppointmentRepository
import com.pedrovasconcelos.beautymanager.domain.scheduler.cancelAppointment
import com.pedrovasconcelos.beautymanager.domain.scheduler.completeAppointment
import com.pedrovasconcelos.beautymanager.domain.shared.BaseError
import com.pedrovasconcelos.beautymanager.domain.shared.NotFoundError
import org.springframework.stereotype.Service
import java.util.UUID
data class CompleteAppointment(
val appointmentId: UUID
)
@Service
class CompleteAppointmentHandler(private val appointmentRepository: AppointmentRepository) {
fun handler(request: CompleteAppointment): Either<BaseError, Appointment> {
val appointment = appointmentRepository.getAppointment(request.appointmentId)
.mapLeft { return Either.Left(it) }
.getOrNull() ?: return NotFoundError("Appointment not found").left()
val completedAppointment = completeAppointment(appointment)
return appointmentRepository.saveAppointment(completedAppointment)
.map { completedAppointment }
.mapLeft { return Either.Left(it) }
}
fun cancelAppointment(request: CompleteAppointment): Either<BaseError, Appointment> {
val appointment = appointmentRepository.getAppointment(request.appointmentId)
.mapLeft { return Either.Left(it) }
.getOrNull() ?: return NotFoundError("Appointment not found").left()
val completedAppointment = cancelAppointment(appointment)
return appointmentRepository.saveAppointment(completedAppointment)
.map { completedAppointment }
.mapLeft { return Either.Left(it) }
}
}
| 0
|
Kotlin
|
0
| 0
|
fbc30e5c6c032b29afef95dac7238389c82b26e6
| 1,880
|
beautymanager
|
MIT License
|
src/main/kotlin/com/erpvin/dto/ProductPhotoDto.kt
|
etertech
| 703,238,112
| false
|
{"Kotlin": 48485, "Dockerfile": 352}
|
package com.erpvin.dto
data class ProductPhotoDto(
val id: Long,
val photoLink: String
)
| 0
|
Kotlin
|
0
| 0
|
e80a3ca9ce2e9f972c156496280a4290e6679668
| 97
|
erp-vin-springboot-kotlin-demo
|
MIT License
|
AndroidApp/app/src/main/java/me/nya_n/notificationnotifier/repositories/sources/KeyValueDataStore.kt
|
ptkNktq
| 50,931,408
| false
| null |
package me.nya_n.notificationnotifier.repositories.sources
import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
open class KeyValueDataStore(
context: Context
) {
private val pref: SharedPreferences
init {
val key = MasterKey.Builder(context)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
pref = EncryptedSharedPreferences.create(
context,
"settings",
key,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}
protected fun get(key: String, defValue: String): String {
return pref.getString(key, defValue) ?: defValue
}
protected fun get(key: String, defValue: Int): Int {
return pref.getInt(key, defValue)
}
protected fun get(key: String, defValue: Boolean): Boolean {
return pref.getBoolean(key, defValue)
}
protected fun put(key: String, value: String) {
pref.edit {
putString(key, value)
}
}
protected fun put(key: String, value: Int) {
pref.edit {
putInt(key, value)
}
}
protected fun put(key: String, value: Boolean) {
pref.edit {
putBoolean(key, value)
}
}
}
| 1
|
Kotlin
|
0
| 1
|
38a98a9ed28f84ace48ac3dfc84c33a13a38cee7
| 1,495
|
AndroidNotificationNotifier
|
MIT License
|
src/main/kotlin/dev/arbjerg/ukulele/jda/ConversationListener.kt
|
Zudrak
| 548,085,793
| false
|
{"Kotlin": 91190, "Java": 8568, "Dockerfile": 282, "Batchfile": 197, "Shell": 99}
|
package dev.arbjerg.ukulele.jda
import ConversationAudioHandler
import dev.arbjerg.ukulele.audio.PCMToWAVConverter
import net.dv8tion.jda.api.audio.AudioReceiveHandler
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import net.dv8tion.jda.api.hooks.ListenerAdapter
import org.springframework.stereotype.Service
import java.io.ByteArrayInputStream
import java.io.File
import javax.sound.sampled.AudioFileFormat
import javax.sound.sampled.AudioFormat
import javax.sound.sampled.AudioInputStream
import javax.sound.sampled.AudioSystem
@Service
class ConversationListener () : ListenerAdapter() {
private var audioChannel : VoiceChannel? = null
private val conversationHandler = ConversationAudioHandler()
override fun onGuildVoiceUpdate(event: GuildVoiceUpdateEvent) {
if(event.member.user.id != event.jda.selfUser.id) {
return;
}
if(event.channelJoined != null) {
handleVoiceJoin(event.channelJoined!!.asVoiceChannel())
}else if(event.channelLeft != null) {
handleVoiceLeft()
}
}
override fun onMessageReceived(event: MessageReceivedEvent) {
if(event.message.contentRaw.startsWith("record")) {
// After receiving some audio data in the handler...
val pcmData = conversationHandler.getLast10SecondsOfAudio()
val outputPath = "output.wav"
try {
val file = File(outputPath)
AudioSystem.write(AudioInputStream(ByteArrayInputStream(pcmData), AudioReceiveHandler.OUTPUT_FORMAT, pcmData.size.toLong()), AudioFileFormat.Type.WAVE, file)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun handleVoiceJoin( voiceChannel : VoiceChannel) {
this.audioChannel = voiceChannel
val guild = audioChannel!!.guild
guild.audioManager.receivingHandler = conversationHandler
}
fun handleVoiceLeft() {
if(audioChannel == null){
return
}
var guild = audioChannel!!.guild
guild.audioManager.receivingHandler = null
}
}
| 0
|
Kotlin
|
0
| 0
|
fc64be67b6e3abe246cc5c65d0a70b5b36e4ab38
| 2,276
|
Chrisalaxelrto-bot
|
MIT License
|
src/main/kotlin/com/surfsoftconsulting/taskmaster/TaskmasterApplication.kt
|
surfsoft
| 318,549,532
| false
| null |
package com.surfsoftconsulting.taskmaster
class TaskmasterApplication {}
| 0
|
Kotlin
|
0
| 0
|
225746dfc6b37b11efba7f4330fbfc530d67e2f2
| 73
|
Taskmaster
|
Apache License 2.0
|
auth/src/main/java/studio/crud/feature/auth/authentication/AuthenticationServiceImpl.kt
|
crud-studio
| 390,327,908
| false
| null |
package studio.crud.feature.auth.authentication
import studio.crud.crudframework.crud.handler.CrudHandler
import studio.crud.crudframework.modelfilter.dsl.where
import studio.crud.crudframework.utils.component.componentmap.annotation.ComponentMap
import mu.KotlinLogging
import org.springframework.stereotype.Component
import studio.crud.feature.auth.authentication.method.base.AuthenticationMethodHandler
import studio.crud.feature.auth.authentication.method.enums.AuthenticationMethodType
import studio.crud.feature.auth.authentication.method.enums.UsernameType
import studio.crud.feature.auth.authentication.model.AuthenticationResultDTO
import studio.crud.feature.auth.authentication.model.CustomParamsDTO
import studio.crud.feature.auth.authentication.model.ForgotPasswordToken
import studio.crud.feature.auth.authentication.notifier.AuthenticationPostProcessor
import studio.crud.feature.auth.authentication.validation.*
import studio.crud.feature.auth.config.properties.AuthProperties
import studio.crud.feature.auth.entity.model.Entity
import studio.crud.feature.auth.exception.*
import studio.crud.feature.auth.model.TokenPayload
import studio.crud.feature.auth.model.UserInfo
import studio.crud.feature.auth.token.TokenHandler
import studio.crud.feature.core.util.extractAndValidatePayload
import studio.crud.feature.core.exception.ServerException
import java.util.*
@Component
class AuthenticationServiceImpl(
private val tokenHandler: TokenHandler,
private val authenticationPostProcessor: AuthenticationPostProcessor,
private val crudHandler: CrudHandler,
private val authProperties: AuthProperties
) : AuthenticationService {
private val setups = mutableMapOf<UserPair, CustomParamsDTO>()
@ComponentMap
private lateinit var authenticationMethodTypeHandlers: Map<AuthenticationMethodType, AuthenticationMethodHandler<Any>>
override fun initializeRegistration(methodType: AuthenticationMethodType, body: String): CustomParamsDTO {
log.trace { "Received initializeRegistration with payload: {$body}" }
val methodHandler = getMethodHandler(methodType)
val payload = extractAndValidatePayload(body, methodHandler.payloadType, InitializeRegistrationValidation::class.java)
methodHandler.getEntityMethod(payload)?.let {
if(methodHandler.methodType.canCrossActions) {
log.trace { "[ Method ID: ${it.id}, Method Type: ${it.methodType}, Entity: ${it.entity.id} ] exists and allowLoginOnRegistration=true, switching to initializeLogin" }
return initializeLogin(methodType, body)
}
log.trace { "[ Method ID: ${it.id}, Method Type: ${it.methodType}, Entity: ${it.entity.id} ] exists and canCrossActions=false, terminating" }
throw EntityAlreadyExistsException()
}
val username = methodHandler.getUsernameFromPayload(payload)
val params = methodHandler.initializeRegistration(payload)
setups[UserPair(username, methodHandler.methodType)] = params
log.trace { "Initialized registration for username: $username, params: $params, method: ${methodHandler.methodType}" }
return params
}
override fun doRegister(methodType: AuthenticationMethodType, body: String): AuthenticationResultDTO {
log.trace { "Received doRegister with payload: {$body}" }
val methodHandler = getMethodHandler(methodType)
val payload = extractAndValidatePayload(body, methodHandler.payloadType, RegistrationValidation::class.java)
try {
val username = methodHandler.getUsernameFromPayload(payload)
methodHandler.getEntityMethod(payload)?.let {
if(methodHandler.methodType.canCrossActions) {
log.trace { "[ Method ID: ${it.id}, Method Type: ${it.methodType}, Entity: ${it.entity.id} ] exists and canCrossActions=true, switching to doLogin" }
return doLogin(methodType, body)
}
log.trace { "[ Method ID: ${it.id}, Method Type: ${it.methodType}, Entity: ${it.entity.id} ] exists and canCrossActions=false, terminating" }
throw EntityNotFoundException()
}
var params = setups[UserPair(username, methodHandler.methodType)]
if(params == null && methodHandler.methodType.registrationInitializationRequired) {
throw RegistrationNotInitializedException()
} else {
params = CustomParamsDTO()
}
val entity = Entity()
val method = methodHandler.doRegister(payload, params, entity)
method.primary = true
entity.authenticationMethods.add(method)
when(method.methodType.usernameType) {
UsernameType.Email -> {
val email = methodHandler.getUsername(method)
val existingEntity = crudHandler.showBy(where {
"email" Equal email
}, Entity::class.java)
.fromCache()
.execute()
if(existingEntity != null) {
throw EmailInUseException()
}
entity.email = email
}
UsernameType.Telephone -> {
val telephone = methodHandler.getUsername(method)
val existingEntity = crudHandler.showBy(where {
"telephone" Equal telephone
}, Entity::class.java)
.fromCache()
.execute()
if(existingEntity != null) {
throw TelephoneInUseException()
}
entity.telephone = methodHandler.getUsername(method)
}
else -> {}
}
crudHandler.create(entity).execute()
log.trace { "Performed registration for [ Method ID: ${method.id}, Method Type: ${method.methodType}, Entity: ${method.entity.id} ], params: [ $params ]" }
val parsedToken = tokenHandler.generateToken(
TokenPayload(
entity.uuid,
false,
false,
Date(System.currentTimeMillis() + authProperties.tokenLifetimeHours * 60L * 60L * 1000L)
)
)
authenticationPostProcessor.onRegistrationSuccess(body, method, parsedToken)
return AuthenticationResultDTO(entity.uuid, parsedToken.token)
} catch(e: ServerException) {
authenticationPostProcessor.onRegistrationFailure(body, e.message.toString())
throw e
} catch(e: Exception) {
authenticationPostProcessor.onRegistrationFailure(body, e.message ?: UNHANDLED_EXCEPTION)
log.error(e) { "Registration failed wjth unknown exception" }
throw e
}
}
override fun initializeLogin(methodType: AuthenticationMethodType, body: String): CustomParamsDTO {
log.trace { "Received initializeLogin with payload: {$body}" }
val methodHandler = getMethodHandler(methodType)
val payload = extractAndValidatePayload(body, methodHandler.payloadType, InitializeLoginValidation::class.java)
val entityMethod = methodHandler.getEntityMethod(payload)
if(entityMethod == null) {
if(methodHandler.methodType.canCrossActions) {
log.trace { "Username [ ${methodHandler.getUsernameFromPayload(payload)} ] for method [ ${methodHandler.methodType} ] does not exist and canCrossActions=true, switching to initializeRegistration" }
return initializeRegistration(methodType, body)
}
log.trace { "Username [ ${methodHandler.getUsernameFromPayload(payload)} ] for method [ ${methodHandler.methodType} ] does not exist and canCrossActions=false, terminating" }
throw EntityNotFoundException()
}
return methodHandler.initializeLogin(body, entityMethod)
}
override fun doLogin(methodType: AuthenticationMethodType, body: String): AuthenticationResultDTO {
log.trace { "Received initializeLogin with payload: {$body}" }
val methodHandler = getMethodHandler(methodType)
val payload = extractAndValidatePayload(body, methodHandler.payloadType, LoginValidation::class.java)
val entityMethod = methodHandler.getEntityMethod(payload)
if(entityMethod == null) {
if(methodHandler.methodType.canCrossActions) {
log.trace { "Username [ ${methodHandler.getUsernameFromPayload(payload)} ] for method [ ${methodHandler.methodType} ] does not exist and allowRegistrationOnLogin=true, switching to initializeRegistration" }
return doRegister(methodType, body)
}
log.trace { "Username [ ${methodHandler.getUsernameFromPayload(payload)} ] for method [ ${methodHandler.methodType} ] does not exist and allowRegistrationOnLogin=false or canCrossActions=false, terminating" }
throw EntityNotFoundException()
}
try {
log.trace { "Performing login request for [ Method ID: ${entityMethod.id}, Method Type: ${entityMethod.methodType}, Entity: ${entityMethod.entity.id} ], method: [ ${methodHandler.methodType} ]" }
methodHandler.doLogin(payload, entityMethod)
log.trace { "Performed login request for [ Method ID: ${entityMethod.id}, Method Type: ${entityMethod.methodType}, Entity: ${entityMethod.entity.id} ], method: [ ${methodHandler.methodType} ]" }
val parsedToken = tokenHandler.generateToken(
TokenPayload(
entityMethod.entity.uuid,
false,
false,
Date(System.currentTimeMillis() + authProperties.tokenLifetimeHours * 60L * 60L * 1000L)
)
)
authenticationPostProcessor.onLoginSuccess(body, entityMethod, parsedToken)
return AuthenticationResultDTO(entityMethod.entity.uuid, parsedToken.token)
} catch(e: ServerException) {
authenticationPostProcessor.onLoginFailure(body, entityMethod, e.message.toString())
throw e
} catch(e: Exception) {
authenticationPostProcessor.onLoginFailure(body, entityMethod, UNHANDLED_EXCEPTION)
log.error(e) { "Login failed with unknown exception" }
throw e
}
}
override fun initializeForgotPassword(methodType: AuthenticationMethodType, body: String) {
log.trace { "Received initializeForgotPassword with payload: {$body}" }
if(!methodType.passwordBased) {
log.error { "initializeForgotPassword failed for method [ $methodType ] as it is not password based" }
throw ForgotPasswordNotSupportedException(methodType)
}
val methodHandler = getMethodHandler(methodType)
val payload = extractAndValidatePayload(body, methodHandler.payloadType, InitializeForgotPasswordValidation::class.java)
val method = methodHandler.getEntityMethod(payload) ?: throw EntityNotFoundException()
val token = crudHandler.create(ForgotPasswordToken(method, method.entity.id)).execute()
authenticationPostProcessor.onForgotPasswordInitialized(token.token, method)
log.trace { "Performed initializeForgotPassword for [ Method ID: ${method.id}, Method Type: ${method.methodType}, Entity: ${method.entity.id} ]: {$body}" }
}
override fun redeemForgotPasswordToken(tokenString: String, newPassword: String) {
log.trace { "Received redeemForgotPasswordToken with token: [ {$tokenString} ]" }
val token = crudHandler.showBy(where {
"token" Equal tokenString
}, ForgotPasswordToken::class.java)
.execute()
?: throw InvalidForgotPasswordTokenException()
val method = token.method
val methodHandler = getMethodHandler(method.methodType)
if(!methodHandler.methodType.passwordBased) {
log.error { "redeemForgotPasswordToken failed for method [ ${methodHandler.methodType} ] as it is not password based" }
throw ForgotPasswordNotSupportedException(methodHandler.methodType)
}
methodHandler.changePassword(newPassword, method)
crudHandler.update(method).execute()
authenticationPostProcessor.onForgotPasswordSuccess(token, method)
crudHandler.delete(token.id, ForgotPasswordToken::class.java).execute()
log.trace { "Performed redeemForgotPasswordToken for [ Method ID: ${method.id}, Method Type: ${method.methodType}, Entity: ${method.entity.id} ]" }
}
override fun changePassword(methodType: AuthenticationMethodType, body: String, newPassword: String, userInfo: UserInfo): String {
val methodHandler = getMethodHandler(methodType)
val payload = extractAndValidatePayload(body, methodHandler.payloadType, ChangePasswordValidation::class.java)
val entityMethod = methodHandler.getEntityMethod(payload) ?: throw EntityNotFoundException()
if(!methodHandler.checkPassword(payload, entityMethod)) {
throw OldPasswordMismatchException()
}
methodHandler.changePassword(newPassword, entityMethod)
val parsedToken = userInfo.parsedToken
if(parsedToken.payload.passwordChangeRequired) {
val newPayload = parsedToken.payload.copy(passwordChangeRequired = false)
return tokenHandler.generateToken(newPayload).token
}
return userInfo.parsedToken.token
}
private fun getMethodHandler(methodType: AuthenticationMethodType): AuthenticationMethodHandler<Any> {
val methodHandler = authenticationMethodTypeHandlers[methodType] ?: throw AuthenticationMethodNotSupportedException(methodType)
return methodHandler
}
override fun getAvailableMethods(): List<AuthenticationMethodDTO> {
return authenticationMethodTypeHandlers.map { AuthenticationMethodDTO(it.key, it.key == authProperties.defaultAuthenticationMethodType) }
}
companion object {
private val UNHANDLED_EXCEPTION = "Unhandled exception"
private val log = KotlinLogging.logger { }
private data class UserPair(val username: String, val methodType: AuthenticationMethodType)
data class AuthenticationMethodDTO(val methodType: AuthenticationMethodType, val default: Boolean)
}
}
| 6
|
Kotlin
|
0
| 0
|
6cb1d5f7b3fc7117c9fbaaf6708ac93ae631e674
| 14,588
|
feature-depot
|
MIT License
|
src/main/kotlin/dev/schlaubi/musicbot/module/song_quiz/game/SongQuizPlayer.kt
|
Korsti
| 414,297,572
| true
|
{"Kotlin": 265776, "Dockerfile": 199, "Shell": 97}
|
package dev.schlaubi.musicbot.module.song_quiz.game
import dev.kord.core.behavior.UserBehavior
import dev.schlaubi.musicbot.game.Player
class SongQuizPlayer(override val user: UserBehavior) : Player
| 0
| null |
0
| 0
|
488ac29bf58aac7aa30a41de296e5a908524b492
| 201
|
mikmusic
|
MIT License
|
app/src/main/java/com/babylon/wallet/android/data/gateway/generated/models/ProgrammaticScryptoSborValueMapAllOf.kt
|
radixdlt
| 513,047,280
| false
|
{"Kotlin": 4905038, "HTML": 215350, "Ruby": 2757, "Shell": 1963}
|
/**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package com.babylon.wallet.android.data.gateway.generated.models
import com.babylon.wallet.android.data.gateway.generated.models.ProgrammaticScryptoSborValueKind
import com.babylon.wallet.android.data.gateway.generated.models.ProgrammaticScryptoSborValueMapEntry
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
import kotlinx.serialization.Contextual
/**
*
*
* @param keyKind
* @param valueKind
* @param propertyEntries
* @param keyTypeName
* @param valueTypeName
*/
@Serializable
data class ProgrammaticScryptoSborValueMapAllOf (
@Contextual @SerialName(value = "key_kind")
val keyKind: ProgrammaticScryptoSborValueKind,
@Contextual @SerialName(value = "value_kind")
val valueKind: ProgrammaticScryptoSborValueKind,
@SerialName(value = "entries")
val propertyEntries: kotlin.collections.List<ProgrammaticScryptoSborValueMapEntry>,
@SerialName(value = "key_type_name")
val keyTypeName: kotlin.String? = null,
@SerialName(value = "value_type_name")
val valueTypeName: kotlin.String? = null
)
| 6
|
Kotlin
|
6
| 9
|
a973af97556c2c3c5c800dac937d0007a13a3a1c
| 1,362
|
babylon-wallet-android
|
Apache License 2.0
|
dolphin/src/main/kotlin/net/bytemc/bytecloud/dolphin/groups/DolphinGroupProviderImpl.kt
|
bytemcnetzwerk
| 684,494,766
| false
|
{"Kotlin": 147393}
|
package net.bytemc.bytecloud.dolphin.groups
import net.bytemc.bytecloud.api.group.CloudGroup
import net.bytemc.bytecloud.api.group.CloudGroupProvider
import net.bytemc.bytecloud.api.group.packets.*
import net.bytemc.bytecloud.api.network.BufferedFuture
import net.bytemc.bytecloud.api.network.PacketBuffer
import net.bytemc.bytecloud.api.network.packet.Packet
import net.bytemc.bytecloud.api.services.CloudServiceType
import net.bytemc.bytecloud.api.services.launch.ServiceLaunchConfiguration
import net.bytemc.bytecloud.dolphin.Dolphin
import java.util.function.BiConsumer
class DolphinGroupProviderImpl : CloudGroupProvider {
override fun create(group: CloudGroup) {
Dolphin.getInstance().clusterConnect.sendPacket(RequestGroupCreationPacket(group))
}
override fun getGroup(name: String): CloudGroup? {
return this.getGroupAsync(name).getSync()
}
override fun getGroupAsync(name: String): BufferedFuture<CloudGroup?> {
return this.asyncRequests(RequestSingleGroupPacket(name), ResponseSingleGroupPacket::class.java) { t, u ->
u.trySuccess(t.group)
}
}
override fun getGroups(): List<CloudGroup> {
return this.getGroupsAsync().getSync()
}
override fun getGroupsAsync(): BufferedFuture<List<CloudGroup>> {
return this.asyncRequests(RequestGroupCollectionPacket(), ResponseGroupCollectionPacket::class.java) { t, u ->
u.trySuccess(t.groups)
}
}
override fun exists(name: String): Boolean {
return this.existsAsync(name).getSync()
}
override fun existsAsync(name: String): BufferedFuture<Boolean> {
return this.asyncRequests(RequestGroupExistsPacket(name), ResponseGroupExistsPacket::class.java) { t, u ->
u.trySuccess(t.state)
}
}
override fun startNewService(group: CloudGroup) {
TODO("Not yet implemented")
}
override fun startNewService(name: String) {
TODO("Not yet implemented")
}
override fun startNewService(configuration: ServiceLaunchConfiguration) {
TODO("Not yet implemented")
}
override fun createInstance(buffer: PacketBuffer): CloudGroup {
val name = buffer.readString()
val memory = buffer.readInt()
val minOnlineCount = buffer.readInt()
val maxOnlineCount = buffer.readInt()
val startPriority = buffer.readInt()
val startPort = buffer.readInt()
val percentageToStartNewService = buffer.readInt()
val static = buffer.readBoolean()
val maintenance = buffer.readBoolean()
val autoUpdating = buffer.readBoolean()
val version = buffer.readEnum(CloudServiceType::class.java)!!
val node = buffer.readString()
val fallback = buffer.readBoolean()
return DolphinGroupImpl(
name,
version,
memory,
minOnlineCount,
maxOnlineCount,
startPriority,
startPort,
percentageToStartNewService,
static,
maintenance,
autoUpdating,
node,
fallback
)
}
private fun <T, R : Packet> asyncRequests(request: Packet, response: Class<R>, result: BiConsumer<R, BufferedFuture<T>>): BufferedFuture<T> {
val future = BufferedFuture<T>()
val client = Dolphin.getInstance().clusterConnect
client.sendQueryPacket(request, response) {
result.accept(it, future)
}
return future
}
}
| 2
|
Kotlin
|
3
| 5
|
71a52f1a41d3dcd3c656090549e25e13b846539b
| 3,535
|
bytecloud
|
Apache License 2.0
|
src/main/kotlin/com/school/system/grading/repository/impl/UserRepositoryImpl.kt
|
saad129
| 374,616,148
| false
| null |
package com.school.system.grading.repository.impl
import com.school.system.grading.datasource.UserDataSource
import com.school.system.grading.entity.Response
import com.school.system.grading.entity.user.request.UserLogin
import com.school.system.grading.entity.user.request.UserUpdate
import com.school.system.grading.entity.user.request.Users
import com.school.system.grading.entity.user.response.UserResponse
import com.school.system.grading.repository.UserRepository
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Repository
@Repository
class UserRepositoryImpl(
private val userDataSource: UserDataSource
): UserRepository {
override suspend fun fetchAllUsers(): ResponseEntity<Response<List<UserResponse>>> = userDataSource.findAll()
override suspend fun findUserById(id: Int): ResponseEntity<Response<UserResponse>> {
return userDataSource.findById(id)
}
override suspend fun insertUser(users: Users): ResponseEntity<Response<UserResponse>> = userDataSource.insert(users)
override suspend fun loginUser(userLogin: UserLogin): ResponseEntity<Response<UserResponse>> = userDataSource.login(userLogin)
override suspend fun updateUser(userUpdate: UserUpdate): ResponseEntity<Response<UserResponse>> {
return userDataSource.update(userUpdate)
}
}
| 0
|
Kotlin
|
0
| 0
|
4800be374e1a7e030f02ce5bbc0db7802a715610
| 1,345
|
school-grading-prototype
|
Apache License 2.0
|
service/catalog-service/src/main/kotlin/com/msa/catalogservice/global/config/KafkaConsumerConfig.kt
|
earlgrey02
| 634,131,701
| false
| null |
package com.msa.catalogservice.global.config
import org.apache.kafka.clients.consumer.ConsumerConfig
import org.apache.kafka.common.serialization.StringDeserializer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.kafka.annotation.EnableKafka
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory
import org.springframework.kafka.core.ConsumerFactory
import org.springframework.kafka.core.DefaultKafkaConsumerFactory
@EnableKafka
@Configuration
class KafkaConsumerConfig {
@Bean
fun consumerFactory(): ConsumerFactory<String, String> =
HashMap<String, Any>().apply {
put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092")
put(ConsumerConfig.GROUP_ID_CONFIG, "consumerGroupId")
put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer::class)
put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer::class)
}.let {
DefaultKafkaConsumerFactory(it)
}
@Bean
fun kafkaListenerContainerFactory(): ConcurrentKafkaListenerContainerFactory<String, String> =
ConcurrentKafkaListenerContainerFactory<String, String>().apply {
setConsumerFactory(consumerFactory())
}
}
| 0
|
Kotlin
|
0
| 0
|
e8c63816fecc31e0ccc372e89e5b082b7296a3cb
| 1,338
|
Spring-MSA
|
MIT License
|
twitlin/src/common/test/kotlin/com/sorrowblue/twitlin/v2/tweets/counts/TweetsCountsApiTest.kt
|
SorrowBlue
| 278,215,181
| false
| null |
package com.sorrowblue.twitlin.v2.tweets.counts
import com.sorrowblue.twitlin.Twitlin
import com.sorrowblue.twitlin.v2.testResult
import kotlin.test.Test
import kotlin.time.Duration.Companion.minutes
import kotlin.time.ExperimentalTime
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import kotlinx.datetime.Clock
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import test.AbstractTest
@ExperimentalCoroutinesApi
class TweetsCountsApiTest : AbstractTest {
private val tweetsCountsApi = Twitlin.getApi<TweetsCountsApi>(oauth1aClient)
@OptIn(ExperimentalTime::class)
@Test
fun testRecent() = runTest {
tweetsCountsApi.recent(
"lakers",
granularity = "day",
endTime = Clock.System.now().minus(1.minutes).toLocalDateTime(TimeZone.UTC)
).testResult()
}
}
| 1
|
Kotlin
|
0
| 1
|
0604daf5524688f112960eb039d90ff44765445e
| 895
|
Twitlin
|
MIT License
|
sharedCompose/src/commonMain/kotlin/com/movisens/bluetooth/kmm/view/DetailScreen.kt
|
rzetzsche
| 720,164,007
| false
|
{"Kotlin": 48456, "Swift": 10972, "Shell": 228}
|
package com.movisens.bluetooth.kmm.view
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.currentOrThrow
import com.movisens.bluetooth.kmm.repository.bluetooth.BluetoothDevice
import com.movisens.bluetooth.kmm.viewmodel.DetailViewModel
import com.movisens.bluetooth.kmm.viewmodel.DetailViewModel.State.Error
import com.movisens.bluetooth.kmm.viewmodel.DetailViewModel.State.Loaded.AirTag
import com.movisens.bluetooth.kmm.viewmodel.DetailViewModel.State.Loading
import org.koin.core.component.KoinComponent
import org.koin.core.parameter.parametersOf
class DetailScreen(private val bluetoothDevice: BluetoothDevice) : Screen, KoinComponent {
private val detailViewModel =
getKoin().get<DetailViewModel>(parameters = { parametersOf(bluetoothDevice) })
@Composable
override fun Content() {
val detailState by detailViewModel.state.collectAsState()
val navigator = LocalNavigator.currentOrThrow
Scaffold(topBar = {
TopAppBar(title = { Text("App") }, navigationIcon = {
IconButton(onClick = { navigator.pop() }) {
Icon(Icons.Default.ArrowBack, null)
}
})
}) {
Column(
modifier = Modifier.padding(16.dp).fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(bluetoothDevice.name ?: "Air Tag")
Text(bluetoothDevice.identifier)
Text(bluetoothDevice.rssi.toString())
Box(modifier = Modifier.height(100.dp))
detailState.let { detailState ->
when (detailState) {
is DetailViewModel.State.Loaded.MovisensSensorLoaded -> Column {
val movisensSensorValues = detailState.movisensSensorValues
Text("${movisensSensorValues.manufacturer} ${movisensSensorValues.modelNumber}")
Text("Firmware Version: ${movisensSensorValues.firmware}")
Text("Serial Number: ${movisensSensorValues.serialNumber}")
Text("Battery Level: ${movisensSensorValues.batteryLevel} %")
}
is Error -> Text(detailState.error)
is AirTag -> {
Text("Battery Level: ${detailState.batteryLevel}")
Box(modifier = Modifier.height(100.dp))
if (detailState is AirTag.Loaded)
Button(onClick = { detailViewModel.playAirtagSound() }) {
Text("Play Sound")
}
else {
CircularProgressIndicator()
}
}
is Loading -> CircularProgressIndicator()
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
0fc70f2f1026aedc7c854af9affe0274e5fe0842
| 3,996
|
BluetoothKotlinMultiplatform
|
Apache License 2.0
|
app/src/main/java/com/muhammadwahyudin/identitasku/ui/home/HomeViewModelImpl.kt
|
hyuwah
| 170,234,024
| false
| null |
package com.muhammadwahyudin.identitasku.ui.home
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.map
import com.muhammadwahyudin.identitasku.data.Constants
import com.muhammadwahyudin.identitasku.data.model.Data
import com.muhammadwahyudin.identitasku.data.model.DataType
import com.muhammadwahyudin.identitasku.data.model.DataWithDataType
import com.muhammadwahyudin.identitasku.data.repository.IAppRepository
import com.muhammadwahyudin.identitasku.ui._base.BaseViewModel
import com.muhammadwahyudin.identitasku.ui.home.contract.HomeUiState
import com.muhammadwahyudin.identitasku.ui.home.contract.HomeViewModel
import com.muhammadwahyudin.identitasku.ui.home.contract.SortFilterViewModel
import com.muhammadwahyudin.identitasku.ui.home.contract.SortFilterViewModel.Companion.DEFAULT_SORT
import com.muhammadwahyudin.identitasku.ui.home.contract.SortFilterViewModel.Companion.SORT
import com.muhammadwahyudin.identitasku.utils.ioLaunch
class HomeViewModelImpl(private val appRepository: IAppRepository) : BaseViewModel(),
HomeViewModel,
SortFilterViewModel {
private val dataWithType = MutableLiveData<List<DataWithDataType>>(listOf())
private val dataType = MutableLiveData<List<DataType>>(listOf())
private val existingUniqueDataType = MutableLiveData<List<DataType>>(listOf())
private val _uiState = dataWithType.map { it.mapToUiState(0) } as MutableLiveData
val uiState get() = _uiState as LiveData<HomeUiState>
override var currentSort = DEFAULT_SORT
private set
override var currentFilter: List<Int> = listOf()
private set
override fun addData(data: Data, typeName: String) {
ioLaunch(spv) {
val newDataId = appRepository.insert(data).toInt()
val message = "$typeName successfully added"
postSnackbar(message)
val list = appRepository.getAllDataWithType()
val scrollPos = list.indexOfFirst { it.id == newDataId }
_uiState.postValue(list.mapToUiState(if (scrollPos == -1) 0 else scrollPos))
}
}
override fun deleteDatas(datasWithDataType: List<DataWithDataType>) {
ioLaunch(spv) {
appRepository.deleteDatasById(datasWithDataType.map { it.id })
loadAllData()
}
}
override fun updateData(data: Data, typeName: String) {
ioLaunch(spv) {
appRepository.update(data)
val message = "$typeName successfully updated"
postSnackbar(message)
val list = appRepository.getAllDataWithType()
val scrollPos = list.indexOfFirst { it.id == data.id }
_uiState.postValue(list.mapToUiState(if (scrollPos == -1) 0 else scrollPos))
}
}
override fun getAllDataType(): LiveData<List<DataType>> {
ioLaunch(spv) {
dataType.postValue(
appRepository.getAllDataType()
)
}
return dataType
}
override fun loadAllData() {
ioLaunch(spv) {
dataWithType.postValue(appRepository.getAllDataWithType())
}
}
override fun refreshData() {
ioLaunch(spv) {
val list = appRepository.getAllDataWithType()
_uiState.postValue(list.mapToUiState(-1))
}
}
override fun getAllExistingUniqueType(): LiveData<List<DataType>> {
ioLaunch(spv) {
existingUniqueDataType.postValue(
appRepository.getAllExistingUniqueType()
)
}
return existingUniqueDataType
}
override fun List<DataWithDataType>.sort(sort: SORT): List<DataWithDataType> {
return when (sort) {
SORT.NEWEST -> this
SORT.OLDEST -> this.asReversed()
SORT.CATEGORY -> this.sortedBy { it.typeId }
}
}
override fun List<DataWithDataType>.filter(filters: List<Int>): List<DataWithDataType> {
return if (filters.isNotEmpty()) {
this.filter { filters.contains(it.typeId) }
} else {
this
}
}
override fun sortAndFilter(sort: SORT, filter: List<Int>) {
currentSort = sort
currentFilter = filter
loadAllData()
}
private fun List<DataWithDataType>.mapToUiState(scrollPos: Int): HomeUiState {
return if (this.isEmpty()) {
HomeUiState.EmptyNoData
} else {
val filters = currentFilter.map { typeId ->
Constants.TYPE.values().find { it.value == typeId } ?: Constants.TYPE.DEFAULT
}
val uiList = this.sort(currentSort).filter(currentFilter)
if (uiList.isEmpty())
HomeUiState.EmptyFiltered(filters)
else
HomeUiState.HasData(uiList, currentSort, filters, scrollPos)
}
}
// Debug
fun debugPopulateData() {
ioLaunch(spv) {
appRepository.deleteAllData()
appRepository.resetDataType()
appRepository.prepopulateData()
loadAllData()
}
}
}
| 1
|
Kotlin
|
1
| 1
|
a8cc2a0b0d5d9dd90fc5f229d84ed42c499b1bf8
| 5,092
|
IdentitasKu
|
MIT License
|
core/src/main/kotlin/org/eduardoleolim/organizadorpec660/instrument/application/update/InstrumentUpdater.kt
|
eduardoleolim
| 673,214,659
| false
|
{"Kotlin": 827389, "Shell": 2116}
|
package org.eduardoleolim.organizadorpec660.instrument.application.update
import org.eduardoleolim.organizadorpec660.instrument.domain.*
import org.eduardoleolim.organizadorpec660.municipality.domain.MunicipalityCriteria
import org.eduardoleolim.organizadorpec660.municipality.domain.MunicipalityRepository
import org.eduardoleolim.organizadorpec660.shared.domain.Either
import org.eduardoleolim.organizadorpec660.shared.domain.Left
import org.eduardoleolim.organizadorpec660.shared.domain.Right
import org.eduardoleolim.organizadorpec660.statisticType.domain.StatisticTypeCriteria
import org.eduardoleolim.organizadorpec660.statisticType.domain.StatisticTypeRepository
class InstrumentUpdater(
private val instrumentRepository: InstrumentRepository,
private val statisticTypeRepository: StatisticTypeRepository,
private val municipalityRepository: MunicipalityRepository
) {
fun update(
instrumentId: String,
statisticYear: Int,
statisticMonth: Int,
agencyId: String,
statisticTypeId: String,
municipalityId: String,
file: ByteArray
): Either<InstrumentError, Unit> {
val instrument = searchInstrument(instrumentId) ?: return Left(InstrumentNotFoundError(instrumentId))
val instrumentFileId = instrument.instrumentFileId().toString()
val instrumentFile =
searchInstrumentFile(instrumentFileId) ?: return Left(InstrumentFileNotFoundError(instrumentFileId))
val existsAnotherInstrument = existsAnotherInstrumentSameData(
instrumentId,
statisticYear,
statisticMonth,
agencyId,
statisticTypeId,
municipalityId
)
if (existsAnotherInstrument)
return Left(
InstrumentAlreadyExistsError(
statisticYear,
statisticMonth,
agencyId,
statisticTypeId,
municipalityId
)
)
if (existsStatisticType(statisticTypeId).not())
return Left(StatisticTypeNotFoundError(statisticTypeId))
if (existsMunicipality(municipalityId).not())
return Left(MunicipalityNotFoundError(municipalityId))
instrument.apply {
changeStatisticYear(statisticYear)
changeStatisticMonth(statisticMonth)
changeStatisticTypeId(statisticTypeId)
changeMunicipalityId(municipalityId)
}
instrumentFile.apply {
changeContent(file)
}
instrumentRepository.save(instrument, instrumentFile)
return Right(Unit)
}
private fun searchInstrument(instrumentId: String) =
InstrumentCriteria.idCriteria(instrumentId).let {
instrumentRepository.matching(it).firstOrNull()
}
private fun searchInstrumentFile(instrumentFileId: String) =
instrumentRepository.searchInstrumentFile(instrumentFileId)
private fun existsAnotherInstrumentSameData(
instrumentId: String,
statisticYear: Int,
statisticMonth: Int,
agencyId: String,
statisticTypeId: String,
municipalityId: String
) = InstrumentCriteria.anotherInstrumentCriteria(
instrumentId,
statisticYear,
statisticMonth,
agencyId,
statisticTypeId,
municipalityId
).let {
instrumentRepository.count(it) > 0
}
private fun existsStatisticType(statisticTypeId: String) =
StatisticTypeCriteria.idCriteria(statisticTypeId).let {
statisticTypeRepository.count(it) > 0
}
private fun existsMunicipality(municipalityId: String) =
MunicipalityCriteria.idCriteria(municipalityId).let {
municipalityRepository.count(it) > 0
}
}
| 0
|
Kotlin
|
0
| 0
|
8b03fcbe17e4274b70a8fba40975e59f6868c06d
| 3,849
|
organizador-pec-6-60
|
Creative Commons Attribution 4.0 International
|
ZelisPolarResearchApp/PolarSdkEcgHrDemoMarchLibraryUpdates/app/src/main/java/com/polar/polarsdkecghrdemo/ECGActivity.kt
|
hanna8008
| 725,296,132
| false
|
{"Kotlin": 52386, "Java": 1131}
|
package com.polar.polarsdkecghrdemo
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.androidplot.xy.BoundaryMode
import com.androidplot.xy.StepMode
import com.androidplot.xy.XYPlot
import com.polar.sdk.api.PolarBleApi
import com.polar.sdk.api.PolarBleApiCallback
import com.polar.sdk.api.PolarBleApiDefaultImpl.defaultImplementation
import com.polar.sdk.api.errors.PolarInvalidArgument
import com.polar.sdk.api.model.PolarDeviceInfo
import com.polar.sdk.api.model.PolarEcgData
import com.polar.sdk.api.model.PolarHrData
import com.polar.sdk.api.model.PolarSensorSetting
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.Disposable
import java.util.*
class ECGActivity : AppCompatActivity(), PlotterListener {
companion object {
private const val TAG = "ECGActivity"
}
private lateinit var api: PolarBleApi
private lateinit var textViewHR: TextView
private lateinit var textViewRR: TextView
private lateinit var textViewDeviceId: TextView
private lateinit var textViewBattery: TextView
private lateinit var textViewFwVersion: TextView
private lateinit var plot: XYPlot
private lateinit var ecgPlotter: EcgPlotter
private var ecgDisposable: Disposable? = null
private var hrDisposable: Disposable? = null
private lateinit var deviceId: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ecg)
deviceId = intent.getStringExtra("id") ?: throw Exception("ECGActivity couldn't be created, no deviceId given")
textViewHR = findViewById(R.id.hr)
textViewRR = findViewById(R.id.rr)
textViewDeviceId = findViewById(R.id.deviceId)
textViewBattery = findViewById(R.id.battery_level)
textViewFwVersion = findViewById(R.id.fw_version)
plot = findViewById(R.id.plot)
api = defaultImplementation(
applicationContext,
setOf(
PolarBleApi.PolarBleSdkFeature.FEATURE_POLAR_ONLINE_STREAMING,
PolarBleApi.PolarBleSdkFeature.FEATURE_BATTERY_INFO,
PolarBleApi.PolarBleSdkFeature.FEATURE_DEVICE_INFO
)
)
api.setApiCallback(object : PolarBleApiCallback() {
override fun blePowerStateChanged(powered: Boolean) {
Log.d(TAG, "BluetoothStateChanged $powered")
}
override fun deviceConnected(polarDeviceInfo: PolarDeviceInfo) {
Log.d(TAG, "Device connected " + polarDeviceInfo.deviceId)
Toast.makeText(applicationContext, R.string.connected, Toast.LENGTH_SHORT).show()
}
override fun deviceConnecting(polarDeviceInfo: PolarDeviceInfo) {
Log.d(TAG, "Device connecting ${polarDeviceInfo.deviceId}")
}
override fun deviceDisconnected(polarDeviceInfo: PolarDeviceInfo) {
Log.d(TAG, "Device disconnected ${polarDeviceInfo.deviceId}")
}
override fun bleSdkFeatureReady(identifier: String, feature: PolarBleApi.PolarBleSdkFeature) {
Log.d(TAG, "feature ready $feature")
when (feature) {
PolarBleApi.PolarBleSdkFeature.FEATURE_POLAR_ONLINE_STREAMING -> {
streamECG()
streamHR()
}
else -> {}
}
}
override fun disInformationReceived(identifier: String, uuid: UUID, value: String) {
if (uuid == UUID.fromString("00002a28-0000-1000-8000-00805f9b34fb")) {
val msg = "Firmware: " + value.trim { it <= ' ' }
Log.d(TAG, "Firmware: " + identifier + " " + value.trim { it <= ' ' })
textViewFwVersion.append(msg.trimIndent())
}
}
override fun batteryLevelReceived(identifier: String, level: Int) {
Log.d(TAG, "Battery level $identifier $level%")
val batteryLevelText = "Battery level: $level%"
textViewBattery.append(batteryLevelText)
}
override fun hrNotificationReceived(identifier: String, data: PolarHrData.PolarHrSample) {
// deprecated
}
override fun polarFtpFeatureReady(identifier: String) {
// deprecated
}
override fun streamingFeaturesReady(identifier: String, features: Set<PolarBleApi.PolarDeviceDataType>) {
// deprecated
}
override fun hrFeatureReady(identifier: String) {
// deprecated
}
})
try {
api.connectToDevice(deviceId)
} catch (a: PolarInvalidArgument) {
a.printStackTrace()
}
val deviceIdText = "ID: $deviceId"
textViewDeviceId.text = deviceIdText
ecgPlotter = EcgPlotter("ECG", 130)
ecgPlotter.setListener(this)
plot.addSeries(ecgPlotter.getSeries(), ecgPlotter.formatter)
plot.setRangeBoundaries(-1.5, 1.5, BoundaryMode.FIXED)
plot.setRangeStep(StepMode.INCREMENT_BY_FIT, 0.25)
plot.setDomainStep(StepMode.INCREMENT_BY_VAL, 130.0)
plot.setDomainBoundaries(0, 650, BoundaryMode.FIXED)
plot.linesPerRangeLabel = 2
}
public override fun onDestroy() {
super.onDestroy()
ecgDisposable?.let {
if (!it.isDisposed) it.dispose()
}
api.shutDown()
}
fun streamECG() {
val isDisposed = ecgDisposable?.isDisposed ?: true
if (isDisposed) {
ecgDisposable = api.requestStreamSettings(deviceId, PolarBleApi.PolarDeviceDataType.ECG)
.toFlowable()
.flatMap { sensorSetting: PolarSensorSetting -> api.startEcgStreaming(deviceId, sensorSetting.maxSettings()) }
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ polarEcgData: PolarEcgData ->
Log.d(TAG, "ecg update")
for (data in polarEcgData.samples) {
ecgPlotter.sendSingleSample((data.voltage.toFloat() / 1000.0).toFloat())
}
},
{ error: Throwable ->
Log.e(TAG, "Ecg stream failed $error")
ecgDisposable = null
},
{
Log.d(TAG, "Ecg stream complete")
}
)
} else {
// NOTE stops streaming if it is "running"
ecgDisposable?.dispose()
ecgDisposable = null
}
}
fun streamHR() {
val isDisposed = hrDisposable?.isDisposed ?: true
if (isDisposed) {
hrDisposable = api.startHrStreaming(deviceId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ hrData: PolarHrData ->
for (sample in hrData.samples) {
Log.d(TAG, "HR " + sample.hr)
if (sample.rrsMs.isNotEmpty()) {
val rrText = "(${sample.rrsMs.joinToString(separator = "ms, ")}ms)"
textViewRR.text = rrText
}
textViewHR.text = sample.hr.toString()
}
},
{ error: Throwable ->
Log.e(TAG, "HR stream failed. Reason $error")
hrDisposable = null
},
{ Log.d(TAG, "HR stream complete") }
)
} else {
// NOTE stops streaming if it is "running"
hrDisposable?.dispose()
hrDisposable = null
}
}
override fun update() {
runOnUiThread { plot.redraw() }
}
}
| 2
|
Kotlin
|
0
| 1
|
9555e057ef720cfb79fe5f54b2f499dcf376497b
| 8,205
|
Zelis_Polar_App_Development_Research_High-Point-University-
|
MIT License
|
app/src/main/java/com/hvasoft/weather/common/entities/WeatherBase.kt
|
hva94
| 575,948,749
| false
| null |
package com.hvasoft.weather.common.entities
open class WeatherBase(
dt: Long,
humidity: Int,
temp: Double,
weather: List<Weather>)
| 0
|
Kotlin
|
0
| 1
|
90590847bacc093317e4f6ac8a07a223c2abd01a
| 147
|
Weather
|
Apache License 2.0
|
math/src/commonMain/kotlin/me/y9san9/calkt/math/parse/MathParseOperandFunction.kt
|
y9san9
| 842,898,431
| false
|
{"Kotlin": 79012}
|
package me.y9san9.calkt.math.parse
import me.y9san9.calkt.Expression
import me.y9san9.calkt.parse.ParseContext
public fun interface MathParseOperandFunction {
public operator fun invoke(context: ParseContext): Expression
}
| 1
|
Kotlin
|
1
| 21
|
06d1ecbca749ad4107d08d719916a10aa95aa6df
| 229
|
calkt
|
MIT License
|
role-guardian/src/main/java/org/rfcx/guardian/guardian/audio/capture/AudioScheduleService.kt
|
rfcx
| 7,535,854
| false
|
{"Gradle": 11, "Java Properties": 2, "Shell": 67, "Text": 29, "Ignore List": 10, "Batchfile": 2, "Markdown": 4, "INI": 1, "JSON": 37, "Proguard": 7, "Kotlin": 66, "XML": 159, "Java": 238, "Makefile": 170, "C": 541, "Python": 13, "Perl": 7, "Roff Manpage": 7, "Public Key": 1, "HTML": 165, "JavaScript": 4, "C++": 20, "M4Sugar": 39, "RPM Spec": 2, "CSS": 4, "OpenStep Property List": 2, "Microsoft Visual Studio Solution": 5, "Cue Sheet": 50, "CUE": 1, "Unity3D Asset": 80, "Java Server Pages": 1, "SVG": 2, "Assembly": 3, "M4": 1, "Unix Assembly": 2, "Dockerfile": 1}
|
package org.rfcx.guardian.guardian.audio.capture
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import org.rfcx.guardian.guardian.RfcxGuardian
import org.rfcx.guardian.guardian.companion.CompanionSocketService
import org.rfcx.guardian.utility.misc.TimeUtils.isNowOutsideTimeRange
import org.rfcx.guardian.utility.rfcx.RfcxLog
import org.rfcx.guardian.utility.rfcx.RfcxPrefs
class AudioScheduleService : Service() {
companion object {
const val SERVICE_NAME = "AudioSchedule"
}
private val logTag = RfcxLog.generateLogTag(RfcxGuardian.APP_ROLE, "AudioScheduleService")
private var audioScheduleSvc: AudioScheduleSvc? = null
private var runFlag = false
private var app: RfcxGuardian? = null
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
this.audioScheduleSvc = AudioScheduleSvc()
this.app = application as RfcxGuardian
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
Log.v(logTag, "Starting service: $logTag")
this.runFlag = true
app!!.rfcxSvc.setRunState(SERVICE_NAME, true)
try {
this.audioScheduleSvc?.start()
} catch (e: IllegalThreadStateException) {
RfcxLog.logExc(logTag, e)
}
return START_NOT_STICKY
}
override fun onDestroy() {
super.onDestroy()
runFlag = false
app!!.rfcxSvc.setRunState(SERVICE_NAME, false)
}
private inner class AudioScheduleSvc : Thread("AudioScheduleService-AudioScheduleSvc") {
override fun run() {
val audioScheduleService = this@AudioScheduleService
app = application as RfcxGuardian
while (audioScheduleService.runFlag) {
val offHour = app!!.rfcxPrefs.getPrefAsString(RfcxPrefs.Pref.AUDIO_CAPTURE_SCHEDULE_OFF_HOURS)
if (!isNowOutsideTimeRange(offHour)) {
if (app!!.rfcxSvc.isRunning(AudioCaptureService.SERVICE_NAME)) {
Log.d(logTag, "Stopping AudioCaptureService due to off hours: $offHour")
app!!.rfcxSvc.stopService(AudioCaptureService.SERVICE_NAME)
}
} else {
if (!app!!.rfcxSvc.isRunning(AudioCaptureService.SERVICE_NAME)) {
Log.d(logTag, "Starting AudioCaptureService due to off hours: $offHour")
app!!.rfcxSvc.triggerService(AudioCaptureService.SERVICE_NAME, false)
}
}
// To let AudioCaptureService take its time to start or stop itself
sleep(1500)
}
app!!.rfcxSvc.setRunState(SERVICE_NAME, false)
audioScheduleService.runFlag = false
Log.v(logTag, "Stopping service: $logTag")
}
}
}
| 21
|
C
|
0
| 0
|
627594651e0665b17f2990187c1c5d86ced1c199
| 3,020
|
rfcx-guardian-android
|
Apache License 2.0
|
app/src/main/java/com/justnik/mosplace/data/network/apiservices/ReviewApiService.kt
|
JustNik8
| 460,106,261
| false
|
{"Kotlin": 160815}
|
package com.justnik.mosplace.data.network.apiservices
import com.justnik.mosplace.data.network.datamodels.ReviewDto
import com.justnik.mosplace.data.network.reviewmodels.AddReviewBody
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Query
interface ReviewApiService {
@GET("api/v1/comment_by_article_id")
suspend fun loadPlaceReviews(
@Query(QUERY_PARAM_PLACE_ID) placeId: Long
) : List<ReviewDto>
@POST("api/v1/comment_add")
suspend fun addReview(
@Body addReviewBody: AddReviewBody
)
companion object{
private const val QUERY_PARAM_PLACE_ID = "place_id"
}
}
| 0
|
Kotlin
|
1
| 1
|
8ae2a811c895c6b4d75f8e31139dd4d15c425561
| 673
|
MosPlace
|
Apache License 2.0
|
app/src/main/java/com/layfones/calculator/ui/screens/CalculatorScreen.kt
|
layfones
| 528,757,200
| false
| null |
package com.layfones.calculator.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.layfones.calculator.MainViewModel
import com.layfones.calculator.R
import com.layfones.calculator.ui.components.Backspace
import com.layfones.calculator.ui.components.CalcButton
import com.layfones.calculator.ui.components.ToolButton
import com.layfones.calculator.ui.theme.CalcTheme
import com.layfones.calculator.util.stateList2String
@Preview(showSystemUi = true)
@Composable
fun CalculatorScreen() {
val viewModel: MainViewModel = viewModel()
Box(
Modifier
.fillMaxSize()
.background(color = CalcTheme.colors.backgroundColor)
.windowInsetsPadding(WindowInsets.safeDrawing)
) {
Column(
modifier = Modifier
.fillMaxSize()
.background(CalcTheme.colors.backgroundColor)
) {
Toolbar(viewModel)
Result(
Modifier
.fillMaxWidth()
.weight(1f),
viewModel
)
ButtonGroup(
Modifier
.fillMaxWidth(),
viewModel
)
}
}
}
@Composable
fun Toolbar(viewModel: MainViewModel) {
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 16.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
ToolButton(if (viewModel.dark) R.drawable.ic_light_mode else R.drawable.ic_dark_mode) {
viewModel.changeTheme()
}
ToolButton(R.drawable.ic_delete) {
viewModel.clearRecord()
}
}
}
@Composable
fun Result(modifier: Modifier, viewModel: MainViewModel) {
val listState = rememberLazyListState()
LaunchedEffect(viewModel.flag) {
listState.animateScrollToItem(index = viewModel.records.size)
}
LazyColumn(
state = listState, modifier = modifier, verticalArrangement = Arrangement.Bottom
) {
items(
items = viewModel.records,
key = { record ->
record.id
}
) { record ->
Column(
Modifier
.fillMaxWidth()
.padding(top = 20.dp, start = 20.dp, end = 20.dp),
horizontalAlignment = Alignment.End
) {
Text(
text = record.expression,
fontSize = 24.sp,
color = CalcTheme.colors.resultColor
)
Text(
text = record.result,
fontSize = 30.sp,
color = CalcTheme.colors.resultColor
)
}
}
item {
Column(
Modifier
.fillMaxWidth()
.padding(top = 20.dp, start = 20.dp, end = 20.dp)
.background(CalcTheme.colors.backgroundColor),
horizontalAlignment = Alignment.End
) {
Text(text = viewModel.currentExpression.stateList2String(),
fontSize = 24.sp,
color = CalcTheme.colors.resultColor
)
Text(
text = if (viewModel.hasError) "Error!" else viewModel.currentResult,
fontSize = 30.sp,
color = CalcTheme.colors.resultColor
)
}
}
}
}
val buttons = arrayOf(
arrayOf("AC", "7", "4", "1", "%"),
arrayOf("÷", "8", "5", "2", "0"),
arrayOf("×", "9", "6", "3", "."),
arrayOf("X", "-", "+", "="),
)
@Composable
fun ButtonGroup(modifier: Modifier, viewModel: MainViewModel) {
Row(
modifier
.padding(vertical = 20.dp, horizontal = 24.dp)
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
buttons.forEach {
Column(
Modifier.width(60.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
it.forEach { it ->
if (it == "X") {
Backspace() {
viewModel.notifyDown()
if (viewModel.hasError) {
viewModel.clear()
} else {
if (viewModel.hasResult) {
viewModel.addResult()
viewModel.clear()
} else {
if (viewModel.currentExpression.size > 0) {
viewModel.currentExpression.removeLast()
}
}
}
}
} else {
CalcButton(
Modifier
.width(60.dp)
.height(if (it == "=") 132.dp else 60.dp),
symbol = it,
) { symbol ->
viewModel.notifyDown()
when (symbol) {
"=" -> {
if (viewModel.currentExpression.size > 0) {
val last = viewModel.currentExpression.last()
val n = arrayOf("+", "-", "×", "÷", ".")
if (!n.contains(last) && !viewModel.hasError) {
viewModel.calculate()
}
}
}
"AC" -> {
if (!viewModel.hasError && viewModel.hasResult) {
viewModel.addResult()
}
viewModel.clear()
}
"%" -> {
if (viewModel.currentExpression.size > 0) {
val last = viewModel.currentExpression.last()
val n = arrayOf("+", "-", "×", "÷", ".")
if (!n.contains(last) && !viewModel.hasError) {
if (viewModel.hasResult) {
viewModel.addResult()
viewModel.clear()
val lastResult =
viewModel.lastResult().replaceFirst("=", "")
viewModel.currentExpression.add(lastResult)
}
viewModel.currentExpression.add("×0.01")
}
}
}
in "+", "-", "×", "÷" -> {
if (viewModel.currentExpression.size > 0) {
val last = viewModel.currentExpression.last()
val n = arrayOf("+", "-", "×", "÷")
if (!n.contains(last) && !viewModel.hasError) {
if (viewModel.hasResult) {
viewModel.addResult()
viewModel.clear()
val lastResult =
viewModel.lastResult().replaceFirst("=", "")
viewModel.currentExpression.add(lastResult)
}
viewModel.currentExpression.add(symbol)
}
}
}
else -> {
if (viewModel.hasError) {
viewModel.clear()
viewModel.currentExpression.add(symbol)
} else {
if (viewModel.hasResult) {
viewModel.addResult()
viewModel.clear()
}
if (viewModel.currentExpression.size < 36) {
viewModel.currentExpression.add(symbol)
}
}
}
}
}
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fe53ca30082c2835673e1ab0b82e212bcf5c51d3
| 9,890
|
ComposeCalculator
|
MIT License
|
app/src/main/java/xyz/leomurca/sporteventtracker/MainActivity.kt
|
leomurca
| 815,376,543
| false
|
{"Kotlin": 46715}
|
package xyz.leomurca.sporteventtracker
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import dagger.hilt.android.AndroidEntryPoint
import xyz.leomurca.sporteventtracker.ui.home.HomeScreen
import xyz.leomurca.sporteventtracker.ui.home.HomeViewModel
import xyz.leomurca.sporteventtracker.ui.theme.SportEventTrackerTheme
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val viewModel: HomeViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
SportEventTrackerTheme {
Scaffold(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background))
{
Scaffold(
modifier = Modifier.padding(it),
topBar = {
CustomTopAppBar()
}
) { paddingValues ->
HomeScreen(viewModel = viewModel, modifier = Modifier.padding(top = paddingValues.calculateTopPadding()))
}
}
}
}
}
}
@Composable
fun CustomTopAppBar() {
Row(
modifier = Modifier
.height(70.dp)
.padding(0.dp)
.fillMaxWidth()
.background(MaterialTheme.colorScheme.tertiary),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.drawable.logo_sportstracker),
contentDescription = "Logo",
modifier = Modifier.padding(vertical = 4.dp)
)
}
}
| 0
|
Kotlin
|
0
| 0
|
f0b1eafb2810b9c7f9595fd04562503a7b4ad6e5
| 2,623
|
sport-event-tracker
|
MIT License
|
src/main/kotlin/br/com/danielvazmartins/labcreditsystemkotlin/service/ICustomerService.kt
|
danielvazmartins
| 709,357,294
| false
|
{"Kotlin": 51198}
|
package br.com.danielvazmartins.labcreditsystemkotlin.service
import br.com.danielvazmartins.labcreditsystemkotlin.entity.Customer
interface ICustomerService {
fun save(customer: Customer): Customer
fun findById(id: Long): Customer
fun delete(id: Long)
}
| 0
|
Kotlin
|
0
| 0
|
fd235cb0e9938035c176ea676477becaeb6b5954
| 270
|
lab-credit-system-kotlin
|
MIT License
|
stream-chat-android-ui-uitests/src/androidTest/java/io/getstream/chat/android/uitests/snapshot/uicomponents/search/SearchViewTest.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.uitests.snapshot.uicomponents.search
import android.view.View
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import com.karumi.shot.FragmentScenarioUtils.waitForFragment
import com.karumi.shot.ScreenshotTest
import io.getstream.chat.android.core.internal.InternalStreamChatApi
import io.getstream.chat.android.uitests.R
import org.hamcrest.BaseMatcher
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.junit.Test
@InternalStreamChatApi
class SearchViewTest : ScreenshotTest {
@Test
fun testWithNoCustomizations() {
val fragmentScenario = launchFragmentInContainer<ComponentBrowserSearchViewFragment>()
compareScreenshot(fragmentScenario.waitForFragment())
}
@Test
fun eraseContentShouldWork() {
launchFragmentInContainer<ComponentBrowserSearchViewFragment>()
val text = "lalalala"
onView(getElementFromMatchAtPosition(withId(R.id.inputField), 0)).perform(typeText(text))
onView(getElementFromMatchAtPosition(withId(R.id.inputField), 0)).check(matches(withText(text)))
onView(getElementFromMatchAtPosition(withId(R.id.clearInputButton), 0)).perform(click())
onView(getElementFromMatchAtPosition(withId(R.id.inputField), 0)).check(matches(withText("")))
}
@Test
fun testVeryLongSearch() {
val fragmentScenario = launchFragmentInContainer<ComponentBrowserSearchViewFragment>()
val text = "lalalala"
repeat(10) {
onView(getElementFromMatchAtPosition(withId(R.id.inputField), 0)).perform(typeText(text))
}
compareScreenshot(fragmentScenario.waitForFragment())
}
}
private fun getElementFromMatchAtPosition(matcher: Matcher<View>, position: Int): Matcher<View> {
return object : BaseMatcher<View>() {
var counter = 0
override fun matches(item: Any?): Boolean {
if (matcher.matches(item)) {
if (counter == position) {
counter++
return true
}
counter++
}
return false
}
override fun describeTo(description: Description) {
description.appendText("Element at hierarchy position $position")
}
}
}
| 24
|
Kotlin
|
273
| 1,451
|
8e46f46a68810d8086c48a88f0fff29faa2629eb
| 3,270
|
stream-chat-android
|
FSF All Permissive License
|
src/test/kotlin/cz/opendatalab/captcha/datamanagement/objectdetection/ObjectDetectorKotlinDLTest.kt
|
opendatalabcz
| 481,095,558
| false
|
{"Kotlin": 221562, "JavaScript": 47287, "HTML": 26542, "CSS": 9253, "Dockerfile": 304}
|
package cz.opendatalab.captcha.datamanagement.objectdetection
import cz.opendatalab.captcha.TestImages
import mu.KotlinLogging
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.springframework.util.FileSystemUtils
import java.nio.file.Paths
internal class ObjectDetectorKotlinDLTest {
private val objectDetector = ObjectDetectorKotlinDL(cachePath.toAbsolutePath().toString())
@Test
fun `detect person detected`() {
val detected = objectDetector.detect(TestImages.IMAGE_1)
assertTrue(detected.isNotEmpty())
assertTrue(detected.stream().anyMatch{ obj -> obj.label.equals("person") })
}
@Test
fun `getSupportedLabels not empty`() {
assertTrue(objectDetector.getSupportedLabels().isNotEmpty())
}
companion object {
private val cachePath = Paths.get(System.getProperty("java.io.tmpdir"), "czech-captcha")
private val logger = KotlinLogging.logger {}
@AfterAll
@JvmStatic
private fun removeCache() {
logger.info("Deleting directory with object detection model after tests.")
try {
FileSystemUtils.deleteRecursively(cachePath)
} catch (e: Exception) {
logger.warn("Could not delete directory with OD cache.", e)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
16e1871255bdda1a79a0b44502d2acc01b6ad0af
| 1,399
|
czech-captcha
|
Apache License 2.0
|
app/src/main/java/com/coppel/preconfirmar/loteo/ListaLoteoFragment.kt
|
Aguayo91
| 394,428,141
| false
| null |
package com.coppel.preconfirmar.loteo
import android.app.Dialog
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.Button
import android.widget.TextView
import androidx.navigation.fragment.findNavController
import com.coppel.preconfirmar.R
import com.coppel.preconfirmar.application.RxApplication
import com.coppel.preconfirmar.databinding.FragmentListaLoteoBinding
import com.coppel.preconfirmar.preconfirmar.HomeFragment
import com.coppel.preconfirmar.preconfirmar.HomeFragmentDirections
import com.orhanobut.logger.Logger
class ListaLoteoFragment : Fragment(R.layout.fragment_lista_loteo) {
companion object {
private val TAG = ListaLoteoFragment::class.qualifiedName
}
lateinit var binding: FragmentListaLoteoBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentListaLoteoBinding.bind(view)
binding.mifolio.text = RxApplication.pref
.obtenerFoliodelSurtido()
binding.miseleccion.text = RxApplication.pref.
obtenerTipoSeleccionado().toString()
binding.milayoutSeleccion.setOnClickListener {
finalizarSurtido()
Logger.d("el Tipo Seleccionado es " +
RxApplication.pref.obtenerTipoSeleccionado().toString()
)
Logger.d("el Folio es " +
RxApplication.pref.obtenerFoliodelSurtido()
)
}
}
private fun finalizarSurtido() {
activity?.runOnUiThread {
Handler(Looper.getMainLooper()).postDelayed({
showIniciarLoteo(
resources.getString(R.string.titulo_iniciarFolio),
resources.getString(R.string.msg_iniciarFolio,RxApplication.pref
.obtenerFoliodelSurtido())
)
}, 0)
}
}
private fun showIniciarLoteo(title: String, mensaje: String) {
val showfinalizar = Dialog(requireActivity())
showfinalizar.requestWindowFeature(Window.FEATURE_NO_TITLE)
showfinalizar.setCancelable(false)
showfinalizar.setContentView(R.layout.alertdialog_decision)
showfinalizar.window!!.setWindowAnimations(R.style.DialogAnimation)
val body = showfinalizar.findViewById(R.id.title_warning) as TextView
val message = showfinalizar.findViewById(R.id.message_warning) as TextView
body.text = title
message.text = mensaje
val btntoAccept = showfinalizar.findViewById(R.id.alert_btn_si) as Button
val btntoCancelled = showfinalizar.findViewById(R.id.alert_btn_no) as Button
btntoAccept.setText(R.string.btn_irregularidad_si)
btntoCancelled.setText(R.string.btn_irregularidad_no)
btntoCancelled.setOnClickListener {
showfinalizar.dismiss()
}
btntoAccept.setOnClickListener {
val action = ListaLoteoFragmentDirections.actionListaLoteoFragmentToLoteoFragment()
findNavController().navigate(action)
showfinalizar.dismiss()
}
showfinalizar.show()
}
}
| 0
|
Kotlin
|
0
| 0
|
17880cc61f72229b0b8ed8f87afa560877234097
| 3,363
|
Christian
|
MIT License
|
app/src/main/java/com/example/cryptoapp/data/repository/CoinRepositoryImpl.kt
|
jlpmartinss
| 855,792,857
| false
|
{"Kotlin": 31610}
|
package com.example.cryptoapp.data.repository
import com.example.cryptoapp.data.remote.CoinPaprikaApi
import com.example.cryptoapp.data.remote.dto.CoinDetailDto
import com.example.cryptoapp.data.remote.dto.CoinDto
import com.example.cryptoapp.domain.repository.CoinRepository
import javax.inject.Inject
class CoinRepositoryImpl @Inject constructor(
private val api: CoinPaprikaApi
) : CoinRepository {
override suspend fun getCoins(): List<CoinDto> {
return api.getCoins()
}
override suspend fun getCoinById(coinId: String): CoinDetailDto {
return api.getCoinById(coinId)
}
}
| 0
|
Kotlin
|
0
| 0
|
e15502aa9608828687b2374da081b01dcc6695a2
| 614
|
CryptoApp
|
MIT License
|
app/src/main/java/com/example/cryptoapp/data/repository/CoinRepositoryImpl.kt
|
jlpmartinss
| 855,792,857
| false
|
{"Kotlin": 31610}
|
package com.example.cryptoapp.data.repository
import com.example.cryptoapp.data.remote.CoinPaprikaApi
import com.example.cryptoapp.data.remote.dto.CoinDetailDto
import com.example.cryptoapp.data.remote.dto.CoinDto
import com.example.cryptoapp.domain.repository.CoinRepository
import javax.inject.Inject
class CoinRepositoryImpl @Inject constructor(
private val api: CoinPaprikaApi
) : CoinRepository {
override suspend fun getCoins(): List<CoinDto> {
return api.getCoins()
}
override suspend fun getCoinById(coinId: String): CoinDetailDto {
return api.getCoinById(coinId)
}
}
| 0
|
Kotlin
|
0
| 0
|
e15502aa9608828687b2374da081b01dcc6695a2
| 614
|
CryptoApp
|
MIT License
|
app/src/main/java/com/elliot/weathermate/views/init/InitActivity.kt
|
elliot-cx
| 619,191,283
| false
| null |
package com.elliot.weathermate.views.init
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.elliot.weathermate.Utils
import com.elliot.weathermate.views.main.MainActivity
import com.elliot.weathermate.views.setup.SetupActivity
class InitActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(Utils.initConfig(applicationContext)){
// Initialisation des locations
Utils.loadLocations(this)
// Lancement de l'activitée principale
startActivity(Intent(this,MainActivity::class.java))
}else{
startActivity(Intent(this,SetupActivity::class.java))
}
this.finish()
}
}
| 0
|
Kotlin
|
0
| 0
|
0dd1dcbf0b7c9762a898d87f2b1fbced4efd263a
| 804
|
WeatherMate
|
MIT License
|
app/src/main/java/com/wisnu/kurniawan/wallee/features/dashboard/ui/DashboardNavRail.kt
|
wisnukurniawan
| 502,203,866
| false
|
{"Kotlin": 546472}
|
package com.wisnu.kurniawan.wallee.features.dashboard.ui
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationRail
import androidx.compose.material3.NavigationRailItem
import androidx.compose.material3.NavigationRailItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import com.wisnu.kurniawan.wallee.foundation.uicomponent.PgIcon
@Composable
fun DashboardNavRail(
currentDestination: NavDestination?,
viewModel: DashboardHostViewModel,
onTabClick: (String) -> Unit
) {
val state by viewModel.state.collectAsStateWithLifecycle()
DashboardNavRail(
sections = state.sections,
currentDestination = currentDestination,
onTabClick = {
onTabClick(it.route)
}
)
}
@Composable
private fun DashboardNavRail(
sections: List<DashboardSection>,
currentDestination: NavDestination?,
onTabClick: (DashboardSection) -> Unit
) {
NavigationRail(
modifier = Modifier.safeDrawingPadding(),
containerColor = Color.Transparent,
) {
sections.forEachIndexed { _, item ->
val selected = currentDestination?.hierarchy?.any { it.route == item.route } == true
NavigationRailItem(
selected = selected,
onClick = { onTabClick(item) },
icon = {
val color = if (selected) {
MaterialTheme.colorScheme.primary
} else {
LocalContentColor.current
}
PgIcon(imageVector = item.icon, tint = color)
},
label = { Text(stringResource(item.title)) },
colors = NavigationRailItemDefaults.colors(
selectedTextColor = MaterialTheme.colorScheme.primary,
)
)
}
}
}
| 11
|
Kotlin
|
17
| 168
|
0076eebb25846bbab772accfb2a4e49ffa7be3d5
| 2,370
|
Compose-Expense
|
Apache License 2.0
|
src/jsMain/kotlin/external/index.Asn1js.module_asn1js.kt
|
asit-fdraschbacher
| 373,781,190
| true
|
{"Kotlin": 195978, "HTML": 3567, "JavaScript": 1308}
|
@file:JsModule("asn1js")
@file:JsNonModule
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
package Asn1js
import kotlin.js.*
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
external interface LocalBaseBlockParams {
var blockLength: Number?
get() = definedExternally
set(value) = definedExternally
var error: String?
get() = definedExternally
set(value) = definedExternally
var warnings: Array<String>?
get() = definedExternally
set(value) = definedExternally
var valueBeforeDecode: ArrayBuffer?
get() = definedExternally
set(value) = definedExternally
}
external interface JsonLocalBaseBlock {
var blockName: String
var blockLength: Number
var error: String
var warnings: Array<String>
var valueBeforeDecode: ArrayBuffer
}
external open class LocalBaseBlock(params: LocalBaseBlockParams = definedExternally) {
open var blockLength: Number
open var error: String
open var warnings: Array<String>
open var valueBeforeDecode: ArrayBuffer
open fun toJSON(): Any
companion object {
fun blockName(): String
}
}
external interface LocalHexBlockParams : LocalBaseBlockParams {
var isHexOnly: Boolean?
get() = definedExternally
set(value) = definedExternally
var valueHex: ArrayBuffer?
get() = definedExternally
set(value) = definedExternally
}
external interface ILocalHexBlock {
var isHexOnly: Boolean
var valueHex: ArrayBuffer
fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
fun toBER(sizeOnly: Boolean = definedExternally): ArrayBuffer
fun toJSON(): Any
}
external open class LocalHexBlock(params: Any) : ILocalHexBlock {
override var isHexOnly: Boolean
override var valueHex: ArrayBuffer
override fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
override fun toBER(sizeOnly: Boolean): ArrayBuffer
override fun toJSON(): Any
companion object {
fun blockName(): String
}
}
external interface `T$10` {
var isConstructed: Boolean?
get() = definedExternally
set(value) = definedExternally
var tagClass: Number?
get() = definedExternally
set(value) = definedExternally
var tagNumber: Number?
get() = definedExternally
set(value) = definedExternally
}
external interface LocalIdentificationBlockParams {
var idBlock: LocalHexBlockParams? /* LocalHexBlockParams? & `T$10`? */
get() = definedExternally
set(value) = definedExternally
}
external open class LocalIdentificationBlock(params: LocalIdentificationBlockParams = definedExternally) : LocalBaseBlock, ILocalHexBlock {
open var isConstructed: Boolean
open var tagClass: Number
open var tagNumber: Number
override var isHexOnly: Boolean
override var valueHex: ArrayBuffer
override fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
override fun toBER(sizeOnly: Boolean): ArrayBuffer
}
external interface `T$11` {
var isIndefiniteForm: Boolean?
get() = definedExternally
set(value) = definedExternally
var longFormUsed: Boolean?
get() = definedExternally
set(value) = definedExternally
var length: Number
}
external interface LocalLengthBlockParams {
var lenBlock: `T$11`?
get() = definedExternally
set(value) = definedExternally
}
external open class LocalLengthBlock(params: LocalLengthBlockParams = definedExternally) : LocalBaseBlock {
open var isIndefiniteForm: Boolean
open var longFormUsed: Boolean
open var length: Number
open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number)
open fun toBER(sizeOnly: Boolean = definedExternally): ArrayBuffer
}
external open class LocalValueBlock(params: LocalBaseBlockParams = definedExternally) : LocalBaseBlock {
open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number)
open fun toBER(sizeOnly: Boolean = definedExternally): ArrayBuffer
}
external interface BaseBlockParams : LocalBaseBlockParams {
var name: String?
get() = definedExternally
set(value) = definedExternally
var optional: Boolean?
get() = definedExternally
set(value) = definedExternally
var primitiveSchema: Any?
get() = definedExternally
set(value) = definedExternally
}
external open class BaseBlock<T : LocalValueBlock>(parameters: BaseBlockParams = definedExternally, valueBlockType: Any = definedExternally) : LocalBaseBlock {
open var idBlock: LocalIdentificationBlock
open var lenBlock: LocalLengthBlock
open var valueBlock: T
open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
open fun toBER(sizeOnly: Boolean = definedExternally): ArrayBuffer
}
external interface LocalPrimitiveValueBlockParams : LocalBaseBlockParams {
var valueHex: ArrayBuffer?
get() = definedExternally
set(value) = definedExternally
var isHexOnly: Boolean?
get() = definedExternally
set(value) = definedExternally
}
external open class LocalPrimitiveValueBlock(params: LocalBaseBlockParams = definedExternally) : LocalValueBlock {
open var valueHex: ArrayBuffer
open var isHexOnly: Boolean
override open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
override fun toBER(sizeOnly: Boolean): ArrayBuffer
}
external open class Primitive(parameters: BaseBlockParams = definedExternally, valueBlockType: Any = definedExternally) : BaseBlock<LocalPrimitiveValueBlock>
external interface LocalConstructedValueBlockParams : LocalBaseBlockParams {
var value: LocalValueBlock?
get() = definedExternally
set(value) = definedExternally
var isIndefiniteForm: Boolean?
get() = definedExternally
set(value) = definedExternally
}
external open class LocalConstructedValueBlock(params: LocalBaseBlockParams = definedExternally) : LocalValueBlock {
open var value: Array<LocalValueBlock>
open var isIndefiniteForm: Boolean
override open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
override fun toBER(sizeOnly: Boolean): ArrayBuffer
}
external open class Constructed(parameters: BaseBlockParams = definedExternally, valueBlockType: Any = definedExternally) : BaseBlock<LocalConstructedValueBlock>
external interface LocalEndOfContentValueBlockParams : LocalBaseBlockParams
external open class LocalEndOfContentValueBlock(params: LocalEndOfContentValueBlockParams = definedExternally) : LocalValueBlock {
override open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
override fun toBER(sizeOnly: Boolean): ArrayBuffer
}
external open class EndOfContent(parameters: BaseBlockParams = definedExternally, valueBlockType: Any = definedExternally) : BaseBlock<LocalEndOfContentValueBlock>
external interface LocalBooleanValueBlockParams : LocalBaseBlockParams {
var value: Boolean?
get() = definedExternally
set(value) = definedExternally
var isHexOnly: Boolean?
get() = definedExternally
set(value) = definedExternally
var valueHex: ArrayBuffer?
get() = definedExternally
set(value) = definedExternally
}
external open class LocalBooleanValueBlock(params: LocalBaseBlockParams = definedExternally) : LocalValueBlock {
open var value: Boolean
open var isHexOnly: Boolean
open var valueHex: ArrayBuffer
override open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
override fun toBER(sizeOnly: Boolean): ArrayBuffer
}
external open class Boolean(parameters: BaseBlockParams = definedExternally, valueBlockType: Any = definedExternally) : BaseBlock<LocalBooleanValueBlock>
external open class Sequence(parameters: BaseBlockParams = definedExternally, valueBlockType: Any = definedExternally) : Constructed
external open class Set(parameters: BaseBlockParams = definedExternally, valueBlockType: Any = definedExternally) : Constructed
external open class Null(parameters: BaseBlockParams = definedExternally, valueBlockType: Any = definedExternally) : BaseBlock<LocalValueBlock>
external interface LocalOctetStringValueBlockParams : LocalConstructedValueBlockParams, LocalHexBlockParams {
var isConstructed: Boolean?
get() = definedExternally
set(value) = definedExternally
}
external open class LocalOctetStringValueBlock(params: LocalOctetStringValueBlockParams = definedExternally) : LocalConstructedValueBlock, ILocalHexBlock {
open var isConstructed: Boolean
override var isHexOnly: Boolean
override var valueHex: ArrayBuffer
}
external open class OctetString(params: LocalOctetStringValueBlockParams = definedExternally) : BaseBlock<LocalOctetStringValueBlock> {
open fun isEqual(octetString: OctetString): Boolean
}
external interface LocalBitStringValueBlockParams : LocalConstructedValueBlockParams, LocalHexBlockParams {
var unusedBits: Number?
get() = definedExternally
set(value) = definedExternally
var isConstructed: Boolean?
get() = definedExternally
set(value) = definedExternally
override var blockLength: Number?
get() = definedExternally
set(value) = definedExternally
}
external open class LocalBitStringValueBlock(params: LocalBitStringValueBlockParams = definedExternally) : LocalConstructedValueBlock {
open var unusedBits: Number
open var isConstructed: Boolean
override var blockLength: Number
open var isHexOnly: Boolean
open var valueHex: ArrayBuffer
}
external open class BitString(params: LocalBitStringValueBlockParams = definedExternally) : BaseBlock<LocalBitStringValueBlock> {
open fun isEqual(bitString: BitString): Boolean
}
external interface LocalIntegerValueBlockParams : LocalBaseBlockParams, LocalHexBlockParams
external open class LocalIntegerValueBlock(params: LocalIntegerValueBlockParams = definedExternally) : LocalValueBlock {
open var valueDec: Number
open var isHexOnly: Boolean
open var valueHex: ArrayBuffer
override open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
override fun toBER(sizeOnly: Boolean): ArrayBuffer
open fun fromDER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number, expectedLength: Number = definedExternally): Number
open fun toDER(sizeOnly: Boolean = definedExternally): ArrayBuffer
}
external interface IntegerParams {
var value: Number?
get() = definedExternally
set(value) = definedExternally
}
external open class Integer(params: IntegerParams = definedExternally) : BaseBlock<LocalIntegerValueBlock> {
open fun isEqual(otherValue: Integer): Boolean
open fun isEqual(otherValue: ArrayBuffer): Boolean
open fun convertToDER(): Integer
open fun convertFromDER(): Integer
}
external open class Enumerated(params: IntegerParams = definedExternally) : Integer
external interface LocalSidValueBlockParams : LocalBaseBlockParams, LocalHexBlockParams {
var valueDec: Number?
get() = definedExternally
set(value) = definedExternally
var isFirstSid: Boolean?
get() = definedExternally
set(value) = definedExternally
}
external open class LocalSidValueBlock(params: LocalSidValueBlockParams = definedExternally) : LocalBaseBlock {
open var valueDec: Number
open var isFirstSid: Boolean
open var isHexOnly: Boolean
open var valueHex: ArrayBuffer
open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
open fun toBER(sizeOnly: Boolean = definedExternally): ArrayBuffer
override fun toString(): String
}
external interface LocalObjectIdentifierValueBlockParams : LocalBaseBlockParams {
var value: String?
get() = definedExternally
set(value) = definedExternally
}
external open class LocalObjectIdentifierValueBlock(params: LocalObjectIdentifierValueBlockParams = definedExternally) : LocalValueBlock {
open fun fromString(data: String): Boolean
override fun toString(): String
}
external open class ObjectIdentifier(params: LocalObjectIdentifierValueBlockParams = definedExternally) : BaseBlock<LocalObjectIdentifierValueBlock>
external interface LocalUtf8StringValueBlockParams : LocalBaseBlockParams, LocalHexBlock
external open class LocalUtf8StringValueBlock(params: LocalSidValueBlockParams = definedExternally) : LocalValueBlock {
open var isHexOnly: Boolean
open var valueHex: ArrayBuffer
override open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
override open fun toBER(sizeOnly: Boolean): ArrayBuffer
override fun toString(): String
}
external interface Utf8StringParams {
var value: String?
get() = definedExternally
set(value) = definedExternally
}
external open class Utf8String(params: Utf8StringParams = definedExternally) : BaseBlock<LocalUtf8StringValueBlock> {
open fun fromBuffer(inputBuffer: ArrayBuffer)
open fun fromString(inputString: String)
}
external interface LocalBmpStringValueBlockParams : LocalHexBlockParams, LocalBaseBlockParams
external open class LocalBmpStringValueBlock(params: LocalBmpStringValueBlockParams = definedExternally) : LocalValueBlock {
open var value: String
open var isHexOnly: Boolean
open var valueHex: ArrayBuffer
override open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
}
external interface BmpStringParams {
var value: String?
get() = definedExternally
set(value) = definedExternally
}
external open class BmpString(params: BmpStringParams = definedExternally) : BaseBlock<LocalBmpStringValueBlock> {
open fun fromBuffer(inputBuffer: ArrayBuffer)
open fun fromString(inputString: String)
}
external interface LocalUniversalStringValueParams : LocalHexBlockParams, LocalBaseBlockParams
external open class LocalUniversalStringValueBlock(params: LocalUniversalStringValueParams = definedExternally) : LocalValueBlock {
open var value: String
open var isHexOnly: Boolean
open var valueHex: ArrayBuffer
override open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
override open fun toBER(sizeOnly: Boolean): ArrayBuffer
}
external interface UniversalStringParams {
var value: String?
get() = definedExternally
set(value) = definedExternally
}
external open class UniversalString(params: UniversalStringParams = definedExternally) : BaseBlock<LocalUniversalStringValueBlock> {
open fun fromBuffer(inputBuffer: ArrayBuffer)
open fun fromString(inputString: String)
}
external interface LocalSimpleLocalSimpleStringValueBlockParams : LocalHexBlockParams, LocalBaseBlockParams
external open class LocalSimpleLocalSimpleStringValueBlock(params: LocalSimpleLocalSimpleStringValueBlockParams = definedExternally) : LocalValueBlock {
open var value: String
open var isHexOnly: Boolean
open var valueHex: ArrayBuffer
override open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
override open fun toBER(sizeOnly: Boolean): ArrayBuffer
}
external interface LocalSimpleStringBlockParams {
var value: String?
get() = definedExternally
set(value) = definedExternally
}
external open class LocalSimpleStringBlock(params: LocalSimpleStringBlockParams = definedExternally) : BaseBlock<LocalSimpleLocalSimpleStringValueBlock> {
open fun fromBuffer(inputBuffer: ArrayBuffer)
open fun fromString(inputString: String)
}
external open class NumericString(params: LocalSimpleStringBlockParams = definedExternally) : LocalSimpleStringBlock
external open class PrintableString(params: LocalSimpleStringBlockParams = definedExternally) : LocalSimpleStringBlock
external open class TeletexString(params: LocalSimpleStringBlockParams = definedExternally) : LocalSimpleStringBlock
external open class VideotexString(params: LocalSimpleStringBlockParams = definedExternally) : LocalSimpleStringBlock
external open class IA5String(params: LocalSimpleStringBlockParams = definedExternally) : LocalSimpleStringBlock
external open class GraphicString(params: LocalSimpleStringBlockParams = definedExternally) : LocalSimpleStringBlock
external open class VisibleString(params: LocalSimpleStringBlockParams = definedExternally) : LocalSimpleStringBlock
external open class GeneralString(params: LocalSimpleStringBlockParams = definedExternally) : LocalSimpleStringBlock
external open class CharacterString(params: LocalSimpleStringBlockParams = definedExternally) : LocalSimpleStringBlock
external interface UTCTimeParams : LocalSimpleLocalSimpleStringValueBlockParams {
var value: String?
get() = definedExternally
set(value) = definedExternally
var valueDate: Date?
get() = definedExternally
set(value) = definedExternally
}
external open class UTCTime(params: UTCTimeParams = definedExternally) : VisibleString {
open var year: Number
open var month: Number
open var day: Number
open var hour: Number
open var minute: Number
open var second: Number
open fun toBuffer(): ArrayBuffer
open fun fromDate(inputDate: Date)
open fun toDate(): Date
}
external open class GeneralizedTime(params: UTCTimeParams = definedExternally) : UTCTime {
open var millisecond: Number
}
external open class DATE(params: Utf8StringParams = definedExternally) : Utf8String
external open class TimeOfDay(params: Utf8StringParams = definedExternally) : Utf8String
external open class DateTime(params: Utf8StringParams = definedExternally) : Utf8String
external open class Duration(params: Utf8StringParams = definedExternally) : Utf8String
external open class TIME(params: Utf8StringParams = definedExternally) : Utf8String
external interface ChoiceParams {
var value: Array<LocalValueBlock>?
get() = definedExternally
set(value) = definedExternally
var optional: Boolean?
get() = definedExternally
set(value) = definedExternally
}
external open class Choice(params: ChoiceParams = definedExternally) {
open var value: Array<LocalValueBlock>
open var optional: Boolean
}
external interface AnyParams {
var name: String?
get() = definedExternally
set(value) = definedExternally
var optional: Boolean?
get() = definedExternally
set(value) = definedExternally
}
external open class Any(params: AnyParams = definedExternally) {
open var name: String
open var optional: Boolean
}
external interface RepeatedParams {
var name: String?
get() = definedExternally
set(value) = definedExternally
var optional: Boolean?
get() = definedExternally
set(value) = definedExternally
var value: Any?
get() = definedExternally
set(value) = definedExternally
var local: Boolean?
get() = definedExternally
set(value) = definedExternally
}
external open class Repeated(params: RepeatedParams = definedExternally) {
open var name: String
open var optional: Boolean
open var value: Any
open var local: Boolean
}
external interface RawDataParams {
var data: ArrayBuffer?
get() = definedExternally
set(value) = definedExternally
}
external open class RawData(params: RawDataParams = definedExternally) {
open var data: ArrayBuffer
open fun fromBER(inputBuffer: ArrayBuffer, inputOffset: Number, inputLength: Number): Number
open fun toBER(sizeOnly: Boolean = definedExternally): ArrayBuffer
}
external interface `T$12` {
var offset: Number
var result: LocalBaseBlock
}
external fun fromBER(inputBuffer: ArrayBuffer): `T$12`
external interface `T$13` {
var verified: Boolean
var result: Any?
get() = definedExternally
set(value) = definedExternally
}
external fun compareSchema(root: Any, inputData: Any, inputSchema: Any): `T$13`
external fun verifySchema(inputBuffer: ArrayBuffer, inputSchema: Any): `T$13`
| 0
| null |
0
| 0
|
f347dc143010e5299765551df41bc4228ad728d2
| 20,748
|
hcert-kotlin
|
Apache License 2.0
|
nodecore-cli/src/main/java/nodecore/cli/serialization/BitcoinBlockPayload.kt
|
VeriBlock
| 179,742,374
| false
|
{"Gradle Kotlin DSL": 22, "INI": 3, "Markdown": 15, "Shell": 1, "Text": 14, "Ignore List": 6, "Batchfile": 2, "Git Attributes": 1, "EditorConfig": 2, "YAML": 3, "Kotlin": 480, "Java": 253, "Dockerfile": 6, "Java Properties": 1, "XML": 9, "JSON with Comments": 3, "JSON": 6, "JavaScript": 2, "Browserslist": 1, "HTML": 10, "SCSS": 13, "Protocol Buffer": 1}
|
// VeriBlock NodeCore CLI
// Copyright 2017-2021 <NAME>
// All rights reserved.
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
package nodecore.cli.serialization
import com.google.gson.annotations.SerializedName
import nodecore.api.grpc.RpcGetLastBitcoinBlockReply
import org.veriblock.sdk.extensions.toHex
class BitcoinBlockPayload(
reply: RpcGetLastBitcoinBlockReply
) {
@SerializedName("header")
val header = reply.header.toHex()
@SerializedName("height")
val height = reply.height
@SerializedName("hash")
val hash = reply.hash.toHex()
}
| 72
|
Kotlin
|
16
| 12
|
ef06c51c1410ba59da13403b65e367b21dcfed21
| 694
|
nodecore
|
MIT License
|
sample/src/main/java/org/walletconnect/example/wallet/ui/WalletUiState.kt
|
WalletConnect-Labs
| 397,808,009
| false
| null |
package org.walletconnect.example.wallet.ui
import org.walletconnect.walletconnectv2.client.SessionProposal
sealed class WalletUiEvent
data class ShowSessionProposalDialog(val proposal: SessionProposal) : WalletUiEvent()
data class UpdateActiveSessions(val sessions: List<Session>) : WalletUiEvent()
object RejectSession : WalletUiEvent()
data class Session(
var icon: String = "",
var name: String = "",
var uri: String = ""
)
| 1
|
Kotlin
|
2
| 11
|
b05a1990cfbfc43b3380274183c33b0b7b307dc2
| 442
|
WalletConnectKotlinV2
|
Apache License 2.0
|
app/src/main/java/com/pandacorp/noteui/presentation/utils/helpers/Utils.kt
|
MrRuslanYT
| 547,794,682
| false
| null |
package com.pandacorp.noteui.presentation.utils.helpers
import android.app.Activity
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updateLayoutParams
import androidx.core.view.updateMargins
import androidx.transition.Slide
import androidx.transition.Transition
import androidx.transition.TransitionManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.target.Target
import com.pandacorp.noteui.app.R
import com.pandacorp.noteui.domain.model.ColorItem
class Utils {
companion object {
/**
* Get a list of images that user can choose to set a note's background
*/
val backgroundDrawablesList = listOf(
R.drawable.image_night_city,
R.drawable.image_city,
R.drawable.image_moon,
R.drawable.image_night_sky,
R.drawable.image_nature,
R.drawable.image_mountain,
R.drawable.image_colors,
R.drawable.image_speed
)
/**
* Get a list of default colors that will be shown on the database creation
*/
fun getDefaultColorsList(context: Context): List<ColorItem> = mutableListOf(
ColorItem(id = 1, color = ContextCompat.getColor(context, R.color.light_yellow)),
ColorItem(id = 2, color = ContextCompat.getColor(context, R.color.light_green)),
ColorItem(id = 3, color = ContextCompat.getColor(context, R.color.light_lime)),
ColorItem(id = 4, color = ContextCompat.getColor(context, R.color.light_blue)),
ColorItem(id = 5, color = ContextCompat.getColor(context, R.color.light_pink)),
ColorItem(id = 6, color = ContextCompat.getColor(context, R.color.light_purple)),
ColorItem(id = 7, color = ContextCompat.getColor(context, R.color.light_red))
)
/**
* Changes the note background in adapter and NoteScreen
* @param background encoded string background, stored in db
* @param imageView image view, where need to change the background
* @param isAdapter if true then set colorPrimary as background if it is a color, else colorBackground for NoteScreen
* @param isUseGlide if false don't use glide to change background instantly for NoteScreen
*/
fun changeNoteBackground(
background: String,
imageView: ImageView,
isAdapter: Boolean = false,
isUseGlide: Boolean = true
) {
try {
// note.background is an image drawable from Utils
val drawable =
ContextCompat.getDrawable(imageView.context, backgroundDrawablesList[background.toInt()])
if (!isUseGlide) {
imageView.setImageDrawable(drawable)
return
}
Glide.with(imageView.context)
.load(drawable)
.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) // Needed for correct work in adapters
.into(imageView)
} catch (e: ArrayIndexOutOfBoundsException) { // note.background is a color.
val typedValue = TypedValue()
if (isAdapter)
imageView.context.theme.resolveAttribute(android.R.attr.colorPrimary, typedValue, true)
else
imageView.context.theme.resolveAttribute(android.R.attr.colorBackground, typedValue, true)
val color = typedValue.data
if (!isUseGlide) {
imageView.setImageDrawable(ColorDrawable(color))
return
}
Glide.with(imageView.context)
.load(ColorDrawable(color))
.transition(DrawableTransitionOptions.withCrossFade())
.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) // Needed for correct work in adapters
.into(imageView)
} catch (e: NumberFormatException) { // note.background is an image from storage (uri)
if (!isUseGlide) {
imageView.setImageURI(Uri.parse(background))
return
}
Glide.with(imageView.context)
.load(Uri.parse(background))
.transition(DrawableTransitionOptions.withCrossFade())
.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) // Needed for correct work in adapters
.into(imageView)
}
}
/**
* Starts a sliding animation for 2 views
*/
fun animateViewSliding(
showingView: View,
hidingView: View
) {
val parent = showingView.parent as ViewGroup
val showingAnimation = Slide(Gravity.BOTTOM).apply {
duration = Constants.HIDE_DURATION
addTarget(showingView)
}
val hidingAnimation = Slide(Gravity.BOTTOM).apply {
duration = Constants.SHOW_DURATION
addTarget(hidingView)
}.addListener(object : Transition.TransitionListener {
override fun onTransitionEnd(transition: Transition) {
TransitionManager.beginDelayedTransition(parent, showingAnimation)
showingView.visibility = View.VISIBLE
}
override fun onTransitionCancel(transition: Transition) {}
override fun onTransitionStart(transition: Transition) {}
override fun onTransitionPause(transition: Transition) {}
override fun onTransitionResume(transition: Transition) {}
})
TransitionManager.beginDelayedTransition(parent, hidingAnimation)
hidingView.visibility = View.GONE
}
/**
* Method to apply insets to window to set soft input method SOFT_INPUT_ADJUST_RESIZE for api >= 30
*/
fun setUiWindowInsets(activity: Activity, root: View) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) activity.window.setDecorFitsSystemWindows(false)
var posTop = 0
var posBottom = 0
ViewCompat.setOnApplyWindowInsetsListener(root) { _, insets ->
if (posBottom == 0) {
posTop = insets.getInsets(WindowInsetsCompat.Type.systemBars()).top
posBottom = insets.getInsets(WindowInsetsCompat.Type.systemBars()).bottom
}
root.updateLayoutParams<ViewGroup.MarginLayoutParams> {
updateMargins(
top = posTop,
bottom = posBottom)
}
insets
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
d9cc0ca8e17a5af92bfced5bc3bd85776d2a0204
| 7,277
|
NoteUI
|
Apache License 2.0
|
feature/profilecard/src/androidMain/kotlin/io/github/droidkaigi/confsched/profilecard/component/InvertSystemBarAppearance.android.kt
|
DroidKaigi
| 776,354,672
| false
|
{"Kotlin": 1119401, "Swift": 211686, "Shell": 2954, "Makefile": 1314, "Ruby": 386}
|
package io.github.droidkaigi.confsched.profilecard.component
import android.app.Activity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.core.view.WindowCompat
@Composable
internal actual fun InvertSystemBarAppearance() {
val activity = LocalContext.current as Activity
val insetsController = WindowCompat.getInsetsController(activity.window, activity.window.decorView)
val originalIsAppearanceLight = remember { insetsController.isAppearanceLightStatusBars }
DisposableEffect(Unit) {
insetsController.isAppearanceLightStatusBars = !originalIsAppearanceLight
onDispose {
insetsController.isAppearanceLightStatusBars = originalIsAppearanceLight
}
}
}
| 49
|
Kotlin
|
201
| 438
|
57c38a76beb5b75edc9220833162e1257f40ac06
| 861
|
conference-app-2024
|
Apache License 2.0
|
RecyclerView/app/src/main/java/com/example/demoapp/MainActivity.kt
|
BennyZhang-Canviz
| 255,919,665
| false
| null |
package com.example.demoapp
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var users = ArrayList<User>()
for(i in 0..10){
var viewType = if(i%2==0) 0 else 1
val user = User(address = "Beijing$i", username = "Tom$i" , viewType = viewType)
users.add(user)
}
rvDemo.adapter = MainAdapter(users,this)
//使用LinearLayoutManager
var layoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
//使用GridLayoutManager
//var layoutManager = GridLayoutManager(this,2)
rvDemo.layoutManager = layoutManager
//添加分隔线
var decoration = DividerItemDecoration(this,DividerItemDecoration.VERTICAL)
//自定义颜色
ContextCompat.getDrawable(this, R.drawable.decoratoin)?.let { decoration.setDrawable(it) }
rvDemo.addItemDecoration(decoration)
}
}
| 0
|
Kotlin
|
0
| 0
|
55ae049d5c880b67251e40cf658c4535d52cd017
| 1,456
|
Android
|
Apache License 2.0
|
libs/trezor/src/commonMain/kotlin/kosh/libs/trezor/DefaultTrezorManager.kt
|
niallkh
| 855,100,709
| false
|
{"Kotlin": 1892361, "Swift": 21492}
|
package kosh.libs.trezor
import arrow.fx.coroutines.Resource
import arrow.fx.coroutines.resource
import co.touchlab.kermit.Logger
import kosh.libs.transport.Device
import kosh.libs.usb.Usb
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class DefaultTrezorManager(
private val usb: Usb,
private val sessionsCache: SessionsCache,
) : TrezorManager {
private val logger = Logger.withTag("[K]TrezorManager")
override val devices: Flow<List<TrezorDevice>>
get() = usb.devices(trezorUsbConfig)
.map { it.map(::mapTrezorDevice) }
override suspend fun open(
id: Long,
listener: TrezorManager.Connection.Listener,
): Resource<TrezorManager.Connection> = resource {
logger.d { "open(id = ${id})" }
DefaultTrezorConnection(
connection = TrezorUsbFormat(usb.open(id.toString(), trezorUsbConfig).bind()),
listener = listener,
sessionCache = sessionsCache.create(id)
)
}
}
internal fun mapTrezorDevice(device: Device): TrezorDevice = TrezorDevice(
id = device.id.toLong(),
product = device.name
)
| 0
|
Kotlin
|
0
| 3
|
e0149252019f8b47ceede5c0c1eb78c0a1e1c203
| 1,146
|
kosh
|
MIT License
|
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bulk/Happyemoji.kt
|
Tlaster
| 560,394,734
| false
|
{"Kotlin": 25133302}
|
package moe.tlaster.icons.vuesax.vuesaxicons.bulk
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
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 moe.tlaster.icons.vuesax.vuesaxicons.BulkGroup
public val BulkGroup.Happyemoji: ImageVector
get() {
if (_happyemoji != null) {
return _happyemoji!!
}
_happyemoji = Builder(name = "Happyemoji", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, fillAlpha = 0.4f, strokeAlpha
= 0.4f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(11.9707f, 22.0f)
curveTo(17.4936f, 22.0f, 21.9707f, 17.5228f, 21.9707f, 12.0f)
curveTo(21.9707f, 6.4771f, 17.4936f, 2.0f, 11.9707f, 2.0f)
curveTo(6.4479f, 2.0f, 1.9707f, 6.4771f, 1.9707f, 12.0f)
curveTo(1.9707f, 17.5228f, 6.4479f, 22.0f, 11.9707f, 22.0f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(11.9999f, 19.2499f)
curveTo(9.8499f, 19.2499f, 7.8299f, 18.1999f, 6.5999f, 16.4299f)
curveTo(6.3599f, 16.0899f, 6.4499f, 15.6199f, 6.7899f, 15.3899f)
curveTo(7.1299f, 15.1499f, 7.5999f, 15.2399f, 7.8299f, 15.5799f)
curveTo(8.7799f, 16.9399f, 10.3399f, 17.7599f, 11.9999f, 17.7599f)
curveTo(13.6599f, 17.7599f, 15.2199f, 16.9499f, 16.1699f, 15.5799f)
curveTo(16.4099f, 15.2399f, 16.8699f, 15.1599f, 17.2099f, 15.3899f)
curveTo(17.5499f, 15.6299f, 17.6299f, 16.0899f, 17.3999f, 16.4299f)
curveTo(16.1699f, 18.1999f, 14.1499f, 19.2499f, 11.9999f, 19.2499f)
close()
}
}
.build()
return _happyemoji!!
}
private var _happyemoji: ImageVector? = null
| 0
|
Kotlin
|
0
| 2
|
b8a8231e6637c2008f675ae76a3423b82ee53950
| 2,764
|
VuesaxIcons
|
MIT License
|
android/src/main/kotlin/co/glyco/flutter_essentials/Accelerometer.kt
|
acastr7
| 199,530,601
| false
|
{"Dart": 35326, "Kotlin": 26667, "Swift": 17464, "Ruby": 2978, "Objective-C": 415}
|
package co.glyco.flutter_essentials
import android.content.Intent
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.net.Uri
import android.os.Parcel
import android.os.Parcelable
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.EventChannel
class Accelerometer(val messenger: BinaryMessenger) : MethodChannel.MethodCallHandler, EventChannel.StreamHandler {
companion object {
const val prefix: String = "Accelerometer."
const val knownArgumentKeyStart: String = "startSpeed"
fun resolveDialIntent(number: String): Intent? {
var telUri = Uri.parse("tel:$number")
return Intent(Intent.ACTION_DIAL, telUri)
}
private var listener: AccelerometerListener? = null
private var accelerometer: Sensor? = null
private var eventSink: EventChannel.EventSink? = null
}
init {
var eventChannel = EventChannel(messenger, "flutter_essentials.Accelerometer")
eventChannel.setStreamHandler(this)
}
private val isSupported: Boolean
get() = Platform.sensorManager?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
var method = call.method.substringAfter(prefix)
if (method == "isSupported") {
result.success(isSupported)
} else if (method == "start") {
call.argument<String>(knownArgumentKeyStart)?.let {
var speed = SensorManager.SENSOR_DELAY_NORMAL
when {
it.endsWith("UI") -> speed = SensorManager.SENSOR_DELAY_UI
it.endsWith("GAME") -> speed = SensorManager.SENSOR_DELAY_GAME
it.endsWith("FASTEST") -> speed = SensorManager.SENSOR_DELAY_FASTEST
}
start(speed)
result.success(null)
} ?: result.error(method, "$knownArgumentKeyStart not found", null)
} else if (method == "stop") {
stop()
result.success(null)
} else {
result.notImplemented()
}
}
override fun onListen(arguments: Any?, incomingEventSink: EventChannel.EventSink?) {
eventSink = incomingEventSink
}
override fun onCancel(arguments: Any?) {
eventSink = null
}
fun start(sensorSpeed: Int) {
listener = AccelerometerListener()
accelerometer = Platform.sensorManager?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
Platform.sensorManager?.registerListener(listener, accelerometer, sensorSpeed)
}
fun stop() {
if (listener == null || accelerometer == null) return
Platform.sensorManager?.unregisterListener(listener, accelerometer)
listener = null
accelerometer = null
}
inner class AccelerometerListener : SensorEventListener {
// acceleration due to gravity
val gravity = 9.81
override fun onSensorChanged(event: SensorEvent?) {
if (event != null) {
val sensorValues = DoubleArray(event.values.size)
for (i in 0 until event.values.size) {
sensorValues[i] = event.values[i].toDouble() / gravity
}
eventSink?.success(sensorValues)
}
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
}
}
| 0
|
Dart
|
1
| 1
|
57c4f27ccfdc05827c2c47f7fd3c869bc1484b32
| 3,639
|
flutter_essentials
|
MIT License
|
mvvm-coroutines-clean-architecture/app/src/main/java/br/com/mobiplus/gitclient/presentation/ui/gitRepo/list/GitRepoListViewModel.kt
|
mariofelesdossantosjunior
| 249,457,538
| false
| null |
package br.com.mobiplus.gitclient.presentation.ui.gitRepo.list
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import br.com.mobiplus.gitclient.domain.base.BaseErrorData
import br.com.mobiplus.gitclient.domain.model.GitRepoModel
import br.com.mobiplus.gitclient.domain.model.GithubError
import br.com.mobiplus.gitclient.domain.usecases.GetGitRepoListUseCase
import br.com.mobiplus.gitclient.presentation.extensions.loadViewState
import br.com.mobiplus.gitclient.presentation.ui.base.ViewState
import br.com.mobiplus.gitclient.presentation.ui.gitRepo.list.model.GitRepoUIModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class GitRepoListViewModel(private val getGitRepoListUseCase: GetGitRepoListUseCase) : ViewModel() {
private val _gitRepoListState =
MutableLiveData<ViewState<List<GitRepoUIModel>, BaseErrorData<GithubError>>>()
val gitRepoListState: LiveData<ViewState<List<GitRepoUIModel>, BaseErrorData<GithubError>>>
get() = _gitRepoListState
init {
loadGitRepoList()
}
fun loadGitRepoList() {
_gitRepoListState.postValue(ViewState.Loading())
viewModelScope.launch(Dispatchers.IO) {
val params = GetGitRepoListUseCase.Params()
val resultWrapper = getGitRepoListUseCase
.runAsync(params)
.transformSuccess(
transformSuccess()
)
val viewState = loadViewState(resultWrapper)
_gitRepoListState.postValue(viewState)
}
}
private fun transformSuccess(): (List<GitRepoModel>) -> List<GitRepoUIModel> {
return { list ->
list.map { gitRepoModel ->
val gitRepoUIModel = GitRepoUIModel()
gitRepoUIModel.mapFrom(gitRepoModel)
gitRepoUIModel
}
}
}
}
| 2
| null |
1
| 1
|
f1d96c8f45814b883fab3987b8e365310e2de2dc
| 1,967
|
android-architecture-examples
|
MIT License
|
androidApp/src/main/java/me/lwn/cakom/android/domain/model/XhubEntity.kt
|
fatterx
| 477,536,944
| false
| null |
package me.lwn.cakom.android.domain.model
/**
* Created by fatterx on 2022/4/4
*/
data class XhubEntity(
val leftText: String = "Gay",
val rightText: String = "Hub"
)
| 0
|
Kotlin
|
0
| 0
|
b88b867675d18c51c6a69fcde524a9267c6af098
| 178
|
cakom-mvi
|
MIT License
|
src/main/java/com/patres/automation/action/delay/TimeContainer.kt
|
bhaweshksingh
| 280,514,738
| true
|
{"Kotlin": 351445, "CSS": 23726, "Java": 2979, "Batchfile": 22}
|
package com.patres.automation.action.delay
data class TimeContainer(
val value: Long,
val type: TimeType = TimeType.MILLISECONDS
) {
fun calculateMilliseconds() = type.toMilliseconds(value)
}
| 0
| null |
0
| 0
|
bd6403e43e231527ed99244ddf73d57aebbb83e6
| 214
|
AutomationBoot
|
Apache License 1.1
|
app/src/main/java/com/anugrahdev/litenews/menu/sources/views/SourcesFragment.kt
|
anugrahdev
| 260,928,757
| false
| null |
package com.anugrahdev.litenews.menu.sources.views
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.anugrahdev.litenews.R
import com.anugrahdev.litenews.databinding.FragmentSourcesBinding
import com.anugrahdev.litenews.menu.sources.adapters.SourceAdapter
import com.anugrahdev.litenews.menu.sources.models.SourceModel
import com.anugrahdev.litenews.menu.sources.viewmodels.SourceViewModel
import com.anugrahdev.litenews.utils.NewsViewModelFactory
import com.anugrahdev.litenews.utils.Resource
import com.anugrahdev.litenews.utils.toast
import org.kodein.di.KodeinAware
import org.kodein.di.android.x.closestKodein
import org.kodein.di.generic.instance
class SourcesFragment : Fragment(), KodeinAware {
private var _binding: FragmentSourcesBinding?=null
private val binding get() = _binding!!
override val kodein by closestKodein()
private lateinit var viewModel: SourceViewModel
private val factory: NewsViewModelFactory by instance()
private val args: SourcesFragmentArgs by navArgs()
private lateinit var sourceAdapter: SourceAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
viewModel = ViewModelProvider(this,factory).get(SourceViewModel::class.java)
_binding = FragmentSourcesBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as AppCompatActivity).supportActionBar?.show()
(activity as AppCompatActivity).supportActionBar?.title = args.category
setupRecyclerView()
viewModel.getNewsSources(country = viewModel.country, category = args.category)
viewModel.sources.observe(viewLifecycleOwner, { response ->
when(response){
is Resource.Success->{
response.data?.let {
if (it.isEmpty()){
binding.llSourceEmpty.visibility = View.VISIBLE
}else {
val allSource = SourceModel(category = args.category, country = "", description = "", id = "all", language = "", name = "All Source", url = "")
sourceAdapter.submitList(mutableListOf(allSource) + it)
}
stopLoading()
}
}
is Resource.Error->{
stopLoading()
response.message?.let {
requireContext().toast("Error occured : $it")
}
}
is Resource.Loading->{
startLoading()
}
}
})
}
private fun startLoading(){
binding.shimmerFrameLayout.startShimmer()
binding.shimmerFrameLayout.visibility = View.VISIBLE
binding.rvSources.visibility = View.GONE
}
private fun stopLoading(){
binding.shimmerFrameLayout.stopShimmer()
binding.shimmerFrameLayout.visibility = View.GONE
binding.rvSources.visibility = View.VISIBLE
}
private fun setupRecyclerView(){
sourceAdapter = SourceAdapter {
val bundle = Bundle().apply {
putString("sourceId", it.id)
putString("sourceName", it.name)
putString("category", args.category)
}
findNavController().navigate(R.id.action_sourcesFragment_to_technologyFragment, bundle)
}
binding.rvSources.apply {
adapter = sourceAdapter
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 1
|
244e7ed0f526a26462f43c74ab7beee0ad3656c1
| 4,111
|
Litenews
|
MIT License
|
common/src/commonMain/kotlin/tk/zwander/common/util/Settings.kt
|
zacharee
| 342,079,605
| false
|
{"Kotlin": 421919}
|
package tk.zwander.common.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import com.russhwolf.settings.ObservableSettings
import com.russhwolf.settings.SettingsListener
expect fun ObservableSettings(): ObservableSettings
object BifrostSettings {
object Keys {
val useNativeFileDialog = SettingsKey.Boolean("useNativeFileDialog", false, settings)
val allowLowercaseCharacters = SettingsKey.Boolean("allowLowercaseCharacters", false, settings)
val autoDeleteEncryptedFirmware = SettingsKey.Boolean("autoDeleteEncryptedFirmware", false, settings)
}
val settings = ObservableSettings()
}
sealed class SettingsKey<Type> {
abstract val key: kotlin.String
abstract val default: Type?
abstract val settings: ObservableSettings
abstract fun getValue(): Type?
abstract fun setValue(value: Type?)
protected abstract fun registerListener(callback: (Type?) -> Unit): SettingsListener
@Composable
fun collectAsMutableState(): MutableState<Type?> {
val state = remember {
mutableStateOf(getValue())
}
LaunchedEffect(state.value) {
setValue(state.value)
}
DisposableEffect(this) {
val listener = registerListener {
state.value = it
}
onDispose {
listener.deactivate()
}
}
return state
}
operator fun invoke(): Type? = getValue()
data class Boolean(
override val key: kotlin.String,
override val default: kotlin.Boolean?,
override val settings: ObservableSettings,
) : SettingsKey<kotlin.Boolean>() {
override fun getValue(): kotlin.Boolean? {
return settings.getBooleanOrNull(key) ?: default
}
override fun setValue(value: kotlin.Boolean?) {
if (value == null) {
settings.remove(key)
} else {
settings.putBoolean(key, value)
}
}
override fun registerListener(callback: (kotlin.Boolean?) -> Unit): SettingsListener {
return settings.addBooleanOrNullListener(key, callback)
}
}
data class Int(
override val key: kotlin.String,
override val default: kotlin.Int?,
override val settings: ObservableSettings,
) : SettingsKey<kotlin.Int>() {
override fun getValue(): kotlin.Int? {
return settings.getIntOrNull(key) ?: default
}
override fun setValue(value: kotlin.Int?) {
if (value == null) {
settings.remove(key)
} else {
settings.putInt(key, value)
}
}
override fun registerListener(callback: (kotlin.Int?) -> Unit): SettingsListener {
return settings.addIntOrNullListener(key, callback)
}
}
data class Long(
override val key: kotlin.String,
override val default: kotlin.Long?,
override val settings: ObservableSettings,
) : SettingsKey<kotlin.Long>() {
override fun getValue(): kotlin.Long? {
return settings.getLongOrNull(key) ?: default
}
override fun setValue(value: kotlin.Long?) {
if (value == null) {
settings.remove(key)
} else {
settings.putLong(key, value)
}
}
override fun registerListener(callback: (kotlin.Long?) -> Unit): SettingsListener {
return settings.addLongOrNullListener(key, callback)
}
}
data class String(
override val key: kotlin.String,
override val default: kotlin.String?,
override val settings: ObservableSettings,
) : SettingsKey<kotlin.String>() {
override fun getValue(): kotlin.String? {
return settings.getStringOrNull(key) ?: default
}
override fun setValue(value: kotlin.String?) {
if (value == null) {
settings.remove(key)
} else {
settings.putString(key, value)
}
}
override fun registerListener(callback: (kotlin.String?) -> Unit): SettingsListener {
return settings.addStringOrNullListener(key, callback)
}
}
data class Float(
override val key: kotlin.String,
override val default: kotlin.Float?,
override val settings: ObservableSettings,
) : SettingsKey<kotlin.Float>() {
override fun getValue(): kotlin.Float? {
return settings.getFloatOrNull(key) ?: default
}
override fun setValue(value: kotlin.Float?) {
if (value == null) {
settings.remove(key)
} else {
settings.putFloat(key, value)
}
}
override fun registerListener(callback: (kotlin.Float?) -> Unit): SettingsListener {
return settings.addFloatOrNullListener(key, callback)
}
}
data class Double(
override val key: kotlin.String,
override val default: kotlin.Double,
override val settings: ObservableSettings,
) : SettingsKey<kotlin.Double>() {
override fun getValue(): kotlin.Double {
return settings.getDouble(key, default)
}
override fun setValue(value: kotlin.Double?) {
if (value == null) {
settings.remove(key)
} else {
settings.putDouble(key, value)
}
}
override fun registerListener(callback: (kotlin.Double?) -> Unit): SettingsListener {
return settings.addDoubleOrNullListener(key, callback)
}
}
data class Complex<Type>(
override val key: kotlin.String,
override val default: Type?,
val deserializer: (kotlin.String?) -> Type?,
val serializer: (Type?) -> kotlin.String?,
override val settings: ObservableSettings,
) : SettingsKey<Type>() {
override fun getValue(): Type? {
return deserializer(settings.getStringOrNull(key))
}
override fun setValue(value: Type?) {
val serialized = serializer(value)
if (serialized == null) {
settings.remove(key)
} else {
settings.putString(key, serialized)
}
}
override fun registerListener(callback: (Type?) -> Unit): SettingsListener {
return settings.addStringOrNullListener(key) {
callback(deserializer(it))
}
}
}
}
| 5
|
Kotlin
|
84
| 690
|
a9b7bab51ceb55c6800a9aaeeef4cc50764f8ecf
| 6,846
|
SamloaderKotlin
|
MIT License
|
src/main/kotlin/me/melijn/melijnbot/commands/anime/PunchCommand.kt
|
ToxicMushroom
| 107,187,088
| false
| null |
package me.melijn.melijnbot.commands.anime
import me.melijn.melijnbot.commandutil.anime.AnimeCommandUtil
import me.melijn.melijnbot.internals.command.AbstractCommand
import me.melijn.melijnbot.internals.command.CommandCategory
import me.melijn.melijnbot.internals.command.ICommandContext
class PunchCommand : AbstractCommand("command.punch") {
init {
id = 72
name = "punch"
commandCategory = CommandCategory.ANIME
}
override suspend fun execute(context: ICommandContext) {
AnimeCommandUtil.execute(context, "punch")
}
}
| 5
|
Kotlin
|
22
| 80
|
01107bbaad0e343d770b1e4124a5a9873b1bb5bd
| 571
|
Melijn
|
MIT License
|
app/src/main/java/com/ved/net/response/AllResponse.kt
|
vedeng
| 244,312,896
| false
| null |
package com.ved.net.response
import com.bese.widget.addressselect.Region
import com.netlib.BaseResponse
data class AppBaseUrlResponse(var data: AppBaseUrlData) : BaseResponse()
data class CheckUpdateResponse(var data: CheckUpdateData) : BaseResponse()
data class RegionListResponse(var data: ArrayList<Region?>?) : BaseResponse()
| 0
|
Kotlin
|
0
| 0
|
8a92cd925b57a481a8e0422d225da2c5396bca22
| 332
|
Bese
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/com/empcontrol/backend/enums/EmployeeStatus.kt
|
rgomqui
| 838,395,439
| false
|
{"Kotlin": 24635, "Dockerfile": 254, "Java": 86}
|
package com.empcontrol.backend.enums
enum class EmployeeStatus {
ACTIVE, INACTIVE
}
| 0
|
Kotlin
|
0
| 0
|
cca4f4937849cd986be363c46882c04aa609de82
| 88
|
emp_control_backend
|
The Unlicense
|
0291.Word Pattern II.kt
|
sarvex
| 842,260,390
| false
|
{"Kotlin": 1775678, "PowerShell": 418}
|
internal class Solution {
private var vis: Set<String>? = null
private var d: Map<Char, String>? = null
private var p: String? = null
private var s: String? = null
private var m = 0
private var n = 0
fun wordPatternMatch(pattern: String?, s: String): Boolean {
vis = HashSet()
d = HashMap()
this.p = pattern
this.s = s
m = p!!.length
n = s.length
return dfs(0, 0)
}
private fun dfs(i: Int, j: Int): Boolean {
if (i == m && j == n) {
return true
}
if (i == m || j == n || m - i > n - j) {
return false
}
val c = p!![i]
for (k in j + 1..n) {
val t: String = s.substring(j, k)
if (d!!.getOrDefault(c, "").equals(t)) {
if (dfs(i + 1, k)) {
return true
}
}
if (!d!!.containsKey(c) && !vis!!.contains(t)) {
d.put(c, t)
vis.add(t)
if (dfs(i + 1, k)) {
return true
}
vis.remove(t)
d.remove(c)
}
}
return false
}
}
| 0
|
Kotlin
|
0
| 0
|
17a80985d970c8316fb694e4952692e598d700af
| 1,014
|
kotlin-leetcode
|
MIT License
|
dial-phone-core/src/commonMain/kotlin/de/mtorials/dialphone/core/RoomExtensions.kt
|
mtorials
| 272,526,016
| false
| null |
package de.mtorials.dialphone.core
import de.mtorials.dialphone.api.model.mevents.roommessage.MRoomMessage
import de.mtorials.dialphone.api.model.mevents.roomstate.MRoomName
import de.mtorials.dialphone.core.entities.MemberImpl
import de.mtorials.dialphone.core.entities.Message
import de.mtorials.dialphone.core.entities.MessageImpl
import de.mtorials.dialphone.core.entities.room.JoinedRoom
/**
* Write a message to the room
*/
suspend infix fun JoinedRoom.write(message: String) = this@write.sendTextMessage(message)
/**
* rename the room
*/
suspend infix fun JoinedRoom.rename(name: String) = setName(name)
suspend fun JoinedRoom.sendTextMessage(content: String) = sendMRoomMessageEvent(MRoomMessage.TextContent(body = content))
/**
* Send a HTML message
*/
suspend fun JoinedRoom.sendHtmlMessage(content: String, nonFormattedContent: String? = null) = this.sendMRoomMessageEvent(
content = MRoomMessage.TextContent(
body = nonFormattedContent ?: content,
format = MRoomMessage.htmlFormat,
formattedBody = content,
)
)
/**
* Send an image
*/
suspend fun JoinedRoom.sendImageWithUrl(url: String, title: String? = null) = this.sendMRoomMessageEvent(
content = MRoomMessage.ImageContent(
body = title ?: "image send with dial-phone",
url = url
)
)
/**
* Change the name of the room
*/
suspend fun JoinedRoom.setName(name: String) = this@setName.sendStateEvent(MRoomName.Content(
name = name
), "m.room.name")
| 1
|
Kotlin
|
0
| 6
|
1f78fed1af1287069fa8c6c585f868cd75e372f9
| 1,486
|
dial-phone
|
Apache License 2.0
|
core/src/commonMain/kotlin/dev/iaiabot/furuhuru/repository/ScreenshotRepository.kt
|
iaia
| 523,282,500
| false
| null |
package dev.iaiabot.furuhuru.repository
import kotlinx.coroutines.flow.Flow
interface ScreenshotRepository {
suspend fun save(fileStr: String)
suspend fun load(remove: Boolean = false): String?
suspend fun remove()
suspend fun observe(): Flow<String?>
}
| 2
|
Kotlin
|
0
| 0
|
b83cf1558a8bb906015b3cc478ab8e18e80e5a89
| 272
|
Furuhuru
|
MIT License
|
src/main/kotlin/ampersand/userservice/persistence/MassageStatus.kt
|
Team-Ampersand
| 745,334,935
| false
|
{"Kotlin": 37212, "Dockerfile": 91}
|
package ampersand.userservice.persistence
enum class MassageStatus {
CAN, CANT
}
| 4
|
Kotlin
|
0
| 2
|
1a21bd0b3f66e56503e448eb923e376599af036c
| 85
|
Dotori-V3-Member
|
Apache License 2.0
|
src/test/kotlin/uk/org/lidalia/kotlinfromgroovy/testsupport/ClassWithDefaultedArgumentsToMethods.kt
|
Lidalia-World
| 716,557,125
| false
|
{"Kotlin": 38920, "Groovy": 37085, "Dockerfile": 3166, "Shell": 209}
|
package uk.org.lidalia.kotlinfromgroovy.testsupport
class ClassWithDefaultedArgumentsToMethods {
val calls = mutableListOf<Call>()
fun functionWithOneDefaultedArgument(argument1: String = "argument1") {
calls += Call(
functionName = "functionWithOneDefaultedArgument",
arguments = linkedMapOf(
"argument1" to argument1,
),
)
}
fun functionWithTwoArgumentFirstDefaulted(argument1: String = "argument1", argument2: String) {
calls += Call(
functionName = "functionWithTwoArgumentFirstDefaulted",
arguments = linkedMapOf(
"argument1" to argument1,
"argument2" to argument2,
),
)
}
fun functionWithTwoArgumentsSecondDefaulted(argument1: String, argument2: String = "argument2") {
calls += Call(
functionName = "functionWithTwoArgumentsSecondDefaulted",
arguments = linkedMapOf(
"argument1" to argument1,
"argument2" to argument2,
),
)
}
fun functionWithTwoArgumentsBothDefaulted(
argument1: String = "argument1",
argument2: String = "argument2",
) {
calls += Call(
functionName = "functionWithTwoArgumentsBothDefaulted",
arguments = linkedMapOf(
"argument1" to argument1,
"argument2" to argument2,
),
)
}
fun functionWithOneNullableArgumentDefaultedToNotNull(argument1: String? = "argument1") {
calls += Call(
functionName = "functionWithOneNullableArgumentDefaultedToNotNull",
arguments = linkedMapOf(
"argument1" to argument1,
),
)
}
fun functionWithOneNullableArgumentDefaultedToNull(argument1: String? = null) {
calls += Call(
functionName = "functionWithOneNullableArgumentDefaultedToNull",
arguments = linkedMapOf(
"argument1" to argument1,
),
)
}
}
| 1
|
Kotlin
|
0
| 0
|
b694959a14c0a25140b616293045acc309f2caef
| 1,824
|
kotlin-from-groovy
|
Apache License 2.0
|
gaia/src/main/kotlin/fyi/pauli/ichor/gaia/networking/packet/outgoing/configuration/RegistryData.kt
|
ichor-dev
| 676,285,724
| false
|
{"Kotlin": 78133}
|
package fyi.pauli.ichor.gaia.networking.packet.outgoing.configuration
import fyi.pauli.ichor.gaia.extensions.bytes.buffer
import fyi.pauli.ichor.gaia.extensions.bytes.buffer.compoundTag
import fyi.pauli.ichor.gaia.models.nbt.impl.CompoundTag
import fyi.pauli.ichor.gaia.networking.packet.State
import fyi.pauli.ichor.gaia.networking.packet.outgoing.OutgoingPacket
import java.nio.ByteBuffer
/**
* Represents certain registries that are sent from the server and are applied on the client.
*
* @param registryCodec CompoundTag, which contains the registries mentioned here:
* @see "https://wiki.vg/Pre-release_protocol#Registry_Data"
*/
data class RegistryData(var registryCodec: CompoundTag) : OutgoingPacket() {
override val id: Int
get() = 0x05
override val state: State
get() = State.CONFIGURATION
override fun serialize(): ByteBuffer {
return buffer {
compoundTag(registryCodec)
}
}
}
| 5
|
Kotlin
|
0
| 0
|
7db6bad2aa9c963ae7410a685857c1d634c27344
| 910
|
ichor
|
Apache License 2.0
|
gaia/src/main/kotlin/fyi/pauli/ichor/gaia/networking/packet/outgoing/configuration/RegistryData.kt
|
ichor-dev
| 676,285,724
| false
|
{"Kotlin": 78133}
|
package fyi.pauli.ichor.gaia.networking.packet.outgoing.configuration
import fyi.pauli.ichor.gaia.extensions.bytes.buffer
import fyi.pauli.ichor.gaia.extensions.bytes.buffer.compoundTag
import fyi.pauli.ichor.gaia.models.nbt.impl.CompoundTag
import fyi.pauli.ichor.gaia.networking.packet.State
import fyi.pauli.ichor.gaia.networking.packet.outgoing.OutgoingPacket
import java.nio.ByteBuffer
/**
* Represents certain registries that are sent from the server and are applied on the client.
*
* @param registryCodec CompoundTag, which contains the registries mentioned here:
* @see "https://wiki.vg/Pre-release_protocol#Registry_Data"
*/
data class RegistryData(var registryCodec: CompoundTag) : OutgoingPacket() {
override val id: Int
get() = 0x05
override val state: State
get() = State.CONFIGURATION
override fun serialize(): ByteBuffer {
return buffer {
compoundTag(registryCodec)
}
}
}
| 5
|
Kotlin
|
0
| 0
|
7db6bad2aa9c963ae7410a685857c1d634c27344
| 910
|
ichor
|
Apache License 2.0
|
src/main/kotlin/org/lj92458/plugins/services/MyProjectService.kt
|
lj92458
| 490,599,655
| false
| null |
package org.lj92458.plugins.services
import com.intellij.openapi.project.Project
import org.lj92458.plugins.MyBundle
class MyProjectService(project: Project) {
init {
println(MyBundle.message("projectService", project.name))
}
}
| 0
|
Kotlin
|
1
| 0
|
c4797a7b11b0f1dcb65df4a4ce1bb617f9a75df5
| 248
|
reformatMine
|
Apache License 2.0
|
sample/src/main/java/nu/dropud/bundr/app/InitActivity.kt
|
Bundedaterne
| 129,445,865
| false
| null |
package nu.dropud.bundr.app
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.messaging.FirebaseMessaging
import kotlinx.android.synthetic.main.activity_init.*
import nu.dropud.bundr.R
import nu.dropud.bundr.common.extension.ChildEventAdded
import nu.dropud.bundr.common.extension.ChildEventRemoved
import nu.dropud.bundr.common.extension.areAllPermissionsGranted
import nu.dropud.bundr.common.extension.rxChildEvents
import nu.dropud.bundr.feature.base.BaseActivity
import nu.dropud.bundr.feature.main.MainActivity
import nu.dropud.bundr.feature.main.video.VideoFragment
class InitActivity : AppCompatActivity() {
companion object {
private val NECESSARY_PERMISSIONS = arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)
private const val CHECK_PERMISSIONS_AND_CONNECT_REQUEST_CODE = 1
}
var availableChugger: Long = 0;
var fireReference = FirebaseDatabase.getInstance().getReference("online_devices/")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_init)
FirebaseMessaging.getInstance().subscribeToTopic("hot_singles_in_your_area")
val button = findViewById<Button>(R.id.chug_button)
button.setOnClickListener {
startActivity(Intent(this@InitActivity, MainActivity::class.java))
}
val context = applicationContext
if (!(context.areAllPermissionsGranted(*NECESSARY_PERMISSIONS))) {
requestPermissions(arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO), CHECK_PERMISSIONS_AND_CONNECT_REQUEST_CODE)
}
fireReference.addValueEventListener(object : ValueEventListener {
override fun onCancelled(databaseError: DatabaseError?) {
}
override fun onDataChange(dataSnapshot: DataSnapshot) {
val childrenCount = dataSnapshot.childrenCount
if (childrenCount == 1L) {
waitingText.text = "" + dataSnapshot.childrenCount
staticText.text = " chugger is waiting in your area"
} else {
waitingText.text = "" + dataSnapshot.childrenCount
staticText.text = " chuggers are waiting in your area"
}
}
})
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) = when (requestCode) {
CHECK_PERMISSIONS_AND_CONNECT_REQUEST_CODE -> {
val grantResult = grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }
if (!grantResult) {
error("Memes")
} else {
}
}
else -> {
error("Unknown permission request code $requestCode")
}
}
}
| 2
|
Kotlin
|
2
| 0
|
bad0ae3b772e56c1571bda1feb5836d067be15e2
| 3,287
|
Bundr
|
Apache License 2.0
|
kotlinui/src/main/java/kotlinx/kotlinui/Views/Spacer.kt
|
bclnet
| 327,138,530
| false
| null |
package kotlinx.kotlinui
import android.content.Context
import android.widget.Space
import android.view.View as XView
import kotlinx.ptype.PType
class Spacer : View, ViewBuildable {
override val body: Never
get() = error("Never")
//: ViewBuildable
override fun buildView(context: Context?): XView =
Space(context)
companion object {
//: Register
fun register() {
PType.register<Spacer>()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8ea61bd04ce4a0b3dd440c36d4b82a5ccf5ec3f2
| 470
|
KotlinUI
|
MIT License
|
app/src/main/java/com/bereguliak/arscheduler/di/module/loading/LoadingModule.kt
|
YuriyBereguliak
| 177,011,797
| false
| null |
package com.bereguliak.arscheduler.di.module.loading
import com.bereguliak.arscheduler.ui.fragments.loading.view.LoadingFragment
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
abstract class LoadingModule {
@ContributesAndroidInjector(modules = [LoadingContractModule::class])
@LoadingScope
internal abstract fun contributeLoadinfFragment(): LoadingFragment
}
| 0
|
Kotlin
|
0
| 2
|
562dca9b6595baab35f395c5dac386c4720cfce8
| 404
|
ArScheduler
|
MIT License
|
domain/src/main/java/com/nowiwr01p/domain/auth/verification/usecase/SetVerificationCompletedUseCase.kt
|
nowiwr01w
| 584,138,480
| false
| null |
package com.nowiwr01p.domain.auth.verification.usecase
import com.nowiwr01p.domain.UseCase
import com.nowiwr01p.domain.auth.verification.repository.VerificationLocalRepository
import com.nowiwr01p.domain.auth.verification.repository.VerificationRemoteRepository
class SetVerificationCompletedUseCase(
private val localRepository: VerificationLocalRepository,
private val remoteRepository: VerificationRemoteRepository
): UseCase<Unit, Unit> {
override suspend fun execute(input: Unit) {
remoteRepository.setVerificationCompleted()
localRepository.setVerificationCompleted()
}
}
| 0
|
Kotlin
|
1
| 1
|
5595a307cbb8ca5b9979aa76894f3498bdac34f3
| 612
|
Meetings
|
MIT License
|
android/app/src/main/kotlin/com/example/flutter_github_actions_advanced/MainActivity.kt
|
daniil-shumko
| 461,507,858
| false
|
{"C++": 16842, "Dart": 12870, "CMake": 8271, "HTML": 3974, "C": 734, "Swift": 404, "Shell": 211, "Kotlin": 148, "Objective-C": 38}
|
package com.example.flutter_github_actions_advanced
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0
|
C++
|
1
| 0
|
d21f65ba7604f12e305fbd144756b5108eed21cc
| 148
|
flutter_github_actions_advanced
|
MIT License
|
app/src/main/java/com/jfma75/composeform/components/DatePickerView.kt
|
JuanFcoMiranda
| 430,703,059
| false
|
{"Kotlin": 49019}
|
package com.jfma75.composeform.components
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import com.google.android.material.datepicker.MaterialDatePicker
import com.jfma75.composeform.screens.InputWrapper
import java.lang.Exception
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalDateTime.ofInstant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.*
@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun DatePickerView(
datePicked : InputWrapper,
onValueChange : (date : Long) -> Unit,
) {
val activity = LocalContext.current as? AppCompatActivity
val fieldValue = remember {
mutableStateOf(TextFieldValue(datePicked.value, TextRange(datePicked.value.length)))
}
@RequiresApi(Build.VERSION_CODES.O)
fun showDatePicker(
activity: AppCompatActivity?
) {
val calendar: Calendar = Calendar.getInstance()
calendar.apply {
val selectedDate = dateFormatter(fieldValue.value.text)
set(Calendar.YEAR, selectedDate.year)
set(Calendar.MONTH, selectedDate.monthValue-1)
set(Calendar.DAY_OF_MONTH, selectedDate.dayOfMonth)
}
MaterialDatePicker.Builder.datePicker()
.setSelection(calendar.timeInMillis).build().apply {
activity?.supportFragmentManager?.let { supportFragmentManager ->
show(supportFragmentManager, "Tag")
addOnPositiveButtonClickListener {
fieldValue.value = TextFieldValue(text = dateFormatter(it))
onValueChange(it)
}
}
}
}
Column {
Box(
modifier = Modifier
.padding(16.dp)
.border(
1.dp, if (datePicked.errorId != null) {
MaterialTheme.colors.error
} else {
MaterialTheme.colors.surface
}
)
.clickable {
showDatePicker(activity)
}
) {
Row(
modifier = Modifier
.padding(16.dp)
) {
Text(
text = fieldValue.value.text,
color = MaterialTheme.colors.surface,
modifier = Modifier
.padding(horizontal = 32.dp)
)
Icon(
imageVector = Icons.Default.DateRange,
contentDescription = null,
modifier = Modifier
.size(20.dp),
tint = MaterialTheme.colors.surface
)
}
}
if (datePicked.errorId != null) {
Text(
text = stringResource(datePicked.errorId),
color = MaterialTheme.colors.surface,
style = MaterialTheme.typography.caption,
modifier = Modifier.padding(horizontal = 16.dp)
)
}
}
}
@RequiresApi(Build.VERSION_CODES.O)
fun dateFormatter(localDate: LocalDate): String {
localDate.let {
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.ENGLISH)
return formatter.format(localDate)
}
}
@RequiresApi(Build.VERSION_CODES.O)
fun dateFormatter(stringDate: String): LocalDate {
if(stringDate.isBlank()) return LocalDate.now()
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.ENGLISH)
return LocalDate.parse(stringDate, formatter)
}
@RequiresApi(Build.VERSION_CODES.O)
fun dateFormatter(longDate: Long): String {
val date: LocalDateTime = ofInstant(Instant.ofEpochMilli(longDate), ZoneId.systemDefault())
return dateFormatter(date.toLocalDate())
}
@RequiresApi(Build.VERSION_CODES.O)
fun isValidDateTime(stringDate: String) : Boolean {
if(stringDate.isBlank()) return false
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.ENGLISH)
return try {
val date = LocalDate.parse(stringDate, formatter)
date != null
} catch (ex: Exception) {
false
}
}
| 0
|
Kotlin
|
0
| 0
|
f9611efb7c9d55276f3a93a95d603352fe91702f
| 5,050
|
ComposeForm
|
Apache License 2.0
|
libraries/cache/src/main/java/com/ezike/tobenna/starwarssearch/cache/model/CharacterCacheModel.kt
|
Ezike
| 294,171,829
| false
|
{"Kotlin": 190343, "Shell": 657}
|
package com.ezike.tobenna.starwarssearch.cache.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "SEARCH_HISTORY")
data class CharacterCacheModel(
val name: String,
val birthYear: String,
val height: String,
@PrimaryKey
val url: String
) {
var lastUpdated: Long = 0L
}
| 0
|
Kotlin
|
30
| 198
|
f091dc9b19b0a4b5b38d27c5331a4d70388f970d
| 331
|
StarWarsSearch-MVI
|
Apache License 2.0
|
appModules/appFeatures/impl/src/jsMain/kotlin/dev/reprator/appFeatures/impl/performance/PerformanceComponent.kt
|
TheReprator
| 781,077,991
| false
|
{"Kotlin": 399028, "Swift": 5325, "HTML": 357, "JavaScript": 92}
|
package dev.reprator.appFeatures.impl.performance
import dev.reprator.appFeatures.api.performance.Tracer
import dev.reprator.core.inject.ApplicationScope
import me.tatarka.inject.annotations.Provides
actual interface PerformanceComponent {
@ApplicationScope
@Provides
fun provideTracer(tracer: JsTracer): Tracer = tracer
}
| 1
|
Kotlin
|
0
| 0
|
1468ecc36c791f643973d0fadae9f6154d726b84
| 338
|
ExpenseManagment
|
Apache License 2.0
|
auth/src/main/kotlin/gov/cdc/prime/reportstream/auth/service/ProxyURIStrategy.kt
|
CDCgov
| 304,423,150
| false
|
{"Kotlin": 5417139, "CSS": 3370586, "TypeScript": 1881870, "Java": 1326278, "HCL": 282334, "MDX": 140844, "PLpgSQL": 77695, "Shell": 69067, "HTML": 68387, "SCSS": 66843, "Smarty": 51325, "RouterOS Script": 17080, "Python": 13724, "Makefile": 8166, "JavaScript": 8003, "Dockerfile": 3127}
|
package gov.cdc.prime.reportstream.auth.service
import gov.cdc.prime.reportstream.auth.config.ApplicationConfig
import org.springframework.context.annotation.Profile
import org.springframework.stereotype.Component
import java.net.URI
/**
* Implementations are ways to decide the ultimate destination of an incoming request
*/
interface ProxyURIStrategy {
fun getTargetURI(incomingUri: URI): URI
}
/**
* This implementation decides via the path prefix. Currently used locally for when all services are
* running on different ports of localhost.
*
* Configured under proxyConfig.pathMappings
*
* http://localhost:9000/submissions/health -> http://localhost:8880/health
*/
@Component
@Profile("local")
class PathPrefixProxyURIStrategy(
private val applicationConfig: ApplicationConfig,
) : ProxyURIStrategy {
override fun getTargetURI(incomingUri: URI): URI {
val proxyPathMappings = applicationConfig.proxyConfig.pathMappings
val maybePathMapping = proxyPathMappings.find { incomingUri.path.startsWith(it.pathPrefix) }
return if (maybePathMapping != null) {
val baseUri = URI(maybePathMapping.baseUrl)
val path = incomingUri.path.removePrefix(maybePathMapping.pathPrefix)
URI(
baseUri.scheme,
baseUri.userInfo,
baseUri.host,
baseUri.port,
path,
incomingUri.query,
incomingUri.fragment
)
} else {
throw IllegalStateException("no configured proxy target in path mappings for path=${incomingUri.path}")
}
}
}
@Component
@Profile("deployed")
class HostProxyPathURIStrategy : ProxyURIStrategy {
override fun getTargetURI(incomingUri: URI): URI {
TODO("Not yet implemented")
}
}
| 1,458
|
Kotlin
|
39
| 71
|
81f5d3c284982ccdb7f24f36fc69fdd8fac2a919
| 1,827
|
prime-reportstream
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/io/korostenskyi/chestnut/presentation/screen/home/HomeViewModel.kt
|
korostenskyi
| 401,812,198
| false
| null |
package io.korostenskyi.chestnut.presentation.screen.home
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import dagger.hilt.android.lifecycle.HiltViewModel
import io.korostenskyi.chestnut.domain.interactor.MovieInteractor
import io.korostenskyi.chestnut.presentation.navigation.NavigationFlow
import io.korostenskyi.chestnut.presentation.navigation.Router
import io.korostenskyi.chestnut.presentation.utils.DEFAULT_PAGE_SIZE
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val movieInteractor: MovieInteractor,
private val navigationFlow: NavigationFlow
) : ViewModel() {
private val _isRefreshing = MutableStateFlow(false)
val isRefreshing = _isRefreshing.asStateFlow()
val moviesStateFlow = Pager(PagingConfig(pageSize = DEFAULT_PAGE_SIZE)) {
MoviePagingSource(movieInteractor, _isRefreshing)
}.flow.stateIn(viewModelScope, SharingStarted.Lazily, PagingData.empty()).cachedIn(viewModelScope)
fun openDetailsScreen(movieId: Int) {
viewModelScope.launch {
navigationFlow.navigate {
fromHomeToDetails(movieId)
}
}
}
fun openSettingsScreen() {
viewModelScope.launch {
navigationFlow.navigate(Router::fromHomeToSettings)
}
}
fun openFavoritesScreen() {
viewModelScope.launch {
navigationFlow.navigate(Router::fromHomeToFavorites)
}
}
}
| 3
|
Kotlin
|
0
| 0
|
5c7e285cb495e83bf9d9d29817fd0eb76f601a35
| 1,821
|
Chestnut-Compose
|
MIT License
|
core/src/river/exertion/kcop/assets/NarrativeAsset.kt
|
exertionriver
| 589,248,613
| false
| null |
package river.exertion.kcop.assets
import river.exertion.kcop.narrative.structure.Narrative
class NarrativeAsset(var narrative : Narrative? = null) {
var status : String? = null
var statusDetail : String? = null
}
| 0
|
Kotlin
|
0
| 0
|
011e04852134376b1888aa115885d535d72d8c8c
| 223
|
kcop
|
MIT License
|
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/NestedBlockDepthSpec.kt
|
lummax
| 92,387,195
| true
|
{"Kotlin": 203718, "Java": 153}
|
package io.gitlab.arturbosch.detekt.rules
import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell
import io.gitlab.arturbosch.detekt.rules.complexity.NestedBlockDepth
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.subject.SubjectSpek
import org.jetbrains.spek.subject.itBehavesLike
import kotlin.test.assertEquals
/**
* @author Artur Bosch
*/
class NestedBlockDepthSpec : SubjectSpek<NestedBlockDepth>({
subject { NestedBlockDepth(threshold = 3) }
itBehavesLike(CommonSpec())
describe("nested classes are also considered") {
it("should detect only the nested large class") {
val root = load(Case.NestedClasses)
subject.visit(root)
assertEquals(subject.findings.size, 1)
assertEquals((subject.findings[0] as ThresholdedCodeSmell).value, 5)
}
}
})
| 0
|
Kotlin
|
0
| 0
|
391c9d0cda1660b4869448eb07b8a5c74dc90383
| 834
|
detekt
|
Apache License 2.0
|
app/src/main/java/com/lnight/externalstorageandroid15/MainViewModel.kt
|
EvgenyPlaksin
| 844,281,754
| false
|
{"Kotlin": 13737}
|
package com.lnight.externalstorageandroid15
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainViewModel(
private val mediaReader: MediaReader
): ViewModel() {
var files by mutableStateOf(listOf<MediaFile>())
private set
init {
viewModelScope.launch(Dispatchers.IO) {
files = mediaReader.getAllMediaFiles()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
796ab028654cbd2a8747e4d5b5e75d77358450be
| 604
|
ExternalStorageAndroid15
|
MIT License
|
src/main/kotlin/no/nav/omsorgspenger/KtorHttp.kt
|
navikt
| 314,496,410
| false
| null |
package no.nav.omsorgspenger
import io.ktor.client.call.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import no.nav.helse.dusseldorf.ktor.client.SimpleHttpClient
import no.nav.helse.dusseldorf.ktor.client.SimpleHttpClient.httpDelete
import no.nav.helse.dusseldorf.ktor.client.SimpleHttpClient.httpGet
import no.nav.helse.dusseldorf.ktor.client.SimpleHttpClient.httpOptions
import no.nav.helse.dusseldorf.ktor.client.SimpleHttpClient.httpPatch
import no.nav.helse.dusseldorf.ktor.client.SimpleHttpClient.httpPost
import no.nav.helse.dusseldorf.ktor.client.SimpleHttpClient.httpPut
import org.slf4j.LoggerFactory
internal object KtorHttp {
private val config = SimpleHttpClient.Config(engine = OkHttp)
private val logger = LoggerFactory.getLogger(KtorHttp::class.java)
internal suspend fun ApplicationCall.forwardPatch(toUrl: String, extraHeaders: Map<String, Any?> = emptyMap()) {
kotlin.runCatching { receiveNullable<ByteArray>() }.getOrNull().also { body ->
forward {
toUrl.httpPatch(config) { builder ->
populateBuilder(
builder = builder,
extraHeaders = extraHeaders,
body = body
)
}
}
}
}
internal suspend fun ApplicationCall.forwardPost(toUrl: String, extraHeaders: Map<String, Any?> = emptyMap()) {
kotlin.runCatching { receiveNullable<ByteArray>() }.getOrNull().also { body ->
forward {
toUrl.httpPost(config) { builder ->
populateBuilder(
builder = builder,
extraHeaders = extraHeaders,
body = body
)
}
}
}
}
internal suspend fun ApplicationCall.forwardPut(toUrl: String, extraHeaders: Map<String, Any?> = emptyMap()) {
kotlin.runCatching { receiveNullable<ByteArray>() }.getOrNull().also { body ->
forward {
toUrl.httpPut(config) { builder ->
populateBuilder(
builder = builder,
extraHeaders = extraHeaders,
body = body
)
}
}
}
}
internal suspend fun ApplicationCall.forwardDelete(toUrl: String, extraHeaders: Map<String, Any?> = emptyMap()) {
kotlin.runCatching { receiveNullable<ByteArray>() }.getOrNull().also { body ->
forward {
toUrl.httpDelete(config) { builder ->
populateBuilder(
builder = builder,
extraHeaders = extraHeaders,
body = body
)
}
}
}
}
internal suspend fun ApplicationCall.forwardOptions(toUrl: String, extraHeaders: Map<String, Any?> = emptyMap()) {
forward {
toUrl.httpOptions(config) { builder ->
populateBuilder(
builder = builder,
extraHeaders = extraHeaders,
body = null
)
}
}
}
private suspend fun ApplicationCall.doGet(toUrl: String, extraHeaders: Map<String, Any?> = emptyMap()) =
toUrl.httpGet(config) { builder ->
populateBuilder(
builder = builder,
extraHeaders = extraHeaders,
body = null
)
}
internal suspend fun ApplicationCall.forwardGet(toUrl: String, extraHeaders: Map<String, Any?> = emptyMap()) {
forward { doGet(toUrl, extraHeaders) }
}
private suspend fun ApplicationCall.forward(
respondOnError: Boolean = true,
block: suspend () -> Pair<HttpRequestData, Result<HttpResponse>>
): Boolean {
val (httpRequestData, httpResponseResult) = block()
return httpResponseResult.fold(
onSuccess = {
val doRespond = when (respondOnError) {
true -> true
false -> it.status.isSuccess()
}
val responseBody = it.body<ByteArray>()
if (!doRespond || it.status.value >= 500) {
val queryNames = httpRequestData.url.parameters.names()
val urlUtenQueryParameters = "${httpRequestData.url}".substringBefore("?")
logger.error(
"Uventet response gjennom proxy: Method=[${httpRequestData.method.value}], Url=[$urlUtenQueryParameters], QueryNames=$queryNames, Accept=[${httpRequestData.headers[HttpHeaders.Accept]}], HttpStatusCode=[${it.status.value}], Response=[${
String(
responseBody
)
}]"
)
}
if (doRespond) {
it.headers.forEach { key, values ->
if (!HttpHeaders.isUnsafe(key)) {
values.forEach { value ->
response.header(key, value)
}
}
}
respondBytes(
contentType = it.contentType(),
status = it.status,
bytes = responseBody
)
}
doRespond
},
onFailure = {
logger.error(
"Feil ved proxy av request: Method=[${httpRequestData.method.value}], Url=[${httpRequestData.url}]",
it
)
if (respondOnError) {
respondText(
status = HttpStatusCode.BadGateway,
text = "Unable to proxy request."
)
}
respondOnError
}
)
}
private fun ApplicationCall.populateBuilder(
builder: HttpRequestBuilder,
body: ByteArray?,
extraHeaders: Map<String, Any?>
) {
// Body
body?.also {
builder.setBody(
ByteArrayContent(
bytes = it,
contentType = request.contentType()
)
)
}
// Timeout
builder.timeout {
connectTimeoutMillis = 20_000
requestTimeoutMillis = 20_000
socketTimeoutMillis = 20_000
}
// Headers
val extra = extraHeaders.filterValues { it != null }.mapValues { it.value!! }
val remove = extraHeaders.filterValues { it == null }
request.headers.forEach { key, values ->
if (key !in remove && !HttpHeaders.isUnsafe(key)) {
values.forEach { value -> builder.header(key, value) }
}
}
extra.forEach { (key, value) ->
builder.header(key, value)
}
}
}
| 7
|
Kotlin
|
0
| 0
|
87d0cfc14760a41ee8396d762ee058dcf993555b
| 7,349
|
omsorgspenger-proxy
|
MIT License
|
app/src/main/java/com/sevenzerotwo/takeit/pages/funktions.kt
|
SwastikGorai
| 590,920,284
| false
| null |
package com.sevenzerotwo.takeit.pages
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.TextSelectionColors
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
class funktions {
@Composable
fun logobutton(pid: Painter, contentDesc: String) {
Button(
onClick = { },
border = BorderStroke(1.dp, Color.Gray),
modifier = Modifier
.height(60.dp)
.width(90.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color.White),
shape = RoundedCornerShape(20)
) {
Image(
painter = pid,
contentDescription = contentDesc
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun templatee(textboxValue: String, text: String) {
var vall = textboxValue
Box(
Modifier
.fillMaxWidth()
)
{
Column {
Text(text = text)
TextField(
value = vall,
onValueChange = { vall = it },
Modifier
.fillMaxWidth()
.padding(top = 4.dp),
shape = RoundedCornerShape(16.dp),
colors = TextFieldDefaults.textFieldColors(
disabledLabelColor = Color.White,
selectionColors = TextSelectionColors(
handleColor = Color.Black,
backgroundColor = Color.Gray
),
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent
)
)
}
}
}
//Sign In Button
@Composable
fun signinbutton(button_text: String) {
Button(
onClick = { },
modifier = Modifier
.fillMaxWidth()
.height(60.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color.Black),
shape = RoundedCornerShape(24)
)
{
Text(
text = button_text,
color = Color.White,
textAlign = TextAlign.Center,
lineHeight = 125.sp,
style = TextStyle(
fontSize = 18.sp
)
)
}
}
//Already have an account, Sign In
@Composable
fun accountPresent(siz: TextUnit) {
Row(
Modifier.fillMaxSize(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Text(
text = "Already have an account? ", fontSize = siz,
color = Color.Black,
)
Text(text = "Sign In",
fontSize = siz,
color = Color.Black,
fontWeight = FontWeight.Bold,
textDecoration = TextDecoration.Underline,
modifier = Modifier.clickable { })
}
}
}
| 0
|
Kotlin
|
0
| 6
|
faa75644d2614bafcb22344d5196540777b37b6a
| 3,973
|
Take_It
|
MIT License
|
compiler/testData/diagnostics/tests/ReturnInFunctionWithoutBody.fir.kt
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
fun foo1(): () -> String = <!RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY!>return<!> { "some long expression "}
fun foo2(): () -> String = <!RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY!>return<!UNRESOLVED_LABEL!>@label<!><!> { "some long expression "}
fun foo3(): () -> String = <!RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY!>return<!><!SYNTAX!>@<!> { "some long expression "}
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 364
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/com/github/parkee/messenger/model/response/ResponsePayload.kt
|
parkee
| 58,060,512
| false
| null |
package com.github.parkee.messenger.model.response
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
data class ResponsePayload(
@JsonProperty("url") val url: String
)
| 0
|
Kotlin
|
3
| 5
|
ddde00d68f36f26978426cfe5ebb1a6cecb310af
| 285
|
messenger-send-api-client
|
MIT License
|
deprecated/template-xml/app/src/main/java/co/nimblehq/template/xml/ui/ErrorMapping.kt
|
nimblehq
| 101,353,301
| false
|
{"Kotlin": 387666, "Ruby": 5344, "XSLT": 1824}
|
package co.nimblehq.template.xml.ui
import android.content.Context
import co.nimblehq.template.xml.R
import co.nimblehq.template.xml.domain.exceptions.ApiException
fun Throwable.userReadableMessage(context: Context): String {
return when (this) {
is ApiException -> error?.message
else -> message
} ?: context.getString(R.string.error_generic)
}
| 31
|
Kotlin
|
23
| 94
|
f07941499a70b6144f4280c233edba542ab3e516
| 372
|
android-templates
|
MIT License
|
arrangement/src/main/java/com/fang/arrangement/ui/shared/component/DropdownSelector.kt
|
7ANG2C
| 794,384,998
| false
|
{"Kotlin": 435901}
|
package com.fang.arrangement.ui.shared.component
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.HorizontalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.PopupProperties
import com.fang.arrangement.ui.shared.ext.clickRipple
import com.fang.cosmos.foundation.Action
import com.fang.cosmos.foundation.Invoke
import com.fang.cosmos.foundation.ui.dsl.MaterialShape
import com.fang.cosmos.foundation.ui.ext.crop
@Composable
internal fun <T> DropdownSelector(
items: Collection<T>,
selected: T?,
expandedState: MutableState<Boolean>,
modifier: Modifier = Modifier,
onDismissRequest: Invoke = {},
offset: DpOffset = DpOffset(0.dp, 6.dp),
scrollState: ScrollState = rememberScrollState(),
properties: PopupProperties = PopupProperties(focusable = true),
shape: Shape = MaterialShape.small,
onSelected: Action<T>,
content: @Composable ColumnScope.(T) -> Unit,
) = DropdownMenu(
expanded = expandedState.value,
onDismissRequest = {
onDismissRequest()
expandedState.value = false
},
modifier =
modifier
.crop(vertical = 8.dp)
.clip(MaterialShape.small),
offset = offset,
scrollState = scrollState,
properties = properties,
shape = shape,
) {
items.forEachIndexed { i, item ->
Column(
modifier =
Modifier
.fillMaxWidth()
.clickRipple {
if (selected != item) onSelected(item)
expandedState.value = false
},
) {
content(item)
}
if (i != items.size - 1) {
HorizontalDivider(
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7df9040856234c63b597a24e51feda55a19f4900
| 2,442
|
FANG
|
Apache License 2.0
|
android-compose/ComposeStore/app/src/main/java/io/github/mrgsrylm/composeshop/features/login/LoginViewModel.kt
|
mrgsrylm
| 740,344,950
| false
|
{"Kotlin": 604059}
|
package io.github.mrgsrylm.composeshop.features.login
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.mrgsrylm.composeshop.common.Resource
import io.github.mrgsrylm.composeshop.domain.model.user.User
import io.github.mrgsrylm.composeshop.domain.use_cases.local.GetSavedUserUseCase
import io.github.mrgsrylm.composeshop.domain.use_cases.local.SaveUserUseCase
import io.github.mrgsrylm.composeshop.domain.use_cases.remote.login.LoginUseCase
import io.github.mrgsrylm.composeshop.features.login.core.LoginEvent
import io.github.mrgsrylm.composeshop.features.login.core.LoginState
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(
private val loginUseCase: LoginUseCase,
private val saveUserUseCase: SaveUserUseCase,
private val getSavedUserUseCase: GetSavedUserUseCase
) : ViewModel() {
var loginState by mutableStateOf(LoginState())
private set
init {
getSavedUser()
}
fun onEvent(event: LoginEvent) {
when (event) {
is LoginEvent.Login -> login(event.username, event.password)
is LoginEvent.SaveUser -> saveUser(event.user)
}
}
private fun login(username: String, password: String) {
viewModelScope.launch {
loginUseCase(username, password).collect { result ->
when (result) {
is Resource.Loading -> {
loginState = loginState.copy(
isLoading = true,
loggedUser = null,
savedUser = null,
error = null
)
}
is Resource.Success -> {
result.data?.let { user ->
loginState = loginState.copy(
isLoading = false,
loggedUser = user,
savedUser = null,
error = null
)
}
}
is Resource.Error -> {
result.message?.let { errorMessage ->
loginState = loginState.copy(
isLoading = false,
error = errorMessage,
loggedUser = null,
savedUser = null
)
}
}
}
}
}
}
private fun saveUser(user: User) {
viewModelScope.launch {
saveUserUseCase(user).collect { result ->
when (result) {
is Resource.Loading -> {
loginState = loginState.copy(
isLoading = true,
loggedUser = null,
savedUser = null,
error = null
)
}
is Resource.Success -> {
result.data?.let { user ->
loginState = loginState.copy(
isLoading = false,
savedUser = user,
loggedUser = null,
error = null
)
}
}
is Resource.Error -> {
result.message?.let { errorMessage ->
loginState = loginState.copy(
isLoading = false,
error = errorMessage,
savedUser = null,
loggedUser = null
)
}
}
}
}
}
}
private fun getSavedUser() {
viewModelScope.launch {
getSavedUserUseCase().collect { result ->
when (result) {
is Resource.Loading -> {
loginState = loginState.copy(
isLoading = true,
loggedUser = null,
savedUser = null,
error = null
)
}
is Resource.Success -> {
result.data?.let { user ->
loginState = loginState.copy(
isLoading = false,
savedUser = user,
loggedUser = null,
error = null
)
}
}
is Resource.Error -> {
result.message?.let { errorMessage ->
loginState = loginState.copy(
isLoading = false,
error = errorMessage,
savedUser = null,
loggedUser = null
)
}
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
719dca756600fbdd75c228cd0998ddceb0ac63bc
| 5,669
|
kotlin-sandbox
|
MIT License
|
app/src/main/java/ru/rznnike/eyehealthmanager/app/ui/item/TestTypeSmallItem.kt
|
RznNike
| 207,148,781
| false
|
{"Kotlin": 879326}
|
package ru.rznnike.eyehealthmanager.app.ui.item
import android.view.LayoutInflater
import android.view.ViewGroup
import ru.rznnike.eyehealthmanager.R
import ru.rznnike.eyehealthmanager.app.global.BaseBindingItem
import ru.rznnike.eyehealthmanager.databinding.ItemTestTypeSmallBinding
import ru.rznnike.eyehealthmanager.domain.model.enums.TestType
class TestTypeSmallItem(
val testType: TestType
) : BaseBindingItem<ItemTestTypeSmallBinding>() {
override var identifier = testType.id.toLong()
override val type: Int = R.id.testTypeSmallItem
override fun createBinding(inflater: LayoutInflater, parent: ViewGroup?) =
ItemTestTypeSmallBinding.inflate(inflater, parent, false)
override fun ItemTestTypeSmallBinding.bindView() {
imageViewIcon.setImageResource(testType.iconResId)
imageViewIcon.setBackgroundResource(
if (isSelected) R.drawable.bg_rounded_8_outline_accent else R.color.colorTransparent
)
}
}
| 0
|
Kotlin
|
0
| 4
|
70c802c797d8d893e9d19952a4ea4269ed33e544
| 975
|
EyeHealthManager
|
MIT License
|
octicons/src/commonMain/kotlin/compose/icons/octicons/BellSlash16.kt
|
DevSrSouza
| 311,134,756
| false
|
{"Kotlin": 36719092}
|
package compose.icons.octicons
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 compose.icons.Octicons
public val Octicons.BellSlash16: ImageVector
get() {
if (_bellSlash16 != null) {
return _bellSlash16!!
}
_bellSlash16 = Builder(name = "BellSlash16", defaultWidth = 16.0.dp, defaultHeight =
16.0.dp, viewportWidth = 16.0f, viewportHeight = 16.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(8.0f, 1.5f)
curveToRelative(-0.997f, 0.0f, -1.895f, 0.416f, -2.534f, 1.086f)
arcTo(0.75f, 0.75f, 0.0f, false, true, 4.38f, 1.55f)
arcTo(5.0f, 5.0f, 0.0f, false, true, 13.0f, 5.0f)
verticalLineToRelative(2.373f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.5f, 0.0f)
lineTo(11.5f, 5.0f)
arcTo(3.5f, 3.5f, 0.0f, false, false, 8.0f, 1.5f)
close()
moveTo(4.182f, 4.31f)
lineTo(1.19f, 2.143f)
arcToRelative(0.75f, 0.75f, 0.0f, true, false, -0.88f, 1.214f)
lineTo(3.0f, 5.305f)
verticalLineToRelative(2.642f)
arcToRelative(0.25f, 0.25f, 0.0f, false, true, -0.042f, 0.139f)
lineTo(1.255f, 10.64f)
arcTo(1.518f, 1.518f, 0.0f, false, false, 2.518f, 13.0f)
horizontalLineToRelative(11.108f)
lineToRelative(1.184f, 0.857f)
arcToRelative(0.75f, 0.75f, 0.0f, true, false, 0.88f, -1.214f)
lineToRelative(-1.375f, -0.996f)
arcToRelative(1.196f, 1.196f, 0.0f, false, false, -0.013f, -0.01f)
lineTo(4.198f, 4.321f)
arcToRelative(0.733f, 0.733f, 0.0f, false, false, -0.016f, -0.011f)
close()
moveTo(11.555f, 11.5f)
lineTo(4.5f, 6.391f)
verticalLineToRelative(1.556f)
curveToRelative(0.0f, 0.346f, -0.102f, 0.683f, -0.294f, 0.97f)
lineToRelative(-1.703f, 2.556f)
arcToRelative(0.018f, 0.018f, 0.0f, false, false, -0.003f, 0.01f)
arcToRelative(0.015f, 0.015f, 0.0f, false, false, 0.005f, 0.012f)
arcToRelative(0.017f, 0.017f, 0.0f, false, false, 0.006f, 0.004f)
lineToRelative(0.007f, 0.001f)
horizontalLineToRelative(9.037f)
close()
moveTo(8.0f, 16.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 1.985f, -1.75f)
curveToRelative(0.017f, -0.137f, -0.097f, -0.25f, -0.235f, -0.25f)
horizontalLineToRelative(-3.5f)
curveToRelative(-0.138f, 0.0f, -0.252f, 0.113f, -0.235f, 0.25f)
arcTo(2.0f, 2.0f, 0.0f, false, false, 8.0f, 16.0f)
close()
}
}
.build()
return _bellSlash16!!
}
private var _bellSlash16: ImageVector? = null
| 17
|
Kotlin
|
25
| 571
|
a660e5f3033e3222e3553f5a6e888b7054aed8cd
| 3,626
|
compose-icons
|
MIT License
|
library/src/main/java/com/github/lcdsmao/springx/ViewPropertySpringAnimator.kt
|
lcdsmao
| 187,489,244
| false
| null |
package com.github.lcdsmao.springx
import android.view.View
import androidx.annotation.MainThread
import androidx.dynamicanimation.animation.DynamicAnimation
import androidx.dynamicanimation.animation.FloatPropertyCompat
import androidx.dynamicanimation.animation.SpringAnimation
import androidx.dynamicanimation.animation.SpringForce
class ViewPropertySpringAnimator<T : View>(
private val view: T
) {
interface AnimatorListener<T : View> {
fun onAnimationStart(animator: ViewPropertySpringAnimator<T>) {}
fun onAnimationCancel(animator: ViewPropertySpringAnimator<T>) {}
fun onAnimationEnd(animator: ViewPropertySpringAnimator<T>) {}
}
private val pendingAnimations = mutableListOf<SpringAnimationHolder>()
// Contains pending animations and running animations
private val animatorMap = mutableMapOf<FloatPropertyCompat<in T>, SpringAnimation>()
val isRunning: Boolean
get() = animatorMap.values.any { it.isRunning }
private var defaultDampingRatio: Float = SpringForce.DAMPING_RATIO_MEDIUM_BOUNCY
private var defaultStiffness: Float = SpringForce.STIFFNESS_MEDIUM
private var animatorListener: AnimatorListener<T>? = null
fun defaultDampingRatio(value: Float) = apply {
defaultDampingRatio = value
}
fun defaultStiffness(value: Float) = apply {
defaultStiffness = value
}
fun x(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(DynamicAnimation.X, value, config)
/**
* Eager evaluate the final value from the current value.
*/
fun xBy(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(DynamicAnimation.X, value, config)
fun y(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(DynamicAnimation.Y, value, config)
/**
* Eager evaluate the final value from the current value.
*/
fun yBy(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(DynamicAnimation.Y, value, config)
fun z(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(DynamicAnimation.Z, value, config)
/**
* Eager evaluate the final value from the current value.
*/
fun zBy(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(DynamicAnimation.Z, value, config)
fun rotation(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(DynamicAnimation.ROTATION, value, config)
/**
* Eager evaluate the final value from the current value.
*/
fun rotationBy(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(DynamicAnimation.ROTATION, value, config)
fun rotationX(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(DynamicAnimation.ROTATION_X, value, config)
/**
* Eager evaluate the final value from the current value.
*/
fun rotationXBy(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(DynamicAnimation.ROTATION_X, value, config)
fun rotationY(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(DynamicAnimation.ROTATION_Y, value, config)
/**
* Eager evaluate the final value from the current value.
*/
fun rotationYBy(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(DynamicAnimation.ROTATION_Y, value, config)
fun translationX(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(DynamicAnimation.TRANSLATION_X, value, config)
/**
* Eager evaluate the final value from the current value.
*/
fun translationXBy(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(DynamicAnimation.TRANSLATION_X, value, config)
fun translationY(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(DynamicAnimation.TRANSLATION_Y, value, config)
/**
* Eager evaluate the final value from the current value.
*/
fun translationYBy(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(DynamicAnimation.TRANSLATION_Y, value, config)
fun translationZ(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(DynamicAnimation.TRANSLATION_Z, value, config)
/**
* Eager evaluate the final value from the current value.
*/
fun translationZBy(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(DynamicAnimation.TRANSLATION_Z, value, config)
fun scaleX(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(DynamicAnimation.SCALE_X, value, config)
/**
* Eager evaluate the final value from the current value.
*/
fun scaleXBy(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(DynamicAnimation.SCALE_X, value, config)
fun scaleY(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(DynamicAnimation.SCALE_Y, value, config)
/**
* Eager evaluate the final value from the current value.
*/
fun scaleYBy(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(DynamicAnimation.SCALE_Y, value, config)
fun alpha(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(DynamicAnimation.ALPHA, value, config)
/**
* Eager evaluate the final value from the current value.
*/
fun alphaBy(
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(DynamicAnimation.ALPHA, value, config)
/**
* A new [SpringAnimation] will be created every time you call this method.
*/
fun animateProperty(
value: Float,
setter: T.(Float) -> Unit,
getter: T.() -> Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animateProperty(createCustomProperty(setter, getter), value, config)
/**
* Eager evaluate the final value from the current value.
* A new [SpringAnimation] will be created every time you call this method.
*/
fun animatePropertyBy(
setter: T.(Float) -> Unit,
getter: T.() -> Float,
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
): ViewPropertySpringAnimator<T> =
animatePropertyBy(createCustomProperty(setter, getter), value, config)
fun animateProperty(
property: FloatPropertyCompat<in T>,
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
) = apply {
animatePropertyInternal(property, value, config)
}
/**
* Eager evaluate the final value from the current value.
*/
fun animatePropertyBy(
property: FloatPropertyCompat<in T>,
value: Float,
config: SpringAnimationConfig.() -> Unit = {}
) = apply {
animatePropertyInternal(property, value + property.getValue(view), config)
}
@MainThread
fun start(): ViewPropertySpringAnimator<T> = apply {
if (pendingAnimations.isEmpty()) return@apply
val animations = pendingAnimations.toList()
pendingAnimations.clear()
animatorListener?.onAnimationStart(this)
animations.forEach { it.start() }
}
@MainThread
fun cancel() {
pendingAnimations.clear()
val animations = animatorMap.values.toList()
animatorMap.clear()
animations.forEach { it.cancel() }
animatorListener?.onAnimationCancel(this)
}
@MainThread
fun skipToEnd() {
pendingAnimations.clear()
val animations = animatorMap.values.toList()
animations.filter { it.canSkipToEnd() }
.forEach { it.skipToEnd() }
}
fun setListener(
onStart: (animator: ViewPropertySpringAnimator<T>) -> Unit = {},
onCancel: (animator: ViewPropertySpringAnimator<T>) -> Unit = {},
onEnd: (animator: ViewPropertySpringAnimator<T>) -> Unit = {}
) = setListener(object : AnimatorListener<T> {
override fun onAnimationStart(animator: ViewPropertySpringAnimator<T>) {
onStart(animator)
}
override fun onAnimationCancel(animator: ViewPropertySpringAnimator<T>) {
onCancel(animator)
}
override fun onAnimationEnd(animator: ViewPropertySpringAnimator<T>) {
onEnd(animator)
}
})
fun setListener(listener: AnimatorListener<T>?) = apply {
this.animatorListener = listener
}
fun removeUpdateListener(listener: DynamicAnimation.OnAnimationUpdateListener) {
animatorMap.forEach { (_, animation) ->
animation.removeUpdateListener(listener)
}
}
fun removeEndListener(listener: DynamicAnimation.OnAnimationEndListener) {
animatorMap.forEach { (_, animation) ->
animation.removeEndListener(listener)
}
}
private fun createCustomProperty(
setter: T.(Float) -> Unit,
getter: T.() -> Float
) = object : FloatPropertyCompat<T>("CustomProperty") {
override fun getValue(view: T): Float {
return getter.invoke(view)
}
override fun setValue(view: T, value: Float) {
setter.invoke(view, value)
}
}
private fun animatePropertyInternal(
property: FloatPropertyCompat<in T>,
finalValue: Float,
configBuilder: SpringAnimationConfig.() -> Unit = {}
) {
var anim = animatorMap[property]
if (anim == null) {
anim = SpringAnimation(view, property)
anim.cleanSelfOnEnd(property)
animatorMap[property] = anim
}
val config = SpringAnimationConfig(finalValue).apply(configBuilder)
config.defaultDampingRatio = defaultDampingRatio
config.defaultStiffness = defaultStiffness
pendingAnimations += SpringAnimationHolder(anim, config)
}
private fun SpringAnimation.cleanSelfOnEnd(
property: FloatPropertyCompat<in T>
) {
val listener = object : DynamicAnimation.OnAnimationEndListener {
override fun onAnimationEnd(
animation: DynamicAnimation<out DynamicAnimation<*>>?,
canceled: Boolean,
value: Float,
velocity: Float
) {
animatorMap.remove(property)
animation?.removeEndListener(this)
if (animatorMap.isEmpty() && !canceled) {
animatorListener?.onAnimationEnd(this@ViewPropertySpringAnimator)
}
}
}
addEndListener(listener)
}
}
| 12
|
Kotlin
|
1
| 104
|
2b8d9fee70981142967680cb038e04c2fca163a6
| 11,188
|
SpringX
|
Apache License 2.0
|
android/src/main/java/ch/jls/reactnative/mapboxnavigation/MapboxNavigationViewManager.kt
|
jls-digital
| 804,361,168
| false
|
{"Kotlin": 44814, "TypeScript": 7585, "Swift": 6530, "Ruby": 3293, "Objective-C": 3126, "JavaScript": 2122, "Objective-C++": 815, "C": 103}
|
package ch.jls.reactnative.mapboxnavigation
import android.content.pm.PackageManager
import android.util.Log
import android.view.Choreographer
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.fragment.app.FragmentActivity
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.ViewGroupManager
import com.facebook.react.uimanager.annotations.ReactProp
import com.mapbox.common.MapboxOptions
import com.mapbox.geojson.Point
class MapboxNavigationViewManager(private var reactContext: ReactApplicationContext) :
ViewGroupManager<FrameLayout>() {
private var accessToken: String? = null
private var mapboxNavigationFragment: MapboxNavigationFragment? = null
/**
* Navigation destination point
*/
private var destination: Point? = null
/**
* Navigation origin point
*/
private var origin: Point? = null
/**
* List of waypoints for the navigation to follow
*/
private var waypoints: List<Point> = ArrayList()
/**
* Whether navigation should be simulated
*/
private var shouldSimulateRoute = false
/**
* Whether feedback should be shown by mapbox when navigation is finished
*/
private var shouldShowEndOfRouteFeedback = false
/**
* Whether the voice should be muted
*/
private var isVoiceInstructionsMuted = false
companion object {
private const val REACT_CLASS = "MapboxNavigation"
private const val COMMAND_CREATE = 1
}
init {
reactContext.runOnUiQueueThread {
try {
val app = reactContext.packageManager.getApplicationInfo(
reactContext.packageName,
PackageManager.GET_META_DATA
)
val bundle = app.metaData
val accessToken = bundle.getString("MAPBOX_ACCESS_TOKEN")
this.accessToken = accessToken
if (accessToken != null) {
MapboxOptions.accessToken = accessToken
}
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
}
}
override fun getName() = REACT_CLASS
override fun createViewInstance(reactContext: ThemedReactContext): FrameLayout {
return FrameLayout(reactContext)
}
override fun onDropViewInstance(view: FrameLayout) {
super.onDropViewInstance(view)
Log.d("MapboxNavigation", "Dropping view instance")
val activity = reactContext.currentActivity as FragmentActivity
activity.supportFragmentManager
.beginTransaction()
.remove(this.mapboxNavigationFragment!!)
.commit()
Log.d("MapboxNavigation", "Fragment removed")
}
override fun getCommandsMap(): Map<String, Int> {
return mapOf("create" to COMMAND_CREATE)
}
override fun receiveCommand(root: FrameLayout, commandId: String?, args: ReadableArray?) {
super.receiveCommand(root, commandId, args)
val reactNativeViewId = requireNotNull(args).getInt(0)
Log.d("MapboxNavigation", "Received command: $commandId with viewId: $reactNativeViewId")
when (requireNotNull(commandId).toInt()) {
COMMAND_CREATE -> createFragment(root, reactNativeViewId)
}
}
private fun createFragment(root: FrameLayout, reactNativeViewId: Int) {
val parentView = root.findViewById<ViewGroup>(reactNativeViewId)
setupLayout(parentView)
this.mapboxNavigationFragment = MapboxNavigationFragment(this.reactContext)
this.mapboxNavigationFragment!!.setOrigin(this.origin)
this.mapboxNavigationFragment!!.setDestination(this.destination)
this.mapboxNavigationFragment!!.resetWaypoints()
this.waypoints.forEach { this.mapboxNavigationFragment!!.addWaypoint(it) }
this.mapboxNavigationFragment!!.setShouldSimulateRoute(this.shouldSimulateRoute)
this.mapboxNavigationFragment!!.setShouldShowEndOfRouteFeedback(this.shouldShowEndOfRouteFeedback)
this.mapboxNavigationFragment!!.setMute(this.isVoiceInstructionsMuted)
val activity = reactContext.currentActivity as FragmentActivity
activity.supportFragmentManager
.beginTransaction()
.replace(reactNativeViewId, this.mapboxNavigationFragment!!, reactNativeViewId.toString())
.commit()
Log.d("MapboxNavigation", "Fragment created: ${this.mapboxNavigationFragment}")
}
private fun setupLayout(parentView: View) {
Choreographer.getInstance().postFrameCallback(object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
layoutChildView(parentView)
parentView.viewTreeObserver.dispatchOnGlobalLayout()
Choreographer.getInstance().postFrameCallback(this)
}
})
}
private fun layoutChildView(parentView: View) {
val fragmentView = this.mapboxNavigationFragment?.view ?: return
val parentWidth = parentView.width
val parentHeight = parentView.height
// When using this fragment approach, this is the only way to ensure that the ConstraintLayout
// used at the root of navigation_view.xml is properly sized.
fragmentView.measure(
View.MeasureSpec.makeMeasureSpec(parentWidth, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(parentHeight, View.MeasureSpec.EXACTLY)
)
fragmentView.layout(0, 0, parentWidth, parentHeight)
}
@ReactProp(name = "destination")
fun setDestination(view: FrameLayout, destination: ReadableArray?) {
if (destination == null) {
this.destination = null
this.mapboxNavigationFragment?.setDestination(null)
return
}
this.destination = Point.fromLngLat(destination.getDouble(0), destination.getDouble(1))
this.mapboxNavigationFragment?.setDestination(this.destination)
}
@ReactProp(name = "origin")
fun setOrigin(view: FrameLayout, origin: ReadableArray?) {
if (origin == null) {
this.origin = null
this.mapboxNavigationFragment?.setOrigin(null)
return
}
this.origin = Point.fromLngLat(origin.getDouble(0), origin.getDouble(1))
this.mapboxNavigationFragment?.setOrigin(this.origin)
}
@ReactProp(name = "waypoints")
fun setWaypoints(view: FrameLayout, waypoints: ReadableArray?) {
this.mapboxNavigationFragment?.resetWaypoints()
if (waypoints == null) {
this.waypoints = ArrayList()
return
}
for (i in 0 until waypoints.size()) {
val entry = waypoints.getArray(i)
val point = Point.fromLngLat(entry.getDouble(0), entry.getDouble(1))
this.waypoints += point
this.mapboxNavigationFragment?.addWaypoint(point)
}
}
@ReactProp(name = "shouldSimulateRoute")
fun setShouldSimulateRoute(view: FrameLayout, shouldSimulateRoute: Boolean) {
this.shouldSimulateRoute = shouldSimulateRoute
this.mapboxNavigationFragment?.setShouldSimulateRoute(shouldSimulateRoute)
}
@ReactProp(name = "shouldShowEndOfRouteFeedback")
fun setShowsEndOfRouteFeedback(view: FrameLayout, shouldShowEndOfRouteFeedback: Boolean) {
this.shouldShowEndOfRouteFeedback = shouldShowEndOfRouteFeedback
this.mapboxNavigationFragment?.setShouldShowEndOfRouteFeedback(shouldShowEndOfRouteFeedback)
}
@ReactProp(name = "mute")
fun setMute(view: FrameLayout, mute: Boolean) {
this.isVoiceInstructionsMuted = mute
this.mapboxNavigationFragment?.setMute(mute)
}
}
| 0
|
Kotlin
|
0
| 0
|
ca6453d9e069e11898938ab4b1daa3579cfe793e
| 7,320
|
react-native-mapbox-navigation
|
MIT License
|
core/src/commonMain/kotlin/io/shortway/kobankat/EntitlementVerificationMode.kt
|
JayShortway
| 758,647,648
| false
|
{"Kotlin": 225838, "Ruby": 2360, "Swift": 594}
|
package io.shortway.kobankat
/**
* Verification strictness levels for [EntitlementInfo].
*/
public enum class EntitlementVerificationMode {
/**
* The SDK will not perform any entitlement verification.
*/
DISABLED,
/**
* Enable entitlement verification.
*/
INFORMATIONAL,
}
| 8
|
Kotlin
|
3
| 9
|
f374c234be5b1fc5da36dbf0ddcfe0398d871cf5
| 312
|
kobankat
|
MIT License
|
app/src/main/java/com/example/arduino_sense/SignupActivity.kt
|
tlehikoinen
| 472,755,130
| false
|
{"Kotlin": 62084}
|
package com.example.arduino_sense
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import okhttp3.ResponseBody
class SignupActivity : AppCompatActivity() {
lateinit var signup_btn: Button
lateinit var text_username: EditText
lateinit var text_password: EditText
lateinit var text_response: TextView
var userService = UserService()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_signup)
initSignupBtn()
initTextBoxes()
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
private fun initSignupBtn() {
signup_btn = findViewById(R.id.btn_signup)
signup_btn.setOnClickListener { signUp() }
}
private fun initTextBoxes() {
text_username = findViewById(R.id.signup_username)
text_password = findViewById(R.id.signup_password)
text_response = findViewById(R.id.signup_text_response)
}
private fun signUp() {
Log.d("Signup", "username ${text_username.text} password ${text_password.text}")
val reqUser = PostUserReq(text_username.text.toString(), text_password.text.toString())
userService.createUser(reqUser, object : UserService.SignupCallback {
override fun onSuccess(response: String) {
Log.d("signup", "success ${response}")
toast("SignUp success, you can login now")
onBackPressed()
}
override fun onFailure(errorMessage: String) {
Log.d("signup", "signup failed $errorMessage")
set_res_text_delay(errorMessage, 2000)
}
})
}
private fun toast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show()
}
private fun set_res_text_delay(text: String, delayMs: Long) {
text_response.setText(text)
Handler(Looper.getMainLooper()).postDelayed(
{ text_response.setText("") },
delayMs
)
}
}
| 0
|
Kotlin
|
2
| 0
|
09032f742d1fff4077f58e9f9cd5020ece340d4f
| 2,327
|
arduino-sense
|
MIT License
|
src/main/kotlin/com/yingtaohuo/db/DBWXUser.kt
|
menuxx
| 96,880,838
| false
|
{"JavaScript": 1254682, "Kotlin": 162067, "FreeMarker": 67462, "Java": 22082, "CSS": 2227, "HTML": 4}
|
package com.yingtaohuo.db
import com.yingtaohuo.model.WXUserModel
import com.yingtaohuo.sso.db.tables.TWxUser
import com.yingtaohuo.sso.db.tables.records.TWxUserRecord
import com.zaxxer.hikari.HikariDataSource
import org.jooq.impl.DSL
import org.springframework.stereotype.Service
/**
* 作者: <EMAIL>
* 创建于: 2017/10/18
* 微信: yin80871901
*/
@Service
class DBWXUser(private val dataSource: HikariDataSource) {
fun findUserByOpenid(openid: String) : TWxUserRecord? {
val tWxUser = TWxUser.T_WX_USER
dataSource.connection.use {
DSL.using(it).use { ctx ->
return ctx.select().from(tWxUser).where(tWxUser.OPENID.eq(openid)).fetchOne()?.into(TWxUserRecord::class.java)
}
}
}
fun findUserByUnionid(unionid: String) : TWxUserRecord? {
val tWxUser = TWxUser.T_WX_USER
dataSource.connection.use {
DSL.using(it).use { ctx ->
return ctx.select().from(tWxUser).where(tWxUser.UNIONID.eq(unionid)).fetchOne()?.into(TWxUserRecord::class.java)
}
}
}
fun insertUser(user: WXUserModel) : Int {
val tWxUser = TWxUser.T_WX_USER
dataSource.connection.use {
DSL.using(it).use { ctx ->
return ctx.insertInto(tWxUser)
.set(toRecord<TWxUserRecord, WXUserModel>(user, false, true))
.returning(tWxUser.ID).fetchOne().getValue(tWxUser.ID).toInt()
}
}
}
fun updateUser(user: WXUserModel) : Int {
val tWxUser = TWxUser.T_WX_USER
dataSource.connection.use {
DSL.using(it).use { ctx ->
return ctx.update(tWxUser)
.set(toRecord<TWxUserRecord, WXUserModel>(user, false, true))
.where(tWxUser.UNIONID.eq(user.unionid))
.execute()
}
}
}
}
| 0
|
JavaScript
|
0
| 0
|
81ffb601aa4b92024966067574357109ac81e115
| 1,917
|
sso
|
Apache License 2.0
|
Aretech App/app/src/main/java/com/example/aretech/ui/activities/menu/notification/util/PAGER.kt
|
s3bu7i
| 871,643,869
| false
|
{"Kotlin": 317569, "TypeScript": 228210, "JavaScript": 16695, "Java": 6185, "CSS": 1738, "Python": 1259}
|
package com.example.aretech.ui.activities.menu.notification.util
enum class PAGER {
NOTIFICATION_UNREAD,
NOTIFICATION_READ
}
| 0
|
Kotlin
|
0
| 1
|
a5c86328a4fced42e04380e448e53f9452be9b5b
| 133
|
Aretech
|
MIT License
|
sketch-core/src/commonMain/kotlin/com/github/panpf/sketch/request/ImageOptionsProvider.kt
|
panpf
| 14,798,941
| false
|
{"Kotlin": 2979756, "Shell": 1469}
|
/*
* Copyright (C) 2024 panpf <<EMAIL>>
*
* 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.github.panpf.sketch.request
/**
* Interface for providing [ImageOptions]
*
* @see com.github.panpf.sketch.core.common.test.request.ImageOptionsProviderTest
*/
interface ImageOptionsProvider {
var imageOptions: ImageOptions?
}
/**
* Update [ImageOptions] with the specified configuration block
*
* @see com.github.panpf.sketch.core.common.test.request.ImageOptionsProviderTest.testUpdateImageOptions
*/
fun ImageOptionsProvider.updateImageOptions(configBlock: (ImageOptions.Builder.() -> Unit)) {
imageOptions = imageOptions?.newOptions(configBlock) ?: ImageOptions(configBlock)
}
| 8
|
Kotlin
|
309
| 2,057
|
89784530da0de6085a5b08f810415147cb3165cf
| 1,214
|
sketch
|
Apache License 2.0
|
app/src/main/java/com/ferdyhaspin/githubuserapp/util/ext/ViewExt.kt
|
ferdyhaspin
| 262,837,173
| false
| null |
package com.ferdyhaspin.githubuserapp.util.ext
import android.content.Context
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.ferdyhaspin.githubuserapp.R
/**
* Created by ferdyhaspin on 26/04/20.
* Copyright (c) 2020 Github User Apps All rights reserved.
*/
fun Context.toast(message: String) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
fun View.toVisible() {
this.visibility = View.VISIBLE
}
fun View.toGone() {
this.visibility = View.GONE
}
fun ImageView.loadImageCircle(url: String) =
Glide.with(this)
.setDefaultRequestOptions(
RequestOptions()
.placeholder(
R.drawable.bg_fill_darkwhite_circle
)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
)
.load(url)
.into(this)
| 0
|
Kotlin
|
0
| 0
|
d129fbec737258e0582bb5abe01e54b54916fad0
| 1,006
|
github-user
|
Apache License 2.0
|
demo/multiround/src/test/java/com/alessandro/claymore/demo/multiround/villains/VillainsActivityTest.kt
|
alecarnevale
| 559,250,665
| false
|
{"Kotlin": 92000}
|
package com.alessandro.claymore.demo.multiround.villains
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.core.app.ActivityScenario
import com.alessandro.claymore.demo.multiround.models.Villain
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import dagger.hilt.android.testing.HiltTestApplication
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import javax.inject.Inject
@RunWith(RobolectricTestRunner::class)
@Config(application = HiltTestApplication::class)
@HiltAndroidTest
class VillainsActivityTest {
@get:Rule
val composeTestRule = createComposeRule()
@get:Rule
val hiltRule = HiltAndroidRule(this)
@Inject
lateinit var villainsActivityIntent: VillainsActivityIntent
@Before
fun setup() {
hiltRule.inject()
}
@Test
fun `Villains appear`() {
ActivityScenario.launch<VillainsActivity>(villainsActivityIntent(Villain("Shredder"), Villain("Karai"))).use { scenario ->
scenario.onActivity {
with(composeTestRule) {
onNodeWithText("Waiting for the first villain...").assertIsDisplayed()
onNodeWithText("Waiting for the second villain...").assertIsDisplayed()
onNodeWithText("Release villains").performClick()
onNodeWithText("Shredder appears!").assertIsDisplayed()
onNodeWithText("Karai appears!").assertIsDisplayed()
}
}
}
}
}
| 1
|
Kotlin
|
0
| 5
|
fedfc34d5d114fff7f3f5063906caf70ea419137
| 1,712
|
claymore
|
Apache License 2.0
|
library/src/main/java/by/dzmitry_lakisau/month_year_picker_dialog/MonthsAdapter.kt
|
Dzmitry-Lakisau
| 420,276,564
| false
|
{"Kotlin": 32379}
|
/**
* Copyright © 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package by.dzmitry_lakisau.month_year_picker_dialog
import android.graphics.Canvas
import android.graphics.Paint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.children
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.textview.MaterialTextView
import java.text.SimpleDateFormat
import java.util.*
internal class MonthsAdapter(private val onMonthSelectedListener: ((Int) -> Unit)? = null) : RecyclerView.Adapter<MonthsAdapter.ViewHolder>() {
var isAnnualMode = false
var minMonth = Calendar.JANUARY
var selectedMonth = Calendar.JANUARY
var maxMonth = Calendar.DECEMBER
var minYear = 0
private var selectedYear = 0
var maxYear = 0
lateinit var monthFormat: SimpleDateFormat
private val months = listOf(
Calendar.JANUARY,
Calendar.FEBRUARY,
Calendar.MARCH,
Calendar.APRIL,
Calendar.MAY,
Calendar.JUNE,
Calendar.JULY,
Calendar.AUGUST,
Calendar.SEPTEMBER,
Calendar.OCTOBER,
Calendar.NOVEMBER,
Calendar.DECEMBER
)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_month, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.onBindViewHolder(months[position])
}
override fun getItemCount(): Int {
return months.size
}
fun setSelectedYear(year: Int) {
selectedYear = year
if (!isAnnualMode) {
if (selectedYear == minYear) {
if (selectedMonth < minMonth) {
selectedMonth = minMonth
onMonthSelectedListener?.invoke(selectedMonth)
}
} else if (selectedYear == maxYear) {
if (selectedMonth > maxMonth) {
selectedMonth = maxMonth
onMonthSelectedListener?.invoke(selectedMonth)
}
}
notifyItemRangeChanged(0, months.size)
}
}
private fun isInRange(month: Int): Boolean {
return when {
isAnnualMode -> {
month in minMonth..maxMonth
}
minYear == maxYear -> {
month in minMonth..maxMonth
}
selectedYear == maxYear -> {
month <= maxMonth
}
selectedYear == minYear -> {
month >= minMonth
}
else -> {
true
}
}
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val tvName: MaterialTextView = itemView.findViewById(R.id.tv_name)
fun onBindViewHolder(item: Int) {
tvName.text = getMonthName(item, monthFormat)
itemView.isEnabled = isInRange(item)
tvName.isEnabled = itemView.isEnabled
itemView.isSelected = item == selectedMonth
itemView.setOnClickListener {
selectedMonth = item
notifyDataSetChanged()
onMonthSelectedListener?.invoke(selectedMonth)
}
}
}
class SelectedItemDecoration(selectedMonthBackgroundColor: Int): RecyclerView.ItemDecoration() {
private val selectedMonthBackgroundPaint: Paint = Paint().apply { color = selectedMonthBackgroundColor }
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
parent.children.forEach { view ->
if (view.isSelected) {
val radius = (view.height / 2).toFloat()
c.drawCircle(view.left + radius, view.top + radius, radius, selectedMonthBackgroundPaint)
}
}
}
}
}
| 2
|
Kotlin
|
0
| 9
|
82f8a43949863acf42161826c0b9c31bc5de6431
| 4,527
|
MonthYearPickerDialog
|
Apache License 2.0
|
app/src/main/java/com/memad/moviesmix/ui/main/trending/TrendingFragment.kt
|
Mohamed-Emad126
| 438,245,160
| false
|
{"Kotlin": 191086, "Makefile": 158}
|
package com.memad.moviesmix.ui.main.trending
import android.animation.ObjectAnimator
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import android.widget.Toast
import androidx.core.view.doOnPreDraw
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.commit451.coiltransformations.BlurTransformation
import com.google.android.material.imageview.ShapeableImageView
import com.google.android.material.transition.MaterialFadeThrough
import com.google.gson.Gson
import com.memad.moviesmix.R
import com.memad.moviesmix.data.local.MovieEntity
import com.memad.moviesmix.databinding.FragmentTrendingBinding
import com.memad.moviesmix.utils.Constants
import com.memad.moviesmix.utils.GenresUtils
import com.memad.moviesmix.utils.NetworkStatus
import com.memad.moviesmix.utils.Resource
import com.memad.moviesmix.utils.getSnapPosition
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint
class TrendingFragment : Fragment(), TrendingAdapter.OnMoviesClickListener {
private lateinit var snapHelper: LinearSnapHelper
@Volatile
private var error: String = ""
@Inject
lateinit var trendingAdapter: TrendingAdapter
private val trendingViewModel by viewModels<TrendingViewModel>()
private var _binding: FragmentTrendingBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enterTransition = MaterialFadeThrough()
exitTransition = MaterialFadeThrough()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
_binding = FragmentTrendingBinding.inflate(inflater, container, false)
setupDiscreteScrollView()
setupObservables()
binding.sparkButton.setOnClickListener {
if (binding.sparkButton.isChecked) {
binding.sparkButton.isChecked = false
trendingViewModel.removeFromFavourites(
trendingAdapter.currentList[snapHelper.getSnapPosition(
binding.recyclerTrending
)].movieId!!
)
} else {
binding.sparkButton.playAnimation()
binding.sparkButton.isChecked = true
trendingViewModel.addToFavourites(
trendingAdapter.currentList[snapHelper.getSnapPosition(
binding.recyclerTrending
)]
)
}
}
return binding.root
}
private fun setupDiscreteScrollView() {
binding.recyclerTrending.adapter = trendingAdapter
binding.recyclerTrending.layoutManager = LinearLayoutManager(
requireContext(),
LinearLayoutManager.HORIZONTAL,
false
)
trendingAdapter.trendingMovieClickListener = this
snapHelper = object : LinearSnapHelper() {
override fun findSnapView(layoutManager: RecyclerView.LayoutManager?): View? {
val firstVisiblePosition =
(layoutManager as LinearLayoutManager).findFirstCompletelyVisibleItemPosition()
val lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition()
val firstItem = 0
val lastItem = layoutManager.itemCount - 1
return when {
firstItem == firstVisiblePosition -> layoutManager.findViewByPosition(
firstVisiblePosition
)
lastItem == lastVisiblePosition -> layoutManager.findViewByPosition(
lastVisiblePosition
)
else -> super.findSnapView(layoutManager)
}
}
}
snapHelper.attachToRecyclerView(binding.recyclerTrending)
binding.recyclerTrending
.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
val viewHolder: RecyclerView.ViewHolder? =
binding.recyclerTrending.findViewHolderForAdapterPosition(
snapHelper.getSnapPosition(recyclerView)
)
if (newState == RecyclerView.SCROLL_STATE_IDLE && viewHolder is TrendingAdapter.TrendingViewHolder) {
binding.recyclerTrending.layoutManager?.let {
snapPositionChange(
it.getPosition(
snapHelper.findSnapView(
binding.recyclerTrending.layoutManager
)!!
)
)
}
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (!recyclerView.canScrollHorizontally(1)) {
trendingViewModel.loadNextPage()
}
}
})
}
private fun setupObservables() {
networkCheck()
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
trendingViewModel.moviesResource.collect {
when (it) {
is Resource.Loading -> loading()
is Resource.Error -> error(list = it.data!!)
is Resource.Success -> success()
}
}
}
}
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
trendingViewModel.moviesList.collectLatest {
trendingAdapter.submitList(it)
success()
}
}
}
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
trendingViewModel.checkFavouritesFlow.collect { booleans ->
trendingAdapter.submitFavouritesList(booleans)
}
}
}
}
private fun networkCheck() {
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
trendingViewModel.networkStatus.collectLatest {
when (it) {
is NetworkStatus.Disconnected -> {
error = getString(R.string.no_network)
Toast.makeText(requireContext(), error, Toast.LENGTH_LONG).show()
}
else -> {}
}
}
}
}
}
private fun error(list: List<MovieEntity>) {
if (list.isEmpty()) {
binding.movieName.text = error
binding.headerText.visibility = GONE
binding.movieGenre.visibility = GONE
binding.sparkButton.visibility = GONE
binding.releaseYear.visibility = GONE
binding.backdropImage.load(R.drawable.start_img_min_blur) { allowHardware(false) }
binding.progressPercent.text = ""
binding.progressBar.progress = 0
networkCheck()
} else {
success()
}
}
private fun success() {
binding.headerText.text = getString(R.string.trending_header)
binding.headerText.visibility = VISIBLE
binding.movieGenre.visibility = VISIBLE
binding.sparkButton.visibility = VISIBLE
binding.releaseYear.visibility = VISIBLE
}
private fun loading() {
binding.movieName.text = getString(R.string.loading)
binding.movieGenre.visibility = GONE
binding.sparkButton.visibility = GONE
binding.releaseYear.visibility = GONE
binding.progressPercent.text = ""
createProgressAnimation(0.0)
binding.backdropImage.load(R.drawable.start_img_min_blur) {
allowHardware(false)
}
}
private fun handleDetailsUi(
position: Int
) {
if (trendingAdapter.currentList[position].moviePage == -122)
return
binding.movieName.text = trendingAdapter.currentList[position].movie?.original_title
binding.backdropImage.load(
Constants.POSTER_BASE_URL + trendingAdapter.currentList[position].movie?.backdrop_path
) {
transformations(BlurTransformation(requireContext(), 3f, 3f))
crossfade(true)
placeholder(R.drawable.start_img_min_blur)
error(R.drawable.start_img_min_blur)
allowHardware(false)
}
createProgressAnimation(trendingAdapter.currentList[position].movie?.vote_average!!)
binding.releaseYear.text = trendingAdapter.currentList[position].movie?.release_date
binding.movieGenre.text = trendingAdapter.currentList[position].movie?.genre_ids.let {
GenresUtils.getGenres(
it!!
).joinToString(separator = ", ")
}.toString()
if (trendingAdapter.favouriteList.isNotEmpty()) {
binding.sparkButton.isChecked = trendingAdapter.favouriteList[position]
}
}
private fun createProgressAnimation(voteAverage: Double) {
binding.progressBar
val animation: ObjectAnimator = ObjectAnimator.ofInt(
binding.progressBar, "progress", binding.progressBar.progress, voteAverage.toInt() * 100
)
animation.duration = 300
animation.setAutoCancel(true)
animation.interpolator = DecelerateInterpolator()
animation.addUpdateListener {
binding.progressPercent.text =
(it.getAnimatedValue("progress") as Int).toFloat().div(100.0).toString()
}
animation.start()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onMovieClicked(position: Int, imageView: ShapeableImageView) {
val extras = FragmentNavigatorExtras(
imageView to position.toString() + "poster"
)
val movieResult = trendingAdapter.currentList[position]
findNavController().navigate(
TrendingFragmentDirections.actionTrendingFragmentToMovieDescriptionFragment(
Gson().toJson(movieResult),
position.toString()
),
extras
)
}
fun snapPositionChange(position: Int) {
success()
handleDetailsUi(position)
}
override fun onResume() {
super.onResume()
if (binding.recyclerTrending.layoutManager != null && snapHelper.findSnapView(binding.recyclerTrending.layoutManager) != null) {
binding.recyclerTrending.layoutManager?.let {
snapPositionChange(
it.getPosition(
snapHelper.findSnapView(
binding.recyclerTrending.layoutManager
)!!
)
)
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
postponeEnterTransition()
view.doOnPreDraw { startPostponedEnterTransition() }
}
}
| 0
|
Kotlin
|
8
| 45
|
a0d5aea7c91db0eef3a847918998a84e79a335ba
| 12,367
|
MoviesMix
|
MIT License
|
app/src/main/java/jp/cordea/d7362089/ui/details/Details.kt
|
CORDEA
| 492,123,031
| false
| null |
package jp.cordea.d7362089.ui.details
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.annotation.ExperimentalCoilApi
import coil.compose.rememberImagePainter
import jp.cordea.d7362089.ui.theme.D7362089Theme
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
@Composable
@OptIn(ExperimentalMaterial3Api::class, ExperimentalCoilApi::class)
fun Details(viewModel: DetailsViewModel) {
val appBarMaxHeight = with(LocalDensity.current) { 250.dp.toPx() }
val appBarMinHeight = with(LocalDensity.current) { 64.dp.toPx() }
val appBarHeight = remember { mutableStateOf(appBarMaxHeight) }
val scrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
appBarHeight.value =
(appBarHeight.value + available.y).coerceIn(appBarMinHeight, appBarMaxHeight)
return Offset.Zero
}
}
}
val thumbnail by viewModel.thumbnail.observeAsState()
val description by viewModel.description.observeAsState()
val userName by viewModel.userName.observeAsState()
val width by viewModel.width.observeAsState()
val height by viewModel.height.observeAsState()
val createdAt by viewModel.createdAt.observeAsState()
val downloads by viewModel.downloads.observeAsState()
val location by viewModel.location.observeAsState()
Scaffold(
modifier = Modifier.nestedScroll(scrollConnection),
topBar = {
Box(
modifier = Modifier
.height(with(LocalDensity.current) { appBarHeight.value.toDp() })
) {
Image(
painter = rememberImagePainter(data = thumbnail),
contentDescription = description,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
SmallTopAppBar(
modifier = Modifier.align(Alignment.BottomCenter),
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = Color.Transparent
),
title = { Text("By $userName") },
)
}
}
) {
LazyColumn(
contentPadding = it,
modifier = Modifier.padding(16.dp),
) {
item {
Text(description.orEmpty())
}
item { Divider(modifier = Modifier.padding(vertical = 8.dp)) }
item {
ListItem(title = "Size", content = "$width x $height")
}
createdAt?.let {
item {
ListItem(
title = "Created date",
content = it.format(
DateTimeFormatter.ofLocalizedDateTime(
FormatStyle.LONG,
FormatStyle.SHORT
)
)
)
}
}
item {
ListItem(title = "Downloads", content = "$downloads")
}
item {
ListItem(title = "Location", content = location.orEmpty())
}
}
}
}
@Composable
private fun ListItem(title: String, content: String) {
Column(
modifier = Modifier
.fillMaxWidth()
.requiredHeight(64.dp),
verticalArrangement = Arrangement.Center
) {
Text(
title,
style = MaterialTheme.typography.titleSmall,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Spacer(modifier = Modifier.height(4.dp))
Text(
content,
style = MaterialTheme.typography.bodyMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
@Preview(showBackground = true)
@Composable
fun Preview() {
D7362089Theme {
Column(modifier = Modifier.padding(16.dp)) {
ListItem("title", "content")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7829b3aabdd412d5f85657a0b56ff596e02a2ec5
| 5,143
|
d7362089
|
Apache License 2.0
|
AstroYoga/common-ui-compose/src/main/java/com/shushant/common/compose/utils/ActivityProvider.kt
|
ShushantTiwari-ashu
| 667,410,698
| false
| null |
package com.shushant.common.compose.utils
import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
class ActivityProvider(application: Application) {
var activeActivity: ComponentActivity? = null
var scope: CoroutineScope? = null
val activityAliveListenerList = arrayListOf<ActivityAliveListener>()
private val _currentActivity = MutableStateFlow<ComponentActivity?>(null)
val currentActivity: Flow<ComponentActivity?>
get() = _currentActivity
init {
application.registerActivityLifecycleCallbacks(
object : Application.ActivityLifecycleCallbacks {
override fun onActivityPaused(activity: Activity) {
_currentActivity.value = null
activeActivity = null
scope = null
}
override fun onActivityResumed(activity: Activity) {
activeActivity = activity as? ComponentActivity
_currentActivity.value = activeActivity
scope = activeActivity?.lifecycleScope
activityAliveListenerList.forEach {
it.onAlive(activeActivity)
}
activityAliveListenerList.clear()
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
}
override fun onActivityStarted(activity: Activity) {
}
override fun onActivityStopped(activity: Activity) {
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}
override fun onActivityDestroyed(activity: Activity) {
}
}
)
}
fun addListener(activityAliveListener: ActivityAliveListener) {
activityAliveListenerList.add(activityAliveListener)
}
fun safeUseScope(block: CoroutineScope.() -> Unit) {
scope?.let {
block.invoke(it)
} ?: kotlin.run {
CoroutineScope(SupervisorJob() + Dispatchers.Default).launch {
currentActivity.collect { curActivity ->
curActivity?.lifecycleScope?.let(block)
}
}
}
}
}
interface ActivityAliveListener {
fun onAlive(activeActivity: ComponentActivity?)
}
| 0
|
Kotlin
|
0
| 0
|
9882d51d4a1d975249109c097da0c7b141e6ff69
| 2,751
|
AstroYoga-Full-kotlin-stack-App
|
Apache License 2.0
|
src/jvmMain/kotlin/com/bkahlert/netmon/scanner/NetworkFilterSettings.kt
|
bkahlert
| 671,899,608
| false
|
{"Kotlin": 911730, "JavaScript": 766538, "Shell": 102968, "HTML": 57668, "Python": 13258, "CSS": 6078, "Jinja": 809}
|
package com.bkahlert.netmon.scanner
import com.bkahlert.kommons.config.Settings
/** Settings for the network monitor's scanner. */
object NetworkFilterSettings : Settings("network") {
/**
* The minimum number of host bits, that is, the IP address length minus the prefix.
*
* The default is `4`, which corresponds to IPv4 networks with a `/28` prefix and IPv6 networks, with a `/124` prefix.
* Or differently put: networks with 2^4 = 16 IP addresses.
*/
val minHostBits: UInt by setting(default = 4u)
/**
* The maximum number of host bits, that is, the IP address length minus the prefix.
*
* The default is `16`, which corresponds to IPv4 networks with a `/16` prefix and IPv6 networks, with a `/112` prefix.
* Or differently put: networks with 2^16 = 65536 IP addresses.
*/
val maxHostBits: UInt by setting(default = 16u)
val hostBitsRange: IntRange get() = minHostBits.toInt()..maxHostBits.toInt()
}
| 0
|
Kotlin
|
0
| 1
|
0bfd007d349dc9dbb7c2308a92fa9584f16ca767
| 978
|
netmon
|
MIT License
|
server/src/main/kotlin/net/eiradir/server/session/ServerSessionManager.kt
|
Eiradir
| 635,460,745
| false
|
{"Kotlin": 646160, "Dockerfile": 470}
|
package net.eiradir.server.session
import arrow.core.Either
import net.eiradir.server.auth.EiradirAuthentication
import net.eiradir.server.auth.EiradirCredentials
interface ServerSessionManager {
suspend fun createSession(authentication: EiradirAuthentication): Session
suspend fun verifySession(credentials: EiradirCredentials): Either<ServerSessionError, Session>
}
| 11
|
Kotlin
|
0
| 0
|
edca8986ef06fd5a75fd2a4dc53dfe75dbfbbaae
| 377
|
eiradir-server
|
MIT License
|
buildSrc/src/main/kotlin/VerifyTemplateExtension.kt
|
ohtomi
| 48,268,715
| false
| null |
import groovy.lang.Closure
import org.gradle.api.Action
import org.gradle.api.model.ObjectFactory
import org.gradle.util.ConfigureUtil
open class VerifyTemplateExtension(val objectFactory: ObjectFactory) {
val templates: MutableList<VerifyTemplateConventionItem> = mutableListOf()
fun template(configuration: Closure<VerifyTemplateConventionItem>) {
VerifyTemplateConventionItem.newInstance(objectFactory).also {
ConfigureUtil.configure(configuration, it)
templates.add(it)
}
}
fun template(action: Action<in VerifyTemplateConventionItem>) {
VerifyTemplateConventionItem.newInstance(objectFactory).also {
action.execute(it)
templates.add(it)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
67d030557296229b6f3f51d31be7567829b3092f
| 753
|
lazybones-templates
|
MIT License
|
data/src/main/kotlin/io/github/jisungbin/githubusers/data/util/Response.kt
|
jisungbin
| 414,807,757
| false
| null |
/*
* AndroidModernArchitectureSample © 2021 Ji Sungbin. all rights reserved.
* AndroidModernArchitectureSample license is under the Apache-2.0.
*
* [Response.kt] created by Ji Sungbin on 21. 10. 8. 오후 4:09
*
* Please see: https://github.com/jisungbin/AndroidModernArchitectureSample/blob/master/LICENSE
*/
package io.github.jisungbin.githubusers.data.util
import io.github.jisungbin.githubusers.domain.GithubResult
import retrofit2.Response
fun <T> Response<T>.isValid() = isSuccessful && body() != null
fun <T> Response<T>.toFailResult(requestMethod: String) = GithubResult.Fail(
Exception("Github.$requestMethod request fail.\n\n${errorBody()?.use { it.string() }}")
)
| 3
|
Kotlin
|
0
| 23
|
2916ccf068512574b15c4ac2a32f624249f03984
| 686
|
AndroidModernArchitectureSample
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.