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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vck/src/commonMain/kotlin/at/asitplus/wallet/lib/agent/Holder.kt | a-sit-plus | 602,578,639 | false | {"Kotlin": 1076316} | package at.asitplus.wallet.lib.agent
import at.asitplus.KmmResult
import at.asitplus.jsonpath.core.NodeList
import at.asitplus.jsonpath.core.NormalizedJsonPath
import at.asitplus.wallet.lib.data.ConstantIndex
import at.asitplus.wallet.lib.data.VerifiablePresentation
import at.asitplus.wallet.lib.data.dif.ConstraintField
import at.asitplus.wallet.lib.data.dif.FormatHolder
import at.asitplus.wallet.lib.data.dif.InputDescriptor
import at.asitplus.wallet.lib.data.dif.PresentationDefinition
import at.asitplus.wallet.lib.data.dif.PresentationSubmission
import at.asitplus.wallet.lib.iso.IssuerSigned
import kotlinx.serialization.Serializable
@Serializable
data class CredentialSubmission(
val credential: SubjectCredentialStore.StoreEntry,
val disclosedAttributes: Collection<NormalizedJsonPath>,
)
typealias InputDescriptorMatches = Map<SubjectCredentialStore.StoreEntry, Map<ConstraintField, NodeList>>
/**
* Summarizes operations for a Holder in the sense of the [W3C VC Data Model](https://w3c.github.io/vc-data-model/).
*
* It can store Verifiable Credentials, and create a Verifiable Presentation out of the stored credentials
*/
interface Holder {
/**
* The public key for this agent, i.e. the "holder key" that the credentials get bound to.
*/
val keyPair: KeyPairAdapter
/**
* Sets the revocation list ot use for further processing of Verifiable Credentials
*
* @return `true` if the revocation list has been validated and set, `false` otherwise
*/
fun setRevocationList(it: String): Boolean
sealed class StoreCredentialInput {
data class Vc(
val vcJws: String,
val scheme: ConstantIndex.CredentialScheme,
) : StoreCredentialInput()
data class SdJwt(
val vcSdJwt: String,
val scheme: ConstantIndex.CredentialScheme,
) : StoreCredentialInput()
data class Iso(
val issuerSigned: IssuerSigned,
val scheme: ConstantIndex.CredentialScheme,
) : StoreCredentialInput()
}
/**
* Stores the verifiable credential in [credential] if it parses and validates,
* and returns it for future reference.
*
* Note: Revocation credentials should not be stored, but set with [setRevocationList].
*/
suspend fun storeCredential(credential: StoreCredentialInput): KmmResult<StoredCredential>
/**
* Gets a list of all stored credentials, with a revocation status.
*
* Note that the revocation status may be [Validator.RevocationStatus.UNKNOWN] if no revocation list
* has been set with [setRevocationList]
*/
suspend fun getCredentials(): Collection<StoredCredential>?
sealed class StoredCredential(
open val storeEntry: SubjectCredentialStore.StoreEntry,
val status: Validator.RevocationStatus,
) {
class Vc(
override val storeEntry: SubjectCredentialStore.StoreEntry.Vc,
status: Validator.RevocationStatus
) : StoredCredential(
storeEntry = storeEntry, status = status
)
class SdJwt(
override val storeEntry: SubjectCredentialStore.StoreEntry.SdJwt,
status: Validator.RevocationStatus
) : StoredCredential(
storeEntry = storeEntry, status = status
)
class Iso(
override val storeEntry: SubjectCredentialStore.StoreEntry.Iso,
status: Validator.RevocationStatus
) : StoredCredential(
storeEntry = storeEntry, status = status
)
}
data class PresentationResponseParameters(
val presentationSubmission: PresentationSubmission,
val presentationResults: List<CreatePresentationResult>
)
/**
* Creates an array of [VerifiablePresentation] and a [PresentationSubmission] to match
* the [presentationDefinition].
*
* Fails in case the default submission is not a valid submission.
*
* @param fallbackFormatHolder: format holder to be used in case there is no format holder in a
* given presentation definition and the input descriptor.
* This will mostly resolve to be the some clientMetadata.vpFormats
* @param pathAuthorizationValidator: Provides the user of this library with a way to enforce
* authorization rules.
*/
suspend fun createPresentation(
challenge: String,
// TODO Pass a public key adapter here
audienceId: String,
presentationDefinition: PresentationDefinition,
fallbackFormatHolder: FormatHolder? = null,
pathAuthorizationValidator: PathAuthorizationValidator? = null,
): KmmResult<PresentationResponseParameters>
/**
* Creates an array of [VerifiablePresentation] and a [PresentationSubmission] from already
* preselected [presentationSubmissionSelection].
*
* Assumptions:
* - the presentation submission selection is a valid submission regarding the submission requirements
*
* @param presentationDefinitionId: id of the presentation definition this submission is intended for
* @param presentationSubmissionSelection: a selection of input descriptors by id and
* corresponding credentials along with a description of the fields to be disclosed
*/
suspend fun createPresentation(
challenge: String,
audienceId: String,
presentationDefinitionId: String?,
presentationSubmissionSelection: Map<String, CredentialSubmission>,
): KmmResult<PresentationResponseParameters>
/**
* Creates a mapping from the input descriptors of the presentation definition to matching
* credentials and the fields that would need to be disclosed.
*
* @param fallbackFormatHolder: format holder to be used in case there is no format holder in a
* given presentation definition and the input descriptor.
* This will mostly resolve to be the some clientMetadata.vpFormats
* @param pathAuthorizationValidator: Provides the user of this library with a way to enforce
* authorization rules on attribute credentials that are to be disclosed.
*/
suspend fun matchInputDescriptorsAgainstCredentialStore(
inputDescriptors: Collection<InputDescriptor>,
fallbackFormatHolder: FormatHolder? = null,
pathAuthorizationValidator: PathAuthorizationValidator? = null,
): KmmResult<Map<String, InputDescriptorMatches>>
/**
* Evaluates a given input descriptor against a store enctry.
*
* @param fallbackFormatHolder: format holder to be used in case there is no format holder in the input descriptor.
* This will mostly be some presentationDefinition.formats ?: clientMetadata.vpFormats
* @param pathAuthorizationValidator: Provides the user of this library with a way to enforce
* authorization rules on attribute credentials that are to be disclosed.
* @return for each constraint field a set of matching nodes or null,
*/
fun evaluateInputDescriptorAgainstCredential(
inputDescriptor: InputDescriptor,
credential: SubjectCredentialStore.StoreEntry,
fallbackFormatHolder: FormatHolder?,
pathAuthorizationValidator: (NormalizedJsonPath) -> Boolean,
): KmmResult<Map<ConstraintField, NodeList>>
sealed class CreatePresentationResult {
/**
* [jws] contains a valid, serialized, Verifiable Presentation that can be parsed by [Verifier.verifyPresentation]
*/
data class Signed(val jws: String) : CreatePresentationResult()
/**
* [sdJwt] contains a serialized SD-JWT credential with disclosures and key binding JWT appended
* (separated with `~` as in the specification), that can be parsed by [Verifier.verifyPresentation].
*/
data class SdJwt(val sdJwt: String) : CreatePresentationResult()
/**
* [document] contains a valid ISO 18013 [Document] with [IssuerSigned] and [DeviceSigned] structures
*/
data class Document(val document: at.asitplus.wallet.lib.iso.Document) :
CreatePresentationResult()
}
}
fun Map<String, Map<SubjectCredentialStore.StoreEntry, Map<ConstraintField, NodeList>>>.toDefaultSubmission() =
mapNotNull { descriptorCredentialMatches ->
descriptorCredentialMatches.value.entries.firstNotNullOfOrNull { credentialConstraintFieldMatches ->
CredentialSubmission(
credential = credentialConstraintFieldMatches.key,
disclosedAttributes = credentialConstraintFieldMatches.value.values.mapNotNull {
it.firstOrNull()?.normalizedJsonPath
},
)
}?.let {
descriptorCredentialMatches.key to it
}
}.toMap()
/**
* Implementations should return true, when the credential attribute may be disclosed to the verifier.
*/
typealias PathAuthorizationValidator = (credential: SubjectCredentialStore.StoreEntry, attributePath: NormalizedJsonPath) -> Boolean
open class PresentationException : Exception {
constructor(message: String) : super(message)
constructor(throwable: Throwable) : super(throwable)
} | 23 | Kotlin | 1 | 22 | fed7fe718763edf02578261c0d4fa91d763ac4a2 | 9,231 | vck | Apache License 2.0 |
app/src/main/java/com/guilla/lab/db/data/Database.kt | FGuillRepo | 189,380,725 | false | null | package com.guilla.lab.db.data
import android.arch.persistence.room.Database
import android.arch.persistence.room.RoomDatabase
import com.guilla.lab.Model.Repository
import com.guilla.lab.db.data.Database.Companion.VERSION
@Database(entities = [Repository::class], version = VERSION, exportSchema = false)
abstract class Database : RoomDatabase() {
abstract val productDao: RepositoryDao
companion object {
internal const val VERSION = 1
}
} | 0 | Kotlin | 0 | 0 | 3a13a8ea883b79160c8741984cb98a4ebe65fb28 | 468 | Sample_RepositoryList_Dagger | Apache License 2.0 |
shared/src/commonMain/kotlin/di/viewmodel/viewModelModules.kt | marazmone | 662,759,669 | false | {"Kotlin": 175669, "Swift": 1244, "Shell": 228, "Ruby": 101} | package di.viewmodel
import di.viewmodel.auth.authViewModelModule
import di.viewmodel.auth.splashViewModelScreenModule
import di.viewmodel.main.mainViewModelModule
import di.viewmodel.test.testViewModelModule
fun viewModelModules() = listOf(
testViewModelModule(),
splashViewModelScreenModule(),
authViewModelModule(),
mainViewModelModule(),
)
| 3 | Kotlin | 1 | 5 | 0696f7f764f5ca153cb1d4e44bfe5f165017fbca | 362 | VocaFlow | Apache License 2.0 |
vscode/src/jsMain/kotlin/vscode/AuthenticationProviderInformation.kt | lppedd | 761,812,661 | false | {"Kotlin": 1887051} | package vscode
/**
* Basic information about an [AuthenticationProvider]
*/
external interface AuthenticationProviderInformation {
/**
* The unique identifier of the authentication provider.
*/
val id: String
/**
* The human-readable name of the authentication provider.
*/
val label: String
}
| 0 | Kotlin | 0 | 3 | 0f493d3051afa3de2016e5425a708c7a9ed6699a | 318 | kotlin-externals | MIT License |
src/main/kotlin/com/github/mangatmodi/randomjson/service/RandomDouble.kt | mangatmodi | 163,420,278 | false | null | package com.github.mangatmodi.randomjson.service
import java.util.concurrent.ThreadLocalRandom
/**
* Generator for random double values
* */
interface RandomDouble : RandomValue<Double> {
/** return a random double value
* */
override fun next(): Double
companion object {
@Deprecated("Not compatible with Java. It will be removed", ReplaceWith("threadLocalRandom()"))
fun default(): RandomDouble = RandomDoubleThreadLocalImpl()
/**
* Uses [ThreadLocalRandom] to generate double value between 1 and 1_000_000
* */
@JvmStatic
fun threadLocalRandom(): RandomDouble = RandomDoubleThreadLocalImpl()
}
private class RandomDoubleThreadLocalImpl : RandomDouble {
override fun next() = ThreadLocalRandom
.current()
.nextDouble(1.0, 1000000.0)
.let {
Math.round(it * 100.0).toDouble() / 100.0
}
}
}
| 3 | Kotlin | 0 | 71 | 2a2425c5e1a3286f97c28ac9999eaf96f9fbeb4e | 956 | RandomJson | MIT License |
lottie-compose/src/main/java/com/airbnb/lottie/compose/LottieAnimation.kt | sharathks84 | 383,218,700 | true | {"Java Properties": 2, "Shell": 8, "Markdown": 9, "Gradle": 8, "Batchfile": 1, "Text": 1, "JavaScript": 1, "Ignore List": 5, "XML": 197, "Kotlin": 131, "JSON": 362, "INI": 2, "YAML": 2, "SVG": 1, "Java": 205, "Proguard": 1} | package com.airbnb.lottie.compose
import androidx.annotation.FloatRange
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.platform.LocalContext
import com.airbnb.lottie.ImageAssetDelegate
import com.airbnb.lottie.LottieComposition
import com.airbnb.lottie.LottieDrawable
import com.airbnb.lottie.manager.ImageAssetManager
import com.airbnb.lottie.setImageAssetManager
/**
* This is the base LottieAnimation composable. It takes a composition and renders it at a specific progress.
*
* The overloaded version of [LottieAnimation] that handles playback and is sufficient for most use cases.
*
* @param composition The composition that will be rendered. To generate a [LottieComposition], you can use
* [rememberLottieComposition].
* @param progress The progress (between 0 and 1) that should be rendered. If you want to render a specific
* frame, you can use [LottieComposition.getFrameForProgress]. In most cases, you will want
* to use one of th overloaded LottieAnimation composables that drives the animation for you.
* The overloads that have isPlaying as a parameter instead of progress will drive the
* animation automatically. You may want to use this version if you want to drive the animation
* from your own Animatable or via events such as download progress or a gesture.
* @param imageAssetsFolder If you use image assets, you must explicitly specify the folder in assets/ in which
* they are located because bodymovin uses the name filenames across all
* compositions (img_#). Do NOT rename the images themselves.
* If your images are located in src/main/assets/airbnb_loader/ then imageAssetsFolder
* should be set to "airbnb_loader"
* Be wary if you are using many images, however. Lottie is designed to work with
* vector shapes from After Effects. If your images look like they could be
* represented with vector shapes, see if it is possible to convert them to shape
* layers and re-export your animation. Check the documentation at
* http://airbnb.io/lottie for more information about importing shapes from Sketch
* or Illustrator to avoid this.
* @param imageAssetDelegate Use this if you can't bundle images with your app. This may be useful if you
* download the animations from the network or have the images saved to an SD Card.
* In that case, Lottie will defer the loading of the bitmap to this delegate.
* Be wary if you are using many images, however. Lottie is designed to work with
* vector shapes from After Effects. If your images look like they could be
* represented with vector shapes, see if it is possible to convert them to shape
* layers and re-export your animation. Check the documentation at
* http://airbnb.io/lottie for more information about importing shapes from Sketch
* or Illustrator to avoid this.
* @param outlineMasksAndMattes Enable this to debug slow animations by outlining masks and mattes.
* The performance overhead of the masks and mattes will be proportional to the
* surface area of all of the masks/mattes combined.
* DO NOT leave this enabled in production.
* @param applyOpacityToLayers Sets whether to apply opacity to the each layer instead of shape.
* Opacity is normally applied directly to a shape. In cases where translucent
* shapes overlap, applying opacity to a layer will be more accurate at the
* expense of performance.
* Note: This process is very expensive. The performance impact will be reduced
* when hardware acceleration is enabled.
* @param enableMergePaths Enables experimental merge paths support. Most animations with merge paths will
* want this on but merge path support is more limited than some other rendering
* features so it defaults to off. The only way to know if your animation will work
* well with merge paths or not is to try it. If your animation has merge paths and
* doesn't render correctly, please file an issue.
*/
@Composable
fun LottieAnimation(
composition: LottieComposition?,
@FloatRange(from = 0.0, to = 1.0) progress: Float,
modifier: Modifier = Modifier,
imageAssetsFolder: String? = null,
imageAssetDelegate: ImageAssetDelegate? = null,
outlineMasksAndMattes: Boolean = false,
applyOpacityToLayers: Boolean = false,
enableMergePaths: Boolean = false,
) {
val drawable = remember { LottieDrawable() }
var imageAssetManager by remember { mutableStateOf<ImageAssetManager?>(null) }
if (composition == null || composition.duration == 0f) return Box(modifier)
if (composition.hasImages()) {
val context = LocalContext.current
LaunchedEffect(context, composition, imageAssetsFolder, imageAssetDelegate) {
imageAssetManager = ImageAssetManager(context, imageAssetsFolder, imageAssetDelegate, composition.images)
}
} else {
imageAssetManager = null
}
Canvas(
modifier = modifier
.maintainAspectRatio(composition)
) {
drawIntoCanvas { canvas ->
withTransform({
scale(size.width / composition.bounds.width().toFloat(), size.height / composition.bounds.height().toFloat(), Offset.Zero)
}) {
drawable.composition = composition
drawable.setOutlineMasksAndMattes(outlineMasksAndMattes)
drawable.isApplyingOpacityToLayersEnabled = applyOpacityToLayers
drawable.enableMergePathsForKitKatAndAbove(enableMergePaths)
drawable.setImageAssetManager(imageAssetManager)
drawable.progress = progress
drawable.draw(canvas.nativeCanvas)
}
}
}
}
/**
* This is like [LottieAnimation] except that it handles driving the animation via [animateLottieCompositionAsState]
* instead of taking a raw progress parameter.
*
* @see LottieAnimation
* @see animateLottieCompositionAsState
*/
@Composable
fun LottieAnimation(
composition: LottieComposition?,
modifier: Modifier = Modifier,
isPlaying: Boolean = true,
restartOnPlay: Boolean = true,
clipSpec: LottieClipSpec? = null,
speed: Float = 1f,
iterations: Int = 1,
imageAssetsFolder: String? = null,
imageAssetDelegate: ImageAssetDelegate? = null,
outlineMasksAndMattes: Boolean = false,
applyOpacityToLayers: Boolean = false,
enableMergePaths: Boolean = false,
) {
val progress by animateLottieCompositionAsState(
composition,
isPlaying,
restartOnPlay,
clipSpec,
speed,
iterations,
)
LottieAnimation(
composition,
progress,
modifier,
imageAssetsFolder,
imageAssetDelegate,
outlineMasksAndMattes,
applyOpacityToLayers,
enableMergePaths,
)
}
private fun Modifier.maintainAspectRatio(composition: LottieComposition?): Modifier {
composition ?: return this
// TODO: use ContentScale and a transform here
return this.then(aspectRatio(composition.bounds.width() / composition.bounds.height().toFloat()))
}
| 0 | null | 0 | 0 | a30a2ab145393f3d19de3409e633fed9df7cf3fd | 8,500 | lottie-sharks | Apache License 2.0 |
bff-tiltaksarrangor/src/main/kotlin/no/nav/amt/tiltak/bff/tiltaksarrangor/dto/EndringsmeldingDto.kt | navikt | 393,356,849 | false | null | package no.nav.amt.tiltak.bff.tiltaksarrangor.dto
import no.nav.amt.tiltak.core.domain.tiltak.Endringsmelding
import no.nav.amt.tiltak.core.domain.tiltak.EndringsmeldingStatusAarsak
import java.time.LocalDate
import java.util.*
data class EndringsmeldingDto(
val id: UUID,
val innhold: Innhold?,
val type: Type
) {
enum class Type {
LEGG_TIL_OPPSTARTSDATO,
ENDRE_OPPSTARTSDATO,
FORLENG_DELTAKELSE,
AVSLUTT_DELTAKELSE,
DELTAKER_IKKE_AKTUELL,
ENDRE_DELTAKELSE_PROSENT,
DELTAKER_ER_AKTUELL,
ENDRE_SLUTTDATO
}
sealed class Innhold {
data class LeggTilOppstartsdatoInnhold(
val oppstartsdato: LocalDate,
) : Innhold()
data class EndreOppstartsdatoInnhold(
val oppstartsdato: LocalDate,
) : Innhold()
data class EndreDeltakelseProsentInnhold(
val deltakelseProsent: Int,
val dagerPerUke: Int?,
val gyldigFraDato: LocalDate?
) : Innhold()
data class ForlengDeltakelseInnhold(
val sluttdato: LocalDate,
) : Innhold()
data class AvsluttDeltakelseInnhold(
val sluttdato: LocalDate,
val aarsak: EndringsmeldingStatusAarsakDto,
) : Innhold()
data class DeltakerIkkeAktuellInnhold(
val aarsak: EndringsmeldingStatusAarsakDto,
) : Innhold()
data class EndreSluttdatoInnhold(
val sluttdato: LocalDate
) : Innhold()
}
}
fun Endringsmelding.Innhold.toDto(): EndringsmeldingDto.Innhold {
return when(this) {
is Endringsmelding.Innhold.LeggTilOppstartsdatoInnhold ->
EndringsmeldingDto.Innhold.LeggTilOppstartsdatoInnhold(this.oppstartsdato)
is Endringsmelding.Innhold.EndreOppstartsdatoInnhold ->
EndringsmeldingDto.Innhold.EndreOppstartsdatoInnhold(this.oppstartsdato)
is Endringsmelding.Innhold.ForlengDeltakelseInnhold ->
EndringsmeldingDto.Innhold.ForlengDeltakelseInnhold(this.sluttdato)
is Endringsmelding.Innhold.AvsluttDeltakelseInnhold ->
EndringsmeldingDto.Innhold.AvsluttDeltakelseInnhold(this.sluttdato, this.aarsak.toDto())
is Endringsmelding.Innhold.DeltakerIkkeAktuellInnhold ->
EndringsmeldingDto.Innhold.DeltakerIkkeAktuellInnhold(this.aarsak.toDto())
is Endringsmelding.Innhold.EndreDeltakelseProsentInnhold ->
EndringsmeldingDto.Innhold.EndreDeltakelseProsentInnhold(
deltakelseProsent = this.deltakelseProsent,
dagerPerUke = this.dagerPerUke,
gyldigFraDato = this.gyldigFraDato
)
is Endringsmelding.Innhold.EndreSluttdatoInnhold -> EndringsmeldingDto.Innhold.EndreSluttdatoInnhold(this.sluttdato)
}
}
fun EndringsmeldingStatusAarsak.toDto(): EndringsmeldingStatusAarsakDto {
return when(this.type) {
EndringsmeldingStatusAarsak.Type.SYK -> EndringsmeldingStatusAarsakDto(EndringsmeldingStatusAarsakDto.Type.SYK)
EndringsmeldingStatusAarsak.Type.FATT_JOBB -> EndringsmeldingStatusAarsakDto(EndringsmeldingStatusAarsakDto.Type.FATT_JOBB)
EndringsmeldingStatusAarsak.Type.TRENGER_ANNEN_STOTTE -> EndringsmeldingStatusAarsakDto(EndringsmeldingStatusAarsakDto.Type.TRENGER_ANNEN_STOTTE)
EndringsmeldingStatusAarsak.Type.UTDANNING -> EndringsmeldingStatusAarsakDto(EndringsmeldingStatusAarsakDto.Type.UTDANNING)
EndringsmeldingStatusAarsak.Type.IKKE_MOTT -> EndringsmeldingStatusAarsakDto(EndringsmeldingStatusAarsakDto.Type.IKKE_MOTT)
EndringsmeldingStatusAarsak.Type.OPPFYLLER_IKKE_KRAVENE -> EndringsmeldingStatusAarsakDto(EndringsmeldingStatusAarsakDto.Type.OPPFYLLER_IKKE_KRAVENE, this.beskrivelse)
EndringsmeldingStatusAarsak.Type.ANNET -> EndringsmeldingStatusAarsakDto(EndringsmeldingStatusAarsakDto.Type.ANNET, this.beskrivelse)
}
}
fun Endringsmelding.Type.toDto(): EndringsmeldingDto.Type {
return when (this) {
Endringsmelding.Type.LEGG_TIL_OPPSTARTSDATO -> EndringsmeldingDto.Type.LEGG_TIL_OPPSTARTSDATO
Endringsmelding.Type.ENDRE_OPPSTARTSDATO -> EndringsmeldingDto.Type.ENDRE_OPPSTARTSDATO
Endringsmelding.Type.FORLENG_DELTAKELSE -> EndringsmeldingDto.Type.FORLENG_DELTAKELSE
Endringsmelding.Type.AVSLUTT_DELTAKELSE -> EndringsmeldingDto.Type.AVSLUTT_DELTAKELSE
Endringsmelding.Type.DELTAKER_IKKE_AKTUELL -> EndringsmeldingDto.Type.DELTAKER_IKKE_AKTUELL
Endringsmelding.Type.ENDRE_DELTAKELSE_PROSENT -> EndringsmeldingDto.Type.ENDRE_DELTAKELSE_PROSENT
Endringsmelding.Type.DELTAKER_ER_AKTUELL -> EndringsmeldingDto.Type.DELTAKER_ER_AKTUELL
Endringsmelding.Type.ENDRE_SLUTTDATO -> EndringsmeldingDto.Type.ENDRE_SLUTTDATO
}
}
fun Endringsmelding.toDto() = EndringsmeldingDto(id = id, innhold = innhold?.toDto(), type=type.toDto())
| 2 | Kotlin | 3 | 4 | 7f3df04447dc622e87538f454e4fcc69bfd713e9 | 4,419 | amt-tiltak | MIT License |
sample/src/main/java/app/starzero/navbuilder/sample/ui/detail/DetailViewModel.kt | STAR-ZERO | 635,777,914 | false | null | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.starzero.navbuilder.sample.ui.detail
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class DetailViewModel @Inject constructor(
savedStateHandle: SavedStateHandle
) : ViewModel() {
val args = DetailArgs(savedStateHandle)
}
| 0 | Kotlin | 0 | 4 | 0dc465fdbcb4157eb87866ee3c71e958fae359eb | 961 | navbuilder | Apache License 2.0 |
src/main/kotlin/no/nav/pgi/popp/lagreinntekt/LagreInntektPopp.kt | navikt | 296,824,775 | false | {"Kotlin": 76345, "Shell": 808, "Dockerfile": 421} | package no.nav.pgi.popp.lagreinntekt
import net.logstash.logback.marker.Markers
import no.nav.pgi.domain.PensjonsgivendeInntekt
import no.nav.pgi.domain.serialization.PgiDomainSerializer
import no.nav.pgi.popp.lagreinntekt.kafka.KafkaFactory
import no.nav.pgi.popp.lagreinntekt.kafka.KafkaInntektFactory
import no.nav.pgi.popp.lagreinntekt.kafka.inntekt.PensjonsgivendeInntektConsumer
import no.nav.pgi.popp.lagreinntekt.kafka.republish.RepubliserHendelseProducer
import no.nav.pgi.popp.lagreinntekt.popp.PoppClient
import no.nav.pgi.popp.lagreinntekt.popp.PoppClient.PoppResponse
import no.nav.pgi.popp.lagreinntekt.util.maskFnr
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.errors.TopicAuthorizationException
import org.slf4j.LoggerFactory
import java.net.http.HttpResponse
internal class LagreInntektPopp(
private val poppResponseCounter: PoppResponseCounter,
private val poppClient: PoppClient,
kafkaFactory: KafkaFactory = KafkaInntektFactory()
) {
private val pgiConsumer = PensjonsgivendeInntektConsumer(kafkaFactory)
private val republiserHendelseProducer = RepubliserHendelseProducer(kafkaFactory)
private companion object {
private val log = LoggerFactory.getLogger(LagreInntektPopp::class.java)
private val secureLog = LoggerFactory.getLogger("tjenestekall")
}
internal fun processInntektRecords() {
try {
val inntektRecords = pgiConsumer.pollInntektRecords()
handleInntektRecords(inntektRecords)
pgiConsumer.commit()
} catch (topicAuthorizationException: TopicAuthorizationException) {
log.warn("Kafka credential rotation triggered. Shutting down app")
throw topicAuthorizationException
}
}
private fun handleInntektRecords(inntektRecords: List<ConsumerRecord<String, String>>) {
val delayRequestsToPopp = inntektRecords.hasDuplicates()
if (delayRequestsToPopp) log.info("More than one of the same fnr in polled records, delaying calls to popp for ${inntektRecords.size} records")
inntektRecords.forEach { inntektRecord ->
handleInntektRecord(delayRequestsToPopp, inntektRecord)
}
}
private fun handleInntektRecord(
delayRequestsToPopp: Boolean,
inntektRecord: ConsumerRecord<String, String>
) {
if (delayRequestsToPopp) {
Thread.sleep(30L)
}
val pensjonsgivendeInntekt =
PgiDomainSerializer().fromJson(PensjonsgivendeInntekt::class, inntektRecord.value())
log.info(
Markers.append("sekvensnummer", pensjonsgivendeInntekt.metaData.sekvensnummer),
"Kaller POPP for lagring av pgi. Sekvensnummer: ${pensjonsgivendeInntekt.metaData.sekvensnummer}"
)
when (val response = poppClient.postPensjonsgivendeInntekt(pensjonsgivendeInntekt)) {
is PoppResponse.OK -> logSuccessfulRequestToPopp(response.httpResponse, pensjonsgivendeInntekt)
is PoppResponse.PidValidationFailed -> logPidValidationFailed(
response.httpResponse,
pensjonsgivendeInntekt
)
is PoppResponse.InntektAarValidationFailed -> logInntektAarValidationFailed(
response.httpResponse,
pensjonsgivendeInntekt
)
is PoppResponse.BrukerEksistererIkkeIPEN -> {
logWarningBrukerEksistereIkkeIPenRepublishing(response.httpResponse, pensjonsgivendeInntekt)
republiserHendelseProducer.send(inntektRecord)
}
is PoppResponse.AnnenKonflikt -> {
logErrorRepublishing(response.httpResponse, pensjonsgivendeInntekt)
republiserHendelseProducer.send(inntektRecord)
}
is PoppResponse.UkjentStatus -> {
logShuttingDownDueToUnhandledStatus(response.httpResponse, pensjonsgivendeInntekt)
throw UnhandledStatusCodePoppException(response.httpResponse)
}
}
}
internal fun isClosed() = pgiConsumer.isClosed() && republiserHendelseProducer.isClosed()
internal fun closeKafka() {
pgiConsumer.close()
republiserHendelseProducer.close()
}
private fun logSuccessfulRequestToPopp(response: HttpResponse<String>, pgi: PensjonsgivendeInntekt) {
poppResponseCounter.ok(response.statusCode())
val sekvensnummer = pgi.metaData.sekvensnummer
val marker = Markers.append("sekvensnummer", sekvensnummer)
log.info(
marker,
"Lagret OK i POPP. (Status: ${response.statusCode()}) Sekvensnummer: $sekvensnummer"
)
secureLog.info(
marker,
"Lagret OK i POPP. ${response.logString()}. For pgi: $pgi"
)
}
private fun logPidValidationFailed(response: HttpResponse<String>, pgi: PensjonsgivendeInntekt) {
poppResponseCounter.pidValidationFailed(response.statusCode())
val sekvensnummer = pgi.metaData.sekvensnummer
val marker = Markers.append("sekvensnummer", sekvensnummer)
log.warn(
marker,
"""Failed when adding to POPP. Inntekt will be descarded. Pid did not validate ${response.logString()}. For pgi: $pgi""".maskFnr()
)
secureLog.warn(
marker,
"Failed when adding to POPP. Inntekt will be descarded. Pid did not validate ${response.logString()}. For pgi: $pgi"
)
}
private fun logInntektAarValidationFailed(response: HttpResponse<String>, pgi: PensjonsgivendeInntekt) {
poppResponseCounter.inntektArValidation(response.statusCode())
val sekvensnummer = pgi.metaData.sekvensnummer
val marker = Markers.append("sekvensnummer", sekvensnummer)
log.warn(
marker,
"""Inntektaar is not valid for pgi. Inntekt will be descarded. ${response.logString()}. For pgi: $pgi """.maskFnr()
)
secureLog.warn(
marker,
"Inntektaar is not valid for pgi. Inntekt will be descarded.. ${response.logString()}. For pgi: $pgi "
)
}
private fun logWarningBrukerEksistereIkkeIPenRepublishing(
response: HttpResponse<String>,
pgi: PensjonsgivendeInntekt
) {
poppResponseCounter.republish(response.statusCode())
log.warn(
Markers.append("sekvensnummer", pgi.metaData.sekvensnummer),
"""Failed when adding to POPP. Bruker eksisterer ikke i PEN. Initiating republishing. ${response.logString()}. For pgi: $pgi""".maskFnr()
)
secureLog.warn(
Markers.append("sekvensnummer", pgi.metaData.sekvensnummer),
"Failed when adding to POPP. Bruker eksisterer ikke i PEN. Initiating republishing. ${response.logString()}. For pgi: $pgi"
)
}
private fun logErrorRepublishing(response: HttpResponse<String>, pgi: PensjonsgivendeInntekt) {
poppResponseCounter.republish(response.statusCode())
log.error(
Markers.append("sekvensnummer", pgi.metaData.sekvensnummer),
"""Failed when adding to POPP. Initiating republishing. ${response.logString()}. For pgi: $pgi""".maskFnr()
)
secureLog.error(
Markers.append("sekvensnummer", pgi.metaData.sekvensnummer),
"Failed when adding to POPP. Initiating republishing. ${response.logString()}. For pgi: $pgi"
)
}
private fun logShuttingDownDueToUnhandledStatus(response: HttpResponse<String>, pgi: PensjonsgivendeInntekt) {
poppResponseCounter.shutdown(response.statusCode())
val sekvensnummer = pgi.metaData.sekvensnummer
val marker = Markers.append("sekvensnummer", sekvensnummer)
log.error(
marker,
"""Failed when adding to POPP. Initiating shutdown. ${response.logString()}. For pgi: $pgi """.maskFnr()
)
secureLog.error(
marker,
"Failed when adding to POPP. Initiating shutdown. ${response.logString()}. For pgi: $pgi "
)
}
}
private fun List<ConsumerRecord<String, String>>.hasDuplicates() =
map { it.key() }.toHashSet().size != size
private fun HttpResponse<String>.logString() =
"PoppResponse(Status: ${statusCode()}${if (body().isEmpty()) "" else " Body: ${body()}"})"
| 0 | Kotlin | 1 | 0 | 3acb18fbd4b2413aa5757eafe293133afbe9f92a | 8,364 | pgi-lagre-inntekt-popp | MIT License |
lib/src/main/kotlin/com/github/mrbean355/dota2/ability/Ability.kt | MrBean355 | 303,105,754 | false | null | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.mrbean355.dota2.ability
/**
* An ability slot that belongs to a hero.
*/
interface Ability {
val name: String
val level: Int
val canCast: Boolean
val isPassive: Boolean
val isEnabled: Boolean
val cooldown: Int
val isUltimate: Boolean
val charges: Int?
val maxCharges: Int?
val chargeCooldown: Int?
}
| 0 | Kotlin | 0 | 6 | 59193d7f2a5b8566569fd83698f38f9410a54034 | 953 | dota2-gsi | Apache License 2.0 |
src/com/github/gdgvenezia/TeamMemberModel.kt | GDG-Venezia | 216,021,508 | false | null | package com.github.gdgvenezia
data class TeamMemberModel(
val firstname: String,
val lastname: String,
val pictureUrl: String,
val shortDescription: String,
val longDescription: String,
val twitterUrl: String,
val linkedinUrl: String
)
| 0 | Kotlin | 0 | 2 | 04ae6992d46053d3daf179622b6ec479d2480871 | 265 | gdg-venezia-showcase-app-backend | Apache License 2.0 |
app/src/main/java/com/pablogv63/quicklock/domain/util/CredentialFilter.kt | pablogv63 | 492,472,948 | false | null | package com.pablogv63.quicklock.domain.util
sealed class CredentialFilter {
object Name: CredentialFilter()
object Username: CredentialFilter()
object Category: CredentialFilter()
} | 0 | Kotlin | 0 | 0 | 8a7dd428c649b4f53144dd6b29b93eb9a1366886 | 194 | QuickLock | MIT License |
Chapter-2/WhatsPackt/feature/chat/src/main/java/com/packt/feature/chat/data/network/datasource/ChatRoomDataSource.kt | PacktPublishing | 621,206,516 | false | {"Kotlin": 543087} | package com.packt.feature.chat.data.network.datasource
import com.packt.feature.chat.data.network.model.ChatRoomModel
import com.packt.feature.chat.di.ChatModule.Companion.API_CHAT_ROOM_URL_NAME
import com.packt.feature.chat.di.ChatModule.Companion.API_CLIENT
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import javax.inject.Inject
import javax.inject.Named
class ChatRoomDataSource @Inject constructor(
@Named(API_CLIENT) private val client: HttpClient,
@Named(API_CHAT_ROOM_URL_NAME) private val url: String
) {
suspend fun getInitialChatRoom(id: String): ChatRoomModel {
return client.get(url.format(id)).body()
}
} | 1 | Kotlin | 7 | 23 | aeeb4e61395cf08830841762e0cfcfbdcd5836d0 | 684 | Thriving-in-Android-Development-using-Kotlin | MIT License |
codegen/poetry/src/main/kotlin/com/yandex/yatagan/codegen/poetry/FieldSpecBuilder.kt | yandex | 570,094,802 | false | {"Kotlin": 1455421} | /*
* Copyright 2022 Yandex LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yandex.yatagan.codegen.poetry
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.TypeName
import javax.lang.model.element.Modifier
@JavaPoetry
class FieldSpecBuilder(type: TypeName, name: String) {
@PublishedApi
internal val impl: FieldSpec.Builder = FieldSpec.builder(type, name)
fun modifiers(vararg modifiers: Modifier) {
impl.addModifiers(*modifiers)
}
inline fun initializer(block: ExpressionBuilder.() -> Unit) {
impl.initializer(buildExpression(block))
}
fun initializer(code: CodeBlock) {
impl.initializer(code)
}
} | 11 | Kotlin | 10 | 231 | d0d7b823711c7f5a48cfd76d673ad348407fd904 | 1,243 | yatagan | Apache License 2.0 |
src/main/kotlin/com/mqgateway/core/device/DigitalOutputDevice.kt | alemoke | 407,462,631 | false | {"Groovy": 189986, "Kotlin": 162270, "Shell": 3776} | package com.mqgateway.core.device
import com.mqgateway.core.gatewayconfig.DeviceType
import com.mqgateway.core.hardware.MqGpioPinDigitalOutput
abstract class DigitalOutputDevice(id: String, type: DeviceType, protected val pin: MqGpioPinDigitalOutput) : Device(id, type)
| 0 | null | 0 | 0 | 076a162d0e2f9f86256b4e146d6ae33243e11cc6 | 272 | mqgateway | MIT License |
bookingservice-meeting-app-ktor/src/test/kotlin/SlotSuccessStubTest.kt | akopovab | 638,664,041 | false | null | package ru.otuskotlin.public.bookingservice.meeting
import io.kotest.assertions.ktor.client.shouldHaveStatus
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.ktor.client.call.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.jackson.*
import io.ktor.server.testing.*
import ru.otuskotlin.public.bookingservice.api.apiV1Mapper
import ru.otuskotlin.public.bookingservice.api.models.*
import ru.otuskotlin.public.bookingservice.stubs.SlotStub
class SlotSuccessStubTest : FunSpec({
test("search slot success stub") {
testApplication {
val client = createClient {
install(ContentNegotiation) {
jackson {
setConfig(apiV1Mapper.serializationConfig)
setConfig(apiV1Mapper.deserializationConfig)
}
}
}
val searchRequest = SlotSearchRequest(
requestType = "search",
requestId = "123",
debug = Debug(
mode = RequestDebugMode.STUB,
stub = RequestDebugStubs.SUCCESS
),
employeeId = "123"
)
val response = client.post("/api/slot/search") {
contentType(ContentType.Application.Json)
setBody(searchRequest)
}
val searchResponse = response.body<SlotSearchResponse>()
val responseStub = SlotStub.getSlots()
response shouldHaveStatus HttpStatusCode.OK
searchResponse.requestId shouldBe "123"
searchResponse.slots?.get(0)?.slotId shouldBe responseStub.toList()[0].id.asString()
searchResponse.slots?.get(1)?.slotId shouldBe responseStub.toList()[1].id.asString()
}
}
}) | 0 | Kotlin | 0 | 0 | 7d837698d96892fe5ac9369ee069e1f7913855d3 | 1,916 | ok-bookingservice | Apache License 2.0 |
idea/idea-analysis/src/org/jetbrains/kotlin/idea/klib/utils.kt | meilalina | 246,773,071 | false | null | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.klib
import org.jetbrains.kotlin.library.KotlinLibrary
import java.io.IOException
fun <T> KotlinLibrary.readSafe(defaultValue: T, action: KotlinLibrary.() -> T) = try {
action()
} catch (_: IOException) {
defaultValue
}
| 0 | null | 0 | 1 | 3cbfdd19f521edfb7bf72bd80b18868efe2fcf06 | 474 | kotlin | Apache License 2.0 |
catalog/src/commonMain/kotlin/dev/helw/playground/sdui/FullScreenDemo.kt | ahmedre | 680,260,539 | false | {"Kotlin": 114371, "Swift": 29613, "HTML": 237} | /**
* Copyright (c) 2023 Ahmed El-Helw and Abdulahi Osoble
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package dev.helw.playground.sdui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import dev.helw.playground.sdui.action.ActionHandler
import dev.helw.playground.sdui.action.LocalServerDrivenUiActionHandler
import dev.helw.playground.sdui.action.OnClick
import dev.helw.playground.sdui.action.OnViewed
import dev.helw.playground.sdui.design.core.color.LocalBackgroundColors
/**
* Used only by Desktop and Web
*/
@Composable
internal fun FullScreenDemo(modifier: Modifier = Modifier) {
val actionHandler = object : ActionHandler {
var text: String = ""
override suspend fun onClick(action: OnClick) {
text = when (action) {
is OnClick.Deeplink -> {
"Deeplink to ${action.deeplink}"
}
is OnClick.InteractionEvent -> {
"Interaction Event\nname: ${action.eventName}, data: ${action.data}"
}
}
println("--------> ONCLICK: $text")
}
override suspend fun onViewed(action: OnViewed) {
text = when (action) {
is OnViewed.ImpressionEvent -> {
"Impression Event\nname: ${action.eventName}, data: ${action.data}"
}
}
println("--------> ONVIEWED: $text")
}
}
CompositionLocalProvider(LocalServerDrivenUiActionHandler provides actionHandler) {
Surface(modifier = modifier.fillMaxSize()) {
var destination by remember { mutableStateOf(NavigationGraph[0]) }
Column(modifier = Modifier.fillMaxSize()) {
Row(modifier = Modifier.fillMaxWidth()) {
MainDemo(
graph = NavigationGraph,
modifier = Modifier.weight(2f),
onClick = { destination = it })
Spacer(
modifier = Modifier
.width(1.dp)
.fillMaxHeight()
.background(color = LocalBackgroundColors.current.primary.color)
)
destination.content.invoke(
Modifier
.weight(3f)
.padding(horizontal = 16.dp)
.padding(top = 16.dp)
)
}
}
}
}
}
| 0 | Kotlin | 0 | 3 | d9e02bcf1251834fe34518f7109b21a5ae7960f5 | 3,407 | sdui | MIT License |
src/main/java/me/han/muffin/client/imixin/netty/packet/server/ISPacketCloseWindow.kt | SmallFishDD | 425,272,585 | false | {"Kotlin": 1725682, "Java": 943392, "GLSL": 15937} | package me.han.muffin.client.imixin.netty.packet.server
interface ISPacketCloseWindow {
var windowId: Int
} | 1 | Kotlin | 2 | 2 | 13235eada9edd9ccca039dea4d3a59cc7a930830 | 112 | muffin-0.10.4-src-leaked | MIT License |
app/src/main/java/com/arjun/samachar/ui/base/AppNavigation.kt | ArjunJadeja | 826,162,538 | false | {"Kotlin": 141881} | package com.arjun.samachar.ui.base
import android.content.Context
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.arjun.samachar.ui.MainViewModel
import com.arjun.samachar.ui.headlines.bookmark.BookmarksScreen
import com.arjun.samachar.ui.headlines.home.HomeScreen
import com.arjun.samachar.ui.headlines.offline.OfflineScreen
import com.arjun.samachar.ui.headlines.search.SearchScreen
sealed class Route(val name: String) {
data object HomeScreen : Route(name = "home_screen")
data object SearchScreen : Route(name = "search_screen")
data object BookmarksScreen : Route(name = "bookmarks_screen")
data object OfflineScreen : Route(name = "offline_screen")
}
@Composable
fun AppNavHost(
mainViewModel: MainViewModel,
customTabsIntent: CustomTabsIntent
) {
val navController = rememberNavController()
val context = LocalContext.current
NavHost(
navController = navController,
startDestination = Route.HomeScreen.name
) {
composable(route = Route.HomeScreen.name) {
HomeScreen(
context = context,
navController = navController,
mainViewModel = mainViewModel
) {
openCustomChromeTab(
customTabsIntent = customTabsIntent,
context = context,
url = it
)
}
}
composable(route = Route.SearchScreen.name) {
SearchScreen(
context = context,
navController = navController,
mainViewModel = mainViewModel
) {
openCustomChromeTab(
customTabsIntent = customTabsIntent,
context = context,
url = it
)
}
}
composable(route = Route.BookmarksScreen.name) {
BookmarksScreen(context = context, navController = navController) {
openCustomChromeTab(
customTabsIntent = customTabsIntent,
context = context,
url = it
)
}
}
composable(route = Route.OfflineScreen.name) {
OfflineScreen(context = context, navController = navController) {
openCustomChromeTab(
customTabsIntent = customTabsIntent,
context = context,
url = it
)
}
}
}
}
fun openCustomChromeTab(customTabsIntent: CustomTabsIntent, context: Context, url: String) {
customTabsIntent.launchUrl(context, Uri.parse(url))
}
| 0 | Kotlin | 7 | 50 | 38ea4dce5b3e32fdd9bc6d5546045800434836e5 | 2,945 | samachar | The Unlicense |
src/test/kotlin/kotlinmud/action/impl/admin/room/RoomBriefTest.kt | danielmunro | 241,230,796 | false | null | package kotlinmud.action.impl.admin.room
import assertk.assertThat
import assertk.assertions.isEqualTo
import kotlinmud.test.helper.createTestService
import org.junit.Test
class RoomBriefTest {
@Test
fun testCanChangeRoomBrief() {
// setup
val test = createTestService()
// given
val room = test.getStartRoom()
val model = test.getStartRoomModel()
val brief = "a decaying dock going out to a pond"
// when
test.runActionAsAdmin("room brief $brief")
// then
assertThat(room.brief).isEqualTo(brief)
assertThat(model.name).isEqualTo(brief)
}
}
| 0 | Kotlin | 1 | 9 | b7ee0d21ae813990896b1b8c6703da9bd1f1fc5b | 646 | kotlinmud | MIT License |
hoard/src/main/java/com/github/popalay/hoard/fetchpolicy/FetchPolicy.kt | Popalay | 134,461,747 | false | {"Kotlin": 25031} | package com.github.popalay.hoard.fetchpolicy
/**
* Created by <NAME> on 18.12.2017
* Copyright (c) 2017. All right reserved
*/
interface FetchPolicy<in RAW> {
fun onFetched(data: RAW)
fun shouldFetch(data: RAW): Boolean
} | 2 | Kotlin | 0 | 7 | 936d4f9aef3ccae6c868b07ec357955c490a3b04 | 235 | Hoard | Apache License 2.0 |
tmp/arrays/youTrackTests/6333.kt | DaniilStepanov | 228,623,440 | false | null | // Original bug: KT-30516
class KotlinNativeFramework {
fun helloFromKotlin() : String {
var x = 0
repeat(10) {
x++
}
return "Hello from Kotlin! $x"
}
}
| 1 | null | 1 | 1 | 602285ec60b01eee473dcb0b08ce497b1c254983 | 182 | bbfgradle | Apache License 2.0 |
liquidators/aave-liquidator/src/main/java/io/defitrack/mev/liquidation/HealthFactorUpdater.kt | decentri-fi | 462,678,154 | false | null | package io.defitrack.mev.liquidation
import io.defitrack.mev.chains.contract.multicall.MultiCallElement
import io.defitrack.mev.chains.polygon.config.PolygonContractAccessor
import io.defitrack.mev.common.FormatUtilsExtensions.asEth
import io.defitrack.mev.protocols.aave.AaveService
import io.defitrack.mev.protocols.aave.UserAccountData
import io.defitrack.mev.user.UserService
import io.defitrack.mev.user.domain.AaveUser
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.math.BigInteger
@Component
@ConditionalOnProperty(value = ["flags.health-factor-updater"], havingValue = "true", matchIfMissing = true)
class HealthFactorUpdater(
private val userService: UserService,
private val aaveService: AaveService,
private val polygonContractAccessor: PolygonContractAccessor
) {
private val log: Logger = LoggerFactory.getLogger(this::class.java)
@Scheduled(fixedDelay = 2000)
fun updateUserHFs() {
val chunked = userService.getAlllUsers().chunked(500)
chunked.parallelStream().forEach {
updateHfs(it)
}
}
private fun updateHfs(it: List<AaveUser>) {
try {
getHealthFactor(it).forEachIndexed { index, result ->
updateHf(it[index], result.healthFactor?.asEth() ?: -1.0)
}
} catch (ex: Exception) {
log.error("unable to update hf: {}", ex.message)
}
}
private fun updateHf(
user: AaveUser,
hf: Double
) {
userService.updateUserHF(user, hf)
}
private fun getHealthFactor(users: List<AaveUser>) = getUserAccountData(users.map {
it.address
})
private fun getUserAccountData(
users: List<String>
): List<UserAccountData> {
return polygonContractAccessor.readMultiCall(
users.map {
MultiCallElement(
aaveService.lendingPoolContract.getUserAccountDataFunction(it),
aaveService.lendingPoolContract.address
)
}
).map {
with(it) {
UserAccountData(
this[0].value as BigInteger,
this[1].value as BigInteger,
this[2].value as BigInteger,
this[3].value as BigInteger,
this[4].value as BigInteger,
this[5].value as BigInteger
)
}
}
}
} | 0 | Kotlin | 0 | 0 | 975b929c95013fe9f999966002947d7987204466 | 2,644 | mev-infrastructure | MIT License |
androidApp/src/main/java/dev/avatsav/linkding/android/extensions/Modifiers.kt | avatsav | 576,855,763 | false | null | package dev.avatsav.linkding.android.extensions
import androidx.compose.ui.Modifier
fun Modifier.onCondition(condition: Boolean, modifier: Modifier.() -> Modifier): Modifier {
return then(if (condition) modifier() else this)
}
| 2 | Kotlin | 0 | 5 | 2cb7619829ef7d622cd20c39b8436a1110f21008 | 233 | linkding-apps | MIT License |
app/src/main/java/com/gaugustini/vort/model/SimpleArmorPiece.kt | gaugustini | 416,395,415 | false | null | package com.gaugustini.vort.model
import androidx.room.ColumnInfo
/**
* A class used to represent [ArmorPiece] with less data.
*/
data class SimpleArmorPiece(
val id: Int,
val slots: Int,
@ColumnInfo(name = "skill_one") val skillOne: Int?,
@ColumnInfo(name = "skill_one_points") val skillOnePoints: Int?,
@ColumnInfo(name = "skill_two") val skillTwo: Int?,
@ColumnInfo(name = "skill_two_points") val skillTwoPoints: Int?,
@ColumnInfo(name = "skill_three") val skillThree: Int?,
@ColumnInfo(name = "skill_three_points") val skillThreePoints: Int?,
@ColumnInfo(name = "skill_four") val skillFour: Int?,
@ColumnInfo(name = "skill_four_points") val skillFourPoints: Int?,
@ColumnInfo(name = "skill_five") val skillFive: Int?,
@ColumnInfo(name = "skill_five_points") val skillFivePoints: Int?,
) {
/**
* Returns points from a given skill.
*/
fun getPoints(skill: Int): Int {
if (skill == skillOne) return skillOnePoints ?: 0
if (skill == skillTwo) return skillTwoPoints ?: 0
if (skill == skillThree) return skillThreePoints ?: 0
if (skill == skillFour) return skillFourPoints ?: 0
if (skill == skillFive) return skillFivePoints ?: 0
return 0
}
}
| 0 | Kotlin | 0 | 0 | 2f26bb863801caab95733511c6683b527ef33f35 | 1,265 | vort | MIT License |
app/src/main/java/repo/pattimuradev/fsearch/view/fragment/ChatDaftarPenggunaFragment.kt | PattimuraDev | 638,790,083 | false | null | package repo.pattimuradev.fsearch.view.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.fragment_chat_daftar_pengguna.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import repo.pattimuradev.fsearch.R
import repo.pattimuradev.fsearch.misc.DaftarPenggunaClickListener
import repo.pattimuradev.fsearch.misc.DateAndTimeHandler
import repo.pattimuradev.fsearch.model.UserProfile
import repo.pattimuradev.fsearch.view.adapter.DaftarPenggunaAdapter
import repo.pattimuradev.fsearch.viewmodel.ChatViewModel
import repo.pattimuradev.fsearch.viewmodel.UserViewModel
class ChatDaftarPenggunaFragment : Fragment(), DaftarPenggunaClickListener {
private lateinit var daftarPenggunaAdapter: DaftarPenggunaAdapter
private val userViewModel: UserViewModel by viewModels()
private val chatViewModel: ChatViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_chat_daftar_pengguna, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
chat_daftar_pengguna_button_back.setOnClickListener {
Navigation.findNavController(requireView()).navigate(R.id.action_chatDaftarPenggunaFragment_to_chatFragment)
}
// handle back button
activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner, object: OnBackPressedCallback(true){
override fun handleOnBackPressed() {
Navigation.findNavController(requireView()).navigate(R.id.action_chatDaftarPenggunaFragment_to_chatFragment)
}
})
initAdapter()
}
/**
* Fungsi untuk menginisiasi data pengguna yang tampil di halaman chat
* @author PattimuraDev (<NAME>)
*/
private fun initAdapter() {
daftarPenggunaAdapter = DaftarPenggunaAdapter(this)
rv_daftar_pengguna_halaman_chat.layoutManager = LinearLayoutManager(requireContext())
rv_daftar_pengguna_halaman_chat.adapter = daftarPenggunaAdapter
viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO){
userViewModel.getAllUser()
}
userViewModel.currentUserProfile.observe(viewLifecycleOwner){ currentUserProfile ->
daftarPenggunaAdapter.setUserId(currentUserProfile.id!!)
daftarPenggunaAdapter.notifyDataSetChanged()
userViewModel.allUser.observe(viewLifecycleOwner){ listUser ->
val result = mutableListOf<UserProfile>()
for(i in listUser){
if(i.id!! != currentUserProfile.id){
result += i
}
}
daftarPenggunaAdapter.setListPengguna(result)
daftarPenggunaAdapter.notifyDataSetChanged()
}
}
}
override fun clickOnLikeButton(item: UserProfile, position: Int) {
// nothing to do
}
override fun clickOnDaftarPenggunaBody(item: UserProfile, position: Int) {
userViewModel.currentUserProfile.observe(viewLifecycleOwner){ currentUsserProfile ->
viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO){
chatViewModel.addEmptyChatRoom(
currentUsserProfile.id!!,
item.id!!,
currentUsserProfile.urlFoto,
item.urlFoto,
currentUsserProfile.nama,
item.nama,
DateAndTimeHandler.currentDate().time
)
}
chatViewModel.newEmptyChatRoom.observe(viewLifecycleOwner){ chatRoom ->
val posisiCurrentUser = chatRoom.personInChat.indexOf(currentUsserProfile.id)
val bundle = Bundle()
bundle.putParcelable("chat_room_data", chatRoom)
bundle.putInt("chat_posisi_user", posisiCurrentUser)
Navigation.findNavController(requireView()).navigate(R.id.action_chatDaftarPenggunaFragment_to_ruangObrolanFragment, bundle)
}
}
}
} | 0 | Kotlin | 0 | 1 | ba0642322a4bfb0ad0b874febf12faee6877cf9c | 4,624 | FSearch | Apache License 2.0 |
app/src/main/java/com/dcrtns/adnotebook/Key.kt | renedeanda | 271,965,465 | false | null | package com.dcrtns.adnotebook
object Key {
const val ADNOTE = "adnote"
const val IS_EDITING = "is_editing"
const val THEME_KEY = "theme_key"
const val INVITE_FRIENDS = "invite_friends"
const val RATING_LINK = "rating_link"
const val FEEDBACK_LINK = "feedback_link"
const val DEV_LINK = "dev_link"
const val DELIGHTFUL_LINK = "delightful_link"
const val MAIN_RECYCLER_POSITION = "main_recycler_position"
} | 1 | Kotlin | 1 | 3 | de450c7d6a65f84538777f67c6cbf74d0c74399a | 441 | AdNotes | Apache License 2.0 |
marketpay/src/main/java/com/arefbhrn/marketpay/exception/MarketNotFoundException.kt | arefbhrn | 260,071,686 | false | null | package com.arefbhrn.marketpay.exception
import com.arefbhrn.marketpay.BillingConnection
class MarketNotFoundException : IllegalStateException() {
override val message: String?
get() = BillingConnection.MARKET_NAME + " is not installed"
}
| 0 | Kotlin | 0 | 1 | a0f74e013bd6a4742e331ee05fb03859dda584fd | 255 | MarketPay | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/application/api/ApiFeature.kt | navikt | 270,656,175 | false | null | package no.nav.syfo.application.api
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import io.ktor.server.application.*
import io.ktor.http.*
import io.ktor.serialization.jackson.*
import io.ktor.server.metrics.micrometer.*
import io.ktor.server.plugins.callid.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.response.*
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig
import no.nav.syfo.application.metric.METRICS_REGISTRY
import no.nav.syfo.util.*
import java.time.Duration
import java.util.*
fun Application.installCallId() {
install(CallId) {
retrieve { it.request.headers[NAV_CALL_ID_HEADER] }
generate { UUID.randomUUID().toString() }
verify { callId: String -> callId.isNotEmpty() }
header(NAV_CALL_ID_HEADER)
}
}
fun Application.installContentNegotiation() {
install(ContentNegotiation) {
jackson {
registerKotlinModule()
registerModule(JavaTimeModule())
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
}
}
}
fun Application.installMetrics() {
install(MicrometerMetrics) {
registry = METRICS_REGISTRY
distributionStatisticConfig = DistributionStatisticConfig.Builder()
.percentilesHistogram(true)
.maximumExpectedValue(Duration.ofSeconds(20).toNanos().toDouble())
.build()
}
}
fun Application.installStatusPages() {
install(StatusPages) {
exception<Throwable> { call, cause ->
call.respond(HttpStatusCode.InternalServerError, cause.message ?: "Unknown error")
call.application.log.error("Caught exception {} {} {}", cause, call.getCallId(), call.getConsumerId())
throw cause
}
}
}
| 3 | Kotlin | 0 | 0 | 3a67e239a123504f6cf81866afd29dc88f38eb74 | 2,107 | ispengestopp | MIT License |
app/src/main/java/com/heyanle/easybangumi4/compose/setting/Setting.kt | easybangumiorg | 413,723,669 | false | null | package com.heyanle.easybangumi4.ui.setting
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.res.stringResource
import com.heyanle.easy_i18n.R
import com.heyanle.easybangumi4.LocalNavController
/**
* Created by HeYanLe on 2023/8/5 23:02.
* https://github.com/heyanLE
*/
sealed class SettingPage(
val router: String,
val title: @Composable () -> Unit,
val content: @Composable ColumnScope.(NestedScrollConnection) -> Unit,
) {
object Appearance : SettingPage("appearance", {
Text(text = stringResource(id = R.string.appearance_setting))
}, {
AppearanceSetting(it)
})
object Player : SettingPage("player", {
Text(text = stringResource(id = R.string.player_setting))
}, {
PlayerSetting(nestedScrollConnection = it)
})
}
val settingPages = mapOf(
SettingPage.Appearance.router to SettingPage.Appearance,
SettingPage.Player.router to SettingPage.Player,
)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Setting(
router: String
) {
val nav = LocalNavController.current
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior()
settingPages[router]?.let { settingPage ->
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
contentColor = MaterialTheme.colorScheme.onBackground
) {
Column {
TopAppBar(
title = settingPage.title,
navigationIcon = {
IconButton(onClick = {
nav.popBackStack()
}) {
Icon(
imageVector = Icons.Filled.ArrowBack,
stringResource(id = R.string.back)
)
}
},
scrollBehavior = scrollBehavior
)
settingPage.content(
this,
scrollBehavior.nestedScrollConnection
)
}
}
}
} | 8 | null | 57 | 977 | e93dd2933af9c693e5d6730833651b3e2caea553 | 2,881 | EasyBangumi | Apache License 2.0 |
Kotlin/src/main/kotlin/domain/MessageReader.kt | adrrriannn | 258,185,660 | false | {"C++": 724486, "XSLT": 19568, "Pascal": 16226, "C#": 13851, "PLpgSQL": 10627, "C": 9261, "Smalltalk": 8793, "ABAP": 8568, "Java": 8402, "F#": 8361, "PHP": 7763, "Ada": 7270, "JavaScript": 7008, "Kotlin": 6507, "Common Lisp": 6116, "CMake": 5564, "Scheme": 5368, "Swift": 4964, "Groovy": 4478, "PLSQL": 4471, "Erlang": 4392, "Perl": 4384, "D": 4258, "COBOL": 4067, "TypeScript": 3925, "Haskell": 3880, "Rust": 3786, "Makefile": 3644, "Ruby": 3448, "Python": 3402, "Scala": 3343, "Raku": 3281, "R": 3160, "Elixir": 2885, "TSQL": 2870, "Go": 2568, "Elm": 2363, "Dart": 2148, "Shell": 1132, "Dockerfile": 500, "SQLPL": 133} | package domain
import MessageRepository
class MessageReader(val messageRepository: MessageRepository) {
operator fun invoke(user: User): Posts {
return messageRepository.findByUser(user)
}
}
| 12 | C++ | 0 | 0 | e0ee30fc6625091d246a7225fd9edfd95716f6e4 | 210 | CokaidoKata | MIT License |
app/src/main/java/io/filmtime/MainActivity.kt | moallemi | 633,160,161 | false | {"Kotlin": 190120, "Shell": 35} | package io.filmtime
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.navigation.compose.rememberNavController
import dagger.hilt.android.AndroidEntryPoint
import io.filmtime.ui.FilmTimeApp
import io.filmtime.ui.theme.FilmTimeTheme
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
FilmTimeTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
) {
FilmTimeApp(
navController = rememberNavController(),
)
}
}
}
}
}
| 11 | Kotlin | 9 | 34 | 44749b018a1a96ac87474f313b82b34fbefcc3d2 | 936 | Film-Time | MIT License |
app/src/main/java/io/filmtime/MainActivity.kt | moallemi | 633,160,161 | false | {"Kotlin": 190120, "Shell": 35} | package io.filmtime
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.navigation.compose.rememberNavController
import dagger.hilt.android.AndroidEntryPoint
import io.filmtime.ui.FilmTimeApp
import io.filmtime.ui.theme.FilmTimeTheme
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
FilmTimeTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background,
) {
FilmTimeApp(
navController = rememberNavController(),
)
}
}
}
}
}
| 11 | Kotlin | 9 | 34 | 44749b018a1a96ac87474f313b82b34fbefcc3d2 | 936 | Film-Time | MIT License |
ok-propertysale-be-business-logic/src/main/kotlin/ru/otus/otuskotlin/propertysale/be/business/logic/HouseCrud.kt | otuskotlin | 330,109,804 | false | null | package ru.otus.otuskotlin.propertysale.be.business.logic
import ru.otus.otuskotlin.propertysale.be.business.logic.pipelines.house.HouseCreate
import ru.otus.otuskotlin.propertysale.be.business.logic.pipelines.house.HouseDelete
import ru.otus.otuskotlin.propertysale.be.business.logic.pipelines.house.HouseFilter
import ru.otus.otuskotlin.propertysale.be.business.logic.pipelines.house.HouseRead
import ru.otus.otuskotlin.propertysale.be.business.logic.pipelines.house.HouseUpdate
import ru.otus.otuskotlin.propertysale.be.common.context.BePsContext
import ru.otus.otuskotlin.propertysale.be.common.repositories.IFlatRepository
import ru.otus.otuskotlin.propertysale.be.common.repositories.IHouseRepository
import ru.otus.otuskotlin.propertysale.be.common.repositories.IRoomRepository
class HouseCrud(
private val flatRepoTest: IFlatRepository = IFlatRepository.NONE,
private val flatRepoProd: IFlatRepository = IFlatRepository.NONE,
private val houseRepoTest: IHouseRepository = IHouseRepository.NONE,
private val houseRepoProd: IHouseRepository = IHouseRepository.NONE,
private val roomRepoTest: IRoomRepository = IRoomRepository.NONE,
private val roomRepoProd: IRoomRepository = IRoomRepository.NONE,
) {
suspend fun list(context: BePsContext) {
HouseFilter.execute(context.apply(this::configureContext))
}
suspend fun create(context: BePsContext) {
HouseCreate.execute(context.apply(this::configureContext))
}
suspend fun read(context: BePsContext) {
HouseRead.execute(context.apply(this::configureContext))
}
suspend fun update(context: BePsContext) {
HouseUpdate.execute(context.apply(this::configureContext))
}
suspend fun delete(context: BePsContext) {
HouseDelete.execute(context.apply(this::configureContext))
}
private fun configureContext(context: BePsContext) {
context.flatRepoTest = flatRepoTest
context.flatRepoProd = flatRepoProd
context.houseRepoTest = houseRepoTest
context.houseRepoProd = houseRepoProd
context.roomRepoTest = roomRepoTest
context.roomRepoProd = roomRepoProd
}
}
| 0 | Kotlin | 0 | 1 | ed9a38627e64ed36131280ca7449547ba1d06829 | 2,166 | otuskotlin-202012-propertysale-ks | MIT License |
app/src/main/java/org/openedx/app/OpenEdXApp.kt | openedx | 613,282,821 | false | {"Kotlin": 2073675, "Groovy": 5883, "JavaScript": 1129} | package org.openedx.app
import android.app.Application
import com.braze.Braze
import com.braze.configuration.BrazeConfig
import com.google.firebase.FirebaseApp
import io.branch.referral.Branch
import org.koin.android.ext.android.inject
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
import org.openedx.app.di.appModule
import org.openedx.app.di.networkingModule
import org.openedx.app.di.screenModule
import org.openedx.core.config.Config
class OpenEdXApp : Application() {
private val config by inject<Config>()
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@OpenEdXApp)
modules(
appModule,
networkingModule,
screenModule
)
}
if (config.getFirebaseConfig().enabled) {
FirebaseApp.initializeApp(this)
}
if (config.getBranchConfig().enabled) {
if (BuildConfig.DEBUG) {
Branch.enableTestMode()
Branch.enableLogging()
}
Branch.getAutoInstance(this)
}
if (config.getBrazeConfig().isEnabled && config.getFirebaseConfig().enabled) {
val isCloudMessagingEnabled = config.getFirebaseConfig().isCloudMessagingEnabled &&
config.getBrazeConfig().isPushNotificationsEnabled
val brazeConfig = BrazeConfig.Builder()
.setIsFirebaseCloudMessagingRegistrationEnabled(isCloudMessagingEnabled)
.setFirebaseCloudMessagingSenderIdKey(config.getFirebaseConfig().projectNumber)
.setHandlePushDeepLinksAutomatically(true)
.setIsFirebaseMessagingServiceOnNewTokenRegistrationEnabled(true)
.build()
Braze.configure(this, brazeConfig)
}
}
}
| 85 | Kotlin | 23 | 18 | 4d36310011d20ce0fe896ae4e4d3ca2148f322b6 | 1,873 | openedx-app-android | Apache License 2.0 |
graph/graph-core-model/src/main/kotlin/org/orkg/graph/domain/BundleConfiguration.kt | TIBHannover | 197,416,205 | false | {"Kotlin": 2966676, "Cypher": 216833, "Python": 4881, "Groovy": 1936, "Shell": 1803, "HTML": 240} | package org.orkg.graph.domain
import org.orkg.common.ThingId
/**
* A Bundle configuration class containing the min and max levels to be fetched
* Also the list of classes to be white-listed or black-listed during the fetch
* @param minLevel the minimum level to be fetched (if not provided it is set to 0)
* @param maxLevel the maximum level of statements to be fetched (if not provided, all child statements will be fetched)
* @param blacklist the list of classes to be black-listed (i.e. not fetched), these classes are checked on the subjects and objects of a statement
* @param whitelist the list of classes to be white-listed (i.e. the only ones to be fetched), these classes are checked on the subjects and objects of a statement
*/
data class BundleConfiguration(
val minLevel: Int?,
val maxLevel: Int?,
val blacklist: kotlin.collections.List<ThingId>,
val whitelist: kotlin.collections.List<ThingId>
) {
companion object Factory {
fun firstLevelConf(): BundleConfiguration =
BundleConfiguration(minLevel = null, maxLevel = 1, blacklist = emptyList(), whitelist = emptyList())
}
}
| 0 | Kotlin | 1 | 5 | f9de52bdf498fdc200e7f655a52cecff215c1949 | 1,142 | orkg-backend | MIT License |
src/main/kotlin/com/vv/life/publish/nexus/NexusService.kt | willpyshan13 | 272,149,126 | false | null | package com.vv.life.publish.nexus
import com.vv.life.publish.nexus.model.ProfileRepositoriesResponse
import com.vv.life.publish.nexus.model.Repository
import com.vv.life.publish.nexus.model.TransitionRepositoryInput
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
/* Nexus service definition based on the incomplete documentation at:
* -Nexus STAGING API: https://oss.sonatype.org/nexus-staging-plugin/default/docs/index.html
* -Nexus CORE API: https://repository.sonatype.org/nexus-restlet1x-plugin/default/docs/index.html
*/
interface NexusService {
@GET("staging/profile_repositories")
fun getProfileRepositories(): Call<ProfileRepositoriesResponse>
@GET("staging/repository/{repositoryId}")
fun getRepository(@Path("repositoryId") repositoryId: String): Call<Repository>
@POST("staging/bulk/close")
fun closeRepository(@Body input: TransitionRepositoryInput): Call<Unit>
@POST("staging/bulk/promote")
fun releaseRepository(@Body input: TransitionRepositoryInput): Call<Unit>
}
| 0 | Kotlin | 0 | 1 | e438da05c746a5f15df6fbc9850b411060a64d94 | 1,086 | gradle-publish-plugin | Apache License 2.0 |
app/src/androidTest/java/com/ibtikar/mvvm_starter_koin_coroutines/scenarios/ArticleDetailsScreenScenario.kt | KhaledSherifSayed | 375,848,364 | false | null | package com.ibtikar.mvvm_starter_koin_coroutines.scenarios
import com.ibtikar.mvvm_starter_koin_coroutines.articleDetails.ArticleDetailsScreen
import com.kaspersky.kaspresso.testcases.api.scenario.Scenario
import com.kaspersky.kaspresso.testcases.core.testcontext.TestContext
/**
* Created by Meslmawy on 2/8/2021
*/
class ArticleDetailsScreenScenario : Scenario() {
val detailsScreen = ArticleDetailsScreen()
override val steps: TestContext<Unit>.() -> Unit = {
detailsScreen {
step("make sure first item is visible and has data") {
name {
isVisible()
hasAnyText()
}
image {
isVisible()
}
knonw_as {
isVisible()
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 701fcea68ed7da29416c850495b632751ed31e53 | 858 | NY-Times-Popular-Articles | The Unlicense |
new-tab-page/new-tab-page-impl/src/main/java/com/duckduckgo/newtabpage/impl/view/NewTabPageView.kt | duckduckgo | 78,869,127 | false | null | /*
* Copyright (c) 2024 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.newtabpage.impl.view
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import androidx.core.view.children
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.findViewTreeViewModelStoreOwner
import com.duckduckgo.anvil.annotations.InjectWith
import com.duckduckgo.browser.api.ui.BrowserScreens.NewTabSettingsScreenNoParams
import com.duckduckgo.common.ui.view.gone
import com.duckduckgo.common.ui.view.hide
import com.duckduckgo.common.ui.view.hideKeyboard
import com.duckduckgo.common.ui.view.show
import com.duckduckgo.common.ui.viewbinding.viewBinding
import com.duckduckgo.common.utils.ViewViewModelFactory
import com.duckduckgo.di.scopes.ViewScope
import com.duckduckgo.navigation.api.GlobalActivityStarter
import com.duckduckgo.newtabpage.api.NewTabPageSection
import com.duckduckgo.newtabpage.impl.databinding.ViewNewTabPageBinding
import com.duckduckgo.newtabpage.impl.view.NewTabPageViewModel.ViewState
import dagger.android.support.AndroidSupportInjection
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import logcat.logcat
@InjectWith(ViewScope::class)
class NewTabPageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
) : LinearLayout(context, attrs, defStyle) {
@Inject
lateinit var viewModelFactory: ViewViewModelFactory
@Inject
lateinit var globalActivityStarter: GlobalActivityStarter
private var coroutineScope: CoroutineScope? = null
private val binding: ViewNewTabPageBinding by viewBinding()
private val viewModel: NewTabPageViewModel by lazy {
ViewModelProvider(findViewTreeViewModelStoreOwner()!!, viewModelFactory)[NewTabPageViewModel::class.java]
}
override fun onAttachedToWindow() {
AndroidSupportInjection.inject(this)
super.onAttachedToWindow()
findViewTreeLifecycleOwner()?.lifecycle?.addObserver(viewModel)
@SuppressLint("NoHardcodedCoroutineDispatcher")
coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
viewModel.viewState
.onEach { render(it) }
.launchIn(coroutineScope!!)
setClickListeners()
setAnimationListeners()
}
private fun render(viewState: ViewState) {
logcat { "New Tab Render: loading: ${viewState.loading} showDax: ${viewState.showDax} sections: ${viewState.sections.size}" }
if (viewState.loading) {
binding.newTabContentShimmer.startShimmer()
} else {
if (viewState.showDax) {
binding.ddgLogo.show()
} else {
binding.ddgLogo.gone()
}
if (viewState.sections.isEmpty()) {
binding.newTabContentShimmer.gone()
binding.newTabSectionsContent.gone()
} else {
binding.newTabSectionsContent.setOnHierarchyChangeListener(
object : OnHierarchyChangeListener {
var childsAdded = 0
override fun onChildViewAdded(
p0: View?,
p1: View?,
) {
childsAdded++
logcat { "New Tab Render: child added $childsAdded" }
if (childsAdded == viewState.sections.size) {
binding.newTabContentShimmer.gone()
binding.newTabSectionsContent.show()
}
}
override fun onChildViewRemoved(
p0: View?,
p1: View?,
) {
}
},
)
// we only want to make changes if the sections have changed
val existingSections = binding.newTabSectionsContent.children.map { it.tag }.toMutableList()
val newSections = viewState.sections.map { it.name }
if (existingSections != newSections) {
// RMF is a special case, we don't want to remove it.
// We can only show that message once, so removing the view and adding it again won't work
val rmfView = binding.newTabSectionsContent.findViewWithTag<View>(NewTabPageSection.REMOTE_MESSAGING_FRAMEWORK.name)
if (rmfView != null) {
binding.newTabSectionsContent.removeViews(1, binding.newTabSectionsContent.childCount - 1)
} else {
binding.newTabSectionsContent.removeAllViews()
}
}
// we will only add sections that haven't been added yet
viewState.sections.onEach { section ->
val sectionView = binding.newTabSectionsContent.findViewWithTag<View>(section.name)
if (sectionView == null) {
binding.newTabSectionsContent.addView(
section.getView(context).also { it?.tag = section.name },
android.view.ViewGroup.LayoutParams(
android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
),
)
}
}
binding.newTabSectionsContent.show()
}
}
}
private fun setClickListeners() {
binding.newTabEditScroll.setOnClickListener {
viewModel.onCustomisePageClicked()
globalActivityStarter.start(context, NewTabSettingsScreenNoParams)
}
binding.newTabEditAnchor.setOnClickListener {
viewModel.onCustomisePageClicked()
globalActivityStarter.start(context, NewTabSettingsScreenNoParams)
}
}
private fun setAnimationListeners() {
binding.newTabContentScroll.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
binding.root.requestFocus()
binding.root.hideKeyboard()
}
binding.newTabContentScroll.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
val rect = Rect()
binding.root.getWindowVisibleDisplayFrame(rect)
val screenHeight = binding.root.rootView.height
val keypadHeight = screenHeight - rect.bottom
// If the change in screen
if (keypadHeight > screenHeight * 0.15) {
binding.newTabEditAnchor.hide()
} else {
// If the scrollView can scroll, hide the button
if (binding.newTabContentScroll.canScrollVertically(1) || binding.newTabContentScroll.canScrollVertically(-1)) {
binding.newTabEditAnchor.hide()
binding.newTabEditScroll.show()
} else {
binding.newTabEditAnchor.show()
binding.newTabEditScroll.hide()
}
}
}
}
}
| 67 | null | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 8,142 | Android | Apache License 2.0 |
flv-processing/src/main/kotlin/github/hua0512/flv/utils/StreamFetcher.kt | stream-rec | 756,063,189 | false | {"Kotlin": 1127068, "Dockerfile": 1856} | /*
* MIT License
*
* Stream-rec https://github.com/hua0512/stream-rec
*
* Copyright (c) 2024 hua0512 (https://github.com/hua0512)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package github.hua0512.flv.utils
import github.hua0512.flv.FlvReader
import github.hua0512.flv.data.FlvData
import github.hua0512.flv.data.FlvTag
import github.hua0512.plugins.StreamerContext
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.CancellationException
import io.ktor.utils.io.jvm.javaio.toInputStream
import io.ktor.utils.io.streams.asInput
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
/**
* Extension function to convert a ByteReadChannel to a Flow of FlvData.
* This function reads FLV data from the ByteReadChannel and emits it as a Flow of FlvData.
*
* @receiver ByteReadChannel The input ByteReadChannel to read FLV data from.
* @return Flow<FlvData> A Flow emitting FlvData objects read from the ByteReadChannel.
* @author hua0512
* @date : 2024/9/10 14:10
*/
fun ByteReadChannel.asStreamFlow(closeSource: Boolean = true, context: StreamerContext): Flow<FlvData> = flow {
val ins = [email protected]()
val flvReader = FlvReader(ins.asInput())
var tag: FlvData? = null
with(flvReader) {
try {
readHeader(::emit)
readTags {
tag = it
emit(it)
}
FlvReader.logger.debug("${context.name} End of stream")
} catch (e: Exception) {
// log other exceptions
if (e !is CancellationException) {
e.printStackTrace()
FlvReader.logger.error("${context.name} Exception: ${e.message}")
}
throw e
} finally {
if (closeSource) {
close()
}
(tag as? FlvTag)?.let {
if (it.isAvcEndSequence()) return@let
emit(
createEndOfSequenceTag(
it.num + 1,
it.header.timestamp,
it.header.streamId
)
)
}
tag = null
}
}
} | 13 | Kotlin | 47 | 540 | 719d517fe20af6fac6bbc4630d4be4f26d1381e7 | 3,011 | stream-rec | MIT License |
src/main/java/me/bytebeats/jsonmaster/util/GsonUtil.kt | bytebeats | 298,255,508 | false | {"Kotlin": 33695, "Java": 27630} | package me.bytebeats.jsonmaster.util
import com.google.gson.FieldNamingPolicy
import com.google.gson.GsonBuilder
import com.google.gson.JsonParser
import java.lang.RuntimeException
object GsonUtil {
@Throws(RuntimeException::class)
fun toPrettyString(raw: String): String {
val gson = GsonBuilder().setPrettyPrinting().create()
val jsonElement = JsonParser.parseString(raw)
return gson.toJson(jsonElement)
}
@Throws(Exception::class)
fun toCompactString(raw: String): String {
val gson = GsonBuilder().run {
setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
}.create()
val jsonElement = JsonParser.parseString(raw)
return gson.toJson(jsonElement)
}
} | 2 | Kotlin | 0 | 2 | 273f990add9b583e1074df674596a1a486c1b935 | 763 | JsonMaster | MIT License |
app/src/main/java/com/baljeet/expirytracker/fragment/shared/PdfViewModel.kt | baljeet808 | 391,490,393 | false | null | package com.baljeet.expirytracker.fragment.shared
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.baljeet.expirytracker.CustomApplication
class PdfViewModel(app : Application): AndroidViewModel(app) {
val context = getApplication<CustomApplication>()
} | 0 | Kotlin | 0 | 1 | c5dfa7efb0a18b49e415113ec420b10a18912157 | 297 | ExpiryTracker | Apache License 2.0 |
gremlin-kore/src/main/kotlin/org/apache/tinkerpop4/gremlin/process/remote/traversal/AbstractRemoteTraversal.kt | phreed | 449,920,526 | false | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop4.gremlin.process.remote.traversal
import org.apache.tinkerpop4.gremlin.process.remote.traversal.step.map.RemoteStep
/**
* This is a stub implementation for [RemoteTraversal] and requires that the [.nextTraverser] method
* is implemented from [Traversal.Admin]. It is this method that gets called from [RemoteStep] when
* the [Traversal] is iterated.
*
* @author <NAME> (http://stephen.genoprime.com)
*/
abstract class AbstractRemoteTraversal<S, E> : RemoteTraversal<S, E> {
/**
* Note that internally `#nextTraverser()` is called from within a loop (specifically in
* [AbstractStep.next] that breaks properly when a `NoSuchElementException` is thrown. In
* other words the "results" should be iterated to force that failure.
*/
@Override
abstract fun nextTraverser(): Traverser.Admin<E>?
@get:Override
@set:Override
var sideEffects: TraversalSideEffects
get() {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
set(sideEffects) {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
@get:Override
val bytecode: Bytecode
get() {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
@get:Override
val steps: List<Any>
get() {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
@Override
@Throws(IllegalStateException::class)
fun <S2, E2> addStep(index: Int, step: Step<*, *>?): Admin<S2, E2> {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
@Override
@Throws(IllegalStateException::class)
fun <S2, E2> removeStep(index: Int): Admin<S2, E2> {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
@Override
@Throws(IllegalStateException::class)
fun applyStrategies() {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
@get:Override
val traverserGenerator: TraverserGenerator
get() {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
@get:Override
val traverserRequirements: Set<Any>
get() {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
@get:Override
@set:Override
var strategies: TraversalStrategies
get() {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
set(strategies) {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
@get:Override
@set:Override
var parent: TraversalParent
get() {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
set(step) {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
@Override
fun clone(): Admin<S, E> {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
@get:Override
val isLocked: Boolean
get() {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
@get:Override
@set:Override
var graph: Optional<Graph>
get() {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
set(graph) {
throw UnsupportedOperationException("Remote traversals do not support this method")
}
} | 4 | null | 1 | 1 | cb6805d686e9a27caa8e597b0728a50a63dc9092 | 4,600 | tinkerpop4 | Apache License 2.0 |
android/src/main/kotlin/org/ar/rtm_engine/ArRtmPlugin.kt | anyRTC | 309,550,765 | false | null | package org.ar.rtm_engine
import android.content.Context
import android.os.Handler
import android.os.Looper
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
import org.ar.rtm.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
class ArRtmPlugin: MethodCallHandler {
private val registrar: Registrar
private val methodChannel: MethodChannel
private val eventHandler: Handler
private var nextClientIndex: Long = 0
private var clients = HashMap<Long, RTMClient>()
companion object {
@JvmStatic
fun registerWith(registrar: Registrar) {
val channel = MethodChannel(registrar.messenger(), "org.ar.rtm")
val plugin = ArRtmPlugin(registrar, channel)
channel.setMethodCallHandler(plugin)
}
}
constructor(registrar: Registrar, channel: MethodChannel) {
this.registrar = registrar
this.methodChannel = channel
this.eventHandler = Handler(Looper.getMainLooper())
}
private fun getActiveContext(): Context {
return when {
(registrar.activity() == null) -> registrar.context()
else -> registrar.activity()
}
}
private fun runMainThread(f: () -> Unit) {
eventHandler.post(f)
}
override fun onMethodCall(methodCall: MethodCall, result: Result) {
val methodName: String? = when {
methodCall.method is String -> methodCall.method as String
else -> null
}
val callArguments: Map<String, Any>? = when {
methodCall.arguments is Map<*, *> -> methodCall.arguments as Map<String, Any>
else -> null
}
val call: String? = when {
callArguments!!.get("call") is String -> callArguments.get("call") as String
else -> null
}
var params: Map<String, Any> = callArguments["params"] as Map<String, Any>
when (call) {
"static" -> {
handleStaticMethod(methodName, params, result)
}
"ARRtmClient" -> {
handleClientMethod(methodName, params, result)
}
"ARRtmChannel" -> {
handleChannelMethod(methodName, params, result)
}
else -> {
result.notImplemented()
}
}
}
private fun handleStaticMethod(methodName: String?, params: Map<String, Any>, result: MethodChannel.Result) {
when (methodName) {
"createInstance" -> {
val appId: String? = when {
params["appId"] is String -> params["appId"] as String
else -> null
}
if (null == appId) {
runMainThread {
result.success(hashMapOf("errorCode" to -1))
}
return
}
while (null != clients[nextClientIndex]) {
nextClientIndex++
}
val rtmClient = RTMClient(getActiveContext(), appId, nextClientIndex, registrar.messenger(), eventHandler)
result.success(hashMapOf(
"errorCode" to 0,
"index" to nextClientIndex
))
clients[nextClientIndex] = rtmClient
nextClientIndex++
}
"getSdkVersion" -> {
result.success(hashMapOf(
"errorCode" to 0,
"version" to RtmClient.getSdkVersion()
))
}
else -> {
result.notImplemented();
}
}
}
private fun handleClientMethod(methodName: String?, params: Map<String, Any>, result: Result) {
val clientIndex = (params["clientIndex"] as Int).toLong()
var args: Map<String, Any>? = when {
(params.get("args") is Map<*,*>) -> (params["args"] as Map<String, Any>)
else -> null
}
val rtmClient = when {
clients[clientIndex] is RTMClient -> clients[clientIndex] as RTMClient
else -> null
}
if (null == rtmClient) {
runMainThread {
result.success(hashMapOf("errorCode" to -1))
}
return
}
var client: RtmClient = rtmClient.client
when (methodName) {
"destroy" -> {
rtmClient.channels.forEach{
val pair = it.toPair()
pair.second.release()
}
rtmClient.channels.clear()
clients.remove(clientIndex)
runMainThread {
result.success(hashMapOf("errorCode" to 0))
}
}
"setLog" -> {
val relativePath = "/sdcard/${getActiveContext().packageName}"
val size: Int = when {
args?.get("size") is Int -> args.get("size") as Int
else -> 524288
}
val path: String? = when {
args?.get("path") is String -> "${relativePath}/${(args.get("path") as String)}"
else -> null
}
val level: Int = when {
args?.get("level") is Int -> args.get("level") as Int
else -> 0
}
runMainThread {
result.success(hashMapOf(
"errorCode" to 0,
"results" to hashMapOf(
"setLogFileSize" to client.setLogFileSize(size),
"setLogLevel" to client.setLogFilter(level),
"setLogFile" to client.setLogFile(path)
)
))
}
}
"login" -> {
var token = args?.get("token")
token = when {
(token is String) -> token
else -> ""
}
var userId = args?.get("userId")
userId = when {
(userId is String) -> userId
else -> ""
}
client.login(
token,
userId as String,
object: ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf("errorCode" to 0))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
}
)
}
"setParameters"->{
var params = args?.get("parameters")
params = when{
(params is String) ->params
else -> ""
}
client.setParameters(params)
}
"logout" -> {
client.logout(
object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf("errorCode" to 0))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
}
)
}
"queryPeersOnlineStatus" -> {
var peerIds: Set<String>? = (args?.get("peerIds") as ArrayList<String>).toSet()
client.queryPeersOnlineStatus(peerIds,
object : ResultCallback<MutableMap<String, Boolean>> {
override fun onSuccess(resp: MutableMap<String, Boolean>) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0,
"results" to resp
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
}
)
}
"sendMessageToPeer" -> {
var peerId: String? = args?.get("peerId") as String
var text = args.get("message") as String
val message = client.createMessage()
message.text = text
val options = SendMessageOptions().apply {
(args["historical"] as? Boolean)?.let {
enableHistoricalMessaging = it
}
(args["offline"] as? Boolean)?.let {
enableOfflineMessaging = it
}
}
if (peerId != null) {
client.sendMessageToPeer(peerId,
message,
options,
object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
}
)
}
}
"setLocalUserAttributes" -> {
val attributes: List<Map<String, String>>? = args?.get("attributes") as List<Map<String, String>>
var localUserAttributes = ArrayList<RtmAttribute>()
attributes!!.forEach {
var rtmAttribute = RtmAttribute()
rtmAttribute.key = it["key"]
rtmAttribute.value = it["value"]
localUserAttributes.add(rtmAttribute)
}
client.setLocalUserAttributes(localUserAttributes,
object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
}
)
}
"addOrUpdateLocalUserAttributes" -> {
val attributes: List<Map<String, String>>? = args?.get("attributes") as List<Map<String, String>>
var localUserAttributes = ArrayList<RtmAttribute>()
attributes!!.forEach {
var rtmAttribute = RtmAttribute()
rtmAttribute.key = it["key"]
rtmAttribute.value = it["value"]
localUserAttributes.add(rtmAttribute)
}
client.addOrUpdateLocalUserAttributes(localUserAttributes,
object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
}
)
}
"deleteLocalUserAttributesByKeys" -> {
val keys: List<String>? = args?.get("keys") as List<String>
client.deleteLocalUserAttributesByKeys(keys,
object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
}
)
}
"clearLocalUserAttributes" -> {
client.clearLocalUserAttributes(
object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
}
)
}
"getUserAttributes" -> {
val userId: String? = when {
args?.get("userId") is String -> args.get("userId") as String
else -> null
}
client.getUserAttributes(userId,
object : ResultCallback<List<RtmAttribute>> {
override fun onSuccess(resp: List<RtmAttribute>) {
var attributes: MutableMap<String, String> = HashMap<String, String>()
resp.map {
attributes[it.key] = it.value
}
runMainThread {
result.success(hashMapOf(
"errorCode" to 0,
"attributes" to attributes
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
})
}
"getUserAttributesByKeys" -> {
val userId: String? = when {
args?.get("userId") is String -> args.get("userId") as String
else -> null
}
var keys: List<String>? = when {
args?.get("keys") is List<*> -> args.get("keys") as List<String>
else -> null
}
client.getUserAttributesByKeys(userId,
keys,
object : ResultCallback<List<RtmAttribute>> {
override fun onSuccess(resp: List<RtmAttribute>) {
var attributes: MutableMap<String, String> = HashMap<String, String>()
resp.map {
attributes[it.key] = it.value
}
runMainThread {
result.success(hashMapOf(
"errorCode" to 0,
"attributes" to attributes
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
})
}
"setChannelAttributes" -> {
val channelId: String? = when {
args?.get("channelId") is String -> args.get("channelId") as String
else -> null
}
val enableNotificationToChannelMembers: Boolean = when {
args?.get("enableNotificationToChannelMembers") is Boolean -> args.get("enableNotificationToChannelMembers") as Boolean
else -> false
}
val attributes: List<Map<String, String>>? = args?.get("attributes") as List<Map<String, String>>
var channelAttributes = ArrayList<RtmChannelAttribute>()
attributes!!.forEach {
var rtmChannelAttribute = RtmChannelAttribute()
rtmChannelAttribute.key = it["key"]
rtmChannelAttribute.value = it["value"]
channelAttributes.add(rtmChannelAttribute)
}
client.setChannelAttributes(channelId, channelAttributes,
ChannelAttributeOptions(enableNotificationToChannelMembers),
object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
}
)
}
"addOrUpdateChannelAttributes" -> {
val channelId: String? = when {
args?.get("channelId") is String -> args.get("channelId") as String
else -> null
}
val enableNotificationToChannelMembers: Boolean = when {
args?.get("enableNotificationToChannelMembers") is Boolean -> args.get("enableNotificationToChannelMembers") as Boolean
else -> false
}
val attributes: List<Map<String, String>>? = args?.get("attributes") as List<Map<String, String>>
var channelAttributes = ArrayList<RtmChannelAttribute>()
attributes!!.forEach {
var rtmChannelAttribute = RtmChannelAttribute()
rtmChannelAttribute.key = it["key"]
rtmChannelAttribute.value = it["value"]
channelAttributes.add(rtmChannelAttribute)
}
client.addOrUpdateChannelAttributes(channelId, channelAttributes,
ChannelAttributeOptions(enableNotificationToChannelMembers),
object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
}
)
}
"deleteChannelAttributesByKeys" -> {
val channelId: String? = when {
args?.get("channelId") is String -> args.get("channelId") as String
else -> null
}
val enableNotificationToChannelMembers: Boolean = when {
args?.get("enableNotificationToChannelMembers") is Boolean -> args.get("enableNotificationToChannelMembers") as Boolean
else -> false
}
val keys: List<String>? = args?.get("keys") as List<String>
client.deleteChannelAttributesByKeys(channelId, keys,
ChannelAttributeOptions(enableNotificationToChannelMembers),
object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
}
)
}
"clearChannelAttributes" -> {
val channelId: String? = when {
args?.get("channelId") is String -> args.get("channelId") as String
else -> null
}
val enableNotificationToChannelMembers: Boolean = when {
args?.get("enableNotificationToChannelMembers") is Boolean -> args.get("enableNotificationToChannelMembers") as Boolean
else -> false
}
client.clearChannelAttributes(channelId,
ChannelAttributeOptions(enableNotificationToChannelMembers),
object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
}
)
}
"getChannelAttributes" -> {
val channelId: String? = when {
args?.get("channelId") is String -> args.get("channelId") as String
else -> null
}
client.getChannelAttributes(channelId,
object : ResultCallback<List<RtmChannelAttribute>> {
override fun onSuccess(resp: List<RtmChannelAttribute>) {
var attributes = ArrayList<Map<String, Any>>()
for(attribute in resp.orEmpty()){
attributes.add(hashMapOf(
"key" to attribute.key,
"value" to attribute.value,
"userId" to attribute.getLastUpdateUserId(),
"updateTs" to attribute.getLastUpdateTs()
))
}
runMainThread {
result.success(hashMapOf(
"errorCode" to 0,
"attributes" to attributes
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
})
}
"getChannelAttributesByKeys" -> {
val channelId: String? = when {
args?.get("channelId") is String -> args.get("channelId") as String
else -> null
}
var keys: List<String>? = when {
args?.get("keys") is List<*> -> args.get("keys") as List<String>
else -> null
}
client.getChannelAttributesByKeys(channelId,
keys,
object : ResultCallback<List<RtmChannelAttribute>> {
override fun onSuccess(resp: List<RtmChannelAttribute>) {
var attributes = ArrayList<Map<String, Any>>()
for(attribute in resp.orEmpty()){
attributes.add(hashMapOf(
"key" to attribute.key,
"value" to attribute.value,
"userId" to attribute.getLastUpdateUserId(),
"updateTs" to attribute.getLastUpdateTs()
))
}
runMainThread {
result.success(hashMapOf(
"errorCode" to 0,
"attributes" to attributes
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
})
}
"sendLocalInvitation" -> {
val calleeId = when {
args?.get("calleeId") is String -> args["calleeId"] as String
else -> null
}
val content = when {
args?.get("content") is String -> args["content"] as String
else -> null
}
val channelId = when {
args?.get("channelId") is String -> args["channelId"] as String
else -> null
}
val localInvitation = rtmClient.callKit.createLocalInvitation(calleeId.toString())
if (null != content) {
localInvitation?.content = content
}
if (null != channelId) {
localInvitation?.channelId = channelId
}
if (localInvitation != null) {
rtmClient.callKit.sendLocalInvitation(localInvitation, object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
rtmClient.localInvitations[localInvitation.calleeId] = localInvitation
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
})
}
}
"cancelLocalInvitation" -> {
val calleeId = when {
args?.get("calleeId") is String -> args["calleeId"] as String
else -> null
}
val content = when {
args?.get("content") is String -> args["content"] as String
else -> null
}
val channelId = when {
args?.get("channelId") is String -> args["channelId"] as String
else -> null
}
val localInvitation = when {
rtmClient.localInvitations[calleeId] is LocalInvitation -> rtmClient.localInvitations[calleeId]
else -> null
}
if (null == localInvitation) {
runMainThread {
result.success(hashMapOf("errorCode" to -1))
}
return
}
if (null != content) {
localInvitation.content = content
}
if (null != channelId) {
localInvitation.channelId = channelId
}
rtmClient.callKit.cancelLocalInvitation(localInvitation, object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
rtmClient.localInvitations.remove(localInvitation.calleeId)
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
})
}
"acceptRemoteInvitation" -> {
val response = when {
args?.get("response") is String -> args.get("response") as String
else -> null
}
val callerId = when {
args?.get("callerId") is String -> args.get("callerId") as String
else -> null
}
var remoteInvitation: RemoteInvitation? = when {
rtmClient.remoteInvitations[callerId] is RemoteInvitation -> rtmClient.remoteInvitations[callerId]
else -> null
}
if (null == remoteInvitation) {
runMainThread {
result.success(hashMapOf("errorCode" to -1))
}
return
}
if (null != response) {
remoteInvitation.response = response
}
rtmClient.callKit.acceptRemoteInvitation(remoteInvitation, object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
rtmClient.remoteInvitations.remove(remoteInvitation.callerId)
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
})
}
"refuseRemoteInvitation" -> {
val response = when {
args?.get("response") is String -> args.get("response") as String
else -> null
}
val callerId = when {
args?.get("callerId") is String -> args.get("callerId") as String
else -> null
}
var remoteInvitation: RemoteInvitation? = when {
rtmClient.remoteInvitations[callerId] is RemoteInvitation -> rtmClient.remoteInvitations[callerId]
else -> null
}
if (null == remoteInvitation) {
runMainThread {
result.success(hashMapOf("errorCode" to -1))
}
return
}
if (null != response) {
remoteInvitation.response = response
}
rtmClient.callKit.refuseRemoteInvitation(remoteInvitation, object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
rtmClient.remoteInvitations.remove(remoteInvitation.callerId)
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
})
}
"createChannel" -> {
val channelId = args?.get("channelId") as String
val rtmChannel = RTMChannel(clientIndex, channelId, registrar.messenger(), eventHandler)
val channel: RtmChannel? = client.createChannel(channelId, rtmChannel)
if (null == channel) {
runMainThread {
result.success(hashMapOf("errorCode" to -1))
}
return
}
rtmClient.channels[channelId] = channel
runMainThread {
result.success(hashMapOf("errorCode" to 0))
}
}
"releaseChannel" -> {
val channelId = args?.get("channelId") as String
val rtmChannel = rtmClient.channels[channelId]
if (null == rtmChannel) {
runMainThread {
result.success(hashMapOf("errorCode" to -1))
}
return
}
rtmChannel.release()
rtmClient.channels.remove(channelId)
runMainThread {
result.success(hashMapOf("errorCode" to 0))
}
}
"subscribePeersOnlineStatus"->{
val peers: List<String>? = args?.get("peerIds") as List<String>
val setPeers = mutableSetOf<String>()
peers?.forEach {
setPeers.add(it)
}
client.subscribePeersOnlineStatus(setPeers,object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.errorCode))
}
}
})
}
"unsubscribePeersOnlineStatus"->{
val peers: List<String>? = args?.get("peerIds") as List<String>
val setPeers = mutableSetOf<String>()
peers?.forEach {
setPeers.add(it)
}
client.unsubscribePeersOnlineStatus(setPeers,object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.errorCode))
}
}
})
}
else -> {
result.notImplemented();
}
}
}
private fun handleChannelMethod(methodName: String?, params: Map<String, Any>, result: MethodChannel.Result) {
val _clientIndex = (params["clientIndex"] as Int).toLong()
val _channelId = params["channelId"] as String
var args: Map<String, Any>? = when {
(params.get("args") is Map<*,*>) -> params["args"] as Map<String, Any>
else -> null
}
val rtmClient: RTMClient? = clients[_clientIndex]
if (null == rtmClient) {
runMainThread {
result.success(hashMapOf("errorCode" to -1))
}
return
}
val client: RtmClient? = rtmClient.client
if (null == client) {
runMainThread {
result.success(hashMapOf("errorCode" to -1))
}
return
}
val rtmChannel = rtmClient.channels[_channelId]
if (null == rtmChannel) {
runMainThread {
result.success(hashMapOf("errorCode" to -1))
}
return
}
when (methodName) {
"join" -> {
rtmChannel.join(object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
})
}
"sendMessage" -> {
val message = client.createMessage()
message.text = args?.get("message") as String
val options = SendMessageOptions().apply {
(args["historical"] as? Boolean)?.let {
enableHistoricalMessaging = it
}
(args["offline"] as? Boolean)?.let {
enableOfflineMessaging = it
}
}
rtmChannel.sendMessage(message, options, object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
})
}
"leave" -> {
rtmChannel.leave(object : ResultCallback<Void> {
override fun onSuccess(resp: Void?) {
runMainThread {
result.success(hashMapOf(
"errorCode" to 0
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
})
}
"getMembers" -> {
rtmChannel.getMembers(object : ResultCallback<List<RtmChannelMember>> {
override fun onSuccess(resp: List<RtmChannelMember>) {
val membersList = ArrayList<Map<String, String>>()
for (member in resp) {
membersList.add(hashMapOf("userId" to member.userId, "channelId" to member.channelId))
}
runMainThread {
result.success(hashMapOf(
"errorCode" to 0,
"members" to membersList
))
}
}
override fun onFailure(code: ErrorInfo) {
runMainThread {
result.success(hashMapOf("errorCode" to code.getErrorCode()))
}
}
})
}
else -> {
result.notImplemented();
}
}
}
} | 1 | Kotlin | 0 | 5 | d90434e70c2f943a0ec3ab8295da2d08169af13c | 34,406 | Flutter-RTM | MIT License |
kotlin-mui-icons/src/main/generated/mui/icons/material/FlipCameraIosSharp.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/FlipCameraIosSharp")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val FlipCameraIosSharp: SvgIconComponent
| 10 | null | 5 | 983 | 7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35 | 218 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/com/app/di/Modules.kt | yashaggind | 219,290,865 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 17, "JSON": 2, "XML": 11, "Java": 1} | package com.app.di
import com.app.repository.UserRepository
import com.app.ui.users.viewmodel.UserViewModel
import org.koin.android.ext.koin.androidApplication
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.loadKoinModules
import org.koin.dsl.module
fun injectFeature() = loadFeature
private val loadFeature by lazy {
loadKoinModules(
listOf(viewModelModule,
repositoryModule)
)
}
val viewModelModule = module {
viewModel { UserViewModel(userRepository = get()) }
}
val repositoryModule = module {
single { UserRepository(androidApplication()) }
}
/*val uiHelperModule = module {
single { UiHelper(androidContext()) }
}*/
/*val jsonReaderModule = module {
single { JsonReaderHelper(androidApplication()) }
}*/
| 1 | null | 1 | 1 | 326afe74134718ab8bfebb4a1499cdb5da419ad9 | 805 | CircleDistance | Apache License 2.0 |
v2-model/src/commonMain/kotlin/com/bselzer/gw2/v2/model/guild/log/KickLog.kt | Woody230 | 388,820,096 | false | {"Kotlin": 750899} | package com.bselzer.gw2.v2.model.guild.log
import com.bselzer.gw2.v2.model.account.AccountName
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName("kick")
data class KickLog(
/**
* The account name of the guild member who kicked the [user].
*/
@SerialName("kicked_by")
val kickedBy: AccountName = AccountName()
) : GuildLog() | 2 | Kotlin | 0 | 2 | 7bd43646f94d1e8de9c20dffcc2753707f6e455b | 405 | GW2Wrapper | Apache License 2.0 |
src/main/kotlin/net/ree_jp/reefseichi/form/WorldSelectForm.kt | ReefNetwork | 249,418,062 | false | null | /*
* RRRRRR jjj
* RR RR eee eee pp pp
* RRRRRR ee e ee e _____ jjj ppp pp
* RR RR eeeee eeeee jjj pppppp
* RR RR eeeee eeeee jjj pp
* jjjj pp
*
* Copyright (c) 2020. Ree-jp. All Rights Reserved.
*/
package net.ree_jp.reefseichi.form
import cn.nukkit.Player
import cn.nukkit.Server
import cn.nukkit.form.element.ElementButton
import cn.nukkit.form.response.FormResponse
import cn.nukkit.form.response.FormResponseSimple
import cn.nukkit.form.window.FormWindowSimple
class WorldSelectForm(player: Player, content: String) : Response, FormWindowSimple("ワールド選択", content) {
init {
val server = Server.getInstance()
addButton(ElementButton("ロビー") { player.teleport(server.getLevelByName("lobby").safeSpawn) })
addButton(ElementButton("整地ワールド1") { player.teleport(server.getLevelByName("dig_1").safeSpawn) })
addButton(ElementButton("整地ワールド2") { player.teleport(server.getLevelByName("dig_2").safeSpawn) })
addButton(ElementButton("整地ワールド3") { player.teleport(server.getLevelByName("dig_3").safeSpawn) })
}
override fun handleResponse(player: Player, response: FormResponse) {
if (response !is FormResponseSimple) throw Exception("不正なformの返り値")
response.clickedButton.runTask()
}
} | 0 | Kotlin | 0 | 0 | ff24f5e992c91348a632fa540348bd536d627866 | 1,374 | ReefServer | MIT License |
server/src/main/kotlin/fi/vauhtijuoksu/vauhtijuoksuapi/server/impl/base/PatchRouter.kt | Vauhtijuoksu | 394,707,727 | false | null | package fi.vauhtijuoksu.vauhtijuoksuapi.server.impl.base
import fi.vauhtijuoksu.vauhtijuoksuapi.database.api.VauhtijuoksuDatabase
import fi.vauhtijuoksu.vauhtijuoksuapi.exceptions.UserError
import fi.vauhtijuoksu.vauhtijuoksuapi.models.Model
import fi.vauhtijuoksu.vauhtijuoksuapi.server.ApiConstants
import fi.vauhtijuoksu.vauhtijuoksuapi.server.api.ApiModel
import fi.vauhtijuoksu.vauhtijuoksuapi.server.api.PartialRouter
import io.vertx.core.Future
import io.vertx.core.json.jackson.DatabindCodec.mapper
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import io.vertx.ext.web.handler.AuthenticationHandler
import io.vertx.ext.web.handler.AuthorizationHandler
import io.vertx.ext.web.handler.BodyHandler
import io.vertx.ext.web.handler.CorsHandler
import mu.KotlinLogging
import java.util.UUID
open class PatchRouter<M : Model, ApiRepresentation : ApiModel<M>>(
private val authenticationHandler: AuthenticationHandler,
private val adminRequired: AuthorizationHandler,
private val authenticatedEndpointCorsHandler: CorsHandler,
private val db: VauhtijuoksuDatabase<M>,
private val patchValidator: (M) -> String?,
private val toApiRepresentation: (M) -> ApiRepresentation,
) : PartialRouter {
private val logger = KotlinLogging.logger {}
override fun configure(router: Router, basepath: String) {
router.patch("$basepath/:id")
.handler(authenticatedEndpointCorsHandler)
.handler(BodyHandler.create())
.handler(authenticationHandler)
.handler(adminRequired)
.handler { ctx ->
val id: UUID
try {
id = UUID.fromString(ctx.pathParam("id"))
} catch (_: IllegalArgumentException) {
throw UserError("Not UUID: ${ctx.pathParam("id")}")
}
val jsonBody = ctx.body().asJsonObject() ?: throw UserError("Body is required on PATCH")
logger.debug { "Patching a record with object $jsonBody" }
db.getById(id)
.map { merge(ctx, it) }
.compose(db::update)
.compose { respond(id, ctx) }
.onFailure(ctx::fail)
}
}
private fun merge(ctx: RoutingContext, existingData: M): M {
val oldData = mapper().readerForUpdating(toApiRepresentation(existingData))
val mergedData: M = try {
oldData.readValue<ApiRepresentation>(ctx.body().asString()).toModel()
} catch (@Suppress("TooGenericExceptionCaught") e: Throwable) {
throw UserError("Error patching object: ${e.message}", e)
}
val validationMessage = patchValidator(mergedData)
if (validationMessage != null) {
throw UserError("Invalid input: $validationMessage")
}
return mergedData
}
protected open fun respond(updatedId: UUID, ctx: RoutingContext): Future<Void> {
return db.getById(updatedId)
.map { updatedRecord ->
logger.info { "Patched record $updatedRecord" }
ctx.response().setStatusCode(ApiConstants.OK)
.end(toApiRepresentation(updatedRecord).toJson().encode())
}
.mapEmpty()
}
}
| 4 | null | 0 | 3 | 177cd5f19794fc3b7fbff8439070762753896168 | 3,306 | vauhtijuoksu-api | MIT License |
app/src/main/java/com/example/alexmelnikov/coinspace/ui/accounts/AccountsPresenter.kt | millerovv | 141,981,951 | false | null | package com.example.alexmelnikov.coinspace.ui.accounts
import android.util.Log
import com.example.alexmelnikov.coinspace.BaseApp
import com.example.alexmelnikov.coinspace.model.entities.Account
import com.example.alexmelnikov.coinspace.model.getCurrencyByString
import com.example.alexmelnikov.coinspace.model.interactors.CurrencyConverter
import com.example.alexmelnikov.coinspace.model.interactors.IUserBalanceInteractor
import com.example.alexmelnikov.coinspace.model.interactors.Money
import com.example.alexmelnikov.coinspace.model.interactors.defaultCurrency
import com.example.alexmelnikov.coinspace.model.repositories.AccountsRepository
import com.example.alexmelnikov.coinspace.model.repositories.IDeferOperationsRepository
import com.example.alexmelnikov.coinspace.model.repositories.IOperationsRepository
import com.example.alexmelnikov.coinspace.model.repositories.IPatternsRepository
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class AccountsPresenter : AccountsContract.Presenter {
private lateinit var view: AccountsContract.AccountsView
@Inject
lateinit var accountsRepository: AccountsRepository
@Inject
lateinit var patternsRepository: IPatternsRepository
@Inject
lateinit var operationsRepository: IOperationsRepository
@Inject
lateinit var currencyConverter: CurrencyConverter
@Inject
lateinit var defererOperationsRepository: IDeferOperationsRepository
@Inject
lateinit var balanceInteractor: IUserBalanceInteractor
override fun attach(view: AccountsContract.AccountsView) {
this.view = view
BaseApp.instance.component.inject(this)
}
override fun addNewAccountButtonClick() {
view.openAddAccountFragment()
}
override fun accountsDataRequest() {
accountsRepository.getAccountsOffline()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ accountsList -> handleSuccessAccountsRequest(accountsList) },
{ handleErrorAccountsRequest() })
}
private fun handleSuccessAccountsRequest(accounts: List<Account>) {
view.replaceAccountsRecyclerData(accounts)
Log.d("mytag", "accounts req success :: $accounts")
}
private fun handleErrorAccountsRequest() {
Log.d("mytag", "cant't get data from db")
}
override fun removeAccount(account: Account) {
var money = Money(account.balance, getCurrencyByString(account.currency))
money = currencyConverter.convertCurrency(money, defaultCurrency)
money = Money(balanceInteractor.getUserBalance().count - money.count, defaultCurrency).copy()
Log.i("Updated balance request", "${money}")
balanceInteractor.setBalance(money)
val id = account.id!!
patternsRepository.removePatternByAccountId(id)
defererOperationsRepository.removeOperationsByAccountId(id)
operationsRepository.removeOperationsByAccountId(id)
accountsRepository.removeByAccountId(id)
}
} | 0 | Kotlin | 1 | 0 | f2bfad76ec826349bd15db12969ca57b7691e05d | 3,120 | CoinSpace | MIT License |
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/operations/PackageSearchOperation.kt | ingokegel | 72,937,917 | true | null | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations
import com.intellij.buildsystem.model.unified.UnifiedDependency
import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository
import com.jetbrains.packagesearch.intellij.plugin.extensibility.PackageSearchModule
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
internal sealed class PackageSearchOperation<T> {
abstract val model: T
abstract val packageSearchModule: PackageSearchModule
sealed class Package : PackageSearchOperation<UnifiedDependency>() {
abstract override val model: UnifiedDependency
data class Remove(
override val model: UnifiedDependency,
override val packageSearchModule: PackageSearchModule,
val currentVersion: PackageVersion,
val currentScope: PackageScope
) : Package() {
override fun toString() =
"Package.Remove(model='${model.displayName}', moduleModule='${packageSearchModule.getFullName()}', " +
"currentVersion='$currentVersion', scope='$currentScope')"
}
}
sealed class Repository : PackageSearchOperation<UnifiedDependencyRepository>() {
abstract override val model: UnifiedDependencyRepository
data class Remove(
override val model: UnifiedDependencyRepository,
override val packageSearchModule: PackageSearchModule
) : Repository() {
override fun toString() = "Repository.Remove(model='${model.displayName}', moduleModule='${packageSearchModule.getFullName()}')"
}
}
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 2,531 | intellij-community | Apache License 2.0 |
navigationrail/navigationrail/src/main/java/com/microsoft/device/dualscreen/navigationrail/NavigationRailView.kt | microsoft | 262,129,243 | false | null | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
package com.microsoft.device.dualscreen.navigationrail
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Point
import android.graphics.Rect
import android.os.Build
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.BaseInterpolator
import androidx.activity.ComponentActivity
import androidx.core.view.animation.PathInterpolatorCompat
import androidx.customview.view.AbsSavedState
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.transition.ChangeBounds
import androidx.transition.Transition
import androidx.transition.TransitionManager
import androidx.window.layout.WindowInfoTracker
import androidx.window.layout.WindowLayoutInfo
import androidx.window.layout.WindowMetricsCalculator
import com.google.android.material.navigationrail.NavigationRailMenuView
import com.google.android.material.navigationrail.NavigationRailView
import com.microsoft.device.dualscreen.utils.wm.DisplayPosition
import com.microsoft.device.dualscreen.utils.wm.OnVerticalSwipeListener
import com.microsoft.device.dualscreen.utils.wm.ScreenMode
import com.microsoft.device.dualscreen.utils.wm.extractFoldingFeatureRect
import com.microsoft.device.dualscreen.utils.wm.getWindowVisibleDisplayFrame
import com.microsoft.device.dualscreen.utils.wm.isFoldingFeatureHorizontal
import com.microsoft.device.dualscreen.utils.wm.isInDualMode
import com.microsoft.device.dualscreen.utils.wm.isSeparating
import com.microsoft.device.dualscreen.utils.wm.locationOnScreen
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
private const val MARGIN_LOWERING_FACTOR = 0.95
/**
* A sub class of the [NavigationRailView] that can position its children in different ways when the application is spanned on both screens.
* Using the [arrangeButtons] and [setMenuGravity] the children can be split in any way between the two screens.
* Animations can be used when changing the arrangement of the buttons on the two screen.
*/
class NavigationRailView : NavigationRailView {
constructor(context: Context) : super(context) {
this.registerWindowInfoFlow()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
this.registerWindowInfoFlow()
extractAttributes(context, attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
this.registerWindowInfoFlow()
extractAttributes(context, attrs)
}
private var screenMode = ScreenMode.DUAL_SCREEN
private var job: Job? = null
private var windowLayoutInfo: WindowLayoutInfo? = null
private var topBtnCount: Int = -1
private var bottomBtnCount: Int = -1
private fun normalizeFoldingFeatureRectForView(): Rect {
return windowLayoutInfo.extractFoldingFeatureRect().apply {
offset(-locationOnScreen.x, 0)
}
}
private fun registerWindowInfoFlow() {
val activity = (context as? ComponentActivity)
?: throw RuntimeException("Context must implement androidx.activity.ComponentActivity!")
job = activity.lifecycleScope.launch(Dispatchers.Main) {
activity.lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
WindowInfoTracker.getOrCreate(activity)
.windowLayoutInfo(activity)
.collect { info ->
windowLayoutInfo = info
onInfoLayoutChanged()
}
}
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
job?.cancel()
}
private fun onInfoLayoutChanged() {
setScreenParameters()
val changeBounds: Transition = ChangeBounds()
changeBounds.duration = 300L
changeBounds.interpolator = PathInterpolatorCompat.create(0.2f, 0f, 0f, 1f)
TransitionManager.beginDelayedTransition(this@NavigationRailView, changeBounds)
requestLayout()
}
private var onSwipeListener: OnVerticalSwipeListener =
object : OnVerticalSwipeListener(context) {
override fun onSwipeTop() {
super.onSwipeTop()
if (allowFlingGesture) {
menuGravity = Gravity.TOP
}
}
override fun onSwipeBottom() {
super.onSwipeBottom()
if (allowFlingGesture) {
menuGravity = Gravity.BOTTOM
}
}
}
/**
* Use an animation to move the buttons when the menu gravity is changed or [arrangeButtons] is called.
* By default the [AccelerateDecelerateInterpolator] is used.
*/
var useAnimation: Boolean = true
/**
* Set the interpolator for the animation when menu gravity is changed or [arrangeButtons] is called.
* By default the [AccelerateDecelerateInterpolator] is used.
*/
var animationInterpolator: BaseInterpolator = AccelerateDecelerateInterpolator()
/**
* Allows the buttons to be moved to [DisplayPosition.START] or [DisplayPosition.END] with a swipe gesture.
*/
var allowFlingGesture: Boolean = true
private fun extractAttributes(context: Context, attrs: AttributeSet?) {
val styledAttributes =
context.theme.obtainStyledAttributes(
attrs,
R.styleable.ScreenManagerAttrs,
0,
0
)
try {
screenMode = ScreenMode.fromId(
styledAttributes.getResourceId(
R.styleable.ScreenManagerAttrs_tools_application_mode,
ScreenMode.DUAL_SCREEN.ordinal
)
)
useAnimation =
styledAttributes.getBoolean(
R.styleable.ScreenManagerAttrs_useAnimation,
useAnimation
)
allowFlingGesture =
styledAttributes.getBoolean(
R.styleable.ScreenManagerAttrs_allowFlingGesture,
allowFlingGesture
)
} finally {
styledAttributes.recycle()
}
}
private var topScreenHeight = -1
private var bottomScreenHeight = -1
private var appWindowFrameHeight = -1
private var hingeHeight = -1
private var statusBarHeight = -1
private var screenSize = Point()
private var appWindowPosition = Rect()
private var hingePosition = Rect()
private var shouldRedrawMenu = true
private fun setScreenParameters() {
if (!isIntersectingHorizontalHinge()) {
return
}
context.getWindowVisibleDisplayFrame().let { windowRect ->
appWindowPosition = windowRect
appWindowFrameHeight = windowRect.height()
normalizeFoldingFeatureRectForView().let { hingeRect ->
hingePosition = hingeRect
val windowBounds = WindowMetricsCalculator.getOrCreate()
.computeCurrentWindowMetrics(context as Activity).bounds
screenSize = Point(windowBounds.width(), windowBounds.height())
statusBarHeight = screenSize.y - appWindowFrameHeight
hingeHeight = hingeRect.height()
topScreenHeight = hingeRect.top - windowRect.top
bottomScreenHeight = windowRect.bottom - hingeRect.bottom
shouldRedrawMenu = true
}
}
}
private fun isIntersectingHorizontalHinge(): Boolean {
normalizeFoldingFeatureRectForView().let {
return windowLayoutInfo.isFoldingFeatureHorizontal() &&
(this.absY() + this.height > it.bottom)
}
}
/**
* Determines if the buttons should be split to avoid overlapping over the foldable feature.
*/
private fun shouldSplitButtons(): Boolean {
return windowLayoutInfo.isInDualMode() &&
windowLayoutInfo.isFoldingFeatureHorizontal() &&
windowLayoutInfo.isSeparating() &&
isIntersectingHorizontalHinge()
}
/**
* Sets the menu gravity and splits the menu buttons to avoid overlapping the folding feature
*/
override fun setMenuGravity(gravity: Int) {
super.setMenuGravity(gravity)
topBtnCount = -1
bottomBtnCount = -1
shouldRedrawMenu = true
requestLayout()
}
/**
* When the application is in spanned mode the buttons can be split between the screens.
* @param startBtnCount - how many buttons should be positioned on the top screen
* @param endBtnCount - how many buttons should be positioned on the bottom screen
*/
fun arrangeButtons(startBtnCount: Int, endBtnCount: Int) {
getChildMenu()?.let { child ->
if (!shouldSplitButtons()) {
if (child.doesChildCountMatch(startBtnCount, endBtnCount)) {
syncBtnCount(startBtnCount, endBtnCount)
}
return
}
shouldRedrawMenu = true
menuGravity = Gravity.CENTER
syncBtnCount(startBtnCount, endBtnCount)
requestLayout()
}
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
if (shouldRedrawMenu) {
super.onLayout(changed, left, top, right, bottom)
getChildMenu()?.let { childMenu ->
if (!shouldSplitButtons()) {
return
}
val childMenuTop = calculateMenuTopMargin()
childMenu.layout(left, childMenuTop, right, bottom)
childMenu.positionButtonsByGravity()
shouldRedrawMenu = !shouldRedrawMenu
}
}
}
/**
* Positions the buttons inside the [NavigationRailMenuView] depending on the selected gravity
* and the foldable feature.
*/
private fun NavigationRailMenuView.positionButtonsByGravity() {
when (getGravity()) {
Gravity.CENTER_VERTICAL -> {
positionButtonsInCenter()
}
Gravity.BOTTOM -> {
positionButtonsOnBottom()
}
Gravity.TOP -> {
positionButtonsOnTop()
}
}
}
private fun NavigationRailMenuView.positionButtonsOnTop() {
val childMenuTop = calculateMenuTopMargin()
val defaultChildHeight = getChildAt(0).measuredHeight
val availableHeightOnTopScreen = topScreenHeight - childMenuTop
val skipAnimation = shouldSkipAnimation(this)
// If the gravity is [Gravity.TOP] check if the buttons can fit
// in a single screen by reducing the margins between them.
if (defaultChildHeight * childCount * MARGIN_LOWERING_FACTOR <= availableHeightOnTopScreen &&
defaultChildHeight * childCount > availableHeightOnTopScreen
) {
for (i in 0 until childCount) {
val newChildHeight = availableHeightOnTopScreen / childCount
val childTop = i * newChildHeight
setButtonPosition(getChildAt(i), childTop, skipAnimation)
}
return
} else {
// If the buttons can't fit on the top screen, move some on the bottom screen.
var topStartingPosition = getChildAt(0).top
val childrenAboveHinge =
(availableHeightOnTopScreen / defaultChildHeight).coerceAtMost(childCount)
for (i in 0 until childrenAboveHinge) {
val childTop = i * defaultChildHeight + topStartingPosition
val child = getChildAt(i)
child.layout(child.left, 0, child.right, defaultChildHeight)
setButtonPosition(child, childTop, skipAnimation)
}
if (childrenAboveHinge < childCount) {
topStartingPosition = availableHeightOnTopScreen + hingeHeight
for (i in 0 until childCount - childrenAboveHinge) {
val childTop =
+i * defaultChildHeight + topStartingPosition
val child = getChildAt(i + childrenAboveHinge)
child.layout(child.left, 0, child.right, 0 + defaultChildHeight)
setButtonPosition(child, childTop, skipAnimation)
}
}
}
}
private fun NavigationRailMenuView.positionButtonsOnBottom() {
val availableHeightOnBottomScreen = appWindowPosition.bottom - hingePosition.bottom
val defaultChildHeight = getChildAt(0).measuredHeight
val skipAnimation = shouldSkipAnimation(this)
val startingPosition = this.height - availableHeightOnBottomScreen
val newChildHeight =
(availableHeightOnBottomScreen / childCount).coerceAtMost(defaultChildHeight)
for (i in 0 until childCount) {
val childTop = i * newChildHeight + startingPosition
val child = getChildAt(i)
child.layout(child.left, 0, child.right, 0 + defaultChildHeight)
setButtonPosition(child, childTop, skipAnimation)
}
return
}
private fun NavigationRailMenuView.positionButtonsInCenter() {
if (topBtnCount == -1 || bottomBtnCount == -1) {
topBtnCount = childCount / 2 + childCount % 2
bottomBtnCount = childCount / 2
}
val buttonsCount = topBtnCount + bottomBtnCount
if (buttonsCount == 0) {
return
}
if (topBtnCount == 0) {
positionButtonsOnBottom()
return
}
if (bottomBtnCount == 0) {
positionButtonsOnTop()
return
}
val childMenuTop = calculateMenuTopMargin()
val defaultChildHeight = getChildAt(0).measuredHeight
val availableHeightOnTopScreen = topScreenHeight - childMenuTop
val skipAnimation = shouldSkipAnimation(this)
var btnMargin = 0
// Calculate a negative button margin if there is not enough space on the top
if (defaultChildHeight * topBtnCount > availableHeightOnTopScreen) {
btnMargin =
(availableHeightOnTopScreen - defaultChildHeight * topBtnCount) / topBtnCount
}
val topStartingPosition =
availableHeightOnTopScreen - topBtnCount * (defaultChildHeight + btnMargin)
for (i in 0 until topBtnCount) {
val childTop = topStartingPosition + i * (defaultChildHeight + btnMargin)
val child = getChildAt(i)
child.layout(child.left, 0, child.right, 0 + defaultChildHeight)
setButtonPosition(child, childTop, skipAnimation)
}
val availableHeightOnBottomScreen = appWindowPosition.bottom - hingePosition.bottom
val bottomStartingPosition = this.height - availableHeightOnBottomScreen
// Calculate a negative button margin if there is not enough space on the bottom
if (defaultChildHeight * bottomBtnCount > availableHeightOnBottomScreen) {
btnMargin =
(availableHeightOnBottomScreen - defaultChildHeight * bottomBtnCount) / bottomBtnCount
}
for (i in topBtnCount until buttonsCount) {
val childTop = bottomStartingPosition +
(i - topBtnCount) * (defaultChildHeight + btnMargin)
val child = getChildAt(i)
child.layout(child.left, 0, child.right, 0 + defaultChildHeight)
setButtonPosition(child, childTop, skipAnimation)
}
}
/**
* Sets the position inside the [NavigationRailMenuView] and triggers the translation animations.
*/
private fun setButtonPosition(
child: View,
childTop: Int,
skipAnimation: Boolean
) {
if (skipAnimation || !useAnimation || Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
child.translationY = childTop.toFloat()
} else {
child.animate()
.setInterpolator(animationInterpolator)
.translationY(childTop.toFloat())
}
}
/**
* Returns the margin of the [NavigationRailMenuView] from the top of it's parent.
* This is useful when the [NavigationRailView] contains a header view.
*/
private fun calculateMenuTopMargin(): Int {
return headerView?.let {
val topMargin =
resources.getDimensionPixelSize(com.google.android.material.R.dimen.mtrl_navigation_rail_margin)
it.bottom + topMargin
} ?: 0
}
private fun getGravity() = menuGravity and Gravity.VERTICAL_GRAVITY_MASK
private fun getChildMenu(): NavigationRailMenuView? {
for (i in 0..childCount) {
val child = getChildAt(i)
if (child is NavigationRailMenuView) {
return child
}
}
return null
}
/**
* Checks if the newly requested positioning for the buttons matches the existing one.
*/
private fun NavigationRailMenuView.doesChildCountMatch(
startBtnCount: Int,
endBtnCount: Int
): Boolean {
return startBtnCount >= 0 && endBtnCount >= 0 && childCount == startBtnCount + endBtnCount
}
/**
* Skip the animation on the first layout pass.
*/
private fun shouldSkipAnimation(menu: NavigationRailMenuView): Boolean {
for (i in 0 until menu.childCount) {
if (menu.getChildAt(i).left != 0) {
return true
}
}
return false
}
/**
* Synchronize the [startBtnCount] and [endBtnCount].
*/
private fun syncBtnCount(startBtnCount: Int, endBtnCount: Int) {
this.topBtnCount = startBtnCount
this.bottomBtnCount = endBtnCount
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
if (!allowFlingGesture) {
return super.onInterceptTouchEvent(ev)
}
onSwipeListener.onTouchEvent(ev)
if (onSwipeListener.onInterceptTouchEvent(ev)) {
return true
}
return super.onInterceptTouchEvent(ev)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(ev: MotionEvent?): Boolean {
if (!allowFlingGesture) {
return super.onTouchEvent(ev)
}
return onSwipeListener.onTouchEvent(ev)
}
override fun onSaveInstanceState(): Parcelable {
val superState: Parcelable = super.onSaveInstanceState()
val state = SavedState(superState)
state.useAnimation = this.useAnimation
state.allowFlingGesture = this.allowFlingGesture
state.menuGravity = getGravity()
state.topBtnCount = this.topBtnCount
state.bottomBtnCount = this.bottomBtnCount
return state
}
override fun onRestoreInstanceState(state: Parcelable?) {
when (state) {
is SavedState -> {
super.onRestoreInstanceState(state.superState)
this.useAnimation = state.useAnimation
this.allowFlingGesture = state.allowFlingGesture
menuGravity = state.menuGravity
this.topBtnCount = state.topBtnCount
this.bottomBtnCount = state.bottomBtnCount
}
else -> {
super.onRestoreInstanceState(state)
}
}
}
internal class SavedState : AbsSavedState {
var useAnimation: Boolean = true
var allowFlingGesture: Boolean = true
var menuGravity: Int = Gravity.TOP
var topBtnCount: Int = -1
var bottomBtnCount: Int = -1
constructor(superState: Parcelable) : super(superState)
constructor(source: Parcel, loader: ClassLoader?) : super(source, loader) {
useAnimation = source.readInt() == 1
allowFlingGesture = source.readInt() == 1
menuGravity = source.readInt()
topBtnCount = source.readInt()
bottomBtnCount = source.readInt()
}
override fun writeToParcel(out: Parcel, flags: Int) {
super.writeToParcel(out, flags)
out.writeInt(if (useAnimation) 1 else 0)
out.writeInt(if (allowFlingGesture) 1 else 0)
out.writeInt(menuGravity)
out.writeInt(topBtnCount)
out.writeInt(bottomBtnCount)
}
companion object {
@JvmField
val CREATOR: Parcelable.ClassLoaderCreator<SavedState> =
object : Parcelable.ClassLoaderCreator<SavedState> {
override fun createFromParcel(source: Parcel, loader: ClassLoader): SavedState {
return SavedState(source, loader)
}
override fun createFromParcel(source: Parcel): SavedState {
return SavedState(source, null)
}
override fun newArray(size: Int): Array<SavedState> {
return newArray(size)
}
}
}
}
}
fun View.absY(): Int {
val location = IntArray(2)
this.getLocationOnScreen(location)
return location[1]
} | 4 | null | 16 | 63 | 059a23684baff99de1293d1f54119b611a5765a3 | 21,846 | surface-duo-sdk | MIT License |
Android/src/main/java/com/example/vocab/gui/BaseViewModel.kt | Arduino13 | 599,629,871 | false | null | package com.example.vocab.gui
import androidx.lifecycle.ViewModel
import com.example.vocab.Tools
import java.lang.Exception
/**
* Generic ViewModel for managing temporarily changes in models and saving them to global model
*
* @property newObjects list of objects which were added to the model
* @property deletedObjects copy of object that were deleted from the model
*/
abstract class BaseViewModel(): ViewModel() {
private val newObjects = mutableListOf<BaseItem<*>>()
private val deletedObjects = mutableListOf<BaseItem<*>>()
private var objectThatIsWriting: String? = null
/**
* Event for child class when save method is called
*/
protected abstract fun onSave(newObjects: List<BaseItem<*>>)
/**
* Event for child class when delete method is called
*/
protected abstract fun onDelete(deletedObjects: List<BaseItem<*>>)
/**
* Event for child class when commit method is called
*/
protected abstract fun onCommit(newObjects: List<BaseItem<*>>, deletedObjects: List<BaseItem<*>>)
/**
* Event for child class to reload data
*/
protected abstract fun loadData()
/**
* generates handler (id), to guarantee there is only one object at the time that is writing to
* model, sometimes in case of multiple steps dialog for creating word for example,
* there are multiple fragments with same model
*
* @return id as handler
*/
fun requestAccess(): String?{
return if(objectThatIsWriting == null){
objectThatIsWriting = Tools.getUUID()
return objectThatIsWriting
} else{
null
}
}
/**
* save new object to model, but no to global model
*/
fun save(newObject: BaseItem<*>, obj: String){
if(obj == objectThatIsWriting) {
newObjects.add(newObject)
onSave(listOf(newObject))
}
else throw Exception("Denied writing access to fragmentModel")
}
/**
* saves a list of objects to model, but no to global model
*/
fun save(newObjectsLocal: List<BaseItem<*>>, obj: String){
if(obj == objectThatIsWriting){
for(obj in newObjectsLocal){
newObjects.add(obj)
}
onSave(newObjectsLocal)
}
}
/**
* deletes object from model, but not from global model
*/
fun delete(deletedObjects: List<BaseItem<*>>, obj: String){
if(obj == objectThatIsWriting){
for(d in deletedObjects){
if(d in newObjects) newObjects.remove(d)
else this.deletedObjects.add(d)
}
onDelete(deletedObjects)
}
else throw Exception("Denied writing access to fragmentModel")
}
/**
* commits all changes to global model and to database
*/
fun commit(){
onCommit(newObjects, deletedObjects)
}
/**
* releasing access to model
*/
fun releaseAccess(){
objectThatIsWriting = null
newObjects.clear()
deletedObjects.clear()
loadData()
}
} | 0 | Kotlin | 0 | 0 | 5281c5b8281fd3cb06cf670dcaa7e6c858606179 | 3,130 | 3N | MIT License |
app/src/main/java/com/breezefsmshreebajrangsteeludyog/features/orderList/api/OrderListRepo.kt | DebashisINT | 645,424,403 | false | null | package com.breezefsmshreebajrangsteeludyog.features.orderList.api
import com.breezefsmshreebajrangsteeludyog.features.orderList.model.OrderListResponseModel
import io.reactivex.Observable
/**
* Created by Saikat on 01-10-2018.
*/
class OrderListRepo(val apiService: OrderListApi) {
fun getOrderList(sessiontoken: String, user_id: String, date: String): Observable<OrderListResponseModel> {
return apiService.getOrderList(sessiontoken, user_id, date)
}
} | 0 | Kotlin | 0 | 0 | 35e09f089ea181c5927063a5f14fc9ef3b090210 | 474 | ShreeBajrangSteelUdyog | Apache License 2.0 |
app/src/main/java/com/marcodallaba/mlkit/kotlin/CameraXLivePreviewActivity.kt | marcodb97 | 338,252,794 | false | null | /*
* Copyright 2020 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcodallaba.mlkit.kotlin
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.CompoundButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.google.android.gms.common.annotation.KeepName
import com.google.mlkit.common.MlKitException
import com.marcodallaba.mlkit.kotlin.facedetector.FaceDetectorProcessor
import com.marcodallaba.mlkit.kotlin.preference.PreferenceUtils
import com.marcodallaba.mlkit.kotlin.preference.SettingsActivity
import com.marcodallaba.mlkit.kotlin.preference.SettingsActivity.LaunchSource
import com.marcodallaba.mlkit.kotlin.viewmodels.CameraXViewModel
import com.marcodallaba.mlkit.kotlin.visionprocessors.VisionImageProcessor
import com.marcodallaba.mlkit.R
import com.marcodallaba.mlkit.databinding.ActivityCameraxLivePreviewBinding
import java.util.*
@KeepName
class CameraXLivePreviewActivity :
AppCompatActivity(),
ActivityCompat.OnRequestPermissionsResultCallback,
CompoundButton.OnCheckedChangeListener {
private lateinit var binding: ActivityCameraxLivePreviewBinding
private var cameraProvider: ProcessCameraProvider? = null
private var previewUseCase: Preview? = null
private var analysisUseCase: ImageAnalysis? = null
private var imageProcessor: VisionImageProcessor? = null
private var needUpdateGraphicOverlayImageSourceInfo = false
private var lensFacing = CameraSelector.LENS_FACING_BACK
private var cameraSelector: CameraSelector? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate")
if (savedInstanceState != null) {
lensFacing =
savedInstanceState.getInt(
STATE_LENS_FACING,
CameraSelector.LENS_FACING_BACK
)
}
cameraSelector = CameraSelector.Builder().requireLensFacing(lensFacing).build()
binding = ActivityCameraxLivePreviewBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.facingSwitch.setOnCheckedChangeListener(this)
ViewModelProvider(this,
ViewModelProvider.AndroidViewModelFactory.getInstance(application))
.get(CameraXViewModel::class.java)
.processCameraProvider
.observe(
this,
{ provider: ProcessCameraProvider? ->
cameraProvider = provider
if (allPermissionsGranted()) {
bindAllCameraUseCases()
}
}
)
binding.settingsButton.setOnClickListener {
val intent =
Intent(applicationContext, SettingsActivity::class.java)
intent.putExtra(
SettingsActivity.EXTRA_LAUNCH_SOURCE,
LaunchSource.CAMERAX_LIVE_PREVIEW
)
startActivity(intent)
}
if (!allPermissionsGranted()) {
runtimePermissions
}
}
override fun onSaveInstanceState(bundle: Bundle) {
super.onSaveInstanceState(bundle)
bundle.putInt(STATE_LENS_FACING, lensFacing)
}
override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
Log.d(TAG, "Set facing")
if (cameraProvider == null) {
return
}
val newLensFacing = if (lensFacing == CameraSelector.LENS_FACING_FRONT) {
CameraSelector.LENS_FACING_BACK
} else {
CameraSelector.LENS_FACING_FRONT
}
val newCameraSelector =
CameraSelector.Builder().requireLensFacing(newLensFacing).build()
try {
if (cameraProvider!!.hasCamera(newCameraSelector)) {
lensFacing = newLensFacing
cameraSelector = newCameraSelector
bindAllCameraUseCases()
return
}
} catch (e: CameraInfoUnavailableException) {
// Falls through
}
Toast.makeText(
applicationContext, "This device does not have lens with facing: $newLensFacing",
Toast.LENGTH_SHORT
)
.show()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.live_preview_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.settings) {
val intent = Intent(this, SettingsActivity::class.java)
intent.putExtra(
SettingsActivity.EXTRA_LAUNCH_SOURCE,
LaunchSource.CAMERAX_LIVE_PREVIEW
)
startActivity(intent)
return true
}
return super.onOptionsItemSelected(item)
}
public override fun onResume() {
super.onResume()
bindAllCameraUseCases()
}
override fun onPause() {
super.onPause()
imageProcessor?.run {
this.stop()
}
}
public override fun onDestroy() {
super.onDestroy()
imageProcessor?.run {
this.stop()
}
}
private fun bindAllCameraUseCases() {
bindPreviewUseCase()
bindAnalysisUseCase()
}
private fun bindPreviewUseCase() {
if (!PreferenceUtils.isCameraLiveViewportEnabled(this)) {
return
}
if (cameraProvider == null) {
return
}
if (previewUseCase != null) {
cameraProvider!!.unbind(previewUseCase)
}
previewUseCase = Preview.Builder().build()
previewUseCase!!.setSurfaceProvider(binding.previewView.surfaceProvider)
cameraProvider!!.bindToLifecycle(/* lifecycleOwner= */this, cameraSelector!!, previewUseCase)
}
@SuppressLint("NewApi")
private fun bindAnalysisUseCase() {
if (cameraProvider == null) {
return
}
if (analysisUseCase != null) {
cameraProvider!!.unbind(analysisUseCase)
}
if (imageProcessor != null) {
imageProcessor!!.stop()
}
imageProcessor = try {
val faceDetectorOptions =
PreferenceUtils.getFaceDetectorOptionsForLivePreview(this)
FaceDetectorProcessor(this, faceDetectorOptions)
} catch (e: Exception) {
Log.e(
TAG,
"Can not create image processor: $FACE_DETECTION",
e
)
Toast.makeText(
applicationContext,
"Can not create image processor: " + e.localizedMessage,
Toast.LENGTH_LONG
)
.show()
return
}
val builder = ImageAnalysis.Builder()
val targetAnalysisSize = PreferenceUtils.getCameraXTargetAnalysisSize(this)
if (targetAnalysisSize != null) {
builder.setTargetResolution(targetAnalysisSize)
}
analysisUseCase = builder.build()
needUpdateGraphicOverlayImageSourceInfo = true
analysisUseCase?.setAnalyzer(
// imageProcessor.processImageProxy will use another thread to run the detection underneath,
// thus we can just runs the analyzer itself on main thread.
ContextCompat.getMainExecutor(this),
{ imageProxy: ImageProxy ->
if (needUpdateGraphicOverlayImageSourceInfo) {
val isImageFlipped =
lensFacing == CameraSelector.LENS_FACING_FRONT
val rotationDegrees =
imageProxy.imageInfo.rotationDegrees
if (rotationDegrees == 0 || rotationDegrees == 180) {
binding.graphicOverlay.setImageSourceInfo(
imageProxy.width, imageProxy.height, isImageFlipped
)
} else {
binding.graphicOverlay.setImageSourceInfo(
imageProxy.height, imageProxy.width, isImageFlipped
)
}
needUpdateGraphicOverlayImageSourceInfo = false
}
try {
imageProcessor!!.processImageProxy(imageProxy, binding.graphicOverlay)
} catch (e: MlKitException) {
Log.e(
TAG,
"Failed to process image. Error: " + e.localizedMessage
)
Toast.makeText(
applicationContext,
e.localizedMessage,
Toast.LENGTH_SHORT
)
.show()
}
}
)
cameraProvider!!.bindToLifecycle( /* lifecycleOwner= */this, cameraSelector!!, analysisUseCase)
}
private val requiredPermissions: Array<String?>
get() = try {
val info = this.packageManager
.getPackageInfo(this.packageName, PackageManager.GET_PERMISSIONS)
val ps = info.requestedPermissions
if (ps != null && ps.isNotEmpty()) {
ps
} else {
arrayOfNulls(0)
}
} catch (e: Exception) {
arrayOfNulls(0)
}
private fun allPermissionsGranted(): Boolean {
for (permission in requiredPermissions) {
if (!isPermissionGranted(this, permission)) {
return false
}
}
return true
}
private val runtimePermissions: Unit
get() {
val allNeededPermissions: MutableList<String?> = ArrayList()
for (permission in requiredPermissions) {
if (!isPermissionGranted(this, permission)) {
allNeededPermissions.add(permission)
}
}
if (allNeededPermissions.isNotEmpty()) {
ActivityCompat.requestPermissions(
this,
allNeededPermissions.toTypedArray(),
PERMISSION_REQUESTS
)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
Log.i(TAG, "Permission granted!")
if (allPermissionsGranted()) {
bindAllCameraUseCases()
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
companion object {
private const val TAG = "CameraXLivePreview"
private const val PERMISSION_REQUESTS = 1
private const val FACE_DETECTION = "Face Detection"
private const val STATE_LENS_FACING = "lens_facing"
private fun isPermissionGranted(
context: Context,
permission: String?
): Boolean {
if (ContextCompat.checkSelfPermission(context, permission!!)
== PackageManager.PERMISSION_GRANTED
) {
Log.i(TAG, "Permission granted: $permission")
return true
}
Log.i(TAG, "Permission NOT granted: $permission")
return false
}
}
}
| 0 | Kotlin | 0 | 0 | ebc06fbbb8f56b0273e96c0908978cebc64ab795 | 12,746 | mlkit-face-detector | Apache License 2.0 |
app/src/main/java/com/stratagile/qlink/ui/activity/my/component/EpidemicClaimComponent.kt | qlcchain | 115,608,966 | false | null | package com.stratagile.qlink.ui.activity.my.component
import com.stratagile.qlink.application.AppComponent
import com.stratagile.qlink.ui.activity.base.ActivityScope
import com.stratagile.qlink.ui.activity.my.EpidemicClaimActivity
import com.stratagile.qlink.ui.activity.my.module.EpidemicClaimModule
import dagger.Component
/**
* @author hzp
* @Package com.stratagile.qlink.ui.activity.my
* @Description: The component for EpidemicClaimActivity
* @date 2020/04/15 17:22:27
*/
@ActivityScope
@Component(dependencies = arrayOf(AppComponent::class), modules = arrayOf(EpidemicClaimModule::class))
interface EpidemicClaimComponent {
fun inject(EpidemicClaimActivity: EpidemicClaimActivity): EpidemicClaimActivity
} | 1 | null | 18 | 46 | 1c8066e4ebbb53c7401751ea3887a6315ccbe5eb | 723 | QWallet-Android | MIT License |
library/src/commonMain/kotlin/com/befrvnk/knotion/endpoints/databases/CreateDatabaseParams.kt | befrvnk | 672,042,674 | false | {"Kotlin": 76571} | package com.befrvnk.knotion.endpoints.databases
import com.befrvnk.knotion.objects.database.DatabaseProperties
import com.befrvnk.knotion.objects.other.Parent
import com.befrvnk.knotion.objects.richtext.RichText
import kotlinx.serialization.Serializable
@Serializable
data class CreateDatabaseParams(
val parent: Parent,
val title: List<RichText>,
val properties: DatabaseProperties,
) | 1 | Kotlin | 0 | 0 | 19b7164c8c662cc7e6a6953311b21565c7798516 | 399 | knotion | MIT License |
src/test/kotlin/io/github/tiagodocouto/helper/infra/Mongo.kt | tiagodocouto | 677,972,009 | false | null | /*
* Copyright (c) 2023 RealmKit
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package dev.realmkit.hellper.infra
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.test.context.DynamicPropertyRegistry
import org.testcontainers.containers.MongoDBContainer
/**
* # [Mongo]
* Wraps the [MongoDB][MongoTemplate] container
*/
object Mongo {
private const val MONGO_DOCKER_IMAGE = "mongo:latest"
private val container by lazy {
MongoDBContainer(MONGO_DOCKER_IMAGE).apply {
start()
}
}
/**
* Clears the [MongoDB][MongoTemplate] collections
*
* @param registry the [property registry][DynamicPropertyRegistry]
* @return nothing
* @see DynamicPropertyRegistry
*/
fun registry(registry: DynamicPropertyRegistry) =
registry.add("spring.data.mongodb.uri") { container.replicaSetUrl }
}
| 28 | Kotlin | 0 | 1 | bde3f410cc4f075f5330ea828e5408dab8abfb47 | 1,931 | player-service | MIT License |
src/main/kotlin/cn/disy920/okapi/bot/OneBot.kt | disymayufei | 779,888,694 | false | {"Kotlin": 129606} | package cn.disy920.okapi.bot
import cn.disy920.okapi.event.manager.EventManager
class OneBot {
companion object {
val eventManager = EventManager.INSTANCE
}
} | 0 | Kotlin | 0 | 2 | f541ce8ff5eb5420e3321abe84a721a4d6d62126 | 176 | OneBot-Kotlin-SDK | Apache License 2.0 |
app/src/main/java/com/example/businesscard/db/BusinessCard.kt | agamkoradiya | 286,033,319 | false | null | package com.example.businesscard.db
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.io.Serializable
@Entity(tableName = "business_card_table")
data class BusinessCard(
val cardDesignCode: String,
val isMy: Boolean,
val companyName: String,
val jobTitle: String,
val ownerName: String,
val phoneNumber: String,
val mailAddress: String,
val websiteUrl: String,
val address: String
) : Serializable {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
} | 2 | Kotlin | 3 | 4 | 660939de700ece62409acb3dfc2f9ecb5d755b55 | 518 | Business-Card-Sharing-Saver-App | MIT License |
app/src/main/java/com/ryz/kryption/module/MainModule.kt | MhmmdRFadhil | 439,800,994 | false | null | package com.ryz.kryption.module
import com.ryz.kryption.ui.MainPresenter
import org.koin.dsl.module
val mainModule = module {
factory { MainPresenter() }
} | 0 | Kotlin | 0 | 0 | 562eae1e590ba3f4acb77cbcea717aefabd1ad60 | 161 | Kryption | MIT License |
app/src/main/java/vac/test/aidldemo/MainActivity.kt | Vaccae | 680,685,548 | false | null | package vac.test.aidldemo
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import vac.test.aidldemo.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var mAdapter: TestDataAdapter
private fun bindAidlService() {
val intent = Intent()
// AIDLService中的包名
val pkg = "vac.test.aidlservice"
// AIDLService中定义的action
val act = "AIDL_SERVICE"
val cls = "vac.test.aidlservice.AidlService"
intent.action = act
intent.setClassName(pkg, cls)
val aidlserviceconnect = AidlProcessUtil.getAidlServiceConnection()
val bl = bindService(intent, aidlserviceconnect, BIND_AUTO_CREATE)
Log.i("aidlpkg", "bindservice ${bl}")
if (!bl) {
Snackbar.make(
binding.recyclerView,
"AIDL_SERVICEE服务绑定失败,请检查是否安装服务程序",
Snackbar.LENGTH_INDEFINITE
)
.setAction("关闭") {
Toast.makeText(this, "点击关闭按钮", Toast.LENGTH_SHORT).show()
}
.show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
mAdapter = TestDataAdapter()
mAdapter.submitList(null)
val layoutManager = LinearLayoutManager(this)
binding.recyclerView.layoutManager = layoutManager
binding.recyclerView.adapter = mAdapter
val curProcessName = AidlProcessUtil.getCurrentProcessName(this)
if (curProcessName == packageName) {
bindAidlService()
}
binding.btngetlist.setOnClickListener {
AidlProcessUtil.getAidlService()?.testDatas?.let {
mAdapter.submitList(it)
}
}
binding.btngetdata.setOnClickListener { view ->
AidlProcessUtil.getAidlService()?.getTestData("00001")?.let { p ->
val msg = "编码${p.code} 名称:${p.name} 价格:${p.price} 数量:${p.qty}"
Snackbar.make(view, msg, Snackbar.LENGTH_LONG).setAction("Action", null).show()
}
}
}
} | 0 | Kotlin | 0 | 0 | 9eb8bcbd90896ecce8ab1e45f64dbaa07fcb64e9 | 2,519 | AndroidAIDLDemo | Apache License 2.0 |
core/domain/src/main/java/com/github/mukiva/openweather/core/domain/weather/Speed.kt | MUKIVA | 715,584,869 | false | {"Kotlin": 323153} | package com.github.mukiva.openweather.core.domain.weather
import com.github.mukiva.openweather.core.domain.settings.UnitsType
data class Speed(
val unitsType: UnitsType,
private val kph: Double,
private val mph: Double,
) {
val value: Double
get() = when (unitsType) {
UnitsType.METRIC -> kph
UnitsType.IMPERIAL -> mph
}
}
| 0 | Kotlin | 0 | 5 | c616fcc30cbea2fa079fac76c4eb16ec6922705d | 381 | open-weather | Apache License 2.0 |
mvc/src/main/kotlin/com/marwoj/eeaao/mvc/ActivityController.kt | marwoj | 604,318,053 | false | null | package com.marwoj.eeaao.mvc
import com.marwoj.eeaao.model.Activity
import com.marwoj.eeaao.model.ActivityDetails
import com.marwoj.eeaao.model.Author
import com.marwoj.eeaao.model.AuthorStatistics
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.Future
@RestController
class ActivityController(
private val activityRepository: ActivityRepository,
private val authorRepository: AuthorRepository,
) {
@GetMapping("/activities/author/{authorId}")
fun activitiesByAuthor(@PathVariable authorId: String): List<Activity> =
activityRepository.findAllByAuthorId(authorId)
@GetMapping("/activities/{activityId}/author")
fun activityDetails(@PathVariable activityId: String): ActivityDetails {
val activity = activityRepository.findById(activityId).orElseThrow { Exception("Activity does not exist") }
val author = authorRepository.findById(activity.authorId).orElseThrow { Exception("Author does not exist") }
return ActivityDetails(title = activity.title, firstName = author.firstName, lastName = author.lastName)
}
@GetMapping("/activities/author/{authorId}/statistics")
fun authorStatistics(@PathVariable authorId: String): AuthorStatistics =
// try with resources in Kotlin
Executors.newSingleThreadExecutor().use { executor ->
val author: Future<Author> =
executor.submit(Callable {
authorRepository.findById(authorId).orElseThrow { Exception("Author does not exist") }
})
val activitiesCount: Future<Long> =
executor.submit(Callable { activityRepository.countActivitiesByAuthorId(authorId) })
AuthorStatistics(
firstName = author.get().firstName,
lastName = author.get().lastName,
activitiesCount = activitiesCount.get()
)
}
}
| 0 | Kotlin | 0 | 0 | 1f664b4f8f301a72271e3f0bdc40ce54c54c7b41 | 2,121 | Everything-Everywhere-All-at-Once | Apache License 2.0 |
demo/composeApp/src/commonMain/kotlin/ovh/plrapps/mapcompose/demo/viewmodels/CenteringOnMarkerVM.kt | p-lr | 777,977,251 | false | {"Kotlin": 270653} | package ovh.plrapps.mapcompose.demo.viewmodels
import androidx.compose.foundation.layout.size
import androidx.compose.material.Icon
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.model.ScreenModel
import cafe.adriel.voyager.core.model.screenModelScope
import kotlinx.coroutines.launch
import mapcompose_mp.demo.composeapp.generated.resources.Res
import mapcompose_mp.demo.composeapp.generated.resources.map_marker
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
import ovh.plrapps.mapcompose.api.addLayer
import ovh.plrapps.mapcompose.api.addMarker
import ovh.plrapps.mapcompose.api.centerOnMarker
import ovh.plrapps.mapcompose.api.enableRotation
import ovh.plrapps.mapcompose.demo.providers.makeTileStreamProvider
import ovh.plrapps.mapcompose.ui.state.MapState
class CenteringOnMarkerVM(): ScreenModel {
private val tileStreamProvider = makeTileStreamProvider()
@OptIn(ExperimentalResourceApi::class)
val state = MapState(4, 4096, 4096) {
rotation(45f)
}.apply {
addLayer(tileStreamProvider)
addMarker("parking", 0.2457938, 0.3746023) {
Icon(
painter = painterResource(Res.drawable.map_marker),
contentDescription = null,
modifier = Modifier.size(50.dp),
tint = Color(0xCC2196F3)
)
}
enableRotation()
}
fun onCenter() {
screenModelScope.launch {
state.centerOnMarker("parking", destScale = 1f, destAngle = 0f)
}
}
} | 8 | Kotlin | 4 | 10 | 62a0975976f250208abb62e5add7736eea538bd0 | 1,673 | MapComposeMP | Apache License 2.0 |
example/src/main/kotlin/student/infrastructure/adapter/out/query/TimetableQueryAdapter.kt | holixon | 751,579,530 | false | {"Kotlin": 133130, "JavaScript": 185} | package io.holixon.example.university.student.infrastructure.adapter.out.query
import io.holixon.example.university.student.application.port.out.TimetableOutPort
import io.holixon.example.university.student.domain.query.Timetable
import io.holixon.example.university.student.infrastructure.adapter.out.query.impl.TimetableByMatriculationNumber
import org.axonframework.messaging.responsetypes.ResponseTypes
import org.axonframework.queryhandling.QueryGateway
import org.springframework.stereotype.Component
import java.util.*
@Component
class TimetableQueryAdapter(
private val queryGateway: QueryGateway
) : TimetableOutPort {
override fun getTimetableByMatriculationNumber(matriculationNumber: String): Timetable? {
return queryGateway
.query(
"findTimetable",
TimetableByMatriculationNumber(matriculationNumber = matriculationNumber),
ResponseTypes.optionalInstanceOf(Timetable::class.java)
).join()
.toKotlin()
}
fun <T> Optional<T>.toKotlin(): T? = if (this.isEmpty) {
null
} else {
this.get()
}
}
| 1 | Kotlin | 0 | 1 | 4f1d71fe38eed1af87ba302a9045dd00afc84d08 | 1,074 | axon-eclipse-store-projection-example | Apache License 2.0 |
app/src/main/java/com/example/bankuish_technical_challenge/data/response/githubRepo/GithubRepoLicenseDTO.kt | MJackson22-bit | 842,190,889 | false | {"Kotlin": 68012} | package com.example.bankuish_technical_challenge.data.response.githubRepo
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class GithubRepoLicenseDTO(
@SerialName("key") val key: String? = null,
@SerialName("name") val name: String? = null,
@SerialName("spdx_id") val spdxId: String? = null,
@SerialName("url") val url: String? = null,
@SerialName("node_id") val nodeId: String? = null
)
| 0 | Kotlin | 0 | 0 | faf1fbd0483ade4fa9bddbd1de7e7e5e20231c44 | 462 | bankuish-technical-challenge | MIT License |
app/src/main/kotlin/com/yajatkumar/newsapp/SettingsActivity.kt | YAJATapps | 418,653,307 | false | {"Kotlin": 76190} | package com.yajatkumar.newsapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import com.yajatkumar.newsapp.databinding.ActivitySettingsBinding
import com.yajatkumar.newsapp.fragment.SettingsFragment
/**
* The settings activity to set preferences for the app
*/
class SettingsActivity : AppCompatActivity() {
private lateinit var binding: ActivitySettingsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySettingsBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
// Set the custom toolbar
setSupportActionBar(binding.customToolbar.toolbarCentered)
supportActionBar?.setDisplayShowTitleEnabled(false)
binding.customToolbar.toolbarTitle.text = resources.getString(R.string.settings)
// Display the back button in actionBar
supportActionBar?.setDisplayHomeAsUpEnabled(true)
// Replace the settings_container with SettingsFragment
supportFragmentManager
.beginTransaction()
.replace(R.id.settings_container, SettingsFragment())
.commit()
}
// Finish the activity when back button is clicked
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
} | 0 | Kotlin | 0 | 2 | a1b876024c4a6851f0e3280f3d48a45bcd5ea58f | 1,556 | NewsApp | Apache License 2.0 |
services/csm.cloud.project.notifications/src/main/kotlin/com/bosch/pt/csm/cloud/projectmanagement/project/daycard/repository/DayCardRepositoryExtension.kt | boschglobal | 805,348,245 | false | {"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344} | /*
* *************************************************************************
*
* Copyright: Robert Bosch Power Tools GmbH, 2019
*
* *************************************************************************
*/
package com.bosch.pt.csm.cloud.projectmanagement.project.daycard.repository
import com.bosch.pt.csm.cloud.projectmanagement.project.daycard.model.DayCard
import java.util.UUID
interface DayCardRepositoryExtension {
fun find(identifier: UUID, version: Long, projectIdentifier: UUID): DayCard
fun findDayCards(projectIdentifier: UUID): List<DayCard>
fun deleteDayCard(identifier: UUID, projectIdentifier: UUID)
}
| 0 | Kotlin | 3 | 9 | 9f3e7c4b53821bdfc876531727e21961d2a4513d | 646 | bosch-pt-refinemysite-backend | Apache License 2.0 |
VIewpagerDemo/app/src/main/java/com/notrace/demo/CardFragment.kt | messnoTrace | 107,351,335 | false | null | package com.notrace.demo
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.CardView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
/**
* Created by smile-up on 2017/10/18.
*/
class CardFragment:Fragment() {
var mCardView:CardView? =null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var view=inflater!!.inflate(R.layout.fragment_card,container,false)
mCardView=view.findViewById(R.id.cardView)
mCardView?.maxCardElevation=mCardView!!.cardElevation*8
return view
}
fun getCardView():CardView?{
return mCardView
}
} | 0 | Kotlin | 0 | 0 | 484fa20dea8f3d1482dc66e2f266ce8032561c92 | 739 | ViewPagerCardDemo | Apache License 2.0 |
VIewpagerDemo/app/src/main/java/com/notrace/demo/CardFragment.kt | messnoTrace | 107,351,335 | false | null | package com.notrace.demo
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.CardView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
/**
* Created by smile-up on 2017/10/18.
*/
class CardFragment:Fragment() {
var mCardView:CardView? =null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var view=inflater!!.inflate(R.layout.fragment_card,container,false)
mCardView=view.findViewById(R.id.cardView)
mCardView?.maxCardElevation=mCardView!!.cardElevation*8
return view
}
fun getCardView():CardView?{
return mCardView
}
} | 0 | Kotlin | 0 | 0 | 484fa20dea8f3d1482dc66e2f266ce8032561c92 | 739 | ViewPagerCardDemo | Apache License 2.0 |
src/main/kotlin/io/saagie/astonparking/domain/Request.kt | saagie | 98,111,756 | false | null | package io.saagie.astonparking.domain
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.time.LocalDate
import java.time.LocalDateTime
@Document
data class Request (
@Id val id: String? = null,
val date: LocalDate,
val userId: String,
val submitDate: LocalDateTime
) | 1 | Kotlin | 1 | 0 | d5cb3c6d16f146e78716e458f09e35927d4c113b | 369 | aston-parking | MIT License |
app/src/main/java/com/ghstudios/android/data/cursors/QuestCursor.kt | gatheringhallstudios | 60,881,315 | false | null | package com.ghstudios.android.data.cursors
import android.database.Cursor
import android.database.CursorWrapper
import com.ghstudios.android.data.classes.Location
import com.ghstudios.android.data.classes.Quest
import com.ghstudios.android.data.classes.QuestHub
import com.ghstudios.android.data.database.S
import com.ghstudios.android.data.util.getInt
import com.ghstudios.android.data.util.getLong
import com.ghstudios.android.data.util.getString
/**
* A convenience class to wrap a cursor that returns rows from the "quests"
* table. The [] method will give you a Quest instance
* representing the current row.
*/
class QuestCursor(c: Cursor) : CursorWrapper(c) {
/**
* Returns a Quest object configured for the current row, or null if the
* current row is invalid.
*/
//0=Normal,1=Key,2=Urgent
val quest: Quest
get() {
val quest = Quest().apply {
id = getLong(S.COLUMN_QUESTS_ID)
name = getString("q" + S.COLUMN_QUESTS_NAME) ?: ""
jpnName = getString("q" + S.COLUMN_QUESTS_JPN_NAME) ?: ""
goal = getString(S.COLUMN_QUESTS_GOAL)
hub = QuestHub.from(getString(S.COLUMN_QUESTS_HUB)!!)
type = getInt(S.COLUMN_QUESTS_TYPE)
stars = getString(S.COLUMN_QUESTS_STARS)
timeLimit = getInt(S.COLUMN_QUESTS_TIME_LIMIT)
fee = getInt(S.COLUMN_QUESTS_FEE)
reward = getInt(S.COLUMN_QUESTS_REWARD)
hrp = getInt(S.COLUMN_QUESTS_HRP)
subGoalA = getString(S.COLUMN_QUESTS_SUB_A_GOAL)
subRewardA = getInt(S.COLUMN_QUESTS_SUB_A_REWARD)
subHrpA = getInt(S.COLUMN_QUESTS_SUB_A_HRP)
subGoalB = getString(S.COLUMN_QUESTS_SUB_B_GOAL)
subRewardB = getInt(S.COLUMN_QUESTS_SUB_B_REWARD)
subHrpB = getInt(S.COLUMN_QUESTS_SUB_B_HRP)
goalType = getInt(S.COLUMN_QUESTS_GOAL_TYPE)
hunterType = getInt(S.COLUMN_QUESTS_HUNTER_TYPE)
flavor = getString(S.COLUMN_QUESTS_FLAVOR)
hirer = getString(S.COLUMN_QUESTS_HIRER)
metadata = getInt(S.COLUMN_QUESTS_METADATA)
rank = getString(S.COLUMN_QUESTS_RANK)
permitMonsterId = getInt(S.COLUMN_QUESTS_PERMIT_MONSTER_ID)
}
if(quest.name.isEmpty()) quest.name = quest.jpnName
quest.location = Location().apply {
id = getLong(S.COLUMN_QUESTS_LOCATION_ID)
name = getString("l" + S.COLUMN_LOCATIONS_NAME)
fileLocation = getString(S.COLUMN_LOCATIONS_MAP)
}
return quest
}
} | 12 | null | 37 | 90 | 572ede48d78b9f61a91c7ef1fc64f87c9743b162 | 2,732 | MHGenDatabase | MIT License |
plot-demo/src/jvmBrowserMain/kotlin/plotDemo/plotConfig/BackgroundPinkBrowser.kt | JetBrains | 176,771,727 | false | null | /*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plotDemo.plotConfig
import jetbrains.datalore.plotDemo.model.plotConfig.BackgroundPink
object BackgroundPinkBrowser {
@JvmStatic
fun main(args: Array<String>) {
with(BackgroundPink()) {
@Suppress("UNCHECKED_CAST")
(PlotConfigBrowserDemoUtil.show(
"Plot background - pink (in a pink window)",
plotSpecList(),
backgroundColor = "pink"
))
}
}
}
| 93 | Kotlin | 47 | 889 | 2fb1fe8e812ed0b84cd32954331a76775e75d4d2 | 628 | lets-plot | MIT License |
api/src/main/kotlin/dev/gleroy/ivanachess/api/security/AuthenticationController.kt | hugoamalric | 378,921,142 | false | null | package dev.gleroy.ivanachess.api.security
import dev.gleroy.ivanachess.api.AbstractController
import dev.gleroy.ivanachess.api.Properties
import dev.gleroy.ivanachess.io.ApiConstants
import dev.gleroy.ivanachess.io.Credentials
import dev.gleroy.ivanachess.io.UserConverter
import dev.gleroy.ivanachess.io.UserRepresentation
import org.springframework.http.HttpStatus
import org.springframework.security.core.Authentication
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import java.time.Clock
import java.time.Duration
import javax.servlet.http.HttpServletResponse
import javax.validation.Valid
/**
* Authentication API controller.
*
* @param service Authentication service.
* @param userConverter User converter.
* @param clock Clock.
* @param props Properties.
*/
@RestController
@RequestMapping(ApiConstants.Authentication.Path)
@Validated
class AuthenticationController(
private val service: AuthenticationService,
private val userConverter: UserConverter,
private val clock: Clock,
override val props: Properties,
) : AbstractController() {
/**
* Generate JWT for user.
*
* @param creds Credentials.
* @param response HTTP response.
*/
@PostMapping
@ResponseStatus(HttpStatus.NO_CONTENT)
fun logIn(@RequestBody @Valid creds: Credentials, response: HttpServletResponse) {
val jwt = service.generateJwt(creds.pseudo, creds.password)
val maxAge = Duration.between(clock.instant(), jwt.expirationDate).toSeconds().toInt()
response.addHeader(props.auth.header.name, "${props.auth.header.valuePrefix}${jwt.token}")
response.addCookie(createAuthenticationCookie(jwt.token, maxAge))
}
/**
* Delete authentication cookie.
*
* @param response HTTP response.
*/
@DeleteMapping
@ResponseStatus(HttpStatus.NO_CONTENT)
fun logOut(response: HttpServletResponse) {
response.addCookie(expireAuthenticationCookie())
}
/**
* Get current authenticated user.
*
* @param auth Authentication.
* @return Representation of user.
*/
@GetMapping
@ResponseStatus(HttpStatus.OK)
fun me(auth: Authentication): UserRepresentation {
return userConverter.convertToPrivateRepresentation(authenticatedUser(auth))
}
}
| 0 | null | 0 | 0 | 6e6b8da2b5b84fc2ad946ddd7899c35904974a87 | 2,354 | ivana-chess | Apache License 2.0 |
src/main/kotlin/ReflectFun.kt | congwiny | 172,692,942 | false | {"Gradle": 3, "INI": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "Java": 12, "Kotlin": 26, "Java Properties": 1, "XML": 6} | package reflect.func
import kotlin.reflect.full.createInstance
import kotlin.reflect.full.functions
class Person {
var name: String? = null
var age: Int = 0
//成员函数
fun setNameAndAge(name: String, age: Int) {
this.name = name
this.age = age
}
override fun toString(): String {
return "Person [name=$name, age=$age]"
}
}
//Person扩展函数
fun Person.getNameAndAge() = "name=$name,age=$age"
fun main() {
val clz = Person::class
val person = clz.createInstance()
clz.functions.forEach { println(it.name) }
val pfn1 = clz.functions.first()
pfn1.call(person, "Tom", 20)
println(person)
val pfn2 = Person::setNameAndAge //KFunction3<Person,String,Int,Unit>
pfn2(person, "Tony", 18) // Person [name=Tom, age=20]
println(person) // Person [name=Tony, age=18]
pfn2.call(person, "Ben", 28)
println(person) // Person [name=Ben, age=28]
pfn2.invoke(person,"Catty",16)
println(person) //Person [name=Catty, age=16]
val pfn3 = Person::getNameAndAge //KFunction3<Person,String>
println(pfn3(person))
} | 0 | Kotlin | 0 | 0 | 8c8ac2f83b32deaa8400afff342131e645aac73b | 1,103 | KotlinShare | Apache License 2.0 |
src/mingwX64Main/kotlin/io/github/reblast/kpresence/ipc/IPC.kt | reblast | 770,371,275 | false | {"Kotlin": 26219} | package io.github.reblast.kpresence.ipc
import io.github.reblast.kpresence.utils.putInt
import io.github.reblast.kpresence.utils.reverseBytes
import kotlinx.cinterop.*
import platform.posix.close
import platform.posix.errno
import platform.posix.read
import platform.posix.write
import platform.windows.*
@OptIn(ExperimentalForeignApi::class)
actual fun readBytes(handle: Int, bufferSize: Int): ByteArray {
if (handle == -1) throw IllegalStateException("Not connected")
val buffer = ByteArray(bufferSize)
val bytesRead = read(handle, buffer.refTo(0), buffer.size.toUInt())
return buffer.copyOf(bytesRead)
}
@OptIn(ExperimentalForeignApi::class)
actual fun writeBytes(handle: Int, opcode: Int, data: String) {
if (handle == -1) throw IllegalStateException("Not connected")
val bytes = data.encodeToByteArray()
val buffer = ByteArray(bytes.size + 8)
buffer.putInt(opcode.reverseBytes())
buffer.putInt(bytes.size.reverseBytes(), 4)
bytes.copyInto(buffer, 8)
write(handle, buffer.refTo(0), buffer.size.toUInt())
}
| 0 | Kotlin | 0 | 3 | 83833eb1125be68527ff4eb4c2538475bb6f92ed | 1,044 | KPresence | MIT License |
VCL/src/test/java/io/velocitycareerlabs/entities/VCLTokenTest.kt | velocitycareerlabs | 525,006,413 | false | {"Kotlin": 801591} | /**
* Created by Michael Avoyan on 24/12/2023.
*
* Copyright 2022 Velocity Career Labs inc.
* SPDX-License-Identifier: Apache-2.0
*/
package io.velocitycareerlabs.entities
import io.velocitycareerlabs.api.entities.VCLToken
import io.velocitycareerlabs.infrastructure.resources.valid.TokenMocks
import org.junit.Test
class VCLTokenTest {
lateinit var subject: VCLToken
@Test
fun testToken1() {
subject = VCLToken(value = TokenMocks.TokenStr)
assert(subject.value == TokenMocks.TokenStr)
assert(subject.jwtValue.encodedJwt == TokenMocks.TokenStr)
assert(subject.expiresIn == 1704020514L)
}
@Test
fun testToken2() {
subject = VCLToken(jwtValue = TokenMocks.TokenJwt)
assert(subject.value == TokenMocks.TokenJwt.encodedJwt)
assert(subject.jwtValue.encodedJwt == TokenMocks.TokenJwt.encodedJwt)
assert(subject.expiresIn == 1704020514L)
}
} | 4 | Kotlin | 0 | 1 | a94a66b42d7a92730a35818ad478c2d405ce1ccb | 939 | WalletAndroid | Apache License 2.0 |
app/src/main/java/com/example/myapplication/ui/mood_test_pager/MoodTestPagerViewModel.kt | AssasinNik | 751,365,646 | false | {"Kotlin": 183992, "Java": 97790} | package com.example.myapplication.ui.mood_test_pager
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.data.movie_data.Movie
import com.example.myapplication.data.movie_data.MovieRepository
import com.example.myapplication.data.questions_data.QuestionRepository
import com.example.myapplication.data.remote.PostService
import com.example.myapplication.data.remote.dto.FilmErrorResponse
import com.example.myapplication.data.remote.dto.FilmListResponse
import com.example.myapplication.data.remote.dto.PostRequestMood
import com.example.myapplication.data.user_data.UserRepository
import com.example.myapplication.util.Routes
import com.example.myapplication.util.UiEvent
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class MoodTestPagerViewModel @Inject constructor(
private val questionRepository: QuestionRepository,
private val userRepository: UserRepository,
private val movieRepository: MovieRepository,
): ViewModel() {
var token by mutableStateOf("")
private set
private val uniqueRandomNumbers = generateUniqueRandomNumbers(24)
val question1 = questionRepository.getQuestionsById(uniqueRandomNumbers[0])
val question2 = questionRepository.getQuestionsById(uniqueRandomNumbers[1])
val question3 = questionRepository.getQuestionsById(uniqueRandomNumbers[2])
val question4 = questionRepository.getQuestionsById(uniqueRandomNumbers[3])
val question5 = questionRepository.getQuestionsById(uniqueRandomNumbers[4])
var answer1 by mutableStateOf("")
var answer2 by mutableStateOf("")
var answer3 by mutableStateOf("")
var answer4 by mutableStateOf("")
var answer5 by mutableStateOf("")
val genresRating = mutableMapOf(
"спорт" to 0,
"биография" to 0,
"комедия" to 0,
"ужасы" to 0,
"боевик" to 0,
"драма" to 0,
"мелодрама" to 0,
"мультфильм" to 0,
"фэнтези" to 0,
"фантастика" to 0,
"криминал" to 0,
"триллер" to 0,
"приключения" to 0,
"детектив" to 0,
"военный" to 0
)
private val _uiEvent = Channel<UiEvent>()
val uiEvent = _uiEvent.receiveAsFlow()
fun onEvent(event: MoodTestPagerEvent) {
when (event) {
is MoodTestPagerEvent.onCloseIconClick -> {
sendUiEvent(UiEvent.PopBackStack)
}
is MoodTestPagerEvent.onLastPageClick -> {
val answers = mutableListOf<String>()
listOf(answer1, answer2, answer3, answer4, answer5).forEach { answer ->
answers .addAll(answer.split(" ", ignoreCase = true, limit = 0))
}
for (answer in answers) {
when (answer.toLowerCase()) {
"спорт" -> genresRating["спорт"] = genresRating["спорт"]?.plus(1) ?: 1
"биография" -> genresRating["биография"] = genresRating["биография"]?.plus(1) ?: 1
"комедия" -> genresRating["комедия"] = genresRating["комедия"]?.plus(1) ?: 1
"ужасы" -> genresRating["ужасы"] = genresRating["ужасы"]?.plus(1) ?: 1
"боевик" -> genresRating["боевик"] = genresRating["боевик"]?.plus(1) ?: 1
"драма" -> genresRating["драма"] = genresRating["драма"]?.plus(1) ?: 1
"мелодрама" -> genresRating["мелодрама"] = genresRating["мелодрама"]?.plus(1) ?: 1
"мультфильм" -> genresRating["мультфильм"] = genresRating["мультфильм"]?.plus(1) ?: 1
"фэнтези" -> genresRating["фэнтези"] = genresRating["фэнтези"]?.plus(1) ?: 1
"фантастика" -> genresRating["фантастика"] = genresRating["фантастика"]?.plus(1) ?: 1
"криминал" -> genresRating["криминал"] = genresRating["криминал"]?.plus(1) ?: 1
"триллер" -> genresRating["триллер"] = genresRating["триллер"]?.plus(1) ?: 1
"приключения" -> genresRating["приключения"] = genresRating["приключения"]?.plus(1) ?: 1
"детектив" -> genresRating["детектив"] = genresRating["детектив"]?.plus(1) ?: 1
"военный" -> genresRating["военный"] = genresRating["военный"]?.plus(1) ?: 1
}
}
//Твой код получения фильмов и добавление их в ROOM
getFilms(token,genresRating)
}
}
}
init {
viewModelScope.launch {
userRepository.getUser()?.let { user ->
token = user.token
}
}
}
private fun sendUiEvent(event: UiEvent) {
viewModelScope.launch {
_uiEvent.send(event)
}
}
fun getFilms(token: String , genresRating: MutableMap<String, Int>) {
val topTwoEntries = genresRating.entries.sortedByDescending { it.value }.take(2)
val valuesArray = topTwoEntries.map { it.key }.toTypedArray()
val individualArrays = mutableListOf<Array<String>>()
valuesArray.forEach { key ->
individualArrays.add(arrayOf(key))
}
val apiService = PostService.create()
Log.d("MoodScreenViewModel", "Starting getFilms with token: $token")
if (apiService == null) {
Log.e("MoodScreenViewModel", "apiService is null at the time of the call")
} else {
Log.d("MoodScreenViewModel", "apiService is initialized")
}
val filmRequest = PostRequestMood(token, valuesArray)
viewModelScope.launch {
val response = apiService.Post_MovieMood(filmRequest)
when (response) {
is FilmListResponse -> {
var count = 0
response.data?.forEach { film ->
if (count < 7) {
val movie = Movie(
movieId = film.movie_id,
title = film.title ?: "",
titleEn = film.titleEn ?: "",
genres = film.genres.joinToString(", "),
posterURL = film.posterURL,
rating = film.rating.toInt(),
length = film.length,
description = film.description ?: "",
releaseYear = film.releaseDate.toString(),
ageLimit = film.ageLimit.toString()
)
viewModelScope.launch(Dispatchers.IO) {
movieRepository.deleteMovies()
movieRepository.insertFilms(movie)
}
Log.d("RegisterScreenViewModel", "Movie fetched and saved: ${film.title}")
sendUiEvent(UiEvent.Navigate(Routes.MOVIE_LIST_SCREEN))
count++
}
}
}
is FilmErrorResponse -> {
println("Fetching movies failed: ${response.message}")
Log.e("MoodScreenViewModel", "Fetching movies failed: ${response.message}")
}
else -> {
println("An unexpected error occurred during fetching movies")
Log.e("MoodScreenViewModel", "An unexpected error occurred during fetching movies")
}
}
}
val filmRequest1 = PostRequestMood(token, individualArrays[0])
viewModelScope.launch {
val response = apiService.Post_MovieMood(filmRequest1)
when (response) {
is FilmListResponse -> {
var count = 0
response.data?.forEach { film ->
if (count < 3) {
val movie = Movie(
movieId = film.movie_id,
title = film.title ?: "",
titleEn = film.titleEn ?: "",
genres = film.genres.joinToString(", "),
posterURL = film.posterURL,
rating = film.rating.toInt(),
length = film.length,
description = film.description ?: "",
releaseYear = film.releaseDate.toString(),
ageLimit = film.ageLimit.toString()
)
viewModelScope.launch(Dispatchers.IO) {
movieRepository.insertFilms(movie)
}
Log.d("RegisterScreenViewModel", "Movie fetched and saved: ${film.title}")
sendUiEvent(UiEvent.Navigate(Routes.MOVIE_LIST_SCREEN))
count++
}
}
}
is FilmErrorResponse -> {
println("Fetching movies failed: ${response.message}")
Log.e("MoodScreenViewModel", "Fetching movies failed: ${response.message}")
}
else -> {
println("An unexpected error occurred during fetching movies")
Log.e("MoodScreenViewModel", "An unexpected error occurred during fetching movies")
}
}
}
val filmRequest2 = PostRequestMood(token, individualArrays[1])
viewModelScope.launch {
val response = apiService.Post_MovieMood(filmRequest2)
when (response) {
is FilmListResponse -> {
var count = 0
response.data?.forEach { film ->
if (count < 3) {
val movie = Movie(
movieId = film.movie_id,
title = film.title ?: "",
titleEn = film.titleEn ?: "",
genres = film.genres.joinToString(", "),
posterURL = film.posterURL,
rating = film.rating.toInt(),
length = film.length,
description = film.description ?: "",
releaseYear = film.releaseDate.toString(),
ageLimit = film.ageLimit.toString()
)
viewModelScope.launch(Dispatchers.IO) {
movieRepository.insertFilms(movie)
}
Log.d("RegisterScreenViewModel", "Movie fetched and saved: ${film.title}")
sendUiEvent(UiEvent.Navigate(Routes.MOVIE_LIST_SCREEN))
count++
}
}
}
is FilmErrorResponse -> {
println("Fetching movies failed: ${response.message}")
Log.e("MoodScreenViewModel", "Fetching movies failed: ${response.message}")
}
else -> {
println("An unexpected error occurred during fetching movies")
Log.e("MoodScreenViewModel", "An unexpected error occurred during fetching movies")
}
}
}
}
private fun generateUniqueRandomNumbers(max: Int): List<Int> {
val numbers = mutableSetOf<Int>()
while (numbers.size < 6) {
val randomNumber = (0..max).random()
numbers.add(randomNumber)
}
return numbers.toList()
}
} | 0 | Kotlin | 0 | 1 | 731cf4758f4c398b1780f4cd4625e98cd60ee8ef | 12,333 | Films_mob_app | Apache License 2.0 |
src/commonMain/kotlin/com/jeffpdavidson/kotwords/formats/unidecode/xa8.kt | jpd236 | 143,651,464 | false | {"Kotlin": 4431127, "HTML": 41941, "Rouge": 3731, "Perl": 1705, "Shell": 744, "JavaScript": 618} | package com.jeffpdavidson.kotwords.formats.unidecode
internal val xa8 = arrayOf(
// 0xa800: ꠀ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa801: ꠁ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa802: ꠂ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa803: ꠃ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa804: ꠄ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa805: ꠅ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa806: ꠆ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa807: ꠇ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa808: ꠈ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa809: ꠉ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa80a: ꠊ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa80b: ꠋ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa80c: ꠌ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa80d: ꠍ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa80e: ꠎ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa80f: ꠏ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa810: ꠐ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa811: ꠑ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa812: ꠒ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa813: ꠓ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa814: ꠔ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa815: ꠕ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa816: ꠖ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa817: ꠗ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa818: ꠘ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa819: ꠙ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa81a: ꠚ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa81b: ꠛ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa81c: ꠜ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa81d: ꠝ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa81e: ꠞ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa81f: ꠟ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa820: ꠠ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa821: ꠡ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa822: ꠢ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa823: ꠣ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa824: ꠤ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa825: ꠥ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa826: ꠦ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa827: ꠧ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa828: ꠨ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa829: ꠩ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa82a: ꠪ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa82b: ꠫ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa82c: ꠬ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa82d: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa82e: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa82f: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa830: ꠰ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa831: ꠱ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa832: ꠲ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa833: ꠳ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa834: ꠴ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa835: ꠵ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa836: ꠶ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa837: ꠷ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa838: ꠸ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa839: ꠹ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa83a: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa83b: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa83c: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa83d: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa83e: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa83f: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa840: ꡀ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa841: ꡁ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa842: ꡂ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa843: ꡃ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa844: ꡄ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa845: ꡅ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa846: ꡆ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa847: ꡇ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa848: ꡈ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa849: ꡉ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa84a: ꡊ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa84b: ꡋ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa84c: ꡌ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa84d: ꡍ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa84e: ꡎ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa84f: ꡏ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa850: ꡐ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa851: ꡑ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa852: ꡒ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa853: ꡓ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa854: ꡔ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa855: ꡕ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa856: ꡖ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa857: ꡗ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa858: ꡘ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa859: ꡙ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa85a: ꡚ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa85b: ꡛ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa85c: ꡜ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa85d: ꡝ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa85e: ꡞ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa85f: ꡟ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa860: ꡠ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa861: ꡡ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa862: ꡢ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa863: ꡣ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa864: ꡤ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa865: ꡥ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa866: ꡦ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa867: ꡧ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa868: ꡨ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa869: ꡩ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa86a: ꡪ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa86b: ꡫ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa86c: ꡬ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa86d: ꡭ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa86e: ꡮ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa86f: ꡯ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa870: ꡰ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa871: ꡱ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa872: ꡲ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa873: ꡳ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa874: ꡴ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa875: ꡵ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa876: ꡶ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa877: ꡷ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa878: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa879: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa87a: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa87b: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa87c: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa87d: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa87e: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa87f: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa880: ꢀ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa881: ꢁ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa882: ꢂ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa883: ꢃ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa884: ꢄ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa885: ꢅ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa886: ꢆ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa887: ꢇ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa888: ꢈ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa889: ꢉ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa88a: ꢊ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa88b: ꢋ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa88c: ꢌ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa88d: ꢍ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa88e: ꢎ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa88f: ꢏ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa890: ꢐ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa891: ꢑ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa892: ꢒ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa893: ꢓ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa894: ꢔ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa895: ꢕ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa896: ꢖ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa897: ꢗ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa898: ꢘ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa899: ꢙ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa89a: ꢚ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa89b: ꢛ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa89c: ꢜ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa89d: ꢝ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa89e: ꢞ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa89f: ꢟ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8a0: ꢠ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8a1: ꢡ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8a2: ꢢ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8a3: ꢣ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8a4: ꢤ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8a5: ꢥ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8a6: ꢦ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8a7: ꢧ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8a8: ꢨ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8a9: ꢩ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8aa: ꢪ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ab: ꢫ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ac: ꢬ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ad: ꢭ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ae: ꢮ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8af: ꢯ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8b0: ꢰ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8b1: ꢱ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8b2: ꢲ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8b3: ꢳ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8b4: ꢴ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8b5: ꢵ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8b6: ꢶ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8b7: ꢷ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8b8: ꢸ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8b9: ꢹ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ba: ꢺ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8bb: ꢻ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8bc: ꢼ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8bd: ꢽ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8be: ꢾ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8bf: ꢿ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8c0: ꣀ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8c1: ꣁ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8c2: ꣂ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8c3: ꣃ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8c4: ꣄ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8c5: ꣅ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8c6: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8c7: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8c8: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8c9: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ca: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8cb: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8cc: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8cd: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ce: ꣎ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8cf: ꣏ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8d0: ꣐ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8d1: ꣑ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8d2: ꣒ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8d3: ꣓ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8d4: ꣔ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8d5: ꣕ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8d6: ꣖ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8d7: ꣗ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8d8: ꣘ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8d9: ꣙ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8da: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8db: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8dc: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8dd: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8de: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8df: => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8e0: ꣠ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8e1: ꣡ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8e2: ꣢ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8e3: ꣣ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8e4: ꣤ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8e5: ꣥ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8e6: ꣦ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8e7: ꣧ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8e8: ꣨ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8e9: ꣩ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ea: ꣪ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8eb: ꣫ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ec: ꣬ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ed: ꣭ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ee: ꣮ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ef: ꣯ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8f0: ꣰ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8f1: ꣱ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8f2: ꣲ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8f3: ꣳ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8f4: ꣴ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8f5: ꣵ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8f6: ꣶ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8f7: ꣷ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8f8: ꣸ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8f9: ꣹ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8fa: ꣺ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8fb: ꣻ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8fc: ꣼ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8fd: ꣽ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8fe: ꣾ => [?]
"\u005b\u003f\u005d\u0020",
// 0xa8ff: ꣿ => [?]
"\u005b\u003f\u005d\u0020",
)
| 8 | Kotlin | 6 | 25 | 0c94260c3e9472db2e89f6c62ba715e85e1539f4 | 14,676 | kotwords | Apache License 2.0 |
dimension/src/main/java/pcb/uwu/amount/base/LuminousIntensity.kt | pedro-borges | 105,442,770 | false | {"Maven POM": 4, "Markdown": 5, "Text": 1, "Ignore List": 1, "YAML": 1, "Kotlin": 245} | package pcb.uwu.amount.base
import pcb.uwu.amount.derived.geometry.Area
import pcb.uwu.amount.derived.optics.Luminance
import pcb.uwu.amount.derived.optics.LuminousFlux
import pcb.uwu.amount.derived.scalar.SolidAngle
import pcb.uwu.core.CompositeUnitAmount
import pcb.uwu.core.Magnitude
import pcb.uwu.core.Magnitude.NATURAL
import pcb.uwu.core.UnitAmount
import pcb.uwu.unit.base.LuminousIntensityUnit
import pcb.uwu.unit.derived.geometry.AreaUnit
import pcb.uwu.unit.derived.optics.LuminanceUnit
import pcb.uwu.unit.derived.optics.LuminousFluxUnit
import pcb.uwu.util.UnitAmountUtils
open class LuminousIntensity : CompositeUnitAmount<LuminousIntensityUnit>
{
@JvmOverloads
constructor(amount: Number,
magnitude: Magnitude = NATURAL,
unit: LuminousIntensityUnit)
: super(amount, magnitude, unit)
@JvmOverloads
constructor(amount: String,
magnitude: Magnitude = NATURAL,
unit: LuminousIntensityUnit)
: super(amount, magnitude, unit)
// region UnitAmount
@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
override fun plus(luminousIntensity: UnitAmount<LuminousIntensityUnit>) =
LuminousIntensity(amount = this.amount + (luminousIntensity to this.unit).amount,
unit = this.unit)
@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
override fun minus(luminousIntensity: UnitAmount<LuminousIntensityUnit>) =
LuminousIntensity(amount = this.amount - (luminousIntensity to this.unit).amount,
unit = this.unit)
override fun times(scalar: Number) =
LuminousIntensity(amount = this.amount * scalar,
unit = this.unit)
override fun div(scalar: Number) =
LuminousIntensity(amount = this.amount / scalar,
unit = this.unit)
override fun to(unit: LuminousIntensityUnit) =
LuminousIntensity(amount = UnitAmountUtils.getAmountIn(unitAmount = this, newUnit = unit),
unit = unit)
// endregion
// region composition
open operator fun times(solidAngle: SolidAngle) =
LuminousFlux(amount = this.amount * solidAngle.amount,
unit = LuminousFluxUnit(this.unit, solidAngle.unit))
open operator fun div(area: Area) =
Luminance(amount = this.amount / area.amount,
unit = LuminanceUnit(this.unit, area.unit))
open operator fun div(luminance: Luminance) =
Area(amount = this.amount / luminance.amount,
unit = AreaUnit(this.unit, luminance.unit))
// endregion
}
| 10 | Kotlin | 0 | 2 | 4a2e79272dd83e3d47d8fac6677471add4be02ad | 2,649 | units | Apache License 2.0 |
src/Day01.kt | kuolemax | 573,740,719 | false | null | fun main() {
fun countPerCalories(input: List<String>): MutableList<Int> {
val arr = mutableListOf<Int>()
var index = 0
var newStart = 0
val lines = input.iterator()
while (lines.hasNext()) {
val next = lines.next()
if (next.isNotBlank()) {
// 连续的值,累加
if (index == newStart) {
arr.add(next.toInt())
} else {
arr[index] = arr[index] + next.toInt()
}
newStart++
} else {
// 空行,重新累加
index++
newStart = index
}
}
return arr
}
fun part1(input: List<String>): Int {
val arr = countPerCalories(input)
return arr.max()
}
fun part2(input: List<String>): Int {
val calories = countPerCalories(input)
calories.sortDescending()
return calories.subList(0, 3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3045f307e24b6ca557b84dac18197334b8a8a9bf | 1,274 | aoc2022--kotlin | Apache License 2.0 |
algorithm/crom-fortune-v1/src/test/kotlin/com.sundbybergsit.cromfortune.algorithm.cromfortunev1/StubbedStockPriceApi.kt | Sundbybergs-IT | 2,808,467 | false | {"Kotlin": 401505, "Java": 57117, "Batchfile": 150} | package com.sundbybergsit.cromfortune.algorithm.cromfortunev1
import com.sundbybergsit.cromfortune.domain.StockPrice
import com.sundbybergsit.cromfortune.domain.StockPriceApi
class StubbedStockPriceApi(private val stockPrices: MutableSet<StockPrice> = mutableSetOf()) : StockPriceApi {
override fun put(stockPrice: Set<StockPrice>) {
stockPrices.addAll(stockPrice)
}
override fun getStockPrice(stockSymbol: String): StockPrice? {
return stockPrices.find { stockPrice -> stockPrice.stockSymbol == stockSymbol }
}
}
| 17 | Kotlin | 0 | 0 | c930a1b13bd4ed07a41627e89fb2acbdcd1e64fd | 551 | Crom-Fortune | The Unlicense |
app/src/test/kotlin/codes/chrishorner/socketweather/test/TestChannel.kt | chris-horner | 229,036,471 | false | null | package codes.chrishorner.socketweather.test
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED
import kotlinx.coroutines.withTimeout
class TestChannel<T> {
private val channel = Channel<T>(capacity = UNLIMITED)
suspend fun awaitValue() = try {
withTimeout(1_000L) { channel.receive() }
} catch (e: TimeoutCancellationException) {
error("No value produced in 1,000ms.")
}
fun send(value: T) = channel.trySend(value)
fun assertEmpty() {
if (!channel.isEmpty) {
throw AssertionError("Asserted empty channel is not empty.")
}
}
}
| 7 | Kotlin | 9 | 58 | f9a8a2deaaec9b90ac6a2b9b8228db36086d9a80 | 676 | SocketWeather | Apache License 2.0 |
02-meet-the-busso-application/projects/starter/BussoServer/src/repository/impl/ResourceBusStopRepository.kt | kodecocodes | 276,127,940 | false | {"Kotlin": 6099963, "Shell": 1914} | package com.raywenderlich.busso.server.repository.impl
import com.google.gson.Gson
import com.raywenderlich.busso.server.model.BusStop
import com.raywenderlich.busso.server.repository.BusStopRepository
import kotlin.random.Random
/**
* Min number of busStop per request
*/
const val MIN_BUS_STOP_NUMBER = 4
/**
* Max number of busStop per request
*/
const val MAX_BUS_STOP_NUMBER = 8
/**
* Number of arrivals for line
*/
fun busStopNumberRange() = 0..Random.nextInt(MIN_BUS_STOP_NUMBER, MAX_BUS_STOP_NUMBER)
/**
* The Path for the data file
*/
private const val BUS_STOP_RESOURCE_PATH = "/data/bus_stop_list.json"
/**
* BusStopRepository implementation which picks a random number of BusStop from some data
* in the configuration file
*/
class ResourceBusStopRepository : BusStopRepository {
private val model: BusStopData
init {
val jsonAsText = this::class.java.getResource(BUS_STOP_RESOURCE_PATH).readText()
model = Gson().fromJson(jsonAsText, BusStopData::class.java).apply {
items.forEach { butStop ->
[email protected][butStop.id] = butStop
}
}
}
override suspend fun findBusStopByLocation(latitude: Float, longitude: Float, radius: Int): List<BusStop> =
mutableListOf<BusStop>().apply {
// TODO make this random but dependent on the input position. Otherwise
// it changes everytime
(2..10).forEach {
add(model.items[it])
}
/**
// To remove duplicates.
val positions = mutableSetOf<Int>()
busStopNumberRange().forEach {
val randomPosition = Random.nextInt(0, model.items.size)
if (!positions.contains(randomPosition)) {
positions.add(randomPosition)
add(model.items[randomPosition])
}
}
*/
}.sortedBy { busStop -> busStop.distance }
override suspend fun findBusStopById(budStopId: String): BusStop? =
model.stopMap[budStopId]
}
/**
* Local model for the Json file in resources
*/
private data class BusStopData(
val version: String = "",
val items: List<BusStop> = emptyList(),
val stopMap: MutableMap<String, BusStop> = mutableMapOf()
) | 4 | Kotlin | 30 | 32 | acbe16193cdbe12204709a611348fda69af8455c | 2,314 | dag-materials | Apache License 2.0 |
guides/micronaut-cli-jwkgen/kotlin/src/main/kotlin/example/micronaut/JsonWebKeyGenerator.kt | micronaut-projects | 326,986,278 | false | {"Java": 2207487, "Groovy": 1129386, "Kotlin": 977645, "JavaScript": 110091, "HTML": 93452, "CSS": 30567, "Shell": 5473, "AppleScript": 1063, "Python": 47} | /*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.micronaut
import java.util.Optional
/**
* [JSON Web Key](https://datatracker.ietf.org/doc/html/rfc7517)
*/
interface JsonWebKeyGenerator {
fun generateJsonWebKey(kid: String?): Optional<String>
}
| 209 | Java | 31 | 36 | 9f04eb978f4882e883adffb6c95d6a6928d79b29 | 823 | micronaut-guides | Creative Commons Attribution 4.0 International |
TalkIn/app/src/main/java/com/example/talk_in/UserProfileScreen.kt | Ijaiswalshivam | 664,282,006 | false | {"Dart": 183322, "Kotlin": 103209, "HTML": 2833, "Java": 2614} | package com.example.talk_in
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.example.talk_in.databinding.ActivityUserProfileScreenBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
class UserProfileScreen : AppCompatActivity() {
private lateinit var binding: ActivityUserProfileScreenBinding
private var USER_MODE: String? = null
private lateinit var imageUri: Uri
private lateinit var storageReference: StorageReference
private lateinit var mAuth: FirebaseAuth
private lateinit var mDbRef: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityUserProfileScreenBinding.inflate(layoutInflater)
setContentView(binding.root)
// Initialize Firebase Auth and Database Reference
mAuth = FirebaseAuth.getInstance()
mDbRef = FirebaseDatabase.getInstance().getReference()
USER_MODE = intent.getStringExtra("MODE").toString()
var currentUserUid = mAuth.currentUser?.uid.toString()
if (USER_MODE == "RECEIVER_USER") {
currentUserUid = intent.getStringExtra("RECEIVER_UID").toString()
binding.aboutMeTextViewTitle.text = "About"
binding.logoutBtn.visibility = View.GONE
binding.editAboutIcon.visibility = View.GONE
binding.editContactIcon.visibility = View.GONE
binding.showLocationSection.visibility = View.GONE
binding.userprofileImageBtn.visibility = View.GONE
}
setProfileImage(currentUserUid)
currentUserUid.let { uid ->
mDbRef.child("user").child(uid).get().addOnSuccessListener { snapshot ->
val currentUser = snapshot.getValue(User::class.java)
currentUser?.let {
binding.nameOfUser.text = it.name
binding.emailid.text = it.email
binding.showLocationToggleBtn.isChecked = it.showLocation!!
binding.aboutMeTextView.text = it.aboutMe
if (it.mobile.isNullOrEmpty()) {
binding.phoneNumber.text = "Add a new Phone Number"
} else {
binding.phoneNumber.text = it.mobile
}
}
}.addOnFailureListener { exception ->
// Handle any potential errors here
}
}
binding.showLocationToggleBtn.setOnCheckedChangeListener { _, isChecked ->
currentUserUid.let { uid ->
mDbRef.child("user").child(uid).child("showLocation").setValue(isChecked)
}
}
binding.userprofileImageBtn.setOnClickListener {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(intent, 100)
}
binding.logoutBtn.setOnClickListener {
val currentUser = mAuth.currentUser
currentUser?.uid?.let { userId ->
mDbRef.child("users-device-tokens").child(userId).removeValue()
.addOnSuccessListener {
mAuth.signOut()
val intent = Intent(this@UserProfileScreen, LogIn::class.java)
finish()
startActivity(intent)
}
.addOnFailureListener { e ->
// Handle error
}
}
}
binding.backBtn.setOnClickListener {
val intent = Intent(this@UserProfileScreen, MainActivity::class.java)
finish()
startActivity(intent)
}
binding.editAboutIcon.setOnClickListener {
showCustomDialog(this) { newText ->
// Handle the result (newText) here
mAuth.currentUser?.let { it1 ->
mDbRef.child("user").child(it1.uid).child("aboutMe").setValue(newText)
.addOnSuccessListener {
binding.aboutMeTextView.text = newText
}
.addOnFailureListener{
Toast.makeText(this@UserProfileScreen, "Failed to update value!!", Toast.LENGTH_SHORT).show()
}
}
}
}
binding.editContactIcon.setOnClickListener {
showPhoneNumberDialog(this) { newPhoneNumber ->
mAuth.currentUser?.let { currentUser ->
val userUid = currentUser.uid
mDbRef.child("user").child(userUid).child("mobile").setValue(newPhoneNumber)
.addOnSuccessListener {
binding.phoneNumber.text = newPhoneNumber
Toast.makeText(this@UserProfileScreen, "Phone number updated successfully!", Toast.LENGTH_SHORT).show()
}
.addOnFailureListener {
Toast.makeText(this@UserProfileScreen, "Failed to update phone number!", Toast.LENGTH_SHORT).show()
}
}
}
}
}
private fun showCustomDialog(context: Context, listener: (String) -> Unit) {
val dialogView = LayoutInflater.from(context).inflate(R.layout.custom_dialog_layout, null)
val editText = dialogView.findViewById<EditText>(R.id.edit_text)
AlertDialog.Builder(context)
.setView(dialogView)
.setTitle("Edit Status")
.setPositiveButton("Save") { _, _ ->
val newText = editText.text.toString().trim()
if (newText.isNotEmpty()) {
listener.invoke(newText)
} else {
Toast.makeText(this, "Status cannot be empty.", Toast.LENGTH_SHORT).show()
}
}
.setNegativeButton("Cancel") { dialog, _ ->
dialog.cancel()
}
.create()
.show()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 100 && resultCode == RESULT_OK && data != null && data.data != null) {
imageUri = data.data!!
uploadImageToFirebaseStorage(imageUri)
}
}
private fun uploadImageToFirebaseStorage(imageUri: Uri) {
val currentUserUid = mAuth.currentUser?.uid ?: return
storageReference = FirebaseStorage.getInstance().reference.child("user_profile_images")
.child("$currentUserUid.jpg")
storageReference.putFile(imageUri)
.addOnSuccessListener { taskSnapshot ->
storageReference.downloadUrl.addOnSuccessListener { uri ->
mDbRef.child("user").child(currentUserUid).child("profileImageUrl")
.setValue(uri.toString())
setProfileImage(currentUserUid)
}
}
.addOnFailureListener { exception ->
// Handle any errors that may occur during the upload process
}
}
private fun setProfileImage(currentUserUid: String) {
storageReference = FirebaseStorage.getInstance().reference.child("user_profile_images")
.child("$currentUserUid.jpg")
storageReference.downloadUrl.addOnSuccessListener { uri ->
Glide.with(this)
.load(uri)
.circleCrop()
.placeholder(R.drawable.default_profile_image)
.error(R.drawable.error_profile_image)
.into(binding.userprofileImage)
}
}
private fun updateAboutMe(aboutMe: String, currentUserUid: String) {
mDbRef.child("user").child(currentUserUid).child("aboutMe").setValue(aboutMe)
}
override fun onBackPressed() {
super.onBackPressed()
val intent = Intent(this@UserProfileScreen, MainActivity::class.java)
finish()
startActivity(intent)
}
private fun showPhoneNumberDialog(context: Context, listener: (String) -> Unit) {
val dialogView = LayoutInflater.from(context).inflate(R.layout.custom_dialog_phone_layout, null)
val editText = dialogView.findViewById<EditText>(R.id.edit_phone_text)
val dialog = AlertDialog.Builder(context)
.setView(dialogView)
.setTitle("Edit Phone Number")
.setPositiveButton("Save") { _, _ ->
val newPhoneNumber = editText.text.toString()
listener.invoke(newPhoneNumber)
}
.setNegativeButton("Cancel") { dialog, _ ->
dialog.cancel()
}
.create()
dialog.show()
}
}
| 18 | Dart | 45 | 29 | 8ce35fd85ba45bc2b56f823467dfe58c3e577484 | 9,398 | Talk-In | MIT License |
core-navigation/src/main/java/com/rocket/android/core/navigation/NavigatorLifecycle.kt | Rocket-Beer | 388,802,591 | false | null | package com.rocket.android.core.navigation
import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
class NavigatorLifecycle {
var activity: FragmentActivity? = null
var activityLifecycleCallbacks = object : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
setCurrentActivity(activity)
}
override fun onActivityStarted(activity: Activity) {
setCurrentActivity(activity)
}
override fun onActivityResumed(activity: Activity) {
setCurrentActivity(activity)
}
override fun onActivityPaused(activity: Activity) {
}
override fun onActivityStopped(activity: Activity) {
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}
override fun onActivityDestroyed(activity: Activity) {
}
}
private fun setCurrentActivity(currentActivity: Activity) {
if (currentActivity is FragmentActivity && currentActivity !is NavigatorIgnoreActivity) {
this.activity = currentActivity
}
}
} | 4 | Kotlin | 0 | 1 | bea739d0f28ec6d252e1ab6c3cad87e013b48dc9 | 1,247 | rocket-core-presentation | Apache License 2.0 |
pdfviewer/src/jsMain/kotlin/dev/eduardoteles/opendanfeview/pdfviewer/libs/pdfjs/RenderTask.kt | eduardoteles17 | 864,113,390 | false | {"Kotlin": 16900, "HTML": 316, "JavaScript": 182} | package dev.eduardoteles.opendanfeview.pdfviewer.libs.pdfjs
import kotlin.js.Promise
external object RenderTask {
fun onContinue()
val promise: Promise<Unit>
fun cancel(extraDelay: Int = definedExternally)
}
| 0 | Kotlin | 0 | 3 | 309b0b6c99699b81adcd9048b9831e20f47c0246 | 222 | OpenDanfeView | MIT License |
src/main/kotlin/frc/kyberlib/lighting/animations/AnimationRGBRain.kt | Kanishk-Pandey | 625,399,371 | false | null | package frc.kyberlib.lighting.animations
import frc.kyberlib.math.units.extensions.Time
import java.awt.Color
import kotlin.math.ceil
import kotlin.math.pow
class AnimationRGBRain(
private val cycles: Double = 1.0,
private val dropLength: Int,
val secondsPerMovement: Time,
val reversed: Boolean = false,
enableTransparency: Boolean = false,
condition: () -> Boolean = { true }
) : LEDAnimation(condition, enableTransparency) {
private fun constructInitialBuffer(length: Int): MutableList<Color> {
return Array<Color>(dropLength * ceil(length.toDouble() / dropLength).toInt()) {
val alpha = ((1 + (it % dropLength)) / dropLength.toFloat()).pow(2)
Color(1F, 1F, 1F, alpha)
}.toMutableList()
}
private fun constructRGBBuffer(length: Int): MutableList<Color> {
return if (cycles >= 1) {
Array<Color>(length) {
val hue = (it % (length / cycles)) / (length / cycles)
Color.getHSBColor(1 - hue.toFloat(), 1F, 1F)
}.asList().toMutableList()
} else {
Array<Color>((length / cycles).toInt()) {
val hue = it / (length / cycles)
Color.getHSBColor(1 - hue.toFloat(), 1F, 1F)
}.asList().toMutableList()
}
}
override fun getBuffer(time: Time, length: Int): List<Color> {
val b = constructInitialBuffer(length)
val rgb = constructRGBBuffer(length)
// println(rgb.size)
for (i in 0 until (time / secondsPerMovement).toInt() % (dropLength * rgb.size)) {
b.add(0, b.removeAt(b.size - 1))
rgb.add(0, rgb.removeAt(rgb.size - 1))
}
val trimmed = b.take(length).toMutableList()
for (i in trimmed.indices) {
trimmed[i] = Color(
(trimmed[i].red * rgb[i].red / 255.0).toInt(),
(trimmed[i].green * rgb[i].green / 255.0).toInt(),
(trimmed[i].blue * rgb[i].blue / 255.0).toInt(),
trimmed[i].alpha
)
}
if (reversed) {
trimmed.reverse()
}
return trimmed
}
}
| 0 | Kotlin | 0 | 0 | e5d6c96397e1b4ab703e638db2361418fd9d4939 | 2,174 | MyRoboticsCode | Apache License 2.0 |
app/src/main/java/org/stepic/droid/storage/migration/MigrationFrom67To68.kt | StepicOrg | 42,045,161 | false | {"Kotlin": 4281147, "Java": 1001895, "CSS": 5482, "Shell": 618} | package org.stepic.droid.storage.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import org.stepic.droid.storage.structure.DbStructureCourse
import org.stepik.android.cache.section.structure.DbStructureSection
object MigrationFrom67To68 : Migration(67, 68) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE ${DbStructureCourse.TABLE_NAME} ADD COLUMN ${DbStructureCourse.Columns.IS_PROCTORED} INTEGER")
db.execSQL("ALTER TABLE ${DbStructureSection.TABLE_NAME} ADD COLUMN ${DbStructureSection.Columns.EXAM_DURATION_MINUTES} INTEGER")
db.execSQL("ALTER TABLE ${DbStructureSection.TABLE_NAME} ADD COLUMN ${DbStructureSection.Columns.EXAM_SESSION} LONG")
db.execSQL("ALTER TABLE ${DbStructureSection.TABLE_NAME} ADD COLUMN ${DbStructureSection.Columns.PROCTOR_SESSION} LONG")
db.execSQL("ALTER TABLE ${DbStructureSection.TABLE_NAME} ADD COLUMN ${DbStructureSection.Columns.IS_PROCTORING_CAN_BE_SCHEDULED} INTEGER")
db.execSQL("CREATE TABLE IF NOT EXISTS `ExamSession` (`id` INTEGER NOT NULL, `user` INTEGER NOT NULL, `section` INTEGER NOT NULL, `beginDate` INTEGER, `endDate` INTEGER, `timeLeft` REAL NOT NULL, `randomExam` INTEGER NOT NULL, PRIMARY KEY(`id`))")
db.execSQL("CREATE TABLE IF NOT EXISTS `ProctorSession` (`id` INTEGER NOT NULL, `user` INTEGER NOT NULL, `section` INTEGER NOT NULL, `createDate` INTEGER, `startUrl` TEXT NOT NULL, `stopUrl` TEXT NOT NULL, `startDate` INTEGER, `stopDate` INTEGER, `submitDate` INTEGER, `comment` TEXT NOT NULL, `score` REAL NOT NULL, PRIMARY KEY(`id`))")
}
} | 13 | Kotlin | 54 | 189 | dd12cb96811a6fc2a7addcd969381570e335aca7 | 1,642 | stepik-android | Apache License 2.0 |
src/test/kotlin/com/example/e2e/browser/CompareScreenshotsIT.kt | globalworming | 364,037,743 | false | null | package com.example.e2e.browser
import com.example.screenplay.question.image.NoDifferenceToSnapshot
import net.serenitybdd.junit.runners.SerenityRunner
import net.serenitybdd.screenplay.Actor
import net.serenitybdd.screenplay.GivenWhenThen.*
import net.serenitybdd.screenplay.abilities.BrowseTheWeb
import net.serenitybdd.screenplay.actions.Open
import net.thucydides.core.annotations.Managed
import org.hamcrest.CoreMatchers.*
import org.junit.Test
import org.junit.runner.RunWith
import org.openqa.selenium.WebDriver
@RunWith(SerenityRunner::class)
class CompareScreenshotsIT {
@Managed(driver = "chrome")
private lateinit var aBrowser: WebDriver
/**
* naive example of a failing screenshot comparison
* would need to be extended to only screenshot specific elements, see implementation CreateSnapshot
*/
@Test
fun `when comparing full size page`() {
val tester = Actor("tester")
tester.can(BrowseTheWeb.with(aBrowser))
tester.attemptsTo(Open.url("https://www.gns.cri.nz/Home/Our-Science/Energy-Futures/Oil-and-Gas/Petroleum-Basin-Explorer"))
tester.should(seeThat(NoDifferenceToSnapshot("homepage.png"), `is`(true)))
}
} | 1 | Kotlin | 0 | 3 | 6210037934792fa6a7f46c265ec12557c9d80edf | 1,164 | serenity-kotlin-junit-screenplay-starter | Apache License 2.0 |
app/src/main/java/me/ycdev/android/demo/customviews/ui/events/CallRecord.kt | ycdev-demo | 47,069,805 | false | null | package me.ycdev.android.demo.customviews.ui.events
import android.view.MotionEvent
data class CallRecord(val tag: String, val event: CallEvent, val actionStr: String) {
companion object {
fun create(tag: String, event: CallEvent): CallRecord {
return CallRecord(tag, event, "")
}
fun create(tag: String, event: CallEvent, action: Int): CallRecord {
return CallRecord(tag, event, MotionEvent.actionToString(action))
}
}
} | 0 | Kotlin | 0 | 0 | 5afe34b35006621f7aec242d4c720ebd01f078f9 | 488 | CustomViews | Apache License 2.0 |
client/src/commonMain/kotlin/com/algolia/client/model/search/RedirectRuleIndexMetadata.kt | algolia | 153,273,215 | false | null | /** Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. */
package com.algolia.client.model.search
import kotlinx.serialization.*
import kotlinx.serialization.json.*
/**
* RedirectRuleIndexMetadata
*
* @param source Source index for the redirect rule.
* @param dest Destination index for the redirect rule.
* @param reason Reason for the redirect rule.
* @param succeed Redirect rule status.
* @param `data`
*/
@Serializable
public data class RedirectRuleIndexMetadata(
/** Source index for the redirect rule. */
@SerialName(value = "source") val source: String,
/** Destination index for the redirect rule. */
@SerialName(value = "dest") val dest: String,
/** Reason for the redirect rule. */
@SerialName(value = "reason") val reason: String,
/** Redirect rule status. */
@SerialName(value = "succeed") val succeed: Boolean,
@SerialName(value = "data") val `data`: RedirectRuleIndexData,
)
| 40 | null | 8 | 59 | ad21e6ddfbee8df4c40524ff401b5e1058f7b8b7 | 1,049 | algoliasearch-client-kotlin | MIT License |
domain/src/main/kotlin/net/corda/tools/error/codes/server/domain/ErrorCoordinates.kt | AlexRogalskiy | 449,477,678 | true | {"Kotlin": 114301, "Dockerfile": 491} | package net.corda.tools.error.codes.server.domain
data class ErrorCoordinates(val code: ErrorCode, val releaseVersion: ReleaseVersion, val platformEdition: PlatformEdition) | 1 | null | 0 | 0 | 7bc7fcc3d7e3a51a531b2988b7d3ca691272e12b | 173 | error-codes-web-app | Apache License 2.0 |
livechat/src/main/java/com/desk360/livechat/presentation/activity/livechat/LoginNewChatActivity.kt | Teknasyon-Teknoloji | 394,270,981 | false | null | package com.desk360.livechat.presentation.activity.livechat
import android.content.Intent
import android.content.res.Resources
import android.graphics.Color.parseColor
import android.text.Editable
import android.view.ContextThemeWrapper
import android.widget.LinearLayout
import androidx.appcompat.widget.AppCompatEditText
import com.desk360.base.presentation.addTextWatcher
import com.desk360.base.presentation.setError
import com.desk360.base.util.Utils
import com.desk360.livechat.R
import com.desk360.livechat.data.model.chatsettings.CustomField
import com.desk360.livechat.databinding.ActivityLoginNewChatBinding
import com.desk360.livechat.manager.LiveChatHelper
import com.desk360.livechat.presentation.activity.BaseActivity
import com.desk360.livechat.presentation.activity.BaseChatActivity
class LoginNewChatActivity : BaseActivity<ActivityLoginNewChatBinding, LoginNewChatViewModel>() {
override fun getLayoutResId() = R.layout.activity_login_new_chat
override fun getViewModelClass() = LoginNewChatViewModel::class.java
private lateinit var customField: LinearLayout
private val currentEditTextList = mutableListOf<AppCompatEditText>()
private var activeCustomField = mutableListOf<CustomField>()
override fun onResume() {
super.onResume()
viewModel.checkStatus()
}
private val Int.px get() = (this * Resources.getSystem().displayMetrics.density).toInt()
private fun String.toEditable(): Editable = Editable.Factory.getInstance().newEditable(this)
override fun initUI() {
binding.viewModel = viewModel
binding.textViewLoginBg.onClick {
createNewChat()
}
binding.toolbar.imageViewBack.onClick {
LiveChatHelper.closeKeyboard(this, binding.toolbar.imageViewBack)
onBackPressed()
}
customField = findViewById(R.id.custom_field_layout)
setCustomField()
binding.editTextNickname.addTextWatcher(binding.textViewNicknameError)
binding.editTextMailAddress.addTextWatcher(binding.textViewEmailError)
binding.editTextMessage.addTextWatcher(binding.textViewMessageError)
}
private fun setCustomField() {
viewModel.customFieldList?.let { list ->
list.forEach { i ->
i.isActive?.takeIf { it }.let {
activeCustomField.add(i)
addCustomField(i)
}
}
}
}
private fun addCustomField(field: CustomField) {
val layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, 46.px
)
layoutParams.setMargins(0, 0, 0, 30)
val editText =
AppCompatEditText(
ContextThemeWrapper(this, R.style.CustomEditText), null, 0
).apply {
hint = field.title?.toEditable()
tag = field.key
}
currentEditTextList.add(editText)
customField.addView(editText, layoutParams)
}
override fun initObservers() {
viewModel.isSentOfflineMessage.observe(this, { isSuccessful ->
if (isSuccessful) {
finish()
startActivity(Intent(this, SentMessageInfoActivity::class.java))
}
})
viewModel.conversationId.observe(this, { conversationId ->
if (conversationId.isNotEmpty()) {
finish()
startActivity(Intent(this, LiveChatActivity::class.java).apply {
putExtra(BaseChatActivity.EXTRA_CONVERSATION_ID, conversationId)
})
}
})
viewModel.screenModel.observe(this, { data ->
currentEditTextList.forEach { i ->
data?.writeMessageTextColor?.let { i.setTextColor(parseColor(it)) }
data?.placeholderColor?.let { i.setHintTextColor(parseColor(it)) }
}
})
}
private fun createNewChat() {
viewModel.setSessionRequest(
binding.editTextNickname.text.toString().trim(),
binding.editTextMailAddress.text.toString().trim(),
binding.editTextMessage.text.toString().trim()
)
currentEditTextList.forEachIndexed { i, editText ->
activeCustomField[i].value = editText.text.toString()
}
if (!viewModel.isNicknameValid()) {
setError(
binding.editTextNickname,
binding.textViewNicknameError,
LiveChatHelper.settings?.data?.language?.requiredMessage
)
binding.editTextNickname.requestFocus()
return
}
if (!viewModel.isEmailAddressValid()) {
setError(
binding.editTextMailAddress,
binding.textViewEmailError,
LiveChatHelper.settings?.data?.language?.requiredMessage
)
binding.editTextMailAddress.requestFocus()
return
}
if (!Utils.isEmailValid(binding.editTextMailAddress.text.toString().trim())) {
setError(
binding.editTextMailAddress,
binding.textViewEmailError,
LiveChatHelper.settings?.data?.language?.requiredMessage
)
binding.editTextMailAddress.requestFocus()
return
}
if (!viewModel.isMessageValid()) {
setError(
binding.editTextMessage,
binding.textViewMessageError,
LiveChatHelper.settings?.data?.language?.requiredMessage
)
binding.editTextMessage.requestFocus()
return
}
viewModel.createNewChat(activeCustomField)
}
} | 0 | null | 2 | 31 | 7d28b500c13af208afbf27168445a4908a835ca3 | 5,751 | desk360-livechat-android-sdk | MIT License |
base/src/main/java/com/mindera/skeletoid/analytics/interfaces/IAnalyticsManager.kt | mccostic | 357,604,914 | true | {"Kotlin": 395894, "Java": 10994} | package com.mindera.skeletoid.analytics.interfaces
import android.app.Activity
import android.content.Context
import android.os.Bundle
import com.mindera.skeletoid.analytics.appenders.interfaces.IAnalyticsAppender
/**
* Analytics interface
*/
interface IAnalyticsManager {
/**
* Enable analytics appenders
*
* @param context Context
* @param analyticsAppenders Log appenders to enable
* @return Ids of the logs enabled by their order
*/
fun addAppenders(
context: Context,
analyticsAppenders: List<IAnalyticsAppender>
): Set<String>
/**
* Disable analytics appenders
*
* @param context Context
* @param analyticsIds Log ids of each of the analytics enabled by the order sent
*/
fun removeAppenders(
context: Context,
analyticsIds: Set<String>
)
/**
* Disable all analytics appenders
*/
fun removeAllAppenders()
/**
* Track app event
*
* @param eventName Event name
* @param analyticsPayload Generic analytics payload
*/
fun trackEvent(
eventName: String,
analyticsPayload: Map<String, Any>
)
/**
* Track app event
*
* @param eventName Event name
* @param analyticsPayload Generic analytics payload
*/
fun trackEvent(eventName: String, analyticsPayload: Bundle)
/**
* Track app page hit
*
* @param activity Activity that represent
* @param screenName Screen name
* @param screenClassOverride Screen class override name
*/
fun trackPageHit(
activity: Activity,
screenName: String,
screenClassOverride: String? = null
)
/**
* Sets the user ID
*
* @param userID ID of the user
*/
fun setUserID(userID: String)
/**
* Sets a custom property of the user
*
* @param name Property name
* @param value Property value
*/
fun setUserProperty(name: String, value: String?)
} | 0 | null | 0 | 0 | e67d4bfd98e7364daae014710a4ef04e9ce63341 | 2,065 | skeletoid | MIT License |
code/app/src/main/java/com/istudio/distancetracker/utils/Constants.kt | devrath | 571,263,897 | false | {"Kotlin": 48672} | package com.istudio.distancetracker.utils
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
object Constants {
val disneyLandLocation = LatLng(33.81213278476581, -117.91896178782112)
val draggableMarkerLocation = LatLng(33.81196172266233, -117.9192556460658)
val customMarkerLocation = LatLng(33.812302725281405, -117.91956550307864)
val layoutMarkerLocation = LatLng(33.81148154041286, -117.92105482994259)
const val disneyLandMarkerStr = "Disney land marker"
private val disneyLandLocationBound1 = LatLng(33.8061483029195, -117.93071633478273) //SW
private val disneyLandLocationBound2 = LatLng(33.81231042413435, -117.91898157364918) //NE
val disneyBoundsLocation = LatLngBounds(disneyLandLocationBound1, disneyLandLocationBound2)
val polyPointsOfDisney = arrayListOf(
disneyLandLocation,
LatLng(33.812182619161156, -117.91890451874627),
LatLng(33.81210461964178, -117.91882807578864),
LatLng(33.81200544872161, -117.91889311935783),
LatLng(33.812040548554805, -117.91924247708515)
)
val polygonPointsOfDisney = arrayListOf(
disneyLandLocation,
LatLng(33.812182619161156, -117.91890451874627),
LatLng(33.81210461964178, -117.91882807578864),
LatLng(33.81200544872161, -117.91889311935783),
)
} | 0 | Kotlin | 0 | 0 | 6cae29c6241ca5a5a0d50801cd1a0054921853db | 1,379 | droid-map-demo | Apache License 2.0 |
Introduction/Lambdas/src/TaskExtensionLambdaExercices.kt | Rosietesting | 373,564,502 | false | {"HTML": 178715, "JavaScript": 147056, "Kotlin": 113135, "CSS": 105840} |
fun main(args: Array<String>) {
fun containsEven(collection: Collection<Int>): Boolean =
collection.any { TODO() }
// Function that takes two strings and don't return anything
fun joinString(a: String , b: String ) {
a+b
}
// Function that takes a collection of integers and returns and boolean
fun CheckSizeGreatedThan1(collection: Collection<Int>): Boolean {
return collection.size == 3
}
fun findValueGreaterThan(collection: Collection<Int>): Boolean =
collection.find {it > 0} == 2
fun findEvenNumber(collection: Collection<Int>): Boolean =
collection.any {it % 2 == 0}
val col = listOf<Int>(1,1,12)
//containsEven1(col)
val r = CheckSizeGreatedThan1(col)
val d = findValueGreaterThan(col)
val isEvenNumber = findEvenNumber(col)
//containsEven(col)
fun assertValueInList(mutableListOf : List<(String)>){
//Assert("x" in mutableListOf) {"X Value not found"}
}
val list1 = listOf<String>("a","b")
assertValueInList(list1)
/*
LAMBDA EXPRESSIONS.
SYNTAX:
val lambdaName : Type = { argumentList -> codeBody }
Without the type will be
val lambdaName = {argumentList -> codeBody }
*/
// Calling funcions
val intv = squareValueFunction(5)
println("calling regular function " + intv)
// Lambda expression fashion examples
//This lambda multiplies its single argument numbers by 100 then returns that value as a String.
// It receives Input as an argument and multiplies times 100.
// The latest value is the return. In this case a stirng
val multiplyValue = { input: Int ->
val magnitude = input * 100
magnitude.toString()
}
//This lambda expression that takes and int number and returns Int: (Int) -> Int
val squareVal = { number : Int ->
// It returns the last sentence of th labda expression
val abc = number * 100
abc
}
// The final expression is the value that will be returned after a lambda is executed
val calculateGrade = { grade : Int ->
when(grade) {
in 0..40 -> "Fail"
in 41..70 -> "Pass"
in 71..100 -> "Distinction"
else -> false
}
}
calculateGrade(99)
// Example defining the arguments and return type explicitly
// and may use the return statement the same as any method:
//fun(grade: Int): String / This explicitly says that we receive and int and return a String
val calculateValue = fun(grade: Int): String {
if (grade < 0 || grade > 100) {
return "Error"
} else if (grade < 40) {
return "Fail"
} else if (grade < 70) {
return "Pass"
}
return "Distinction"
}
// Lambda expression to use it
// 1. Define the array
val array = arrayOf(1, 2, 3, 4, 5, 6)
// Longhand version read each array
array.forEach { item -> println(item * 4) }
// shorthand
array.forEach { println(it * 4) }
println("Value 14Jane is" + squareVal(5))
//Using it in lambda expression
// no return value
//val nonReturn : Int -> Unit = {num -> println(num)}
val theList = listOf("one", "two", "three")
assert("two" in theList)
val stringMult = multiplyValue(33)
println("Lenght is ${stringMult.length} and the value is ${stringMult}" )
println("Calculation using lambda function " + multiplyValue(55))
val square : (Int) -> Int = { value ->
value * value
}
println(square(5))
// Lambda function
val maxValue = { a: String, b: String -> a.length < b.length }
println("maxValue is" + maxValue)
// Regular function
println(compareFucntion("rosi", "pe"))
}
// Regular function that multiply two values and returns an integer
fun squareValueFunction(value: Int) : Int = value * value
// Regular function fashion example 2
fun compareFucntion(a: String, b: String): Boolean = a.length < b.length | 0 | HTML | 0 | 0 | b0aa518d220bb43c9398dacc8a6d9b6c602912d5 | 4,077 | KotlinKoans | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.