path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/elbehiry/steller/app/di/AppModule.kt
Elbehiry
301,862,208
false
null
package com.elbehiry.steller.app.di import com.elbehiry.steller.app.ui.main.MainViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val appModule = module { viewModel { MainViewModel(get()) } }
1
Kotlin
1
3
d6d774341264c0b120213b626c02070723071d0a
233
Steller
Apache License 2.0
src/main/kotlin/no/nav/familie/ba/sak/kjerne/vedtak/vedtaksperiode/vedtakBegrunnelseProdusent/hentBegrunnelser/HentStandardBegrunnelser.kt
navikt
224,639,942
false
{"Kotlin": 6468958, "Gherkin": 948328, "PLpgSQL": 4478, "Shell": 3178, "Dockerfile": 522}
package no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.hentBegrunnelser import no.nav.familie.ba.sak.kjerne.autovedtak.fødselshendelse.Resultat import no.nav.familie.ba.sak.kjerne.behandling.domene.Behandling import no.nav.familie.ba.sak.kjerne.beregning.domene.YtelseType import no.nav.familie.ba.sak.kjerne.brev.domene.EndretUtbetalingsperiodeDeltBostedTriggere import no.nav.familie.ba.sak.kjerne.brev.domene.ISanityBegrunnelse import no.nav.familie.ba.sak.kjerne.brev.domene.SanityBegrunnelse import no.nav.familie.ba.sak.kjerne.brev.domene.SanityPeriodeResultat import no.nav.familie.ba.sak.kjerne.brev.domene.Tema import no.nav.familie.ba.sak.kjerne.brev.domene.UtvidetBarnetrygdTrigger import no.nav.familie.ba.sak.kjerne.endretutbetaling.domene.Årsak import no.nav.familie.ba.sak.kjerne.grunnlag.personopplysninger.Person import no.nav.familie.ba.sak.kjerne.vedtak.begrunnelser.IVedtakBegrunnelse import no.nav.familie.ba.sak.kjerne.vedtak.begrunnelser.Standardbegrunnelse import no.nav.familie.ba.sak.kjerne.vedtak.domene.VedtaksperiodeMedBegrunnelser import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.BegrunnelseGrunnlagForPeriodeMedOpphør import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.BegrunnelseGrunnlagForPeriodeMedReduksjonPåTversAvBehandlinger import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.IBegrunnelseGrunnlagForPeriode import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.TemaerForBegrunnelser import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.begrunnelseGjelderOpphørFraForrigeBehandling import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.begrunnelseGjelderReduksjonFraForrigeBehandling import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.erGjeldendeForBrevPeriodeType import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.erGjeldendeForFagsakType import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.erGjeldendeForRolle import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.erGjeldendeForUtgjørendeVilkår import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.erLikVilkårOgUtdypendeVilkårIPeriode import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.erSammeTemaSomPeriode import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.hentEndretUtbetalingDennePerioden import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.hentResultaterForForrigePeriode import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.matcherErAutomatisk import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.skalFiltreresPåHendelser import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtakBegrunnelseProdusent.skalVisesSelvOmIkkeEndring import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtaksperiodeProdusent.IEndretUtbetalingAndelForVedtaksperiode import no.nav.familie.ba.sak.kjerne.vedtak.vedtaksperiode.vedtaksperiodeProdusent.VilkårResultatForVedtaksperiode import no.nav.familie.ba.sak.kjerne.vilkårsvurdering.domene.Regelverk import java.math.BigDecimal internal fun hentStandardBegrunnelser( begrunnelseGrunnlag: IBegrunnelseGrunnlagForPeriode, sanityBegrunnelser: Map<Standardbegrunnelse, SanityBegrunnelse>, person: Person, vedtaksperiode: VedtaksperiodeMedBegrunnelser, behandling: Behandling, relevantePeriodeResultater: List<SanityPeriodeResultat>, erUtbetalingEllerDeltBostedIPeriode: Boolean, utvidetVilkårPåSøkerIPeriode: VilkårResultatForVedtaksperiode?, utvidetVilkårPåSøkerIForrigePeriode: VilkårResultatForVedtaksperiode?, temaSomPeriodeErVurdertEtter: TemaerForBegrunnelser, ): Set<IVedtakBegrunnelse> { val endretUtbetalingDennePerioden = hentEndretUtbetalingDennePerioden(begrunnelseGrunnlag) val filtrertPåTema = sanityBegrunnelser.filterValues { it.erSammeTemaSomPeriode(temaSomPeriodeErVurdertEtter) } val filtrertPåRolleOgFagsaktype = filtrertPåTema .filterValues { begrunnelse -> begrunnelse.erGjeldendeForRolle(person, behandling.fagsak.type) } .filterValues { it.erGjeldendeForFagsakType(behandling.fagsak.type) } val relevanteBegrunnelser = filtrertPåRolleOgFagsaktype .filterValues { it.periodeResultat in relevantePeriodeResultater } .filterValues { it.matcherErAutomatisk(behandling.skalBehandlesAutomatisk) } .filterValues { it.erGjeldendeForBrevPeriodeType(vedtaksperiode, erUtbetalingEllerDeltBostedIPeriode) } .filterValues { !it.begrunnelseGjelderReduksjonFraForrigeBehandling() && !it.begrunnelseGjelderOpphørFraForrigeBehandling() } val filtrertPåVilkårOgEndretUtbetaling = relevanteBegrunnelser.filterValues { val begrunnelseErGjeldendeForUtgjørendeVilkår = it.vilkår.isNotEmpty() val begrunnelseErGjeldendeForEndretUtbetaling = it.endringsaarsaker.isNotEmpty() when { begrunnelseErGjeldendeForUtgjørendeVilkår && begrunnelseErGjeldendeForEndretUtbetaling -> filtrerPåVilkår( it, begrunnelseGrunnlag, utvidetVilkårPåSøkerIPeriode, utvidetVilkårPåSøkerIForrigePeriode, ) && filtrerPåEndretUtbetaling(it, endretUtbetalingDennePerioden) begrunnelseErGjeldendeForUtgjørendeVilkår -> filtrerPåVilkår( it, begrunnelseGrunnlag, utvidetVilkårPåSøkerIPeriode, utvidetVilkårPåSøkerIForrigePeriode, ) else -> it.erEndretUtbetaling(endretUtbetalingDennePerioden) } } val filtrertPåReduksjonFraForrigeBehandling = filtrertPåRolleOgFagsaktype.filterValues { it.erGjeldendeForReduksjonFraForrigeBehandling(begrunnelseGrunnlag) } val filtrertPåOpphørFraForrigeBehandling = filtrertPåRolleOgFagsaktype.filterValues { it.erGjeldendeForOpphørFraForrigeBehandling(begrunnelseGrunnlag) } val filtrertPåSmåbarnstillegg = relevanteBegrunnelser.filterValues { begrunnelse -> begrunnelse.erGjeldendeForSmåbarnstillegg(begrunnelseGrunnlag) } val filtrertPåEtterEndretUtbetaling = filtrertPåTema .filterValues { it.periodeResultat in hentResultaterForForrigePeriode(begrunnelseGrunnlag.forrigePeriode) } .filterValues { begrunnelse -> begrunnelse.erGjeldendeForRolle(person, behandling.fagsak.type) } .filterValues { it.erEtterEndretUtbetaling( endretUtbetalingDennePerioden = endretUtbetalingDennePerioden, endretUtbetalingForrigePeriode = hentEndretUtbetalingForrigePeriode(begrunnelseGrunnlag), ) } val filtrertPåHendelser = relevanteBegrunnelser.filterValues { it.skalFiltreresPåHendelser( begrunnelseGrunnlag, vedtaksperiode.fom, ) } val filtrertPåSkalVisesSelvOmIkkeEndring = relevanteBegrunnelser.filterValues { it.skalVisesSelvOmIkkeEndring(begrunnelseGrunnlag.dennePerioden) } return filtrertPåVilkårOgEndretUtbetaling.keys + filtrertPåReduksjonFraForrigeBehandling.keys + filtrertPåOpphørFraForrigeBehandling.keys + filtrertPåSmåbarnstillegg.keys + filtrertPåEtterEndretUtbetaling.keys + filtrertPåHendelser.keys + filtrertPåSkalVisesSelvOmIkkeEndring.keys } private fun filtrerPåVilkår( it: SanityBegrunnelse, begrunnelseGrunnlag: IBegrunnelseGrunnlagForPeriode, utvidetVilkårPåSøkerIPeriode: VilkårResultatForVedtaksperiode?, utvidetVilkårPåSøkerIForrigePeriode: VilkårResultatForVedtaksperiode?, ) = !it.begrunnelseGjelderReduksjonFraForrigeBehandling() && it.erGjeldendeForUtgjørendeVilkår( begrunnelseGrunnlag, utvidetVilkårPåSøkerIPeriode, utvidetVilkårPåSøkerIForrigePeriode, ) && it.erGjeldendeForRegelverk( begrunnelseGrunnlag, ) private fun filtrerPåEndretUtbetaling( it: SanityBegrunnelse, endretUtbetalingDennePerioden: IEndretUtbetalingAndelForVedtaksperiode?, ) = it.erEndretUtbetaling(endretUtbetalingDennePerioden) private fun SanityBegrunnelse.erEndretUtbetaling( endretUtbetaling: IEndretUtbetalingAndelForVedtaksperiode?, ): Boolean { return this.gjelderEndretUtbetaling() && this.erLikEndretUtbetalingIPeriode(endretUtbetaling) } private fun SanityBegrunnelse.erGjeldendeForRegelverk(begrunnelseGrunnlag: IBegrunnelseGrunnlagForPeriode): Boolean = begrunnelseGrunnlag.dennePerioden.vilkårResultater.none { it.vurderesEtter == Regelverk.EØS_FORORDNINGEN } || this.tema == Tema.FELLES fun ISanityBegrunnelse.erGjeldendeForReduksjonFraForrigeBehandling(begrunnelseGrunnlag: IBegrunnelseGrunnlagForPeriode): Boolean { if (begrunnelseGrunnlag !is BegrunnelseGrunnlagForPeriodeMedReduksjonPåTversAvBehandlinger) { return false } val oppfylteVilkårDenneBehandlingen = begrunnelseGrunnlag.dennePerioden.vilkårResultater.filter { it.resultat == Resultat.OPPFYLT } .map { it.vilkårType }.toSet() val oppfylteVilkårForrigeBehandling = begrunnelseGrunnlag.sammePeriodeForrigeBehandling?.vilkårResultater?.filter { it.resultat == Resultat.OPPFYLT } ?.map { it.vilkårType }?.toSet() ?: emptySet() val vilkårMistetSidenForrigeBehandling = oppfylteVilkårForrigeBehandling - oppfylteVilkårDenneBehandlingen val begrunnelseGjelderMistedeVilkår = this.vilkår.all { it in vilkårMistetSidenForrigeBehandling } val haddeSmåbarnstilleggForrigeBehandling = begrunnelseGrunnlag.erSmåbarnstilleggIForrigeBehandlingPeriode() val harSmåbarnstilleggDennePerioden = begrunnelseGrunnlag.dennePerioden.andeler.any { it.type == YtelseType.SMÅBARNSTILLEGG } val begrunnelseGjelderTaptSmåbarnstillegg = UtvidetBarnetrygdTrigger.SMÅBARNSTILLEGG in utvidetBarnetrygdTriggere && haddeSmåbarnstilleggForrigeBehandling && !harSmåbarnstilleggDennePerioden return begrunnelseGjelderReduksjonFraForrigeBehandling() && (begrunnelseGjelderMistedeVilkår || begrunnelseGjelderTaptSmåbarnstillegg) } private fun SanityBegrunnelse.erGjeldendeForSmåbarnstillegg( begrunnelseGrunnlag: IBegrunnelseGrunnlagForPeriode, ): Boolean { val erSmåbarnstilleggForrigePeriode = begrunnelseGrunnlag.forrigePeriode?.andeler?.any { it.type == YtelseType.SMÅBARNSTILLEGG } == true val erSmåbarnstilleggDennePerioden = begrunnelseGrunnlag.dennePerioden.andeler.any { it.type == YtelseType.SMÅBARNSTILLEGG } val erSmåbarnstilleggIForrigeBehandlingPeriode = begrunnelseGrunnlag.erSmåbarnstilleggIForrigeBehandlingPeriode() val begrunnelseGjelderSmåbarnstillegg = UtvidetBarnetrygdTrigger.SMÅBARNSTILLEGG in utvidetBarnetrygdTriggere val erEndringISmåbarnstilleggFraForrigeBehandling = erSmåbarnstilleggIForrigeBehandlingPeriode != erSmåbarnstilleggDennePerioden val begrunnelseMatcherPeriodeResultat = this.matcherPerioderesultat( erSmåbarnstilleggForrigePeriode, erSmåbarnstilleggDennePerioden, erSmåbarnstilleggIForrigeBehandlingPeriode, ) val erEndringISmåbarnstillegg = erSmåbarnstilleggForrigePeriode != erSmåbarnstilleggDennePerioden return begrunnelseGjelderSmåbarnstillegg && begrunnelseMatcherPeriodeResultat && (erEndringISmåbarnstillegg || erEndringISmåbarnstilleggFraForrigeBehandling) } private fun SanityBegrunnelse.erEtterEndretUtbetaling( endretUtbetalingDennePerioden: IEndretUtbetalingAndelForVedtaksperiode?, endretUtbetalingForrigePeriode: IEndretUtbetalingAndelForVedtaksperiode?, ): Boolean { if (!this.erEndringsårsakOgGjelderEtterEndretUtbetaling()) return false return this.matcherEtterEndretUtbetaling( endretUtbetalingDennePerioden = endretUtbetalingDennePerioden, endretUtbetalingForrigePeriode = endretUtbetalingForrigePeriode, ) } private fun SanityBegrunnelse.matcherEtterEndretUtbetaling( endretUtbetalingDennePerioden: IEndretUtbetalingAndelForVedtaksperiode?, endretUtbetalingForrigePeriode: IEndretUtbetalingAndelForVedtaksperiode?, ): Boolean { val begrunnelseMatcherEndretUtbetalingIForrigePeriode = this.endringsaarsaker.all { it == endretUtbetalingForrigePeriode?.årsak } val begrunnelseMatcherEndretUtbetalingIDennePerioden = this.endringsaarsaker.all { it == endretUtbetalingDennePerioden?.årsak } if (!begrunnelseMatcherEndretUtbetalingIForrigePeriode || begrunnelseMatcherEndretUtbetalingIDennePerioden) return false return endretUtbetalingForrigePeriode?.årsak != Årsak.DELT_BOSTED || this.erDeltBostedUtbetalingstype( endretUtbetalingForrigePeriode, ) } private fun SanityBegrunnelse.erEndringsårsakOgGjelderEtterEndretUtbetaling() = this.endringsaarsaker.isNotEmpty() && this.gjelderEtterEndretUtbetaling() private fun SanityBegrunnelse.gjelderEndretUtbetaling() = this.endringsaarsaker.isNotEmpty() && !this.gjelderEtterEndretUtbetaling() private fun SanityBegrunnelse.erLikEndretUtbetalingIPeriode( endretUtbetaling: IEndretUtbetalingAndelForVedtaksperiode?, ): Boolean { if (endretUtbetaling == null) return false val erEndringsårsakerIBegrunnelseOgPeriodeLike = this.endringsaarsaker.all { it == endretUtbetaling.årsak } if (!erEndringsårsakerIBegrunnelseOgPeriodeLike) return false return if (endretUtbetaling.årsak == Årsak.DELT_BOSTED) { this.erDeltBostedUtbetalingstype(endretUtbetaling) } else { true } } private fun SanityBegrunnelse.erDeltBostedUtbetalingstype( endretUtbetaling: IEndretUtbetalingAndelForVedtaksperiode, ): Boolean { val inneholderAndelSomSkalUtbetales = endretUtbetaling.prosent != BigDecimal.ZERO return when (this.endretUtbetalingsperiodeDeltBostedUtbetalingTrigger) { EndretUtbetalingsperiodeDeltBostedTriggere.UTBETALING_IKKE_RELEVANT -> true EndretUtbetalingsperiodeDeltBostedTriggere.SKAL_UTBETALES -> inneholderAndelSomSkalUtbetales EndretUtbetalingsperiodeDeltBostedTriggere.SKAL_IKKE_UTBETALES -> !inneholderAndelSomSkalUtbetales null -> true } } private fun hentEndretUtbetalingForrigePeriode(begrunnelseGrunnlag: IBegrunnelseGrunnlagForPeriode) = begrunnelseGrunnlag.forrigePeriode?.endretUtbetalingAndel.takeIf { begrunnelseGrunnlag.forrigePeriode?.erOrdinæreVilkårInnvilget() == true } private fun SanityBegrunnelse.matcherPerioderesultat( erSmåbarnstilleggForrigePeriode: Boolean, erSmåbarnstilleggDennePerioden: Boolean, erSmåbarnstilleggIForrigeBehandlingPeriode: Boolean, ): Boolean { val erReduksjon = !erSmåbarnstilleggDennePerioden && (erSmåbarnstilleggForrigePeriode || erSmåbarnstilleggIForrigeBehandlingPeriode) val erØkning = erSmåbarnstilleggDennePerioden && (!erSmåbarnstilleggForrigePeriode || !erSmåbarnstilleggIForrigeBehandlingPeriode) val erBegrunnelseReduksjon = periodeResultat == SanityPeriodeResultat.REDUKSJON val erBegrunnelseØkning = periodeResultat == SanityPeriodeResultat.INNVILGET_ELLER_ØKNING val reduksjonMatcher = erReduksjon == erBegrunnelseReduksjon val økningMatcher = erØkning == erBegrunnelseØkning return reduksjonMatcher && økningMatcher } fun ISanityBegrunnelse.erGjeldendeForOpphørFraForrigeBehandling(begrunnelseGrunnlag: IBegrunnelseGrunnlagForPeriode): Boolean { if (begrunnelseGrunnlag !is BegrunnelseGrunnlagForPeriodeMedOpphør || !begrunnelseGjelderOpphørFraForrigeBehandling()) { return false } val oppfylteVilkårDenneBehandlingen = begrunnelseGrunnlag.dennePerioden.vilkårResultater.filter { it.resultat == Resultat.OPPFYLT } .map { it.vilkårType }.toSet() val oppfylteVilkårsresultaterForrigeBehandling = begrunnelseGrunnlag.sammePeriodeForrigeBehandling?.vilkårResultater?.filter { it.resultat == Resultat.OPPFYLT } val oppfylteVilkårForrigeBehandling = oppfylteVilkårsresultaterForrigeBehandling?.map { it.vilkårType }?.toSet() ?: emptySet() val vilkårMistetSidenForrigeBehandling = oppfylteVilkårForrigeBehandling - oppfylteVilkårDenneBehandlingen val begrunnelseGjelderMistedeVilkår = if (this.vilkår.isNotEmpty()) { this.erLikVilkårOgUtdypendeVilkårIPeriode( oppfylteVilkårsresultaterForrigeBehandling?.filter { it.vilkårType in vilkårMistetSidenForrigeBehandling } ?: emptyList(), ) } else { vilkårMistetSidenForrigeBehandling.isNotEmpty() } val ikkeOppfylteVilkårDenneBehandlingen = begrunnelseGrunnlag.dennePerioden.vilkårResultater.filter { it.resultat == Resultat.IKKE_OPPFYLT } val begrunnelsenGjelderVilkårIkkeLengerOppfylt = this.erLikVilkårOgUtdypendeVilkårIPeriode(ikkeOppfylteVilkårDenneBehandlingen.filter { it.vilkårType in vilkårMistetSidenForrigeBehandling }) val dennePeriodenErFørsteVedtaksperiodePåFagsak = begrunnelseGrunnlag.forrigePeriode == null || begrunnelseGrunnlag.forrigePeriode!!.andeler.firstOrNull() == null return (begrunnelseGjelderMistedeVilkår || begrunnelsenGjelderVilkårIkkeLengerOppfylt) && dennePeriodenErFørsteVedtaksperiodePåFagsak }
9
Kotlin
1
9
e531227fb85cd4d7ef8f85fea7e3d285605a5527
17,826
familie-ba-sak
MIT License
cesium-kotlin/src/jsMain/kotlin/cesium/engine/DebugAppearance.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! @file:JsModule("@cesium/engine") package cesium.engine import kotlinx.js.JsPlainObject /** * Visualizes a vertex attribute by displaying it as a color for debugging. * * Components for well-known unit-length vectors, i.e., `normal`, * `tangent`, and `bitangent`, are scaled and biased * from [-1.0, 1.0] to (-1.0, 1.0). * ``` * const primitive = new Primitive({ * geometryInstances : // ... * appearance : new DebugAppearance({ * attributeName : 'normal' * }) * }); * ``` * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/DebugAppearance.html">Online Documentation</a> */ external class DebugAppearance( options: ConstructorOptions, ) { /** * @property [attributeName] The name of the attribute to visualize. * @property [perInstanceAttribute] Boolean that determines whether this attribute is a per-instance geometry attribute. * Default value - `false` * @property [glslDatatype] The GLSL datatype of the attribute. Supported datatypes are `float`, `vec2`, `vec3`, and `vec4`. * Default value - `'vec3'` * @property [vertexShaderSource] Optional GLSL vertex shader source to override the default vertex shader. * @property [fragmentShaderSource] Optional GLSL fragment shader source to override the default fragment shader. * @property [renderState] Optional render state to override the default render state. */ @JsPlainObject interface ConstructorOptions { val attributeName: String val perInstanceAttribute: Boolean? val glslDatatype: String? val vertexShaderSource: String? val fragmentShaderSource: String? val renderState: Any? } /** * This property is part of the [Appearance] interface, but is not * used by [DebugAppearance] since a fully custom fragment shader is used. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/DebugAppearance.html#material">Online Documentation</a> */ var material: Material /** * When `true`, the geometry is expected to appear translucent. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/DebugAppearance.html#translucent">Online Documentation</a> */ var translucent: Boolean /** * The GLSL source code for the vertex shader. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/DebugAppearance.html#vertexShaderSource">Online Documentation</a> */ val vertexShaderSource: String /** * The GLSL source code for the fragment shader. The full fragment shader * source is built procedurally taking into account the [DebugAppearance.material]. * Use [DebugAppearance.getFragmentShaderSource] to get the full source. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/DebugAppearance.html#fragmentShaderSource">Online Documentation</a> */ val fragmentShaderSource: String /** * The WebGL fixed-function state to use when rendering the geometry. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/DebugAppearance.html#renderState">Online Documentation</a> */ val renderState: Any /** * When `true`, the geometry is expected to be closed. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/DebugAppearance.html#closed">Online Documentation</a> */ val closed: Boolean /** * The name of the attribute being visualized. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/DebugAppearance.html#attributeName">Online Documentation</a> */ val attributeName: String /** * The GLSL datatype of the attribute being visualized. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/DebugAppearance.html#glslDatatype">Online Documentation</a> */ val glslDatatype: String /** * Returns the full GLSL fragment shader source, which for [DebugAppearance] is just * [DebugAppearance.fragmentShaderSource]. * @return The full GLSL fragment shader source. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/DebugAppearance.html#getFragmentShaderSource">Online Documentation</a> */ fun getFragmentShaderSource(): String /** * Determines if the geometry is translucent based on [DebugAppearance.translucent]. * @return `true` if the appearance is translucent. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/DebugAppearance.html#isTranslucent">Online Documentation</a> */ fun isTranslucent(): Boolean /** * Creates a render state. This is not the final render state instance; instead, * it can contain a subset of render state properties identical to the render state * created in the context. * @return The render state. * @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/DebugAppearance.html#getRenderState">Online Documentation</a> */ fun getRenderState(): Any }
1
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
4,954
types-kotlin
Apache License 2.0
feature/mobile/provider-settings/src/main/kotlin/com/flixclusive/feature/mobile/provider/settings/component/AuthorCard.kt
rhenwinch
659,237,375
false
{"Kotlin": 1598408, "Java": 18011}
package com.flixclusive.feature.mobile.provider.settings.component import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.flixclusive.core.ui.common.util.ifElse import com.flixclusive.core.ui.mobile.component.ImageWithSmallPlaceholder import com.flixclusive.gradle.entities.Author import com.flixclusive.core.ui.common.R as UiCommonR import com.flixclusive.core.util.R as UtilR @Composable internal fun AuthorCard( modifier: Modifier = Modifier, author: Author, ) { val uriHandler = LocalUriHandler.current Column( verticalArrangement = Arrangement.spacedBy(4.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier .ifElse( condition = author.githubLink != null, ifTrueModifier = Modifier.clickable { uriHandler.openUri(author.githubLink!!) } ) ) { ImageWithSmallPlaceholder( modifier = Modifier .size(45.dp), placeholderModifier = Modifier.fillMaxSize(), urlImage = "${author.githubLink}.png", placeholderId = UiCommonR.drawable.profile_placeholder, contentDescId = UtilR.string.author_icon_content_desc, ) Text( text = author.name, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.titleMedium.copy( fontWeight = FontWeight.Black, fontSize = 14.sp ) ) } }
22
Kotlin
21
255
96ef3356d3d5d756a83883af302d2312e6f6a619
2,183
Flixclusive
MIT License
BaseDebug/src/main/java/com/bihe0832/android/base/debug/audio/asr/DebugRecordAndASRFragRecment.kt
AndroidAppFactory
222,415,705
false
{"Java": 2866631, "C++": 2708240, "Kotlin": 1433883, "HTML": 18641, "JavaScript": 18036, "Groovy": 10003, "Shell": 5604, "AIDL": 3845, "CMake": 1415}
/* * * * * Created by zixie <[email protected]> on 2022/7/8 下午10:09 * * Copyright (c) 2022 . All rights reserved. * * Last modified 2022/7/8 下午10:05 * */ package com.bihe0832.android.base.debug.audio.asr import android.annotation.SuppressLint import android.content.Context import android.util.Log import android.view.View import com.bihe0832.android.common.debug.item.DebugItemData import com.bihe0832.android.common.debug.module.DebugEnvFragment import com.bihe0832.android.common.permission.PermissionResultOfAAF import com.bihe0832.android.framework.file.AAFFileWrapper import com.bihe0832.android.lib.aaf.tools.AAFDataCallback import com.bihe0832.android.lib.adapter.CardBaseModule import com.bihe0832.android.lib.audio.AudioRecordConfig import com.bihe0832.android.lib.audio.AudioUtils import com.bihe0832.android.lib.audio.record.AudioRecordManager import com.bihe0832.android.lib.audio.record.wrapper.AAFAudioTools import com.bihe0832.android.lib.audio.record.wrapper.AudioRecordFile import com.bihe0832.android.lib.audio.wav.PcmToWav import com.bihe0832.android.lib.audio.wav.WavHeader import com.bihe0832.android.lib.audio.wav.WaveFileReader import com.bihe0832.android.lib.file.FileUtils import com.bihe0832.android.lib.log.ZLog import com.bihe0832.android.lib.pinyin.FilePinyinMapDict import com.bihe0832.android.lib.pinyin.PinYinTools import com.bihe0832.android.lib.speech.DEFAULT_ENDPOINT_MODEL_DIR import com.bihe0832.android.lib.speech.DEFAULT_KWS_MODEL_DIR import com.bihe0832.android.lib.speech.endpoint.ASRWithEndpoint import com.bihe0832.android.lib.speech.getDefaultKeywordSpotterConfig import com.bihe0832.android.lib.speech.getDefaultOnlineRecognizerConfig import com.bihe0832.android.lib.speech.kws.KeywordSpotterManager import com.bihe0832.android.lib.speech.recognition.ASROfflineManager import com.k2fsa.sherpa.onnx.OfflineModelConfig import com.k2fsa.sherpa.onnx.OfflineParaformerModelConfig import com.k2fsa.sherpa.onnx.OfflineRecognizerConfig import com.k2fsa.sherpa.onnx.SherpaAudioConvertTools import com.k2fsa.sherpa.onnx.getFeatureConfig import java.io.File class DebugRecordAndASRFragRecment : DebugEnvFragment() { val TAG = this.javaClass.simpleName private val mAudioRecordFile = mutableListOf<AudioRecordFile>() private val mASROfflineManager by lazy { ASROfflineManager() } private val mKeywordSpotterManager by lazy { KeywordSpotterManager() } private val scene = "debugRecord" override fun getDataList(): ArrayList<CardBaseModule> { return ArrayList<CardBaseModule>().apply { add(DebugItemData("文字转拼音", View.OnClickListener { testPinyin() })) add(DebugItemData("指定文件 WAV头 信息查看", View.OnClickListener { readWavHead(preFile()) })) add(DebugItemData("空文件 WAV头 信息查看", View.OnClickListener { readWavHead(preEmpty()) })) add(getDebugFragmentItemData("本地 WAV 查看及识别", DebugWAVWithASRListFragment::class.java)) add(DebugItemData("初始化", View.OnClickListener { init() })) add( DebugItemData("ARS 静音检测:结束实时识别及录制", View.OnClickListener { ASRWithEndpoint.stopRecord(context!!) }) ) add(DebugItemData("ARS 实时打断", View.OnClickListener { forceEndCurrent() })) add(DebugItemData("ARS 静音检测:开启录制在回调保存为文件", View.OnClickListener { startRecord() })) add(DebugItemData("ARS 静音检测:开启录制在回调识别部分文区间", View.OnClickListener { testSplit() })) add(DebugItemData("ARS 识别:开启录制识别静音检测回调数据", View.OnClickListener { startReal() })) add(DebugItemData("ARS 识别:开启录制识别静音检测回调文件", View.OnClickListener { startRealFile() })) add(DebugItemData("ARS 识别:基于本地文件识别", View.OnClickListener { startFile(preFile()) })) add(DebugItemData("WAV 录制测试:开始录制", View.OnClickListener { startWav() })) add(DebugItemData("WAV 录制测试:结束录制", View.OnClickListener { stopWav() })) add(DebugItemData("WAV 录制测试:录制文件开始(可同时多个)", View.OnClickListener { startWaveFile() })) add(DebugItemData("WAV 录制测试:录制文件结束(关闭所有)", View.OnClickListener { stopWaveFile() })) add(DebugItemData( "清空本地音频临时缓存" ) { FileUtils.deleteDirectory(File(AAFFileWrapper.getMediaTempFolder())) }) } } private fun testPinyin() { mutableListOf("阿珂没有闪现", "妲己没闪现", "大司命没有技能").forEach { ZLog.d(it + " Convert to Pinyin:" + PinYinTools.toPinyin(it, "").toLowerCase()) ZLog.d(it + " Convert to Pinyin:" + PinYinTools.toPinyin(it, " ").toLowerCase()) ZLog.d(it + " Convert to Pinyin:" + PinYinTools.toPinyin(it, ",").toLowerCase()) ZLog.d(it + " Convert to Pinyin:" + PinYinTools.toPinyin(it, "-").toLowerCase()) } } @SuppressLint("MissingPermission") fun init() { val file = AAFFileWrapper.getTempFolder() + "dict.txt" FileUtils.copyAssetsFileToPath(context, "cncity.txt", file) PinYinTools.init( PinYinTools.newConfig().with( FilePinyinMapDict( context!!, file ) ) ) AAFAudioTools.addRecordScene(scene, "读取麦克风", "音频录制测试") AAFAudioTools.startRecordPermissionCheck(activity, scene, object : PermissionResultOfAAF(false) { override fun onSuccess() { AAFAudioTools.init() ASRWithEndpoint.init( context!!, getDefaultOnlineRecognizerConfig( AudioRecordConfig.DEFAULT_SAMPLE_RATE_IN_HZ, DEFAULT_ENDPOINT_MODEL_DIR ) ) mASROfflineManager.initRecognizer(getASROfflineRecognizerConfig(context!!)) mKeywordSpotterManager.initRecognizer( context!!, getDefaultKeywordSpotterConfig( AudioRecordConfig.DEFAULT_SAMPLE_RATE_IN_HZ, DEFAULT_KWS_MODEL_DIR ) ) } }) } fun startWav() { AAFAudioTools.startRecordPermissionCheck(activity, scene, object : PermissionResultOfAAF(false) { override fun onSuccess() { AudioRecordManager.startRecord( activity, scene, "rere" ) { config, audioChunk, dataLength -> ZLog.d(TAG, "Started recording callback:${dataLength}") } } }) } fun stopWav() { AudioRecordManager.stopRecord(context!!, scene) } fun startWaveFile() { val file = AAFFileWrapper.getMediaTempFolder() + System.currentTimeMillis() + ".wav" AAFAudioTools.startRecordPermissionCheck(activity, scene, object : PermissionResultOfAAF(false) { override fun onSuccess() { AudioRecordFile(System.currentTimeMillis().toString(), File(file)).let { mAudioRecordFile.add(it) it.startRecord(activity, "特惠") } } }) } fun stopWaveFile() { mAudioRecordFile.forEach { it.stopRecord(context!!) } } fun preFile(): String { val file = AAFFileWrapper.getMediaTempFolder() + "temp.wav" FileUtils.copyAssetsFileToPath(context!!, "0.wav", file) return file } fun preEmpty(): String { val file = AAFFileWrapper.getMediaTempFolder() + "temp.wav" File(file).let { FileUtils.deleteFile(file) it.createNewFile() FileUtils.writeDataToFile( file, 0, WavHeader( AudioRecordConfig( AudioRecordConfig.DEFAULT_AUDIO_SOURCE, AudioRecordConfig.DEFAULT_SAMPLE_RATE_IN_HZ, AudioRecordConfig.DEFAULT_CHANNEL_CONFIG, AudioRecordConfig.DEFAULT_AUDIO_FORMAT ), it.length() ).toBytes(), false ) } return file } fun readWavHead(filePath: String) { val wavFileReader = WaveFileReader(filePath) ZLog.d(wavFileReader.toString()) } fun startRecord() { AAFAudioTools.startRecordPermissionCheck(activity, scene, object : PermissionResultOfAAF(false) { override fun onSuccess() { ASRWithEndpoint.startDataRecord() { audioRecordConfig, pcmData, result -> ZLog.d(TAG, "Started recording callback:${pcmData?.size}") val fileFolder = AAFFileWrapper.getMediaTempFolder() pcmData?.let { if (FileUtils.checkAndCreateFolder(fileFolder)) { val file = FileUtils.getFolderPathWithSeparator(fileFolder) + System.currentTimeMillis() + ".wav" ZLog.d(TAG, "record data:${file}") val byteArray = AudioUtils.shortArrayToByteArray(pcmData) PcmToWav( audioRecordConfig.sampleRateInHz, audioRecordConfig.channelConfig, audioRecordConfig.audioFormat ).convertToFile(byteArray, file) ZLog.d(TAG, "record data:${file}") } } } } }) } fun forceEndCurrent() { ASRWithEndpoint.forceEndCurrent().let { ZLog.d(TAG, "forceEndCurrent:$it") } } fun testSplit() { ASRWithEndpoint.startDataRecord { audioRecordConfig, pcmData, result -> ZLog.d(TAG, "Started recording callback:${pcmData?.size}") val fileFolder = AAFFileWrapper.getMediaTempFolder() pcmData?.let { if (FileUtils.checkAndCreateFolder(fileFolder)) { val file = FileUtils.getFolderPathWithSeparator(fileFolder) + System.currentTimeMillis() + ".wav" ZLog.d(TAG, "record data:${file}") val byteArray = AudioUtils.shortArrayToByteArray(pcmData) recognise( audioRecordConfig.sampleRateInHz, SherpaAudioConvertTools.byteArrayToSherpaArray(byteArray) ) PcmToWav( audioRecordConfig.sampleRateInHz, audioRecordConfig.channelConfig, audioRecordConfig.audioFormat ).convertToFile(byteArray, file) val length = it.size * 1.0f / audioRecordConfig.sampleRateInHz if (length > 3.2) { val shortArray = ShortArray((audioRecordConfig.sampleRateInHz * 3.2).toInt() + audioRecordConfig.sampleRateInHz) System.arraycopy( it, it.size - (audioRecordConfig.sampleRateInHz * 3.2).toInt(), shortArray, audioRecordConfig.sampleRateInHz, (audioRecordConfig.sampleRateInHz * 3.2).toInt() ) val file2 = FileUtils.getFolderPathWithSeparator(fileFolder) + System.currentTimeMillis() + ".wav" val byteArray2 = AudioUtils.shortArrayToByteArray(shortArray) recognise( audioRecordConfig.sampleRateInHz, SherpaAudioConvertTools.byteArrayToSherpaArray(byteArray2) ) PcmToWav( audioRecordConfig.sampleRateInHz, audioRecordConfig.channelConfig, audioRecordConfig.audioFormat ).convertToFile(byteArray2, file2) ZLog.d(TAG, "record data:${file2}") } } } } } fun startReal() { ASRWithEndpoint.startDataRecord { audioRecordConfig, pcmData, result -> pcmData?.let { data -> Log.i(TAG, "====================") val max = (Short.MAX_VALUE * 0.1f).toInt().toShort() Log.i( TAG, "record data size:${pcmData.size} max:$max, audioMax: ${pcmData.max()}" ) if (SherpaAudioConvertTools.isOverSilence(pcmData, max)) { val samples = SherpaAudioConvertTools.shortArrayToSherpaArray(data, data.size) recognise(audioRecordConfig.sampleRateInHz, samples) // AudioUtils.shortArrayToByteArray(data).let { // SherpaAudioConvertTools.byteArrayToSherpaArray(it).let { float -> // recognise(audioRecordConfig.sampleRateInHz, float) // } // // AudioUtils.byteArrayToShortArray(it, it.size).let { short -> // val erer = SherpaAudioConvertTools.shortArrayToSherpaArray(short, short.size) // recognise(audioRecordConfig.sampleRateInHz, erer) // } // } } else { Log.i(TAG, "无效音频,无有效内容") } Log.i(TAG, "====================") } } } fun startRealFile() { val max = (Short.MAX_VALUE * 0.1f).toInt().toShort() ASRWithEndpoint.startFileRecord(activity, "File", AAFFileWrapper.getMediaTempFolder(), max, object : AAFDataCallback<String>() { override fun onSuccess(result: String?) { ZLog.d(TAG, "record data:${result}") result?.let { readWavHead(it) recognise( WaveFileReader(result).sampleRate.toInt(), SherpaAudioConvertTools.readWavAudioToSherpaArray(result) ) } } }) } fun concatenate(first: FloatArray?, second: FloatArray?): FloatArray { val result = FloatArray((first?.size ?: 0) + (second?.size ?: 0)) first?.copyInto(result, 0) second?.copyInto(result, first?.size ?: 0) return result } fun recognise(sampleRateInHz: Int, data: FloatArray?) { data?.let { samples -> Log.i(TAG, "record data:${samples.size}") mKeywordSpotterManager.doRecognizer(sampleRateInHz, samples).let { Log.i(TAG, "mKeywordSpotterManager Start to recognizer:$it") } mASROfflineManager.startRecognizer(sampleRateInHz, samples).let { Log.i(TAG, "mRecognizerManager Start to recognizer:$it") } } } fun startFile(file: String) { readWavHead(file) SherpaAudioConvertTools.readWavAudioToSherpaArray(file)?.let { recognise(WaveFileReader(file).sampleRate.toInt(), it) } } } fun getASROfflineRecognizerConfig(context: Context): OfflineRecognizerConfig { val modelDir = "sherpa-onnx-paraformer-zh-2023-09-14" FileUtils.copyAssetsFolderToFolder(context, modelDir, AAFFileWrapper.getTempFolder() + modelDir) return OfflineRecognizerConfig( featConfig = getFeatureConfig(AudioRecordConfig.DEFAULT_SAMPLE_RATE_IN_HZ, 80), modelConfig = OfflineModelConfig( paraformer = OfflineParaformerModelConfig( model = AAFFileWrapper.getTempFolder() + "$modelDir/model.int8.onnx", ), tokens = AAFFileWrapper.getTempFolder() + "$modelDir/tokens.txt", modelType = "paraformer", ) ) }
0
Java
21
72
e11cbca06d092a3bdd5a58dd4a5260b1f4a208d8
15,828
AndroidAppFactory
MIT License
ui-kit/src/main/java/com/quickblox/android_ui_kit/presentation/base/BaseViewModel.kt
QuickBlox
637,751,718
false
{"Kotlin": 1833847}
/* * Created by Injoit on 13.01.2023. * Copyright © 2023 Quickblox. All rights reserved. */ package com.quickblox.android_ui_kit.presentation.base import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.quickblox.android_ui_kit.QuickBloxUiKit import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch abstract class BaseViewModel : ViewModel() { private var connectionRepository = QuickBloxUiKit.getDependency().getConnectionRepository() private var connectionJob: Job? = null private val _errorMessage = MutableLiveData<String>() val errorMessage: LiveData<String> get() = _errorMessage private val _loading = MutableLiveData<Boolean>() val loading: LiveData<Boolean> get() = _loading protected fun subscribeConnection() { if (connectionJob?.isActive == true) { return } connectionJob = viewModelScope.launch { connectionRepository.subscribe().collect { connected -> CoroutineScope(Dispatchers.Main).launch { if (connected) { onConnected() } else { onDisconnected() } } } } } protected fun showError(message: String?) { message?.let { _errorMessage.postValue(it) } } protected fun showLoading() { _loading.postValue(true) } protected fun hideLoading() { _loading.postValue(false) } protected open fun onConnected() {} protected open fun onDisconnected() {} }
1
Kotlin
0
4
0ef856d22efb1540d6e238a073badbf31c03961a
1,798
android-ui-kit
MIT License
ComposeCollapsingTopBar/src/main/java/com/flaringapp/compose/topbar/nestedcollapse/CollapsingTopBarNestedCollapseState.kt
flaringapp
825,947,316
false
{"Kotlin": 214786}
/* * Copyright 2024 Flaringapp * * 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.flaringapp.compose.topbar.nestedcollapse import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.remember import com.flaringapp.compose.topbar.CollapsingTopBar /** * Creates a [CollapsingTopBarNestedCollapseState] that is remembered across compositions. */ @Composable fun rememberCollapsingTopBarNestedCollapseState(): CollapsingTopBarNestedCollapseState { return remember { CollapsingTopBarNestedCollapseState() } } /** * A contract for any top bar [CollapsingTopBar] nested collapse element to provide its own * minimum height. Used in [CollapsingTopBar] to determine ultimate minimum top bar height. * * @see CollapsingTopBar * @see CollapsingTopBarColumn */ @Stable interface CollapsingTopBarNestedCollapseElement { /** * The minimum height of this nested collapse element. */ val minHeight: Int } /** * A mutable implementation of [CollapsingTopBarNestedCollapseElement] for nested collapse element * to update. Must be updated in measurement phase. * * In most cases, this will be created via [rememberCollapsingTopBarNestedCollapseState]. */ @Stable class CollapsingTopBarNestedCollapseState : CollapsingTopBarNestedCollapseElement { /** * The minimum height of this nested collapse element. Must be updated in measurement phase. * Not a state because hosting [CollapsingTopBar] is remeasured every time after this element, * therefore reads up to date value anyways. */ override var minHeight: Int = 0 }
1
Kotlin
0
1
17dce0307bc2f51a63e869345be33aa6ff30d7d4
2,159
ComposeCollapsingTopBar
Apache License 2.0
src/main/kotlin/ru/nick252/types/results/services/ServicesKeepDays.kt
nick2525
344,564,064
false
null
package ru.nick252.types.results.services data class ServicesKeepDays( val name: String?, val description: String?, val example: String?, val selector: ServicesSelector? )
0
Kotlin
0
1
b599b5e2567b939dd1326f8ddbfee8040ae49367
188
KotlinHAApi
MIT License
library-common/src/main/kotlin/cz/filipproch/reactor/common/views/events/OptionsItemSelectedEvent.kt
Reacto-Rx
95,313,773
false
null
package cz.filipproch.reactor.common.views.events import android.view.MenuItem import cz.filipproch.reactor.base.view.UiEvent /** * TODO: add description */ data class OptionsItemSelectedEvent( val menuItem: MenuItem ) : UiEvent
0
Kotlin
0
1
e2fc992cfbb55963acb407972437d63efabedbb9
240
reactorx-core
MIT License
server-testing/src/test/kotlin/com/lightningkite/lightningserver/auth/SmsAuthTest.kt
lightningkite
512,032,499
false
{"Kotlin": 2203220, "TypeScript": 38628, "JavaScript": 118}
package com.lightningkite.lightningdb.test.com.lightningkite.lightningserver.auth import com.lightningkite.lightningdb.collection import com.lightningkite.lightningserver.TestSettings import com.lightningkite.lightningdb.test.User import com.lightningkite.lightningserver.auth.* import com.lightningkite.lightningserver.auth.old.* import com.lightningkite.lightningserver.auth.old.BaseAuthEndpoints import com.lightningkite.lightningserver.auth.old.SmsAuthEndpoints import com.lightningkite.lightningserver.core.ServerPath import com.lightningkite.lightningserver.db.ModelSerializationInfo import com.lightningkite.lightningserver.db.modelInfo import com.lightningkite.lightningserver.exceptions.BadRequestException import com.lightningkite.lightningserver.http.HttpHeader import com.lightningkite.lightningserver.http.HttpHeaders import com.lightningkite.lightningserver.http.HttpStatus import com.lightningkite.lightningserver.http.test import com.lightningkite.lightningserver.sms.TestSMSClient import com.lightningkite.lightningserver.typed.AuthAndPathParts import kotlinx.coroutines.runBlocking import org.junit.Test import kotlin.time.Duration import java.util.* import kotlin.test.assertEquals import kotlin.test.fail import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.minutes class SmsAuthTest { init { TestSettings } @Test fun testPinCorrect() { val info = modelInfo<User, User, UUID>( getBaseCollection = { TestSettings.database().collection() }, forUser = { it }, authOptions = authOptions<User>(), serialization = ModelSerializationInfo() ) val phoneAccess: UserPhoneAccess<User, UUID> = info.userPhoneAccess { User(email = "$it@phone", phoneNumber = it) } val path = ServerPath("auth") val baseAuth = BaseAuthEndpoints(path, phoneAccess, TestSettings.jwtSigner, expiration = 1.hours, emailExpiration = 5.minutes) val phoneAuth = SmsAuthEndpoints(baseAuth, phoneAccess, TestSettings.cache, TestSettings.sms) runBlocking { phoneAuth.loginSms.implementation(AuthAndPathParts(null, null, arrayOf()), "8013693729") val pinRegex = Regex("[0-9][0-9][0-9][0-9][0-9][0-9]") val pin = (TestSettings.sms() as TestSMSClient).lastMessageSent?.message?.let { pinRegex.find(it)?.value }!! val token = phoneAuth.loginSmsPin.implementation(AuthAndPathParts(null, null, arrayOf()), PhonePinLogin("8013693729", pin)) assertEquals( HttpStatus.OK, baseAuth.getSelf.route.endpoint.test( headers = HttpHeaders(HttpHeader.Authorization to token, HttpHeader.ContentType to "application/json") ).status) } } @Test fun testPinIncorrect() { val info = modelInfo<User, User, UUID>( getBaseCollection = { TestSettings.database().collection() }, forUser = { it }, authOptions = authOptions<User>(), serialization = ModelSerializationInfo() ) val phoneAccess: UserPhoneAccess<User, UUID> = info.userPhoneAccess { User(email = "$it@phone", phoneNumber = it) } val path = ServerPath("auth") val baseAuth = BaseAuthEndpoints(path, phoneAccess, TestSettings.jwtSigner, expiration = 1.hours, emailExpiration = 5.minutes) val phoneAuth = SmsAuthEndpoints(baseAuth, phoneAccess, TestSettings.cache, TestSettings.sms) runBlocking { phoneAuth.loginSms.implementation(AuthAndPathParts(null, null, arrayOf()), "8013693729") val pinRegex = Regex("[0-9][0-9][0-9][0-9][0-9][0-9]") val pin = "wrong" try { phoneAuth.loginSmsPin.implementation(AuthAndPathParts(null, null, arrayOf()), PhonePinLogin("8013693729", pin)) fail() } catch (e: BadRequestException) { assertEquals("Incorrect PIN. 4 attempts remain.", e.message) } } } }
2
Kotlin
1
5
f404cc57cbdbe2a90b4e59d4ecd5ad22e008a730
4,045
lightning-server
MIT License
compiler/src/main/kotlin/eu/nitok/jitsu/compiler/graph/Utils.kt
nbrugger-tgm
683,089,096
false
{"Kotlin": 135785, "TypeScript": 4002}
package eu.nitok.jitsu.compiler.graph import eu.nitok.jitsu.compiler.diagnostic.CompilerMessage sealed interface ReasonedBoolean { data object True: ReasonedBoolean data class False(val message: String, val hints: List<CompilerMessage.Hint>) : ReasonedBoolean{ constructor(message: String, vararg hints: CompilerMessage.Hint) : this( message, hints.toList() ) } }
0
Kotlin
0
0
89c549b28b5cacf39e75ab0cd5f8296ddd45c017
418
jitsu
Apache License 2.0
src/main/kotlin/com/github/lppedd/cc/whatsnew/WhatsNewAction.kt
lppedd
208,670,987
false
null
package com.github.lppedd.cc.whatsnew import com.github.lppedd.cc.CCBundle import com.github.lppedd.cc.CCIcons import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction /** * Displays a dialog containing plugin's changelogs. * * @author <NAME> * @see [WhatsNewDialog] */ private class WhatsNewAction : DumbAwareAction() { init { templatePresentation.apply { text = CCBundle["cc.whatsnew.title"] icon = CCIcons.Logo } } override fun actionPerformed(event: AnActionEvent) { WhatsNewDialog.showForProject(event.project ?: return) } }
24
null
12
189
97bf78ac1757379f035c58cd8706381d9bcb8da1
620
idea-conventional-commit
MIT License
shared/src/commonMain/kotlin/core/ui/screens/itemlist/ItemHome.kt
wgcarvajal
683,392,078
false
{"Kotlin": 325898, "Swift": 2024, "Shell": 228}
package core.ui.screens.itemlist import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import dev.icerock.moko.resources.ImageResource import dev.icerock.moko.resources.compose.painterResource @Composable fun ItemHome( text: String, backgroundColor: Color, imageResource: ImageResource, onClick: () -> Unit ) { Box( modifier = Modifier.fillMaxWidth() .height(120.dp) ) { Box( modifier = Modifier.fillMaxSize() .padding(top = 20.dp) .clickable { onClick() } .border( width = 5.dp, color = Color.White, shape = RoundedCornerShape(10) ) .shadow(elevation = 2.dp, shape = RoundedCornerShape(10)) .clip(shape = RoundedCornerShape(10)) .background(color = backgroundColor) ) Image( modifier = Modifier.fillMaxHeight(), painter = painterResource(imageResource), contentScale = ContentScale.FillHeight, contentDescription = null ) Text( modifier = Modifier.align(alignment = Alignment.CenterEnd) .padding(top = 30.dp, end = 15.dp), text = text, color = Color.White, fontSize = 16.sp ) } }
0
Kotlin
0
0
9f17ae1098b80f4e80ad8dbe5f9a1eccd3c74725
2,254
guau-multiplatform
Apache License 2.0
MVIPractice/data/src/main/java/com/kimmandoo/data/usecase/file/GetImageUseCaseImpl.kt
kimmandoo
810,895,614
false
{"Kotlin": 300640}
package com.kimmandoo.data.usecase.file import android.content.Context import android.net.Uri import android.provider.MediaStore import com.kimmandoo.domain.model.Image import com.kimmandoo.domain.usecase.file.GetImageUseCase import javax.inject.Inject class GetImageUseCaseImpl @Inject constructor( private val context: Context ) : GetImageUseCase { override fun invoke(contentUri: String): Image? { val uri = Uri.parse(contentUri) val projection = arrayOf( MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.SIZE, MediaStore.Images.Media.MIME_TYPE ) val cursor = context.contentResolver.query( uri, projection, null, null, null ) return cursor?.use { c-> c.moveToNext() // 커서를 한칸 내려서 정보 가져오기 val idIdx = c.getColumnIndexOrThrow(projection[0]) val nameIdx = c.getColumnIndexOrThrow(projection[1]) val sizeIdx = c.getColumnIndexOrThrow(projection[2]) val typeIdx = c.getColumnIndexOrThrow(projection[3]) // idx를 알아야 커서가 컬럼에 대한 값을 가져올 수 있다 val id = c.getLong(idIdx) val name = c.getString(nameIdx) val size = c.getLong(sizeIdx) val type = c.getString(typeIdx) Image(contentUri, name, size, type) } } }
0
Kotlin
0
0
9a8ea13862807e5064362abaab34cef720c379cf
1,452
android-drill
MIT License
app/src/main/java/com/patar_dev/opportunityowl/model/notification/NotificationDataTwo.kt
DevP-ai
700,999,288
false
{"Kotlin": 58751}
package com.patar_dev.opportunityowl.model.notification data class NotificationDataTwo ( val name : String ? = null, val jobTitle : String ? = null, )
0
Kotlin
0
0
ded20284a62accd98426074745930d438834396a
159
OpportunityOwl
MIT License
glide-loader/src/main/java/com/ouattararomuald/slider/loaders/glide/GlideImageLoader.kt
eajazi
214,972,654
true
{"Kotlin": 42465, "Java": 1568}
package com.ouattararomuald.slider.loaders.glide import android.widget.ImageView import androidx.annotation.DrawableRes import com.ouattararomuald.slider.ImageLoader /** * Loads images image using Glide. * * @property errorResId an error drawable to be used if the request image could not be loaded. * @property placeholderResId a placeholder drawable to be used while the image is being loaded. * If the requested image is not immediately available in the memory cache then this resource * will be set on the target [ImageView]. */ class GlideImageLoader( @DrawableRes private val errorResId: Int, @DrawableRes private val placeholderResId: Int ) : ImageLoader { override fun load(path: String, imageView: ImageView) { GlideApp.with(imageView).load(path).apply { if (placeholderResId > 0) { placeholder(placeholderResId) } if (errorResId > 0) { error(errorResId) } centerCrop() into(imageView) } } }
0
Kotlin
0
0
ac033e669d75fdd68ca0bf303b8a514a018d938c
979
android-image-slider
Apache License 2.0
sample/src/main/java/com/miquido/restmock/sample/SampleApplication.kt
miquido
330,661,583
false
null
package com.miquido.restmock.sample import android.app.Application import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin import org.koin.core.logger.Level import timber.log.Timber class SampleApplication : Application() { override fun onCreate() { super.onCreate() initTimber() initKoin() } private fun initTimber() { if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) } } private fun initKoin() { startKoin { androidContext(this@SampleApplication) androidLogger(Level.NONE) modules( mainModule(mockApi = BuildConfig.API_MOCKED) ) } } }
0
Kotlin
0
1
b357f1362e4ad2c9dcb66b5c909e75c91f7ddf86
785
rest-mock
Apache License 2.0
backend/src/main/kotlin/net/iceyleagons/butler/services/GatekeeperService.kt
IceyLeagons
561,907,558
false
{"Kotlin": 47195, "Svelte": 24955, "TypeScript": 22439, "SCSS": 2753, "HTML": 1308, "CSS": 291, "JavaScript": 213}
package net.iceyleagons.butler.services import com.fasterxml.jackson.annotation.JsonProperty import jakarta.servlet.http.HttpServletRequest import java.util.* interface GatekeeperService { data class GatekeeperEntity( val id: String, val email: String, val displayName: String, val identities: List<GatekeeperIdentity> ) { fun getIdentityById(id: String): Optional<GatekeeperIdentity> { return Optional.ofNullable(identities.firstOrNull { it.providerId == id }) } } fun getAuthorizeUri(): String fun getLinkUri(): String fun fetchInformation(request: HttpServletRequest): GatekeeperEntity data class GatekeeperIdentity( val providerId: String, val providerAccessToken: String, @JsonProperty("providerAccessTokenExpires") val providerAccessTokenExpiry: Long, @JsonProperty("data") val extraData: Map<String, Any> ) }
0
Kotlin
0
0
c5c110fb17dd40ec9429e76f48658c5af53cf67c
959
Butler
MIT License
rest/src/commonMain/kotlin/service/AutoModerationService.kt
kordlib
202,856,399
false
{"Kotlin": 2692423, "Java": 87103}
package dev.kord.rest.service import dev.kord.common.entity.AutoModerationRuleEventType import dev.kord.common.entity.DiscordAutoModerationRule import dev.kord.common.entity.Snowflake import dev.kord.rest.builder.automoderation.* import dev.kord.rest.json.request.AutoModerationRuleCreateRequest import dev.kord.rest.json.request.AutoModerationRuleModifyRequest import dev.kord.rest.request.RequestHandler import dev.kord.rest.request.auditLogReason import dev.kord.rest.route.Route import kotlin.contracts.InvocationKind.EXACTLY_ONCE import kotlin.contracts.contract public class AutoModerationService(requestHandler: RequestHandler) : RestService(requestHandler) { public suspend fun listAutoModerationRulesForGuild(guildId: Snowflake): List<DiscordAutoModerationRule> = call(Route.AutoModerationRulesForGuildList) { keys[Route.GuildId] = guildId } public suspend fun getAutoModerationRule(guildId: Snowflake, ruleId: Snowflake): DiscordAutoModerationRule = call(Route.AutoModerationRuleGet) { keys[Route.GuildId] = guildId keys[Route.AutoModerationRuleId] = ruleId } public suspend fun createAutoModerationRule( guildId: Snowflake, request: AutoModerationRuleCreateRequest, reason: String? = null, ): DiscordAutoModerationRule = call(Route.AutoModerationRuleCreate) { keys[Route.GuildId] = guildId body(AutoModerationRuleCreateRequest.serializer(), request) auditLogReason(reason) } public suspend inline fun createKeywordAutoModerationRule( guildId: Snowflake, name: String, eventType: AutoModerationRuleEventType, builder: KeywordAutoModerationRuleCreateBuilder.() -> Unit, ): DiscordAutoModerationRule { contract { callsInPlace(builder, EXACTLY_ONCE) } val request = KeywordAutoModerationRuleCreateBuilder(name, eventType).apply(builder) return createAutoModerationRule(guildId, request.toRequest(), request.reason) } public suspend inline fun createSpamAutoModerationRule( guildId: Snowflake, name: String, eventType: AutoModerationRuleEventType, builder: SpamAutoModerationRuleCreateBuilder.() -> Unit, ): DiscordAutoModerationRule { contract { callsInPlace(builder, EXACTLY_ONCE) } val request = SpamAutoModerationRuleCreateBuilder(name, eventType).apply(builder) return createAutoModerationRule(guildId, request.toRequest(), request.reason) } public suspend inline fun createKeywordPresetAutoModerationRule( guildId: Snowflake, name: String, eventType: AutoModerationRuleEventType, builder: KeywordPresetAutoModerationRuleCreateBuilder.() -> Unit, ): DiscordAutoModerationRule { contract { callsInPlace(builder, EXACTLY_ONCE) } val request = KeywordPresetAutoModerationRuleCreateBuilder(name, eventType).apply(builder) return createAutoModerationRule(guildId, request.toRequest(), request.reason) } public suspend inline fun createMentionSpamAutoModerationRule( guildId: Snowflake, name: String, eventType: AutoModerationRuleEventType, builder: MentionSpamAutoModerationRuleCreateBuilder.() -> Unit, ): DiscordAutoModerationRule { contract { callsInPlace(builder, EXACTLY_ONCE) } val request = MentionSpamAutoModerationRuleCreateBuilder(name, eventType).apply(builder) return createAutoModerationRule(guildId, request.toRequest(), request.reason) } @Deprecated( "The 'mentionLimit' parameter is optional, only 'mentionLimit' OR 'mentionRaidProtectionEnabled' is required.", ReplaceWith( "this.createMentionSpamAutoModerationRule(guildId, name, eventType) { " + "[email protected] = mentionLimit\nbuilder() }" ), DeprecationLevel.WARNING, ) public suspend inline fun createMentionSpamAutoModerationRule( guildId: Snowflake, name: String, eventType: AutoModerationRuleEventType, mentionLimit: Int, builder: MentionSpamAutoModerationRuleCreateBuilder.() -> Unit, ): DiscordAutoModerationRule { contract { callsInPlace(builder, EXACTLY_ONCE) } return createMentionSpamAutoModerationRule(guildId, name, eventType) { this.mentionLimit = mentionLimit builder() } } public suspend fun modifyAutoModerationRule( guildId: Snowflake, ruleId: Snowflake, request: AutoModerationRuleModifyRequest, reason: String? = null, ): DiscordAutoModerationRule = call(Route.AutoModerationRuleModify) { keys[Route.GuildId] = guildId keys[Route.AutoModerationRuleId] = ruleId body(AutoModerationRuleModifyRequest.serializer(), request) auditLogReason(reason) } public suspend inline fun modifyUntypedAutoModerationRule( guildId: Snowflake, ruleId: Snowflake, builder: UntypedAutoModerationRuleModifyBuilder.() -> Unit, ): DiscordAutoModerationRule { contract { callsInPlace(builder, EXACTLY_ONCE) } val request = UntypedAutoModerationRuleModifyBuilder().apply(builder) return modifyAutoModerationRule(guildId, ruleId, request.toRequest(), request.reason) } public suspend inline fun modifyKeywordAutoModerationRule( guildId: Snowflake, ruleId: Snowflake, builder: KeywordAutoModerationRuleModifyBuilder.() -> Unit, ): DiscordAutoModerationRule { contract { callsInPlace(builder, EXACTLY_ONCE) } val request = KeywordAutoModerationRuleModifyBuilder().apply(builder) return modifyAutoModerationRule(guildId, ruleId, request.toRequest(), request.reason) } public suspend inline fun modifySpamAutoModerationRule( guildId: Snowflake, ruleId: Snowflake, builder: SpamAutoModerationRuleModifyBuilder.() -> Unit, ): DiscordAutoModerationRule { contract { callsInPlace(builder, EXACTLY_ONCE) } val request = SpamAutoModerationRuleModifyBuilder().apply(builder) return modifyAutoModerationRule(guildId, ruleId, request.toRequest(), request.reason) } public suspend inline fun modifyKeywordPresetAutoModerationRule( guildId: Snowflake, ruleId: Snowflake, builder: KeywordPresetAutoModerationRuleModifyBuilder.() -> Unit, ): DiscordAutoModerationRule { contract { callsInPlace(builder, EXACTLY_ONCE) } val request = KeywordPresetAutoModerationRuleModifyBuilder().apply(builder) return modifyAutoModerationRule(guildId, ruleId, request.toRequest(), request.reason) } public suspend inline fun modifyMentionSpamAutoModerationRule( guildId: Snowflake, ruleId: Snowflake, builder: MentionSpamAutoModerationRuleModifyBuilder.() -> Unit, ): DiscordAutoModerationRule { contract { callsInPlace(builder, EXACTLY_ONCE) } val request = MentionSpamAutoModerationRuleModifyBuilder().apply(builder) return modifyAutoModerationRule(guildId, ruleId, request.toRequest(), request.reason) } public suspend fun deleteAutoModerationRule( guildId: Snowflake, ruleId: Snowflake, reason: String? = null, ): Unit = call(Route.AutoModerationRuleDelete) { keys[Route.GuildId] = guildId keys[Route.AutoModerationRuleId] = ruleId auditLogReason(reason) } }
43
Kotlin
74
781
29a904b330c592799c29381e7cfa9fe99f8e9dc0
7,567
kord
MIT License
sample/wearapp/src/main/java/com/estivensh4/wearapp/presentation/MainActivity.kt
estivensh
716,450,518
false
{"Kotlin": 155379, "Shell": 2027}
package com.estivensh4.wearapp.presentation import android.os.Bundle import android.os.StrictMode import android.os.StrictMode.ThreadPolicy import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable 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.platform.LocalContext import androidx.compose.ui.tooling.preview.Devices import androidx.compose.ui.tooling.preview.Preview import androidx.wear.compose.material.Button import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.PositionIndicator import androidx.wear.compose.material.Scaffold import androidx.wear.compose.material.ScalingLazyColumn import androidx.wear.compose.material.Text import androidx.wear.compose.material.TimeText import androidx.wear.compose.material.rememberScalingLazyListState import com.estivensh4.s3.ImageFile import com.estivensh4.shared.SampleViewModel import com.estivensh4.wearapp.presentation.theme.ExampleTheme import kotlinx.datetime.Clock import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.plus class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val gfgPolicy = ThreadPolicy.Builder().permitAll().build() StrictMode.setThreadPolicy(gfgPolicy) setContent { WearApp() } } } @Composable fun WearApp() { ExampleTheme { val sampleViewModel = SampleViewModel() val bucketName = "test-bucket-wear-app" val state = rememberScalingLazyListState() val context = LocalContext.current val key = "test (1).jpg" val photoPicker = rememberLauncherForActivityResult( contract = ActivityResultContracts.PickVisualMedia() ) { if (it != null) { sampleViewModel.putObject( bucketName = bucketName, key = key, imageFile = ImageFile( uri = it, contentResolver = context.contentResolver ) ) } else { Log.d("PhotoPicker", "No media selected") } } Scaffold( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colors.background), timeText = { TimeText() }, positionIndicator = { PositionIndicator(scalingLazyListState = state) } ) { ScalingLazyColumn( state = state, ) { item { Button( onClick = { sampleViewModel.generatePresignedUrl(bucketName, key) }, modifier = Modifier.fillMaxWidth() ) { Text(text = "Generate presigned url") } } item { Button( onClick = { sampleViewModel.createBucket(bucketName) }, modifier = Modifier.fillMaxWidth() ) { Text(text = "Create bucket") } } item { Button( onClick = { sampleViewModel.listBuckets() }, modifier = Modifier.fillMaxWidth() ) { Text(text = "List buckets") } } item { Button( onClick = { sampleViewModel.deleteBucket(bucketName) }, modifier = Modifier.fillMaxWidth() ) { Text(text = "Delete bucket") } } item { Button( onClick = { photoPicker.launch( PickVisualMediaRequest( ActivityResultContracts.PickVisualMedia.ImageOnly ) ) }, modifier = Modifier.fillMaxWidth() ) { Text(text = "Put object") } } } } } } @Preview(device = Devices.WEAR_OS_SMALL_ROUND, showSystemUi = true) @Composable fun DefaultPreview() { WearApp() }
2
Kotlin
1
7
72f9a9ccedeed893c2b35e44a6ee6b8ea708e611
5,204
aws-kmp
Apache License 2.0
src/test/kotlin/co/nums/intellij/aem/htl/editor/comments/HtlCommenterTestBase.kt
karollewandowski
74,054,504
false
null
package co.nums.intellij.aem.htl.editor.comments import co.nums.intellij.aem.htl.HtlTestBase abstract class HtlCommenterTestBase : HtlTestBase() { abstract val commentType: String protected fun doCommenterTest(before: String, after: String) = testByText(before, after) { myFixture.performEditorAction(commentType) } }
0
Kotlin
8
26
9e76302b897bddb9ce6721d67787e92be575794f
343
aem-intellij-plugin
MIT License
src/test/kotlin/co/uk/lambda/forensics/validator/EmailValidatorTest.kt
dgundogan
249,957,696
false
null
package co.uk.lambda.forensics.validator import org.junit.Assert import org.junit.Test class EmailValidatorTest{ private val validator = EmailValidator @Test fun `Given missing @ in email, it returns false`() { Assert.assertFalse(validator.isEmailValid("test.com")) } @Test fun `Given missing dot in email, it returns false`() { Assert.assertFalse(validator.isEmailValid("test@domain")) } @Test fun `Given missing @ and dot in email, it returns false`() { Assert.assertFalse(validator.isEmailValid("domain")) } @Test fun `Given a valid email, it returns true`() { Assert.assertTrue(validator.isEmailValid("<EMAIL>")) } }
0
Kotlin
0
0
0ecace1d4ae7d2b33c079fe18dc6e9e943bfa71b
712
forensics-svc
MIT License
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/analytics/amplitude/AmplitudePackage.kt
derekstavis
184,342,737
true
{"Objective-C": 20602533, "Java": 13690880, "C++": 11626391, "Kotlin": 5359352, "TypeScript": 4619500, "Objective-C++": 4368983, "Swift": 1078083, "JavaScript": 1013246, "Starlark": 712574, "Ruby": 519774, "C": 282818, "Makefile": 193716, "Shell": 54009, "Assembly": 46734, "HTML": 36667, "CMake": 26275, "CSS": 1306, "Batchfile": 89}
package abi43_0_0.expo.modules.analytics.amplitude import android.content.Context import abi43_0_0.expo.modules.core.BasePackage import abi43_0_0.expo.modules.core.ExportedModule class AmplitudePackage : BasePackage() { override fun createExportedModules(context: Context): List<ExportedModule> { return listOf(AmplitudeModule(context)) } }
1
Objective-C
1
2
e377f0cd22db5cd7feb8e80348cd7064db5429b1
351
expo
MIT License
app/src/main/java/i/herman/app/TestDispatchers.kt
ihermandev
574,420,150
false
{"Kotlin": 133424}
package i.herman.app import kotlinx.coroutines.Dispatchers class TestDispatchers : CoroutineDispatchers { override val background = Dispatchers.Unconfined }
0
Kotlin
0
0
29c0dde061a15c33a9c4ede6cbd6b779ea6e40ad
163
FriendsComposeCourse
Apache License 2.0
plugins/power-assert/testData/codegen/boolean/BooleanMixWithOrLast.kt
JetBrains
3,432,266
false
null
fun box() = expectThrowableMessage { val text = "Hello" assert((text.length == 5 && text.lowercase() == text) || text.length == 1) }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
141
kotlin
Apache License 2.0
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveUtil.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.refactoring.move import com.intellij.ide.util.DirectoryUtil import com.intellij.openapi.application.runReadAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.psi.* import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.move.moveMembers.MoveMemberHandler import com.intellij.refactoring.move.moveMembers.MoveMembersOptions import com.intellij.refactoring.move.moveMembers.MoveMembersProcessor import com.intellij.refactoring.util.MoveRenameUsageInfo import com.intellij.refactoring.util.NonCodeUsageInfo import com.intellij.usageView.UsageInfo import com.intellij.util.IncorrectOperationException import com.intellij.util.SmartList import com.intellij.util.containers.addIfNotNull import org.jetbrains.kotlin.backend.jvm.ir.psiElement import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.utils.fqname.isImported import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.codeInsight.shorten.isToBeShortened import org.jetbrains.kotlin.idea.core.util.toPsiDirectory import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.statistics.KotlinMoveRefactoringFUSCollector import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.* import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.expressions.DoubleColonLHS import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly import java.io.File import java.util.* private val LOG = Logger.getInstance("#org.jetbrains.kotlin.idea.refactoring.move.MoveUtil") internal var KtFile.allElementsToMove: List<PsiElement>? by UserDataProperty(Key.create("SCOPE_TO_MOVE")) internal var KtSimpleNameExpression.internalUsageInfo: UsageInfo? by CopyablePsiUserDataProperty(Key.create("INTERNAL_USAGE_INFO")) internal var KtFile.updatePackageDirective: Boolean? by UserDataProperty(Key.create("UPDATE_PACKAGE_DIRECTIVE")) internal fun KtElement.getInternalReferencesToUpdateOnPackageNameChange(containerChangeInfo: MoveContainerChangeInfo): List<UsageInfo> { val usages = ArrayList<UsageInfo>() processInternalReferencesToUpdateOnPackageNameChange(this, containerChangeInfo) { expr, factory -> usages.addIfNotNull(factory(expr)) } return usages } internal fun getTargetPackageFqName(targetContainer: PsiElement): FqName? { if (targetContainer is PsiDirectory) { val targetPackage = JavaDirectoryService.getInstance()?.getPackage(targetContainer) return if (targetPackage != null) FqName(targetPackage.qualifiedName) else null } return if (targetContainer is KtFile) targetContainer.packageFqName else null } internal fun markInternalUsages(usages: Collection<UsageInfo>) { usages.forEach { (it.element as? KtSimpleNameExpression)?.internalUsageInfo = it } } internal fun restoreInternalUsages( scope: KtElement, oldToNewElementsMapping: Map<PsiElement, PsiElement>, forcedRestore: Boolean = false ): List<UsageInfo> { return scope.collectDescendantsOfType<KtSimpleNameExpression>().mapNotNull { val usageInfo = it.internalUsageInfo if (!forcedRestore && usageInfo?.element != null) return@mapNotNull usageInfo val referencedElement = (usageInfo as? MoveRenameUsageInfo)?.referencedElement ?: return@mapNotNull null val newReferencedElement = mapToNewOrThis(referencedElement, oldToNewElementsMapping) if (!newReferencedElement.isValid) return@mapNotNull null (usageInfo as? KotlinMoveRenameUsage)?.refresh(it, newReferencedElement) } } internal fun cleanUpInternalUsages(usages: Collection<UsageInfo>) { usages.forEach { (it.element as? KtSimpleNameExpression)?.internalUsageInfo = null } } fun guessNewFileName(declarationsToMove: Collection<KtNamedDeclaration>): String? { if (declarationsToMove.isEmpty()) return null val representative = declarationsToMove.singleOrNull() ?: declarationsToMove.filterIsInstance<KtClassOrObject>().singleOrNull() val newFileName = representative?.run { if (containingKtFile.isScript()) "$name.kts" else "$name.${KotlinFileType.EXTENSION}" } ?: declarationsToMove.first().containingFile.name return newFileName.capitalizeAsciiOnly() } // returns true if successful private fun updateJavaReference(reference: PsiReferenceExpression, oldElement: PsiElement, newElement: PsiElement): Boolean { if (oldElement is PsiMember && newElement is PsiMember) { // Remove import of old package facade, if any val oldClassName = oldElement.containingClass?.qualifiedName if (oldClassName != null) { val importOfOldClass = (reference.containingFile as? PsiJavaFile)?.importList?.allImportStatements?.firstOrNull { when (it) { is PsiImportStatement -> it.qualifiedName == oldClassName is PsiImportStaticStatement -> it.isOnDemand && it.importReference?.canonicalText == oldClassName else -> false } } if (importOfOldClass != null && importOfOldClass.resolve() == null) { importOfOldClass.delete() } } val newClass = newElement.containingClass if (newClass != null && reference.qualifierExpression != null) { val refactoringOptions = object : MoveMembersOptions { override fun getMemberVisibility(): String = PsiModifier.PUBLIC override fun makeEnumConstant(): Boolean = true override fun getSelectedMembers(): Array<PsiMember> = arrayOf(newElement) override fun getTargetClassName(): String? = newClass.qualifiedName } val moveMembersUsageInfo = MoveMembersProcessor.MoveMembersUsageInfo( newElement, reference.element, newClass, reference.qualifierExpression, reference ) val moveMemberHandler = MoveMemberHandler.EP_NAME.forLanguage(reference.element.language) if (moveMemberHandler != null) { moveMemberHandler.changeExternalUsage(refactoringOptions, moveMembersUsageInfo) return true } } } return false } internal fun mapToNewOrThis(e: PsiElement, oldToNewElementsMapping: Map<PsiElement, PsiElement>) = oldToNewElementsMapping[e] ?: e private fun postProcessMoveUsage( usage: UsageInfo, oldToNewElementsMapping: Map<PsiElement, PsiElement>, nonCodeUsages: ArrayList<NonCodeUsageInfo>, shorteningMode: KtSimpleNameReference.ShorteningMode ) { if (usage is NonCodeUsageInfo) { nonCodeUsages.add(usage) return } if (usage !is MoveRenameUsageInfo) return val oldElement = usage.referencedElement!! val newElement = mapToNewOrThis(oldElement, oldToNewElementsMapping) when (usage) { is KotlinMoveRenameUsage.Deferred -> { val newUsage = usage.resolve(newElement) ?: return postProcessMoveUsage(newUsage, oldToNewElementsMapping, nonCodeUsages, shorteningMode) } is KotlinMoveRenameUsage.Unqualifiable -> { val file = with(usage) { if (addImportToOriginalFile) originalFile else mapToNewOrThis( originalFile, oldToNewElementsMapping ) } as KtFile addDelayedImportRequest(newElement, file) } else -> { val reference = (usage.element as? KtSimpleNameExpression)?.mainReference ?: usage.reference processReference(reference, newElement, shorteningMode, oldElement) } } } private fun processReference( reference: PsiReference?, newElement: PsiElement, shorteningMode: KtSimpleNameReference.ShorteningMode, oldElement: PsiElement ) { try { when { reference is KtSimpleNameReference -> reference.bindToElement(newElement, shorteningMode) reference is PsiReferenceExpression && updateJavaReference(reference, oldElement, newElement) -> return else -> reference?.bindToElement(newElement) } } catch (e: IncorrectOperationException) { LOG.warn("bindToElement not implemented for ${reference!!::class.qualifiedName}") } } /** * Perform usage postprocessing and return non-code usages */ internal fun postProcessMoveUsages( usages: Collection<UsageInfo>, oldToNewElementsMapping: Map<PsiElement, PsiElement> = Collections.emptyMap(), shorteningMode: KtSimpleNameReference.ShorteningMode = KtSimpleNameReference.ShorteningMode.DELAYED_SHORTENING ): List<NonCodeUsageInfo> { val sortedUsages = usages.sortedWith( Comparator { o1, o2 -> val file1 = o1.virtualFile val file2 = o2.virtualFile if (Comparing.equal(file1, file2)) { val rangeInElement1 = o1.rangeInElement val rangeInElement2 = o2.rangeInElement if (rangeInElement1 != null && rangeInElement2 != null) { return@Comparator rangeInElement2.startOffset - rangeInElement1.startOffset } return@Comparator 0 } if (file1 == null) return@Comparator -1 if (file2 == null) return@Comparator 1 Comparing.compare(file1.path, file2.path) } ) val nonCodeUsages = ArrayList<NonCodeUsageInfo>() val progressStep = 1.0 / sortedUsages.size val progressIndicator = ProgressManager.getInstance().progressIndicator progressIndicator?.isIndeterminate = false progressIndicator?.text = KotlinBundle.message("text.updating.usages.progress") usageLoop@ for ((i, usage) in sortedUsages.withIndex()) { progressIndicator?.fraction = (i + 1) * progressStep postProcessMoveUsage(usage, oldToNewElementsMapping, nonCodeUsages, shorteningMode) } progressIndicator?.text = "" return nonCodeUsages } internal fun collectOuterInstanceReferences(member: KtNamedDeclaration): List<OuterInstanceReferenceUsageInfo> { val result = SmartList<OuterInstanceReferenceUsageInfo>() traverseOuterInstanceReferences(member, false) { result += it } return result } @Throws(IncorrectOperationException::class) internal fun getOrCreateDirectory(project: Project, path: String): PsiDirectory { File(path).toPsiDirectory(project)?.let { return it } return WriteCommandAction .writeCommandAction(project) .withName(RefactoringBundle.message("move.title")) .compute<PsiDirectory, Exception> { val fixUpSeparators = path.replace(File.separatorChar, '/') DirectoryUtil.mkdirs(PsiManager.getInstance(project), fixUpSeparators) } } internal fun <T> List<KtNamedDeclaration>.mapWithReadActionInProcess( project: Project, @NlsContexts.DialogTitle title: String, body: (KtNamedDeclaration) -> T ): List<T> = let { declarations -> val result = mutableListOf<T>() val task = object : Task.Modal(project, title, false) { override fun run(indicator: ProgressIndicator) { indicator.isIndeterminate = false indicator.fraction = 0.0 val fraction = 1.0 / declarations.size runReadAction { declarations.forEachIndexed { index, declaration -> result.add(body(declaration)) indicator.fraction = fraction * index } } } } ProgressManager.getInstance().run(task) return result } internal fun logFusForMoveRefactoring( numberOfEntities: Int, entity: KotlinMoveRefactoringFUSCollector.MovedEntity, destination: KotlinMoveRefactoringFUSCollector.MoveRefactoringDestination, isDefault: Boolean, body: Runnable ) { val timeStarted = System.currentTimeMillis() var succeeded = false try { body.run() succeeded = true } finally { KotlinMoveRefactoringFUSCollector.log( timeStarted = timeStarted, timeFinished = System.currentTimeMillis(), numberOfEntities = numberOfEntities, destination = destination, isDefault = isDefault, entity = entity, isSucceeded = succeeded, ) } } internal fun isExtensionRef(expr: KtSimpleNameExpression): Boolean { val resolvedCall = expr.getResolvedCall(expr.analyze(BodyResolveMode.PARTIAL)) ?: return false if (resolvedCall is VariableAsFunctionResolvedCall) { return resolvedCall.variableCall.candidateDescriptor.isExtension || resolvedCall.functionCall.candidateDescriptor.isExtension } return resolvedCall.candidateDescriptor.isExtension } internal fun isQualifiable(callableReferenceExpression: KtCallableReferenceExpression): Boolean { val receiverExpression = callableReferenceExpression.receiverExpression val lhs = callableReferenceExpression.analyze(BodyResolveMode.PARTIAL)[BindingContext.DOUBLE_COLON_LHS, receiverExpression] return lhs is DoubleColonLHS.Type } fun traverseOuterInstanceReferences( member: KtNamedDeclaration, stopAtFirst: Boolean ) = traverseOuterInstanceReferences(member, stopAtFirst) { } private fun traverseOuterInstanceReferences( member: KtNamedDeclaration, stopAtFirst: Boolean, body: (OuterInstanceReferenceUsageInfo) -> Unit ): Boolean { if (member is KtObjectDeclaration || member is KtClass && !member.isInner()) return false val context = member.analyzeWithContent() val containingClassOrObject = member.containingClassOrObject ?: return false val outerClassDescriptor = containingClassOrObject.unsafeResolveToDescriptor() as ClassDescriptor var found = false member.accept(object : PsiRecursiveElementWalkingVisitor() { private fun getOuterInstanceReference(element: PsiElement): OuterInstanceReferenceUsageInfo? { return when (element) { is KtThisExpression -> { val descriptor = context[BindingContext.REFERENCE_TARGET, element.instanceReference] val isIndirect = when { descriptor == outerClassDescriptor -> false descriptor?.isAncestorOf(outerClassDescriptor, true) ?: false -> true else -> return null } OuterInstanceReferenceUsageInfo.ExplicitThis(element, isIndirect) } is KtSimpleNameExpression -> { val resolvedCall = element.getResolvedCall(context) ?: return null val dispatchReceiver = resolvedCall.dispatchReceiver as? ImplicitReceiver val extensionReceiver = resolvedCall.extensionReceiver as? ImplicitReceiver var isIndirect = false val isDoubleReceiver = when (outerClassDescriptor) { dispatchReceiver?.declarationDescriptor -> extensionReceiver != null extensionReceiver?.declarationDescriptor -> dispatchReceiver != null else -> { isIndirect = true when { dispatchReceiver?.declarationDescriptor?.isAncestorOf(outerClassDescriptor, true) ?: false -> extensionReceiver != null extensionReceiver?.declarationDescriptor?.isAncestorOf(outerClassDescriptor, true) ?: false -> dispatchReceiver != null else -> return null } } } OuterInstanceReferenceUsageInfo.ImplicitReceiver(resolvedCall.call.callElement, isIndirect, isDoubleReceiver) } else -> null } } override fun visitElement(element: PsiElement) { getOuterInstanceReference(element)?.let { body(it) found = true if (stopAtFirst) stopWalking() return } super.visitElement(element) } }) return found } internal fun addDelayedImportRequest(elementToImport: PsiElement, file: KtFile) { org.jetbrains.kotlin.idea.codeInsight.shorten.addDelayedImportRequest(elementToImport, file) } internal fun addDelayedShorteningRequest(element: KtElement) { element.isToBeShortened = true } internal fun processInternalReferencesToUpdateOnPackageNameChange( element: KtElement, containerChangeInfo: MoveContainerChangeInfo, body: (originalRefExpr: KtSimpleNameExpression, usageFactory: KotlinUsageInfoFactory) -> Unit ) { val file = element.containingFile as? KtFile ?: return val importPaths = file.importDirectives.mapNotNull { it.importPath } tailrec fun isImported(descriptor: DeclarationDescriptor): Boolean { val fqName = DescriptorUtils.getFqName(descriptor).let { if (it.isSafe) it.toSafe() else return@isImported false } if (importPaths.any { fqName.isImported(it, false) }) return true return when (val containingDescriptor = descriptor.containingDeclaration) { is ClassDescriptor, is PackageViewDescriptor -> isImported(containingDescriptor) else -> false } } fun MoveContainerInfo.matches(decl: DeclarationDescriptor) = when(this) { is MoveContainerInfo.UnknownPackage -> decl is PackageViewDescriptor && decl.fqName == fqName is MoveContainerInfo.Package -> decl is PackageFragmentDescriptor && decl.fqName == fqName is MoveContainerInfo.Class -> decl is ClassDescriptor && decl.importableFqName == fqName } fun isCallableReference(reference: PsiReference): Boolean { return reference is KtSimpleNameReference && reference.element.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference } != null } fun processReference(refExpr: KtSimpleNameExpression, bindingContext: BindingContext): KotlinUsageInfoFactory? { val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, refExpr]?.getImportableDescriptor() ?: return null val containingDescriptor = descriptor.containingDeclaration ?: return null val callableKind = (descriptor as? CallableMemberDescriptor)?.kind if (callableKind != null && callableKind != CallableMemberDescriptor.Kind.DECLARATION) return null // Special case for enum entry superclass references (they have empty text and don't need to be processed by the refactoring) if (refExpr.textRange.isEmpty) return null if (descriptor is ClassDescriptor && descriptor.isInner && refExpr.parent is KtCallExpression) return null val isCallable = descriptor is CallableDescriptor val isExtension = isCallable && isExtensionRef(refExpr) val isCallableReference = isCallableReference(refExpr.mainReference) val declaration by lazy { var result = DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, descriptor) ?: return@lazy null if (descriptor.isCompanionObject() && bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, refExpr] !== null ) { result = (result as? KtObjectDeclaration)?.containingClassOrObject ?: result } result } if (isCallable) { if (!isCallableReference) { if (isExtension && containingDescriptor is ClassDescriptor) { val dispatchReceiver = refExpr.getResolvedCall(bindingContext)?.dispatchReceiver val implicitClass = (dispatchReceiver as? ImplicitClassReceiver)?.classDescriptor val psiClass = implicitClass?.psiElement if (psiClass is KtObjectDeclaration && psiClass.isCompanion()) { return { ImplicitCompanionAsDispatchReceiverUsageInfo(it, psiClass) } } if (dispatchReceiver != null || containingDescriptor.kind != ClassKind.OBJECT) return null } } if (!isExtension) { val isCompatibleDescriptor = containingDescriptor is PackageFragmentDescriptor || containingDescriptor is ClassDescriptor && containingDescriptor.kind == ClassKind.OBJECT || descriptor is JavaCallableMemberDescriptor && ((declaration as? PsiMember)?.hasModifierProperty(PsiModifier.STATIC) == true) if (!isCompatibleDescriptor) return null } } if (!DescriptorUtils.getFqName(descriptor).isSafe) return null val (oldContainer, newContainer) = containerChangeInfo val containerFqName = descriptor.parents.mapNotNull { when { oldContainer.matches(it) -> oldContainer.fqName newContainer.matches(it) -> newContainer.fqName else -> null } }.firstOrNull() val isImported = isImported(descriptor) if (isImported && element is KtFile) return null val declarationNotNull = declaration ?: return null if (isExtension || containerFqName != null || isImported) return { KotlinMoveRenameUsage.createIfPossible(it.mainReference, declarationNotNull, addImportToOriginalFile = false, isInternal = true) } return null } @Suppress("DEPRECATION") val bindingContext = element.analyzeWithAllCompilerChecks().bindingContext element.forEachDescendantOfType<KtReferenceExpression> { refExpr -> if (refExpr !is KtSimpleNameExpression || refExpr.parent is KtThisExpression) return@forEachDescendantOfType processReference(refExpr, bindingContext)?.let { body(refExpr, it) } } } internal fun isValidTargetForImplicitCompanionAsDispatchReceiver( moveTarget: KotlinMoveTarget, companionObject: KtObjectDeclaration ): Boolean { return when (moveTarget) { is KotlinMoveTarget.Companion -> true is KotlinMoveTarget.ExistingElement -> { val targetClass = moveTarget.targetElement as? KtClassOrObject ?: return false val targetClassDescriptor = targetClass.unsafeResolveToDescriptor() as ClassDescriptor val companionClassDescriptor = companionObject.descriptor?.containingDeclaration as? ClassDescriptor ?: return false targetClassDescriptor.isSubclassOf(companionClassDescriptor) } else -> false } } internal fun renderType(classOrObject: KtClassOrObject): String { val type = (classOrObject.unsafeResolveToDescriptor() as ClassDescriptor).defaultType return IdeDescriptorRenderers.SOURCE_CODE.renderType(type) }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
24,879
intellij-community
Apache License 2.0
lib_arch_delegate/src/main/java/com/android/base/delegate/activity/ActivityDelegateOwner.kt
Ztiany
499,083,580
false
null
package com.android.base.delegate.activity import androidx.annotation.UiThread @UiThread interface ActivityDelegateOwner { fun addDelegate(activityDelegate: ActivityDelegate<*>) fun removeDelegate(activityDelegate: ActivityDelegate<*>): Boolean fun findDelegate(predicate: (ActivityDelegate<*>) -> Boolean): ActivityDelegate<*>? fun getStatus(): ActivityState }
0
Kotlin
0
0
599c651ee63597358332b096a6fa53749f61b6b3
384
android-arch-delegate
Apache License 2.0
android/app/src/main/java/com/example/android/fido2/repository/AuthRepository.kt
sbweeden
288,578,283
false
null
/* * Copyright 2019 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.fido2.repository import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.util.Log import androidx.annotation.WorkerThread import androidx.core.content.edit import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import com.example.android.fido2.api.ApiException import com.example.android.fido2.api.AuthApi import com.example.android.fido2.api.Credential import com.example.android.fido2.toBase64 import com.google.android.gms.fido.Fido import com.google.android.gms.fido.fido2.Fido2ApiClient import com.google.android.gms.fido.fido2.Fido2PendingIntent import com.google.android.gms.fido.fido2.api.common.AuthenticatorAssertionResponse import com.google.android.gms.fido.fido2.api.common.AuthenticatorAttestationResponse import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.Tasks import java.util.concurrent.Executor import java.util.concurrent.Executors /** * Works with the API, the local data store, and FIDO2 API. */ class AuthRepository( private val api: AuthApi, private val prefs: SharedPreferences, private val executor: Executor ) { companion object { private const val TAG = "AuthRepository" // Keys for SharedPreferences private const val PREFS_NAME = "auth" private const val PREF_USERNAME = "username" private const val PREF_TOKEN = "token" private const val PREF_CREDENTIALS = "credentials" private const val PREF_LOCAL_CREDENTIAL_ID = "local_credential_id" private var instance: AuthRepository? = null fun getInstance(context: Context): AuthRepository { return instance ?: synchronized(this) { instance ?: AuthRepository( AuthApi(), context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE), Executors.newFixedThreadPool(64) ).also { instance = it } } } } private var fido2ApiClient: Fido2ApiClient? = null fun setFido2APiClient(client: Fido2ApiClient?) { fido2ApiClient = client } private val signInStateListeners = mutableListOf<(SignInState) -> Unit>() /** * Stores a temporary challenge that needs to be memorized between request and response API * calls for credential registration and sign-in. */ private var lastKnownChallenge: String? = null private fun invokeSignInStateListeners(state: SignInState) { val listeners = signInStateListeners.toList() // Copy for (listener in listeners) { listener(state) } } /** * Returns the current sign-in state of the user. The UI uses this to navigate between screens. */ fun getSignInState(): LiveData<SignInState> { return object : LiveData<SignInState>() { private val listener = { state: SignInState -> postValue(state) } init { val username = prefs.getString(PREF_USERNAME, null) val token = prefs.getString(PREF_TOKEN, null) value = when { username.isNullOrBlank() -> SignInState.SignedOut token.isNullOrBlank() -> SignInState.SigningIn(username) else -> SignInState.SignedIn(username, token) } } override fun onActive() { signInStateListeners.add(listener) } override fun onInactive() { signInStateListeners.remove(listener) } } } /** * Sends the username to the server. If it succeeds, the sign-in state will proceed to * [SignInState.SigningIn]. */ fun username(username: String, sending: MutableLiveData<Boolean>) { executor.execute { sending.postValue(true) try { val result = api.username(username) prefs.edit(commit = true) { putString(PREF_USERNAME, result) } invokeSignInStateListeners(SignInState.SigningIn(username)) } finally { sending.postValue(false) } } } /** * Signs in with a password. This should be called only when the sign-in state is * [SignInState.SigningIn]. If it succeeds, the sign-in state will proceed to * [SignInState.SignedIn]. * * @param processing The value is set to `true` while the API call is ongoing. */ fun password(password: String, processing: MutableLiveData<Boolean>) { executor.execute { processing.postValue(true) val username = prefs.getString(PREF_USERNAME, null)!! try { val token = api.password(username, password) prefs.edit(commit = true) { putString(PREF_TOKEN, token) } invokeSignInStateListeners(SignInState.SignedIn(username, token)) } catch (e: ApiException) { Log.e(TAG, "Invalid login credentials", e) // start login over again prefs.edit(commit = true) { remove(PREF_USERNAME) remove(PREF_TOKEN) remove(PREF_CREDENTIALS) } invokeSignInStateListeners( SignInState.SignInError(e.message ?: "Invalid login credentials" )) } finally { processing.postValue(false) } } } /** * Retrieves the list of credential this user has registered on the server. This should be * called only when the sign-in state is [SignInState.SignedIn]. */ fun getCredentials(): LiveData<List<Credential>> { executor.execute { refreshCredentials() } return Transformations.map(prefs.liveStringSet(PREF_CREDENTIALS, emptySet())) { set -> parseCredentials(set) } } @WorkerThread private fun refreshCredentials() { val token = prefs.getString(PREF_TOKEN, null)!! prefs.edit(commit = true) { putStringSet(PREF_CREDENTIALS, api.getKeys(token).toStringSet()) } } private fun List<Credential>.toStringSet(): Set<String> { return mapIndexed { index, credential -> "$index;${credential.id};${credential.publicKey}" }.toSet() } private fun parseCredentials(set: Set<String>): List<Credential> { return set.map { s -> val (index, id, publicKey) = s.split(";") index to Credential(id, publicKey) }.sortedBy { (index, _) -> index } .map { (_, credential) -> credential } } /** * Clears the sign-in token. The sign-in state will proceed to [SignInState.SigningIn]. */ fun clearToken() { executor.execute { val username = prefs.getString(PREF_USERNAME, null)!! prefs.edit(commit = true) { remove(PREF_TOKEN) remove(PREF_CREDENTIALS) } invokeSignInStateListeners(SignInState.SigningIn(username)) } } /** * Clears all the sign-in information. The sign-in state will proceed to * [SignInState.SignedOut]. */ fun signOut() { executor.execute { prefs.edit(commit = true) { remove(PREF_USERNAME) remove(PREF_TOKEN) remove(PREF_CREDENTIALS) } invokeSignInStateListeners(SignInState.SignedOut) } } /** * Starts to register a new credential to the server. This should be called only when the * sign-in state is [SignInState.SignedIn]. */ fun registerRequest(processing: MutableLiveData<Boolean>): LiveData<Fido2PendingIntent> { val result = MutableLiveData<Fido2PendingIntent>() executor.execute { fido2ApiClient?.let { client -> processing.postValue(true) try { val token = prefs.getString(PREF_TOKEN, null)!! // TODO(1): Call the server API: /registerRequest val (options, challenge) = api.registerRequest(token) // - Use api.registerRequest to get a PublicKeyCredentialCreationOptions. lastKnownChallenge = challenge // - Save the challenge for later use in registerResponse. val task: Task<Fido2PendingIntent> = client.getRegisterIntent(options) // - Call fido2ApiClient.getRegisterIntent and create an intent to generate a // new credential. result.postValue(Tasks.await(task)) // - Pass the intent back to the `result` LiveData so that the UI can open the // fingerprint dialog. } catch (e: Exception) { Log.e(TAG, "Cannot call registerRequest", e) } finally { processing.postValue(false) } } } return result } /** * Finishes registering a new credential to the server. This should only be called after * a call to [registerRequest] and a local FIDO2 API for public key generation. */ fun registerResponse(data: Intent, processing: MutableLiveData<Boolean>) { executor.execute { processing.postValue(true) try { val token = prefs.getString(PREF_TOKEN, null)!! val challenge = lastKnownChallenge!! // TODO(3): Call the server API: /registerResponse val response = AuthenticatorAttestationResponse.deserializeFromBytes( data.getByteArrayExtra(Fido.FIDO2_KEY_RESPONSE_EXTRA) ) // - Create an AuthenticatorAttestationResponse from the data intent generated by // the fingerprint dialog. val credentialId = response.keyHandle.toBase64() // - Also save the newly added credential ID into the SharedPreferences. The key is // PREF_LOCAL_CREDENTIAL_ID. The ID can be obtained from the `keyHandle` field of // the AuthenticatorAttestationResponse object. val credentials = api.registerResponse(token, challenge, response) // - Use api.registerResponse to send the response back to the server. prefs.edit { putStringSet(PREF_CREDENTIALS,credentials.toStringSet()) putString(PREF_LOCAL_CREDENTIAL_ID, credentialId) } // - Save the returned list of credentials into the SharedPreferences. The key is // PREF_CREDENTIALS. } catch (e: ApiException) { Log.e(TAG, "Cannot call registerResponse", e) } finally { processing.postValue(false) } } } /** * Removes a credential registered on the server. */ fun removeKey(credentialId: String, processing: MutableLiveData<Boolean>) { executor.execute { processing.postValue(true) try { val token = prefs.getString(PREF_TOKEN, null)!! api.removeKey(token, credentialId) refreshCredentials() } catch (e: ApiException) { Log.e(TAG, "Cannot call removeKey", e) } finally { processing.postValue(false) } } } /** * Starts to sign in with a FIDO2 credential. This should only be called when the sign-in state * is [SignInState.SigningIn]. */ fun signinRequest(processing: MutableLiveData<Boolean>): LiveData<Fido2PendingIntent> { val result = MutableLiveData<Fido2PendingIntent>() executor.execute { fido2ApiClient?.let { client -> processing.postValue(true) try { val username = prefs.getString(PREF_USERNAME, null)!! val credentialId = prefs.getString(PREF_LOCAL_CREDENTIAL_ID, null) // Retrieve sign-in options from the server. val (options, challenge) = api.signinRequest(username, credentialId) // Save the challenge string. lastKnownChallenge = challenge // Create an Intent to open the fingerprint dialog. val task = client.getSignIntent(options) // Pass the Intent back to the UI. result.postValue(Tasks.await(task)) // TODO(4): Call the server API: /signinRequest // - Use api.signinRequest to get a PublicKeyCredentialRequestOptions. // - Save the challenge for later use in signinResponse. // - Call fido2ApiClient.getSignIntent and create an intent to assert the // credential. // - Pass the intent to the `result` LiveData so that the UI can open the // fingerprint dialog. } finally { processing.postValue(false) } } } return result } /** * Finishes to signing in with a FIDO2 credential. This should only be called after a call to * [signinRequest] and a local FIDO2 API for key assertion. */ fun signinResponse(data: Intent, processing: MutableLiveData<Boolean>) { executor.execute { processing.postValue(true) try { val username = prefs.getString(PREF_USERNAME, null)!! val challenge = lastKnownChallenge!! // Extract the AuthenticatorAssertionResponse. val response = AuthenticatorAssertionResponse.deserializeFromBytes( data.getByteArrayExtra(Fido.FIDO2_KEY_RESPONSE_EXTRA) ) // Save the credential ID. val credentialId = response.keyHandle.toBase64() // Send the information to the server val (credentials, token) = api.signinResponse(username, challenge, response) // Store the results. prefs.edit(commit = true) { putString(PREF_TOKEN, token) putStringSet(PREF_CREDENTIALS, credentials.toStringSet()) putString(PREF_LOCAL_CREDENTIAL_ID, credentialId) } // Let the UI know that the sign-in succeeded. invokeSignInStateListeners(SignInState.SignedIn(username, token)) // TODO(6): Call the server API: /signinResponse // - Create an AuthenticatorAssertionResponse from the data intent generated by // the fingerprint dialog. // - Use api.signinResponse to send the response back to the server. // - Save the returned list of credentials into the SharedPreferences. The key is // PREF_CREDENTIALS. // - Save the returned sign-in token into the SharedPreferences. The key is // PREF_TOKEN. // - Also save the credential ID into the SharedPreferences. The key is // PREF_LOCAL_CREDENTIAL_ID. The ID can be obtained from the `keyHandle` field of // the AuthenticatorAssertionResponse object. // - Notify the UI that the sign-in has succeeded. This can be done by calling // `invokeSignInStateListeners(SignInState.SignedIn(username, token))` } catch (e: ApiException) { Log.e(TAG, "Cannot call registerResponse", e) } finally { processing.postValue(false) } } } }
0
Kotlin
1
0
dd9fd7a7297fd1b720a38eab6098e260607b9b9b
16,728
fido2-custom-local
Apache License 2.0
test-app/src/main/kotlin/uk/gov/justice/digital/hmpps/hmppstemplatepackagename/service/OutboundEventsEmitter.kt
ministryofjustice
370,951,976
false
{"Kotlin": 276764, "Shell": 3898}
package uk.gov.justice.digital.hmpps.hmppstemplatepackagename.service import com.fasterxml.jackson.databind.ObjectMapper import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import software.amazon.awssdk.services.sns.model.PublishRequest import uk.gov.justice.hmpps.sqs.HmppsQueueService import uk.gov.justice.hmpps.sqs.MissingTopicException import uk.gov.justice.hmpps.sqs.eventTypeMessageAttributes @Service class OutboundEventsEmitter(hmppsQueueService: HmppsQueueService, private val objectMapper: ObjectMapper) { companion object { val log: Logger = LoggerFactory.getLogger(this::class.java) } private val outboundTopic = hmppsQueueService.findByTopicId("outboundtopic") ?: throw MissingTopicException("Could not find topic outboundtopic") suspend fun sendEvent(hmppsEvent: HmppsEvent) { when (hmppsEvent.type) { "offender.movement.reception", "offender.audit.object", "offender.audit.parameter", "test.type", -> publishToOutboundTopic(hmppsEvent) else -> log.info("Ignoring event of type ${hmppsEvent.type}") } } private suspend fun publishToOutboundTopic(hmppsEvent: HmppsEvent) { outboundTopic.snsClient.publish( PublishRequest.builder() .topicArn(outboundTopic.arn) .message(objectMapper.writeValueAsString(hmppsEvent)) .eventTypeMessageAttributes(hmppsEvent.type) .build() .also { log.info("Published event $hmppsEvent to outbound topic") }, ) } }
0
Kotlin
0
2
194e37c8185490455c3f80ecfa978cf10c02e33d
1,509
hmpps-spring-boot-sqs
MIT License
feature-notes-ui/src/main/kotlin/dev/bogdanzurac/marp/feature/notes/ui/callbacks.kt
bogdanzurac
637,440,236
false
null
package dev.bogdanzurac.marp.feature.notes.ui import dev.bogdanzurac.marp.core.navigation.AppRoute interface NotesCallbacks { fun getLoginRoute(): AppRoute fun shouldShowAllNotes(): Boolean }
0
Kotlin
0
0
e19a1494fbb0abadac81833a1fec108e613f04d4
203
marp-feature-notes
Apache License 2.0
ui/src/main/java/com/pyamsoft/pydroid/ui/preference/CheckBoxPreferenceCompat.kt
pyamsoft
48,562,480
false
null
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** Allows Preferences to use VectorDrawables as icons on API < 21 */ package com.pyamsoft.pydroid.ui.preference import android.content.Context import android.util.AttributeSet import androidx.preference.CheckBoxPreference import androidx.preference.R /** CheckBoxPreference that uses vector drawables */ @Deprecated("Migrate to Jetpack Compose") public open class CheckBoxPreferenceCompat : CheckBoxPreference { /** Construct */ public constructor(context: Context) : this(context, null) /** Construct */ public constructor( context: Context, attrs: AttributeSet? ) : this( context, attrs, context.getStyledAttr(R.attr.checkBoxPreferenceStyle, android.R.attr.checkBoxPreferenceStyle)) /** Construct */ public constructor( context: Context, attrs: AttributeSet?, defStyleAttr: Int ) : this(context, attrs, defStyleAttr, 0) /** Construct */ public constructor( context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int ) : super(context, attrs, defStyleAttr, defStyleRes) { loadIconCompat(attrs) } }
0
Kotlin
3
6
969fa1c129149f7f2bba06b3d072f3368faa8ba7
1,714
pydroid
Apache License 2.0
spring-cloud-gcp-samples/spring-cloud-gcp-kotlin-samples/spring-cloud-gcp-kotlin-app-sample/src/test/kotlin/com/example/RegistrationKotlinSampleApplicationIntegrationTests.kt
GoogleCloudPlatform
257,984,305
false
{"Java": 11197895, "Shell": 46092, "HTML": 42267, "Kotlin": 11028, "Starlark": 5121, "Python": 3197, "CSS": 1504, "FreeMarker": 305}
/* * Copyright 2017-2018 the original author or 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 com.example import com.example.app.Application import com.example.data.Person import org.assertj.core.api.Assertions.assertThat import org.awaitility.Awaitility.await import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfSystemProperty import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post import java.util.concurrent.TimeUnit /** * Tests to verify the Kotlin sample app. * * @since 1.1 */ @ExtendWith(SpringExtension::class) @EnabledIfSystemProperty(named = "it.kotlin", matches = "true") @AutoConfigureMockMvc @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = [Application::class], properties = [ "spring.datasource.password=<PASSWORD>", "spring.cloud.gcp.sql.instance-connection-name=spring-cloud-gcp-ci:us-central1:testmysql", "spring.cloud.gcp.sql.database-name=code_samples_test_db", "spring.test.mockmvc.print=none" ] ) class RegistrationKotlinSampleApplicationIntegrationTests { private val REGISTER_USER_URL = "/registerPerson?firstName=Bob&lastName=Blob&email=<EMAIL>" private val REGISTRANTS_URL = "/registrants" @Autowired private lateinit var mockMvc: MockMvc @Test fun testRegisterPersonSuccessful() { this.mockMvc.perform(post(REGISTER_USER_URL)) await().atMost(60, TimeUnit.SECONDS).untilAsserted { val mvcResult = this.mockMvc .perform(get(REGISTRANTS_URL)) .andReturn() val resultParams = mvcResult.modelAndView?.modelMap val personsList = resultParams?.get("personsList") as List<Person> assertThat(personsList).hasSize(1) val person = personsList[0] assertThat(person.firstName).isEqualTo("Bob") assertThat(person.lastName).isEqualTo("Blob") assertThat(person.email).isEqualTo("<EMAIL>") } } }
98
Java
312
419
333c844f9ffcf621a4617875a16a63ff99ff3662
2,874
spring-cloud-gcp
Apache License 2.0
src/rider/main/kotlin/me/fornever/avaloniarider/idea/settings/AvaloniaSettingsComponent.kt
ForNeVeR
154,947,241
false
null
package me.fornever.avaloniarider.idea.settings import com.intellij.openapi.ui.ComboBox import com.intellij.ui.components.CheckBox import com.intellij.ui.components.JBLabel import me.fornever.avaloniarider.AvaloniaRiderBundle import java.awt.GridBagConstraints import java.awt.GridBagLayout import javax.swing.JPanel class AvaloniaSettingsComponent(state: AvaloniaSettingsState) : JPanel() { private val initialState = AvaloniaSettingsState().apply { copyFrom(state) } private val previewerTransportTypeSelector = ComboBox(AvaloniaPreviewerMethod.values()) private var previewerMethod: AvaloniaPreviewerMethod get() = previewerTransportTypeSelector.selectedItem as AvaloniaPreviewerMethod set(value) { previewerTransportTypeSelector.selectedItem = value } private val synchronizeWithRunConfigurationEditor = CheckBox(AvaloniaRiderBundle.message("settings.synchronizeWithRunConfiguration")) private var synchronizeWithRunConfiguration: Boolean get() = synchronizeWithRunConfigurationEditor.isSelected set(value) { synchronizeWithRunConfigurationEditor.isSelected = value } init { previewerMethod = initialState.previewerMethod synchronizeWithRunConfiguration = initialState.synchronizeWithRunConfiguration layout = GridBagLayout() add(JBLabel("Previewer Method:"), GridBagConstraints().apply { anchor = GridBagConstraints.LINE_START }) add(previewerTransportTypeSelector, GridBagConstraints().apply { gridx = 1 }) add(synchronizeWithRunConfigurationEditor, GridBagConstraints().apply { gridy = 1; gridwidth = 2 }) } var currentState: AvaloniaSettingsState get() = AvaloniaSettingsState().apply { previewerMethod = [email protected] synchronizeWithRunConfiguration = [email protected] } set(value) { previewerMethod = value.previewerMethod synchronizeWithRunConfiguration = value.synchronizeWithRunConfiguration } val isModified: Boolean get() = currentState != initialState }
33
Kotlin
9
202
71833ec9a92091ec22aac4258e2f6874bea44196
2,214
AvaloniaRider
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/appsync/PipelineConfigPropertyDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.appsync import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.appsync.CfnResolver @Generated public fun buildPipelineConfigProperty(initializer: @AwsCdkDsl CfnResolver.PipelineConfigProperty.Builder.() -> Unit): CfnResolver.PipelineConfigProperty = CfnResolver.PipelineConfigProperty.Builder().apply(initializer).build()
1
Kotlin
0
0
a1cf8fbfdfef9550b3936de2f864543edb76348b
457
aws-cdk-kt
Apache License 2.0
domain/src/main/kotlin/no/nav/su/se/bakover/domain/klage/KlageinstanshendelseRepo.kt
navikt
227,366,088
false
{"Kotlin": 10119313, "Shell": 4388, "TSQL": 1233, "Dockerfile": 1209}
package no.nav.su.se.bakover.domain.klage import behandling.klage.domain.UprosessertKlageinstanshendelse import no.nav.su.se.bakover.common.persistence.TransactionContext import java.util.UUID interface KlageinstanshendelseRepo { fun lagre(hendelse: UprosessertKlageinstanshendelse) fun lagre(hendelse: ProsessertKlageinstanshendelse, transactionContext: TransactionContext = defaultTransactionContext()) fun hentUbehandlaKlageinstanshendelser(): List<UprosessertKlageinstanshendelse> fun markerSomFeil(id: UUID) fun defaultTransactionContext(): TransactionContext }
5
Kotlin
1
1
738dc3bc4685d2968a7c217daf4159cfec80fadd
589
su-se-bakover
MIT License
app/src/main/java/shetj/me/base/test/TestProxy.kt
SheTieJun
137,007,462
false
null
package shetj.me.base.test import me.shetj.base.ktx.toJson import java.lang.reflect.GenericArrayType import java.lang.reflect.InvocationHandler import java.lang.reflect.Method import java.lang.reflect.ParameterizedType import java.lang.reflect.Proxy import java.lang.reflect.Type import java.lang.reflect.TypeVariable import java.lang.reflect.WildcardType import java.util.* class TestProxy<T> : InvocationHandler { private var target: T? = // 维护一个目标对象 null constructor(target: T?) { this.target = target } override fun invoke(proxy: Any, method: Method?, args: Array<out Any>?): Any? { println( "测试:${method?.name.toJson()}\n" + "genericReturnType:${method?.genericReturnType}\n" + "parameterAnnotations:${method?.parameterAnnotations?.size}\n" + "annotations:${method?.annotations?.size}\n" + "parameterTypes:${method?.parameterTypes?.size}\n" + "genericParameterTypes:${method?.genericParameterTypes?.size}\n" ) method?.parameterAnnotations?.forEach { } method?.parameterTypes?.forEach { println(getRawType(it)?.simpleName) } method?.genericParameterTypes?.forEach { println(getRawType(it)?.simpleName) } target.let { method!!.invoke(target, *(args ?: arrayOfNulls<Any>(0))) } return null } fun getRawType(type: Type): Class<*>? { Objects.requireNonNull(type, "type == null") if (type is Class<*>) { // Type is a normal class. return type } if (type is ParameterizedType) { // I'm not exactly sure why getRawType() returns Type instead of Class. Neal isn't either but // suspects some pathological case related to nested classes exists. val rawType = type.rawType require(rawType is Class<*>) return rawType } if (type is GenericArrayType) { val componentType = type.genericComponentType return getRawType(componentType)?.let { java.lang.reflect.Array.newInstance(it, 0).javaClass } } if (type is TypeVariable<*>) { // We could use the variable's bounds, but that won't work if there are multiple. Having a raw // type that's more general than necessary is okay. return Any::class.java } if (type is WildcardType) { return getRawType(type.upperBounds[0]) } throw IllegalArgumentException( "Expected a Class, ParameterizedType, or " + "GenericArrayType, but <" + type + "> is of type " + type.javaClass.name ) } } /** * 必须是接口 */ class ProxyFactory { companion object { // 动态代理本质是静态代理是一样的,本质还是会有具体类进行实现 inline fun <reified T> getProxy(tag: T?): T { var clazz = T::class.java val proxy = TestProxy(tag) return Proxy.newProxyInstance(clazz.classLoader, arrayOf(clazz), proxy) as T } } }
1
null
1
7
4d631d482fd5b3cf21188b084b771abfdb3b9704
3,165
BaseKit
MIT License
isolated-test/src/jsMain/kotlin/com/test/example/NodeFilter.kt
turansky
279,976,108
false
null
package com.test.example external enum class NodeFilter { FILTER_ACCEPT, ; }
0
Kotlin
3
32
353041c279af4e094cdadc020f9f90354740276e
87
seskar
Apache License 2.0
app/src/main/java/com/example/calculosfinanceiros/MainActivity.kt
gabriel-lima-2001
322,906,617
false
null
package com.example.calculosfinanceiros import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.* import org.jetbrains.anko.startActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val btnTesouro = findViewById<Button>(R.id.btnTesouro) val btnPoupanca = findViewById<Button>(R.id.btnPoupanca) btnTesouro.setOnClickListener { startActivity<TesouroActivity>() } btnPoupanca.setOnClickListener { startActivity<PoupancaActivity>() } } }
0
Kotlin
0
0
12e76d9caf0d6405e0b49df153c527400f9052bb
704
Calculo-De-Investimentos-Kotlin
MIT License
PhoenixPenNG/libgame/src/main/java/com/phoenixpen/game/data/Structure.kt
nshcat
182,317,693
false
null
package com.phoenixpen.game.data import com.phoenixpen.game.graphics.DrawInfo import com.phoenixpen.game.ascii.Position3D /** * A class representing a base class for all structure types. * A structure is basically a static entity that is unable to move. * * @property baseType Basic structure type information, like interaction with the pathing system. * @property position The position of this structure in the game world. This is fixed. */ abstract class Structure(val baseType: StructureType, val position: Position3D) { /** * Retrieve information on how to draw this structure. This is implemented in structure * sub classes, for example a plant will change its appearance over the seasons. * * @param fancyMode Whether we currently are in fancy graphics mode. * @return [DrawInfo] describing how to draw this structure. */ abstract fun tile(fancyMode: Boolean = true): DrawInfo /** * Check whether this tile should currently be drawn. This is dynamic, since this could depend on * seasonal tiles. * * @return Flag indicating whether this structure should currently be rendered */ abstract fun shouldDraw(): Boolean }
0
Kotlin
0
1
8e29e78b8f3d1ff7bdfedfd7c872b1ac69dd665d
1,201
phoenixpen_ng
MIT License
app/src/main/java/com/dhl/uploadimage_Assignment/loginActivity.kt
santriptmehta
482,034,041
false
null
package com.dhl.uploadimage_Assignment import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.TextUtils import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import com.google.firebase.auth.FirebaseAuth class loginActivity : AppCompatActivity() { lateinit var tv_register : TextView lateinit var btn_login : Button lateinit var et_login_password : EditText lateinit var et_login_email : EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) tv_register = findViewById(R.id.tv_register) btn_login = findViewById(R.id.btn_login) et_login_password = findViewById(R.id.et_login_password) et_login_email = findViewById(R.id.et_login_email) tv_register.setOnClickListener { startActivity(Intent(this@loginActivity, registerActivity::class.java)) } btn_login.setOnClickListener { when { TextUtils.isEmpty(et_login_email.text.toString().trim { it <= ' ' }) -> { Toast.makeText( this@loginActivity, "Please enter email.", Toast.LENGTH_SHORT ).show() } TextUtils.isEmpty(et_login_password.text.toString().trim { it <= ' ' }) -> { Toast.makeText( this@loginActivity, "Please enter password.", Toast.LENGTH_SHORT ).show() } else -> { val email: String = et_login_email.text.toString().trim { it <= ' ' } val password: String = et_login_password.text.toString().trim { it <= ' ' } // Log-In using FirebaseAuth FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password) .addOnCompleteListener { task -> if (task.isSuccessful) { Toast.makeText( this@loginActivity, "You are logged in successfully.", Toast.LENGTH_SHORT ).show() val intent = Intent(this@loginActivity, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK intent.putExtra( "user_id", FirebaseAuth.getInstance().currentUser!!.uid ) intent.putExtra("email_id", email) startActivity(intent) finish() } else { Toast.makeText( this@loginActivity, task.exception!!.message.toString(), Toast.LENGTH_SHORT ).show() } } } } } } }
0
Kotlin
0
0
29b528ea2eb1e65dcf5735086e44ecd940ab877f
3,548
UploadImage
Apache License 2.0
app/src/main/java/com/dhl/uploadimage_Assignment/loginActivity.kt
santriptmehta
482,034,041
false
null
package com.dhl.uploadimage_Assignment import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.TextUtils import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import com.google.firebase.auth.FirebaseAuth class loginActivity : AppCompatActivity() { lateinit var tv_register : TextView lateinit var btn_login : Button lateinit var et_login_password : EditText lateinit var et_login_email : EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) tv_register = findViewById(R.id.tv_register) btn_login = findViewById(R.id.btn_login) et_login_password = findViewById(R.id.et_login_password) et_login_email = findViewById(R.id.et_login_email) tv_register.setOnClickListener { startActivity(Intent(this@loginActivity, registerActivity::class.java)) } btn_login.setOnClickListener { when { TextUtils.isEmpty(et_login_email.text.toString().trim { it <= ' ' }) -> { Toast.makeText( this@loginActivity, "Please enter email.", Toast.LENGTH_SHORT ).show() } TextUtils.isEmpty(et_login_password.text.toString().trim { it <= ' ' }) -> { Toast.makeText( this@loginActivity, "Please enter password.", Toast.LENGTH_SHORT ).show() } else -> { val email: String = et_login_email.text.toString().trim { it <= ' ' } val password: String = et_login_password.text.toString().trim { it <= ' ' } // Log-In using FirebaseAuth FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password) .addOnCompleteListener { task -> if (task.isSuccessful) { Toast.makeText( this@loginActivity, "You are logged in successfully.", Toast.LENGTH_SHORT ).show() val intent = Intent(this@loginActivity, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK intent.putExtra( "user_id", FirebaseAuth.getInstance().currentUser!!.uid ) intent.putExtra("email_id", email) startActivity(intent) finish() } else { Toast.makeText( this@loginActivity, task.exception!!.message.toString(), Toast.LENGTH_SHORT ).show() } } } } } } }
0
Kotlin
0
0
29b528ea2eb1e65dcf5735086e44ecd940ab877f
3,548
UploadImage
Apache License 2.0
app/src/test/java/com/example/android/architecture/blueprints/todoapp/data/source/DefaultTasksRepositoryTest.kt
Mansourx
393,979,445
false
null
package com.example.android.architecture.blueprints.todoapp.data.source import com.example.android.architecture.blueprints.todoapp.MainCoroutineRule import com.example.android.architecture.blueprints.todoapp.data.Result import com.example.android.architecture.blueprints.todoapp.data.Task import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runBlockingTest import org.hamcrest.core.IsEqual import org.junit.Assert.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test /** * Created by <NAME> on 29/08/2021 * NAMSHI General Trading, * Dubai, UAE. */ @ExperimentalCoroutinesApi class DefaultTasksRepositoryTest { private val task1 = Task("Title1", "Description1") private val task2 = Task("Title2", "Description2") private val task3 = Task("Title3", "Description3") private val remoteTasks = listOf(task1, task2).sortedBy { it.id } private val localTasks = listOf(task3).sortedBy { it.id } private val newTasks = listOf(task3).sortedBy { it.id } private lateinit var tasksRemoteDataSource: FakeDataSource private lateinit var tasksLocalDataSource: FakeDataSource // class under test private lateinit var tasksRepository: DefaultTasksRepository @get:Rule var mainCoroutineRule = MainCoroutineRule() @Before fun createRepository() { tasksRemoteDataSource = FakeDataSource(remoteTasks.toMutableList()) tasksLocalDataSource = FakeDataSource(localTasks.toMutableList()) tasksRepository = DefaultTasksRepository( tasksRemoteDataSource, tasksLocalDataSource, Dispatchers.Main // because of the MainCoroutineRule its Test CoroutineDispatcher ) } // We use runBlockingTest function when we call suspend function. to run the code Synchronously // and making the code to run as non-coroutine for testing purpose. // runBlockingTest from this Experimental Library //'testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion"' @ExperimentalCoroutinesApi @Test fun getTasks_RequestAllTasksFromRemoteDataSource() = mainCoroutineRule.runBlockingTest { // When Tasks requested from the datasource val tasks = tasksRepository.getTasks(true) as Result.Success // Then tasks are loaded from remote datasource. assertThat(tasks.data, IsEqual(remoteTasks)) } }
0
Kotlin
0
1
d41bc1ab22dde41a1d7ab57df857e17109ff502b
2,454
android-testing
Apache License 2.0
base-android/src/main/java/com/sfaxdroid/base/Ads.kt
yassinBaccour
106,160,036
false
{"Kotlin": 348508, "Java": 3869}
package com.sfaxdroid.base import android.app.Activity import android.content.Context interface Ads { fun showInterstitial(activity: Activity) fun loadInterstitial(context: Context) }
0
Kotlin
0
2
136ac811fb1495a8ea2800480954121bf092742b
194
SfaxDroid_Wallpaper_App
Apache License 2.0
mobile/src/main/java/com/google/samples/apps/iosched/ui/agenda/AgendaFragment.kt
vcaen
224,569,738
true
{"Kotlin": 1036024, "Java": 63494, "HTML": 24092, "Shell": 5252}
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.google.samples.apps.adssched.ui.agenda import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.BindingAdapter import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.RecyclerView import com.google.samples.apps.adssched.databinding.FragmentAgendaBinding import com.google.samples.apps.adssched.model.Block import com.google.samples.apps.adssched.shared.util.activityViewModelProvider import com.google.samples.apps.adssched.ui.MainNavigationFragment import com.google.samples.apps.adssched.util.clearDecorations import dagger.android.support.DaggerFragment import org.threeten.bp.ZoneId import javax.inject.Inject class AgendaFragment : DaggerFragment(), MainNavigationFragment { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: AgendaViewModel private lateinit var binding: FragmentAgendaBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentAgendaBinding.inflate(inflater, container, false).apply { setLifecycleOwner(this@AgendaFragment) } return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = activityViewModelProvider(viewModelFactory) binding.viewModel = viewModel } override fun onStart() { super.onStart() viewModel.initializeTimeZone() } } @BindingAdapter(value = ["agendaItems", "timeZoneId"]) fun agendaItems(recyclerView: RecyclerView, list: List<Block>?, timeZoneId: ZoneId?) { if (recyclerView.adapter == null) { recyclerView.adapter = AgendaAdapter() } (recyclerView.adapter as AgendaAdapter).apply { this.submitList(list ?: emptyList()) this.timeZoneId = timeZoneId ?: ZoneId.systemDefault() } // Recreate the decoration used for the sticky date headers recyclerView.clearDecorations() if (list != null && list.isNotEmpty()) { recyclerView.addItemDecoration( AgendaHeadersDecoration(recyclerView.context, list) ) } }
0
Kotlin
0
0
d253954a4464b134a9069bc4ca8c97ece69b9f53
2,907
iosched
Apache License 2.0
domain/src/main/kotlin/dvachmovie/usecase/moviestorage/GetMovieListUseCase.kt
sasfmlzr
151,072,454
false
{"Kotlin": 428680}
package dvachmovie.usecase.moviestorage import dvachmovie.db.data.Movie import dvachmovie.storage.MovieStorage import dvachmovie.usecase.base.UseCase import javax.inject.Inject open class GetMovieListUseCase @Inject constructor( private val movieStorage: MovieStorage) : UseCase<Unit, List<Movie>>() { override fun execute(input: Unit): List<Movie> = movieStorage.movieList }
0
Kotlin
2
3
0607e9c90ae503552ff6e9500f659170a0cd97fc
403
DvachMovie
Apache License 2.0
idea/testData/refactoring/changeSignature/SAMAddToNonEmptyParamListAfter.1.kt
JakeWharton
99,388,807
true
null
fun test() { JTest.samTest(SAM { s, n, o -> s + " " + n }) }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
64
kotlin
Apache License 2.0
recorder-view/src/main/java/com/tougee/recorderview/AudioRecordView.kt
Tougee
133,962,690
false
null
package com.tougee.recorderview import android.Manifest import android.animation.ObjectAnimator import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.pm.PackageManager import android.util.AttributeSet import android.view.LayoutInflater import android.view.MotionEvent.* import android.view.View import android.view.View.OnTouchListener import android.view.animation.AccelerateInterpolator import android.view.animation.DecelerateInterpolator import android.widget.FrameLayout import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import com.tougee.recorderview.databinding.ViewAudioRecordBinding import com.tougee.recorderview.databinding.ViewSlidePanelBinding @Suppress("MemberVisibilityCanBePrivate") class AudioRecordView : FrameLayout { companion object { const val RECORD_DELAY = 200L const val RECORD_TIP_MILLIS = 2000L const val ANIMATION_DURATION = 250L } lateinit var callback: Callback lateinit var activity: Activity lateinit var binding: ViewAudioRecordBinding lateinit var _binding: ViewSlidePanelBinding private var isRecording = false private var upBeforeGrant = false @DrawableRes var micIcon: Int = R.drawable.ic_record_mic_black set(value) { if (value == field) return field = value binding.recordIb.setImageResource(value) } @DrawableRes var micActiveIcon: Int = R.drawable.ic_record_mic_white set(value) { if (value == field) return field = value binding.recordCircle.audioDrawable = ResourcesCompat.getDrawable(resources, value, null)!! } var micHintEnable: Boolean = true @ColorInt var micHintColor: Int = ContextCompat.getColor(context, android.R.color.white) set(value) { if (value == field) return field = value binding.recordTipTv.setTextColor(value) } var micHintText: String = context.getString(R.string.hold_to_record_audio) set(value) { if (value == field) return field = value binding.recordTipTv.text = micHintText } @DrawableRes var micHintBg: Int = R.drawable.bg_record_tip set(value) { if (value == field) return field = value binding.recordTipTv.setBackgroundResource(value) } @ColorInt var circleColor: Int = ContextCompat.getColor(context, R.color.color_blue) set(value) { if (value == field) return field = value binding.recordCircle.circlePaint.color = value } @ColorInt var cancelIconColor: Int = ContextCompat.getColor(context, R.color.color_blink) set(value) { if (value == field) return field = value binding.recordCircle.cancelIconPaint.color = value } @ColorInt var blinkColor: Int = ContextCompat.getColor(context, R.color.color_blink) set(value) { if (value == field) return field = value binding.slidePanel.updateBlinkDrawable(value) } var slideCancelText: String = context.getString(R.string.slide_to_cancel) set(value) { if (value == field) return field = value _binding.slideCancelTv.text = value } var cancelText: String = context.getString(R.string.cancel) set(value) { if (value == field) return field = value _binding.cancelTv.text = value } var vibrationEnable: Boolean = true constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { binding = ViewAudioRecordBinding.inflate(LayoutInflater.from(context), this) _binding = ViewSlidePanelBinding.bind(binding.root) val ta = context.obtainStyledAttributes(attrs, R.styleable.AudioRecordView) if (ta.hasValue(R.styleable.AudioRecordView_mic_icon)) { micIcon = ta.getResourceId(R.styleable.AudioRecordView_mic_icon, 0) } if (ta.hasValue(R.styleable.AudioRecordView_mic_active_icon)) { micActiveIcon = ta.getResourceId(R.styleable.AudioRecordView_mic_active_icon, 0) } if (ta.hasValue(R.styleable.AudioRecordView_mic_hint_enable)) { micHintEnable = ta.getBoolean(R.styleable.AudioRecordView_mic_hint_enable, true) } if (ta.hasValue(R.styleable.AudioRecordView_mic_hint_text)) { ta.getString(R.styleable.AudioRecordView_mic_hint_text)?.let { micHintText = it } } if (ta.hasValue(R.styleable.AudioRecordView_mic_hint_color)) { micHintColor = ta.getColor(R.styleable.AudioRecordView_mic_hint_color, 0) } if (ta.hasValue(R.styleable.AudioRecordView_mic_hint_bg)) { micHintBg = ta.getResourceId(R.styleable.AudioRecordView_mic_hint_bg, 0) } if (ta.hasValue(R.styleable.AudioRecordView_circle_color)) { circleColor = ta.getColor(R.styleable.AudioRecordView_circle_color, 0) } if (ta.hasValue(R.styleable.AudioRecordView_cancel_icon_color)) { cancelIconColor = ta.getColor(R.styleable.AudioRecordView_cancel_icon_color, 0) } if (ta.hasValue(R.styleable.AudioRecordView_blink_color)) { blinkColor = ta.getColor(R.styleable.AudioRecordView_blink_color, 0) } if (ta.hasValue(R.styleable.AudioRecordView_slide_cancel_text)) { ta.getString(R.styleable.AudioRecordView_slide_cancel_text)?.let { slideCancelText = it } } if (ta.hasValue(R.styleable.AudioRecordView_cancel_text)) { ta.getString(R.styleable.AudioRecordView_cancel_text)?.let { cancelText = it } } if (ta.hasValue(R.styleable.AudioRecordView_vibration_enable)) { vibrationEnable = ta.getBoolean(R.styleable.AudioRecordView_vibration_enable, true) } ta.recycle() binding.slidePanel.callback = chatSlideCallback binding.recordCircle.callback = recordCircleCallback binding.recordIb.setOnTouchListener(recordOnTouchListener) } @Suppress("unused") fun cancelExternal() { removeCallbacks(recordRunnable) cleanUp() updateRecordCircleAndSendIcon() binding.slidePanel.parent.requestDisallowInterceptTouchEvent(false) } fun setTimeoutSeconds(seconds: Int) { binding.slidePanel.timeoutSeconds = seconds } private fun cleanUp() { startX = 0f originX = 0f isRecording = false } private fun handleCancelOrEnd(cancel: Boolean) { if (cancel) callback.onRecordCancel() else callback.onRecordEnd() if (vibrationEnable) { context.vibrate(longArrayOf(0, 10)) } cleanUp() updateRecordCircleAndSendIcon() } private fun updateRecordCircleAndSendIcon() { if (isRecording) { binding.recordCircle.visibility = View.VISIBLE binding.recordCircle.setAmplitude(.0) ObjectAnimator.ofFloat(binding.recordCircle, "scale", 1f).apply { interpolator = DecelerateInterpolator() duration = 200 addListener( onEnd = { binding.recordCircle.visibility = View.VISIBLE }, onCancel = { binding.recordCircle.visibility = View.VISIBLE } ) }.start() binding.recordIb.animate().setDuration(200).alpha(0f).start() binding.slidePanel.onStart() } else { ObjectAnimator.ofFloat(binding.recordCircle, "scale", 0f).apply { interpolator = AccelerateInterpolator() duration = 200 addListener( onEnd = { binding.recordCircle.visibility = View.GONE binding.recordCircle.setSendButtonInvisible() }, onCancel = { binding.recordCircle.visibility = View.GONE binding.recordCircle.setSendButtonInvisible() } ) }.start() binding.recordIb.animate().setDuration(200).alpha(1f).start() binding.slidePanel.onEnd() } } private fun clickSend() { if (micHintEnable && binding.recordTipTv.visibility == View.INVISIBLE) { binding.recordTipTv.fadeIn(ANIMATION_DURATION) if (vibrationEnable) { context.vibrate(longArrayOf(0, 10)) } postDelayed(hideRecordTipRunnable, RECORD_TIP_MILLIS) } else { removeCallbacks(hideRecordTipRunnable) } postDelayed(hideRecordTipRunnable, RECORD_TIP_MILLIS) } private var startX = 0f private var originX = 0f private var startTime = 0L private var triggeredCancel = false private var hasStartRecord = false private var locked = false private var maxScrollX = context.dip(100f) @SuppressLint("ClickableViewAccessibility") private val recordOnTouchListener = OnTouchListener { _, event -> when (event.action) { ACTION_DOWN -> { if (binding.recordCircle.sendButtonVisible) { return@OnTouchListener false } originX = event.rawX startX = event.rawX val w = binding.slidePanel.slideWidth if (w > 0) { maxScrollX = w } startTime = System.currentTimeMillis() hasStartRecord = false locked = false postDelayed(recordRunnable, RECORD_DELAY) return@OnTouchListener true } ACTION_MOVE -> { if (binding.recordCircle.sendButtonVisible || !hasStartRecord) return@OnTouchListener false val x = binding.recordCircle.setLockTranslation(event.y) if (x == 2) { ObjectAnimator.ofFloat( binding.recordCircle, "lockAnimatedTranslation", binding.recordCircle.startTranslation ).apply { duration = 150 interpolator = DecelerateInterpolator() doOnEnd { locked = true } }.start() binding.slidePanel.toCancel() return@OnTouchListener false } val moveX = event.rawX if (moveX != 0f) { binding.slidePanel.slideText(startX - moveX) if (originX - moveX > maxScrollX) { removeCallbacks(recordRunnable) removeCallbacks(checkReadyRunnable) handleCancelOrEnd(true) binding.slidePanel.parent.requestDisallowInterceptTouchEvent(false) triggeredCancel = true return@OnTouchListener false } } startX = moveX } ACTION_UP, ACTION_CANCEL -> { if (triggeredCancel) { cleanUp() triggeredCancel = false return@OnTouchListener false } if (!hasStartRecord) { removeCallbacks(recordRunnable) removeCallbacks(checkReadyRunnable) cleanUp() if (!post(sendClickRunnable)) { clickSend() } } else if (hasStartRecord && !locked && System.currentTimeMillis() - startTime < 500) { removeCallbacks(recordRunnable) removeCallbacks(checkReadyRunnable) // delay check sendButtonVisible postDelayed( { if (!binding.recordCircle.sendButtonVisible) { handleCancelOrEnd(true) } else { binding.recordCircle.sendButtonVisible = false } }, 200 ) return@OnTouchListener false } if (isRecording && !binding.recordCircle.sendButtonVisible) { handleCancelOrEnd(event.action == ACTION_CANCEL) } else { cleanUp() } if (!callback.isReady()) { upBeforeGrant = true } } } return@OnTouchListener true } private val sendClickRunnable = Runnable { clickSend() } private val hideRecordTipRunnable = Runnable { if (binding.recordTipTv.visibility == View.VISIBLE) { binding.recordTipTv.fadeOut(ANIMATION_DURATION) } } private val recordRunnable: Runnable by lazy { Runnable { hasStartRecord = true removeCallbacks(hideRecordTipRunnable) post(hideRecordTipRunnable) if (ContextCompat.checkSelfPermission( activity, (Manifest.permission.RECORD_AUDIO) ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.RECORD_AUDIO), 99) return@Runnable } callback.onRecordStart() if (vibrationEnable) { context.vibrate(longArrayOf(0, 10)) } upBeforeGrant = false post(checkReadyRunnable) binding.recordIb.parent.requestDisallowInterceptTouchEvent(true) } } private val checkReadyRunnable: Runnable by lazy { Runnable { if (callback.isReady()) { if (upBeforeGrant) { upBeforeGrant = false return@Runnable } isRecording = true updateRecordCircleAndSendIcon() binding.recordCircle.setLockTranslation(10000f) } else { postDelayed(checkReadyRunnable, 50) } } } private val chatSlideCallback = object : SlidePanelView.Callback { override fun onTimeout() { handleCancelOrEnd(false) } override fun onCancel() { handleCancelOrEnd(true) } } private val recordCircleCallback = object : RecordCircleView.Callback { override fun onSend() { handleCancelOrEnd(false) } override fun onCancel() { handleCancelOrEnd(true) } } interface Callback { fun onRecordStart() fun isReady(): Boolean fun onRecordEnd() fun onRecordCancel() } }
2
Kotlin
13
51
d6a4a434e16af67e988e9d5e17188ffc117d63ed
15,683
AudioRecorderView
Apache License 2.0
app/src/main/java/com/prushh/mvvmshop/models/shop/ShopResponse.kt
prushh
283,502,137
false
null
package com.prushh.mvvmshop.models.shop /** * Represent shop API response. * @property message Server response message. * @property status Message based on response status code. * @property products List of required products. */ data class ShopResponse( val message: String, val status: String, val products: MutableList<Product> )
0
Kotlin
0
2
2ba27ecd1b811bbe6684eb37d8e4a027e6e29885
349
MVVMShop
MIT License
app/src/main/java/com/coco/androiddemo/lessions/kotlin_base_types/KTDataForType.kt
cocomanbar
662,634,305
false
null
package com.coco.androiddemo.lessions fun main() { val str = "123456789" for (c in str) { println("c = $c, c is char? ${(c is Char)}") } // it 单独参数可用 // swift $0 $1 .. str.forEach { println(it) } for (index in str.indices) { } for ((index, value) in str.withIndex()) { } var num = 1 while (num < 5) { num += 1 } do { num += 1 } while (num < 10) println("结束") for (index in 0..9) { if (index % 2 == 0) { continue } if (index == 9) { break } println("index = $index") } }
0
Kotlin
0
0
a008fab1fa57f5027dbef367030d87a3483f9e02
652
FirstAndroidDemo
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/guardduty/CfnThreatIntelSetProps.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 142794926}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.guardduty import io.cloudshiftdev.awscdk.CfnTag import io.cloudshiftdev.awscdk.IResolvable import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Any import kotlin.Boolean import kotlin.String import kotlin.Unit import kotlin.collections.List /** * Properties for defining a `CfnThreatIntelSet`. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.guardduty.*; * CfnThreatIntelSetProps cfnThreatIntelSetProps = CfnThreatIntelSetProps.builder() * .format("format") * .location("location") * // the properties below are optional * .activate(false) * .detectorId("detectorId") * .name("name") * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html) */ public interface CfnThreatIntelSetProps { /** * A Boolean value that indicates whether GuardDuty is to start using the uploaded ThreatIntelSet. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html#cfn-guardduty-threatintelset-activate) */ public fun activate(): Any? = unwrap(this).getActivate() /** * The unique ID of the detector of the GuardDuty account that you want to create a threatIntelSet * for. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html#cfn-guardduty-threatintelset-detectorid) */ public fun detectorId(): String? = unwrap(this).getDetectorId() /** * The format of the file that contains the ThreatIntelSet. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html#cfn-guardduty-threatintelset-format) */ public fun format(): String /** * The URI of the file that contains the ThreatIntelSet. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html#cfn-guardduty-threatintelset-location) */ public fun location(): String /** * A user-friendly ThreatIntelSet name displayed in all findings that are generated by activity * that involves IP addresses included in this ThreatIntelSet. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html#cfn-guardduty-threatintelset-name) */ public fun name(): String? = unwrap(this).getName() /** * The tags to be added to a new threat list resource. * * Each tag consists of a key and an optional value, both of which you define. * * For more information, see * [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html#cfn-guardduty-threatintelset-tags) */ public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList() /** * A builder for [CfnThreatIntelSetProps] */ @CdkDslMarker public interface Builder { /** * @param activate A Boolean value that indicates whether GuardDuty is to start using the * uploaded ThreatIntelSet. */ public fun activate(activate: Boolean) /** * @param activate A Boolean value that indicates whether GuardDuty is to start using the * uploaded ThreatIntelSet. */ public fun activate(activate: IResolvable) /** * @param detectorId The unique ID of the detector of the GuardDuty account that you want to * create a threatIntelSet for. */ public fun detectorId(detectorId: String) /** * @param format The format of the file that contains the ThreatIntelSet. */ public fun format(format: String) /** * @param location The URI of the file that contains the ThreatIntelSet. */ public fun location(location: String) /** * @param name A user-friendly ThreatIntelSet name displayed in all findings that are generated * by activity that involves IP addresses included in this ThreatIntelSet. */ public fun name(name: String) /** * @param tags The tags to be added to a new threat list resource. * Each tag consists of a key and an optional value, both of which you define. * * For more information, see * [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . */ public fun tags(tags: List<CfnTag>) /** * @param tags The tags to be added to a new threat list resource. * Each tag consists of a key and an optional value, both of which you define. * * For more information, see * [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . */ public fun tags(vararg tags: CfnTag) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.guardduty.CfnThreatIntelSetProps.Builder = software.amazon.awscdk.services.guardduty.CfnThreatIntelSetProps.builder() /** * @param activate A Boolean value that indicates whether GuardDuty is to start using the * uploaded ThreatIntelSet. */ override fun activate(activate: Boolean) { cdkBuilder.activate(activate) } /** * @param activate A Boolean value that indicates whether GuardDuty is to start using the * uploaded ThreatIntelSet. */ override fun activate(activate: IResolvable) { cdkBuilder.activate(activate.let(IResolvable.Companion::unwrap)) } /** * @param detectorId The unique ID of the detector of the GuardDuty account that you want to * create a threatIntelSet for. */ override fun detectorId(detectorId: String) { cdkBuilder.detectorId(detectorId) } /** * @param format The format of the file that contains the ThreatIntelSet. */ override fun format(format: String) { cdkBuilder.format(format) } /** * @param location The URI of the file that contains the ThreatIntelSet. */ override fun location(location: String) { cdkBuilder.location(location) } /** * @param name A user-friendly ThreatIntelSet name displayed in all findings that are generated * by activity that involves IP addresses included in this ThreatIntelSet. */ override fun name(name: String) { cdkBuilder.name(name) } /** * @param tags The tags to be added to a new threat list resource. * Each tag consists of a key and an optional value, both of which you define. * * For more information, see * [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . */ override fun tags(tags: List<CfnTag>) { cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap)) } /** * @param tags The tags to be added to a new threat list resource. * Each tag consists of a key and an optional value, both of which you define. * * For more information, see * [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . */ override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList()) public fun build(): software.amazon.awscdk.services.guardduty.CfnThreatIntelSetProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.guardduty.CfnThreatIntelSetProps, ) : CdkObject(cdkObject), CfnThreatIntelSetProps { /** * A Boolean value that indicates whether GuardDuty is to start using the uploaded * ThreatIntelSet. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html#cfn-guardduty-threatintelset-activate) */ override fun activate(): Any? = unwrap(this).getActivate() /** * The unique ID of the detector of the GuardDuty account that you want to create a * threatIntelSet for. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html#cfn-guardduty-threatintelset-detectorid) */ override fun detectorId(): String? = unwrap(this).getDetectorId() /** * The format of the file that contains the ThreatIntelSet. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html#cfn-guardduty-threatintelset-format) */ override fun format(): String = unwrap(this).getFormat() /** * The URI of the file that contains the ThreatIntelSet. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html#cfn-guardduty-threatintelset-location) */ override fun location(): String = unwrap(this).getLocation() /** * A user-friendly ThreatIntelSet name displayed in all findings that are generated by activity * that involves IP addresses included in this ThreatIntelSet. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html#cfn-guardduty-threatintelset-name) */ override fun name(): String? = unwrap(this).getName() /** * The tags to be added to a new threat list resource. * * Each tag consists of a key and an optional value, both of which you define. * * For more information, see * [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-threatintelset.html#cfn-guardduty-threatintelset-tags) */ override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): CfnThreatIntelSetProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.guardduty.CfnThreatIntelSetProps): CfnThreatIntelSetProps = CdkObjectWrappers.wrap(cdkObject) as? CfnThreatIntelSetProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: CfnThreatIntelSetProps): software.amazon.awscdk.services.guardduty.CfnThreatIntelSetProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.guardduty.CfnThreatIntelSetProps } }
4
Kotlin
0
4
e15f2e27e08adeb755ad44b2424c195521a6f5ba
11,282
kotlin-cdk-wrapper
Apache License 2.0
base/media/medialib/src/main/kotlin/com/flammky/musicplayer/base/media/mediaconnection/playback/PlaybackProperties.kt
flammky
462,795,948
false
{"Kotlin": 5222947}
package com.flammky.musicplayer.base.media.mediaconnection.playback data class PlaybackProperties( val playWhenReady: Boolean, val playing: Boolean, val shuffleEnabled: Boolean, val canSeekNext: Boolean, val canSeekPrevious: Boolean, val repeatMode: RepeatMode, val playbackState: PlaybackState ) { sealed interface RepeatMode { /** * No Repeat Mode */ object OFF : RepeatMode /** * Repeat currently playing Media Item */ object ONE : RepeatMode /** * Repeat the Playlist */ object ALL : RepeatMode } sealed interface PlaybackState { object IDLE : PlaybackState object BUFFERING : PlaybackState object READY : PlaybackState object ENDED : PlaybackState object ERROR : PlaybackState } companion object { val UNSET = PlaybackProperties( playWhenReady = false, playing = false, shuffleEnabled = false, canSeekNext = false, canSeekPrevious = false, repeatMode = RepeatMode.OFF, playbackState = PlaybackState.IDLE, ) } }
0
Kotlin
6
56
a452c453815851257462623be704559d306fb383
1,001
Music-Player
Apache License 2.0
src/main/kotlin/com/mvp/payment/domain/service/payment/MPOrderService.kt
lfneves
729,678,052
false
{"Kotlin": 74436, "Shell": 4047, "Dockerfile": 255, "Gherkin": 222}
package com.mvp.payment.domain.service.payment import com.mvp.payment.domain.model.payment.store.QrDataDTO import com.mvp.payment.domain.model.payment.store.webhook.MerchantOrderDTO interface MPOrderService { suspend fun saveCheckoutOrderExternalStoreID(merchantOrderDTO: MerchantOrderDTO) suspend fun generateOrderQrs(requestBody: String): QrDataDTO // // fun orderCheckoutGenerateQrs(order: OrderDTO): String // // suspend fun getMerchantOrderByID(requestUrl: String): MerchantOrderResponseDTO suspend fun checkoutOrder(externalId: String): QrDataDTO }
0
Kotlin
0
0
53cdb26677436dd7aadb0114b03267e7e130c2a3
577
tech-challenge-payment
MIT License
app/src/main/kotlin/taiwan/no1/app/ssfm/features/chart/ChartRankChartDetailFragment.kt
pokk
90,497,127
false
null
package taiwan.no1.app.ssfm.features.chart import android.os.Bundle import com.devrapid.kotlinknifer.recyclerview.WrapContentLinearLayoutManager import com.devrapid.kotlinknifer.recyclerview.itemdecorator.VerticalItemDecorator import com.hwangjr.rxbus.RxBus import com.hwangjr.rxbus.annotation.Subscribe import com.hwangjr.rxbus.annotation.Tag import org.jetbrains.anko.bundleOf import taiwan.no1.app.ssfm.R import taiwan.no1.app.ssfm.databinding.FragmentRankChartDetailBinding import taiwan.no1.app.ssfm.features.base.AdvancedFragment import taiwan.no1.app.ssfm.misc.constants.Constant import taiwan.no1.app.ssfm.misc.constants.RxBusTag.HELPER_ADD_TO_PLAYLIST import taiwan.no1.app.ssfm.misc.extension.recyclerview.DataInfo import taiwan.no1.app.ssfm.misc.extension.recyclerview.RankChartDetailAdapter import taiwan.no1.app.ssfm.misc.extension.recyclerview.firstFetch import taiwan.no1.app.ssfm.misc.extension.recyclerview.refreshAndChangeList import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.playerHelper import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.adapters.BaseDataBindingAdapter import taiwan.no1.app.ssfm.models.entities.PlaylistItemEntity import taiwan.no1.app.ssfm.models.entities.v2.RankChartEntity import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemCase import javax.inject.Inject import javax.inject.Named /** * @author jieyi * @since 11/24/17 */ class ChartRankChartDetailFragment : AdvancedFragment<ChartRankChartDetailFragmentViewModel, FragmentRankChartDetailBinding>() { //region Static initialization companion object Factory { // The key name of the fragment initialization parameters. private const val ARG_PARAM_RANK_CODE: String = "param_music_rank_code" private const val ARG_PARAM_CHART_ENTITY: String = "param_music_chart_entity" /** * Use this factory method to create a new instance of this fragment using the provided parameters. * * @return A new instance of [android.app.Fragment] ChartArtistDetailFragment. */ fun newInstance(code: Int = Constant.SPECIAL_NUMBER, chartEntity: RankChartEntity? = null) = ChartRankChartDetailFragment().apply { arguments = bundleOf(ARG_PARAM_RANK_CODE to code, ARG_PARAM_CHART_ENTITY to (chartEntity ?: RankChartEntity())).apply { } } } //endregion @Inject override lateinit var viewModel: ChartRankChartDetailFragmentViewModel @field:[Inject Named("add_playlist_item")] lateinit var addPlaylistItemCase: AddPlaylistItemCase private val trackInfo by lazy { DataInfo() } private var trackRes = mutableListOf<PlaylistItemEntity>() // Get the arguments from the bundle here. private val rankCode by lazy { arguments.getInt(ARG_PARAM_RANK_CODE) } private val chartEntity: RankChartEntity? by lazy { arguments.getParcelable<RankChartEntity>(ARG_PARAM_CHART_ENTITY) } //region Fragment lifecycle override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) RxBus.get().register(this) } override fun onDestroyView() { (binding?.trackAdapter as BaseDataBindingAdapter<*, *>).detachAll() super.onDestroyView() } override fun onDestroy() { RxBus.get().unregister(this) super.onDestroy() } //endregion //region Base fragment implement override fun rendered(savedInstanceState: Bundle?) { binding?.apply { trackLayoutManager = WrapContentLinearLayoutManager(activity) trackAdapter = RankChartDetailAdapter(this@ChartRankChartDetailFragment, R.layout.item_music_type_6, trackRes) { holder, item, index -> if (null == holder.binding.avm) holder.binding.avm = RecyclerViewRankChartDetailViewModel(addPlaylistItemCase, item, index + 1) else holder.binding.avm?.setMusicItem(item, index + 1) } trackDecoration = VerticalItemDecorator(20) } // First time showing this fragment. trackInfo.firstFetch { viewModel.fetchRankChartDetail(rankCode, chartEntity) { trackRes.refreshAndChangeList(it, 0, binding?.trackAdapter as RankChartDetailAdapter, trackInfo) } } playerHelper.currentObject = this.javaClass.name } override fun provideInflateView(): Int = R.layout.fragment_rank_chart_detail //endregion /** * @param playlistItem * * @event_from [taiwan.no1.app.ssfm.features.chart.RecyclerViewRankChartDetailViewModel.trackOnClick] */ @Subscribe(tags = [Tag(HELPER_ADD_TO_PLAYLIST)]) fun addToPlaylist(playlistItem: PlaylistItemEntity) { playerHelper.addToPlaylist(playlistItem, trackRes, this.javaClass.name) } }
0
Kotlin
0
1
1928c2f1a42634ede147517854d06b6fd5d11e7b
5,145
SSFM
Apache License 2.0
src/main/kotlin/com/fiap/order/usecases/CreateOrderUseCase.kt
FIAP-3SOAT-G15
794,350,212
false
{"Kotlin": 125965, "HCL": 4430, "Dockerfile": 283}
package com.fiap.order.usecases import com.fiap.order.domain.entities.OrderItem import com.fiap.order.driver.web.response.PendingOrderResponse import java.util.* interface CreateOrderUseCase { fun create(customerId: UUID?, items: List<OrderItem>): PendingOrderResponse }
0
Kotlin
0
1
53f972c9cb0a7175f3d5ade84c18ac90c025df79
277
orders-api
MIT License
travelmaker_android/app/src/main/java/com/gumibom/travelmaker/ui/main/findmate/meeting_post/MeetingPostViewModel.kt
Leewoogun
767,396,774
false
{"Kotlin": 481004, "Java": 174550, "HTML": 4622, "Dockerfile": 516}
package com.gumibom.travelmaker.ui.main.findmate.meeting_post import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.gumibom.travelmaker.data.dto.response.Position import com.gumibom.travelmaker.domain.meeting_post.PostMeetingUseCase import com.gumibom.travelmaker.model.Address import com.gumibom.travelmaker.model.SendMeetingPost import com.gumibom.travelmaker.ui.common.CommonViewModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject private const val TAG = "MeetingPostViewModel_싸피" @HiltViewModel class MeetingPostViewModel @Inject constructor( private val postMeetingUseCase: PostMeetingUseCase ) : ViewModel(), CommonViewModel { /** * 모임 생성 데이터 모음 */ var title = "" var username = "" var content = "" var authDate = "" var startDate = "" var endDate = "" // position은 viewModel address로 대체하자 var maxMember = 0 var minNative = 0 var minTraveler = 0 var deadlineDate = "" var deadlineTime = "" var categoryList = mutableListOf<String>() private val _imageUrlList = mutableListOf<String>() private val _selectMeetingAddress = MutableLiveData<Address>() val selectMeetingAddress : LiveData<Address> = _selectMeetingAddress private val _urlLiveData = MutableLiveData<MutableList<String>>() val urlLiveData : LiveData<MutableList<String>> = _urlLiveData private val _isSuccess = MutableLiveData<String>() val isSuccess : LiveData<String> = _isSuccess fun meetingSelectAddress(address : Address) { _selectMeetingAddress.value = address } fun addImageUrl(ImageUrl : String) { Log.d(TAG, "addImageUrl: $ImageUrl") _imageUrlList.add(ImageUrl) _urlLiveData.value = _imageUrlList } fun createMeeting() { val sendMeetingPost = SendMeetingPost( title, username, content, authDate, startDate, endDate, _selectMeetingAddress.value!!, maxMember, minNative, minTraveler, deadlineDate, deadlineTime, categoryList ) Log.d(TAG, "createMeeting: $sendMeetingPost") viewModelScope.launch { _isSuccess.value = postMeetingUseCase.createMeeting(sendMeetingPost, _imageUrlList) } } override fun setAddress(address: String) { } }
0
Kotlin
0
0
04e4d7a7a2b613db4a4c9181d015b23b58ea7f70
2,589
TravelMaker
Apache License 1.1
app/src/main/java/me/hegj/wandroid/app/AppLifecyclesImpl.kt
hegaojian
206,478,384
false
null
/* * Copyright 2017 JessYan * * 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 me.hegj.wandroid.app import android.app.Application import android.content.Context import androidx.multidex.MultiDex import butterknife.ButterKnife import cat.ereza.customactivityoncrash.config.CaocConfig import com.jess.arms.base.delegate.AppLifecycles import com.jess.arms.integration.cache.IntelligentCache import com.jess.arms.utils.ArmsUtils import com.kingja.loadsir.callback.SuccessCallback import com.kingja.loadsir.core.LoadSir import com.squareup.leakcanary.LeakCanary import com.squareup.leakcanary.RefWatcher import com.tencent.bugly.Bugly import com.tencent.bugly.crashreport.CrashReport.UserStrategy import com.tencent.mmkv.MMKV import me.hegj.wandroid.BuildConfig import me.hegj.wandroid.app.utils.HttpUtils import me.hegj.wandroid.app.weight.loadCallBack.EmptyCallback import me.hegj.wandroid.app.weight.loadCallBack.ErrorCallback import me.hegj.wandroid.app.weight.loadCallBack.LoadingCallback import me.hegj.wandroid.mvp.ui.activity.error.ErrorActivity import me.hegj.wandroid.mvp.ui.activity.start.SplashActivity /** * ================================================ * 展示 [AppLifecycles] 的用法 * Created by JessYan on 04/09/2017 17:12 * [Contact me](mailto:<EMAIL>) * [Follow me](https://github.com/JessYanCoding) * ================================================ */ class AppLifecyclesImpl : AppLifecycles { override fun attachBaseContext(base: Context) { MultiDex.install(base) //这里比 onCreate 先执行,常用于 MultiDex 初始化,插件化框架的初始化 } override fun onCreate(application: Application) { //初始化MMKV MMKV.initialize(application.filesDir.absolutePath + "/mmkv") if (LeakCanary.isInAnalyzerProcess(application)) { return } ButterKnife.setDebug(BuildConfig.LOG_DEBUG) ArmsUtils.obtainAppComponentFromContext(application).extras() .put(IntelligentCache.getKeyOfKeep(RefWatcher::class.java.name), if (BuildConfig.USE_CANARY) LeakCanary.install(application) else RefWatcher.DISABLED) //界面加载管理 初始化 LoadSir.beginBuilder() .addCallback(LoadingCallback())//加载 .addCallback(ErrorCallback())//错误 .addCallback(EmptyCallback())//空 .setDefaultCallback(SuccessCallback::class.java)//设置默认加载状态页 .commit() //初始化Bugly val context = application.applicationContext // 获取当前包名 val packageName = context.packageName // 获取当前进程名 val processName = HttpUtils.getProcessName(android.os.Process.myPid()) // 设置是否为上报进程 val strategy = UserStrategy(context) strategy.isUploadProcess = processName == null || processName == packageName // 初始化Bugly Bugly.init(context, BuildConfig.BUGLY_KEY, BuildConfig.DEBUG) //防止项目崩溃,崩溃后打开错误界面 CaocConfig.Builder.create() .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //default: CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM .enabled(true)//是否启用CustomActivityOnCrash崩溃拦截机制 必须启用!不然集成这个库干啥??? .showErrorDetails(false) //是否必须显示包含错误详细信息的按钮 default: true .showRestartButton(false) //是否必须显示“重新启动应用程序”按钮或“关闭应用程序”按钮default: true .logErrorOnRestart(false) //是否必须重新堆栈堆栈跟踪 default: true .trackActivities(true) //是否必须跟踪用户访问的活动及其生命周期调用 default: false .minTimeBetweenCrashesMs(2000) //应用程序崩溃之间必须经过的时间 default: 3000 .restartActivity(SplashActivity::class.java) // 重启的activity .errorActivity(ErrorActivity::class.java) //发生错误跳转的activity .eventListener(null) //允许你指定事件侦听器,以便在库显示错误活动 default: null .apply() } override fun onTerminate(application: Application) { } }
1
null
2
713
622016c9695c01f3a134a23c4af1f76686aad6f1
4,352
WanAndroid
Apache License 2.0
app/src/main/kotlin/me/xizzhu/android/joshua/ui/Span.kt
andriiginting
288,359,910
false
null
/* * Copyright (C) 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 me.xizzhu.android.joshua.ui import android.graphics.Typeface import android.text.Spannable import android.text.SpannableStringBuilder import android.text.style.CharacterStyle import android.text.style.RelativeSizeSpan import android.text.style.StyleSpan fun createTitleSizeSpan() = RelativeSizeSpan(0.85F) fun createTitleStyleSpan() = StyleSpan(Typeface.BOLD) fun createKeywordSizeSpan() = RelativeSizeSpan(1.2F) fun createKeywordStyleSpan() = StyleSpan(Typeface.BOLD) fun SpannableStringBuilder.clearAll(): SpannableStringBuilder { clear() clearSpans() return this } fun SpannableStringBuilder.append(i: Int): SpannableStringBuilder = append(i.toString()) fun SpannableStringBuilder.setSpan(span: CharacterStyle): SpannableStringBuilder = setSpan(span, 0, length) fun SpannableStringBuilder.setSpan(span1: CharacterStyle, span2: CharacterStyle): SpannableStringBuilder = setSpan(span1, 0, length).setSpan(span2, 0, length) fun SpannableStringBuilder.setSpan(span: CharacterStyle, start: Int, end: Int): SpannableStringBuilder { setSpan(span, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE) return this } fun SpannableStringBuilder.setSpan(span1: CharacterStyle, span2: CharacterStyle, start: Int, end: Int): SpannableStringBuilder = setSpan(span1, start, end).setSpan(span2, start, end) fun SpannableStringBuilder.toCharSequence(): CharSequence = subSequence(0, length)
0
null
0
1
2372855404bc56da08adff1f5b03f2f2026d50c3
2,021
Joshua
Apache License 2.0
features/feature-details/src/main/kotlin/com/maximillianleonov/cinemax/feature/details/components/Movie.kt
AfigAliyev
523,245,537
false
null
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.maximillianleonov.cinemax.feature.details.components import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import com.maximillianleonov.cinemax.core.model.MovieDetails import com.maximillianleonov.cinemax.core.ui.R import com.maximillianleonov.cinemax.core.ui.mapper.NoMovieRuntimeValue import com.maximillianleonov.cinemax.core.ui.mapper.asNames @Suppress("ReusedModifierInstance") @Composable internal fun MovieDetailsItem( movieDetails: MovieDetails, onBackButtonClick: () -> Unit, onWishlistButtonClick: () -> Unit, modifier: Modifier = Modifier ) { with(movieDetails) { DetailsItem( modifier = modifier, title = title, overview = overview, posterPath = posterPath, releaseDate = releaseDate, runtime = if (runtime == NoMovieRuntimeValue) { stringResource(id = R.string.no_runtime) } else { stringResource(id = R.string.details_runtime_text, runtime.toString()) }, genres = genres.asNames(), voteAverage = voteAverage, credits = credits, isWishlisted = isWishlisted, onBackButtonClick = onBackButtonClick, onWishlistButtonClick = onWishlistButtonClick ) } } @Composable internal fun MovieDetailsItemPlaceholder( onBackButtonClick: () -> Unit, onWishlistButtonClick: () -> Unit, modifier: Modifier = Modifier ) { DetailsItemPlaceholder( modifier = modifier, onBackButtonClick = onBackButtonClick, onWishlistButtonClick = onWishlistButtonClick ) }
8
null
2
89
02e65e899394753e537c6613de6fe4da49bd08f6
2,311
Cinemax
Apache License 2.0
src/test/kotlin/integration/DndR5C7.kt
dkesler
530,453,755
false
{"Kotlin": 136313}
package integration import SolverConfiguration class DndR5C7 : BaseIntegrationTest() { override val file = "/dnd5-7" override val config = SolverConfiguration(true) }
0
Kotlin
0
1
3891aadb125c26e31a1d09664f1988728c1e3e82
176
dungeons-and-diagrams
MIT License
lcc-data/src/main/kotlin/com/joshmanisdabomb/lcc/data/factory/recipe/TrapdoorRecipeFactory.kt
joshmanisdabomb
537,458,013
false
{"Kotlin": 2724329, "Java": 138822}
package com.joshmanisdabomb.lcc.data.factory.recipe import com.joshmanisdabomb.lcc.data.DataAccessor import net.minecraft.data.server.recipe.ShapedRecipeJsonBuilder import net.minecraft.item.Item import net.minecraft.item.ItemConvertible class StairsRecipeFactory(val item: ItemConvertible, val output: Int = 4, val group: String? = null) : RecipeFactory { override fun apply(data: DataAccessor, entry: Item) { ShapedRecipeJsonBuilder.create(entry, output) .pattern("w ") .pattern("ww ") .pattern("www") .input('w', item) .group(group) .apply { hasCriterionShaped(this, item) } .apply { offerShaped(this, data) } } }
0
Kotlin
0
0
a836162eaf64a75ca97daffa02c1f9e66bdde1b4
721
loosely-connected-concepts
Creative Commons Zero v1.0 Universal
core/src/main/java/com/onirutla/movflex/core/data/source/remote/response/GuestStarResponse.kt
onirutlA
476,949,602
false
null
package com.onirutla.movflex.core.data.source.remote.response import com.onirutla.movflex.core.domain.model.GuestStar import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class GuestStarResponse( @Json(name = "adult") val adult: Boolean? = false, @Json(name = "character") val character: String? = "", @Json(name = "credit_id") val creditId: String? = "", @Json(name = "gender") val gender: Int? = 0, @Json(name = "id") val id: Int? = 0, @Json(name = "known_for_department") val knownForDepartment: String? = "", @Json(name = "name") val name: String? = "", @Json(name = "order") val order: Int? = 0, @Json(name = "original_name") val originalName: String? = "", @Json(name = "popularity") val popularity: Double? = 0.0, @Json(name = "profile_path") val profilePath: String? = "", )
0
Kotlin
0
0
689cd51a60c6d1713c2625fbfde2ce59420a19e5
928
MovFlex
MIT License
test/src/me/anno/tests/terrain/v1/TerrainEditMode.kt
AntonioNoack
456,513,348
false
{"Kotlin": 10912545, "C": 236426, "Java": 6754, "Lua": 4496, "C++": 3070, "GLSL": 2698}
package me.anno.tests.terrain.v1 enum class TerrainEditMode { ADDING, PAINTING, SMOOTHING, FLATTENING, }
0
Kotlin
3
24
013af4d92e0f89a83958008fbe1d1fdd9a10e992
122
RemsEngine
Apache License 2.0
app/src/main/java/com/samrudhasolutions/virtualtutoringplatform/network/ApiClient.kt
samrudha01codespace
766,197,634
false
{"Kotlin": 11951}
package com.samrudhasolutions.bolo.network import com.samrudhasolutions.bolo.utils.BASE_URL import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object ApiClient { @Volatile private var INSTANCE: ApiInterface?=null fun getInstance(): ApiInterface { synchronized(this){ return INSTANCE ?:Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() .create(ApiInterface::class.java) .also { INSTANCE =it } } } }
0
Kotlin
0
0
70fa2786dc5c0c3822cc8006c6d3ecd4d279c668
600
PicSolver
MIT License
src/main/kotlin/entity/ontology/WoDTVocabulary.kt
Web-of-Digital-Twins
847,725,953
false
{"Kotlin": 96061, "JavaScript": 983, "Dockerfile": 101}
/* * Copyright (c) 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 * * 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 entity.ontology /** * This module wraps the needed elements of the WoDT vocabulary. */ object WoDTVocabulary { /** Base URI of the vocabulary. */ const val BASE_URI = "https://purl.org/wodt/" /** Physical Asset id predicate. */ const val PHYSICAL_ASSET_ID = BASE_URI + "physicalAssetId" }
2
Kotlin
0
1
5ac73f961a975d65d33a97e9fe0d1b75e5e9f4fa
913
wodt-platform
Apache License 2.0
src/main/kotlin/view/WelcomeScene.kt
Roggired
348,065,860
false
null
package view class WelcomeScene : Scene { override fun start(sceneContext: SceneContext) { println("Welcome to this console-gui monster!") println() println("I can work with trigonometric, polynomial and logarithmic functions and also it compositions.") println() println("LIMITATIONS:") println("1. Equation doesn't need to contain \"=\".") println("2. Equation can contain \"(\" and \")\" only to determine a composition of allowed functions." + System.lineSeparator() + "And for all compositions you have to surround their arguments with \"(\" and \")\".") println("3. To specify a negative power for a polynomial function don't use \"(\" and \")\".") println("4. To specify a power for a polynomial function use \"^\".") println("5. You can apply a function only to one another functions. Sums, differences and staff are not allowed yet. ") println("6. To specify a logarithmic function write \"log^\" and add a base.") println("7. Doubles can be specified only with \".\".") println("8. DO NOT use any tabs or spaces.") println("9. Free member of an equation has to be the last term.") println() println("EXAMPLES OF CORRECT EQUATIONS:") println("x+x^2") println("1.78x+sin(x)") println("2.8x+log^2(sin(x))") println() println("If you want to use default equation, write \"DEFAULT\"") println("If you want to use an equation from a file, write \"FILE FILE NAME HERE\"") println("If you want to type an equation, write \"CONSOLE EQUATION HERE\"") println("If you want to exit, type EXIT") println() sceneContext.router.switch(sceneContext, "SwitchMode") } }
0
Kotlin
0
2
983935fc1ca2a6da564ff8300c2a53cc85dd8701
1,795
maths_lab2
MIT License
plugins/analysis/java-plugin/src/main/kotlin/arrow/meta/plugins/analysis/java/ast/descriptors/JavaSimpleFunctionDescriptor.kt
arrow-kt
217,378,939
false
null
@file:Suppress("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE") package arrow.meta.plugins.analysis.java.ast.descriptors import arrow.meta.plugins.analysis.java.AnalysisContext import arrow.meta.plugins.analysis.phases.analysis.solver.ast.context.descriptors.SimpleFunctionDescriptor import javax.lang.model.element.ElementKind import javax.lang.model.element.ExecutableElement public class JavaSimpleFunctionDescriptor(ctx: AnalysisContext, impl: ExecutableElement) : SimpleFunctionDescriptor, JavaFunctionDescriptor(ctx, impl) { init { require(impl.kind == ElementKind.METHOD) } }
97
Kotlin
40
316
8d2a80cf3a1275a752c18baceed74cb61aa13b4d
586
arrow-meta
Apache License 2.0
app/src/main/java/com/kyant/pixelmusic/api/playlist/Subscriber.kt
Kyant0
334,608,108
false
null
package com.kyant.pixelmusic.api.playlist import kotlinx.serialization.Serializable @Serializable data class Creator( val defaultAvatar: Boolean? = false, val province: Long? = 0, val authStatus: Long? = 0, val followed: Boolean? = false, val avatarUrl: String? = "", val accountStatus: Long? = 0, val gender: Long? = 0, val city: Long? = 0, val birthday: Long? = 0, val userId: Long? = 0, val userType: Long? = 0, val nickname: String? = "", val signature: String? = "", val description: String? = "", val detailDescription: String? = "", val avatarImgId: Long? = 0, val backgroundImgId: Long? = 0, val backgroundUrl: String? = "", val authority: Long? = 0, val mutual: Boolean? = false, val expertTags: String? = "", val experts: String? = "", val djStatus: Long? = 0, val vipType: Long? = 0, val remarkName: String? = "", val authenticationTypes: Long? = 0, val avatarDetail: String? = "", val avatarImgIdStr: String? = "", val backgroundImgIdStr: String? = "", val anchor: Boolean? = false )
1
null
12
95
e94362a4bc9c6da13b1a1848dce528975bf52b13
1,117
PixelMusic
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/calculatereleasedatesapi/resource/ReferenceDataControllerTest.kt
ministryofjustice
387,841,000
false
{"Kotlin": 1622403, "Shell": 7185, "Dockerfile": 1379}
package uk.gov.justice.digital.hmpps.calculatereleasedatesapi.resource import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import io.micrometer.common.util.StringUtils import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import org.springframework.http.MediaType import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit.jupiter.SpringExtension import org.springframework.test.context.web.WebAppConfiguration import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultMatchers import uk.gov.justice.digital.hmpps.calculatereleasedatesapi.enumerations.DateTypeDefinition import uk.gov.justice.digital.hmpps.calculatereleasedatesapi.enumerations.ReleaseDateType @ExtendWith(SpringExtension::class) @ActiveProfiles("test") @WebMvcTest(controllers = [ReferenceDataController::class]) @AutoConfigureMockMvc(addFilters = false) @ContextConfiguration(classes = [ReferenceDataController::class]) @WebAppConfiguration class ReferenceDataControllerTest { @Autowired private lateinit var mvc: MockMvc @Autowired private lateinit var mapper: ObjectMapper @Test fun `should be able to get date types`() { val result = mvc.perform( MockMvcRequestBuilders.get("/reference-data/date-type") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON), ) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) .andReturn() val readValue = mapper.readValue(result.response.contentAsString, object : TypeReference<List<DateTypeDefinition>>() {}) assertThat(readValue).hasSize(ReleaseDateType.entries.size) assertThat(readValue).describedAs("all have a description").allMatch { StringUtils.isNotBlank(it.description) } } }
7
Kotlin
0
5
7d2845a714169839842e7cde67a06b0b99b32229
2,365
calculate-release-dates-api
MIT License
EZRecipes/app/src/main/java/com/abhiek/ezrecipes/ui/MainLayout.kt
Abhiek187
502,751,240
false
{"Kotlin": 212174, "Ruby": 11396}
package com.abhiek.ezrecipes.ui import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.material.* import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import androidx.navigation.compose.rememberNavController import com.abhiek.ezrecipes.ui.navbar.* import com.abhiek.ezrecipes.ui.previews.DevicePreviews import com.abhiek.ezrecipes.ui.previews.DisplayPreviews import com.abhiek.ezrecipes.ui.previews.FontPreviews import com.abhiek.ezrecipes.ui.previews.OrientationPreviews import com.abhiek.ezrecipes.ui.theme.EZRecipesTheme import com.abhiek.ezrecipes.utils.currentWindowSize import com.abhiek.ezrecipes.utils.toPx @Composable fun MainLayout( widthSizeClass: WindowWidthSizeClass ) { // Remember functions can only be called in a composable, not an activity val scope = rememberCoroutineScope() val scaffoldState = rememberScaffoldState(rememberDrawerState(DrawerValue.Closed)) // The navigation controller shouldn't be recreated in other composables val navController = rememberNavController() val drawerWidth = 300 LaunchedEffect(widthSizeClass) { // Close the navigation drawer if the screen is too small if (widthSizeClass != WindowWidthSizeClass.Expanded && scaffoldState.drawerState.isOpen) { scaffoldState.drawerState.close() } } // Material Design layout guidelines: // https://developer.android.com/guide/topics/large-screens/navigation-for-responsive-uis#responsive_ui_navigation EZRecipesTheme { // Great resource for setting up the navigation drawer: https://stackoverflow.com/a/73295465 Scaffold( scaffoldState = scaffoldState, topBar = { TopBar(scope, scaffoldState, navController, widthSizeClass) }, // Show the navigation bar on small screens bottomBar = { if (widthSizeClass == WindowWidthSizeClass.Compact) { BottomBar(navController) } }, // Show the navigation drawer on large screens drawerContent = { if (widthSizeClass == WindowWidthSizeClass.Expanded) { NavigationDrawer(scope, scaffoldState, navController, drawerWidth) } }, // Limit the width of the navigation drawer so there isn't much whitespace drawerShape = object : Shape { override fun createOutline( size: Size, layoutDirection: LayoutDirection, density: Density ) = Outline.Rectangle( Rect(left = 0f, top = 0f, right = drawerWidth.toPx, bottom = size.height) ) }, // Content padding parameter is required: https://stackoverflow.com/a/72085218 content = { padding -> // A surface container using the 'background' color from the theme Surface( modifier = Modifier.padding(padding), color = MaterialTheme.colors.background ) { Row { // Show the navigation rail on medium screens if (widthSizeClass == WindowWidthSizeClass.Medium) { NavRail(navController) } NavigationGraph(navController, widthSizeClass) } } } ) } } @DevicePreviews @DisplayPreviews @FontPreviews @OrientationPreviews @Composable private fun MainLayoutPreview() { // Use the actual size of the device to show accurate previews val windowSize = currentWindowSize() EZRecipesTheme { MainLayout(windowSize.widthSizeClass) } }
0
Kotlin
0
0
145600b596d5b1bdea47e6c472faad827c696497
4,329
ez-recipes-android
MIT License
app/src/main/java/com/prime/media/Home.kt
iZakirSheikh
506,656,610
false
null
@file:Suppress("AnimateAsStateLabel") package com.prime.media import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.AnimationConstants import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.scaleIn import androidx.compose.foundation.background import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.BottomAppBar import androidx.compose.material.ButtonDefaults import androidx.compose.material.Colors import androidx.compose.material.ContentAlpha import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.MaterialTheme import androidx.compose.material.Shapes import androidx.compose.material.Typography import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.FolderCopy import androidx.compose.material.icons.outlined.Home import androidx.compose.material.icons.outlined.LibraryMusic import androidx.compose.material.icons.outlined.PlaylistPlay import androidx.compose.material.icons.outlined.Settings import androidx.compose.material.icons.outlined.VideoLibrary import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.NonRestartableComposable import androidx.compose.runtime.SideEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.dialog import androidx.navigation.compose.rememberNavController import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.rememberPermissionState import com.prime.media.console.Console import com.prime.media.console.PopupMedia import com.prime.media.core.ContentPadding import com.prime.media.core.NightMode import com.prime.media.core.billing.purchased import com.prime.media.core.compose.BottomNavigationItem2 import com.prime.media.core.compose.Channel import com.prime.media.core.compose.LocalNavController import com.prime.media.core.compose.LocalSystemFacade import com.prime.media.core.compose.LocalWindowSizeClass import com.prime.media.core.compose.NavigationRailItem2 import com.prime.media.core.compose.Placeholder import com.prime.media.core.compose.Scaffold2 import com.prime.media.core.compose.current import com.prime.media.core.compose.preference import com.prime.media.core.compose.purchase import com.prime.media.core.playback.MediaItem import com.prime.media.directory.playlists.Members import com.prime.media.directory.playlists.MembersViewModel import com.prime.media.directory.playlists.Playlists import com.prime.media.directory.playlists.PlaylistsViewModel import com.prime.media.directory.store.Albums import com.prime.media.directory.store.AlbumsViewModel import com.prime.media.directory.store.Artists import com.prime.media.directory.store.ArtistsViewModel import com.prime.media.directory.store.Audios import com.prime.media.directory.store.AudiosViewModel import com.prime.media.directory.store.Folders import com.prime.media.directory.store.FoldersViewModel import com.prime.media.directory.store.Genres import com.prime.media.directory.store.GenresViewModel import com.prime.media.editor.TagEditor import com.prime.media.effects.AudioFx import com.prime.media.impl.AudioFxViewModel import com.prime.media.impl.ConsoleViewModel import com.prime.media.impl.LibraryViewModel import com.prime.media.impl.SettingsViewModel import com.prime.media.impl.TagEditorViewModel import com.prime.media.library.Library import com.prime.media.settings.Settings import com.primex.core.Amber import com.primex.core.DahliaYellow import com.primex.core.OrientRed import com.primex.core.SignalWhite import com.primex.core.TrafficBlack import com.primex.core.UmbraGrey import com.primex.core.drawHorizontalDivider import com.primex.core.drawVerticalDivider import com.primex.material2.IconButton import com.primex.material2.OutlinedButton import kotlinx.coroutines.launch import kotlin.math.ln private const val TAG = "Home" /** * A short-hand alias of [MaterialTheme] */ typealias Material = MaterialTheme /** * A variant of caption. */ private val caption2 = TextStyle(fontWeight = FontWeight.Normal, fontSize = 10.sp, letterSpacing = 0.4.sp) /** * A variant of [caption] with a smaller font size and tighter letter spacing. * Use this style for captions that require less emphasis or in situations where space is constrained. * * @see caption */ val Typography.caption2 get() = com.prime.media.caption2 /** * The alpha value for the container colors. * * This constant value represents the alpha (transparency) of the container colors in the current * [MaterialTheme]. The value is a Float between 0.0 and 1.0, where 0.0 is completely transparent * and 1.0 is completely opaque. This value can be used to adjust the transparency of container * backgrounds and other elements in your app that use the container color. */ val MaterialTheme.CONTAINER_COLOR_ALPHA get() = 0.15f /** * A variant of [MaterialTheme.shapes.small] with a corner radius of 8dp. */ private val small2 = RoundedCornerShape(8.dp) /** * A variant of [MaterialTheme.shapes.small] with a radius of 8dp. */ val Shapes.small2 get() = com.prime.media.small2 /** * This Composable function provides a primary container color with reduced emphasis as compared to * the primary color. * It is used for styling elements that require a less prominent color. * * The color returned by this function is derived from the primary color of the current * MaterialTheme with an alpha value equal to [MaterialTheme.CONTAINER_COLOR_ALPHA]. * * @return a [Color] object representing the primary container color. */ val Colors.primaryContainer @Composable inline get() = MaterialTheme.colors.primary.copy(MaterialTheme.CONTAINER_COLOR_ALPHA) /** * Returns a color that is suitable for content (icons, text, etc.) that sits on top of the primary container color. * This color is simply the primary color of the current theme. * * @return [Color] object that represents the on-primary container color */ val Colors.onPrimaryContainer @Composable inline get() = MaterialTheme.colors.primary /** * Secondary container is applied to elements needing less emphasis than secondary */ val Colors.secondaryContainer @Composable inline get() = MaterialTheme.colors.secondary.copy(MaterialTheme.CONTAINER_COLOR_ALPHA) /** * On-secondary container is applied to content (icons, text, etc.) that sits on top of secondary * container */ val Colors.onSecondaryContainer @Composable inline get() = MaterialTheme.colors.secondary /** * Error container is applied to elements associated with an error state */ val Colors.errorContainer @Composable inline get() = MaterialTheme.colors.error.copy(MaterialTheme.CONTAINER_COLOR_ALPHA) /** * On-error container is applied to content (icons, text, etc.) that sits on top of error container */ val Colors.onErrorContainer @Composable inline get() = MaterialTheme.colors.error /** * The overlay color used for backgrounds and shadows. * The color is black with alpha 0.04 on light themes and white with alpha 0.04 on dark themes. */ val Colors.overlay @Composable inline get() = (if (isLight) Color.Black else Color.White).copy(0.04f) /** * The outline color used in the light/dark theme. * * The color is semi-transparent white/black, depending on the current theme, with an alpha of 0.12. */ inline val Colors.outline get() = (if (isLight) Color.Black else Color.White).copy(0.12f) val Colors.onOverlay @Composable inline get() = (MaterialTheme.colors.onBackground).copy(alpha = ContentAlpha.medium) val Colors.lightShadowColor @Composable inline get() = if (isLight) Color.White else Color.White.copy(0.025f) val Colors.darkShadowColor @Composable inline get() = if (isLight) Color(0xFFAEAEC0).copy(0.7f) else Color.Black.copy(0.6f) /** * Computes the surface tonal color at different elevation levels e.g. surface1 through surface5. This function is inspired by the Material 3 design system. * * @param elevation Elevation value used to compute alpha of the color overlay layer. * * @return the [ColorScheme.surface] color with an alpha of the [Colors.primary] color * overlaid on top of it. */ fun Colors.surfaceColorAtElevation( elevation: Dp, ): Color { if (elevation == 0.dp) return surface val alpha = ((4.5f * ln(elevation.value + 1)) + 2f) / 100f return primary.copy(alpha = alpha).compositeOver(surface) } /** * A simple composable that helps in resolving the current app theme as suggested by the [Gallery.NIGHT_MODE] */ @Composable @NonRestartableComposable private fun isPrefDarkTheme(): Boolean { val mode by preference(key = Settings.NIGHT_MODE) return when (mode) { NightMode.YES -> true NightMode.FOLLOW_SYSTEM -> androidx.compose.foundation.isSystemInDarkTheme() else -> false } } // Default Enter/Exit Transitions. @OptIn(ExperimentalAnimationApi::class) private val EnterTransition = scaleIn(tween(220, 90), 0.98f) + fadeIn(tween(700)) private val ExitTransition = fadeOut(tween(700)) /** * The route to permission screen. */ private const val PERMISSION_ROUTE = "_route_storage_permission" /** * The permission screen. */ @OptIn(ExperimentalPermissionsApi::class) @Composable private fun Permission() { val controller = LocalNavController.current // Compose the permission state. // Once granted set different route like folders as start. // Navigate from here to there. val permission = rememberPermissionState(permission = Audiofy.STORAGE_PERMISSION) { if (!it) return@rememberPermissionState controller.graph.setStartDestination(Library.route) controller.navigate(Library.route) { popUpTo(PERMISSION_ROUTE) { inclusive = true } } } Placeholder( iconResId = R.raw.lt_permission, title = stringResource(R.string.permission_screen_title), message = stringResource(R.string.permission_screen_desc), vertical = LocalWindowSizeClass.current.widthSizeClass == WindowWidthSizeClass.Compact ) { OutlinedButton( onClick = { permission.launchPermissionRequest() }, modifier = Modifier.size(width = 200.dp, height = 46.dp), elevation = null, label = "ALLOW", border = ButtonDefaults.outlinedBorder, shape = CircleShape, colors = ButtonDefaults.outlinedButtonColors(backgroundColor = Color.Transparent) ) } } private val LightPrimaryColor = Color(0xFF244285) private val LightPrimaryVariantColor = Color(0xFF305EA5) private val LightSecondaryColor = Color(0xFF8B008B) private val LightSecondaryVariantColor = Color(0xFF7B0084) private val DarkPrimaryColor = Color(0xFFff8f00) private val DarkPrimaryVariantColor = Color.Amber private val DarkSecondaryColor = Color.DahliaYellow private val DarkSecondaryVariantColor = Color(0xFFf57d00) @Composable @NonRestartableComposable fun Material( darkTheme: Boolean, content: @Composable () -> Unit, ) { val background by animateColorAsState( targetValue = if (darkTheme) Color(0xFF0E0E0F) else Color(0xFFF5F5FA), animationSpec = tween(AnimationConstants.DefaultDurationMillis) ) val surface by animateColorAsState( targetValue = if (darkTheme) Color.TrafficBlack else Color.White, animationSpec = tween(AnimationConstants.DefaultDurationMillis) ) val primary = if (darkTheme) DarkPrimaryColor else LightPrimaryColor val primaryVariant = if (darkTheme) DarkPrimaryVariantColor else LightPrimaryVariantColor val secondary = if (darkTheme) DarkSecondaryColor else LightSecondaryColor val secondaryVariant = if (darkTheme) DarkSecondaryVariantColor else LightSecondaryVariantColor val colors = Colors( primary = primary, secondary = secondary, background = background, surface = surface, primaryVariant = primaryVariant, secondaryVariant = secondaryVariant, onPrimary = Color.SignalWhite, onSurface = if (darkTheme) Color.SignalWhite else Color.UmbraGrey, onBackground = if (darkTheme) Color.SignalWhite else Color.UmbraGrey, error = Color.OrientRed, onSecondary = Color.SignalWhite, onError = Color.SignalWhite, isLight = !darkTheme ) // Actual theme compose; in future handle fonts etc. MaterialTheme( colors = colors, content = content, typography = Typography(Settings.DefaultFontFamily) ) // In this block, we handle status_bar related tasks, but this occurs only when // the application is in edit mode. // FixMe: Consider handling scenarios where the current activity is not MainActivity, // as preferences may depend on the MainActivity. // Handle SystemBars logic. val view = LocalView.current // Early return if (view.isInEditMode) return@Material // FixMe: It seems sideEffect is not working for hideSystemBars. val colorSystemBars by preference(key = Settings.COLOR_STATUS_BAR) val hideStatusBar by preference(key = Settings.HIDE_STATUS_BAR) val color = when { colorSystemBars -> Material.colors.primary darkTheme -> DarkSystemBarsColor else -> LightSystemBarsColor } SideEffect { val window = (view.context as Activity).window window.navigationBarColor = color.toArgb() window.statusBarColor = color.toArgb() WindowCompat .getInsetsController(window, view) .isAppearanceLightStatusBars = !darkTheme && !colorSystemBars // if (hideStatusBar) WindowCompat.getInsetsController(window, view) .hide(WindowInsetsCompat.Type.statusBars()) else WindowCompat.getInsetsController(window, view) .show(WindowInsetsCompat.Type.statusBars()) } } /** * A simple structure of the NavGraph. */ @OptIn(ExperimentalAnimationApi::class) @NonRestartableComposable @Composable private fun NavGraph( modifier: Modifier = Modifier ) { val context = LocalContext.current // Load start destination based on if storage permission is set or not. val startDestination = when (ContextCompat.checkSelfPermission(context, Audiofy.STORAGE_PERMISSION)) { PackageManager.PERMISSION_GRANTED -> Library.route else -> PERMISSION_ROUTE } // In order to navigate and remove the need to pass controller below UI components. NavHost( navController = LocalNavController.current, modifier = modifier, startDestination = startDestination, // enterTransition = { EnterTransition }, exitTransition = { ExitTransition }, ) { //Permission composable(PERMISSION_ROUTE) { Permission() } composable(Library.route) { val viewModel = hiltViewModel<LibraryViewModel>() Library(viewModel = viewModel) } composable(Settings.route) { val viewModel = hiltViewModel<SettingsViewModel>() Settings(state = viewModel) } composable(Albums.route) { val viewModel = hiltViewModel<AlbumsViewModel>() Albums(viewModel = viewModel) } composable(Artists.route) { val viewModel = hiltViewModel<ArtistsViewModel>() Artists(viewModel = viewModel) } composable(Audios.route) { val viewModel = hiltViewModel<AudiosViewModel>() Audios(viewModel = viewModel) } composable(Folders.route) { val viewModel = hiltViewModel<FoldersViewModel>() Folders(viewModel = viewModel) } composable(Genres.route) { val viewModel = hiltViewModel<GenresViewModel>() Genres(viewModel = viewModel) } composable(Playlists.route) { val viewModel = hiltViewModel<PlaylistsViewModel>() Playlists(viewModel = viewModel) } composable(Members.route) { val viewModel = hiltViewModel<MembersViewModel>() Members(viewModel = viewModel) } composable(TagEditor.route) { val viewModel = hiltViewModel<TagEditorViewModel>() TagEditor(state = viewModel) } dialog(AudioFx.route) { val viewModel = hiltViewModel<AudioFxViewModel>() AudioFx(state = viewModel) } composable(Console.route) { val viewModel = hiltViewModel<ConsoleViewModel>() Console(state = viewModel) } } } private val LightSystemBarsColor = /*Color(0x10000000)*/ Color.Transparent private val DarkSystemBarsColor = /*Color(0x11FFFFFF)*/ Color.Transparent /** * The array of routes that are required to hide the miniplayer. */ private val HIDDEN_DEST_ROUTES = arrayOf( Console.route, PERMISSION_ROUTE, AudioFx.route ) /** * Extension function for the NavController that facilitates navigation to a specified destination route. * * @param route The destination route to navigate to. * * This function uses the provided route to navigate using the navigation graph. * It includes additional configuration to manage the back stack and ensure a seamless navigation experience. * - It pops up to the start destination of the graph to avoid a buildup of destinations on the back stack. * - It uses the `launchSingleTop` flag to prevent multiple copies of the same destination when re-selecting an item. * - The `restoreState` flag is set to true, ensuring the restoration of state when re-selecting a previously selected item. */ private fun NavController.toRoute(route: String) { navigate(route) { // Pop up to the start destination of the graph to // avoid building up a large stack of destinations // on the back stack as users select items popUpTo(graph.findStartDestination().id) { saveState = true } // Avoid multiple copies of the same destination when // re-selecting the same item launchSingleTop = true // Restore state when re-selecting a previously selected item restoreState = true } } private const val MIME_TYPE_VIDEO = "video/*" @OptIn(ExperimentalMaterialApi::class) @Composable @NonRestartableComposable private fun BottomNav(modifier: Modifier = Modifier) { val navController = LocalNavController.current BottomAppBar( modifier = modifier, windowInsets = WindowInsets.navigationBars, backgroundColor = Material.colors.background, contentColor = Material.colors.onSurface, contentPadding = PaddingValues( horizontal = ContentPadding.normal, vertical = ContentPadding.medium ) ) { var expanded by remember { mutableStateOf(false) } PopupMedia( expanded = expanded, onRequestToggle = {expanded = !expanded } ) Spacer(Modifier.weight(1f)) // Space of normal. val current by navController.currentBackStackEntryAsState() // Home BottomNavigationItem2( label = "Home", icon = Icons.Outlined.Home, checked = current?.destination?.route == Library.route, onClick = { navController.toRoute(Library.direction()) } ) // Audios BottomNavigationItem2( label = "Folders", icon = Icons.Outlined.FolderCopy, checked = current?.destination?.route == Folders.route, onClick = { navController.toRoute(Folders.direction()) } ) // Videos val context = LocalContext.current as MainActivity val launcher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { if (it == null) return@rememberLauncherForActivityResult val intnet = Intent(Intent.ACTION_VIEW).apply { setDataAndType(it, MIME_TYPE_VIDEO) this.`package` = context.packageName } context.startActivity(intnet) } BottomNavigationItem2( label = "Videos", icon = Icons.Outlined.VideoLibrary, checked = false, onClick = { launcher.launch(arrayOf(MIME_TYPE_VIDEO)) } ) // Playlists BottomNavigationItem2( label = "Playlists", icon = Icons.Outlined.PlaylistPlay, checked = current?.destination?.route == Playlists.route, onClick = { navController.toRoute(Playlists.direction()) } ) // Buy full version button. val purchase by purchase(id = BuildConfig.IAP_NO_ADS) val provider = LocalSystemFacade.current if (!purchase.purchased) IconButton( painter = painterResource(id = R.drawable.ic_remove_ads), contentDescription = null, onClick = { provider.launchBillingFlow(BuildConfig.IAP_NO_ADS) } ) else // Settings BottomNavigationItem2( label = "Settings", icon = Icons.Outlined.Settings, checked = current?.destination?.route == Settings.route, onClick = { navController.toRoute(Settings.route) } ) Spacer(modifier = Modifier.weight(1f)) } } @OptIn(ExperimentalMaterialApi::class) @Composable private fun NavRail(modifier: Modifier = Modifier) { androidx.compose.material.NavigationRail( modifier = modifier .width(94.dp) .drawVerticalDivider(Material.colors.outline), windowInsets = WindowInsets.systemBars, backgroundColor = Material.colors.background, contentColor = Material.colors.onSurface, elevation = 0.dp, ) { var expanded by remember { mutableStateOf(false) } PopupMedia( expanded = expanded, onRequestToggle = {expanded = !expanded }, offset = DpOffset(30.dp, -30.dp) ) // Some Space between navs and Icon. Spacer(modifier = Modifier.weight(1f)) val navController = LocalNavController.current // Space of normal. val current by navController.currentBackStackEntryAsState() // Home NavigationRailItem2( label = " Home ", icon = Icons.Outlined.Home, checked = current?.destination?.route == Library.route, onClick = { navController.toRoute(Library.direction()) } ) // Audios NavigationRailItem2( label = " Folders ", icon = Icons.Outlined.FolderCopy, checked = current?.destination?.route == Folders.route, onClick = { navController.toRoute(Folders.direction()) } ) // Videos val context = LocalContext.current as MainActivity val launcher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { if (it == null) return@rememberLauncherForActivityResult val intnet = Intent(Intent.ACTION_VIEW).apply { setDataAndType(it, MIME_TYPE_VIDEO) this.`package` = context.packageName } context.startActivity(intnet) } NavigationRailItem2( label = " Videos ", icon = Icons.Outlined.VideoLibrary, checked = false, onClick = { launcher.launch(arrayOf(MIME_TYPE_VIDEO)) } ) // Playlists NavigationRailItem2( label = "Playlists", icon = Icons.Outlined.PlaylistPlay, checked = current?.destination?.route == Playlists.route, onClick = { navController.toRoute(Playlists.direction()) } ) val purchase by purchase(id = BuildConfig.IAP_NO_ADS) val provider = LocalSystemFacade.current if (!purchase.purchased) IconButton( painter = painterResource(id = R.drawable.ic_remove_ads), contentDescription = null, onClick = { provider.launchBillingFlow(BuildConfig.IAP_NO_ADS) } ) else // Settings NavigationRailItem2( label = "Settings", icon = Icons.Outlined.Settings, checked = current?.destination?.route == Settings.route, onClick = { navController.toRoute(Settings.route) } ) // Some Space between navs and Icon. Spacer(modifier = Modifier.weight(1f)) } } // TODO: Add capability in original API to reverse the drawing of divider. private inline fun Modifier.divider(hide: Boolean, color: Color) = if (hide) Modifier else drawHorizontalDivider(color) @Composable fun Home( channel: Channel ) { val isDark = isPrefDarkTheme() Material(isDark) { val navController = rememberNavController() CompositionLocalProvider(LocalNavController provides navController) { val clazz = LocalWindowSizeClass.current.widthSizeClass val facade = LocalSystemFacade.current Scaffold2( // TODO: Make it dependent LocalWindowSizeClass once horizontal layout of MiniPlayer is Ready. vertical = clazz < WindowWidthSizeClass.Medium, channel = channel, hideNavigationBar = navController.current in HIDDEN_DEST_ROUTES, progress = facade.inAppUpdateProgress, content = { NavGraph(Modifier.divider(clazz > WindowWidthSizeClass.Medium, Material.colors.onSurface)) }, navBar = { when (clazz) { // Always display the bottom navigation when in compact mode. WindowWidthSizeClass.Compact -> BottomNav() // Display the navigation rail for other size classes. // TODO: Consider displaying a larger version of the navigation UI in expanded mode. else -> NavRail() } } ) } // In this section, we handle incoming intents. // Intents can be of two types: video or audio. If it's a video intent, // we navigate to the video screen; otherwise, we play the media item in the MiniPlayer. // In both cases, we trigger a remote action to initiate playback. // Create a coroutine scope to handle asynchronous operations. val scope = rememberCoroutineScope() val activity = LocalView.current.context as MainActivity // Construct the DisposableEffect and listen for events. DisposableEffect(Unit) { // Create a listener for observing changes in incoming intents. val listener = listener@{ intent: Intent -> // Check if the intent action is not ACTION_VIEW; if so, return. if (intent.action != Intent.ACTION_VIEW) return@listener // Obtain the URI from the incoming intent data. val data = intent.data ?: return@listener // Use a coroutine to handle the media item construction and playback. scope.launch { // Construct a MediaItem using the obtained parameters. // (Currently, details about playback queue setup are missing.) val item = MediaItem(activity, data) // Play the media item by replacing the existing queue. activity.remote.set(listOf(item)) activity.remote.play() } // If the intent is related to video content, navigate to the video player screen. navController.navigate(Console.direction()) } // Register the intent listener with the activity. activity.addOnNewIntentListener(listener) // Unregister the intent listener when this composable is disposed. onDispose { activity.removeOnNewIntentListener(listener) } } } }
5
null
9
97
a92a3d74451442b3dfb8d409c1177453c5d656a3
30,581
Audiofy
Apache License 2.0
app/src/main/java/com/example/android_study/jetpack/paging3/_main/ui/adapter/PagingLoadStateAdapter.kt
RhythmCoderZZF
281,057,053
false
null
package com.example.android_study.jetpack.paging3._main.ui.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.view.isVisible import androidx.paging.LoadState import androidx.paging.LoadStateAdapter import androidx.recyclerview.widget.RecyclerView import com.example.android_study.R import com.example.android_study._base.util.LogUtil import com.example.android_study.databinding.RecyclerLoadFooterBinding /** * @author kuky. * @description */ class PagingLoadStateAdapter(private val retry: () -> Unit) : LoadStateAdapter<PagingLoadStateViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState) : PagingLoadStateViewHolder { return PagingLoadStateViewHolder.create(parent, retry) } override fun onBindViewHolder(holder: PagingLoadStateViewHolder, loadState: LoadState) { holder.bind(loadState) } } class PagingLoadStateViewHolder( private val binding: RecyclerLoadFooterBinding, retry: () -> Unit ) : RecyclerView.ViewHolder(binding.root) { init { binding.retryLoadData.setOnClickListener { retry()} } fun bind(loadState: LoadState) { LogUtil.d("zzf","$loadState") binding.loadMore.isVisible = loadState is LoadState.Loading binding.retryLoadData.isVisible = loadState !is LoadState.Loading } companion object { fun create(parent: ViewGroup, retry: () -> Unit): PagingLoadStateViewHolder { val view = LayoutInflater.from(parent.context).inflate( R.layout.recycler_load_footer, parent, false ) return PagingLoadStateViewHolder( RecyclerLoadFooterBinding.bind(view), retry ) } } }
0
Kotlin
0
0
b569adcacfdba5ea6b4c323454c3c5130a1b4763
1,779
AndroidStudy
Apache License 2.0
src/test/kotlin/com/workos/test/passwordless/PasswordlessApiTest.kt
workos
419,780,611
false
null
package com.workos.test.passwordless import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.workos.passwordless.PasswordlessApi import com.workos.passwordless.models.PasswordlessSession import com.workos.passwordless.models.SessionType import com.workos.test.TestBase import org.junit.jupiter.api.Assertions.assertThrows import java.lang.IllegalArgumentException import kotlin.test.Test import kotlin.test.assertEquals class PasswordlessApiTest : TestBase() { private val mapper = jacksonObjectMapper() private fun prepareTest(email: String, requestBody: String): PasswordlessSession { val responseBody = """{ "id": "passwordless_session_01EHDAK2BFGWCSZXP9HGZ3VK8C", "email": "$email", "expires_at": "2020-08-13T05:50:00.000Z", "link": "https://auth.workos.com/passwordless/token/confirm", "object": "passwordless_session" }""" stubResponse( url = "/passwordless/sessions", responseBody = responseBody, requestBody = requestBody ) return mapper.readValue(responseBody, PasswordlessSession::class.java) } @Test fun createSessionWithEmailShouldReturnSession() { val workos = createWorkOSClient() val email = "<EMAIL>" prepareTest( email, """{ "email": "$email", "type": "MagicLink" }""" ) val createSessionOptions = PasswordlessApi.CreateSessionOptions .builder() .email(email) .build() val session = workos.passwordless.createSession(createSessionOptions) assertEquals(session.email, email) } @Test fun createSessionWithEmailAndTypeShouldReturnSession() { val workos = createWorkOSClient() val email = "<EMAIL>" prepareTest( email, """{ "email": "$email", "type": "MagicLink", "redirect_uri": "http://www.google.com" }""" ) val createSessionOptions = PasswordlessApi.CreateSessionOptions .builder() .email(email) .redirectUri("http://www.google.com") .type(SessionType.MagicLink) .build() val session = workos.passwordless.createSession(createSessionOptions) assertEquals(session.email, email) } @Test fun createSessionWithAllParamsShouldReturnSession() { val workos = createWorkOSClient() val email = "<EMAIL>" prepareTest( email, """{ "email": "$email", "type": "MagicLink", "connection": "connectionId", "redirect_uri": "/redirect/to", "expires_in": 500, "state": "app state" }""" ) val createSessionOptions = PasswordlessApi.CreateSessionOptions( email = email, type = SessionType.MagicLink, connection = "connectionId", redirectUri = "/redirect/to", expiresIn = 500, state = "app state" ) val session = workos.passwordless.createSession(createSessionOptions) assertEquals(session.email, email) } @Test fun createSessionOptionsBuilderWithNoEmailShouldThrow() { assertThrows(IllegalArgumentException::class.java) { PasswordlessApi.CreateSessionOptions .builder() .expiresIn(400) .build() } } @Test fun createSessionOptionsDirectWithNoEmailShouldThrow() { assertThrows(IllegalArgumentException::class.java) { PasswordlessApi.CreateSessionOptions(expiresIn = 400) } } @Test fun createSessionOptionsBuilderWithBelowThresholdExpiresInShouldThrow() { assertThrows(IllegalArgumentException::class.java) { PasswordlessApi.CreateSessionOptions .builder() .email("<EMAIL>") .expiresIn(299) .build() } } @Test fun createSessionOptionsDirectWithBelowThresholdShouldThrow() { assertThrows(IllegalArgumentException::class.java) { PasswordlessApi.CreateSessionOptions(email = "<EMAIL>", expiresIn = 299) } } @Test fun createSessionOptionsBuilderWithAboveThresholdExpiresInShouldThrow() { assertThrows(IllegalArgumentException::class.java) { PasswordlessApi.CreateSessionOptions .builder() .email("<EMAIL>") .expiresIn(1801) .build() } } @Test fun createSessionOptionsDirectWithAboveThresholdShouldThrow() { assertThrows(IllegalArgumentException::class.java) { PasswordlessApi.CreateSessionOptions(email = "<EMAIL>", expiresIn = 1801) } } @Test fun sendSessionReturnsSuccessResponse() { val workos = createWorkOSClient() val id = "passwordless_session_01EG1BHJMVYMFBQYZTTC0N73CR" stubResponse( url = "/passwordless/sessions/$id/send", responseBody = """{ "success": true }"""" ) val response = workos.passwordless.sendSession(id) assertEquals(response.success, true) } @Test fun sendSessioReturnsFalseResponse() { val workos = createWorkOSClient() val id = "nope" stubResponse( url = "/passwordless/sessions/$id/send", responseBody = """{ "success": false }"""" ) val response = workos.passwordless.sendSession(id) assertEquals(response.success, false) } }
4
Kotlin
6
9
1f28bfd702ce1009fcee414c3864b6bfe36670d4
5,140
workos-kotlin
MIT License
basick/src/main/java/com/mozhimen/basick/utilk/java/net/UtilKNetworkInterface.kt
mozhimen
353,952,154
false
null
package com.mozhimen.basick.utilk.java.net import com.mozhimen.basick.utilk.android.net.UtilKNetConn import com.mozhimen.basick.utilk.android.util.et import java.net.Inet6Address import java.net.InetAddress import java.net.NetworkInterface import java.net.SocketException import java.util.Enumeration /** * @ClassName UtilKNetworkInterface * @Description TODO * @Author Mozhimen & Kolin Zhao * @Date 2023/9/27 11:34 * @Version 1.0 */ object UtilKNetworkInterface { @JvmStatic fun getNetworkInterfaces(): Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces() ////////////////////////////////////////////////////////////////// /** * 获取网路IP */ @JvmStatic fun getStrIp(): String? { try { val networkInterfaces: Enumeration<NetworkInterface> = getNetworkInterfaces() var inetAddress: InetAddress while (networkInterfaces.hasMoreElements()) { val inetAddresses: Enumeration<InetAddress> = (networkInterfaces.nextElement() as NetworkInterface).inetAddresses while (inetAddresses.hasMoreElements()) { inetAddress = inetAddresses.nextElement() as InetAddress if (inetAddress !is Inet6Address) { if (inetAddress.hostAddress != "127.0.0.1") { return inetAddress.hostAddress ?: continue } } } } } catch (e: SocketException) { e.printStackTrace() "getIP SocketException ${e.message}".et(UtilKNetConn.TAG) } return null } }
0
null
7
115
05064571d43ada3ea6488bafc33d2fe436c0618d
1,671
SwiftKit
Apache License 2.0
app/src/main/java/com/cryptron/breadbox/CoreUtils.kt
defi-ventures
299,059,371
false
{"Gradle": 3, "XML": 262, "Java Properties": 2, "Shell": 2, "Text": 16, "Ignore List": 2, "Batchfile": 2, "Markdown": 1, "YAML": 2, "INI": 1, "Proguard": 1, "Java": 162, "Kotlin": 272, "JSON": 6, "HTML": 2, "Protocol Buffer": 2, "Ruby": 1}
/** * BreadWallet * * Created by <NAME> <<EMAIL>> on 9/25/19. * Copyright (c) 2019 breadwallet LLC * * 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. */ @file:Suppress("EXPERIMENTAL_API_USAGE", "TooManyFunctions") package com.breadwallet.breadbox import com.breadwallet.BuildConfig import com.breadwallet.crypto.Address import com.breadwallet.crypto.AddressScheme import com.breadwallet.crypto.Amount import com.breadwallet.crypto.Currency import com.breadwallet.crypto.Key import com.breadwallet.crypto.Network import com.breadwallet.crypto.NetworkFee import com.breadwallet.crypto.NetworkPeer import com.breadwallet.crypto.System import com.breadwallet.crypto.Transfer import com.breadwallet.crypto.TransferDirection import com.breadwallet.crypto.TransferFeeBasis import com.breadwallet.crypto.Unit import com.breadwallet.crypto.Wallet import com.breadwallet.crypto.WalletManager import com.breadwallet.crypto.WalletManagerMode import com.breadwallet.crypto.WalletManagerState import com.breadwallet.crypto.WalletSweeper import com.breadwallet.crypto.errors.FeeEstimationError import com.breadwallet.crypto.errors.WalletSweeperError import com.breadwallet.crypto.utility.CompletionHandler import com.breadwallet.logger.logError import com.breadwallet.tools.manager.BRSharedPrefs import com.breadwallet.tools.util.BRConstants import com.breadwallet.util.WalletDisplayUtils import com.breadwallet.util.isBitcoin import com.breadwallet.util.isBitcoinCash import com.breadwallet.util.isEthereum import com.breadwallet.util.isRipple import com.google.common.primitives.UnsignedInteger import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.mapNotNull import java.math.BigDecimal import java.text.DecimalFormat import java.text.NumberFormat import java.util.Locale import java.util.concurrent.TimeUnit import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine import kotlin.math.absoluteValue /** Default port for [NetworkPeer] */ private const val DEFAULT_PORT = 8333L /** Returns the [Amount] as a [BigDecimal]. */ fun Amount.toBigDecimal(unit: Unit = this.unit): BigDecimal { return BigDecimal(doubleAmount(unit).or(0.0)) .setScale(unit.decimals.toInt(), BRConstants.ROUNDING_MODE) } /** Returns the [Address] string removing any address prefixes. */ fun Address.toSanitizedString(): String = toString() .removePrefix("bitcoincash:") .removePrefix("bchtest:") /** True when this is a native currency for the network. */ fun Currency.isNative() = type.equals("native", true) /** True when this is an erc20 token for the Ethereum network. */ fun Currency.isErc20() = type.equals("erc20", true) /** True when this is Ethereum. */ fun Currency.isEthereum() = code.isEthereum() && !isErc20() fun Currency.isBitcoin() = code.isBitcoin() fun Currency.isBitcoinCash() = code.isBitcoinCash() /** Returns the [Transfer]'s hash or an empty string. */ fun Transfer.hashString(): String = checkNotNull(hash.orNull()).toString() .let { hash -> val isEthHash = wallet.currency.run { isErc20() || isEthereum() } when { isEthHash -> hash else -> hash.removePrefix("0x") } } /** Returns the [Address] object for [address] from the [Wallet]'s [Network]*/ fun Wallet.addressFor(address: String): Address? { return Address.create(address, walletManager.network).orNull() } /** * By default [com.breadwallet.corecrypto.WalletManager.getDefaultNetworkFee] * is used for the [networkFee]. */ suspend fun Wallet.estimateFee( address: Address, amount: Amount, networkFee: NetworkFee = walletManager.defaultNetworkFee ): TransferFeeBasis = suspendCoroutine { continuation -> val handler = object : CompletionHandler<TransferFeeBasis, FeeEstimationError> { override fun handleData(data: TransferFeeBasis) { continuation.resume(data) } override fun handleError(error: FeeEstimationError) { continuation.resumeWithException(error) } } estimateFee(address, amount, networkFee, handler) } suspend fun WalletManager.createSweeper( wallet: Wallet, key: Key ): WalletSweeper = suspendCoroutine { continuation -> val handler = object : CompletionHandler<WalletSweeper, WalletSweeperError> { override fun handleData(sweeper: WalletSweeper) { continuation.resume(sweeper) } override fun handleError(error: WalletSweeperError) { continuation.resumeWithException(error) } } createSweeper(wallet, key, handler) } suspend fun WalletSweeper.estimateFee(networkFee: NetworkFee): TransferFeeBasis = suspendCoroutine { continuation -> val handler = object : CompletionHandler<TransferFeeBasis, FeeEstimationError> { override fun handleData(feeBasis: TransferFeeBasis) { continuation.resume(feeBasis) } override fun handleError(error: FeeEstimationError) { continuation.resumeWithException(error) } } estimate(networkFee, handler) } private const val ECONOMY_FEE_HOURS = 10L private const val REGULAR_FEE_HOURS = 1L enum class TransferSpeed(val targetTime: Long) { ECONOMY(TimeUnit.HOURS.toMillis(ECONOMY_FEE_HOURS)), REGULAR(TimeUnit.HOURS.toMillis(REGULAR_FEE_HOURS)), PRIORITY(0L); } fun Wallet.feeForSpeed(speed: TransferSpeed): NetworkFee { val fees = walletManager.network.fees return when (fees.size) { 1 -> fees.single() else -> fees.minBy { fee -> (fee.confirmationTimeInMilliseconds.toLong() - speed.targetTime).absoluteValue } ?: walletManager.defaultNetworkFee } } // TODO: Move somewhere UI related fun BigDecimal.formatCryptoForUi( currencyCode: String, scale: Int = WalletDisplayUtils.MAX_DECIMAL_PLACES_FOR_UI, negate: Boolean = false ): String { val amount = if (negate) negate() else this val currencyFormat = DecimalFormat.getCurrencyInstance(Locale.getDefault()) as DecimalFormat val decimalFormatSymbols = currencyFormat.decimalFormatSymbols currencyFormat.isGroupingUsed = true currencyFormat.roundingMode = BRConstants.ROUNDING_MODE decimalFormatSymbols.currencySymbol = "" currencyFormat.decimalFormatSymbols = decimalFormatSymbols currencyFormat.maximumFractionDigits = scale currencyFormat.minimumFractionDigits = 0 return "${currencyFormat.format(amount)} ${currencyCode.toUpperCase()}" } // TODO: Move somewhere UI related fun BigDecimal.formatFiatForUi(currencyCode: String): String { val currencyFormat = NumberFormat.getCurrencyInstance(Locale.getDefault()) as DecimalFormat val decimalFormatSymbols = currencyFormat.decimalFormatSymbols currencyFormat.isGroupingUsed = true currencyFormat.roundingMode = BRConstants.ROUNDING_MODE try { val currency = java.util.Currency.getInstance(currencyCode) val symbol = currency.symbol decimalFormatSymbols.currencySymbol = symbol currencyFormat.decimalFormatSymbols = decimalFormatSymbols currencyFormat.negativePrefix = "-$symbol" currencyFormat.maximumFractionDigits = currency.defaultFractionDigits currencyFormat.minimumFractionDigits = currency.defaultFractionDigits } catch (e: IllegalArgumentException) { logError("Illegal Currency code: $currencyCode") } return currencyFormat.format(this) } val Wallet.currencyId: String get() = currency.uids fun List<Wallet>.filterByCurrencyIds(currencyIds: List<String>) = filter { wallet -> currencyIds.any { it.equals( wallet.currencyId, true ) } } /** Returns the [Wallet] with the given [currencyId] or null. */ fun List<Wallet>.findByCurrencyId(currencyId: String) = find { it.currencyId.equals(currencyId, true) } /** Returns true if any of the [Wallet]s is for the given [currencyId]. */ fun List<Wallet>.containsCurrency(currencyId: String) = findByCurrencyId(currencyId) != null /** Returns true if the [WalletManager]'s [Network] supports the given [currencyId]. */ fun WalletManager.networkContainsCurrency(currencyId: String) = network.containsCurrency(currencyId) /** Returns the [Currency] if the [WalletManager]'s [Network] supports the given [currencyId], null otherwise. */ fun WalletManager.findCurrency(currencyId: String) = network.findCurrency(currencyId) /** Returns true if the [Network] supports the given [currencyId]. */ fun Network.containsCurrency(currencyId: String) = findCurrency(currencyId) != null /** Returns the [Currency] if the [Network] supports the given [currencyId], null otherwise. */ fun Network.findCurrency(currencyId: String) = currencies.find { networkCurrency -> networkCurrency.uids.equals( currencyId, true ) } /** Returns the [Currency] code if the [Transfer] is a ETH fee transfer, blank otherwise. */ fun Transfer.feeForToken(): String { val issuerCode = findIssuerCurrency() return when { !wallet.walletManager.currency.isEthereum() -> "" issuerCode == null || issuerCode.isEthereum() -> "" else -> issuerCode.code } } /** Returns the [Currency] for the issuer matching the target address, null otherwise. */ fun Transfer.findIssuerCurrency() = wallet.walletManager.network.currencies.find { networkCurrency -> networkCurrency .issuer .or("") .equals(target.get().toSanitizedString(), true) } fun WalletManagerState.isTracked() = type == WalletManagerState.Type.CONNECTED || type == WalletManagerState.Type.SYNCING /** Returns [Wallet] [Flow] sorted by [displayOrderCurrencyIds]. */ fun Flow<List<Wallet>>.applyDisplayOrder(displayOrderCurrencyIds: Flow<List<String>>) = combine(displayOrderCurrencyIds) { systemWallets, currencyIds -> currencyIds.mapNotNull { systemWallets.findByCurrencyId(it) } } /** Returns the url scheme for a payment request with this wallet. */ val Wallet.urlScheme: String? get() = when { currency.code.isEthereum() || currency.isErc20() -> "ethereum" currency.code.isRipple() -> "xrp" currency.code.isBitcoin() -> "bitcoin" currency.code.isBitcoinCash() -> when { BuildConfig.BITCOIN_TESTNET -> "bchtest" else -> "bitcoincash" } else -> null } val Wallet.urlSchemes: List<String> get() = when { currency.code.isRipple() -> listOf(urlScheme!!, "xrpl", "ripple") else -> urlScheme?.run(::listOf) ?: emptyList() } /** Creates a [WalletManager] using the appropriate address scheme and [WalletManagerMode]. */ fun System.createWalletManager( network: Network, managerMode: WalletManagerMode?, currencies: Set<Currency>, addressScheme: AddressScheme? = getAddressScheme(network) ) { val wmMode = when { network.currency.isBitcoinCash() -> WalletManagerMode.API_ONLY managerMode == null -> network.defaultWalletManagerMode network.supportsWalletManagerMode(managerMode) -> managerMode else -> network.defaultWalletManagerMode } createWalletManager(network, wmMode, addressScheme, currencies) } /** Return the [AddressScheme] to be used by the given network */ fun System.getAddressScheme(network: Network): AddressScheme { return when { network.currency.code.isBitcoin() -> { if (BRSharedPrefs.getIsSegwitEnabled()) { AddressScheme.BTC_SEGWIT } else { AddressScheme.BTC_LEGACY } } else -> network.defaultAddressScheme } } /** Return a [NetworkPeer] pointing to the given address */ fun Network.getPeerOrNull(node: String): NetworkPeer? { val nodeInfo = node.split(":") if (nodeInfo.isEmpty()) return null val address = nodeInfo[0] val port = if (nodeInfo.size > 1) { UnsignedInteger.valueOf(nodeInfo[1]) } else { UnsignedInteger.valueOf(DEFAULT_PORT) } return createPeer(address, port, null).orNull() } /** True when the [Transfer] was received. */ fun Transfer.isReceived(): Boolean = direction == TransferDirection.RECEIVED fun Transfer.getSize(): Double? { val currencyCode = wallet.currency.code return when { currencyCode.isBitcoin() || currencyCode.isBitcoinCash() -> (confirmedFeeBasis.orNull() ?: estimatedFeeBasis.orNull())?.costFactor else -> null } } /** Returns a [Flow] providing the default [WalletManagerMode] from [System] for a given [currencyId]. */ fun Flow<System>.getDefaultWalletManagerMode(currencyId: String): Flow<WalletManagerMode> = mapNotNull { system -> system.networks .find { it.containsCurrency(currencyId) } ?.run { defaultWalletManagerMode } } /** Returns the default [Unit] for a given [Wallet] */ val Wallet.defaultUnit: Unit get() = walletManager .network .defaultUnitFor(currency) .get() /** Returns the base [Unit] for a given [Wallet] */ val Wallet.baseUnit: Unit get() = walletManager .network .baseUnitFor(currency) .get()
5
null
1
1
8a25940586c472b10d765f6805be502a0c477986
14,436
groestlwallet-android
MIT License
compiler/testData/diagnostics/tests/obsoleteInsufficientDescription.kt
JetBrains
3,432,266
false
null
// ISSUE: KT-59567 // WITH_STDLIB class SomeClass() { fun someFunction() { } suspend fun someSuspendingFunction() { } } fun main() { val someObject = SomeClass() val someSuspendingFunctionReference = someObject::someSuspendingFunction sequence<Int> { println("a function: ${someObject::someFunction}") println("a suspending function: ${someObject::<!ILLEGAL_RESTRICTED_SUSPENDING_FUNCTION_CALL!>someSuspendingFunction<!>}") println("a suspending function: $someSuspendingFunctionReference") } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
556
kotlin
Apache License 2.0
app/src/main/kotlin/my/application/ecogreen/SetUpChooser.kt
hyojin2
375,578,819
false
{"ASP.NET": 181725, "Kotlin": 77574, "Java": 37048}
package my.application.ecogreen import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import com.google.android.material.bottomsheet.BottomSheetDialogFragment import kotlinx.android.synthetic.main.set_up_chooser.* class SetUpChooser : BottomSheetDialogFragment() { interface SetUpChooserNotifierInterface{ fun applicationOnClick() fun deleteUserOnClick() //갤러리 버튼 클리 식 호출 } var setUpChooserNotifierInterface : SetUpChooserNotifierInterface? = null fun addNotifier(listener: SetUpChooserNotifierInterface){ //disuse waste activity에서 호출 예정이라서 private 아님. setUpChooserNotifierInterface = listener } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.set_up_chooser, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setupListener() } private fun setupListener(){ applications.setOnClickListener { setUpChooserNotifierInterface?.applicationOnClick() } delete_user.setOnClickListener { setUpChooserNotifierInterface?.deleteUserOnClick() } } }
0
ASP.NET
0
0
eca1715a6f4f533162b6c724e5943c3dff3ffc86
1,402
BARO_AndroidStudio
Apache License 2.0
app/src/main/java/com/github/braillesystems/learnbraille/ui/screens/practice/CardViewModel.kt
braille-systems
246,795,546
false
null
package com.github.braillesystems.learnbraille.ui.screens.practice import android.app.Application import androidx.lifecycle.* import com.github.braillesystems.learnbraille.data.dsl.ALL_CARDS_DECK_ID import com.github.braillesystems.learnbraille.data.entities.* import com.github.braillesystems.learnbraille.data.repository.MutableActionsRepository import com.github.braillesystems.learnbraille.data.repository.MutablePracticeRepository import com.github.braillesystems.learnbraille.data.repository.PreferenceRepository import com.github.braillesystems.learnbraille.ui.screens.DotsChecker import com.github.braillesystems.learnbraille.ui.screens.MutableDotsChecker import com.github.braillesystems.learnbraille.utils.retryN import com.github.braillesystems.learnbraille.utils.scope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import timber.log.Timber import java.util.* import java.util.concurrent.ArrayBlockingQueue class CardViewModelFactory( private val practiceRepository: MutablePracticeRepository, private val actionsRepository: MutableActionsRepository, private val preferenceRepository: PreferenceRepository, private val application: Application, private val getEnteredDots: () -> BrailleDots ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T = if (modelClass.isAssignableFrom(CardViewModel::class.java)) { @Suppress("UNCHECKED_CAST") CardViewModel( practiceRepository, actionsRepository, preferenceRepository, application, getEnteredDots ) as T } else { throw IllegalArgumentException("Unknown ViewModel class") } } class CardViewModel( private val practiceRepository: MutablePracticeRepository, private val actionsRepository: MutableActionsRepository, private val preferenceRepository: PreferenceRepository, application: Application, private val getEnteredDots: () -> BrailleDots, private val dotsChecker: MutableDotsChecker = MutableDotsChecker.create() ) : AndroidViewModel(application), DotsChecker by dotsChecker { private val _symbol = MutableLiveData<MaterialData>() val symbol: LiveData<MaterialData> get() = _symbol private val _deckTag = MutableLiveData<String>() val deckTag: LiveData<String> get() = _deckTag var nTries: Int = 0 private set var nCorrect: Int = 0 private set var expectedDots: BrailleDots? = null private set private val job = Job() private val uiScope = scope(job) private val nSkipMaterials = 2 private val materialsQueue: Queue<MaterialData> = ArrayBlockingQueue(nSkipMaterials) init { Timber.i("Initialize practice view model") initializeCard(firstTime = true) dotsChecker.apply { getEnteredDots = [email protected] getExpectedDots = { expectedDots } onCheckHandler = { if (dotsChecker.state == DotsChecker.State.INPUT) { nTries++ } } onCorrectHandler = { initializeCard() nCorrect++ uiScope.launch { actionsRepository.addAction(PracticeSubmission(isCorrect = true)) } } onHintHandler = { uiScope.launch { actionsRepository.addAction(PracticeHintAction) } } onIncorrectHandler = { uiScope.launch { actionsRepository.addAction(PracticeSubmission(isCorrect = false)) } } } } override fun onCleared() { super.onCleared() job.cancel() } private fun initializeCard(firstTime: Boolean = false) = uiScope.launch { // If `use only known materials` turned on and current deck became unavailable if (preferenceRepository.practiceUseOnlyKnownMaterials && practiceRepository.randomKnownMaterial() == null ) { practiceRepository.currentDeckId = ALL_CARDS_DECK_ID } if (firstTime) { val deck = practiceRepository.currentDeck() _deckTag.value = deck.tag } val material = retryN(5) { val m = nextMaterial() if (m.data in materialsQueue) null else m } ?: nextMaterial() if (material.data !in materialsQueue) { if (materialsQueue.size == nSkipMaterials) materialsQueue.poll() materialsQueue.add(material.data) } material.data.let { _symbol.value = it expectedDots = when (it) { is OneBrailleSymbol -> it.brailleDots } } } private suspend fun nextMaterial(): Material = if (preferenceRepository.practiceUseOnlyKnownMaterials) { practiceRepository.randomKnownMaterial() } else { practiceRepository.randomMaterial() } ?: error("Current deck should not be empty") }
35
null
3
9
e7e41e88d814aa4f7dd118ed023cdd6f955d53e5
5,206
learn-braille
Apache License 2.0
tools/plugin/gradle-plugin/plugin-build/plugin/src/main/java/dev/elide/buildtools/gradle/plugin/tasks/EmbeddedJsBuildTask.kt
elide-dev
506,113,888
false
null
package dev.elide.buildtools.gradle.plugin.tasks import com.github.gradle.node.task.NodeTask import com.google.protobuf.Timestamp import dev.elide.buildtools.gradle.plugin.BuildMode import dev.elide.buildtools.gradle.plugin.ElideExtension import dev.elide.buildtools.gradle.plugin.cfg.ElideJsHandler import dev.elide.buildtools.gradle.plugin.cfg.StaticValues import dev.elide.buildtools.gradle.plugin.js.BundleTarget import dev.elide.buildtools.gradle.plugin.js.BundleTool import dev.elide.buildtools.gradle.plugin.js.BundleType import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.file.DuplicatesStrategy import org.gradle.api.file.RegularFileProperty import org.gradle.api.plugins.BasePlugin import org.gradle.api.plugins.ExtensionAware import org.gradle.api.provider.ListProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Copy import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Optional import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.options.Option import org.gradle.configurationcache.extensions.capitalized import org.jetbrains.kotlin.gradle.dsl.KotlinJsProjectExtension import org.jetbrains.kotlin.gradle.plugin.KotlinJsCompilerType import org.jetbrains.kotlin.gradle.targets.js.npm.NpmDependencyExtension import tools.elide.assets.* import tools.elide.assets.EmbeddedScriptMetadataKt.jsScriptMetadata import java.io.File import java.io.FileNotFoundException import java.io.IOException import java.nio.charset.StandardCharsets import java.time.Instant /** Task which builds JavaScript targets for embedded use with Elide. */ @Suppress("unused") public abstract class EmbeddedJsBuildTask : BundleSpecTask<EmbeddedScript, EmbeddedBundleSpec>() { public companion object { private const val TASK_NAME: String = "bundleEmbeddedJs" private val defaultTargetMode: BuildMode = BuildMode.DEVELOPMENT private const val defaultTargetModeName: String = BuildMode.DEVELOPMENT_NAME private val defaultTargetType: BundleTarget = BundleTarget.EMBEDDED private const val defaultTargetTypeName: String = BundleTarget.EMBEDDED_NAME private const val defaultEcmaVersion: String = "2022" private const val defaultLibraryName: String = "embedded" private const val defaultEntrypointName: String = "main.mjs" private const val defaultOutputConfig: String = "embedded-js/compile.mjs" private const val defaultProcessShim: String = "embedded-js/shim.process.js" private const val esbuildConfigTemplatePath: String = "/dev/elide/buildtools/js/esbuild-wrapper.mjs.hbs" internal const val processShimTemplatePath: String = "/dev/elide/buildtools/js/process-wrapper.js.hbs" // Determine whether the JS bundle task is eligible to run for the given project / extension pair. @JvmStatic public fun isEligible(extension: ElideExtension, project: Project): Boolean { // we enable the JS build extension in two cases: // // 1) the user has installed the KotlinJS plugin and the Elide plugin. based on whether KotlinJS is // configured for Node or Browser targets, and the presence of the NodeJS plugin, it either builds in // `EMBEDDED` or `WEB` mode. // 2) the user has installed the Elide plugin, and configured a JS block. in this case, the JS block will // tell us the intended target and tool. based on these values, the NodeJS or KotlinJS plugins may be // applied on behalf of the user. return ( project.plugins.hasPlugin("org.jetbrains.kotlin.js") || extension.hasJsTarget() ) } // Apply plugins which are required to run before the JS bundle task. @JvmStatic public fun applyPlugins(node: Boolean, project: Project, cbk: () -> Unit) { applyPlugin(project, "org.jetbrains.kotlin.js") { if (node) { applyPlugin(project, "com.github.node-gradle.node") { cbk.invoke() } } else { cbk.invoke() } } } // After determining the task is eligible, install it in the given project with the provided extension settings. @JvmStatic public fun install(extension: ElideExtension, project: Project) { // apply NPM deps for tooling injectDeps(project) // determine whether we're running an embedded build, in which case the Node plugin is applied as well. val isEmbedded = ( extension.js.bundleTarget.get() == BundleTarget.EMBEDDED ) // apply requisite plugins applyPlugins(isEmbedded, project) { installTasks( extension, project, ) } } // Build and install tasks within the scope of applied required plugins. @JvmStatic public fun installTasks(extension: ElideExtension, project: Project) { // resolve the inflate-runtime task installed on the root project, or if there is not one, create it. val inflateRuntime = resolveInflateRuntimeTask(project, extension) // load JS plugin, configure with output, connect outputs to embedded build project.extensions.configure(KotlinJsProjectExtension::class.java) { jsExt -> val elideJsExt = extension.js val hasNode = project.plugins.hasPlugin( "com.github.node-gradle.node" ) jsExt.js(KotlinJsCompilerType.IR) { if (hasNode || elideJsExt.bundleTarget.get() == BundleTarget.EMBEDDED) { nodejs { binaries.executable() } } else { browser { binaries.executable() } } } // resolve JS IR link task that we just set up val compileProdKotlinJs = resolveJsIrLinkTask( project ) // resolve embedded sources at `ssr/ssr.js` val fetchBuildSources = project.tasks.create("prepareEmbeddedJsBuild", Copy::class.java) { it.dependsOn(compileProdKotlinJs) it.from(compileProdKotlinJs.outputs.files.files) { copySpec -> copySpec.duplicatesStrategy = DuplicatesStrategy.EXCLUDE } @Suppress("deprecation") it.from(compileProdKotlinJs.outputFileProperty) { copySpec -> copySpec.rename { "ssr.js" } } it.into( "${project.buildDir}/ssr" ) } val target = elideJsExt.bundleTarget.get() val tool = elideJsExt.bundleTool.get() setup( project, fetchBuildSources, compileProdKotlinJs, tool, target, extension, elideJsExt, inflateRuntime, ) } } // Load an embedded resource from the plugin JAR. @JvmStatic private fun loadEmbedded(filename: String): String { return (EmbeddedJsBuildTask::class.java.getResourceAsStream( filename ) ?: throw FileNotFoundException( "Failed to locate embedded plugin resource: '$filename'" )).bufferedReader( StandardCharsets.UTF_8 ).readText() } // Inject plugin dependencies required for JS builds. @JvmStatic internal fun injectDeps(project: Project) { // make sure node plugin is applied project.plugins.apply("com.github.node-gradle.node") project.dependencies.apply { (this as ExtensionAware).extensions.configure(NpmDependencyExtension::class.java) { npm -> add("implementation", npm("esbuild", Versions.esbuild)) add("implementation", npm("prepack", Versions.prepack)) add("implementation", npm("buffer", Versions.buffer)) add("implementation", npm("web-streams-polyfill", Versions.webstreams)) } } } // Setup build tasks for the provided project. @Suppress("LongParameterList") @JvmStatic public fun setup( project: Project, fetchSources: Copy, kotlinJsLink: Task, tool: BundleTool, target: BundleTarget, extension: ElideExtension, jsExtension: ElideJsHandler, inflateRuntime: InflateRuntimeTask, ) { if (tool == BundleTool.ESBUILD && target == BundleTarget.EMBEDDED) { BuildMode.values().forEach { mode -> setupEmbeddedEsbuildTask( mode, project, fetchSources, kotlinJsLink, jsExtension, inflateRuntime, ) } setupEsbuildEntrypointTask( project, extension, ) } else if (tool == BundleTool.WEBPACK && target != BundleTarget.EMBEDDED) { BuildMode.values().forEach { mode -> setupBrowserWebpackBuildTask( mode, project, fetchSources, kotlinJsLink, extension, jsExtension, ) } } else error( "Unsupported bundle tool/target combination: $tool/$target" ) } @JvmStatic public fun setupEsbuildEntrypointTask(project: Project, extension: ElideExtension) { project.afterEvaluate { val activeMode = extension.mode val targetBundleTask = "generate${activeMode.name.lowercase().capitalized()}EsBuildConfig" val genSpecTaskName = "generate${activeMode.name.lowercase().capitalized()}EmbeddedJsSpec" val targetEmbeddedTask = "${activeMode.name.lowercase()}EmbeddedExecutable" // create a synthesized distribution as an output val mainDist = project.configurations.create("elideSsrDist") { it.isCanBeConsumed = true it.isCanBeResolved = false } project.artifacts.apply { add( mainDist.name, project.tasks.named(targetEmbeddedTask).map { it.outputs.files.files.single() }, ) add( mainDist.name, project.tasks.named(genSpecTaskName).map { it.outputs.files.files.single() }, ) } project.tasks.create(TASK_NAME) { it.dependsOn(genSpecTaskName) it.dependsOn(targetBundleTask) it.dependsOn(targetEmbeddedTask) } project.tasks.named("assemble") { it.dependsOn(TASK_NAME) } } } @Suppress("LongParameterList", "LongMethod") @JvmStatic public fun setupEmbeddedEsbuildTask( mode: BuildMode, project: Project, fetchSources: Copy, kotlinJsLink: Task, jsExtension: ElideJsHandler, inflateRuntime: InflateRuntimeTask, ) { val modeName = mode.name.lowercase().capitalized() val targetBundleTask = "generate${modeName}EsBuildConfig" val buildTask = project.tasks.create(targetBundleTask, EmbeddedJsBuildTask::class.java) { // setup deps it.dependsOn(project.tasks.named("productionExecutableCompileSync")) it.dependsOn(kotlinJsLink) it.dependsOn(fetchSources) it.dependsOn(inflateRuntime) // setup attrs it.group = "other" it.mode = mode it.tool = jsExtension.bundleTool.get() it.target = jsExtension.bundleTarget.get() it.entryFile.set(fetchSources.destinationDir / "ssr.js") it.libraryName = jsExtension.libraryName.get() // setup properties it.outputBundleName.set(buildString { append("elide-ssr") append(".mjs") }) it.outputOptimizedName.set(buildString { append("elide-ssr") append(".mjs") }) it.outputBundleFolder.set( File("${project.buildDir}/distributions").absolutePath ) it.processShim.set( File("${project.buildDir}/esbuild/process-shim.${modeName.lowercase()}.js") ) it.outputConfig.set( File("${project.buildDir}/esbuild/esbuild.${modeName.lowercase()}.mjs") ) it.modulesFolders.set(listOf( File(inflateRuntime.modulesPath.get().absolutePath), File("${project.rootProject.buildDir}/js/node_modules"), File("${project.rootProject.projectDir}/node_modules"), )) val defaultOptimize = mode == BuildMode.PRODUCTION it.minify = jsExtension.minify.get() ?: defaultOptimize it.prepack = jsExtension.prepack.get() ?: defaultOptimize project.afterEvaluate { _ -> val esbuildTpl = jsExtension.esbuildConfig.get() val esbuildConfigTemplate = if (esbuildTpl == null) { loadEmbedded(esbuildConfigTemplatePath) } else { // if we are given a template, we must load it as a file try { esbuildTpl.readText(StandardCharsets.UTF_8) } catch (err: IOException) { throw IllegalArgumentException( "Failed to load esbuild config template from ${esbuildTpl.absolutePath}", err, ) } } it.configTemplate.set(esbuildConfigTemplate) } } val targetEmbeddedTask = "${modeName.lowercase()}EmbeddedExecutable" val nodeBuildTask = project.tasks.create( targetEmbeddedTask, NodeTask::class.java ) { it.group = "distribution" it.dependsOn(buildTask) it.dependsOn(buildTask.processShim) it.dependsOn(buildTask.outputConfig) it.dependsOn(inflateRuntime) it.script.set(buildTask.outputConfig.get()) it.inputs.files( buildTask.processShim, buildTask.outputConfig, fetchSources.destinationDir / "ssr.js", ) if (mode == BuildMode.PRODUCTION) { it.outputs.file(buildTask.outputOptimizedFile.absolutePath) } else { it.outputs.file(buildTask.outputBundleFile.absolutePath) } } val catalogGenTask = installCatalogTask( targetBundleTask, mode, project, listOf( targetBundleTask, targetEmbeddedTask, ) ) // create a distribution for the bundle val nodeDist = project.configurations.create("elideSsrDist${mode.name.lowercase().capitalized()}") { it.isCanBeConsumed = true it.isCanBeResolved = false } // add to project artifacts project.artifacts.add( nodeDist.name, nodeBuildTask.outputs.files.files.single() ) project.artifacts.add( nodeDist.name, catalogGenTask.outputs.files.files.single() ) } @Suppress("UNUSED_PARAMETER", "LongParameterList") @JvmStatic public fun setupBrowserWebpackBuildTask( mode: BuildMode, project: Project, fetchSources: Copy, kotlinJsLink: Task, extension: ElideExtension, jsExtension: ElideJsHandler, ) { project.logger.lifecycle("Configuring embedded 'webpack' task for CSR...") } } init { description = "Configures an application target for use with ESBuild or Webpack" group = BasePlugin.BUILD_GROUP // set defaults with(project) { // set the default output bundle folder outputBundleFolder.set( file("$buildDir\\$defaultOutputBundleFolder").absolutePath ) // setup asset spec outputSpecName.set( StaticValues.defaultEncoding.fileNamed("embedded") ) bundleEncoding.set( StaticValues.defaultEncoding ) // set the default output bundle name and optimized bundle name outputBundleName.set( defaultOutputBundleName ) outputOptimizedName.set( defaultOutputOptimizedName ) // set the default output config file/wrapper outputConfig.set(file( "$buildDir/$defaultOutputConfig" )) // set the default process shim file processShim.set(file( "$buildDir/$defaultProcessShim" )) } } /** Build mode to apply for targets. */ @get:Input @get:Option( option = "mode", description = ( "Build mode: `${BuildMode.DEVELOPMENT_NAME}` or `${BuildMode.PRODUCTION_NAME}`. Passed to Node. " + "Defaults to `$defaultTargetModeName`." ), ) internal var mode: BuildMode = defaultTargetMode /** Target build type to apply for JS targets. */ @get:Input @get:Option( option = "target", description = ( "Type of target to build: `${BundleTarget.EMBEDDED_NAME}`, `${BundleTarget.NODE_NAME}`, or " + "`${BundleTarget.WEB_NAME}`. Defaults to `$defaultTargetTypeName`." ), ) internal var target: BundleTarget = defaultTargetType /** Target format type for the bundle. */ @get:Input @get:Option( option = "format", description = ( "Format of the bundle to build: `${BundleType.IIFE_NAME}`, `${BundleType.COMMON_JS_NAME}`, or " + "`${BundleType.ESM_NAME}`. Defaults to the value implied by `target`." ), ) internal var format: BundleType = target.bundleType /** Tool to use for building this target.. */ @get:Input @get:Option( option = "tool", description = ( "Tool to use for JS bundling. Supported values are `${BundleTool.ESBUILD_NAME}` or " + "`${BundleTool.WEBPACK_NAME}`. Defaults to the value stipulated by `target`." ), ) internal var tool: BundleTool = target.bundleTool /** Target format type for the bundle. */ @get:Input @get:Option( option = "ecma", description = "ECMA standard level to target. Defaults to `$defaultEcmaVersion`.", ) internal var ecma: String = defaultEcmaVersion /** Name to use within the JAR for this JS bundle. */ @get:Input @get:Option( option = "libraryName", description = "Name to use for the output JavaScript bundle. Defaults to `$defaultLibraryName`.", ) internal var libraryName: String = defaultLibraryName /** Output file for the ESBuild/Webpack configuration, as applicable. */ @get:OutputFile @get:Option( option = "outputConfig", description = "Where to put the generated build configuration or entrypoint. Typically managed by the plugin." ) internal abstract val outputConfig: Property<File> /** Output file for the `process` shim, as applicable. */ @get:OutputFile @get:Option( option = "processShim", description = "Where to put the generated Node process shim. Typically managed by the plugin.", ) internal abstract val processShim: Property<File> /** Name to give the bundle being compiled by this task. */ @get:Input @get:Option( option = "outputBundleName", description = "Name to give the bundle built by this task. Typically managed by the plugin.", ) internal abstract val outputBundleName: Property<String> /** Name to give the pre-compiled and optimized version of the output bundle. */ @get:Input @get:Option( option = "outputOptimizedName", description = "Name to give the optimized bundle built by this task. Typically managed by the plugin.", ) internal abstract val outputOptimizedName: Property<String> /** Input Node Modules directory for installed dependencies. */ @get:InputFiles @get:Option( option = "modulesFolders", description = "Locations of `node_modules` to load from when bundling. Typically managed by the plugin.", ) internal abstract val modulesFolders: ListProperty<File> /** Platform value to specify when invoking ESBuild. */ @get:Input @get:Option( option = "platform", description = "Platform to specify when invoking ESBuild. Defaults to the value stipulated by `target`.", ) internal var platform: String = target.platform /** Whether to perform minification on the target bundle. */ @get:Input @get:Option( option = "minify", description = "Whether to minify the target bundle. Defaults to the value stipulate by `mode`.", ) internal var minify: Boolean = mode.minify /** Whether to perform pre-packing on the target bundle. */ @get:Input @get:Option( option = "prepack", description = "Whether to run the bundle through `prepack`. Only applies to server-side SSR bundles.", ) internal var prepack: Boolean = false /** Whether to generate a single output bundle. */ @get:Input @get:Option( option = "bundle", description = "Whether to generate a bundle. Defaults to `true` and typically needs to stay `true`.", ) internal var bundle: Boolean = true /** Entrypoint file to begin the compilation from. */ @Optional @get:InputFile @get:Option( option = "entryFileName", description = "Name of the source file which should serve as the entrypoint for this build.", ) public var entryFileName: String? = null /** Entrypoint file to begin the compilation from. */ @get:InputFile @get:Option( option = "entryFile", description = "Source file which should serve as the entrypoint for this build.", ) internal abstract val entryFile: RegularFileProperty /** Template content to use for the ESBuild wrapper. Please use with caution, this is not documented yet. */ @get:Option( option = "configTemplate", description = "Configuration template to use for 'esbuild'.", ) @get:Input internal abstract val configTemplate: Property<String> /** Template content to use for the `process` shim. Please use with caution, this is not documented yet. */ @get:Input internal val processShimTemplate = loadEmbedded( processShimTemplatePath ) private fun templateVar(varname: String): String = "{{${varname.uppercase()}}}" private fun replaceVar(subj: String, varname: String, value: String): String = subj.replace(templateVar(varname), value) private fun renderTemplateVals(tpl: String): String { var subj = tpl listOf( "entry" to entryFile.asFile.get().absolutePath.fixSlashes(), "mode" to mode.name.lowercase().trim(), "format" to format.symbol, "bundle" to bundle.toString(), "minify" to minify.toString(), "prepack" to prepack.toString(), "libname" to libraryName, "platform" to platform.trim().lowercase(), "process" to processShim.get().absolutePath.fixSlashes(), "outfile" to outputBundleFile.absolutePath.fixSlashes(), "prepack_outfile" to outputOptimizedFile.absolutePath.fixSlashes(), "nodepath" to modulesFolders.get().joinToString(",") { "'${it.absolutePath.fixSlashes()}'" }, ).forEach { subj = replaceVar(subj, it.first, it.second) } return subj } /** @inheritDoc */ override fun buildAssetCatalog(builderOp: EmbeddedBundleSpec.() -> Unit): EmbeddedScript { return embeddedScript(builderOp) } /** @inheritDoc */ override fun assetCatalog(): EmbeddedBundleSpec.() -> Unit = { module = libraryName filename = outputBundleName.get() language = EmbeddedScriptLanguage.JS lastModified = Timestamp.newBuilder().setSeconds(Instant.now().epochSecond).build() metadata = embeddedScriptMetadata { javascript = jsScriptMetadata { level = when (ecma) { "5" -> EmbeddedScriptMetadata.JsScriptMetadata.JsLanguageLevel.ES5 "6" -> EmbeddedScriptMetadata.JsScriptMetadata.JsLanguageLevel.ES6 "2017" -> EmbeddedScriptMetadata.JsScriptMetadata.JsLanguageLevel.ES2017 "2018" -> EmbeddedScriptMetadata.JsScriptMetadata.JsLanguageLevel.ES2018 "2019" -> EmbeddedScriptMetadata.JsScriptMetadata.JsLanguageLevel.ES2019 "2020" -> EmbeddedScriptMetadata.JsScriptMetadata.JsLanguageLevel.ES2020 "2021" -> EmbeddedScriptMetadata.JsScriptMetadata.JsLanguageLevel.ES2021 "2022" -> EmbeddedScriptMetadata.JsScriptMetadata.JsLanguageLevel.ES2022 else -> EmbeddedScriptMetadata.JsScriptMetadata.JsLanguageLevel.ES2022 } } } } /** @inheritDoc */ override fun runAction() { processShim.get().writeText( renderTemplateVals(processShimTemplate) ) outputConfig.get().writeText( renderTemplateVals(configTemplate.get()) ) logger.lifecycle( "Config generated for `${tool.name.lowercase()}` (mode: ${mode.name}): " + outputConfig.get().path ) } }
75
null
5
97
652036fb4e8394e8ad1aced2f4bbfaa9e00a5181
27,728
elide
MIT License
bot/engine/src/main/kotlin/fr/vsct/tock/bot/admin/message/MessageConfiguration.kt
curinator
207,578,255
true
{"Kotlin": 3731711, "TypeScript": 587148, "HTML": 201325, "CSS": 60702, "JavaScript": 4142, "Shell": 2610}
/* * Copyright (C) 2017 VSCT * * 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 fr.vsct.tock.bot.admin.message import fr.vsct.tock.bot.engine.BotBus import fr.vsct.tock.bot.engine.action.Action import fr.vsct.tock.bot.engine.event.EventType import fr.vsct.tock.bot.engine.user.PlayerId import fr.vsct.tock.translator.UserInterfaceType import java.util.Locale /** * */ interface MessageConfiguration { val eventType: EventType val delay: Long fun toAction(bus: BotBus): Action = toAction( bus.userId, bus.applicationId, bus.botId, bus.userLocale, bus.userInterfaceType) fun toAction(playerId: PlayerId, applicationId: String, recipientId: PlayerId, locale: Locale, userInterfaceType: UserInterfaceType): Action }
0
null
0
1
dd37ec79ba29b4f6aacff704ca3400b41df47efb
1,393
tock
Apache License 2.0
src/main/kotlin/com/art/absencecalendar/ApiImpl.kt
ArturAdamczyk
147,968,333
false
null
package com.art.absencecalendar import com.art.absencecalendar.absence.Absence import com.art.absencecalendar.absence.AbsenceDaoImpl import com.art.absencecalendar.absence.type.AbsenceType import com.art.absencecalendar.absence.type.AbsenceTypeDao import com.art.absencecalendar.absence.user.UserDao import com.art.absencecalendar.interfaces.Api import com.art.absencecalendar.department.Department import com.art.absencecalendar.department.DepartmentDao import com.art.absencecalendar.employee.Employee import com.art.absencecalendar.gender.Gender import com.art.absencecalendar.employee.EmployeeDao import com.art.absencecalendar.employee.EmployeeDaoImpl import com.art.absencecalendar.employee.position.EmployeePosition import com.art.absencecalendar.employee.position.EmployeePositionDao import com.art.absencecalendar.gender.GenderDao class ApiImpl( private val employeeDao: EmployeeDao = EmployeeDaoImpl(), private val absenceDao: AbsenceDaoImpl = AbsenceDaoImpl(), private val genderDao: GenderDao = GenderDao(), private val departmentDao: DepartmentDao = DepartmentDao(), private val employeePosistionDao: EmployeePositionDao = EmployeePositionDao(), private val absenceTypesDao: AbsenceTypeDao = AbsenceTypeDao(), private val userDao: UserDao = UserDao() ): Api { override fun getAbsentEmployees(date: String): List<Employee>{ return employeeDao.getAbsentEmployees(date) } override fun getPresentEmployees(date: String): List<Employee>{ return employeeDao.getPresentEmployees(date) } override fun getEmployees(beginDate: String, endDate: String, absenceType: String, position: String, department: String): List<Employee>{ return employeeDao.getEmployees(beginDate, endDate, absenceType, position, department) } override fun getEmployee(id: String): Employee{ return employeeDao.findById(id.toInt()) } override fun getGenders(): List<Gender>{ return genderDao.genders.values.toList() } override fun getEmployeePositions(): List<EmployeePosition>{ return employeePosistionDao.employeePositions.values.toList() } override fun getDepartments(): List<Department>{ return departmentDao.departments.values.toList() } override fun getAbsenceTypes(): List<AbsenceType>{ return absenceTypesDao.absenceTypes.values.toList() } override fun addEmployee(employee: Employee): Boolean{ return employeeDao.save(employee) } override fun archiveEmployee(id: String): Boolean{ return employeeDao.delete(id.toInt()) } override fun addAbsence(absence: Absence): Boolean{ return absenceDao.save(absence) } override fun deleteAbsence(id: String): Boolean{ return absenceDao.delete(id.toInt()) } }
1
null
1
1
e238e45dbbfb51a2d58af4d1d9bd8e7b4e3b0bd1
2,843
AbsenceCalendarApi
MIT License
src/main/kotlin/uk/gov/justice/digital/assessments/config/CacheConfiguration.kt
ministryofjustice
289,880,556
false
null
package uk.gov.justice.digital.assessments.config import com.fasterxml.jackson.annotation.JsonTypeInfo import com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.datatype.jdk8.Jdk8Module import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule import com.fasterxml.jackson.module.kotlin.KotlinModule import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.redis.cache.RedisCacheConfiguration import org.springframework.data.redis.cache.RedisCacheManager.RedisCacheManagerBuilder import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair import org.springframework.data.redis.serializer.StringRedisSerializer import uk.gov.justice.digital.assessments.config.CacheConstants.ASSESSMENT_CACHE_KEY import uk.gov.justice.digital.assessments.config.CacheConstants.ASSESSMENT_SUMMARY_CACHE_KEY import uk.gov.justice.digital.assessments.config.CacheConstants.LIST_QUESTION_GROUPS_CACHE_KEY import uk.gov.justice.digital.assessments.config.CacheConstants.QUESTIONS_FOR_ASSESSMENT_TYPE_CACHE_KEY import uk.gov.justice.digital.assessments.config.CacheConstants.QUESTION_CACHE_KEY import uk.gov.justice.digital.assessments.config.CacheConstants.QUESTION_GROUP_CONTENTS_CACHE_KEY import uk.gov.justice.digital.assessments.config.CacheConstants.QUESTION_GROUP_SECTIONS_CACHE_KEY import java.time.Duration @Configuration class CacheConfiguration { @Value("\${cache.ttlDays.referenceData}") var referenceDataCacheTtlDays: Long = 1 @Value("\${cache.ttlMinutes.default}") var defaultCacheTtlMinutes: Long = 5 @Bean fun defaultRedisCacheConfiguration(): RedisCacheConfiguration { return getDefaultCacheConfiguration() .entryTtl(Duration.ofMinutes(defaultCacheTtlMinutes)) } private fun getDefaultCacheConfiguration(): RedisCacheConfiguration { return RedisCacheConfiguration.defaultCacheConfig() .disableCachingNullValues() .serializeKeysWith(SerializationPair.fromSerializer(StringRedisSerializer())) .serializeValuesWith(SerializationPair.fromSerializer(GenericJackson2JsonRedisSerializer(objectMapper().configure(FAIL_ON_UNKNOWN_PROPERTIES, false)))) } private fun objectMapper(): ObjectMapper { return ObjectMapper() .registerModules(Jdk8Module(), JavaTimeModule(), KotlinModule()) .apply { activateDefaultTyping(polymorphicTypeValidator, ObjectMapper.DefaultTyping.EVERYTHING, JsonTypeInfo.As.PROPERTY) } } @Bean fun cacheManagerBuilderCustomizer(): RedisCacheManagerBuilderCustomizer? { return RedisCacheManagerBuilderCustomizer { builder: RedisCacheManagerBuilder -> val defaultConfigWithRefDataTtl = getDefaultCacheConfiguration() .entryTtl(Duration.ofDays(referenceDataCacheTtlDays)) arrayOf( ASSESSMENT_CACHE_KEY, QUESTIONS_FOR_ASSESSMENT_TYPE_CACHE_KEY, ASSESSMENT_SUMMARY_CACHE_KEY, QUESTION_CACHE_KEY, LIST_QUESTION_GROUPS_CACHE_KEY, QUESTION_GROUP_CONTENTS_CACHE_KEY, QUESTION_GROUP_SECTIONS_CACHE_KEY ).forEach { builder.withCacheConfiguration(it, defaultConfigWithRefDataTtl) } } } }
5
Kotlin
1
2
48c61ad5cc311c7e8ef0d1dcd8822849c6ba2066
3,546
hmpps-assessments-api
MIT License
defitrack-protocols/iron-bank/src/main/java/io/defitrack/protocol/compound/IronBankService.kt
decentri-fi
426,174,152
false
null
package io.defitrack.protocol.compound import org.springframework.stereotype.Service interface IronBankService { fun getComptroller(): String }
16
Kotlin
6
5
e4640223e69c30f986b8b4238e026202b08a5548
149
defi-hub
MIT License
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/Battery1Bar.kt
karakum-team
387,062,541
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/Battery1Bar") @file:JsNonModule package mui.icons.material @JsName("default") external val Battery1Bar: SvgIconComponent
0
null
5
35
60404a8933357df15ecfd8caf6e83258962ca909
204
mui-kotlin
Apache License 2.0
app/src/main/java/org/lenchan139/lightbrowser/UrlFromExternalActivity.kt
lenchan139
76,649,147
false
null
package org.lenchan139.lightbrowser import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log class UrlFromExternalActivity : AppCompatActivity() { override fun onPause() { super.onPause() overridePendingTransition(0, 0) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //setContentView(R.layout.activity_url_from_external); var inURL: String? if (intent.data != null) { Log.v(getString(R.string.KEY_INURL_INTENT), intent.data.toString()) inURL = intent.data.toString() val intent = Intent(this, MainActivity::class.java) intent.putExtra("InURL", inURL) intent.putExtra("InURLFromExternal", true) startActivity(intent) inURL = null } finish() } }
0
Kotlin
1
2
59aa9b36b645e1046e31e942a7cf60f1ca6d4596
927
LightBrowser
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/paymentcryptography/CfnKey.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 142794926}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.paymentcryptography import io.cloudshiftdev.awscdk.CfnResource import io.cloudshiftdev.awscdk.CfnTag import io.cloudshiftdev.awscdk.IInspectable import io.cloudshiftdev.awscdk.IResolvable import io.cloudshiftdev.awscdk.ITaggableV2 import io.cloudshiftdev.awscdk.TagManager import io.cloudshiftdev.awscdk.TreeInspector import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Any import kotlin.Boolean import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlin.jvm.JvmName import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct import software.constructs.Construct as SoftwareConstructsConstruct /** * Creates an AWS Payment Cryptography key, a logical representation of a cryptographic key, that is * unique in your account and AWS Region . * * You use keys for cryptographic functions such as encryption and decryption. * * In addition to the key material used in cryptographic operations, an AWS Payment Cryptography key * includes metadata such as the key ARN, key usage, key origin, creation date, description, and key * state. * * When you create a key, you specify both immutable and mutable data about the key. The immutable * data contains key attributes that define the scope and cryptographic operations that you can perform * using the key, for example key class (example: `SYMMETRIC_KEY` ), key algorithm (example: * `TDES_2KEY` ), key usage (example: `TR31_P0_PIN_ENCRYPTION_KEY` ) and key modes of use (example: * `Encrypt` ). For information about valid combinations of key attributes, see [Understanding key * attributes](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-validattributes.html) * in the *AWS Payment Cryptography User Guide* . The mutable data contained within a key includes * usage timestamp and key deletion timestamp and can be modified after creation. * * AWS Payment Cryptography binds key attributes to keys using key blocks when you store or export * them. AWS Payment Cryptography stores the key contents wrapped and never stores or transmits them in * the clear. * * *Cross-account use* : This operation can't be used across different AWS accounts. * * *Related operations:* * * * * [DeleteKey](https://docs.aws.amazon.com/payment-cryptography/latest/APIReference/API_DeleteKey.html) * * [GetKey](https://docs.aws.amazon.com/payment-cryptography/latest/APIReference/API_GetKey.html) * * * [ListKeys](https://docs.aws.amazon.com/payment-cryptography/latest/APIReference/API_ListKeys.html) * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.paymentcryptography.*; * CfnKey cfnKey = CfnKey.Builder.create(this, "MyCfnKey") * .exportable(false) * .keyAttributes(KeyAttributesProperty.builder() * .keyAlgorithm("keyAlgorithm") * .keyClass("keyClass") * .keyModesOfUse(KeyModesOfUseProperty.builder() * .decrypt(false) * .deriveKey(false) * .encrypt(false) * .generate(false) * .noRestrictions(false) * .sign(false) * .unwrap(false) * .verify(false) * .wrap(false) * .build()) * .keyUsage("keyUsage") * .build()) * // the properties below are optional * .enabled(false) * .keyCheckValueAlgorithm("keyCheckValueAlgorithm") * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html) */ public open class CfnKey( cdkObject: software.amazon.awscdk.services.paymentcryptography.CfnKey, ) : CfnResource(cdkObject), IInspectable, ITaggableV2 { public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnKeyProps, ) : this(software.amazon.awscdk.services.paymentcryptography.CfnKey(scope.let(CloudshiftdevConstructsConstruct.Companion::unwrap), id, props.let(CfnKeyProps.Companion::unwrap)) ) public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnKeyProps.Builder.() -> Unit, ) : this(scope, id, CfnKeyProps(props) ) /** * */ public open fun attrKeyIdentifier(): String = unwrap(this).getAttrKeyIdentifier() /** * The source of the key material. * * For keys created within AWS Payment Cryptography, the value is `AWS_PAYMENT_CRYPTOGRAPHY` . For * keys imported into AWS Payment Cryptography, the value is `EXTERNAL` . */ public open fun attrKeyOrigin(): String = unwrap(this).getAttrKeyOrigin() /** * The state of key that is being created or deleted. */ public open fun attrKeyState(): String = unwrap(this).getAttrKeyState() /** * Tag Manager which manages the tags for this resource. */ public override fun cdkTagManager(): TagManager = unwrap(this).getCdkTagManager().let(TagManager::wrap) /** * Specifies whether the key is enabled. */ public open fun enabled(): Any? = unwrap(this).getEnabled() /** * Specifies whether the key is enabled. */ public open fun enabled(`value`: Boolean) { unwrap(this).setEnabled(`value`) } /** * Specifies whether the key is enabled. */ public open fun enabled(`value`: IResolvable) { unwrap(this).setEnabled(`value`.let(IResolvable.Companion::unwrap)) } /** * Specifies whether the key is exportable. */ public open fun exportable(): Any = unwrap(this).getExportable() /** * Specifies whether the key is exportable. */ public open fun exportable(`value`: Boolean) { unwrap(this).setExportable(`value`) } /** * Specifies whether the key is exportable. */ public open fun exportable(`value`: IResolvable) { unwrap(this).setExportable(`value`.let(IResolvable.Companion::unwrap)) } /** * Examines the CloudFormation resource and discloses attributes. * * @param inspector tree inspector to collect and process attributes. */ public override fun inspect(inspector: TreeInspector) { unwrap(this).inspect(inspector.let(TreeInspector.Companion::unwrap)) } /** * The role of the key, the algorithm it supports, and the cryptographic operations allowed with * the key. */ public open fun keyAttributes(): Any = unwrap(this).getKeyAttributes() /** * The role of the key, the algorithm it supports, and the cryptographic operations allowed with * the key. */ public open fun keyAttributes(`value`: IResolvable) { unwrap(this).setKeyAttributes(`value`.let(IResolvable.Companion::unwrap)) } /** * The role of the key, the algorithm it supports, and the cryptographic operations allowed with * the key. */ public open fun keyAttributes(`value`: KeyAttributesProperty) { unwrap(this).setKeyAttributes(`value`.let(KeyAttributesProperty.Companion::unwrap)) } /** * The role of the key, the algorithm it supports, and the cryptographic operations allowed with * the key. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("<KEY>") public open fun keyAttributes(`value`: KeyAttributesProperty.Builder.() -> Unit): Unit = keyAttributes(KeyAttributesProperty(`value`)) /** * The algorithm that AWS Payment Cryptography uses to calculate the key check value (KCV). */ public open fun keyCheckValueAlgorithm(): String? = unwrap(this).getKeyCheckValueAlgorithm() /** * The algorithm that AWS Payment Cryptography uses to calculate the key check value (KCV). */ public open fun keyCheckValueAlgorithm(`value`: String) { unwrap(this).setKeyCheckValueAlgorithm(`value`) } /** * */ public open fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList() /** * */ public open fun tags(`value`: List<CfnTag>) { unwrap(this).setTags(`value`.map(CfnTag.Companion::unwrap)) } /** * */ public open fun tags(vararg `value`: CfnTag): Unit = tags(`value`.toList()) /** * A fluent builder for [io.cloudshiftdev.awscdk.services.paymentcryptography.CfnKey]. */ @CdkDslMarker public interface Builder { /** * Specifies whether the key is enabled. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-enabled) * @param enabled Specifies whether the key is enabled. */ public fun enabled(enabled: Boolean) /** * Specifies whether the key is enabled. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-enabled) * @param enabled Specifies whether the key is enabled. */ public fun enabled(enabled: IResolvable) /** * Specifies whether the key is exportable. * * This data is immutable after the key is created. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-exportable) * @param exportable Specifies whether the key is exportable. */ public fun exportable(exportable: Boolean) /** * Specifies whether the key is exportable. * * This data is immutable after the key is created. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-exportable) * @param exportable Specifies whether the key is exportable. */ public fun exportable(exportable: IResolvable) /** * The role of the key, the algorithm it supports, and the cryptographic operations allowed with * the key. * * This data is immutable after the key is created. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-keyattributes) * @param keyAttributes The role of the key, the algorithm it supports, and the cryptographic * operations allowed with the key. */ public fun keyAttributes(keyAttributes: IResolvable) /** * The role of the key, the algorithm it supports, and the cryptographic operations allowed with * the key. * * This data is immutable after the key is created. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-keyattributes) * @param keyAttributes The role of the key, the algorithm it supports, and the cryptographic * operations allowed with the key. */ public fun keyAttributes(keyAttributes: KeyAttributesProperty) /** * The role of the key, the algorithm it supports, and the cryptographic operations allowed with * the key. * * This data is immutable after the key is created. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-keyattributes) * @param keyAttributes The role of the key, the algorithm it supports, and the cryptographic * operations allowed with the key. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("b714e115fede5ef3cfc396081ec9e7e8a294e32945c0ebcf6fea9f595646bc32") public fun keyAttributes(keyAttributes: KeyAttributesProperty.Builder.() -> Unit) /** * The algorithm that AWS Payment Cryptography uses to calculate the key check value (KCV). * * It is used to validate the key integrity. * * For TDES keys, the KCV is computed by encrypting 8 bytes, each with value of zero, with the * key to be checked and retaining the 3 highest order bytes of the encrypted result. For AES keys, * the KCV is computed using a CMAC algorithm where the input data is 16 bytes of zero and * retaining the 3 highest order bytes of the encrypted result. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-keycheckvaluealgorithm) * @param keyCheckValueAlgorithm The algorithm that AWS Payment Cryptography uses to calculate * the key check value (KCV). */ public fun keyCheckValueAlgorithm(keyCheckValueAlgorithm: String) /** * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-tags) * @param tags */ public fun tags(tags: List<CfnTag>) /** * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-tags) * @param tags */ public fun tags(vararg tags: CfnTag) } private class BuilderImpl( scope: SoftwareConstructsConstruct, id: String, ) : Builder { private val cdkBuilder: software.amazon.awscdk.services.paymentcryptography.CfnKey.Builder = software.amazon.awscdk.services.paymentcryptography.CfnKey.Builder.create(scope, id) /** * Specifies whether the key is enabled. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-enabled) * @param enabled Specifies whether the key is enabled. */ override fun enabled(enabled: Boolean) { cdkBuilder.enabled(enabled) } /** * Specifies whether the key is enabled. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-enabled) * @param enabled Specifies whether the key is enabled. */ override fun enabled(enabled: IResolvable) { cdkBuilder.enabled(enabled.let(IResolvable.Companion::unwrap)) } /** * Specifies whether the key is exportable. * * This data is immutable after the key is created. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-exportable) * @param exportable Specifies whether the key is exportable. */ override fun exportable(exportable: Boolean) { cdkBuilder.exportable(exportable) } /** * Specifies whether the key is exportable. * * This data is immutable after the key is created. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-exportable) * @param exportable Specifies whether the key is exportable. */ override fun exportable(exportable: IResolvable) { cdkBuilder.exportable(exportable.let(IResolvable.Companion::unwrap)) } /** * The role of the key, the algorithm it supports, and the cryptographic operations allowed with * the key. * * This data is immutable after the key is created. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-keyattributes) * @param keyAttributes The role of the key, the algorithm it supports, and the cryptographic * operations allowed with the key. */ override fun keyAttributes(keyAttributes: IResolvable) { cdkBuilder.keyAttributes(keyAttributes.let(IResolvable.Companion::unwrap)) } /** * The role of the key, the algorithm it supports, and the cryptographic operations allowed with * the key. * * This data is immutable after the key is created. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-keyattributes) * @param keyAttributes The role of the key, the algorithm it supports, and the cryptographic * operations allowed with the key. */ override fun keyAttributes(keyAttributes: KeyAttributesProperty) { cdkBuilder.keyAttributes(keyAttributes.let(KeyAttributesProperty.Companion::unwrap)) } /** * The role of the key, the algorithm it supports, and the cryptographic operations allowed with * the key. * * This data is immutable after the key is created. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-keyattributes) * @param keyAttributes The role of the key, the algorithm it supports, and the cryptographic * operations allowed with the key. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("b714e115fede5ef3cfc396081ec9e7e8a294e32945c0ebcf6fea9f595646bc32") override fun keyAttributes(keyAttributes: KeyAttributesProperty.Builder.() -> Unit): Unit = keyAttributes(KeyAttributesProperty(keyAttributes)) /** * The algorithm that AWS Payment Cryptography uses to calculate the key check value (KCV). * * It is used to validate the key integrity. * * For TDES keys, the KCV is computed by encrypting 8 bytes, each with value of zero, with the * key to be checked and retaining the 3 highest order bytes of the encrypted result. For AES keys, * the KCV is computed using a CMAC algorithm where the input data is 16 bytes of zero and * retaining the 3 highest order bytes of the encrypted result. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-keycheckvaluealgorithm) * @param keyCheckValueAlgorithm The algorithm that AWS Payment Cryptography uses to calculate * the key check value (KCV). */ override fun keyCheckValueAlgorithm(keyCheckValueAlgorithm: String) { cdkBuilder.keyCheckValueAlgorithm(keyCheckValueAlgorithm) } /** * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-tags) * @param tags */ override fun tags(tags: List<CfnTag>) { cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap)) } /** * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-paymentcryptography-key.html#cfn-paymentcryptography-key-tags) * @param tags */ override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList()) public fun build(): software.amazon.awscdk.services.paymentcryptography.CfnKey = cdkBuilder.build() } public companion object { public val CFN_RESOURCE_TYPE_NAME: String = software.amazon.awscdk.services.paymentcryptography.CfnKey.CFN_RESOURCE_TYPE_NAME public operator fun invoke( scope: CloudshiftdevConstructsConstruct, id: String, block: Builder.() -> Unit = {}, ): CfnKey { val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id) return CfnKey(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.paymentcryptography.CfnKey): CfnKey = CfnKey(cdkObject) internal fun unwrap(wrapped: CfnKey): software.amazon.awscdk.services.paymentcryptography.CfnKey = wrapped.cdkObject as software.amazon.awscdk.services.paymentcryptography.CfnKey } /** * The role of the key, the algorithm it supports, and the cryptographic operations allowed with * the key. * * This data is immutable after the key is created. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.paymentcryptography.*; * KeyAttributesProperty keyAttributesProperty = KeyAttributesProperty.builder() * .keyAlgorithm("keyAlgorithm") * .keyClass("keyClass") * .keyModesOfUse(KeyModesOfUseProperty.builder() * .decrypt(false) * .deriveKey(false) * .encrypt(false) * .generate(false) * .noRestrictions(false) * .sign(false) * .unwrap(false) * .verify(false) * .wrap(false) * .build()) * .keyUsage("keyUsage") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keyattributes.html) */ public interface KeyAttributesProperty { /** * The key algorithm to be use during creation of an AWS Payment Cryptography key. * * For symmetric keys, AWS Payment Cryptography supports `AES` and `TDES` algorithms. For * asymmetric keys, AWS Payment Cryptography supports `RSA` and `ECC_NIST` algorithms. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keyattributes.html#cfn-paymentcryptography-key-keyattributes-keyalgorithm) */ public fun keyAlgorithm(): String /** * The type of AWS Payment Cryptography key to create, which determines the classification of the * cryptographic method and whether AWS Payment Cryptography key contains a symmetric key or an * asymmetric key pair. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keyattributes.html#cfn-paymentcryptography-key-keyattributes-keyclass) */ public fun keyClass(): String /** * The list of cryptographic operations that you can perform using the key. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keyattributes.html#cfn-paymentcryptography-key-keyattributes-keymodesofuse) */ public fun keyModesOfUse(): Any /** * The cryptographic usage of an AWS Payment Cryptography key as defined in section A.5.2 of the * TR-31 spec. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keyattributes.html#cfn-paymentcryptography-key-keyattributes-keyusage) */ public fun keyUsage(): String /** * A builder for [KeyAttributesProperty] */ @CdkDslMarker public interface Builder { /** * @param keyAlgorithm The key algorithm to be use during creation of an AWS Payment * Cryptography key. * For symmetric keys, AWS Payment Cryptography supports `AES` and `TDES` algorithms. For * asymmetric keys, AWS Payment Cryptography supports `RSA` and `ECC_NIST` algorithms. */ public fun keyAlgorithm(keyAlgorithm: String) /** * @param keyClass The type of AWS Payment Cryptography key to create, which determines the * classification of the cryptographic method and whether AWS Payment Cryptography key contains a * symmetric key or an asymmetric key pair. */ public fun keyClass(keyClass: String) /** * @param keyModesOfUse The list of cryptographic operations that you can perform using the * key. */ public fun keyModesOfUse(keyModesOfUse: IResolvable) /** * @param keyModesOfUse The list of cryptographic operations that you can perform using the * key. */ public fun keyModesOfUse(keyModesOfUse: KeyModesOfUseProperty) /** * @param keyModesOfUse The list of cryptographic operations that you can perform using the * key. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("25a602ed6f1cd3a1ce5e2f351feb461dfef93b682f0079085cb41723ee28bb1a") public fun keyModesOfUse(keyModesOfUse: KeyModesOfUseProperty.Builder.() -> Unit) /** * @param keyUsage The cryptographic usage of an AWS Payment Cryptography key as defined in * section A.5.2 of the TR-31 spec. */ public fun keyUsage(keyUsage: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyAttributesProperty.Builder = software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyAttributesProperty.builder() /** * @param keyAlgorithm The key algorithm to be use during creation of an AWS Payment * Cryptography key. * For symmetric keys, AWS Payment Cryptography supports `AES` and `TDES` algorithms. For * asymmetric keys, AWS Payment Cryptography supports `RSA` and `ECC_NIST` algorithms. */ override fun keyAlgorithm(keyAlgorithm: String) { cdkBuilder.keyAlgorithm(keyAlgorithm) } /** * @param keyClass The type of AWS Payment Cryptography key to create, which determines the * classification of the cryptographic method and whether AWS Payment Cryptography key contains a * symmetric key or an asymmetric key pair. */ override fun keyClass(keyClass: String) { cdkBuilder.keyClass(keyClass) } /** * @param keyModesOfUse The list of cryptographic operations that you can perform using the * key. */ override fun keyModesOfUse(keyModesOfUse: IResolvable) { cdkBuilder.keyModesOfUse(keyModesOfUse.let(IResolvable.Companion::unwrap)) } /** * @param keyModesOfUse The list of cryptographic operations that you can perform using the * key. */ override fun keyModesOfUse(keyModesOfUse: KeyModesOfUseProperty) { cdkBuilder.keyModesOfUse(keyModesOfUse.let(KeyModesOfUseProperty.Companion::unwrap)) } /** * @param keyModesOfUse The list of cryptographic operations that you can perform using the * key. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("25a602ed6f1cd3a1ce5e2f351feb461dfef93b682f0079085cb41723ee28bb1a") override fun keyModesOfUse(keyModesOfUse: KeyModesOfUseProperty.Builder.() -> Unit): Unit = keyModesOfUse(KeyModesOfUseProperty(keyModesOfUse)) /** * @param keyUsage The cryptographic usage of an AWS Payment Cryptography key as defined in * section A.5.2 of the TR-31 spec. */ override fun keyUsage(keyUsage: String) { cdkBuilder.keyUsage(keyUsage) } public fun build(): software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyAttributesProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyAttributesProperty, ) : CdkObject(cdkObject), KeyAttributesProperty { /** * The key algorithm to be use during creation of an AWS Payment Cryptography key. * * For symmetric keys, AWS Payment Cryptography supports `AES` and `TDES` algorithms. For * asymmetric keys, AWS Payment Cryptography supports `RSA` and `ECC_NIST` algorithms. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keyattributes.html#cfn-paymentcryptography-key-keyattributes-keyalgorithm) */ override fun keyAlgorithm(): String = unwrap(this).getKeyAlgorithm() /** * The type of AWS Payment Cryptography key to create, which determines the classification of * the cryptographic method and whether AWS Payment Cryptography key contains a symmetric key or * an asymmetric key pair. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keyattributes.html#cfn-paymentcryptography-key-keyattributes-keyclass) */ override fun keyClass(): String = unwrap(this).getKeyClass() /** * The list of cryptographic operations that you can perform using the key. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keyattributes.html#cfn-paymentcryptography-key-keyattributes-keymodesofuse) */ override fun keyModesOfUse(): Any = unwrap(this).getKeyModesOfUse() /** * The cryptographic usage of an AWS Payment Cryptography key as defined in section A.5.2 of * the TR-31 spec. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keyattributes.html#cfn-paymentcryptography-key-keyattributes-keyusage) */ override fun keyUsage(): String = unwrap(this).getKeyUsage() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): KeyAttributesProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyAttributesProperty): KeyAttributesProperty = CdkObjectWrappers.wrap(cdkObject) as? KeyAttributesProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: KeyAttributesProperty): software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyAttributesProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyAttributesProperty } } /** * The list of cryptographic operations that you can perform using the key. * * The modes of use are defined in section A.5.3 of the TR-31 spec. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.paymentcryptography.*; * KeyModesOfUseProperty keyModesOfUseProperty = KeyModesOfUseProperty.builder() * .decrypt(false) * .deriveKey(false) * .encrypt(false) * .generate(false) * .noRestrictions(false) * .sign(false) * .unwrap(false) * .verify(false) * .wrap(false) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html) */ public interface KeyModesOfUseProperty { /** * Specifies whether an AWS Payment Cryptography key can be used to decrypt data. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-decrypt) */ public fun decrypt(): Any? = unwrap(this).getDecrypt() /** * Specifies whether an AWS Payment Cryptography key can be used to derive new keys. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-derivekey) */ public fun deriveKey(): Any? = unwrap(this).getDeriveKey() /** * Specifies whether an AWS Payment Cryptography key can be used to encrypt data. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-encrypt) */ public fun encrypt(): Any? = unwrap(this).getEncrypt() /** * Specifies whether an AWS Payment Cryptography key can be used to generate and verify other * card and PIN verification keys. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-generate) */ public fun generate(): Any? = unwrap(this).getGenerate() /** * Specifies whether an AWS Payment Cryptography key has no special restrictions other than the * restrictions implied by `KeyUsage` . * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-norestrictions) */ public fun noRestrictions(): Any? = unwrap(this).getNoRestrictions() /** * Specifies whether an AWS Payment Cryptography key can be used for signing. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-sign) */ public fun sign(): Any? = unwrap(this).getSign() /** * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-unwrap) */ public fun unwrap(): Any? = unwrap(this).getUnwrap() /** * Specifies whether an AWS Payment Cryptography key can be used to verify signatures. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-verify) */ public fun verify(): Any? = unwrap(this).getVerify() /** * Specifies whether an AWS Payment Cryptography key can be used to wrap other keys. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-wrap) */ public fun wrap(): Any? = unwrap(this).getWrap() /** * A builder for [KeyModesOfUseProperty] */ @CdkDslMarker public interface Builder { /** * @param decrypt Specifies whether an AWS Payment Cryptography key can be used to decrypt * data. */ public fun decrypt(decrypt: Boolean) /** * @param decrypt Specifies whether an AWS Payment Cryptography key can be used to decrypt * data. */ public fun decrypt(decrypt: IResolvable) /** * @param deriveKey Specifies whether an AWS Payment Cryptography key can be used to derive new * keys. */ public fun deriveKey(deriveKey: Boolean) /** * @param deriveKey Specifies whether an AWS Payment Cryptography key can be used to derive new * keys. */ public fun deriveKey(deriveKey: IResolvable) /** * @param encrypt Specifies whether an AWS Payment Cryptography key can be used to encrypt * data. */ public fun encrypt(encrypt: Boolean) /** * @param encrypt Specifies whether an AWS Payment Cryptography key can be used to encrypt * data. */ public fun encrypt(encrypt: IResolvable) /** * @param generate Specifies whether an AWS Payment Cryptography key can be used to generate * and verify other card and PIN verification keys. */ public fun generate(generate: Boolean) /** * @param generate Specifies whether an AWS Payment Cryptography key can be used to generate * and verify other card and PIN verification keys. */ public fun generate(generate: IResolvable) /** * @param noRestrictions Specifies whether an AWS Payment Cryptography key has no special * restrictions other than the restrictions implied by `KeyUsage` . */ public fun noRestrictions(noRestrictions: Boolean) /** * @param noRestrictions Specifies whether an AWS Payment Cryptography key has no special * restrictions other than the restrictions implied by `KeyUsage` . */ public fun noRestrictions(noRestrictions: IResolvable) /** * @param sign Specifies whether an AWS Payment Cryptography key can be used for signing. */ public fun sign(sign: Boolean) /** * @param sign Specifies whether an AWS Payment Cryptography key can be used for signing. */ public fun sign(sign: IResolvable) /** * @param unwrap the value to be set. */ public fun unwrap(unwrap: Boolean) /** * @param unwrap the value to be set. */ public fun unwrap(unwrap: IResolvable) /** * @param verify Specifies whether an AWS Payment Cryptography key can be used to verify * signatures. */ public fun verify(verify: Boolean) /** * @param verify Specifies whether an AWS Payment Cryptography key can be used to verify * signatures. */ public fun verify(verify: IResolvable) /** * @param wrap Specifies whether an AWS Payment Cryptography key can be used to wrap other * keys. */ public fun wrap(wrap: Boolean) /** * @param wrap Specifies whether an AWS Payment Cryptography key can be used to wrap other * keys. */ public fun wrap(wrap: IResolvable) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyModesOfUseProperty.Builder = software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyModesOfUseProperty.builder() /** * @param decrypt Specifies whether an AWS Payment Cryptography key can be used to decrypt * data. */ override fun decrypt(decrypt: Boolean) { cdkBuilder.decrypt(decrypt) } /** * @param decrypt Specifies whether an AWS Payment Cryptography key can be used to decrypt * data. */ override fun decrypt(decrypt: IResolvable) { cdkBuilder.decrypt(decrypt.let(IResolvable.Companion::unwrap)) } /** * @param deriveKey Specifies whether an AWS Payment Cryptography key can be used to derive new * keys. */ override fun deriveKey(deriveKey: Boolean) { cdkBuilder.deriveKey(deriveKey) } /** * @param deriveKey Specifies whether an AWS Payment Cryptography key can be used to derive new * keys. */ override fun deriveKey(deriveKey: IResolvable) { cdkBuilder.deriveKey(deriveKey.let(IResolvable.Companion::unwrap)) } /** * @param encrypt Specifies whether an AWS Payment Cryptography key can be used to encrypt * data. */ override fun encrypt(encrypt: Boolean) { cdkBuilder.encrypt(encrypt) } /** * @param encrypt Specifies whether an AWS Payment Cryptography key can be used to encrypt * data. */ override fun encrypt(encrypt: IResolvable) { cdkBuilder.encrypt(encrypt.let(IResolvable.Companion::unwrap)) } /** * @param generate Specifies whether an AWS Payment Cryptography key can be used to generate * and verify other card and PIN verification keys. */ override fun generate(generate: Boolean) { cdkBuilder.generate(generate) } /** * @param generate Specifies whether an AWS Payment Cryptography key can be used to generate * and verify other card and PIN verification keys. */ override fun generate(generate: IResolvable) { cdkBuilder.generate(generate.let(IResolvable.Companion::unwrap)) } /** * @param noRestrictions Specifies whether an AWS Payment Cryptography key has no special * restrictions other than the restrictions implied by `KeyUsage` . */ override fun noRestrictions(noRestrictions: Boolean) { cdkBuilder.noRestrictions(noRestrictions) } /** * @param noRestrictions Specifies whether an AWS Payment Cryptography key has no special * restrictions other than the restrictions implied by `KeyUsage` . */ override fun noRestrictions(noRestrictions: IResolvable) { cdkBuilder.noRestrictions(noRestrictions.let(IResolvable.Companion::unwrap)) } /** * @param sign Specifies whether an AWS Payment Cryptography key can be used for signing. */ override fun sign(sign: Boolean) { cdkBuilder.sign(sign) } /** * @param sign Specifies whether an AWS Payment Cryptography key can be used for signing. */ override fun sign(sign: IResolvable) { cdkBuilder.sign(sign.let(IResolvable.Companion::unwrap)) } /** * @param unwrap the value to be set. */ override fun unwrap(unwrap: Boolean) { cdkBuilder.unwrap(unwrap) } /** * @param unwrap the value to be set. */ override fun unwrap(unwrap: IResolvable) { cdkBuilder.unwrap(unwrap.let(IResolvable.Companion::unwrap)) } /** * @param verify Specifies whether an AWS Payment Cryptography key can be used to verify * signatures. */ override fun verify(verify: Boolean) { cdkBuilder.verify(verify) } /** * @param verify Specifies whether an AWS Payment Cryptography key can be used to verify * signatures. */ override fun verify(verify: IResolvable) { cdkBuilder.verify(verify.let(IResolvable.Companion::unwrap)) } /** * @param wrap Specifies whether an AWS Payment Cryptography key can be used to wrap other * keys. */ override fun wrap(wrap: Boolean) { cdkBuilder.wrap(wrap) } /** * @param wrap Specifies whether an AWS Payment Cryptography key can be used to wrap other * keys. */ override fun wrap(wrap: IResolvable) { cdkBuilder.wrap(wrap.let(IResolvable.Companion::unwrap)) } public fun build(): software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyModesOfUseProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyModesOfUseProperty, ) : CdkObject(cdkObject), KeyModesOfUseProperty { /** * Specifies whether an AWS Payment Cryptography key can be used to decrypt data. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-decrypt) */ override fun decrypt(): Any? = unwrap(this).getDecrypt() /** * Specifies whether an AWS Payment Cryptography key can be used to derive new keys. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-derivekey) */ override fun deriveKey(): Any? = unwrap(this).getDeriveKey() /** * Specifies whether an AWS Payment Cryptography key can be used to encrypt data. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-encrypt) */ override fun encrypt(): Any? = unwrap(this).getEncrypt() /** * Specifies whether an AWS Payment Cryptography key can be used to generate and verify other * card and PIN verification keys. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-generate) */ override fun generate(): Any? = unwrap(this).getGenerate() /** * Specifies whether an AWS Payment Cryptography key has no special restrictions other than the * restrictions implied by `KeyUsage` . * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-norestrictions) */ override fun noRestrictions(): Any? = unwrap(this).getNoRestrictions() /** * Specifies whether an AWS Payment Cryptography key can be used for signing. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-sign) */ override fun sign(): Any? = unwrap(this).getSign() /** * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-unwrap) */ override fun unwrap(): Any? = unwrap(this).getUnwrap() /** * Specifies whether an AWS Payment Cryptography key can be used to verify signatures. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-verify) */ override fun verify(): Any? = unwrap(this).getVerify() /** * Specifies whether an AWS Payment Cryptography key can be used to wrap other keys. * * Default: - false * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-paymentcryptography-key-keymodesofuse.html#cfn-paymentcryptography-key-keymodesofuse-wrap) */ override fun wrap(): Any? = unwrap(this).getWrap() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): KeyModesOfUseProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyModesOfUseProperty): KeyModesOfUseProperty = CdkObjectWrappers.wrap(cdkObject) as? KeyModesOfUseProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: KeyModesOfUseProperty): software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyModesOfUseProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.paymentcryptography.CfnKey.KeyModesOfUseProperty } } }
0
Kotlin
0
4
9bf6f9403f8b24b070d23a2f895811be72f5d828
47,318
kotlin-cdk-wrapper
Apache License 2.0
app/src/main/java/de/niklasbednarczyk/nbweather/navigation/NBNavigationDrawerItem.kt
NiklasBednarczyk
529,683,941
false
{"Kotlin": 1028822}
package de.niklasbednarczyk.nbweather.navigation import de.niklasbednarczyk.nbweather.core.common.string.NBString import de.niklasbednarczyk.nbweather.core.ui.icons.NBIconModel import de.niklasbednarczyk.nbweather.core.ui.navigation.destination.NBTopLevelDestination import de.niklasbednarczyk.nbweather.core.ui.navigation.destination.NBTopLevelDestinations import de.niklasbednarczyk.nbweather.data.geocoding.models.LocationModelData sealed interface NBNavigationDrawerItem { data object Divider : NBNavigationDrawerItem data class Headline( val label: NBString? ) : NBNavigationDrawerItem sealed interface Item : NBNavigationDrawerItem { val label: NBString? val icon: NBIconModel val selected: Boolean val topLevelDestination: NBTopLevelDestination data class Location( override val label: NBString?, override val icon: NBIconModel, override val selected: Boolean, val location: LocationModelData, ) : Item { override val topLevelDestination: NBTopLevelDestination = NBTopLevelDestinations.Forecast } data class Other( override val label: NBString?, override val icon: NBIconModel, override val topLevelDestination: NBTopLevelDestination ) : Item { override val selected: Boolean get() = false } } }
22
Kotlin
0
1
bd8ac5bae4ed4461e2461b6d89dd67358fdfbdd8
1,463
NBWeather
MIT License
compose/foundation/foundation-newtext/src/commonMain/kotlin/androidx/compose/foundation/newtext/text/copypasta/selection/SimpleLayout.kt
MaxMood96
395,831,835
true
{"Kotlin": 72038273, "Java": 62021571, "C++": 9029994, "Python": 299356, "AIDL": 270753, "Shell": 173288, "HTML": 21175, "ANTLR": 19860, "CMake": 12136, "TypeScript": 7599, "C": 7083, "GLSL": 3842, "Swift": 3153, "JavaScript": 1343}
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.newtext.text.copypasta.selection import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.Layout import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastMap import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract import kotlin.math.max /** * Selection is transparent in terms of measurement and layout and passes the same constraints to * the children. */ @Composable internal fun SimpleLayout(modifier: Modifier = Modifier, content: @Composable () -> Unit) { Layout(modifier = modifier, content = content) { measurables, constraints -> val placeables = measurables.fastMap { measurable -> measurable.measure(constraints) } val width = placeables.fastFold(0) { maxWidth, placeable -> max(maxWidth, (placeable.width)) } val height = placeables.fastFold(0) { minWidth, placeable -> max(minWidth, (placeable.height)) } layout(width, height) { placeables.fastForEach { placeable -> placeable.place(0, 0) } } } } // copypasta from foundation to compile this copypasta @Suppress("BanInlineOptIn") // Treat Kotlin Contracts as non-experimental. @OptIn(ExperimentalContracts::class) internal inline fun <T, R> List<T>.fastFold(initial: R, operation: (acc: R, T) -> R): R { contract { callsInPlace(operation) } var accumulator = initial fastForEach { e -> accumulator = operation(accumulator, e) } return accumulator }
10
Kotlin
0
1
dbae5353c0d623b7e56fd1af3e8f716fb47d2822
2,250
androidx
Apache License 2.0
app/src/main/java/com/gmail/fattazzo/meteo/app/services/WebcamService.kt
fattazzo
182,333,126
false
null
/* * Project: meteo * File: WebcamService.kt * * Created by fattazzo * Copyright © 2019 <NAME>. All rights reserved. * * MIT License * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.gmail.fattazzo.meteo.app.services import android.content.Context import android.util.Log import com.gmail.fattazzo.meteo.data.webcam.Webcams import com.gmail.fattazzo.meteo.preferences.PreferencesService import org.simpleframework.xml.convert.AnnotationStrategy import org.simpleframework.xml.core.Persister import java.io.InputStreamReader import javax.inject.Inject /** * @author fattazzo * * * date: 13/lug/2015 */ class WebcamService @Inject constructor( private val context: Context, private val preferencesService: PreferencesService ) { /** * Carica le webcam presenti. * * @return webcam caricate */ fun caricaWebcam(): Webcams { var webcams: Webcams var inputReader: InputStreamReader? = null try { inputReader = InputStreamReader(context.assets.open("webcam.xml")) val strategy = AnnotationStrategy() val serializer = Persister(strategy) webcams = serializer.read(Webcams::class.java, inputReader, false) val webcamWidgetIds = preferencesService.getWidgetWebcamIds() webcams.webcams.forEach { webcam -> webcam.showInWidget = webcamWidgetIds.indexOf(webcam.id) != -1 } } catch (e: Exception) { Log.e(TAG, "Errore durante la letture del file delle webcam") webcams = Webcams() } finally { inputReader?.close() } return webcams } companion object { private const val TAG = "WebcamXmlParser" } }
1
null
1
1
8345a9a1b0d0dcb87922262c1691cd6ec8d058fc
2,793
meteo
MIT License
presentation/src/main/java/com/nisrulz/example/spacexapi/presentation/features/launch_detail/LaunchDetailScreen.kt
nisrulz
708,230,156
false
null
package com.nisrulz.example.spacexapi.presentation.features.launch_detail import androidx.compose.material3.SnackbarHostState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.nisrulz.example.spacexapi.presentation.features.components.LoadingComponent import com.nisrulz.example.spacexapi.presentation.features.launch_detail.LaunchDetailViewModel.LaunchDetailUiEvent import com.nisrulz.example.spacexapi.presentation.features.launch_detail.LaunchDetailViewModel.LaunchDetailUiState import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.receiveAsFlow @Composable fun LaunchDetailScreen( viewModel: LaunchDetailViewModel = hiltViewModel(), launchId: String, ) { val snackbarHostState = remember { SnackbarHostState() } val state by viewModel.uiState.collectAsStateWithLifecycle() LaunchedEffect(true) { with(viewModel) { getLaunchInfoDetails(launchId) viewModel.eventFlow.receiveAsFlow().collectLatest { when (it) { is LaunchDetailUiEvent.ShowSnackBar -> { snackbarHostState.showSnackbar(message = it.message) } } } } } when (state) { LaunchDetailUiState.Loading -> LoadingComponent() is LaunchDetailUiState.Error -> viewModel.showError((state as LaunchDetailUiState.Error).message) is LaunchDetailUiState.Success -> LaunchDetailSuccessComponent( state = state as LaunchDetailUiState.Success, snackbarHostState = snackbarHostState ) } }
2
null
0
6
47511d9b3af20fa8d69717e23f8acfc704bbadfd
1,847
android-spacex-app
Apache License 2.0
src/app/src/test/kotlin/org/vaccineimpact/orderlyweb/tests/integration_tests/tests/IntegrationTest.kt
vimc
173,126,600
false
null
package org.vaccineimpact.orderlyweb.tests.integration_tests.tests import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import org.assertj.core.api.Assertions import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeAll import org.vaccineimpact.orderlyweb.ContentTypes import org.vaccineimpact.orderlyweb.OrderlyServerClient import org.vaccineimpact.orderlyweb.app_start.main import org.vaccineimpact.orderlyweb.db.AppConfig import org.vaccineimpact.orderlyweb.models.GitCommit import org.vaccineimpact.orderlyweb.models.permissions.ReifiedPermission import org.vaccineimpact.orderlyweb.test_helpers.JSONValidator import org.vaccineimpact.orderlyweb.test_helpers.http.Response import org.vaccineimpact.orderlyweb.tests.integration_tests.APIPermissionChecker import org.vaccineimpact.orderlyweb.tests.integration_tests.WebPermissionChecker import org.vaccineimpact.orderlyweb.tests.integration_tests.helpers.APIRequestHelper import org.vaccineimpact.orderlyweb.tests.integration_tests.helpers.WebRequestHelper import spark.route.HttpMethod import java.io.File abstract class IntegrationTest { val apiRequestHelper = APIRequestHelper() val webRequestHelper = WebRequestHelper() val JSONValidator = JSONValidator() companion object { var appStarted: Boolean = false @BeforeAll @JvmStatic fun startApp() { if (!appStarted) { appStarted = true main(emptyArray()) } } } @BeforeEach fun createDatabase() { println("Copying database from: ${AppConfig()["db.template"]}") val newDbFile = File(AppConfig()["db.location"]) val source = File(AppConfig()["db.template"]) source.copyTo(newDbFile, true) Thread.sleep(1000) } @AfterEach fun deleteDatabases() { File(AppConfig()["db.location"]).delete() } protected fun assertSuccessful(response: Response) { Assertions.assertThat(response.statusCode) .isEqualTo(200) } protected fun assertSuccessfulWithResponseText(response: Response) { Assertions.assertThat(response.statusCode) .withFailMessage(response.text) .isEqualTo(200) } protected fun assertUnauthorized(response: Response, reportName: String) { Assertions.assertThat(response.statusCode) .isEqualTo(403) JSONValidator.validateError(response.text, "forbidden", "You do not have sufficient permissions to access this resource. Missing these permissions: report:${reportName}/reports.read") } protected fun assertJsonContentType(response: Response) { Assertions.assertThat(response.headers["content-type"]).contains("application/json") } protected fun assertHtmlContentType(response: Response) { Assertions.assertThat(response.headers["content-type"]).isEqualTo("text/html") } protected fun assertPlainTextContentType(response: Response) { Assertions.assertThat(response.headers["content-type"]).isEqualTo("text/plain;charset=utf-8") } protected fun assertWebUrlSecured(url: String, requiredPermissions: Set<ReifiedPermission>, contentType: String = ContentTypes.html, method: HttpMethod = HttpMethod.get, postData: Map<String, Any>? = null) { val checker = WebPermissionChecker(url, requiredPermissions, contentType, method, postData) checker.checkPermissionsAreSufficient() for (permission in requiredPermissions) { checker.checkPermissionIsRequired(permission) } } protected fun assertAPIUrlSecured(url: String, requiredPermissions: Set<ReifiedPermission>, contentType: String = ContentTypes.binarydata, method: HttpMethod = HttpMethod.get, postData: Map<String, String>? = null) { val checker = APIPermissionChecker(url, requiredPermissions, contentType, method, postData) checker.checkPermissionsAreSufficient() for (permission in requiredPermissions) { checker.checkPermissionIsRequired(permission) } } protected fun getGitBranchCommit(branch: String): String { val commits = OrderlyServerClient(AppConfig()).get( "/git/commits", context = mock { on { queryString() } doReturn "branch=$branch" } ) return commits.listData(GitCommit::class.java).first().id } }
6
null
4
4
e3a2a8204a3e559e15f1d54e884e8ea1aa798cf0
4,931
orderly-web
MIT License
src/main/kotlin/com/alzakharov/patterns/date/Ca.kt
al-zakharov
508,063,626
false
{"Kotlin": 22276}
package com.alzakharov.patterns.date object Ca { fun apply(date: String) = ( "^((((19|20)(([02468][048])|([13579][26])).02.29))|((20[0-9][0-9])|(19[" + "0-9][0-9])).((((0[1-9])|(1[0-2])).((0[1-9])|(1[0-9])|(2[0-8])))" + "|((((0[13578])|(1[02])).31)|(((0[1,3-9])|(1[0-2])).(29|30)))))\$" ).toRegex().matches(date) }
0
Kotlin
0
0
e80d2853a4546e2493df72b92dd64dd73166fac6
360
kotlin-validators
Apache License 2.0
build-logic/conventionplugins/src/main/kotlin/com/experiment/buildlogic/conventionplugins/KotlinAndroid.kt
aarash709
605,957,736
false
{"Kotlin": 364629, "Shell": 694}
package com.experiment.buildlogic.conventionplugins import com.android.build.api.dsl.CommonExtension import org.gradle.api.JavaVersion import org.gradle.api.Project internal fun Project.configureAndroid( extension: CommonExtension<*, *, *, *, *, *>, ) { extension.apply { compileSdk = 34 defaultConfig { minSdk = 26 } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } } }
3
Kotlin
2
5
1e7b87335f543ac252b622b9217ce833aa8bd2d8
522
Weather
Apache License 2.0
app/src/main/java/jp/juggler/subwaytooter/action/Action_Follow.kt
tateisu
89,120,200
false
null
package jp.juggler.subwaytooter.action import androidx.appcompat.app.AlertDialog import jp.juggler.subwaytooter.ActMain import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.actmain.reloadAccountSetting import jp.juggler.subwaytooter.actmain.showColumnMatchAccount import jp.juggler.subwaytooter.api.* import jp.juggler.subwaytooter.api.entity.* import jp.juggler.subwaytooter.column.ColumnType import jp.juggler.subwaytooter.column.fireRebindAdapterItems import jp.juggler.subwaytooter.column.removeUser import jp.juggler.subwaytooter.dialog.DlgConfirm.confirm import jp.juggler.subwaytooter.dialog.pickAccount import jp.juggler.subwaytooter.table.* import jp.juggler.util.coroutine.launchAndShowError import jp.juggler.util.coroutine.launchMain import jp.juggler.util.log.showToast import jp.juggler.util.network.toFormRequestBody import jp.juggler.util.network.toPost import jp.juggler.util.network.toPostRequestBuilder import jp.juggler.util.ui.dismissSafe import kotlinx.coroutines.CancellationException import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException fun ActMain.clickFollowInfo( pos: Int, accessInfo: SavedAccount, whoRef: TootAccountRef?, forceMenu: Boolean = false, contextMenuOpener: ActMain.(whoRef: TootAccountRef) -> Unit, ) { whoRef ?: return if (forceMenu || accessInfo.isPseudo) { contextMenuOpener(this, whoRef) } else { userProfileLocal(pos, accessInfo, whoRef.get()) } } fun ActMain.clickFollow( pos: Int, accessInfo: SavedAccount, whoRef: TootAccountRef, relation: UserRelation?, ) { relation ?: return val who = whoRef.get() when { accessInfo.isPseudo -> followFromAnotherAccount(pos, accessInfo, who) relation.blocking || relation.muting -> Unit // 何もしない accessInfo.isMisskey && relation.getRequested(who) && !relation.getFollowing(who) -> followRequestDelete( pos, accessInfo, whoRef, callback = cancelFollowRequestCompleteCallback ) relation.getFollowing(who) || relation.getRequested(who) -> follow(pos, accessInfo, whoRef, bFollow = false, callback = unfollowCompleteCallback) else -> follow(pos, accessInfo, whoRef, bFollow = true, callback = followCompleteCallback) } } fun ActMain.clickFollowRequestAccept( accessInfo: SavedAccount, whoRef: TootAccountRef?, accept: Boolean, ) { val who = whoRef?.get() ?: return launchAndShowError { confirm( when { accept -> R.string.follow_accept_confirm else -> R.string.follow_deny_confirm }, daoAcctColor.getNickname(accessInfo, who) ) followRequestAuthorize(accessInfo, whoRef, accept) } } //////////////////////////////////////////////////////////////////////////////////////////////////// fun ActMain.follow( pos: Int, accessInfo: SavedAccount, whoRef: TootAccountRef, bFollow: Boolean = true, bConfirmMoved: Boolean = false, bConfirmed: Boolean = false, callback: () -> Unit = {}, ) { val activity = this@follow val who = whoRef.get() if (accessInfo.isMe(who)) { showToast(false, R.string.it_is_you) return } launchAndShowError { if (!bConfirmMoved && bFollow && who.moved != null) { val selected = suspendCancellableCoroutine { cont -> try { val dialog = AlertDialog.Builder(activity) .setMessage( getString( R.string.jump_moved_user, accessInfo.getFullAcct(who), accessInfo.getFullAcct(who.moved) ) ) .setPositiveButton(R.string.ok) { _, _ -> cont.resume(R.string.ok) } .setNeutralButton(R.string.ignore_suggestion) { _, _ -> cont.resume(R.string.ignore_suggestion) } .setNegativeButton(R.string.cancel, null) .create() dialog.setOnDismissListener { if (cont.isActive) cont.resumeWithException(CancellationException()) } cont.invokeOnCancellation { dialog.dismissSafe() } dialog.show() } catch (ex: Throwable) { cont.resumeWithException(ex) } } when (selected) { R.string.ok -> { userProfileFromAnotherAccount( pos, accessInfo, who.moved ) return@launchAndShowError } R.string.ignore_suggestion -> Unit // fall thru } } else if (!bConfirmed) { if (bFollow && who.locked) { confirm( getString( R.string.confirm_follow_request_who_from, whoRef.decoded_display_name, daoAcctColor.getNickname(accessInfo) ), accessInfo.confirmFollowLocked, ) { newConfirmEnabled -> accessInfo.confirmFollowLocked = newConfirmEnabled daoSavedAccount.save(accessInfo) activity.reloadAccountSetting(accessInfo) } } else if (bFollow) { confirm( getString( R.string.confirm_follow_who_from, whoRef.decoded_display_name, daoAcctColor.getNickname(accessInfo) ), accessInfo.confirmFollow ) { newConfirmEnabled -> accessInfo.confirmFollow = newConfirmEnabled daoSavedAccount.save(accessInfo) activity.reloadAccountSetting(accessInfo) } } else { confirm( getString( R.string.confirm_unfollow_who_from, whoRef.decoded_display_name, daoAcctColor.getNickname(accessInfo) ), accessInfo.confirmUnfollow ) { newConfirmEnabled -> accessInfo.confirmUnfollow = newConfirmEnabled daoSavedAccount.save(accessInfo) activity.reloadAccountSetting(accessInfo) } } } var resultRelation: UserRelation? = null runApiTask(accessInfo, progressStyle = ApiTask.PROGRESS_NONE) { client -> val parser = TootParser(activity, accessInfo) var userId = who.id if (who.isRemote) { // リモートユーザの確認 val skipAccountSync = if (accessInfo.isMisskey) { // Misskey の /users/show はリモートユーザに関して404を返すので // userIdからリモートユーザを照合することはできない。 // ただし検索APIがエラーになるかどうかは未確認 false } else { // https://github.com/tateisu/SubwayTooter/issues/124 // によると、閉じたタンスのユーザを同期しようとすると検索APIがエラーを返す // この問題を回避するため、手持ちのuserIdで照合したユーザのacctが目的のユーザと同じなら // 検索APIを呼び出さないようにする val result = client.request("/api/v1/accounts/$userId") ?: return@runApiTask null who.acct == parser.account(result.jsonObject)?.acct } if (!skipAccountSync) { // 同タンスのIDではなかった場合、検索APIを使う val (result, ar) = client.syncAccountByAcct(accessInfo, who.acct) val user = ar?.get() ?: return@runApiTask result userId = user.id } } if (accessInfo.isMisskey) { client.request( when { bFollow -> "/api/following/create" else -> "/api/following/delete" }, accessInfo.putMisskeyApiToken().apply { put("userId", userId) } .toPostRequestBuilder() )?.also { result -> fun saveFollow(f: Boolean) { val ur = daoUserRelation.load(accessInfo.db_id, userId) ur.following = f daoUserRelation.save1Misskey( System.currentTimeMillis(), accessInfo.db_id, userId.toString(), ur ) resultRelation = ur } val error = result.error when { // success error == null -> saveFollow(bFollow) // already followed/unfollowed error.contains("already following") -> saveFollow(bFollow) error.contains("already not following") -> saveFollow(bFollow) // else something error } } } else { client.request( "/api/v1/accounts/$userId/${if (bFollow) "follow" else "unfollow"}", "".toFormRequestBody().toPost() )?.also { result -> val newRelation = parseItem(result.jsonObject) { TootRelationShip(parser, it) } resultRelation = daoUserRelation.saveUserRelation(accessInfo, newRelation) } } }?.let { result -> val relation = resultRelation when { relation != null -> { when { // 鍵付きアカウントにフォローリクエストを申請した状態 bFollow && relation.getRequested(who) -> showToast(false, R.string.follow_requested) !bFollow && relation.getRequested(who) -> showToast(false, R.string.follow_request_cant_remove_by_sender) // ローカル操作成功、もしくはリモートフォロー成功 else -> callback() } showColumnMatchAccount(accessInfo) } bFollow && who.locked && (result.response?.code ?: -1) == 422 -> showToast(false, R.string.cant_follow_locked_user) else -> showToast(false, result.error) } } } } // acct で指定したユーザをリモートフォローする private fun ActMain.followRemote( accessInfo: SavedAccount, acct: Acct, locked: Boolean, bConfirmed: Boolean = false, callback: () -> Unit = {}, ) { if (accessInfo.isMe(acct)) { showToast(false, R.string.it_is_you) return } launchAndShowError { if (!bConfirmed) { if (locked) { confirm( getString( R.string.confirm_follow_request_who_from, daoAcctColor.getNickname(acct), daoAcctColor.getNickname(accessInfo) ), accessInfo.confirmFollowLocked, ) { newConfirmEnabled -> accessInfo.confirmFollowLocked = newConfirmEnabled daoSavedAccount.save(accessInfo) reloadAccountSetting(accessInfo) } } else { confirm( getString( R.string.confirm_follow_who_from, daoAcctColor.getNickname(acct), daoAcctColor.getNickname(accessInfo) ), accessInfo.confirmFollow ) { newConfirmEnabled -> accessInfo.confirmFollow = newConfirmEnabled daoSavedAccount.save(accessInfo) reloadAccountSetting(accessInfo) } } } var resultRelation: UserRelation? = null runApiTask(accessInfo, progressStyle = ApiTask.PROGRESS_NONE) { client -> val parser = TootParser(this, accessInfo) val (r2, ar) = client.syncAccountByAcct(accessInfo, acct) val user = ar?.get() ?: return@runApiTask r2 val userId = user.id if (accessInfo.isMisskey) { client.request( "/api/following/create", accessInfo.putMisskeyApiToken().apply { put("userId", userId) }.toPostRequestBuilder() ).also { result -> if (result?.error?.contains("already following") == true || result?.error?.contains("already not following") == true ) { // DBから読み直して値を変更する resultRelation = daoUserRelation.load(accessInfo.db_id, userId) .apply { following = true } } else { // parserに残ってるRelationをDBに保存する parser.account(result?.jsonObject)?.let { resultRelation = daoUserRelation.saveUserRelationMisskey( accessInfo, it.id, parser ) } } } } else { client.request( "/api/v1/accounts/$userId/follow", "".toFormRequestBody().toPost() )?.also { result -> parseItem(result.jsonObject) { TootRelationShip(parser, it) } ?.let { resultRelation = daoUserRelation.saveUserRelation(accessInfo, it) } } } }?.let { result -> when { resultRelation != null -> { callback() showColumnMatchAccount(accessInfo) } locked && (result.response?.code ?: -1) == 422 -> showToast(false, R.string.cant_follow_locked_user) else -> showToast(false, result.error) } } } } fun ActMain.followFromAnotherAccount( pos: Int, accessInfo: SavedAccount, account: TootAccount?, bConfirmMoved: Boolean = false, ) { account ?: return if (!bConfirmMoved && account.moved != null) { AlertDialog.Builder(this) .setMessage( getString( R.string.jump_moved_user, accessInfo.getFullAcct(account), accessInfo.getFullAcct(account.moved) ) ) .setPositiveButton(R.string.ok) { _, _ -> userProfileFromAnotherAccount(pos, accessInfo, account.moved) } .setNeutralButton(R.string.ignore_suggestion) { _, _ -> followFromAnotherAccount( pos, accessInfo, account, bConfirmMoved = true //CHANGED ) } .setNegativeButton(android.R.string.cancel, null) .show() return } val whoAcct = accessInfo.getFullAcct(account) launchMain { pickAccount( bAuto = false, message = getString(R.string.account_picker_follow), accountListArg = accountListNonPseudo(account.apiHost) )?.let { followRemote( it, whoAcct, account.locked, callback = followCompleteCallback ) } } } fun ActMain.followRequestAuthorize( accessInfo: SavedAccount, whoRef: TootAccountRef, bAllow: Boolean, ) { val who = whoRef.get() if (accessInfo.isMe(who)) { showToast(false, R.string.it_is_you) return } launchMain { runApiTask(accessInfo) { client -> val parser = TootParser(this, accessInfo) if (accessInfo.isMisskey) { client.request( "/api/following/requests/${if (bAllow) "accept" else "reject"}", accessInfo.putMisskeyApiToken().apply { put("userId", who.id) } .toPostRequestBuilder() ).also { result -> val user = parser.account(result?.jsonObject) if (user != null) { // parserに残ってるRelationをDBに保存する daoUserRelation.saveUserRelationMisskey( accessInfo, user.id, parser ) } // 読めなくてもエラー処理は行わない } } else { client.request( "/api/v1/follow_requests/${who.id}/${if (bAllow) "authorize" else "reject"}", "".toFormRequestBody().toPost() )?.also { result -> // Mastodon 3.0.0 から更新されたリレーションを返す // https//github.com/tootsuite/mastodon/pull/11800 val newRelation = parseItem(result.jsonObject) { TootRelationShip(parser, it) } daoUserRelation.saveUserRelation(accessInfo, newRelation) // 読めなくてもエラー処理は行わない } } }?.let { result -> when (result.jsonObject) { null -> showToast(false, result.error) else -> { for (column in appState.columnList) { column.removeUser(accessInfo, ColumnType.FOLLOW_REQUESTS, who.id) // 他のカラムでもフォロー状態の表示更新が必要 if (column.accessInfo == accessInfo && column.type != ColumnType.FOLLOW_REQUESTS ) { column.fireRebindAdapterItems() } } showToast( false, if (bAllow) R.string.follow_request_authorized else R.string.follow_request_rejected, whoRef.decoded_display_name ) } } } } } fun ActMain.followRequestDelete( pos: Int, accessInfo: SavedAccount, whoRef: TootAccountRef, bConfirmed: Boolean = false, callback: () -> Unit = {}, ) { if (!accessInfo.isMisskey) { follow( pos, accessInfo, whoRef, bFollow = false, bConfirmed = bConfirmed, callback = callback ) return } val who = whoRef.get() if (accessInfo.isMe(who)) { showToast(false, R.string.it_is_you) return } launchAndShowError { if (!bConfirmed) { confirm( R.string.confirm_cancel_follow_request_who_from, whoRef.decoded_display_name, daoAcctColor.getNickname(accessInfo) ) } var resultRelation: UserRelation? = null runApiTask(accessInfo, progressStyle = ApiTask.PROGRESS_NONE) { client -> if (!accessInfo.isMisskey) { TootApiResult("Mastodon has no API to cancel follow request") } else { val parser = TootParser(this, accessInfo) var userId: EntityId = who.id // リモートユーザの同期 if (who.isRemote) { val (result, ar) = client.syncAccountByAcct(accessInfo, who.acct) val user = ar?.get() ?: return@runApiTask result userId = user.id } client.request( "/api/following/requests/cancel", accessInfo.putMisskeyApiToken().apply { put("userId", userId) } .toPostRequestBuilder() )?.also { result -> parser.account(result.jsonObject)?.let { // parserに残ってるRelationをDBに保存する resultRelation = daoUserRelation.saveUserRelationMisskey( accessInfo, it.id, parser ) } } } }?.let { result -> when (resultRelation) { null -> showToast(false, result.error) else -> { // ローカル操作成功、もしくはリモートフォロー成功 callback() showColumnMatchAccount(accessInfo) } } } } }
37
null
23
238
f20f9fee8ef29bfcbba0f4c610ca8c2fb1c29d4f
21,661
SubwayTooter
Apache License 2.0
lib/android/src/main/java/qiuxiang/amap3d/map_view/MultiPointManager.kt
qiuxiang
92,480,934
false
null
package qiuxiang.amap3d.map_view import com.facebook.react.bridge.ReadableArray import com.facebook.react.bridge.ReadableMap import com.facebook.react.uimanager.SimpleViewManager import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.uimanager.annotations.ReactProp import qiuxiang.amap3d.getEventTypeConstants @Suppress("unused") internal class MultiPointManager : SimpleViewManager<MultiPoint>() { override fun getName(): String { return "AMapMultiPoint" } override fun createViewInstance(reactContext: ThemedReactContext): MultiPoint { return MultiPoint(reactContext) } override fun getExportedCustomBubblingEventTypeConstants(): Map<String, Any> { return getEventTypeConstants("onAPress") } @ReactProp(name = "items") fun setPoints(multiPoint: MultiPoint, items: ReadableArray) { multiPoint.setItems(items) } @ReactProp(name = "icon") fun setIcon(multiPoint: MultiPoint, icon: ReadableMap?) { icon?.let { multiPoint.setIcon(it) } } }
254
null
321
1,202
da9ca7525b2ce62a441989fd509389cbcfb5e155
1,013
react-native-amap3d
MIT License
apps/teacher/src/androidTest/java/com/instructure/teacher/ui/e2e/LoginE2ETest.kt
instructure
179,290,947
false
null
/* * Copyright (C) 2022 - present Instructure, Inc. * * 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.instructure.teacher.ui.e2e import android.util.Log import com.instructure.canvas.espresso.E2E import com.instructure.canvas.espresso.FeatureCategory import com.instructure.canvas.espresso.Priority import com.instructure.canvas.espresso.TestCategory import com.instructure.canvas.espresso.TestMetaData import com.instructure.dataseeding.api.SeedApi import com.instructure.dataseeding.model.CanvasUserApiModel import com.instructure.dataseeding.model.CourseApiModel import com.instructure.espresso.ViewUtils import com.instructure.teacher.ui.utils.TeacherTest import com.instructure.teacher.ui.utils.seedData import dagger.hilt.android.testing.HiltAndroidTest import org.junit.Test @HiltAndroidTest class LoginE2ETest : TeacherTest() { override fun displaysPageObjects() = Unit override fun enableAndConfigureAccessibilityChecks() = Unit @E2E @Test @TestMetaData(Priority.MANDATORY, FeatureCategory.LOGIN, TestCategory.E2E) fun testLoginE2E() { Log.d(PREPARATION_TAG, "Seeding data.") val data = seedData(students = 1, teachers = 2, courses = 1) val teacher1 = data.teachersList[0] val teacher2 = data.teachersList[1] val course = data.coursesList[0] Log.d(STEP_TAG, "Login with user: ${teacher1.name}, login id: ${teacher1.loginId}.") loginWithUser(teacher1) Log.d(STEP_TAG,"Assert that the Dashboard Page is the landing page and it is loaded successfully.") assertSuccessfulLogin(teacher1) Log.d(STEP_TAG,"Validate ${teacher1.name} user's role as a Teacher.") validateUserRole(teacher1, course, "Teacher") Log.d(STEP_TAG,"Log out with ${teacher1.name} student.") leftSideNavigationDrawerPage.logout() Log.d(STEP_TAG, "Login with user: ${teacher2.name}, login id: ${teacher2.loginId}.") loginWithUser(teacher2, true) Log.d(STEP_TAG,"Assert that the Dashboard Page is the landing page and it is loaded successfully.") assertSuccessfulLogin(teacher2) Log.d(STEP_TAG,"Click on 'Change User' button on the left-side menu.") leftSideNavigationDrawerPage.clickChangeUserMenu() Log.d(STEP_TAG,"Assert that the previously logins has been displayed.") loginLandingPage.assertDisplaysPreviousLogins() Log.d(STEP_TAG, "Login with user: ${teacher1.name}, login id: ${teacher1.loginId}.") loginWithUser(teacher1, true) Log.d(STEP_TAG,"Assert that the Dashboard Page is the landing page and it is loaded successfully.") assertSuccessfulLogin(teacher1) Log.d(STEP_TAG,"Click on 'Change User' button on the left-side menu.") leftSideNavigationDrawerPage.clickChangeUserMenu() Log.d(STEP_TAG,"Assert that the previously logins has been displayed.") loginLandingPage.assertDisplaysPreviousLogins() Log.d(STEP_TAG,"Login with the previous user, ${teacher2.name}, with one click, by clicking on the user's name on the bottom.") loginLandingPage.loginWithPreviousUser(teacher2) Log.d(STEP_TAG,"Assert that the Dashboard Page is the landing page and it is loaded successfully.") assertSuccessfulLogin(teacher2) } @E2E @Test @TestMetaData(Priority.MANDATORY, FeatureCategory.LOGIN, TestCategory.E2E) fun testLoginWithNotTeacherRole() { Log.d(PREPARATION_TAG, "Seeding data.") val data = seedData(students = 1, teachers = 1, courses = 1) val parentData = SeedApi.seedParentData( SeedApi.SeedParentDataRequest( courses=1, students=1, parents=1 ) ) val student = data.studentsList[0] val parent = parentData.parentsList[0] Log.d(STEP_TAG, "Login with user: ${student.name}, login id: ${student.loginId}.") loginWithUser(student) Log.d(STEP_TAG,"Assert that the user has been landed on 'Not a teacher?' Page.") notATeacherPage.assertPageObjects() Log.d(STEP_TAG,"Navigate back to the Teacher app's Login Landing Page's screen.") notATeacherPage.clickOnLoginButton() Log.d(STEP_TAG,"Assert the Teacher app's Login Landing Page's screen is displayed.") loginLandingPage.assertPageObjects() Log.d(STEP_TAG, "Login with user: ${parent.name}, login id: ${parent.loginId}.") loginWithUser(parent, true) Log.d(STEP_TAG,"Assert that the user has been landed on 'Not a teacher?' Page.") notATeacherPage.assertPageObjects() Log.d(STEP_TAG,"Navigate back to the Teacher app's login screen.") notATeacherPage.clickOnLoginButton() Log.d(STEP_TAG,"Assert that the user has landed on Teacher app's Login Landing Page's screen.") loginLandingPage.assertPageObjects() } @E2E @Test @TestMetaData(Priority.MANDATORY, FeatureCategory.LOGIN, TestCategory.E2E) fun testLoginE2EWithLastSavedSchool() { Log.d(PREPARATION_TAG, "Seeding data.") val data = seedData(students = 1, teachers = 2, courses = 1) val teacher1 = data.teachersList[0] val teacher2 = data.teachersList[1] Log.d(STEP_TAG, "Login with user: ${teacher1.name}, login id: ${teacher1.loginId}.") loginWithUser(teacher1) Log.d(STEP_TAG, "Assert that the Dashboard Page is the landing page and it is loaded successfully.") assertSuccessfulLogin(teacher1) Log.d(STEP_TAG, "Log out with ${teacher1.name} student.") leftSideNavigationDrawerPage.logout() Log.d(STEP_TAG, "Login with user: ${teacher2.name}, login id: ${teacher2.loginId}, via the last saved school's button.") loginWithLastSavedSchool(teacher2) Log.d(STEP_TAG, "Assert that the Dashboard Page is the landing page and it is loaded successfully.") assertSuccessfulLogin(teacher2) } @E2E @Test @TestMetaData(Priority.IMPORTANT, FeatureCategory.LOGIN, TestCategory.E2E) fun testInvalidAndEmptyLoginCredentialsE2E() { val INVALID_USERNAME = "<EMAIL>" val INVALID_PASSWORD = "<PASSWORD>" val INVALID_CREDENTIALS_ERROR_MESSAGE = "Invalid username or password. Trouble logging in?" val NO_PASSWORD_GIVEN_ERROR_MESSAGE = "No password was given" val DOMAIN = "mobileqa.beta" Log.d(STEP_TAG, "Click 'Find My School' button.") loginLandingPage.clickFindMySchoolButton() Log.d(STEP_TAG,"Enter domain: $DOMAIN.instructure.com.") loginFindSchoolPage.enterDomain(DOMAIN) Log.d(STEP_TAG,"Click on 'Next' button on the Toolbar.") loginFindSchoolPage.clickToolbarNextMenuItem() Log.d(STEP_TAG, "Try to login with invalid, non-existing credentials ($INVALID_USERNAME, $INVALID_PASSWORD)." + "Assert that the invalid credentials error message is displayed.") loginSignInPage.loginAs(INVALID_USERNAME, INVALID_PASSWORD) loginSignInPage.assertLoginErrorMessage(INVALID_CREDENTIALS_ERROR_MESSAGE) Log.d(STEP_TAG, "Try to login with no credentials typed in either of the username and password field." + "Assert that the no password was given error message is displayed.") loginSignInPage.loginAs(EMPTY_STRING, EMPTY_STRING) loginSignInPage.assertLoginErrorMessage(NO_PASSWORD_GIVEN_ERROR_MESSAGE) Log.d(STEP_TAG, "Try to login with leaving only the password field empty." + "Assert that the no password was given error message is displayed.") loginSignInPage.loginAs(INVALID_USERNAME, EMPTY_STRING) loginSignInPage.assertLoginErrorMessage(NO_PASSWORD_GIVEN_ERROR_MESSAGE) Log.d(STEP_TAG, "Try to login with leaving only the username field empty." + "Assert that the invalid credentials error message is displayed.") loginSignInPage.loginAs(EMPTY_STRING, INVALID_PASSWORD) loginSignInPage.assertLoginErrorMessage(INVALID_CREDENTIALS_ERROR_MESSAGE) } private fun loginWithUser(user: CanvasUserApiModel, lastSchoolSaved: Boolean = false) { if(lastSchoolSaved) { Log.d(STEP_TAG, "Click 'Find another school' button.") loginLandingPage.clickFindAnotherSchoolButton() } else { Log.d(STEP_TAG, "Click 'Find My School' button.") loginLandingPage.clickFindMySchoolButton() } Log.d(STEP_TAG, "Enter domain: ${user.domain}.") loginFindSchoolPage.enterDomain(user.domain) Log.d(STEP_TAG, "Click on 'Next' button on the Toolbar.") loginFindSchoolPage.clickToolbarNextMenuItem() Log.d(STEP_TAG, "Login with user: ${user.name}, login id: ${user.loginId}.") loginSignInPage.loginAs(user) } private fun loginWithLastSavedSchool(user: CanvasUserApiModel) { Log.d(STEP_TAG, "Click on last saved school's button.") loginLandingPage.clickOnLastSavedSchoolButton() Log.d(STEP_TAG, "Login with ${user.name} user.") loginSignInPage.loginAs(user) } private fun validateUserRole(user: CanvasUserApiModel, course: CourseApiModel, role: String) { Log.d(STEP_TAG,"Navigate to 'People' Page of ${course.name} course.") dashboardPage.selectCourse(course) courseBrowserPage.openPeopleTab() Log.d(STEP_TAG,"Assert that ${user.name} user's role is $role.") peopleListPage.assertPersonListed(user, role) Log.d(STEP_TAG,"Navigate back to Dashboard Page.") ViewUtils.pressBackButton(2) } private fun assertSuccessfulLogin(user: CanvasUserApiModel) { dashboardPage.waitForRender() leftSideNavigationDrawerPage.assertUserLoggedIn(user) dashboardPage.assertDisplaysCourses() dashboardPage.assertPageObjects() } }
7
null
98
99
1bac9958504306c03960bdce7fbb87cc63bc6845
10,469
canvas-android
Apache License 2.0
app/src/main/java/com/breezebppoddar/features/stockAddCurrentStock/api/ShopAddStockRepository.kt
DebashisINT
518,335,697
false
{"Kotlin": 15748661, "Java": 1026075}
package com.breezebppoddar.features.stockAddCurrentStock.api import com.breezebppoddar.base.BaseResponse import com.breezebppoddar.features.location.model.ShopRevisitStatusRequest import com.breezebppoddar.features.location.shopRevisitStatus.ShopRevisitStatusApi import com.breezebppoddar.features.stockAddCurrentStock.ShopAddCurrentStockRequest import com.breezebppoddar.features.stockAddCurrentStock.model.CurrentStockGetData import com.breezebppoddar.features.stockCompetetorStock.model.CompetetorStockGetData import io.reactivex.Observable class ShopAddStockRepository (val apiService : ShopAddStockApi){ fun shopAddStock(shopAddCurrentStockRequest: ShopAddCurrentStockRequest?): Observable<BaseResponse> { return apiService.submShopAddStock(shopAddCurrentStockRequest) } fun getCurrStockList(sessiontoken: String, user_id: String, date: String): Observable<CurrentStockGetData> { return apiService.getCurrStockListApi(sessiontoken, user_id, date) } }
0
Kotlin
0
0
753efb0351b3f2eac809d89c0dc7222c7e6ab0ab
991
BPPODDARHOSPITAL
Apache License 2.0
08. Homework Local Storage/LocalStorage/app/src/main/java/com/example/localstorage/daos/UpdateDao.kt
VladoDev03
548,553,324
false
{"Kotlin": 60583}
package com.example.localstorage.daos import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import com.example.localstorage.entities.Country import com.example.localstorage.entities.Update @Dao interface UpdateDao { @Query("SELECT * FROM `update` LIMIT 1") suspend fun get(): Update @Insert suspend fun insert(update: Update) @androidx.room.Update suspend fun update(update: Update) }
0
Kotlin
0
0
bebfa1b7c9c924d5da6053076c3318714d752cc9
438
android-development-kotlin-softuni
MIT License
Browser/src/commonMain/kotlin/io/nacular/doodle/drawing/TextFactory.kt
nacular
108,631,782
false
null
package io.nacular.doodle.drawing import io.nacular.doodle.HTMLElement import io.nacular.doodle.text.StyledText /** * Created by <NAME> on 10/30/17. */ interface TextFactory { fun create (text: String, font: Font? = null, possible: HTMLElement? = null): HTMLElement fun create (text: StyledText, possible: HTMLElement? = null): HTMLElement fun wrapped(text: String, font: Font? = null, width: Double, indent: Double = 0.0, possible: HTMLElement? = null): HTMLElement fun wrapped(text: String, font: Font? = null, indent: Double = 0.0, possible: HTMLElement? = null): HTMLElement fun wrapped(text: StyledText, width: Double, indent: Double = 0.0, possible: HTMLElement? = null): HTMLElement fun wrapped(text: StyledText, indent: Double = 0.0, possible: HTMLElement? = null): HTMLElement }
4
null
19
450
2aba993826fcd67dcc825259d6fc7736039de5db
992
doodle
MIT License
app/src/main/java/com/google/samples/apps/sunflower/adapters/CategoryFoodAdapter.kt
zllbird
241,511,935
true
{"Kotlin": 243852}
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.google.samples.apps.sunflower.adapters import android.view.ViewGroup import androidx.compose.ui.platform.ComposeView import androidx.navigation.NavOptions import androidx.navigation.findNavController import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.google.android.material.composethemeadapter.MdcTheme import com.google.samples.apps.sunflower.CategoryFoodListFragmentDirections import com.google.samples.apps.sunflower.HomeFoodViewPagerFragmentDirections import com.google.samples.apps.sunflower.PlantListFragment import com.google.samples.apps.sunflower.R import com.google.samples.apps.sunflower.compose.foods.CategoryFoodItemView import com.google.samples.apps.sunflower.compose.plantlist.PlantListItemView import com.google.samples.apps.sunflower.data.CategoryFood import com.google.samples.apps.sunflower.data.Food import com.google.samples.apps.sunflower.data.Plant /** * Adapter for the [RecyclerView] in [CategoryFood]. */ class CategoryFoodAdapter : ListAdapter<Food, RecyclerView.ViewHolder>(CategoryFoodDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return CategoryFoodViewHolder(ComposeView(parent.context)) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val food = getItem(position) (holder as CategoryFoodViewHolder).bind(food) } class CategoryFoodViewHolder( composeView: ComposeView ) : RecyclerView.ViewHolder(composeView) { fun bind(food: Food) { (itemView as ComposeView).setContent { MdcTheme { CategoryFoodItemView(food) { navigateToAddFoodToHouse(food) } } } } private fun navigateToAddFoodToHouse(food: Food) { val direction = CategoryFoodListFragmentDirections.actionFoodFragmentToInsertHouseFragment( food.foodId ) itemView.findNavController().navigate(direction) // itemView.findNavController().navigate(R.id.create_order_fragment) } } } private class CategoryFoodDiffCallback : DiffUtil.ItemCallback<Food>() { override fun areItemsTheSame(oldItem: Food, newItem: Food): Boolean { return oldItem.foodId == newItem.foodId } override fun areContentsTheSame(oldItem: Food, newItem: Food): Boolean { return oldItem == newItem } }
0
Kotlin
0
0
37b5c513dd1f75ecfb4fc07915d9a56b5735242b
3,205
sunflower
Apache License 2.0
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/javaInterfaceAllUsages.0.kt
JetBrains
2,489,216
false
null
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtClass // OPTIONS: usages // PSI_ELEMENT_AS_TITLE: "interface Server" // IGNORE_PLATFORM_JS: Java-specific code // IGNORE_PLATFORM_NATIVE: Java-specific code package server interface <caret>Server { companion object { @JvmField val ID = "" @JvmStatic fun callStatic() {} } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
345
intellij-community
Apache License 2.0