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/octopus/moviesapp/ui/base/BaseAdapter.kt
b-alramlawi
606,522,847
false
{"Kotlin": 288183}
package com.octopus.moviesapp.ui.base import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.octopus.moviesapp.BR abstract class BaseAdapter<T>( var itemsList: List<T>, private val listener: BaseInteractionListener, ) : RecyclerView.Adapter<BaseAdapter.ItemViewHolder>() { @LayoutRes abstract fun layoutId(): Int class ItemViewHolder(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) override fun getItemCount(): Int = itemsList.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { return ItemViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), layoutId(), parent, false ) ) } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { holder.binding.run { setVariable(BR.item, itemsList[position]) setVariable(BR.listener, listener) } } protected open fun areItemsTheSame(oldItem: T, newItem: T): Boolean { return oldItem == newItem } abstract fun areContentsTheSame(oldItem: T, newItem: T): Boolean fun setItems(newList : List<T>) { val differCallback = BaseDiffUtil( oldList = itemsList, newList = newList, { oldItem, newItem -> areItemsTheSame(oldItem, newItem) }, { oldItem, newItem -> areContentsTheSame(oldItem, newItem) }, ) val diffResult = DiffUtil.calculateDiff(differCallback) itemsList = newList diffResult.dispatchUpdatesTo(this) } }
0
Kotlin
0
0
81c315d24c34cb6a2d2fbbb4c12cf65ac0ae3826
1,886
Movies_app
Apache License 2.0
src/main/kotlin/Day3.kt
clechasseur
258,279,622
false
null
import org.clechasseur.adventofcode2019.Direction import org.clechasseur.adventofcode2019.Pt import org.clechasseur.adventofcode2019.manhattan import org.clechasseur.adventofcode2019.toDirection object Day3 { private const val input = "R997,D443,L406,D393,L66,D223,R135,U452,L918,U354,L985,D402,R257,U225,R298,U369,L762,D373,R781,D935,R363,U952,L174,D529,L127,D549,R874,D993,L890,U881,R549,U537,L174,U766,R244,U131,R861,D487,R849,U304,L653,D497,L711,D916,R12,D753,R19,D528,L944,D155,L507,U552,R844,D822,R341,U948,L922,U866,R387,U973,R534,U127,R48,U744,R950,U522,R930,U320,R254,D577,L142,D29,L24,D118,L583,D683,L643,U974,L683,U985,R692,D271,L279,U62,R157,D932,L556,U574,R615,D428,R296,U551,L452,U533,R475,D302,R39,U846,R527,D433,L453,D567,R614,U807,R463,U712,L247,D436,R141,U180,R783,D65,L379,D935,R989,U945,L901,D160,R356,D828,R45,D619,R655,U104,R37,U793,L360,D242,L137,D45,L671,D844,R112,U627,R976,U10,R942,U26,L470,D284,R832,D59,R97,D9,L320,D38,R326,U317,L752,U213,R840,U789,L152,D64,L628,U326,L640,D610,L769,U183,R844,U834,R342,U630,L945,D807,L270,D472,R369,D920,R283,U440,L597,U137,L133,U458,R266,U91,R137,U536,R861,D325,R902,D971,R891,U648,L573,U139,R951,D671,R996,U864,L749,D681,R255,U306,R154,U706,L817,D798,R109,D594,R496,D867,L217,D572,L166,U723,R66,D210,R732,D741,L21,D574,L523,D646,R313,D961,L474,U990,R125,U928,L58,U726,R200,D364,R244,U622,R823,U39,R918,U549,R667,U935,R372,U241,L56,D713,L735,U735,L812,U700,L408,U980,L242,D697,L580,D34,L266,U190,R876,U857,L967,U493,R871,U563,L241,D636,L467,D793,R304,U103,L950,D503,R487,D868,L358,D747,L338,D273,L485,D686,L974,D724,L534,U561,R729,D162,R731,D17,R305,U712,R472,D158,R921,U827,L944,D303,L526,D782,R575,U948,L401,D142,L48,U766,R799,D242,R821,U673,L120\n" + "L991,D492,L167,D678,L228,U504,R972,U506,R900,U349,R329,D802,R616,U321,R252,U615,R494,U577,R322,D593,R348,U140,L676,U908,L528,D247,L498,D79,L247,D432,L569,U206,L668,D269,L25,U180,R181,D268,R655,D346,R716,U240,L227,D239,L223,U760,L10,D92,L633,D425,R198,U222,L542,D790,L596,U667,L87,D324,R456,U366,R888,U319,R784,D948,R641,D433,L519,U950,L689,D601,L860,U233,R21,D214,L89,U756,L361,U258,L950,D483,R252,U206,L184,U574,L540,U926,R374,U315,R357,U512,R503,U917,R745,D809,L94,D209,R616,U47,R61,D993,L589,D1,R387,D731,R782,U771,L344,U21,L88,U614,R678,U259,L311,D503,L477,U829,R861,D46,R738,D138,L564,D279,L669,U328,L664,U720,L746,U638,R790,D242,R504,D404,R409,D753,L289,U128,L603,D696,L201,D638,L902,D279,L170,D336,L311,U683,L272,U396,R180,D8,R816,D904,L129,D809,R168,D655,L459,D545,L839,U910,L642,U704,R301,D235,R469,D556,L624,D669,L174,D272,R515,D60,L668,U550,L903,D881,L600,D734,R815,U585,R39,D87,R198,D418,L150,D964,L818,D250,L198,D127,R521,U478,L489,D676,L84,U973,R384,D167,R372,D981,L733,D682,R746,D803,L834,D421,R153,U752,L381,D990,R216,U469,L446,D763,R332,D813,L701,U872,L39,D524,L469,U508,L700,D382,L598,U563,R652,D901,R638,D358,L486,D735,L232,U345,R746,U818,L13,U618,R881,D647,R191,U652,R358,U423,L137,D224,R415,U82,R778,D403,R661,D157,R393,D954,L308,D986,L293,U870,R13,U666,L232,U144,R887,U364,L507,U520,R823,D11,L927,D904,R618,U875,R143,D457,R459,D755,R677,D561,L499,U267,L721,U274,L700,D870,L612,D673,L811,D695,R929,D84,L578,U201,L745,U963,L185,D687,L662,U313,L853,U314,R336" private val moves = input.split('\n').map { wire -> wire.splitToSequence(',').map { it.toMove() }.toList() } fun part1(): Int { val (wire1Pts, wire2Pts) = moves.map { wirePoints(it) } return manhattan(wire1Pts.intersect(wire2Pts).min()!!, Pt(0, 0)) } fun part2(): Int { val ptsToDists = mutableMapOf<Pt, MutableList<Int>>() moves.flatMap { move -> wirePoints(move).mapIndexed { i, pt -> pt to i + 1 }.distinctBy { it.first } }.forEach { ptsToDists.getOrPut(it.first) { mutableListOf() }.add(it.second) } return ptsToDists.filter { it.value.size > 1 }.map { it.value.sum() }.min()!! } private fun wirePoints(moves: List<Move>): List<Pt> { val movesIt = moves.iterator() return generateSequence(listOf(Pt(0, 0))) { prev -> when (movesIt.hasNext()) { true -> { val move = movesIt.next() generateSequence(prev.last()) { it + move.direction.displacement }.drop(1).take(move.distance).toList() } false -> null } }.drop(1).flatten().toList() } } private data class Move(val direction: Direction, val distance: Int) private fun String.toMove() = Move(this[0].toDirection(), substring(1).toInt())
0
Kotlin
0
0
187acc910eccb7dcb97ff534e5f93786f0341818
4,555
adventofcode2019
MIT License
3226.Number of Bit Changes to Make Two Integers Equal.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
internal class Solution { fun minChanges(n: Int, k: Int): Int { return if ((n and k) != k) -1 else Integer.bitCount(n xor k) } }
0
Kotlin
0
0
17a80985d970c8316fb694e4952692e598d700af
137
kotlin-leetcode
MIT License
app/src/main/java/uk/nhs/nhsx/covid19/android/app/util/ListUtils.kt
coderus-ltd
369,240,870
true
{"Kotlin": 3133494, "Shell": 1098, "Ruby": 847, "Batchfile": 197}
package uk.nhs.nhsx.covid19.android.app.util fun <T> List<T>.shallowCopy(): List<T> = mutableListOf<T>().apply { addAll(this@shallowCopy) }
0
null
0
0
b74358684b9dbc0174890db896b93b0f7c6660a4
145
covid-19-app-android-ag-public
MIT License
src/test/kotlin/nl/kute/asstring/core/AsStringWithAnnotationsTest.kt
JanHendrikVanHeusden
454,323,023
false
{"Kotlin": 733032, "Java": 31861}
package nl.kute.asstring.core import nl.kute.asstring.annotation.modify.AsStringHash import nl.kute.asstring.annotation.modify.AsStringMask import nl.kute.asstring.annotation.modify.AsStringOmit import nl.kute.asstring.annotation.modify.AsStringReplace import nl.kute.asstring.annotation.option.AsStringOption import nl.kute.asstring.core.defaults.defaultMaxStringValueLength import nl.kute.asstring.core.defaults.defaultNullString import nl.kute.helper.base.ObjectsStackVerifier import nl.kute.reflection.annotationfinder.annotationOfPropertySubSuperHierarchy import nl.kute.reflection.annotationfinder.annotationOfSubSuperHierarchy import nl.kute.reflection.annotationfinder.annotationOfToStringSubSuperHierarchy import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import java.time.LocalDate import kotlin.reflect.full.findAnnotation class AsStringWithAnnotationsTest: ObjectsStackVerifier { @Test fun `non-default AsStringOption parameters should be honoured`() { // arrange val theObjectToPrint = ClassWithNonDefaultAsStringOptions() val asStringOption: AsStringOption = theObjectToPrint::class.annotationOfSubSuperHierarchy()!! val nullStr = "[nil]" assertThat(asStringOption.showNullAs).isEqualTo(nullStr) assertThat(asStringOption.propMaxStringValueLength).isEqualTo(6) val aStringToReplaceByAnother = theObjectToPrint.aStringToReplaceByAnother assertThat(aStringToReplaceByAnother).isEqualTo("a String") val aDateWithMonthMasked = theObjectToPrint.aDateWithMonthMasked.toString() assertThat(aDateWithMonthMasked).isEqualTo("2023-05-24") val noPrint = theObjectToPrint.noPrint.toString() assertThat(theObjectToPrint.noPrint).isExactlyInstanceOf(Any::class.java) val hashed = theObjectToPrint.hashed assertThat(hashed).isEqualTo("a string that should be hashed") val aNullValue = theObjectToPrint.aNullValue assertThat(aNullValue).isNull() // act val stringVal = theObjectToPrint.toString() // assert // values capped at max length of 6, due to propMaxStringLength assertThat(stringVal) .startsWith("${theObjectToPrint::class.java.simpleName}(") .endsWith(")") .`as`("Month should be pattern-replaced, then capped at 6") .matches(""".+?\baDateWithMonthMasked=2023-M\b.+""") .doesNotContain(aDateWithMonthMasked) .`as`("should adhere to `showNullAs`=\"$nullStr\"") .matches(""".+?\baNullValue=\$nullStr.+""") .doesNotMatch("\bnull\b") .`as`("\"a\" should be replaced by \"another\", then capped at 6") .matches(""".+?\baStringToReplaceByAnother=anothe\b.+""") .doesNotContain(aStringToReplaceByAnother) .`as`("value should be hashed, then capped at 8") .matches(""".+?\bhashed=#[a-f0-9]{5}\b.+""") .doesNotContain(hashed) .`as`("should adhere to NoPrint annotation") .doesNotContain("noPrint=") .doesNotContain(noPrint) } @Test fun `AsSringOptions annotation on toString in subclass should be honoured`() { // arrange val theObjectToPrint = SubClassWithAsStringOptionsToString() val asStringOptionClass: AsStringOption = theObjectToPrint::class.annotationOfSubSuperHierarchy()!! val nullStrClass = "[nil]" assertThat(asStringOptionClass.showNullAs).isEqualTo(nullStrClass) assertThat(asStringOptionClass.propMaxStringValueLength).isEqualTo(6) // The @AsStringOption of `toString()` should take prevalence over that of the class val asStringOptionToString: AsStringOption = theObjectToPrint::class.annotationOfToStringSubSuperHierarchy()!! assertThat(asStringOptionToString.showNullAs).isEqualTo(defaultNullString) assertThat(asStringOptionToString.propMaxStringValueLength).isEqualTo(defaultMaxStringValueLength) val aStringToReplaceByAnother = theObjectToPrint.aStringToReplaceByAnother assertThat(aStringToReplaceByAnother).isEqualTo("a String") val aDateWithMonthMasked = theObjectToPrint.aDateWithMonthMasked.toString() assertThat(aDateWithMonthMasked).isEqualTo("2023-05-24") val noPrint = theObjectToPrint.noPrint.toString() val hashed = theObjectToPrint.hashed assertThat(hashed).isEqualTo("a string that should be hashed") val aNullValue = theObjectToPrint.aNullValue assertThat(aNullValue).isNull() // act val stringVal = theObjectToPrint.toString() // assert // values not capped at length 6, due to overriding @AsStringOption on toString() method assertThat(stringVal) .startsWith("${theObjectToPrint::class.java.simpleName}(") .endsWith(")") .`as`("Month should be pattern-replaced, but not capped at 6") .matches(""".+?\baDateWithMonthMasked=2023-MM-24\b.+""") .doesNotContain(aDateWithMonthMasked) .`as`("should adhere to default `showNullAs`=\"$defaultNullString\"") .matches(""".+?\baNullValue=$defaultNullString\b.+""") .doesNotMatch("\bnull\b") .`as`("\"a\" should be replaced by \"another\", but not capped at 6") .matches(""".+?\baStringToReplaceByAnother=another String\b.+""") .doesNotContain(aStringToReplaceByAnother) .`as`("value should be hashed") .matches(""".+?\bhashed=#[a-f0-9]{8}\b#.+""") .doesNotContain(hashed) .`as`("should adhere to NoPrint annotation") .doesNotContain("noPrint=") .doesNotContain(noPrint) } @Test fun `AsStringOptions annotation on class should be honoured in subclass`() { // arrange val theObjectToPrint = SubClassWithAsStringOptionsOnClass() val asStringOption: AsStringOption = theObjectToPrint::class.annotationOfSubSuperHierarchy()!! val nullStr = "nothing here" assertThat(asStringOption.showNullAs).isEqualTo(nullStr) assertThat(asStringOption.propMaxStringValueLength).isEqualTo(defaultMaxStringValueLength) val aStringToReplaceByAnother = theObjectToPrint.aStringToReplaceByAnother assertThat(aStringToReplaceByAnother).isEqualTo("a String") val aDateWithMonthMasked = theObjectToPrint.aDateWithMonthMasked.toString() assertThat(aDateWithMonthMasked).isEqualTo("2023-05-24") val noPrint = theObjectToPrint.noPrint.toString() val hashed = theObjectToPrint.hashed assertThat(hashed).isEqualTo("a string that should be hashed") val aNullValue = theObjectToPrint.aNullValue assertThat(aNullValue).isNull() // act val stringVal = theObjectToPrint.toString() // assert // values not capped at length 6, due to overriding @AsStringOption on toString() method assertThat(stringVal) .startsWith("${theObjectToPrint::class.java.simpleName}(") .endsWith(")") .`as`("Month should be pattern-replaced, but not capped at 6") .matches(""".+?\baDateWithMonthMasked=2023-MM-24\b.+""") .doesNotContain(aDateWithMonthMasked) .`as`("should adhere to default `showNullAs`=\"$nullStr\"") .matches(""".+?\baNullValue=$nullStr\b.+""") .doesNotMatch("\bnull\b") .`as`("\"a\" should be replaced by \"another\", but not capped at 6") .matches(""".+?\baStringToReplaceByAnother=another String\b.+""") .doesNotContain(aStringToReplaceByAnother) .`as`("value should be hashed") .matches(""".+?\bhashed=#[a-f0-9]{8}\b#.+""") .doesNotContain(hashed) .`as`("should adhere to NoPrint annotation") .doesNotContain("noPrint=") .doesNotContain(noPrint) } @Test fun `AsStringOption on class should not override those on toString`() { // arrange val theObjectToPrint = SubSubClassOfAsStringOptionsToStringWithAsStringOptionsOnClass() val asStringOptionClass: AsStringOption = theObjectToPrint::class.annotationOfSubSuperHierarchy()!! assertThat(asStringOptionClass.showNullAs).isEqualTo(defaultNullString) assertThat(asStringOptionClass.propMaxStringValueLength).isEqualTo(2) // The @AsStringOption of `toString()` in the superclass should still take prevalence over that of the subclass val asStringOptionToString: AsStringOption = theObjectToPrint::class.annotationOfToStringSubSuperHierarchy()!! assertThat(asStringOptionToString.showNullAs).isEqualTo(defaultNullString) assertThat(asStringOptionToString.propMaxStringValueLength).isEqualTo(defaultMaxStringValueLength) val aStringToReplaceByAnother = theObjectToPrint.aStringToReplaceByAnother assertThat(aStringToReplaceByAnother).isEqualTo("a String") val aDateWithMonthMasked = theObjectToPrint.aDateWithMonthMasked.toString() assertThat(aDateWithMonthMasked).isEqualTo("2023-05-24") val noPrint = theObjectToPrint.noPrint.toString() val hashed = theObjectToPrint.hashed assertThat(hashed).isEqualTo("a string that should be hashed") val aNullValue = theObjectToPrint.aNullValue assertThat(aNullValue).isNull() // act val stringVal = theObjectToPrint.toString() // assert // values not capped at length 6, due to overriding @AsStringOption on toString() method assertThat(stringVal) .startsWith("${theObjectToPrint::class.java.simpleName}(") .endsWith(")") .`as`("Value should be hashed") .matches(""".+?\baDateWithMonthMasked=#[a-f0-9]{8}\b#.+""") .doesNotContain(aDateWithMonthMasked) .`as`("should adhere to default `showNullAs`=\"$defaultNullString\"") .matches(""".+?\baNullValue=$defaultNullString\b.+""") .doesNotMatch("\bnull\b") .`as`("\"a\" should be replaced by \"another\"") .matches(""".+?\baStringToReplaceByAnother=another String\b.+""") .doesNotContain(aStringToReplaceByAnother) .`as`("value should be hashed") .matches(""".+?\bhashed=#[a-f0-9]{8}\b#.+""") .`as`("should not contain literal value of the property to hash") .doesNotContain(hashed) .`as`("should adhere to NoPrint annotation") .doesNotContain("noPrint=") .doesNotContain(noPrint) } @Test fun `overriding AsStringOption on toString should be honoured`() { // arrange val theObjectToPrint = SubSubClassOfAsStringOptionsToStringWithAsStringOptionsOnToString() val asStringOptionToString: AsStringOption = theObjectToPrint::class.annotationOfToStringSubSuperHierarchy()!! assertThat(asStringOptionToString.showNullAs).isEqualTo(defaultNullString) assertThat(asStringOptionToString.propMaxStringValueLength).isEqualTo(2) val aStringToReplaceByAnother = theObjectToPrint.aStringToReplaceByAnother assertThat(aStringToReplaceByAnother).isEqualTo("a String") val aDateWithMonthMasked = theObjectToPrint.aDateWithMonthMasked.toString() assertThat(aDateWithMonthMasked).isEqualTo("2023-05-24") val noPrint = theObjectToPrint.noPrint.toString() val hashed = theObjectToPrint.hashed assertThat(hashed).isEqualTo("a string that should be hashed") val aNullValue = theObjectToPrint.aNullValue assertThat(aNullValue).isNull() // act val stringVal = theObjectToPrint.toString() // assert // values not capped at length 6, due to overriding @AsStringOption on toString() method assertThat(stringVal) .startsWith("${theObjectToPrint::class.java.simpleName}(") .endsWith(")") .`as`("Month should be hashed, then capped at length 2") .matches(""".+?\baDateWithMonthMasked=[a-f0-9]{2}\b.+""") .doesNotContain(aDateWithMonthMasked) .`as`("should adhere to default `showNullAs`=\"$defaultNullString\"") .matches(""".+?\baNullValue=$defaultNullString\b.+""") .doesNotMatch("\bnull\b") .`as`("\"a\" should be replaced by \"another\", then capped at length 2") .matches(""".+?\baStringToReplaceByAnother=an\b.+""") .doesNotContain(aStringToReplaceByAnother) .`as`("value should be hashed, then capped at length 2") .matches(""".+?\bhashed=#[a-f0-9]\b.+""") .doesNotContain(hashed) .`as`("should adhere to NoPrint annotation") .doesNotContain("noPrint=") .doesNotContain(noPrint) } @Test fun `AsStringOption on property should be honoured`() { // arrange val maxStringLenght = 10 val theObjectToPrint = ClassWithAsStringOptionOnProperty() assertThat(theObjectToPrint.propWithAsStringOption.length).isGreaterThan(maxStringLenght) assertThat(theObjectToPrint::class.annotationOfToStringSubSuperHierarchy<AsStringOption>()).isNull() with(theObjectToPrint::propWithAsStringOption.annotationOfPropertySubSuperHierarchy<AsStringOption>()!!) { assertThat(this.propMaxStringValueLength).isEqualTo(maxStringLenght) } // act val stringVal = theObjectToPrint.toString() // assert assertThat(stringVal) .`as`("Should adhere to @AsStringOption annotation on property") .isEqualTo("ClassWithAsStringOptionOnProperty(propWithAsStringOption=" + "${theObjectToPrint.propWithAsStringOption.take(maxStringLenght)}...)") } @Test fun `AsStringOption on property should override AsStringOption on toString`() { // arrange val maxStringLenght = 10 val theObjectToPrint = ClassWithAsStringOptionsOnPropertyAndToString() assertThat(theObjectToPrint.propWithAsStringOption.length).isGreaterThan(maxStringLenght) assertThat(theObjectToPrint::class.annotationOfToStringSubSuperHierarchy<AsStringOption>()!!.propMaxStringValueLength) .isLessThan(maxStringLenght) with(theObjectToPrint::propWithAsStringOption.annotationOfPropertySubSuperHierarchy<AsStringOption>()!!) { assertThat(this.propMaxStringValueLength).isEqualTo(maxStringLenght) } // act val stringVal = theObjectToPrint.toString() // assert assertThat(stringVal) .`as`("Should ignore the @AsStringOption on toString, but should adhere to @AsStringOption annotation on property") .isEqualTo("ClassWithAsStringOptionsOnPropertyAndToString(propWithAsStringOption=${theObjectToPrint.propWithAsStringOption.take(maxStringLenght)}...)") } @Test fun `test replace & mask 1`() { val phony = Phony() assertThat(phony.toString()) .`as`("Masking should be applied according to ${Phony::phoneNumberMask1 .findAnnotation<AsStringMask>()}") .contains("phoneNumberMask1= +31 6 123********9 0 ") .doesNotContain(phony.phoneNumberMask1) .`as`("Masking should be applied according to ${Phony::phoneNumberMask2 .findAnnotation<AsStringMask>()}") .contains("phoneNumberMask2= +31 6 123 45 ****9 0 ") .doesNotContain(phony.phoneNumberMask2) .`as`("Should apply full masking by default ${Phony::phoneNumberMask5.findAnnotation<AsStringMask>()}") .contains("phoneNumberMask5=**********************") .doesNotContain(phony.phoneNumberMask5) .`as`("Should apply partial masking by custom mask 'x' ${Phony::phoneNumberMask6 .findAnnotation<AsStringMask>()}") .contains("phoneNumberMask6= +xxxx 123 45 67 89 0 ") .doesNotContain(phony.phoneNumberMask6) .`as`("Masking should be applied according to ${Phony::phoneNumberMask7 .findAnnotation<AsStringMask>()}") .contains("phoneNumberMask7= +31******") .doesNotContain(phony.phoneNumberMask7) .`as`("Pattern replacement should be applied according to ${Phony::phoneNumberPatternReplace .findAnnotation<AsStringReplace>()}") .contains("phoneNumberPatternReplace= +31 6 123 ****89 0") .doesNotContain(phony.phoneNumberPatternReplace) } @Test fun `test replace & mask 2`() { val banky = Banky() assertThat(banky.asString()) .`as`("Pattern replacement should be applied according to ") .contains("bankNumberPatternReplace=NL37<bank>*****48739") .doesNotContain(banky.bankNumberPatternReplace) assertThat(banky.asString()) .`as`("Mask should adhere to minLength=4, even with maxLength=2") .containsPattern("""\bcountryCode=\*{4}([),])""") .doesNotContain("countryCode=${banky.countryCode}") } @Test fun `repeating AsStringMask annotations should be honoured, in order`() { @Suppress("unused") class Iban { @AsStringMask(startMaskAt = 2, endMaskAt = 4, mask = '0') @AsStringMask(startMaskAt = 11, endMaskAt = -3, mask = '*', minLength = 40) @AsStringMask(startMaskAt = 31, endMaskAt = 36, mask = '-', maxLength = 32) // fake Maltese IBAN number val iban = "MT52QCGK45148414861965929692444" } assertThat(Iban().asString()).isEqualTo("Iban(iban=MT00QCGK451*****************444-)") } @Test fun `repeating AsStringReplace annotations should be honoured, in order`() { @Suppress("unused") class Words { // removes leading/trailing whitespace and first and last words @AsStringReplace(pattern = """^\s*\S+\s+(.+?)\s+\S+\s*$""", "$1") @AsStringReplace(pattern = """five$""", "three") val fiveWords = " this String contains five words " } assertThat(Words().asString()).isEqualTo("Words(fiveWords=String contains three)") } // region ~ Classes, objects etc. to be used for testing @AsStringOption(showNullAs = "[nil]", propMaxStringValueLength = 6) private open class ClassWithNonDefaultAsStringOptions { @AsStringReplace("^a", "another") val aStringToReplaceByAnother: String = "a String" @AsStringMask(startMaskAt = 5, endMaskAt = 7, mask = 'M') open val aDateWithMonthMasked: LocalDate = LocalDate.of(2023, 5, 24) @AsStringOmit open val noPrint: Any = Any() @AsStringHash val hashed: String = "a string that should be hashed" val aNullValue: Any? = null override fun toString(): String = asString() } private open class SubClassWithAsStringOptionsToString : ClassWithNonDefaultAsStringOptions() { override val noPrint: Any = "should not print this" @AsStringOption // defaults override fun toString(): String = asString() } @AsStringOption(showNullAs = "nothing here") private open class SubClassWithAsStringOptionsOnClass : ClassWithNonDefaultAsStringOptions() { @AsStringHash // Should not override the super method's @AsStringOmit annotation, so should not be included override val noPrint: Any = "should not print this" } @AsStringOption(propMaxStringValueLength = 2) private open class SubSubClassOfAsStringOptionsToStringWithAsStringOptionsOnClass : SubClassWithAsStringOptionsToString() { @AsStringHash override val aDateWithMonthMasked = super.aDateWithMonthMasked override fun toString(): String = asString() } private open class SubSubClassOfAsStringOptionsToStringWithAsStringOptionsOnToString : SubClassWithAsStringOptionsToString() { @AsStringOption(propMaxStringValueLength = 2) override fun toString(): String = asString() } private open class ClassWithAsStringOptionOnProperty { @AsStringOption(propMaxStringValueLength = 10) val propWithAsStringOption: String = "I am a property with @AsStringOption" override fun toString(): String = asString() } private open class ClassWithAsStringOptionsOnPropertyAndToString { @AsStringOption(propMaxStringValueLength = 10) val propWithAsStringOption: String = "I am a property with @AsStringOption" @AsStringOption(propMaxStringValueLength = 5) override fun toString(): String = asString() } private class Phony { @AsStringOmit private val phoneNumber: String = " +31 6 123 45 67 89 0 " @AsStringReplace(pattern = """(\d\s*){4}((\d\s*){3}\s*)$""", replacement = "****$2") val phoneNumberPatternReplace = phoneNumber @AsStringMask(startMaskAt = 10, endMaskAt = -4) val phoneNumberMask1 = phoneNumber @AsStringMask(startMaskAt = -8, endMaskAt = -4) val phoneNumberMask2 = phoneNumber // Should fully mask (default) @AsStringMask val phoneNumberMask5 = phoneNumber @AsStringMask(startMaskAt = 2, endMaskAt = 6, mask = 'x') val phoneNumberMask6 = phoneNumber @AsStringMask(startMaskAt = 4, maxLength = 10) val phoneNumberMask7 = phoneNumber override fun toString() = asString() } private class Banky { @AsStringReplace(pattern = """^(..\d\d)....\d{5}(.+)""", replacement = "$1<bank>*****$2") val bankNumberPatternReplace = "NL37DUMM5273748739" @AsStringMask(minLength = 4, maxLength = 2) val countryCode = "NL" override fun toString(): String = asString() } // endregion }
0
Kotlin
0
1
6d83ba7e801cdd4dc27e321c9048ead4c365766c
22,011
Kute
MIT License
typescript-kotlin/src/main/kotlin/typescript/NamedTupleMember.kt
turansky
393,199,102
false
null
// Automatically generated - do not modify! package typescript external interface NamedTupleMember : TypeNode, JSDocContainer, Declaration { /* readonly kind: SyntaxKind.NamedTupleMember; readonly dotDotDotToken?: Token<SyntaxKind.DotDotDotToken>; readonly name: Identifier; readonly questionToken?: Token<SyntaxKind.QuestionToken>; readonly type: TypeNode; */ }
0
Kotlin
1
10
bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0
393
react-types-kotlin
Apache License 2.0
core/src/main/java/org/openedx/core/config/MicrosoftConfig.kt
openedx
613,282,821
false
{"Kotlin": 2073675, "Groovy": 5883, "JavaScript": 1129}
package org.openedx.core.config import com.google.gson.annotations.SerializedName data class MicrosoftConfig( @SerializedName("ENABLED") private val enabled: Boolean = false, @SerializedName("CLIENT_ID") val clientId: String = "", @SerializedName("PACKAGE_SIGNATURE") val packageSignature: String = "", ) { fun isEnabled() = enabled && clientId.isNotBlank() && packageSignature.isNotBlank() }
85
Kotlin
23
18
4d36310011d20ce0fe896ae4e4d3ca2148f322b6
423
openedx-app-android
Apache License 2.0
src/main/kotlin/com/forum/springboot/forum3API/dtos/ResponseMessage.kt
BraveWorm
602,570,714
false
null
package com.forum.springboot.forum3API.dtos class ResponseMessage(public val message: String) { }
0
Kotlin
0
0
ba91ba139dec92da4f9097160717253fcffbe215
98
Forum3Api
MIT License
validator/src/commonMain/kotlin/io/github/charlietap/chasm/validator/validator/instruction/aggregate/ArrayInitDataInstructionValidator.kt
CharlieTap
743,980,037
false
{"Kotlin": 2038041, "WebAssembly": 45714}
package io.github.charlietap.chasm.validator.validator.instruction.aggregate import com.github.michaelbull.result.Err import com.github.michaelbull.result.Result import com.github.michaelbull.result.binding import com.github.michaelbull.result.toResultOr import io.github.charlietap.chasm.ast.instruction.AggregateInstruction import io.github.charlietap.chasm.ast.type.ConcreteHeapType import io.github.charlietap.chasm.ast.type.Mutability import io.github.charlietap.chasm.ast.type.ReferenceType import io.github.charlietap.chasm.ast.type.ValueType import io.github.charlietap.chasm.type.ext.arrayType import io.github.charlietap.chasm.validator.context.ValidationContext import io.github.charlietap.chasm.validator.error.ModuleValidatorError import io.github.charlietap.chasm.validator.error.TypeValidatorError import io.github.charlietap.chasm.validator.ext.pop import io.github.charlietap.chasm.validator.ext.popI32 import io.github.charlietap.chasm.validator.ext.type import io.github.charlietap.chasm.validator.ext.unpack internal fun ArrayInitDataInstructionValidator( context: ValidationContext, instruction: AggregateInstruction.ArrayInitData, ): Result<Unit, ModuleValidatorError> = binding { val definedType = context.type(instruction.typeIndex).bind() val arrayType = definedType.arrayType().toResultOr { TypeValidatorError.TypeMismatch }.bind() if (arrayType.fieldType.mutability != Mutability.Var) { Err(TypeValidatorError.TypeMismatch).bind<Unit>() } val t = arrayType.fieldType.unpack() if (t !is ValueType.Number && t !is ValueType.Vector) { Err(TypeValidatorError.TypeMismatch).bind<Unit>() } if (instruction.dataIndex.idx.toInt() !in context.datas.indices) { Err(TypeValidatorError.TypeMismatch).bind<Unit>() } repeat(3) { context.popI32().bind() } context.pop(ValueType.Reference(ReferenceType.RefNull(ConcreteHeapType.Defined(definedType)))).bind() }
5
Kotlin
3
67
a452ab9e37504517b43118f636a28f54e7bcb57c
1,980
chasm
Apache License 2.0
app/src/main/java/com/ivanmagda/habito/util/HabitoDateUtils.kt
ivan-magda
80,835,981
false
null
package com.ivanmagda.habito.utils import android.text.format.DateUtils import com.ivanmagda.habito.models.ResetFrequency import java.util.* object HabitoDateUtils { val currentCalendar: Calendar get() = getCalendarWithTime(System.currentTimeMillis()) val startOfCurrentWeek: Long get() = getStartOfWeek(System.currentTimeMillis()) val endOfCurrentWeek: Long get() { val calendar = getCalendarWithTime(startOfCurrentWeek) calendar.add(Calendar.DATE, 6) return calendar.timeInMillis } val numberOfWeeksInCurrentMonth: Int get() { val calendar = getCalendarWithTime(startOfCurrentMonth) return calendar.getActualMaximum(Calendar.WEEK_OF_MONTH) } val startOfCurrentMonth: Long get() { val calendar = currentCalendar calendar.set(Calendar.DAY_OF_MONTH, 1) return calendar.timeInMillis } val endOfCurrentMonth: Long get() { val calendar = currentCalendar calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) return calendar.timeInMillis } val startOfCurrentYear: Long get() { val calendar = currentCalendar calendar.set(Calendar.MONTH, 0) return calendar.timeInMillis } val endOfCurrentYear: Long get() { val calendar = currentCalendar calendar.set(Calendar.MONTH, 11) return calendar.timeInMillis } fun getCalendarWithTime(time: Long): Calendar { val calendar = Calendar.getInstance() calendar.timeInMillis = time return calendar } fun isWithinRange(toCheck: Long, start: Long, end: Long): Boolean { return isWithinRange(Date(toCheck), Date(start), Date(end)) } fun isWithinRange(toCheck: Date, start: Date, end: Date): Boolean { return !(toCheck.before(start) || toCheck.after(end)) } fun isDateInCurrentWeek(date: Long): Boolean { return isDatesInSameMonth(currentCalendar.timeInMillis, getCalendarWithTime(date).timeInMillis) } fun isDatesInSameWeek(lhsDate: Long, rhsDate: Long): Boolean { val lhsCalendar = getCalendarWithTime(lhsDate) val lhsWeek = lhsCalendar.get(Calendar.WEEK_OF_YEAR) val lhsYear = lhsCalendar.get(Calendar.YEAR) val rhsCalendar = getCalendarWithTime(rhsDate) val rhsWeek = rhsCalendar.get(Calendar.WEEK_OF_YEAR) val rhsYear = rhsCalendar.get(Calendar.YEAR) return lhsWeek == rhsWeek && lhsYear == rhsYear } fun isDateInCurrentMonth(date: Long): Boolean { return isDatesInSameMonth(currentCalendar.timeInMillis, getCalendarWithTime(date).timeInMillis) } fun isDatesInSameMonth(lhs: Long, rhs: Long): Boolean { val lhsCalendar = getCalendarWithTime(lhs) val lhsMonth = lhsCalendar.get(Calendar.MONTH) val lhsYear = lhsCalendar.get(Calendar.YEAR) val rhsCalendar = getCalendarWithTime(rhs) val rhsMonth = rhsCalendar.get(Calendar.MONTH) val rhsYear = rhsCalendar.get(Calendar.YEAR) return lhsMonth == rhsMonth && lhsYear == rhsYear } fun isDateInCurrentYear(date: Long): Boolean { val currentCalendar = currentCalendar val year = currentCalendar.get(Calendar.YEAR) val targetCalendar = getCalendarWithTime(date) val targetYear = targetCalendar.get(Calendar.YEAR) return year == targetYear } fun isDateInType(date: Long, type: ResetFrequency.Type): Boolean { return when (type) { ResetFrequency.Type.DAY -> DateUtils.isToday(date) ResetFrequency.Type.WEEK -> HabitoDateUtils.isDateInCurrentWeek(date) ResetFrequency.Type.MONTH -> HabitoDateUtils.isDateInCurrentMonth(date) ResetFrequency.Type.YEAR -> HabitoDateUtils.isDateInCurrentYear(date) ResetFrequency.Type.NEVER -> true } } fun getStartOfWeek(week: Long): Long { val calendar = getCalendarWithTime(week) calendar.set(Calendar.HOUR_OF_DAY, 0) calendar.clear(Calendar.MINUTE) calendar.clear(Calendar.SECOND) calendar.clear(Calendar.MILLISECOND) // get start of this week in milliseconds calendar.set(Calendar.DAY_OF_WEEK, calendar.firstDayOfWeek) return calendar.timeInMillis } fun isSameDay(lhs: Long, rhs: Long): Boolean { val lhsCal = Calendar.getInstance() val rhsCal = Calendar.getInstance() lhsCal.timeInMillis = lhs rhsCal.timeInMillis = rhs return lhsCal.get(Calendar.YEAR) == rhsCal.get(Calendar.YEAR) && lhsCal.get(Calendar.DAY_OF_YEAR) == rhsCal.get(Calendar.DAY_OF_YEAR) } }
11
Kotlin
28
75
6cc7bc1c9d727236a19967fcd0b223838d224083
4,872
Habito
MIT License
src/main/kotlin/com/vitalyk/insight/view/WatchlistView.kt
yay
420,480,103
false
null
package com.vitalyk.insight.view import com.vitalyk.insight.fragment.NewsWatchlistFragment import com.vitalyk.insight.iex.Watchlist import javafx.scene.control.TabPane import javafx.scene.layout.Priority import tornadofx.* class WatchlistView : View("Watchlists") { override val root = vbox { toolbar { button("Main View").action { replaceWith(MainView::class) } } tabpane { hgrow = Priority.ALWAYS tabClosingPolicy = TabPane.TabClosingPolicy.UNAVAILABLE tab("Main") { this += NewsWatchlistFragment("Main") } tab("Indexes") { this += NewsWatchlistFragment(Watchlist.getOrPut("Indexes").apply { addSymbols(listOf( "SPY", // SPDR S&P 500 "DIA", // SPDR Dow Jones Industrial Average "QQQ", // PowerShares QQQ Trust (tracks Nasdaq 100 Index) "MDY", // SPDR S&P Midcap 400 "IWM", // iShares Russell 2000 (small caps) "IFA", // iShares MSCI EAFE (developed markets: UK, France, German, Japan, ...) "EEM" // iShares MSCI Emerging Markets (China, Korea, Taiwan, Brazil, ...) )) }) } } } }
0
Kotlin
0
0
3a52cbf394224755b407fc2a30856ea92d085d74
1,363
insight
MIT License
library-gms-geofence/src/main/java/ru/fabit/gmsgeofence/GmsGeofenceInstance.kt
FabitMobile
611,619,947
false
null
package ru.fabit.gmsgeofence import ru.fabit.gmsgeofence.entity.GmsGeofenceConfig object GmsGeofenceInstance { var eventHandler: GmsGeofenceEventHandler? = null var recoveryManager: RecoveryGeofenceManager? = null var config: GmsGeofenceConfig = GmsGeofenceConfig() fun getInstance(eventHandler: GmsGeofenceEventHandler, recoveryManager: RecoveryGeofenceManager, config: GmsGeofenceConfig) { this.eventHandler = eventHandler this.recoveryManager = recoveryManager this.config = config } }
0
Kotlin
0
0
5513e76239dbed11a200fa796a5c400563591682
534
library-gms-geofence
MIT License
libs/framework/src/main/java/me/pxq/framework/ApiService.kt
drkingwater
279,571,591
false
null
package me.pxq.common import android.os.Build import me.pxq.utils.DeviceUtil import me.pxq.utils.logi import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.io.IOException /** * Description: api服务类 * Author : pxq * Date : 2020/7/28 8:51 PM */ class ApiService { /** * /api/v5/index/tab/allRec?page=0 * &isOldUser=true * &udid=d9e4d30f251a4dcfb56b3465d22aa1748694f6b7 * &udid=0851 A7AB 68D8 B30E 8117 9E82 D267 06EA 52F0 DFC3 * &vc=6030015 * &vn=6.3.1 * &size=1080X1776 * &deviceModel=HTC%20M8w * &first_channel=yingyongbao * &last_channel=yingyongbao * &system_version_code=23 */ class CommonParamsInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val originalRequest = chain.request() val originalHttpUrl = originalRequest.url() val url = originalHttpUrl.newBuilder().apply { addQueryParameter("udid", DeviceUtil.DEVICE_SERIAL) addQueryParameter("vc", "6030015") //官方app 版本号 addQueryParameter("vn", "6.3.1") //官方app 版本名 addQueryParameter("size", DeviceUtil.DISPLAY_SIZE) addQueryParameter("deviceModel", DeviceUtil.DEVICE_MODEL) addQueryParameter("first_channel", "yingyongbao") addQueryParameter("last_channel", "yingyongbao") addQueryParameter("system_version_code", "${Build.VERSION.SDK_INT}") }.build() val request = originalRequest.newBuilder().url(url) .method(originalRequest.method(), originalRequest.body()).build() return chain.proceed(request) } } class LoggingInterceptor : Interceptor { @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() //计算网络请求时间 val t1 = System.currentTimeMillis() val response = chain.proceed(request) val t2 = System.currentTimeMillis() logi( "Received response for \n{${ response.request() .url() }}\nin ${(t2 - t1)} ms" ) return response } } companion object { private const val BASE_URL = "http://baobab.kaiyanapp.com/" // 首页-推荐第一页数据 const val HOME_RECOMMEND_PAGE = "${BASE_URL}api/v5/index/tab/allRec?page=0" // 首页-日报第一页数据 const val HOME_DAILY_PAGE = "${BASE_URL}api/v5/index/tab/feed" // 社区-推荐第一页数据 const val COMMUNITY_RECOMMEND_PAGE = "${BASE_URL}api/v7/community/tab/rec" // 社区-推荐第一页数据 const val COMMUNITY_FOLLOW_PAGE = "${BASE_URL}api/v6/community/tab/follow" // 通知-推送第一页数据 const val NOTIFICATION_PUSH_PAGE = "${BASE_URL}api/v3/messages" private val httpClient = OkHttpClient.Builder() .addInterceptor(CommonParamsInterceptor()) //添加公共参数拦截器 .addInterceptor(LoggingInterceptor()) //添加网络请求日志拦截器 .build() val instance: Api by lazy { Retrofit.Builder() .client(httpClient) .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() .create(Api::class.java) } } }
0
Kotlin
4
15
0feb6ce3cbd9d396ef79d7bd4e6da60f11a13f2c
3,526
eyepetizer-kotlin
Apache License 2.0
Backpack/src/main/java/net/skyscanner/backpack/button/internal/Util.kt
Ollie1990
196,030,235
true
{"Kotlin": 287991, "JavaScript": 15623, "HTML": 6152, "Shell": 2135, "Java": 1444}
package net.skyscanner.backpack.button.internal import android.R import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable import android.graphics.drawable.RippleDrawable import androidx.annotation.ColorInt import androidx.annotation.Dimension import androidx.core.content.ContextCompat import net.skyscanner.backpack.util.resolveThemeColor /** * Utility method to create a ripple drawable for buttons. * * @param normalColor required, used as main background color on the drawable * @param cornerRadius optional, used as the radius on the corners (use 100 for square) * @param strokeColor optional, color integer for the stroke * @param strokeWidth optional, width in px for the stroke * * @return Drawable */ internal fun getRippleDrawable( context: Context, @ColorInt normalColor: Int, @Dimension cornerRadius: Float? = null, @ColorInt strokeColor: Int? = null, @Dimension strokeWidth: Int? = null ) = RippleDrawable( ColorStateList.valueOf(resolveThemeColor(context, R.attr.colorControlHighlight) ?: ContextCompat.getColor(context, net.skyscanner.backpack.R.color.bpkGray100)), corneredDrawable(normalColor, cornerRadius, strokeColor, strokeWidth), corneredDrawable(Color.WHITE, cornerRadius, strokeColor, strokeWidth) ) /** * Utility function to create a cornered (or circle) drawable given a corner radius. * Additional stroke width and color can be defined * * @param color required, used as the background for the drawable * @param cornerRadius optional, if set used as the radius on the drawable * @param strokeColor optional, color integer for the stroke * @param strokeWidth optional, width in px for the stroke * * @return Drawable */ internal fun corneredDrawable( @ColorInt color: Int, @Dimension cornerRadius: Float? = null, @ColorInt strokeColor: Int? = null, strokeWidth: Int? = null ): Drawable { val gd = GradientDrawable() gd.setColor(color) cornerRadius?.let { gd.cornerRadius = it } if (strokeWidth != null && strokeColor != null) { gd.setStroke(strokeWidth, strokeColor) } else { // This is required otherwise the ripple effect leaks outside the button gd.setStroke(0, -1) } return gd } /** * Utility function to state list for a drawable * * @param normalColor required, used as the color for any non specified special state * @param pressedColor required, used as the color for the pressed, focused and activated state * @param disabledColor required, used as the color for the disabled state * * @return ColorStateList */ internal fun getColorSelector( @ColorInt normalColor: Int, @ColorInt pressedColor: Int, @ColorInt disabledColor: Int ) = ColorStateList( arrayOf( intArrayOf(-R.attr.state_enabled), intArrayOf(R.attr.state_pressed), intArrayOf(R.attr.state_focused), intArrayOf(R.attr.state_activated), intArrayOf() ), intArrayOf(disabledColor, pressedColor, pressedColor, pressedColor, normalColor) )
0
Kotlin
0
0
d031937e5952c1f43b50f9d6ad2fb1cf86802cee
3,082
backpack-android
Apache License 2.0
echoframework/src/test/kotlin/org/echo/mobile/framework/model/socketoperations/GetAccountHistorySocketOperationTest.kt
echoprotocol
151,734,824
false
null
package org.echo.mobile.framework.model.socketoperations import org.echo.mobile.framework.model.network.Testnet import org.echo.mobile.framework.model.operations.ContractCreateOperation import org.echo.mobile.framework.model.operations.OperationType import org.echo.mobile.framework.model.operations.TransferOperation import org.echo.mobile.framework.support.EmptyCallback import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test /** * Test cases for [GetAccountHistorySocketOperation] * * @author <NAME> */ class GetAccountHistorySocketOperationTest { private lateinit var operation: GetAccountHistorySocketOperation private val testApiId = 3 private val testCallId = 3 private val testAccountId = "1.2.3" private val testStartId = "1.11.0" private val testLimit = 10 private val testStopId = "1.11.0" @Before fun setUp() { operation = GetAccountHistorySocketOperation( testApiId, testAccountId, testStartId, testStopId, testLimit, Testnet(), testCallId, callback = EmptyCallback() ) } @Test fun serializeToJsonTest() { val json = operation.toJsonObject().asJsonObject assertEquals(json.get(OperationCodingKeys.ID.key).asInt, testCallId) assertEquals( json.get(OperationCodingKeys.METHOD.key).asString, SocketMethodType.CALL.key ) val parameters = json.getAsJsonArray(OperationCodingKeys.PARAMS.key) assertTrue(parameters.size() == 3) val apiId = parameters[0].asInt assertEquals(apiId, testApiId) val apiName = parameters[1].asString assertEquals(apiName, SocketOperationKeys.ACCOUNT_HISTORY.key) val requestParameters = parameters[2].asJsonArray assertTrue(requestParameters.size() == 4) val accountId = requestParameters[0].asString assertEquals(accountId, testAccountId) val startId = requestParameters[1].asString assertEquals(startId, testStartId) val limit = requestParameters[2].asInt assert(limit == testLimit) val stopId = requestParameters[1].asString assertEquals(stopId, testStopId) } @Test fun deserializeFromJsonTest() { val history = operation.fromJson(result) assertNotNull(history) assert(history!!.transactions.size == 2) val contractHistoryItem = history.transactions[0] assertNotNull(contractHistoryItem) val contractOperationHistoryItem = contractHistoryItem.operation assertNotNull(contractOperationHistoryItem) assert(contractOperationHistoryItem is ContractCreateOperation) assert(contractOperationHistoryItem!!.id == OperationType.CONTRACT_CREATE_OPERATION.ordinal.toByte()) val transferHistoryItem = history.transactions[1] assertNotNull(transferHistoryItem) val transferOperationHistoryItem = transferHistoryItem.operation assertNotNull(transferOperationHistoryItem) assert(transferOperationHistoryItem is TransferOperation) assert(transferOperationHistoryItem!!.id == OperationType.TRANSFER_OPERATION.ordinal.toByte()) } val result = """{"id": 3, "jsonrpc": "2.0", "result": [ { "id": "1.6.506", "op": [ 31, { "fee": { "amount": 20, "asset_id": "1.3.0" }, "registrar": "1.2.22", "callee": "1.10.1", "asset_id": "1.3.0", "eth_accuracy": false, "value": { "amount": 20, "asset_id": "1.3.0" }, "gasPrice": 0, "gas": 1000000, "code": "5b34b966" } ], "result": [ 1, "1.17.102" ], "block_num": 86614, "trx_in_block": 0, "op_in_trx": 0, "virtual_op": 1437 }, { "id": "1.6.316", "op": [ 0, { "fee": { "amount": 20, "asset_id": "1.3.0" }, "from": "1.2.22", "to": "1.2.18", "amount": { "amount": 20000, "asset_id": "1.3.24" }, "extensions": [] } ], "result": [ 0, {} ], "block_num": 65681, "trx_in_block": 0, "op_in_trx": 0, "virtual_op": 900 } ]}""" }
0
Kotlin
2
5
92036a0665d706c219d183a4a7582f02b87b9f88
6,972
echo-android-framework
MIT License
lesson2/android/app/src/main/kotlin/com/example/lesson2/MainActivity.kt
Alex-Nunez
458,594,180
false
{"C++": 100921, "CMake": 47660, "Dart": 47525, "HTML": 23585, "C": 4404, "Swift": 2424, "Kotlin": 757, "Objective-C": 228}
package com.example.lesson2 import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
C++
0
0
675c6abefe8fcf872e7a42f2d07fca0caadbbb08
124
basic
Apache License 2.0
mobile/app/src/main/java/at/sunilson/tahomaraffstorecontroller/mobile/shared/presentation/components/TimepickerDialog.kt
sunilson
524,687,319
false
null
package at.sunilson.tahomaraffstorecontroller.mobile.shared.presentation.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TimePicker import androidx.compose.material3.rememberTimePickerState import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import java.time.LocalTime @OptIn(ExperimentalMaterial3Api::class) @Composable fun TimepickerDialog( onDismiss: () -> Unit = {}, onConfirm: (LocalTime) -> Unit = {} ) { val timepickerState = rememberTimePickerState() Dialog(onDismissRequest = onDismiss) { Surface( shape = MaterialTheme.shapes.large, tonalElevation = 6.dp, modifier = Modifier .width(IntrinsicSize.Min) .height(IntrinsicSize.Min) .background( shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.surface ), ) { Column(modifier = Modifier.padding(24.dp)) { TimePicker(state = timepickerState) Row(modifier = Modifier.fillMaxWidth()) { Spacer(modifier = Modifier.weight(1f)) TextButton(onClick = onDismiss) { Text("Cancel") } TextButton(onClick = { onConfirm(LocalTime.of(timepickerState.hour, timepickerState.minute)) }) { Text("Confirm") } } } } } } @Preview(showSystemUi = true) @Composable fun TimepickerDialogPreview() { TimepickerDialog() }
0
Kotlin
0
0
8dedb163d4ba1353508020fe7bfa148d65b02a0a
2,376
somfy-tahoma-raffstore-app
MIT License
client-android/lib/src/test/kotlin/stasis/test/client_android/lib/mocks/MockCredentialsManagementBridge.kt
sndnv
153,169,374
false
{"Scala": 3373826, "Kotlin": 1821771, "Dart": 853650, "Python": 363474, "Shell": 70265, "CMake": 8759, "C++": 4051, "HTML": 2655, "Dockerfile": 1942, "Ruby": 1330, "C": 691, "Swift": 594, "JavaScript": 516}
package stasis.test.client_android.lib.mocks import okio.ByteString import stasis.client_android.lib.api.clients.ServerApiEndpointClient import stasis.client_android.lib.encryption.secrets.DeviceSecret import stasis.client_android.lib.encryption.secrets.UserAuthenticationPassword import stasis.client_android.lib.security.CredentialsManagementBridge import stasis.client_android.lib.utils.Try import stasis.client_android.lib.utils.Try.Success open class MockCredentialsManagementBridge( val deviceSecret: DeviceSecret, val authenticationPassword: UserAuthenticationPassword ) : CredentialsManagementBridge { override fun initDeviceSecret(secret: ByteString): DeviceSecret = deviceSecret override suspend fun loadDeviceSecret(userPassword: CharArray): Try<DeviceSecret> = Success(deviceSecret) override suspend fun storeDeviceSecret(secret: ByteString, userPassword: CharArray): Try<DeviceSecret> = Success(deviceSecret) override suspend fun pushDeviceSecret( api: ServerApiEndpointClient, userPassword: CharArray, remotePassword: CharArray? ): Try<Unit> = Success(Unit) override suspend fun pullDeviceSecret( api: ServerApiEndpointClient, userPassword: CharArray, remotePassword: CharArray? ): Try<DeviceSecret> = Success(deviceSecret) override fun initDigestedUserPassword(digestedUserPassword: String?) = Unit override fun verifyUserPassword(userPassword: CharArray): Boolean = false override suspend fun updateUserCredentials( api: ServerApiEndpointClient, currentUserPassword: CharArray, newUserPassword: CharArray, newUserSalt: String? ): Try<UserAuthenticationPassword> = when (authenticationPassword) { is UserAuthenticationPassword.Hashed -> Success(authenticationPassword.copy()) is UserAuthenticationPassword.Unhashed -> Success(authenticationPassword.copy()) } override suspend fun reEncryptDeviceSecret( currentUserPassword: CharArray, oldUserPassword: CharArray ): Try<Unit> = Success(Unit) override fun getAuthenticationPassword(userPassword: CharArray): UserAuthenticationPassword = when (authenticationPassword) { is UserAuthenticationPassword.Hashed -> authenticationPassword.copy() is UserAuthenticationPassword.Unhashed -> authenticationPassword.copy() } }
0
Scala
4
53
d7b3002880814039b332b3d5373a16b57637eb1e
2,485
stasis
Apache License 2.0
ethers-ens/src/main/kotlin/io/ethers/ens/EnsMiddleware.kt
Kr1ptal
712,963,462
false
{"Kotlin": 1207943, "Solidity": 28233}
package io.ethers.ens import io.ethers.abi.AbiCodec import io.ethers.abi.AbiFunction import io.ethers.abi.AbiType import io.ethers.core.FastHex import io.ethers.core.Jackson import io.ethers.core.types.Address import io.ethers.core.types.BlockId import io.ethers.core.types.Bytes import io.ethers.core.types.CallRequest import io.ethers.logger.err import io.ethers.logger.getLogger import io.ethers.logger.wrn import io.ethers.providers.Provider import io.ethers.providers.middleware.Middleware import io.ethers.providers.types.RpcResponse import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import java.math.BigInteger import java.net.URI import java.net.URL import java.util.concurrent.CompletableFuture class EnsMiddleware @JvmOverloads constructor( provider: Provider, private val registryAddress: Address, private val ccipLookupLimit: Int = 4, private val httpClient: OkHttpClient = OkHttpClient(), ) : Middleware by provider { private val LOG = getLogger() private val registryContract = EnsRegistry(provider, registryAddress) @JvmOverloads constructor( provider: Provider, ccipLookupLimit: Int = 4, client: OkHttpClient = OkHttpClient(), ) : this( provider, getRegistryAddressOrThrow(provider.chainId), ccipLookupLimit, client, ) /** * Resolve ENS name to [Address], as per [specification](https://docs.ens.domains/dapp-developer-guide/resolving-names). * * Returns [RpcResponse] as [CompletableFuture]. Returns error [RpcResponse.Error]. * * Additional support for: * - [Wildcard resolution](https://docs.ens.domains/ens-improvement-proposals/ensip-10-wildcard-resolution) * - [Offchain metadata](https://docs.ens.domains/ens-improvement-proposals/ensip-16-offchain-metadata) */ fun resolveAddress(ensName: String): CompletableFuture<RpcResponse<Address>> = CompletableFuture.supplyAsync { resolveWithParameters( ensName, ExtendedResolver.FUNCTION_ADDR, ).map { AbiCodec.decode(AbiType.Address, it.value) as Address } } /** * Resolve ENS name to a text record associated with a [key], as per [specification](https://docs.ens.domains/ens-improvement-proposals/ensip-5-text-records). * * Returns [RpcResponse] as [CompletableFuture]. Returns error [RpcResponse.Error]. */ fun resolveText(ensName: String, key: String): CompletableFuture<RpcResponse<String>> = CompletableFuture.supplyAsync { return@supplyAsync resolveWithParameters( ensName, ExtendedResolver.FUNCTION_TEXT, mutableListOf(key), mutableListOf(AbiType.String), ).map { AbiCodec.decode(AbiType.String, it.value) as String } } /** * Reverse ENS name resolution, as per [specification](https://docs.ens.domains/ens-improvement-proposals/ensip-3-reverse-resolution). * * Returns [RpcResponse] as [CompletableFuture]. Returns error [RpcResponse.Error]. */ fun resolveEnsName(address: Address): CompletableFuture<RpcResponse<String>> = CompletableFuture.supplyAsync { val ensName = resolveWithParameters( reverseAddressEnsName(address), ExtendedResolver.FUNCTION_NAME, ).map { AbiCodec.decode(AbiType.String, it.value) as String } // To be certain of reverse lookup ENS name, forward resolution must resolve to the original address if (!ensName.isError) { val trueOwner = resolveAddress(ensName.resultOrThrow()).get() if (!trueOwner.isError && trueOwner.resultOrThrow() == address) { return@supplyAsync ensName } else { return@supplyAsync RpcResponse.error( Error.IncorrectOwner("True owner (${trueOwner.resultOrThrow()}) of ENS name: $ensName is not the same as provided address: $address"), ) } } return@supplyAsync ensName } /** * Resolve avatar of [ensName], as per * [specification](https://docs.ens.domains/ens-improvement-proposals/ensip-12-avatar-text-records). * * Returns [RpcResponse] as [CompletableFuture]. Returns error [RpcResponse.Error]. */ fun resolveAvatar(ensName: String): CompletableFuture<RpcResponse<URI>> = CompletableFuture.supplyAsync { val uriRes = getAvatarUri(ensName) if (uriRes.isError) return@supplyAsync uriRes.propagateError() // Get owner of ens name for NFT ownership validation val ensOwnerRes = resolveAddress(ensName).get() if (ensOwnerRes.isError) return@supplyAsync ensOwnerRes.propagateError() return@supplyAsync matchAvatarUri(uriRes.resultOrThrow(), ensOwnerRes.resultOrThrow()) } /** * Resolve avatar of [address], as per * [specification](https://docs.ens.domains/ens-improvement-proposals/ensip-12-avatar-text-records). * * Returns [RpcResponse] as [CompletableFuture]. Returns error [RpcResponse.Error]. */ fun resolveAvatar(address: Address): CompletableFuture<RpcResponse<URI>> = CompletableFuture.supplyAsync { val uriRes = getAvatarUri(address) if (uriRes.isError) return@supplyAsync uriRes.propagateError() return@supplyAsync matchAvatarUri(uriRes.resultOrThrow(), address) } /** * Resolves [ensName] with provided [abiFunction] (eg. addr(bytes32), text(bytes32,string), name(bytes32), ...) * and corresponding parameters and parameter types. */ private fun resolveWithParameters( ensName: String, abiFunction: AbiFunction, parameters: MutableList<Any> = mutableListOf(), paramTypes: MutableList<AbiType> = mutableListOf(), ): RpcResponse<Bytes> { // Check that ens name is valid if (ensName.isBlank() || (ensName.trim().length == 1 && ensName.contains("."))) { return RpcResponse.error(Error.EnsNameInvalid) } val nameHash = runCatching { NameHash.nameHash(ensName) }.getOrElse { return RpcResponse.error(Error.Normalisation(Exception(it))) } val resolverResponse = getResolver(ensName) if (resolverResponse.isError) return resolverResponse.propagateError() // Unwrap resolver from RpcResponse and call its addr() function. // If RpcResponse is an error, map it to error FailedToResolve. val resolver = resolverResponse.resultOrThrow() val supportsWildcard = resolver.supportsInterface(ENSIP_10_INTERFACE_ID).call(BlockId.LATEST).sendAwait() // add nodehash as first parameter, because it is present in all resolutions parameters.add(0, Bytes(nameHash)) paramTypes.add(0, AbiType.FixedBytes(32)) if (supportsWildcard.resultOr(false)) { val dnsEncoded = NameHash.dnsEncode(ensName) val encodedParams = abiFunction.encodeCall(parameters.toTypedArray()) val resolveResult = resolver.resolve(dnsEncoded, encodedParams) .call(BlockId.LATEST) .sendAwait() // try to decode OffchainLookup error val resolveLookupRevert = resolveResult.error?.asTypeOrNull<ExtendedResolver.OffchainLookup>() return if (resolveLookupRevert == null) { // result is resolved ens name resolveResult } else { // result is OffchainLookup error resolveOffchain( resolveLookupRevert, resolver, ccipLookupLimit, ) } } else { // Simple ENS name resolution: resolve by calling corresponding resolving function // (eg. addr(bytes32), text(bytes32, string)) of resolver directly. // Validate that resolver supports abiFunction val supportsFunction = resolver.supportsInterface(Bytes(abiFunction.selector)).call(BlockId.LATEST).sendAwait() if (!supportsFunction.resultOr(false)) { return RpcResponse.error( Error.UnsupportedSelector( resolver.address, FastHex.encodeWithPrefix(abiFunction.selector), ), ) } // create callback for corresponding function selector val callbackData = AbiCodec.encodeWithPrefix( abiFunction.selector, paramTypes, parameters.toTypedArray(), ) return provider.call( CallRequest { to = resolver.address data = Bytes(callbackData) }, BlockId.LATEST, ).map { return@map when { // Return different errors on empty address and failure to resolve it.isError -> RpcResponse.error(Error.FailedToResolve("Failed to resolve ens name: $ensName with resolver ${resolver.address}.")) // TODO - handle differently abiFunction.selector.contentEquals(ExtendedResolver.FUNCTION_ADDR.selector) && (AbiCodec.decode(AbiType.Address, it.resultOrThrow().value) as Address) == Address.ZERO -> RpcResponse.error( Error.UnknownEnsName( resolver.address, FastHex.encodeWithPrefix(nameHash), ), ) else -> it } }.sendAwait() } } /** * Get [ExtendedResolver] for [ensName] using [EnsRegistry] of current chain. */ private fun getResolver(ensName: String): RpcResponse<ExtendedResolver> { return getResolverAddress(ensName).map { ExtendedResolver(provider, it) } } /** * Get resolver address for [ensName] from [EnsRegistry]. */ private fun getResolverAddress(ensName: String): RpcResponse<Address> { val nameHash: ByteArray = runCatching { NameHash.nameHash(ensName) } .getOrElse { return RpcResponse.error(Error.Normalisation(Exception(it))) } .also { if (ensName.isEmpty()) return RpcResponse.error(Error.UnknownResolver) } val address = registryContract.resolver(Bytes(nameHash)) .call(BlockId.LATEST) .map { return@map when { it.isError -> RpcResponse.error( Error.ResolvingResolver( registryAddress, FastHex.encodeWithPrefix(nameHash), ), ) it.resultOrThrow() == Address.ZERO -> RpcResponse.error(Error.UnknownResolver) else -> it } } .sendAwait() if (address.error?.asTypeOrNull<Error.UnknownResolver>() != null) { return getResolverAddress(getParent(ensName)) } return address } /** * If result of resolver.resolve() call is [ExtendedResolver.OffchainLookup] error, try to resolve the name using * [ERC-3668: CCIP offchain data retrieval](https://eips.ethereum.org/EIPS/eip-3668) */ private fun resolveOffchain( revert: ExtendedResolver.OffchainLookup, resolver: ExtendedResolver, lookupLimit: Int, ): RpcResponse<Bytes> { // OffchainLookup.sender has to be resolver address if (revert.sender != resolver.address) { return RpcResponse.error(Error.NestedOffchainLookup) } if (revert.callData.isEmpty) return RpcResponse.error(Error.CcipRevertDataInvalid("Calldata is empty!")) // get gateway result by trying urls one by one and passing sender and data returned by OffchainLookup error val gatewayResult = httpCall(revert.urls, revert.sender, revert.callData) if (gatewayResult.isError) return gatewayResult.propagateError() // call resolver.callbackFunction(gatewayResult, extraData). If this call is CCIP, repeat the procedure. val callbackData = AbiCodec.encodeWithPrefix( revert.callbackFunction.value, CALLBACK_FUNCTION_PARAM_TYPES, arrayOf(gatewayResult.resultOrThrow(), revert.extraData), ) // dynamic bytes val callbackResult = provider.call( CallRequest { to = resolver.address data = Bytes(callbackData) }, BlockId.LATEST, ).sendAwait() // If callbackResult is OffchainLookup error, resolve using recursive CCIP calls val callbackLookupRevert = callbackResult.error?.asTypeOrNull<ExtendedResolver.OffchainLookup>() if (callbackLookupRevert != null) { if (lookupLimit <= 0) return RpcResponse.error(Error.CcipLookupLimit) return resolveOffchain(callbackLookupRevert, resolver, lookupLimit - 1) } else { // callbackResult is resolved ENS name. Decode dynamic bytes to address val resolvedDecoded = AbiCodec.decode(AbiType.Bytes, callbackResult.resultOrThrow().value) as Bytes return RpcResponse.result(resolvedDecoded) } } /** * Executes Cross-Chain Interoperability Protocol (CCIP-Read) request and returns opaque gateway response as [Bytes] * which is sent to the callbackFunction on Offchain Resolver contract. * * @param urls urls parameter of Offchain revert [ExtendedResolver.OffchainLookup] * @param sender sender parameter of [ExtendedResolver.OffchainLookup] - replacing {sender} RPC call parameter * @param calldata calldata parameter of [ExtendedResolver.OffchainLookup] - replacing {data} RPC call parameter */ private fun httpCall(urls: Array<String>, sender: Address, calldata: Bytes): RpcResponse<Bytes> { if (urls.isEmpty()) return RpcResponse.error(Error.CcipCallFailed("No urls to resolve ens name!", null)) for (url in urls) { // If url is missing mandatory {sender} parameter, try next url val request = buildCcipRequest(url, sender, calldata) ?: continue return try { val response = httpClient.newCall(request).execute().use { handleCcipResponse(it, url) } ?: continue if (response.isError) { return response.propagateError() } response } catch (e: Exception) { LOG.err(e) { e.message ?: "" } RpcResponse.error(Error.CcipCallFailed("Unknown error", e)) } } return RpcResponse.error(Error.CcipCallFailed("All urls are invalid or got server response 5xx", null)) } /** * If CCIP [response] from [url]: * - is successful, decode it and return [Bytes]. * - has status code 4xx, return error. Execution is stopped. * - has status code 5xx, return null and try another url, if present. */ private fun handleCcipResponse( response: Response, url: String, ): RpcResponse<Bytes>? { if (response.isSuccessful) { val responseBody = response.body ?: return RpcResponse.error(Error.CcipCallFailed("Response body is null (url: $url)", null)) val gatewayRequestDTO = runCatching { Jackson.MAPPER.readValue( responseBody.byteStream(), EnsGatewayResponseDTO::class.java, ) }.getOrElse { return RpcResponse.error( Error.CcipCallFailed("Error when parsing gateway response 'data' value (response: $response", it), ) } return RpcResponse.result(gatewayRequestDTO.data) } return if (response.code in 400..499) { // 4xx - return an error and stop val mes = "Received status code: ${response.code} during CCIP call (url: $url, error: ${response.message})" LOG.err { mes } RpcResponse.error(Error.CcipCallFailed(mes, null)) } else { // 5xx - server issue, try different url LOG.wrn { "500 error during CCIP call: url: $url, error: ${response.message}" } null } } /** * Builds CCIP-read [okhttp3.Request] from [url], [sender] and [calldata], where [sender] and [calldata] * are RPC request parameters. * * If RPC url contains {data}, the request is GET, otherwise POST. * * If [url] is missing {sender} parameter, return null. */ private fun buildCcipRequest(url: String, sender: Address, calldata: Bytes): Request? { if (!url.contains("{sender}")) return null // skip this url // URL expansion var href = url.replace("{sender}", sender.toString()) return if (url.contains("{data}")) { href = href.replace("{data}", calldata.toString()) Request.Builder().url(href).get().build() } else { val requestDTO = EnsGatewayRequestDTO(calldata, sender.toString()) Request.Builder().url(href) .post( Jackson.MAPPER.writeValueAsString(requestDTO) .toRequestBody(JSON_MEDIA_TYPE), ) .addHeader("Content-Type", "application/json") .build() } } /** * Converts avatar URI to URL. * * If URI schema is: * - https or data, return unchanged * - ipfs, converts IPFS into HTTPS url * - eip155, resolves NFT avatar */ private fun matchAvatarUri(avatarUri: URI, ensOwner: Address): RpcResponse<URI> { return when (val scheme = avatarUri.scheme) { "https", "data" -> RpcResponse.result(avatarUri) "ipfs" -> joinWithIPFSGateway(avatarUri) "eip155" -> { val token = getAvatarNFT(avatarUri, ensOwner) if (token.isError) return token.propagateError() val imageUriRes = resolveNftMetadata(token.resultOrThrow()) if (imageUriRes.isError) { return imageUriRes.propagateError() } val imageUri = imageUriRes.resultOrThrow() if (imageUri.scheme == "ipfs") { val httpsImageUrlRes = joinWithIPFSGateway(imageUriRes.resultOrThrow()) if (httpsImageUrlRes.isError) return httpsImageUrlRes.propagateError() return httpsImageUrlRes } return imageUriRes } else -> RpcResponse.error(Error.UnsupportedScheme(scheme)) } } /** * Retrieves [AvatarNFT] from [avatarUri] and returns it as [RpcResponse]. Performs NFT ownership validation. */ private fun getAvatarNFT(avatarUri: URI, ensOwner: Address): RpcResponse<AvatarNFT> { val parseResult = AvatarNFT.parse(avatarUri) if (parseResult.isError) return parseResult.propagateError() val nftToken = parseResult.resultOrThrow() // validate NFT ownership when (nftToken.nftType) { AvatarNFTType.ERC721 -> { val nft = ERC721(provider, nftToken.nftAddr) val nftOwnerRes = nft.ownerOf(nftToken.tokenId).call(BlockId.LATEST).sendAwait() if (nftOwnerRes.isError) { return RpcResponse.error( Error.AvatarParsing( "Error when retrieving owner of nft ${nftToken.nftAddr} (token id: ${nftToken.tokenId})", null, ), ) } val nftOwner = nftOwnerRes.resultOrThrow() if (nftOwner != ensOwner) { return RpcResponse.error( Error.IncorrectOwner( "ENS name owner: $ensOwner does not match NFT owner: $nftOwner", ), ) } } AvatarNFTType.ERC1155 -> { val nft = ERC1155(provider, nftToken.nftAddr) val balanceRes = nft.balanceOf(ensOwner, nftToken.tokenId).call(BlockId.LATEST).sendAwait() if (balanceRes.isError) { return RpcResponse.error( Error.AvatarParsing( "Error when retrieving balance of nft ${nftToken.nftAddr} (token id: ${nftToken.tokenId}, owner: $ensOwner)", null, ), ) } else if (balanceRes.resultOrThrow().compareTo(BigInteger.ZERO) == 0) { return RpcResponse.error( Error.IncorrectOwner( "ENS owner has 0 balance of token: ${nftToken.tokenId} for nft: ${nftToken.nftAddr}", ), ) } } } return RpcResponse.result(nftToken) } /** * Retrieves metadata URL from NFT, executes it and retrieves "image" parameter from result. * * Metadata URL [example](https://ipfs.io/ipfs/QmYTuHaoY1winNAxmf7JmCmSrkChuMAAnqgSuJBTiWZe9f): * ipfs://ipfs/QmYTuHaoY1winNAxmf7JmCmSrkChuMAAnqgSuJBTiWZe9f */ private fun resolveNftMetadata(token: AvatarNFT): RpcResponse<URI> { val metadataUrlRes = when (token.nftType) { AvatarNFTType.ERC721 -> ERC721(provider, token.nftAddr).tokenURI(token.tokenId).call(BlockId.LATEST).sendAwait() AvatarNFTType.ERC1155 -> ERC1155(provider, token.nftAddr).uri(token.tokenId).call(BlockId.LATEST).sendAwait() } if (metadataUrlRes.isError) return metadataUrlRes.propagateError() val metadataUriStr = metadataUrlRes.resultOrThrow() if (token.nftType == AvatarNFTType.ERC1155) { // Replace {id} with token id, zero padded to 64 hex characters metadataUriStr.replace( "{id}", FastHex.encodeWithoutPrefix(AbiCodec.encode(AbiType.UInt(256), token.tokenId)), ) } val metadataUri = runCatching { val uri = URI(metadataUriStr) if (uri.scheme == "ipfs") joinWithIPFSGateway(uri).resultOrThrow() else uri }.getOrElse { return RpcResponse.error( Error.AvatarParsing("Error on parsing NFT metadata URL: $metadataUriStr", it), ) } // Execute metadataUri request and extract "image" attribute val request = Request.Builder().url(metadataUri.toURL()).build() return runCatching { httpClient.newCall(request).execute().use { it -> if (it.isSuccessful) { val responseBody = it.body ?: return RpcResponse.error( Error.AvatarParsing( "Response body is null (url: $metadataUri)", null, ), ) val metadataDTO = runCatching { Jackson.MAPPER.readValue( responseBody.byteStream(), MetadataDTO::class.java, ) }.getOrElse { return RpcResponse.error(Error.AvatarParsing("Failed to parse response body", it)) } runCatching { RpcResponse.result(URI(metadataDTO.image)) }.getOrElse { RpcResponse.error( Error.AvatarParsing( "Failed to convert metadata image: ${metadataDTO.image} to URI", it, ), ) } } else { RpcResponse.error( Error.AvatarParsing( "Error on executing NFT metadata URL: $metadataUri for token: ${token.tokenId} of " + "NFT: ${token.nftAddr} (${it.message})", null, ), ) } } }.getOrElse { return RpcResponse.error( Error.AvatarParsing("Error while execution metadata request for url: $metadataUri", it), ) } } /** * Get avatar URI text record from [ensName]. */ private fun getAvatarUri(ensName: String): RpcResponse<URI> { val uriRes = resolveText(ensName, "avatar").get() if (uriRes.isError) { return uriRes.propagateError() } else if (uriRes.resultOrThrow().isEmpty()) { return RpcResponse.error(Error.FailedToResolve("Failed to resolve avatar of ens name: $ensName")) } return runCatching { uriRes.map { URI(it) } }.getOrElse { RpcResponse.error(Error.AvatarParsing("Error on parsing URI: ${uriRes.resultOrThrow()}", it)) } } /** * Get avatar URI text record from [address]. */ private fun getAvatarUri(address: Address): RpcResponse<URI> { // Build reverse address ENS val reverseAddr = reverseAddressEnsName(address) // Get resolver for reverse address ENS val resolverResponse = getResolver(reverseAddr) if (resolverResponse.isError) return resolverResponse.propagateError() val reverseResolver = resolverResponse.resultOrThrow() // Try to get avatar via text() for reverse address ENS val uriRes = reverseResolver.text(Bytes(NameHash.nameHash(reverseAddr)), "avatar") .call(BlockId.LATEST) .sendAwait() if (uriRes.isError || uriRes.resultOrThrow().isEmpty()) { // If text() is unsuccessful, reverse resolve address to ENS name, validate its ownership and forward resolve to avatar val ensNameRes = reverseResolver.name(Bytes(NameHash.nameHash(reverseAddr))) .call(BlockId.LATEST) .sendAwait() if (ensNameRes.isError) return ensNameRes.propagateError() val ensName = ensNameRes.resultOrThrow() // Validate ENS name by "resolving the returned name and calling addr on the resolver, checking it matches the original Ethereum address" val ensResolvesTo = resolveAddress(ensName).get() if (ensResolvesTo.isError) { return ensResolvesTo.propagateError() } else if (ensResolvesTo.resultOrThrow() != address) { return RpcResponse.error( Error.IncorrectOwner("ENS name: $ensName resolves to: ${ensResolvesTo.resultOrThrow()} which is not equal to original address: $address"), ) } // Forward resolve avatar return getAvatarUri(ensName) } return runCatching { uriRes.map { URI(it) } }.getOrElse { RpcResponse.error(Error.AvatarParsing("Error on parsing URI: ${uriRes.resultOrThrow()}", it)) } } /** * Build ENS name used for reverse address resolution: <address without prefix>.addr.reverse */ private fun reverseAddressEnsName(address: Address): String { return "${address.toString().lowercase().substring(2)}.$ENS_DOMAIN_REVERSE_REGISTER" } /** * Convert IPFS native URL into HTTPS using [IPFS_GATEWAY], as per * [specification](https://docs-ipfs-tech.ipns.dweb.link/how-to/address-ipfs-on-web/#ipfs-addressing-in-brief). */ private fun joinWithIPFSGateway(uri: URI): RpcResponse<URI> { val path = uri.toString().removePrefix("ipfs://").removePrefix("ipfs/") return RpcResponse.result(URL(URL(IPFS_GATEWAY), path).toURI()) } /** * Possible errors during ens name resolution */ sealed class Error : RpcResponse.Error() { /** * Ens name is not valid. */ data object EnsNameInvalid : Error() /** * Error on ens name normalisation attempt. */ data class Normalisation(val cause: Throwable?) : Error() { override fun doThrow() { throw RuntimeException("Normalisation failed: $cause") } } // Errors when getting resolver address /** * Error on getting resolver address from registry */ data class ResolvingResolver( val registryAddress: Address, val nameHash: String, ) : Error() { override fun doThrow() { throw RuntimeException("Error when getting resolver address from registry> $registryAddress for nameHash: $nameHash.") } } /** * Resolver address not found for given nameHash on registry. */ data object UnknownResolver : Error() // Errors when resolving ENS name with resolver /** * Resolver does not support selector */ data class UnsupportedSelector( val resolver: Address, val selector: String, ) : Error() { override fun doThrow() { throw RuntimeException("Resolver: ") } } /** * Resolver address resolved ens name to an empty address. */ data class UnknownEnsName( val resolverAddr: Address, val nameHash: String, ) : Error() { override fun doThrow() { throw RuntimeException("Resolver: $resolverAddr resolved namehash: $nameHash to an empty address!") } } /** * Resolver for ensName exists, but was not able to resolve it. */ data class FailedToResolve(val message: String) : Error() { override fun doThrow() { throw RuntimeException(message) } } // Reverse lookup specific errors /** * Reverse lookup ENS name does not resolve to original address. * The owner of ENS name is incorrect */ data class IncorrectOwner(val message: String) : Error() { override fun doThrow() { throw RuntimeException(message) } } // Avatar specific errors /** * Avatar URI scheme is not supported */ data class UnsupportedScheme(val scheme: String) : Error() { override fun doThrow() { throw RuntimeException("Avatar URI scheme: $scheme is not supported") } } data class AvatarParsing(val message: String, val cause: Throwable?) : Error() { override fun doThrow() { throw RuntimeException(message, cause) } } // CCIP specific errors /** * Cannot handle OffchainLookup raised inside nested call. */ data object NestedOffchainLookup : Error() /** * CCIP calls reached a maximum limit. */ data object CcipLookupLimit : Error() /** * Data returned with OffchainLookup error is invalid. */ data class CcipRevertDataInvalid(val message: String) : Error() { override fun doThrow() { throw RuntimeException(message) } } /** * Unknown error during CCIP call execution. */ data class CcipCallFailed(val message: String, val cause: Throwable?) : Error() { override fun doThrow() { throw RuntimeException(message, cause) } } } companion object { private val ENSIP_10_INTERFACE_ID = Bytes("0x9061b923") private val CALLBACK_FUNCTION_PARAM_TYPES = listOf(AbiType.Bytes, AbiType.Bytes) private val JSON_MEDIA_TYPE = "application/json".toMediaType() private const val ENS_DOMAIN_REVERSE_REGISTER = "addr.reverse" private val IPFS_GATEWAY = "https://ipfs.io/ipfs/" private val MAINNET_REGISTRY_ADDR = Address("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e") private val ROPSTEN_REGISTRY_ADDR = Address("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e") private val RINKEBY_REGISTRY_ADDR = Address("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e") private val GOERLI_REGISTRY_ADDR = Address("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e") private val SEPOLIA_REGISTRY_ADDR = Address("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e") private fun getRegistryAddress(chainId: Long): Address? { return when (chainId) { 1L -> MAINNET_REGISTRY_ADDR 3L -> ROPSTEN_REGISTRY_ADDR 4L -> RINKEBY_REGISTRY_ADDR 5L -> GOERLI_REGISTRY_ADDR 11155111L -> SEPOLIA_REGISTRY_ADDR else -> return null } } private fun getRegistryAddressOrThrow(chainId: Long): Address { return getRegistryAddress(chainId) ?: throw IllegalArgumentException("No registry address found for chain id: $chainId") } private fun getParent(name: String): String { val ensName = if (name.isNotEmpty()) name.trim() else "" return if (ensName == "." || !ensName.contains(".")) "" else ensName.substring(ensName.indexOf(".") + 1) } } } private data class EnsGatewayRequestDTO(val data: Bytes, val sender: String) private data class EnsGatewayResponseDTO(val data: Bytes)
9
Kotlin
1
5
11b34fd3c599576db8bcfc5fb6c0afc766df0583
34,209
ethers-kt
Apache License 2.0
buildSrc/src/main/kotlin/Publication.kt
ktorio
40,136,600
false
{"Kotlin": 5953667, "C": 453568, "Python": 948, "JavaScript": 775, "HTML": 336, "Mustache": 77, "Handlebars": 9}
/* * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ import org.gradle.api.* import org.gradle.api.publish.* import org.gradle.api.publish.maven.* import org.gradle.api.publish.maven.tasks.* import org.gradle.jvm.tasks.* import org.gradle.kotlin.dsl.* import org.gradle.plugins.signing.* import java.util.concurrent.locks.* fun isAvailableForPublication(publication: Publication): Boolean { val name = publication.name if (name == "maven") return true var result = false val jvmAndCommon = setOf( "jvm", "androidRelease", "androidDebug", "js", "wasmJs", "metadata", "kotlinMultiplatform" ) result = result || name in jvmAndCommon result = result || (HOST_NAME == "linux" && (name == "linuxX64" || name == "linuxArm64")) result = result || (HOST_NAME == "windows" && name == "mingwX64") val macPublications = setOf( "iosX64", "iosArm64", "iosSimulatorArm64", "watchosX64", "watchosArm32", "watchosArm64", "watchosSimulatorArm64", "watchosDeviceArm64", "tvosX64", "tvosArm64", "tvosSimulatorArm64", "macosX64", "macosArm64" ) result = result || (HOST_NAME == "macos" && name in macPublications) return result } fun Project.configurePublication() { apply(plugin = "maven-publish") tasks.withType<AbstractPublishToMaven>().configureEach { onlyIf { isAvailableForPublication(publication) } } val publishingUser: String? = System.getenv("PUBLISHING_USER") val publishingPassword: String? = System.getenv("PUBLISHING_PASSWORD") val repositoryId: String? = System.getenv("REPOSITORY_ID") val publishingUrl: String? = if (repositoryId?.isNotBlank() == true) { println("Set publishing to repository $repositoryId") "https://oss.sonatype.org/service/local/staging/deployByRepositoryId/$repositoryId" } else { System.getenv("PUBLISHING_URL") } val publishLocal: Boolean by rootProject.extra val globalM2: String by rootProject.extra val nonDefaultProjectStructure: List<String> by rootProject.extra val relocatedArtifacts: Map<String, String> by rootProject.extra val emptyJar = tasks.register<Jar>("emptyJar") { archiveAppendix = "empty" } the<PublishingExtension>().apply { repositories { maven { if (publishLocal) { setUrl(globalM2) } else { publishingUrl?.let { setUrl(it) } credentials { username = publishingUser password = <PASSWORD> } } } maven { name = "testLocal" setUrl("$rootProject.buildDir/m2") } } publications.forEach { val publication = it as? MavenPublication ?: return@forEach publication.pom { name = project.name description = project.description?.takeIf { it.isNotEmpty() } ?: "Ktor is a framework for quickly creating web applications in Kotlin with minimal effort." url = "https://github.com/ktorio/ktor" licenses { license { name = "The Apache Software License, Version 2.0" url = "https://www.apache.org/licenses/LICENSE-2.0.txt" distribution = "repo" } } developers { developer { id = "JetBrains" name = "<NAME>" organization = "JetBrains" organizationUrl = "https://www.jetbrains.com" } } scm { url = "https://github.com/ktorio/ktor.git" } relocatedArtifacts[project.name]?.let { newArtifactId -> distributionManagement { relocation { artifactId = newArtifactId } } } } } if (nonDefaultProjectStructure.contains(project.name)) return@apply kotlin.targets.forEach { target -> val publication = publications.findByName(target.name) as? MavenPublication ?: return@forEach if (target.platformType.name == "jvm") { publication.artifact(emptyJar) { classifier = "javadoc" } } else { publication.artifact(emptyJar) { classifier = "javadoc" } publication.artifact(emptyJar) { classifier = "kdoc" } } if (target.platformType.name == "native") { publication.artifact(emptyJar) } } } tasks.named("publish") { dependsOn(tasks.named("publishToMavenLocal")) } val signingKey = System.getenv("SIGN_KEY_ID") val signingKeyPassphrase = System.getenv("SIGN_KEY_PASSPHRASE") if (signingKey != null && signingKey != "") { extra["signing.gnupg.keyName"] = signingKey extra["signing.gnupg.passphrase"] = signingKeyPassphrase apply(plugin = "signing") the<SigningExtension>().apply { useGpgCmd() sign(the<PublishingExtension>().publications) } val gpgAgentLock: ReentrantLock by rootProject.extra { ReentrantLock() } tasks.withType<Sign> { doFirst { gpgAgentLock.lock() } doLast { gpgAgentLock.unlock() } } } val signLinuxArm64Publication = tasks.maybeNamed("signLinuxArm64Publication") if (signLinuxArm64Publication != null) { tasks.maybeNamed("publishLinuxX64PublicationToMavenRepository") { dependsOn(signLinuxArm64Publication) } } val signLinuxX64Publication = tasks.maybeNamed("signLinuxX64Publication") if (signLinuxX64Publication != null) { tasks.maybeNamed("publishLinuxArm64PublicationToMavenRepository") { dependsOn(signLinuxX64Publication) } } }
160
Kotlin
1042
12,861
7e868c503684511e7d41b247424d90baeea58cae
6,504
ktor
Apache License 2.0
src/main/kotlin/dopeasswizard/betterweapons/crafting/ModCraftings.kt
dopeasswizard
726,536,455
false
{"Kotlin": 8235, "Java": 3840}
package dopeasswizard.betterweapons.crafting import dopeasswizard.betterweapons.item.ModItems import net.minecraft.core.block.Block import net.minecraft.core.item.Item import turniplabs.halplibe.helper.RecipeHelper object ModCraftings { fun register() { RecipeHelper.Crafting.createRecipe(ModItems.toolBowSteel, 1, arrayOf<Any>( "OAB", "AOB", "OAB", 'A', Item.ingotSteel, 'B', Item.string )) RecipeHelper.Crafting.createRecipe(ModItems.toolPikeWood, 1, arrayOf<Any>( "O0A", "0I0", "I00", 'A', Block.planksOak, 'I', Item.stick )) RecipeHelper.Crafting.createRecipe(ModItems.toolPikeStone, 1, arrayOf<Any>( "O0A", "0I0", "I00", 'A', Block.cobbleStone, 'I', Item.stick )) RecipeHelper.Crafting.createRecipe(ModItems.toolPikeIron, 1, arrayOf<Any>( "O0A", "0I0", "I00", 'A', Item.ingotIron, 'I', Item.stick )) RecipeHelper.Crafting.createRecipe(ModItems.toolPikeGold, 1, arrayOf<Any>( "O0A", "0I0", "I00", 'A', Item.ingotGold, 'I', Item.stick )) RecipeHelper.Crafting.createRecipe(ModItems.toolPikeDiamond, 1, arrayOf<Any>( "O0A", "0I0", "I00", 'A', Item.diamond, 'I', Item.stick )) RecipeHelper.Crafting.createRecipe(ModItems.toolPikeSteel, 1, arrayOf<Any>( "O0A", "0I0", "I00", 'A', Item.ingotSteel, 'I', Item.stick )) } }
0
Kotlin
0
0
cdbb18b9e849df4a649e2d5b00e8696dbb1e1bd9
1,373
BetterWeapons
Creative Commons Zero v1.0 Universal
src/test/kotlin/io/github/lobodpav/spock/test/idea/Idea.kt
lobodpav
671,811,601
false
{"Kotlin": 29105, "Groovy": 20885, "HTML": 886}
package io.github.lobodpav.spock.test.idea import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.codeInspection.LocalInspectionTool import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.module.Module import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import com.intellij.testFramework.fixtures.CodeInsightTestFixture import com.intellij.testFramework.replaceService import org.jetbrains.plugins.groovy.GroovyFileType /** * Convenience methods allowing for Idea environment manipulation. */ class Idea( private val codeInsightTestFixture: CodeInsightTestFixture, ) { val project: Project = codeInsightTestFixture.project val module: Module = codeInsightTestFixture.module /** Loads any content into the in-memory editor */ fun loadGroovyFileContent(content: String): PsiFile = codeInsightTestFixture.configureByText(GroovyFileType.GROOVY_FILE_TYPE, content) /** Creates a file with the specified content and loads it into the in-memory editor */ fun loadGroovyFileContent(filePath: String, content: String): PsiFile = codeInsightTestFixture.configureByText(filePath, content) /** Wraps the content in a class extending [spock.lang.Specification] and loads it into the in-memory editor */ fun loadSpecWithBody(specBody: String): PsiFile = loadGroovyFileContent(specBody.wrapInSpec()) /** * Returns a directory in the project's virtual file system. * @param relativePath Either an empty string for the `src/` source root directory, or a path to a directory inside the `src/`. */ fun findOrCreateDirectory(relativePath: String = ""): PsiDirectory { val dir = codeInsightTestFixture.tempDirFixture.findOrCreateDir(relativePath) return runReadAction { codeInsightTestFixture.psiManager.findDirectory(dir) ?: throw IllegalStateException("Did not find a PSI directory for '$relativePath'") } } /** Allows tests to switch to Dumb mode by providing a mock service */ fun replaceDumbService(newDumbService: DumbService) { project.replaceService(DumbService::class.java, newDumbService, codeInsightTestFixture.testRootDisposable) } /** Enables defined inspections to be able to test highlighting of errors */ fun enableInspections(vararg inspections: Class<LocalInspectionTool>) { codeInsightTestFixture.enableInspections(*inspections) } /** Returns highlighted warnings and errors */ fun runHighlighting(): List<HighlightInfo> = codeInsightTestFixture.doHighlighting(HighlightSeverity.WARNING) /** * PSI write access is only allowed from inside a write-action, * that must be run on the AWT event dispatching thread under Write Intent lock. * Moreover, PSI changes must happen within a command or an undo-transparent action. * * Therefore, this extension wraps the closure inside a [WriteCommandAction.runWriteCommandAction] and waits for the result. * * @see io.github.lobodpav.spock.test.PsiElementJvmExtensions.read */ fun write(runnable: () -> Unit) { // java.lang.RuntimeException: com.intellij.util.IncorrectOperationException: // Must not change PSI outside command or undo-transparent action. // See com.intellij.openapi.command.WriteCommandAction or com.intellij.openapi.command.CommandProcessor WriteCommandAction.runWriteCommandAction(project) { runnable() } } private fun <T> runReadAction(supplier: () -> T): T = ApplicationManager.getApplication().runReadAction<T> { supplier() } } private fun String.wrapInSpec(): String = """ package test import spock.lang.Specification class Spec extends Specification { $this } """.trimIndent()
0
Kotlin
0
1
d8bf49f83d6ea1cddb1acd25a1154f67073f7267
4,065
spock-intellij-plugin
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/managerecallsapi/config/OpenApiConfiguration.kt
ministryofjustice
371,053,303
false
null
package uk.gov.justice.digital.hmpps.managerecallsapi.config import io.swagger.v3.oas.models.OpenAPI import io.swagger.v3.oas.models.info.Contact import io.swagger.v3.oas.models.info.Info import org.springdoc.core.SpringDocUtils import org.springframework.boot.info.BuildProperties import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import uk.gov.justice.digital.hmpps.managerecallsapi.domain.ColumnName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.CourtId import uk.gov.justice.digital.hmpps.managerecallsapi.domain.CourtName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.CroNumber import uk.gov.justice.digital.hmpps.managerecallsapi.domain.DocumentId import uk.gov.justice.digital.hmpps.managerecallsapi.domain.Email import uk.gov.justice.digital.hmpps.managerecallsapi.domain.FieldName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.FieldPath import uk.gov.justice.digital.hmpps.managerecallsapi.domain.FirstName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.FullName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.LastKnownAddressId import uk.gov.justice.digital.hmpps.managerecallsapi.domain.LastName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.MiddleNames import uk.gov.justice.digital.hmpps.managerecallsapi.domain.MissingDocumentsRecordId import uk.gov.justice.digital.hmpps.managerecallsapi.domain.NomsNumber import uk.gov.justice.digital.hmpps.managerecallsapi.domain.NoteId import uk.gov.justice.digital.hmpps.managerecallsapi.domain.PhoneNumber import uk.gov.justice.digital.hmpps.managerecallsapi.domain.PoliceForceId import uk.gov.justice.digital.hmpps.managerecallsapi.domain.PoliceForceName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.PrisonId import uk.gov.justice.digital.hmpps.managerecallsapi.domain.PrisonName import uk.gov.justice.digital.hmpps.managerecallsapi.domain.RecallId import uk.gov.justice.digital.hmpps.managerecallsapi.domain.RescindRecordId import uk.gov.justice.digital.hmpps.managerecallsapi.domain.UserId import uk.gov.justice.digital.hmpps.managerecallsapi.domain.WarrantReferenceNumber import java.util.UUID @Configuration class OpenApiConfiguration(buildProperties: BuildProperties) { private val version: String = buildProperties.version companion object { init { SpringDocUtils.getConfig() .replaceWithClass(NomsNumber::class.java, String::class.java) .replaceWithClass(NomsNumber::class.java, String::class.java) .replaceWithClass(CroNumber::class.java, String::class.java) .replaceWithClass(FirstName::class.java, String::class.java) .replaceWithClass(MiddleNames::class.java, String::class.java) .replaceWithClass(LastName::class.java, String::class.java) .replaceWithClass(FullName::class.java, String::class.java) .replaceWithClass(Email::class.java, String::class.java) .replaceWithClass(PhoneNumber::class.java, String::class.java) .replaceWithClass(WarrantReferenceNumber::class.java, String::class.java) .replaceWithClass(RecallId::class.java, UUID::class.java) .replaceWithClass(DocumentId::class.java, UUID::class.java) .replaceWithClass(MissingDocumentsRecordId::class.java, UUID::class.java) .replaceWithClass(RescindRecordId::class.java, UUID::class.java) .replaceWithClass(NoteId::class.java, UUID::class.java) .replaceWithClass(LastKnownAddressId::class.java, UUID::class.java) .replaceWithClass(UserId::class.java, UUID::class.java) .replaceWithClass(PrisonId::class.java, String::class.java) .replaceWithClass(PrisonName::class.java, String::class.java) .replaceWithClass(CourtId::class.java, String::class.java) .replaceWithClass(CourtName::class.java, String::class.java) .replaceWithClass(PoliceForceId::class.java, String::class.java) .replaceWithClass(PoliceForceName::class.java, String::class.java) .replaceWithClass(FieldName::class.java, String::class.java) .replaceWithClass(FieldPath::class.java, String::class.java) .replaceWithClass(ColumnName::class.java, String::class.java) } } @Bean fun customOpenAPI(): OpenAPI? = OpenAPI() .info( Info().title("Manage Recalls API").version(version).description( "Back end for Manage Recalls UI. Future API for Recalls: not currently the operational system of reference, which remains PPUD." ) .contact(Contact().name("HMPPS Digital Studio").email("[email protected]")) ) }
3
null
0
1
708e801435483b0406197fdc61e85ab7c2d2cc82
4,635
manage-recalls-api
MIT License
kt-extensions/src/main/java/com/mindera/skeletoid/kt/extensions/utils/AssetFileProvider.kt
Mindera
85,591,428
false
{"Gradle": 12, "XML": 18, "CODEOWNERS": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 9, "Batchfile": 1, "YAML": 1, "Markdown": 10, "Proguard": 8, "Kotlin": 160, "Java": 5}
package com.mindera.skeletoid.kt.extensions.utils import android.content.Context import java.nio.charset.Charset object AssetFileProvider { fun readFile(context: Context, assetFile: String): String { return context.assets .open(assetFile) .readBytes() .toString(Charset.defaultCharset()) } }
7
Kotlin
3
24
881de796fbbe835c74f69f36ccf327bdcb0029f3
346
skeletoid
MIT License
px-checkout/src/main/java/com/mercadopago/android/px/internal/view/experiments/ExperimentHelper.kt
mercadopago
49,529,486
false
null
package com.mercadopago.android.px.internal.view.experiments import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.mercadopago.android.px.internal.experiments.Variant import com.mercadopago.android.px.addons.model.internal.Experiment object ExperimentHelper { fun getVariantsFrom(experiments: List<Experiment>?, vararg localVariants: Variant) = localVariants.map { getVariantFrom(it, experiments) } private fun getVariantFrom(variant: Variant, experiments: List<Experiment>?): Variant { if (experiments != null) { for (experiment in experiments) { val variantName = experiment.variant.name if (variant.isExperiment(experiment.name) && variant.isVariant(variantName)) { return variant } } } return variant.default } fun applyExperimentViewBy(root: ViewGroup, variant: Variant): View = LayoutInflater.from(root.context).inflate(variant.resVariant, root) }
44
null
77
98
b715075dd4cf865f30f6448f3c00d6e9033a1c21
1,050
px-android
MIT License
idea/testData/refactoring/extractFunction/basic/extensionFunForArray.kt
JakeWharton
99,388,807
false
null
// PARAM_TYPES: kotlin.Array<T>, kotlin.Any, kotlin.Cloneable, java.io.Serializable // PARAM_DESCRIPTOR: public fun <T> kotlin.Array<T>.test(): kotlin.Unit defined in root package in file extensionFunForArray.kt // SIBLING: fun <T> Array<T>.test() { <selection>this.isEmpty()</selection> }
0
null
4
83
4383335168338df9bbbe2a63cb213a68d0858104
294
kotlin
Apache License 2.0
core/compiler.common.jvm/src/org/jetbrains/kotlin/load/java/JvmAnnotationNames.kt
nskvortsov
4,137,859
true
{"Kotlin": 54887563, "Java": 7682828, "JavaScript": 185344, "HTML": 79768, "Lex": 23805, "TypeScript": 21756, "Groovy": 11196, "Swift": 9789, "CSS": 9270, "Shell": 7220, "Batchfile": 5727, "Ruby": 2655, "Objective-C": 444, "Scala": 80, "C": 59}
/* * Copyright 2010-2015 JetBrains s.r.o. * * 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 org.jetbrains.kotlin.load.java import org.jetbrains.kotlin.name.FqName val NULLABLE_ANNOTATIONS: List<FqName> = listOf( JvmAnnotationNames.JETBRAINS_NULLABLE_ANNOTATION, FqName("androidx.annotation.Nullable"), FqName("android.support.annotation.Nullable"), FqName("android.annotation.Nullable"), FqName("com.android.annotations.Nullable"), FqName("org.eclipse.jdt.annotation.Nullable"), FqName("org.checkerframework.checker.nullness.qual.Nullable"), FqName("javax.annotation.Nullable"), FqName("javax.annotation.CheckForNull"), FqName("edu.umd.cs.findbugs.annotations.CheckForNull"), FqName("edu.umd.cs.findbugs.annotations.Nullable"), FqName("edu.umd.cs.findbugs.annotations.PossiblyNull"), FqName("io.reactivex.annotations.Nullable") ) val JAVAX_NONNULL_ANNOTATION: FqName = FqName("javax.annotation.Nonnull") val JAVAX_CHECKFORNULL_ANNOTATION: FqName = FqName("javax.annotation.CheckForNull") val NOT_NULL_ANNOTATIONS: List<FqName> = listOf( JvmAnnotationNames.JETBRAINS_NOT_NULL_ANNOTATION, FqName("edu.umd.cs.findbugs.annotations.NonNull"), FqName("androidx.annotation.NonNull"), FqName("android.support.annotation.NonNull"), FqName("android.annotation.NonNull"), FqName("com.android.annotations.NonNull"), FqName("org.eclipse.jdt.annotation.NonNull"), FqName("org.checkerframework.checker.nullness.qual.NonNull"), FqName("lombok.NonNull"), FqName("io.reactivex.annotations.NonNull") ) val COMPATQUAL_NULLABLE_ANNOTATION: FqName = FqName("org.checkerframework.checker.nullness.compatqual.NullableDecl") val COMPATQUAL_NONNULL_ANNOTATION: FqName = FqName("org.checkerframework.checker.nullness.compatqual.NonNullDecl") val ANDROIDX_RECENTLY_NULLABLE_ANNOTATION: FqName = FqName("androidx.annotation.RecentlyNullable") val ANDROIDX_RECENTLY_NON_NULL_ANNOTATION: FqName = FqName("androidx.annotation.RecentlyNonNull") val NULLABILITY_ANNOTATIONS: Set<FqName> = mutableSetOf<FqName>() + NULLABLE_ANNOTATIONS + JAVAX_NONNULL_ANNOTATION + NOT_NULL_ANNOTATIONS + COMPATQUAL_NULLABLE_ANNOTATION + COMPATQUAL_NONNULL_ANNOTATION + ANDROIDX_RECENTLY_NULLABLE_ANNOTATION + ANDROIDX_RECENTLY_NON_NULL_ANNOTATION val READ_ONLY_ANNOTATIONS: List<FqName> = listOf( JvmAnnotationNames.JETBRAINS_READONLY_ANNOTATION, JvmAnnotationNames.READONLY_ANNOTATION ) val MUTABLE_ANNOTATIONS: List<FqName> = listOf( JvmAnnotationNames.JETBRAINS_MUTABLE_ANNOTATION, JvmAnnotationNames.MUTABLE_ANNOTATION )
0
Kotlin
0
3
39d15501abb06f18026bbcabfd78ae4fbcbbe2cb
3,165
kotlin
Apache License 2.0
src/com/theah64/mock_api/database/Images.kt
theapache64
91,213,451
false
{"Java": 246193, "Kotlin": 171960, "JavaScript": 14154, "CSS": 3391}
package com.theah64.mock_api.database import com.theah64.mock_api.models.Image import com.theah64.webengine.database.BaseTable import com.theah64.webengine.database.querybuilders.AddQueryBuilder import com.theah64.webengine.database.querybuilders.QueryBuilderException import com.theah64.webengine.database.querybuilders.SelectQueryBuilder import com.theah64.webengine.database.querybuilders.UpdateQueryBuilder import java.sql.ResultSet import java.sql.SQLException class Images private constructor() : BaseTable<Image>("images") { //id, projectId, tinifyKeyId, imageUrl, thumbUrl; @Throws(SQLException::class, QueryBuilderException::class) override fun add(newInstance: Image): Boolean { return addv3(newInstance) != "-1" } @Throws(QueryBuilderException::class, SQLException::class) override fun addv3(newInstance: Image): String { return AddQueryBuilder.Builder(tableName) .add(COLUMN_PROJECT_ID, newInstance.projectId) .add(COLUMN_TINIFY_KEY_ID, newInstance.tinifyKeyId) .add(COLUMN_IMAGE_URL, newInstance.imageUrl) .add(COLUMN_THUMB_URL, newInstance.thumbUrl) .add(COLUMN_FILE_PATH, newInstance.filePath) .add(COLUMN_IS_COMPRESSED, newInstance.isCompressed) .doneAndReturn().toString() } @Throws(QueryBuilderException::class, SQLException::class) override fun getAll(whereColumn: String, whereColumnValue: String): List<Image> { return SelectQueryBuilder<Image>( tableName, SelectQueryBuilder.Callback<Image> { this.getImageFromResultSet(it) }, arrayOf(Images.COLUMN_ID, COLUMN_PROJECT_ID, COLUMN_TINIFY_KEY_ID, COLUMN_IMAGE_URL, COLUMN_THUMB_URL, COLUMN_FILE_PATH, COLUMN_IS_COMPRESSED), arrayOf(whereColumn), arrayOf(whereColumnValue), SelectQueryBuilder.UNLIMITED, Images.COLUMN_ID + " DESC" ).all } override fun get(column1: String, value1: String, column2: String?, value2: String?): Image? { return SelectQueryBuilder<Image>( tableName, SelectQueryBuilder.Callback<Image> { this.getImageFromResultSet(it) }, arrayOf(Images.COLUMN_ID, COLUMN_PROJECT_ID, COLUMN_TINIFY_KEY_ID, COLUMN_IMAGE_URL, COLUMN_THUMB_URL, COLUMN_FILE_PATH, COLUMN_IS_COMPRESSED), arrayOf(column1, column2), arrayOf(value1, value2), "1", Images.COLUMN_ID + " DESC" ).get() } @Throws(SQLException::class) private fun getImageFromResultSet(rs: ResultSet): Image { return Image( rs.getString(BaseTable.COLUMN_ID), rs.getString(COLUMN_PROJECT_ID), rs.getString(COLUMN_TINIFY_KEY_ID), rs.getString(COLUMN_IMAGE_URL), rs.getString(COLUMN_THUMB_URL), rs.getString(COLUMN_FILE_PATH), rs.getBoolean(COLUMN_IS_COMPRESSED)) } @Throws(SQLException::class, QueryBuilderException::class) override fun update(t: Image): Boolean { return UpdateQueryBuilder.Builder(tableName) .set(COLUMN_IMAGE_URL, t.imageUrl) .set(COLUMN_IS_COMPRESSED, t.isCompressed) .where(BaseTable.COLUMN_ID, t.id) .build() .done() } companion object { const val COLUMN_ID = "id" const val COLUMN_PROJECT_ID = "project_id" const val COLUMN_IMAGE_URL = "image_url" const val COLUMN_THUMB_URL = "thumb_url" const val COLUMN_FILE_PATH = "file_path" const val COLUMN_IS_COMPRESSED = "is_compressed" val instance = Images() const val COLUMN_TINIFY_KEY_ID = "tinify_key_id" } }
5
Java
1
1
f19a9e650a6641ccd59192c176fbbc8eb51cf473
3,762
Mock-API
Apache License 2.0
src/main/kotlin/com/github/seliba/devcordbot/command/context/Context.kt
JohnnyJayJay
263,324,944
true
{"Kotlin": 196318, "Java": 7717}
/* * Copyright 2020 <NAME> & <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.github.seliba.devcordbot.command.context import com.github.seliba.devcordbot.command.AbstractCommand import com.github.seliba.devcordbot.command.CommandClient import com.github.seliba.devcordbot.command.permission.Permission import com.github.seliba.devcordbot.constants.Embeds import com.github.seliba.devcordbot.core.DevCordBot import com.github.seliba.devcordbot.dsl.EmbedConvention import com.github.seliba.devcordbot.dsl.sendMessage import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.JDA import net.dv8tion.jda.api.entities.* import net.dv8tion.jda.api.requests.restaction.MessageAction /** * Representation of a context of a command execution. * @property command the executed command * @property args the [Arguments] of the command * @property commandClient the [CommandClient] which executed this command * @property bot instance of the [DevCordBot] * @property message the message that triggered the command */ @Suppress("MemberVisibilityCanBePrivate", "unused") data class Context( val bot: DevCordBot, val command: AbstractCommand, val args: Arguments, val message: Message, val commandClient: CommandClient ) { /** * The [JDA] instance. */ val jda: JDA get() = message.jda /** * The id of [message]. */ val messageId: Long get() = message.idLong /** * The [TextChannel] of [message]. */ val channel: TextChannel get() = message.textChannel /** * The author of the [message]. */ val author: User get() = message.author /** * The member of the [author]. */ val member: Member get() = message.member!! //CommandClient ignores webhook messages, so this cannot be null /** * The guild of the [channel]. */ val guild: Guild get() = message.guild /** * The [self member][Member] of the bot. */ val me: Member get() = guild.selfMember /** * The [SelfUser] of the bot. */ val selfUser: SelfUser get() = jda.selfUser /** * Sends [content] into [channel]. * @return a [MessageAction] that sends the message */ fun respond(content: String): MessageAction = channel.sendMessage(content) /** * Sends [embed] into [channel]. * @return a [MessageAction] that sends the message */ fun respond(embed: MessageEmbed): MessageAction = channel.sendMessage(embed) /** * Sends [embedBuilder] into [channel]. * @return a [MessageAction] that sends the message */ fun respond(embedBuilder: EmbedBuilder): MessageAction = channel.sendMessage(embedBuilder.build()) /** * Sends [embed] into [channel]. * @return a [MessageAction] that sends the message */ fun respond(embed: EmbedConvention): MessageAction = channel.sendMessage(embed) /** * Sends a help embed for [command]. * @see Embeds.command */ fun sendHelp(): MessageAction = respond(Embeds.command(command)) /** * Checks whether the [member] has [Permission.ADMIN] or not. */ fun hasAdmin(): Boolean = hasPermission(Permission.ADMIN) /** * Checks whether the [member] has [Permission.MODERATOR] or not. */ fun hasModerator(): Boolean = hasPermission(Permission.MODERATOR) private fun hasPermission(permission: Permission) = commandClient.permissionHandler.isCovered(permission, member) }
0
null
0
0
8a1240e14726354d08f682f46084522a6a9c9ffb
4,092
DevcordBot
Apache License 2.0
arrow-libs/optics/arrow-optics/src/test/kotlin/arrow/optics/instances/IndexInstanceTest.kt
tiarebalbi
111,073,383
false
null
package arrow.optics.instances import arrow.core.test.UnitSpec import arrow.core.test.generators.functionAToB import arrow.optics.test.laws.OptionalLaws import arrow.optics.typeclasses.Index import io.kotlintest.properties.Gen class IndexInstanceTest : UnitSpec() { init { testLaws( OptionalLaws.laws( optionalGen = Gen.int().map { Index.list<String>().index(it) }, aGen = Gen.list(Gen.string()), bGen = Gen.string(), funcGen = Gen.functionAToB(Gen.string()) ) ) } }
2
null
1
1
12f047b4a7d267e622933bc991f57a05ecf63add
526
kategory
Apache License 2.0
shark/shark-android/src/main/java/shark/AndroidExtensions.kt
square
34,824,499
false
{"Kotlin": 1569511, "Java": 4762, "Shell": 531, "AIDL": 203}
package shark import shark.HeapObject.HeapInstance /** * The system identity hash code, or null if it couldn't be found. * * Based on the Object.identityHashCode implementation in AOSP. * * Backing field shadow$_monitor_ was added in API 24. * https://cs.android.com/android/_/android/platform/libcore/+ * /de626ec8a109ea18283d96c720cc57e2f32f67fa:ojluni/src/main/java/java/lang/Object.java; * dlc=ba7cc9f5357c323a1006119a20ce025fd4c57fd2 */ val HeapInstance.identityHashCode: Int? get() { // Top 2 bits. val lockWordStateMask = -0x40000000 // Top 2 bits are value 2 (kStateHash). val lockWordStateHash = -0x80000000 // Low 28 bits. val lockWordHashMask = 0x0FFFFFFF val lockWord = this["java.lang.Object", "shadow\$_monitor_"]?.value?.asInt return if (lockWord != null && lockWord and lockWordStateMask == lockWordStateHash) { lockWord and lockWordHashMask } else null } /** * The system identity hashCode represented as hex, or null if it couldn't be found. * This is the string identifier you see when calling Object.toString() at runtime on a class that * does not override its hashCode() method, e.g. com.example.MyThing@6bd57cf */ val HeapInstance.hexIdentityHashCode: String? get() { val hashCode = identityHashCode ?: return null return Integer.toHexString(hashCode) }
81
Kotlin
3958
29,180
5738869542af44bdfd8224603eac7af82327b054
1,351
leakcanary
Apache License 2.0
Mali_Giganci_kotlin/app/src/main/java/com/example/maligiganci/GameTicTacToeHard.kt
karolinam11
624,081,217
false
{"Kotlin": 112142, "TypeScript": 24106, "HTML": 15336, "SCSS": 3239}
package com.example.maligiganci import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.view.View import android.widget.Button import androidx.appcompat.app.AlertDialog import com.example.maligiganci.databinding.ActivityGameTicTacToeBinding import com.google.firebase.database.FirebaseDatabase class GameTicTacToeHard : AppCompatActivity() { enum class Turn { NOUGHT, CROSS } private var firstTurn = Turn.CROSS private var currentTurn = Turn.CROSS private var crossesScore = 0 private var noughtsScore = 0 private var boardList = mutableListOf<Button>() private lateinit var binding: ActivityGameTicTacToeBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityGameTicTacToeBinding.inflate(layoutInflater) setContentView(binding.root) initBoard() if (firstTurn == Turn.CROSS) { // Jeśli pierwszy ruch należy do komputera, wykonaj jego ruch po 1 sekundzie Handler().postDelayed({ val randomButton = getEmptyRandomButton() if (randomButton != null) { addToBoard(randomButton) } }, 1000) } } private fun initBoard() { boardList.add(binding.a1) boardList.add(binding.a2) boardList.add(binding.a3) boardList.add(binding.b1) boardList.add(binding.b2) boardList.add(binding.b3) boardList.add(binding.c1) boardList.add(binding.c2) boardList.add(binding.c3) } fun boardTapped(view: View) { if (view !is Button) return // Użytkownik wykonuje ruch addToBoard(view) if (checkForVictory(NOUGHT)) { noughtsScore++ result("Wygrywasz!") } else if (fullBoard()) { result("Remis") } else { // Komputer wykonuje ruch po 1 sekundzie Handler().postDelayed({ val bestMove = getBestMove() if (bestMove != null) { addToBoard(bestMove) if (checkForVictory(CROSS)) { crossesScore++ result("Komputer wygrywa!") } else if (fullBoard()) { result("Remis") } } }, 1000) } } private fun checkForVictory(symbol: String): Boolean { // Sprawdzenie poziomych linii zwycięstwa if (match(binding.a1, symbol) && match(binding.a2, symbol) && match(binding.a3, symbol)) return true if (match(binding.b1, symbol) && match(binding.b2, symbol) && match(binding.b3, symbol)) return true if (match(binding.c1, symbol) && match(binding.c2, symbol) && match(binding.c3, symbol)) return true // Sprawdzenie pionowych linii zwycięstwa if (match(binding.a1, symbol) && match(binding.b1, symbol) && match(binding.c1, symbol)) return true if (match(binding.a2, symbol) && match(binding.b2, symbol) && match(binding.c2, symbol)) return true if (match(binding.a3, symbol) && match(binding.b3, symbol) && match(binding.c3, symbol)) return true // Sprawdzenie diagonalnych linii zwycięstwa if (match(binding.a1, symbol) && match(binding.b2, symbol) && match(binding.c3, symbol)) return true if (match(binding.a3, symbol) && match(binding.b2, symbol) && match(binding.c1, symbol)) return true return false } private fun match(button: Button, symbol: String): Boolean = button.text == symbol private fun result(title: String) { val databaseReference = FirebaseDatabase.getInstance().getReference("blockBaby/TicTacToe/Hard") databaseReference.child("youHardTicTacToe").setValue(noughtsScore) databaseReference.child("computerHardTicTacToe").setValue(crossesScore) val message = "\nTy $noughtsScore\n\nKomputer $crossesScore" AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .setPositiveButton("Zagraj ponownie") { _, _ -> resetBoard() } .setCancelable(false) .show() } //zamiana kolejności zaczynania gry i reset planszy private fun resetBoard() { for (button in boardList) { button.text = "" } if (firstTurn == Turn.NOUGHT) firstTurn = Turn.CROSS else if (firstTurn == Turn.CROSS) firstTurn = Turn.NOUGHT currentTurn = firstTurn if (currentTurn == Turn.CROSS) { // Jeśli pierwszy ruch należy do komputera, wykonaj jego ruch po 1 sekundzie Handler().postDelayed({ val randomButton = getEmptyRandomButton() if (randomButton != null) { addToBoard(randomButton) } }, 1000) } } private fun fullBoard(): Boolean { for (button in boardList) { if (button.text == "") return false } return true } private fun addToBoard(button: Button) { if (button.text != "") return if (currentTurn == Turn.NOUGHT) { button.text = NOUGHT currentTurn = Turn.CROSS binding.turnTV.text = "Kolej komputera" } else if (currentTurn == Turn.CROSS) { button.text = CROSS currentTurn = Turn.NOUGHT binding.turnTV.text = "Twoja kolej" } } private fun getEmptyRandomButton(): Button? { val emptyButtons = boardList.filter { it.text.isEmpty() } return emptyButtons.randomOrNull() } private fun getBestMove(): Button? { // Sprawdź, czy komputer może wygrać w jednym ruchu for (button in boardList) { if (button.text.isEmpty()) { button.text = CROSS if (checkForVictory(CROSS)) { button.text = "" return button } button.text = "" } } // Sprawdź, czy użytkownik może wygrać w jednym ruchu i zablokuj go for (button in boardList) { if (button.text.isEmpty()) { button.text = NOUGHT if (checkForVictory(NOUGHT)) { button.text = "" return button } button.text = "" } } // Wybierz losowe puste pole return getEmptyRandomButton() } companion object { const val NOUGHT = "O" const val CROSS = "X" } }
0
Kotlin
0
0
3b531f7dfd0a60087a0424ef4788159d18e40cb3
6,936
ZPOProjekt
MIT License
composeApp/src/desktopMain/kotlin/com/zzz1zzz/todolist_cmp/main.kt
zaferertas
863,013,724
false
{"Kotlin": 44574, "Swift": 688}
package com.zzz1zzz.todolist_cmp import androidx.compose.ui.window.application import com.zzz1zzz.todolist_cmp.di.initKoin import org.koin.core.Koin lateinit var koin: Koin fun main() { koin = initKoin().koin return application { MainWindow(applicationScope = this) } }
0
Kotlin
0
0
08e7d61bc691a4a0b2a0cc9a4af4c8b85a624898
293
todolistCMP
Apache License 2.0
mobile_app1/module224/src/main/java/module224packageKt0/Foo518.kt
uber-common
294,831,672
false
null
package module224packageKt0; annotation class Foo518Fancy @Foo518Fancy class Foo518 { fun foo0(){ module224packageKt0.Foo517().foo3() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
237
android-build-eval
Apache License 2.0
net.akehurst.kaf/common/realisation/src/macosX64Main/kotlin/common/Application.kt
dhakehurst
166,023,488
false
null
package net.akehurst.kaf.common.realisation import net.akehurst.kaf.api.AFApplication import net.akehurst.kaf.api.Application import net.akehurst.kaf.service.api.Service import net.akehurst.kaf.service.api.ServiceReference import net.akehurst.kaf.service.logging.api.LogLevel import net.akehurst.kaf.service.logging.api.Logger import kotlin.reflect.KProperty1 actual class ApplicationFrameworkService(){ actual fun doInjections(commandLineArgs: List<String>, root: Identifiable) { } } actual inline fun afApplication(self: Application, id: String, init: AFApplicationDefault.Builder.() -> Unit): AFApplication { val builder = AFApplicationDefault.Builder(self, id) builder.init() return builder.build() } actual class AFApplicationDefault( val self: Application, afIdentity: String, val defineServices: (commandLineArgs:List<String>) -> Map<String, Service>, initialise: () -> Unit, execute: () -> Unit, terminate: () -> Unit ) : AFComponentDefault(afIdentity, initialise, execute, terminate), AFApplication { actual class Builder( val self: Application, val id: String ) { actual var initialise: () -> Unit = {} actual var execute: () -> Unit = {} actual var terminate: () -> Unit = {} actual var defineServices: (commandLineArgs:List<String>) -> Map<String, Service> = { emptyMap() } actual fun build(): AFApplication { return AFApplicationDefault(self, id, defineServices, initialise, execute, terminate) } } private lateinit var _services:Map<String, Service> val services:Map<String, Service> get() { return this._services } private fun logger(): Logger { return this.services["logger"] as Logger } private fun doInjections(commandLineArgs: List<String>) { //TODO: native can't support reflection! } override fun start(commandLineArgs: List<String>) { this._services = this.defineServices(commandLineArgs) logger().log(LogLevel.DEBUG, { "[${this.identity}] Application.start" }) this.doInjections(commandLineArgs) super.start() } }
0
Kotlin
0
0
f74c333396998ad2ead9e5cdd964f88ac4af44d4
2,192
net.akehurst.kaf
Apache License 2.0
app/src/main/java/com/kaii/customwidgets/music_widget/shortboi_ui/Controls.kt
kaii-lb
766,526,006
false
{"Kotlin": 186920}
package com.kaii.customwidgets.music_widget.shortboi_ui import android.graphics.BlendMode import android.graphics.PorterDuff import android.graphics.drawable.Icon import android.media.session.PlaybackState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.unit.dp import androidx.glance.GlanceModifier import androidx.glance.Image import androidx.glance.ImageProvider import androidx.glance.LocalContext import androidx.glance.action.clickable import androidx.glance.appwidget.action.actionRunCallback import androidx.glance.appwidget.cornerRadius import androidx.glance.layout.Alignment import androidx.glance.layout.Column import androidx.glance.layout.ContentScale import androidx.glance.layout.Row import androidx.glance.layout.fillMaxHeight import androidx.glance.layout.fillMaxSize import androidx.glance.layout.fillMaxWidth import androidx.glance.layout.height import androidx.glance.layout.padding import androidx.glance.layout.size import androidx.glance.layout.width import com.kaii.customwidgets.R import com.kaii.customwidgets.music_widget.extension_functions.LaunchMediaPlayer import com.kaii.customwidgets.notification_listener_service.NotificationListenerCustomService @Composable fun ShortControls(playbackState: Int) { Row( modifier = GlanceModifier .fillMaxWidth() .padding(4.dp, 4.dp, 8.dp, 0.dp) .clickable( rippleOverride = R.drawable.music_button_ripple, onClick = actionRunCallback(LaunchMediaPlayer::class.java) ), verticalAlignment = Alignment.Vertical.CenterVertically, horizontalAlignment = Alignment.Horizontal.End, ) { val icon: Icon val scale: ContentScale if (NotificationListenerCustomService.statusBarIcon != null) { icon = NotificationListenerCustomService.statusBarIcon ?: Icon.createWithResource( LocalContext.current, R.drawable.genres) scale = ContentScale.Fit icon.setTint(Color.White.toArgb()) } else { icon = Icon.createWithResource(LocalContext.current, R.drawable.genres) scale = ContentScale.Crop } icon.setTintMode(PorterDuff.Mode.SRC_IN) icon.setTintBlendMode(BlendMode.SRC_IN) // music player icon + launch button Image( provider = ImageProvider(icon), contentDescription = "music player", contentScale = scale, modifier = GlanceModifier.height(18.dp) // 26.dp ) } var playPauseDrawable by remember { mutableIntStateOf(R.drawable.play) } playPauseDrawable = if (playbackState == PlaybackState.STATE_PLAYING) { R.drawable.pause } else { R.drawable.play } Row ( modifier = GlanceModifier .fillMaxSize() // size(size.width * 1.15f) .cornerRadius(24.dp), verticalAlignment = Alignment.Vertical.CenterVertically, horizontalAlignment = Alignment.Horizontal.CenterHorizontally, ) { Column( modifier = GlanceModifier .fillMaxHeight() .width(50.dp) .clickable( rippleOverride = R.drawable.music_button_ripple ) { Thread.sleep(50) NotificationListenerCustomService.skipBackward() Thread.sleep(50) } .padding((2).dp, 22.dp, 0.dp, 40.dp), // size(size.width * 1.15f), verticalAlignment = Alignment.Vertical.CenterVertically, horizontalAlignment = Alignment.Horizontal.CenterHorizontally, ) { // skip backwards button Image(provider = ImageProvider(R.drawable.skip_back), contentDescription = "skip backwards", contentScale = ContentScale.Fit, modifier = GlanceModifier .defaultWeight() .size(40.dp) ) } Column( modifier = GlanceModifier .fillMaxHeight() .width(50.dp) .clickable( rippleOverride = R.drawable.music_button_ripple ) { Thread.sleep(50) NotificationListenerCustomService.playPause() Thread.sleep(50) } .padding(0.dp, 22.dp, 0.dp, 40.dp), // size(size.width * 1.15f), verticalAlignment = Alignment.Vertical.CenterVertically, horizontalAlignment = Alignment.Horizontal.CenterHorizontally, ) { // play pause button Image(provider = ImageProvider(playPauseDrawable), contentDescription = "play pause", contentScale = ContentScale.Fit, modifier = GlanceModifier .defaultWeight() .size(42.dp) ) } Column( modifier = GlanceModifier .fillMaxHeight() .width(50.dp) .clickable( rippleOverride = R.drawable.music_button_ripple ) { Thread.sleep(50) NotificationListenerCustomService.skipForward() Thread.sleep(50) } .padding(0.dp, 22.dp, 4.dp, 40.dp), // size(size.width * 1.15f), verticalAlignment = Alignment.Vertical.CenterVertically, horizontalAlignment = Alignment.Horizontal.CenterHorizontally, ) { // skip forward button Image(provider = ImageProvider(R.drawable.skip_ahead), contentDescription = "skip forwards", contentScale = ContentScale.Fit, modifier = GlanceModifier .defaultWeight() .size(40.dp) ) } } }
0
Kotlin
1
1
d567b50dcabc64d4c58bec2e68e0c8365433882e
6,242
CustomWidgets
MIT License
moviemade/src/main/java/org/michaelbel/moviemade/ui/settings/SettingsScreen.kt
michaelbel
115,437,864
false
null
package org.michaelbel.moviemade.ui.settings import androidx.appcompat.app.AppCompatDelegate import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.ArrowBack import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.google.accompanist.insets.systemBarsPadding import org.michaelbel.moviemade.R import org.michaelbel.moviemade.ui.NavGraph @Composable fun SettingsScreen( navController: NavController ) { val viewModel: SettingsViewModel = hiltViewModel() Scaffold( modifier = Modifier.fillMaxSize(), topBar = { Toolbar(navController) } ) { Content(navController, viewModel) } } @Composable private fun Toolbar( navController: NavController ) { SmallTopAppBar( title = { Text( text = stringResource(R.string.title_settings) ) }, modifier = Modifier.systemBarsPadding(), navigationIcon = { IconButton( onClick = { navController.popBackStack() } ) { Image( imageVector = Icons.Outlined.ArrowBack, contentDescription = null, colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.onSurface) ) } } ) } @Composable private fun Content( navController: NavController, viewModel: SettingsViewModel ) { var themeDialog by remember { mutableStateOf(false) } val currentTheme: Int = viewModel.currentTheme.collectAsState(viewModel.themes.first()).value if (themeDialog) { AlertDialog( onDismissRequest = { themeDialog = false }, confirmButton = {}, title = { Text( text = stringResource(R.string.theme) ) }, text = { Column { viewModel.themes.forEach { theme -> val textId = when (theme) { AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM -> R.string.theme_system AppCompatDelegate.MODE_NIGHT_NO -> R.string.theme_light AppCompatDelegate.MODE_NIGHT_YES -> R.string.theme_dark else -> throw Exception() } val selected: Boolean = currentTheme == theme Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clickable { themeDialog = false viewModel.selectTheme(theme) } ) { RadioButton( selected = selected, colors = RadioButtonDefaults.colors( selectedColor = MaterialTheme.colorScheme.secondary, unselectedColor = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6F) ), onClick = { themeDialog = false viewModel.selectTheme(theme) } ) Spacer(modifier = Modifier.size(4.dp)) Text(text = stringResource(id = textId)) } } } } ) } Column { SettingsListItem( title = { Text( text = stringResource(R.string.theme) ) }, onClick = { themeDialog = true } ) SettingsListItem( title = { Text( text = stringResource(R.string.title_about) ) }, onClick = { navController.navigate(NavGraph.About.route) } ) } }
4
Kotlin
15
57
4da7746083f7739451b5244097f79bfbb3a882ca
4,640
Moviemade
Apache License 2.0
app/src/main/java/com/example/testapplication/util/DateConverter.kt
DaniZakaria63
668,744,134
false
null
package com.example.testapplication.util import androidx.room.TypeConverter import java.util.Date class DateConverter { @TypeConverter fun timestampToDate(value: Long?) : Date? { return value?.let { Date(it) } } @TypeConverter fun dateToTimestamp(date: Date?) : Long? { return date?.time?.toLong() } }
0
Kotlin
0
0
e49765fd227152e25d62b8fa60aadd3522d6aad6
344
test-flow-notification
The Unlicense
app/src/test/java/ua/com/radiokot/photoprism/PhotoPrismMediaWebUrlFactoryTest.kt
Radiokot
612,884,518
false
null
package ua.com.radiokot.photoprism import okhttp3.HttpUrl.Companion.toHttpUrl import org.junit.Assert import org.junit.Test import ua.com.radiokot.photoprism.features.gallery.logic.PhotoPrismMediaWebUrlFactory class PhotoPrismMediaWebUrlFactoryTest { @Test fun getWebViewUrl() { val factory = PhotoPrismMediaWebUrlFactory( webLibraryUrl = "https://photoprism.me/library/".toHttpUrl(), ) val url = factory.getWebViewUrl( uid = "prtkeob2g20yq13w", ) Assert.assertEquals( "https://photoprism.me/library/browse?q=uid%3Aprtkeob2g20yq13w%20quality%3A0&public=false&view=cards", url ) } }
0
Kotlin
8
121
97b659c553b25b4bdc59a1e245229f61f0667db2
691
photoprism-android-client
Apache License 2.0
module-api/src/main/java/langchainkt/model/output/FinishReason.kt
c0x12c
655,095,005
false
{"Kotlin": 322914, "Java": 13181}
package langchainkt.model.output enum class FinishReason { STOP, LENGTH, TOOL_EXECUTION, CONTENT_FILTER }
0
Kotlin
0
0
1dc065a3aec804d53259171f6f95206eb2fdb0b6
115
langchainkt
Apache License 2.0
examples/android/src/main/kotlin/com/algolia/instantsearch/examples/android/showcase/compose/ui/component/HelpDialog.kt
algolia
55,971,521
false
{"Kotlin": 689459}
package com.algolia.instantsearch.examples.showcase.compose.ui.component import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material.AlertDialog import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.algolia.instantsearch.examples.R @Composable fun HelpDialog(openDialog: MutableState<Boolean>, text: String) { HelpDialog(openDialog, arrayOf(text)) } @Composable fun HelpDialog(openDialog: MutableState<Boolean>, text: Array<String>) { if (openDialog.value) { AlertDialog( onDismissRequest = { openDialog.value = false }, title = { Text(text = stringResource(R.string.help)) }, text = { Column { text.forEach { Text(text = it, modifier = Modifier.padding(vertical = 2.dp)) } } }, confirmButton = { TextButton(onClick = { openDialog.value = false }) { Text(stringResource(R.string.ok)) } } ) } }
5
Kotlin
32
156
cb068acebbe2cd6607a6bbeab18ddafa582dd10b
1,417
instantsearch-android
Apache License 2.0
exams/01-FirstMidterm/app/src/main/java/dev/beriashvili/exams/firstmidterm/models/LaunchesModel.kt
GiorgiBeriashvili
244,119,530
false
null
package dev.beriashvili.exams.firstmidterm.models import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.SerializedName class LaunchesModel() : Parcelable { @SerializedName("flight_number") var flightNumber: Int? = 0 @SerializedName("mission_name") var missionName: String? = "" @SerializedName("launch_date_utc") var launchDate: String? = "" var rocket: Rocket? = Rocket() class Rocket { @SerializedName("rocket_name") var rocketName: String? = "" override fun toString(): String { return "Rocket(rocketName=$rocketName)" } } @SerializedName("launch_success") var launchSuccess: Boolean? = false var links: Links? = Links() class Links { @SerializedName("flickr_images") var images: List<String?>? = listOf() override fun toString(): String { return "Links(images=$images)" } } var details: String? = "" constructor(parcel: Parcel) : this() { flightNumber = parcel.readValue(Int::class.java.classLoader) as? Int missionName = parcel.readString() launchDate = parcel.readString() launchSuccess = parcel.readValue(Boolean::class.java.classLoader) as? Boolean details = parcel.readString() } override fun toString(): String { return "LaunchModel(flightNumber=$flightNumber, missionName=$missionName, launchDate=$launchDate, rocket=$rocket, launchSuccess=$launchSuccess, links=$links, details=$details)" } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeValue(flightNumber) parcel.writeString(missionName) parcel.writeString(launchDate) parcel.writeValue(launchSuccess) parcel.writeString(details) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<LaunchesModel> { override fun createFromParcel(parcel: Parcel): LaunchesModel { return LaunchesModel(parcel) } override fun newArray(size: Int): Array<LaunchesModel?> { return arrayOfNulls(size) } } }
0
Kotlin
0
0
c8edb8ff208c66f6ed609f8d98b0e2421129eb77
2,207
android-development
MIT License
library/src/main/java/com/kuaishou/akdanmaku/DanmakuConfig.kt
duqian291902259
469,999,372
true
{"Kotlin": 264991, "Java": 38793}
/* * The MIT License (MIT) * * Copyright 2021 Kwai, Inc. All rights reserved. * * 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. */ /******************************************************************************* * Copyright 2021 Kwai, Inc. All rights reserved. * * 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.kuaishou.akdanmaku import android.util.Log import com.kuaishou.akdanmaku.ecs.DanmakuEngine import com.kuaishou.akdanmaku.ecs.component.filter.DanmakuDataFilter import com.kuaishou.akdanmaku.ecs.component.filter.DanmakuLayoutFilter import com.kuaishou.akdanmaku.ext.RETAINER_AKDANMAKU /** * 弹幕场景设置参数 */ data class DanmakuConfig( var retainerPolicy: Int = RETAINER_AKDANMAKU, /** * 预加载缓存的时间提前量 */ var preCacheTimeMs: Long = 100L, /** * 弹幕的显示时长,滚动类型的弹幕为从屏幕一端出现到屏幕另一端完全移出的时间 */ var durationMs: Long = DEFAULT_DURATION, /** * 滚动弹幕持续时间 */ var rollingDurationMs: Long = durationMs, /** * 文本缩放倍数 */ var textSizeScale: Float = 1f, /** * 播放速率 */ var timeFactor: Float = 1f, /** * 滚动弹幕屏幕的显示区域 */ var screenPart: Float = 1f, /** * 弹幕显示的透明度(不会影响选中的) */ var alpha: Float = 1f, /** * 弹幕是否以粗体渲染 */ var bold: Boolean = true, /** * 绘图 Bitmap 的密度 */ var density: Int = 160, /** * 弹幕是否可见 */ var visibility: Boolean = true, /** * 是否允许重叠 */ var allowOverlap: Boolean = false, /** * 可见性标记,当可见性发生变化时更新 */ var visibilityGeneration: Int = 0, /** * 布局变化标记位,当需要对弹幕重新布局时更新此值 */ var layoutGeneration: Int = 0, /** * 缓存标记位,当弹幕本身样式发生变化需要对绘制样式与缓存进行更新时更新此值 */ var cacheGeneration: Int = 0, /** * 测量标记位,与缓存类似 */ var measureGeneration: Int = 0, /** * 过滤器标记位,当过滤器发生变动时(个数或具体值)更新此值 */ var filterGeneration: Int = 0, /** * 排布标记位,当需要清空排布器,重新高度排布时更新此值 */ var retainerGeneration: Int = 0, /** * 渲染标记位,一般意义上每一次 Update 后都会更新此值,用于计算跳帧与绘制 */ var renderGeneration: Int = 0, /** * 首次显示标记位,主要用于埋点 */ internal var firstShownGeneration: Int = 0, var dataFilter: List<DanmakuDataFilter> = emptyList(), var layoutFilter: List<DanmakuLayoutFilter> = emptyList() ) { var allGeneration = visibilityGeneration + layoutGeneration + cacheGeneration + measureGeneration + filterGeneration + retainerGeneration + renderGeneration private set fun updateVisibility() { visibilityGeneration++ allGeneration++ logGeneration("visibility", visibilityGeneration) } fun updateCache() { cacheGeneration++ allGeneration++ logGeneration("cache", cacheGeneration) } fun updateFilter() { filterGeneration++ allGeneration++ logGeneration("filter", filterGeneration) } fun updateMeasure() { measureGeneration++ allGeneration++ logGeneration("measure", measureGeneration) } fun updateLayout() { layoutGeneration++ allGeneration++ logGeneration("layout", layoutGeneration) } fun updateRetainer() { retainerGeneration++ allGeneration++ logGeneration("retainer", retainerGeneration) } fun updateRender() { renderGeneration++ allGeneration++ } fun updateFirstShown() { firstShownGeneration++ } companion object { private fun logGeneration(type: String, generation: Int) { Log.d(DanmakuEngine.TAG, "Generation[$type] update to $generation") } // 50M 缓存池 var CACHE_POOL_MAX_MEMORY_SIZE = 1024 * 1024 * 50 const val DEFAULT_DURATION = 3800L } }
0
Kotlin
0
0
d5e94969bb7eb7d3e0d299254c3ddbf9c6b06a17
5,639
AkDanmaku
MIT License
app/src/main/java/com/fireblocks/sdkdemo/ui/events/EventWrapper.kt
fireblocks
690,587,303
false
{"Kotlin": 686152, "HTML": 788}
package com.fireblocks.sdkdemo.ui.events import com.fireblocks.sdk.events.Event /** * Created by Fireblocks Ltd. on 13/04/2023. */ class EventWrapper(val event: Event, val index: Int, val timestamp: Long) { override fun toString(): String { return "EventWrapper(event=$event, index=$index)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as EventWrapper if (event != other.event) return false if (index != other.index) return false return true } override fun hashCode(): Int { var result = event.hashCode() result = 31 * result + index return result } }
1
Kotlin
3
1
71d5b09868bfb97766fd2bafbd657bcf66c1a5f3
754
android-ncw-demo
MIT License
src/main/kotlin/y2022/day13/Day13.kt
TimWestmark
571,510,211
false
{"Kotlin": 64408, "Shell": 1067}
package y2022.day13 fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } var index = 0 fun initParseData(line: String): List<Any> { index = 0 return parseData(line) } fun parseData(line: String): List<Any> { val list: MutableList<Any> = mutableListOf() while (index < line.length) { when (line[index]) { '[' -> { index++ list.add(parseData(line)) } ']' -> { index++ break } ',' -> index++ else -> { var numberString: String = line[index].toString() // this is a digit do { index++ if (line[index].isDigit()) { numberString += line[index] } } while (line[index].isDigit()) list.add(numberString.toInt()) } } } return list } fun input(): List<Pair<List<Any>, List<Any>>> { return AoCGenerics.getInputLines("/y2022/day13/input.txt") .chunked(3) .map { index = 0 val firstData = it[0] val secondData = it[1] Pair(initParseData(firstData), initParseData(secondData)) } } fun compareTo(a: List<Any>, b: List<Any>): Int { return inOrder(Pair(a,b)) } fun inOrder(pair: Pair<List<Any>, List<Any>>): Int { val left = pair.first val right = pair.second for (i in 0 until maxOf(left.size, right.size)) { when { left.size <= i -> return 1 right.size <= i -> return -1 left[i] is Int && right[i] is Int -> { return if ((left[i] as Int) < (right[i] as Int)) { 1 } else if ((left[i] as Int) > (right[i] as Int)) { -1 } else continue } left[i] is List<*> && right[i] is List<*> -> { val x = inOrder(Pair(left[i] as List<Any>, right[i] as List<Any> )) if (x != 0) return x else continue } left[i] is List<*> && right[i] is Int -> { return inOrder(Pair(left[i] as List<Any>, listOf(right[i]))) } left[i] is Int && right[i] is List<*> -> { return inOrder(Pair(listOf(left[i]), right[i] as List<Any> )) } } } return 0 } fun part1(): Int { val input = input() return input.mapIndexedNotNull { index, pair -> if (inOrder(pair) > 0) { index + 1 } else { null } }.sum() } fun part2(): Int { val test = input().map { pair -> listOf(pair.first, pair.second) }.flatten().toMutableList() val add1 = listOf(listOf(2)) val add2 = listOf(listOf(6)) test.add(add1) test.add(add2) val myComparator = Comparator<List<Any>> { element1, element2 -> inOrder(Pair(element1, element2)) } val sorted = test.sortedWith(myComparator).reversed() val index1 = sorted.indexOf(add1) + 1 val index2 = sorted.indexOf(add2) + 1 return index1 * index2 }
0
Kotlin
0
0
caab9fb60283783eca2eb123e527c676a66c8001
3,248
AdventOfCode
MIT License
src/main/kotlin/com/mynimef/telegrambot/config/Annotations.kt
MYnimef
458,524,261
false
{"Kotlin": 36843}
package com.mynimef.telegrambot.config /** * Annotation for functions to define the action on the specified command */ @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) annotation class BotCommand(val command: String) /** * Annotation for functions to define the callback from pressing inline buttons */ @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) annotation class BotCallback(val callback: String)
0
Kotlin
0
12
74cd276bd7c63538f5282f55661a8e72f88ed3d0
461
telegrambot-kotlin
MIT License
examples/android-material-ui/app/app/src/main/java/com/intuit/august2020/storybookdemoapp/CardActivity.kt
vasikarla-zz
307,909,395
true
{"TypeScript": 5448, "JavaScript": 381}
package com.intuit.august2020.storybookdemoapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class CardActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_card) } }
0
TypeScript
0
1
9c9a6514998c5a707de613ade3a5c3a84ab53869
320
native
MIT License
editor/src/main/com/mbrlabs/mundus/editor/ui/widgets/MaterialSelectWidget.kt
JamesTKhan
455,272,467
false
null
package com.mbrlabs.mundus.editor.ui.widgets import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.Touchable import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.kotcrab.vis.ui.util.dialog.Dialogs import com.kotcrab.vis.ui.util.dialog.InputDialogAdapter import com.kotcrab.vis.ui.widget.VisLabel import com.kotcrab.vis.ui.widget.VisTable import com.kotcrab.vis.ui.widget.VisTextButton import com.mbrlabs.mundus.commons.assets.Asset import com.mbrlabs.mundus.commons.assets.MaterialAsset import com.mbrlabs.mundus.editor.Mundus import com.mbrlabs.mundus.editor.assets.AssetAlreadyExistsException import com.mbrlabs.mundus.editor.assets.AssetMaterialFilter import com.mbrlabs.mundus.editor.core.project.ProjectManager import com.mbrlabs.mundus.editor.events.AssetSelectedEvent import com.mbrlabs.mundus.editor.events.MaterialDuplicatedEvent import com.mbrlabs.mundus.editor.ui.UI import com.mbrlabs.mundus.editor.ui.modules.dialogs.assets.AssetPickerDialog import com.mbrlabs.mundus.editor.utils.Colors import java.io.FileNotFoundException /** * Displays a materials name and allows the user to change/edit/duplicate it. * Use the [matChangedListener] to get notified when the material has changed. * * @author JamesTKhan * @version June 02, 2023 */ class MaterialSelectWidget(var material: MaterialAsset?) : VisTable() { private val matFilter: AssetMaterialFilter = AssetMaterialFilter() private val matEditBtn: VisTextButton = VisTextButton("Edit") private val matDuplicatedBtn: VisTextButton = VisTextButton("Duplicate") private val matChangedBtn: VisTextButton = VisTextButton("Change") private val matPickerListener: AssetPickerDialog.AssetPickerListener private val matNameLabel: VisLabel = VisLabel() private val projectManager: ProjectManager = Mundus.inject() private val root: VisTable = VisTable() /** * An optional listener for changing the material. If the property is null * the user will not be able to change the material. */ var matChangedListener: MaterialWidget.MaterialChangedListener? = null set(value) { field = value matChangedBtn.touchable = if(value == null) Touchable.disabled else Touchable.enabled } init { setupUI() matPickerListener = object: AssetPickerDialog.AssetPickerListener { override fun onSelected(asset: Asset?) { material = (asset as? MaterialAsset)!! matChangedListener?.materialChanged(material!!) updateUI() } } matDuplicatedBtn.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { Dialogs.showInputDialog(UI, "Name:", "", object : InputDialogAdapter() { override fun finished(input: String?) { if (input != null) { try { val newMaterial = projectManager.current().assetManager.createMaterialAsset(input) if (material != null) { newMaterial.duplicateMaterialAsset(material) } material = newMaterial updateUI() matChangedListener?.materialChanged(material!!) Mundus.postEvent(MaterialDuplicatedEvent()) } catch (e: AssetAlreadyExistsException) { Dialogs.showErrorDialog(UI, "That material already exists. Try a different name.") } catch (e: FileNotFoundException) { Dialogs.showErrorDialog(UI, "Invalid material name.") } } } }) } }) matChangedBtn.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { UI.assetSelectionDialog.show(false, matFilter, matPickerListener) } }) matEditBtn.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { Mundus.postEvent(AssetSelectedEvent(material!!)) UI.docker.assetsDock.setSelected(material!!) } }) } private fun setupUI() { matNameLabel.color = Colors.TEAL matNameLabel.wrap = true add(root).grow().row() root.add(matNameLabel).grow() root.add(matEditBtn) root.add(matDuplicatedBtn).padLeft(4f).right() root.add(matChangedBtn).padLeft(4f).right().row() updateUI() } private fun updateUI() { matNameLabel.setText(if (material == null) "None Selected" else material?.name) matEditBtn.touchable = if (material == null) Touchable.disabled else Touchable.enabled matDuplicatedBtn.touchable = if (material == null) Touchable.disabled else Touchable.enabled matEditBtn.isDisabled = material == null matDuplicatedBtn.isDisabled = material == null } }
22
null
18
94
d196adb1853561aa80f68c57bcaf2a24948aa2b7
5,278
Mundus
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/appconfig/ActionDsl.kt
F43nd1r
643,016,506
false
{"Kotlin": 5432532}
package com.faendir.awscdkkt.generated.services.appconfig import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.appconfig.Action @Generated public fun buildAction(initializer: @AwsCdkDsl Action.Builder.() -> Unit = {}): Action = Action.Builder.create().apply(initializer).build()
1
Kotlin
0
4
3d0f80e3da7d0d87d9a23c70dda9f278dbd3f763
364
aws-cdk-kt
Apache License 2.0
1015/MainActivity.kt
rlawnsqja2
771,865,830
false
{"Kotlin": 13346}
package com.example.m05_intent import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.view.View import android.widget.RadioGroup import android.widget.Toast import androidx.activity.result.ActivityResult import androidx.activity.result.ActivityResultCallback import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import com.example.m05_intent.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) class ImgOnClickListener : View.OnClickListener { override fun onClick(v: View?) { val toast = Toast.makeText(baseContext, R.string.no_image, Toast.LENGTH_LONG) toast.show() } } val iCL = ImgOnClickListener() binding.imageView.setOnClickListener(iCL) class TextOnClickListener : View.OnClickListener { override fun onClick(v: View?) { Log.d("ekpark", "The title is clicked.") } } val tCL = TextOnClickListener() binding.textTitle.setOnClickListener(tCL) binding.radioGroupKind.setOnCheckedChangeListener(object:RadioGroup.OnCheckedChangeListener { override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) { var msg = when(checkedId) { R.id.radioButtonC -> "의류" R.id.radioButtonB -> "도서" R.id.radioButtonE -> "가전제품" R.id.radioButtonT -> "기타" else -> "선택 오류" } Toast.makeText(baseContext, msg, Toast.LENGTH_LONG).show() } }) // input : Intent, output : ActivityResult val contract = ActivityResultContracts.StartActivityForResult() val callback = object : ActivityResultCallback<ActivityResult>{ override fun onActivityResult(result: ActivityResult) { // SaleActivity에서 넘겨준 데이터를 처리 if(result.resultCode == RESULT_OK){ val intentRS = result.data val placePosition = intentRS?.getIntExtra("placeInfo", 0) val placeArray = arrayOf("학교 정문앞", "3호관 정문", "학생 식당 앞", "도서관 앞", "Dream cafe", "오류") Toast.makeText(baseContext, placeArray[placePosition!!], Toast.LENGTH_LONG).show() binding.radioButtonC.isChecked = true binding.checkBoxPrice.isChecked = false binding.editTextText.text.clear() // binding.editTextText.setText("") } else if(result.resultCode == RESULT_CANCELED){ Toast.makeText(baseContext, "취소되었습니다.", Toast.LENGTH_LONG).show() binding.radioButtonC.isChecked = true binding.checkBoxPrice.isChecked = false binding.editTextText.text.clear() } else if(result.resultCode == RESULT_FIRST_USER + 100){ Toast.makeText(baseContext, "수정해주세요.", Toast.LENGTH_LONG).show() } } } val launcher = registerForActivityResult(contract, callback) binding.buttonOK.setOnClickListener { val detailInfo = binding.editTextText.text.toString().trim() if(detailInfo.isEmpty()) { Toast.makeText(baseContext, R.string.detail_hint, Toast.LENGTH_LONG).show() return@setOnClickListener } var kindInfo = when (binding.radioGroupKind.checkedRadioButtonId) { R.id.radioButtonC -> "의류" R.id.radioButtonB -> "도서" R.id.radioButtonE -> "가전" R.id.radioButtonT -> "기타" else -> "오류" } val intentS = Intent(baseContext, SaleActivity::class.java) intentS.putExtra("kInfo", kindInfo) intentS.putExtra("dInfo", detailInfo) intentS.putExtra("pInfo", binding.checkBoxPrice.isChecked) launcher.launch(intentS) //startActivity(intentS) } binding.textViewLink.setOnClickListener{ val intentA = Intent(Intent.ACTION_DIAL, Uri.parse("tel:010-2941-1345")) startActivity(intentA) } } // oncreate }
0
Kotlin
0
0
909832306514b225625dec339b421a8990118f77
4,552
and
MIT License
sample/src/main/java/com/example/dics/activtity_flow/FlowActivity1.kt
sirbralex
532,984,642
false
{"Kotlin": 28051}
package com.example.dics.activtity_flow import android.content.Intent import android.os.Bundle import com.example.dics.base.BaseActivity import com.example.dics.context.diContext import com.example.dics.contextimpl.obtainComponent import com.example.dics.component.Feature_1_Component class FlowActivity1 : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) goBtn.setOnClickListener { startActivity(Intent(this, FlowActivity2::class.java)) finish() } diContext.obtainComponent(Feature_1_Component::class) } }
0
Kotlin
0
2
be6139ae39226908d79be99faa2449a10a7146d1
630
dics
Apache License 2.0
src/main/kotlin/dog/catfood/controllers/DeviceApiController.kt
jbrwn
614,677,886
false
null
package dog.catfood.controllers import dog.catfood.logic.DeviceService import dog.catfood.logic.LocationService import dog.catfood.models.getDevicePrincipal import dog.catfood.plugins.controllers.Controller import dog.catfood.plugins.controllers.GET import dog.catfood.plugins.controllers.POST import dog.catfood.plugins.controllers.authentication.Authenticate import io.ktor.server.application.ApplicationCall import io.ktor.server.plugins.NotFoundException import io.ktor.server.request.receive import io.ktor.server.response.respond import java.time.OffsetDateTime @Authenticate("auth-cert") class DeviceApiController( private val deviceService: DeviceService, private val locationService: LocationService, ): Controller { @GET("/device") suspend fun getDevice(call: ApplicationCall) { val devicePrincipal = call.getDevicePrincipal() val device = deviceService.getDevice(devicePrincipal.id) ?: throw NotFoundException("Device ${devicePrincipal.id} not found") call.respond(device) } @POST("/device/location") suspend fun createLocation(call: ApplicationCall) { val devicePrincipal = call.getDevicePrincipal() val request = call.receive<CreateLocationRequest>() val location = locationService.createLocation(devicePrincipal.id, request) call.respond(location) } } data class CreateLocationRequest( val longitude: Double, // decimal degrees val latitude: Double, // decimal degrees val altitude: Double, // meters val speed: Double, // knots val angle: Double, // Degrees from true north val magneticVariation: Double, // Degrees from true north val timestamp: OffsetDateTime, // fix time )
0
Kotlin
0
0
15572a3335783312282f512946a5c84127c5dc99
1,724
catfood
MIT License
src/commonMain/kotlin/baaahs/show/migration/V6_FlattenPatches.kt
baaahs
174,897,412
false
{"Kotlin": 4817815, "C": 1529197, "C++": 661363, "GLSL": 412779, "JavaScript": 61944, "HTML": 56277, "CMake": 30499, "CSS": 4340, "Shell": 2381, "Python": 1450}
package baaahs.show.migration import baaahs.show.DataMigrator import kotlinx.serialization.json.* /** * This migration simplifies things by merging patches and shader instances. * * In V5 shows: * * { * // Control-level patches: * "controls": { * "aControl": { ... * "patches": [ * { "shaderInstanceIds": ["a"], "surfaces": {...} } * ] * } * }, * // Show-level patches: * "patches": [ * { "shaderInstanceIds": ["b"], "surfaces": {...} } * ], * // ShaderInstance dict: * "shaderInstanceIds": { * "a": {...} * "b": {...} * } * } * * In V6 shows, Patches and ShaderInstances are merged: * * { * // Control-level patches: * "controls": [ * { ... "patchIds": ["a"] } * ], * // Show-level patches: * "patchIds": ["b"], * "patches": { * "a": {..., "surfaces": {...} } * } * } * * Since surfaces currently always match everything, we can safely drop it. */ @Suppress("ClassName") object V6_FlattenPatches : DataMigrator.Migration(6) { private val dataSourceTypeMap = mapOf( "baaahs.Core.FixtureInfo" to "baaahs.Core:FixtureInfo" ) override fun migrate(from: JsonObject): JsonObject { return from.toMutableMap().apply { // Convert patches found in the top-level Show: this.remove("patches")?.jsonArray?.let { showPatches -> this["patchIds"] = extractShaderInstanceIds(showPatches) } // Convert patches found in any Control: mapObjsInDict("controls") { _, control -> control.remove("patches")?.jsonArray?.let { controlPatches -> control["patchIds"] = extractShaderInstanceIds(controlPatches) } } this.remove("shaderInstances")?.jsonObject?.let { shaderInstances -> this["patches"] = shaderInstances } }.toJsonObj() } private fun extractShaderInstanceIds(patches: JsonArray): JsonArray = buildJsonArray { patches.forEach { patch -> patch.jsonObject["shaderInstanceIds"]!!.jsonArray.forEach { shaderInstanceId -> add(shaderInstanceId) } } } }
111
Kotlin
13
40
77ad22b042fc0ac440410619dd27b468c3b3a600
2,272
sparklemotion
MIT License
enro-core/src/main/java/dev/enro/extensions/AnimatedContentScope.KeepVisibleWith.kt
isaac-udy
256,179,010
false
{"Kotlin": 1447007}
package dev.enro.extensions import androidx.compose.animation.AnimatedVisibilityScope import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.core.Transition import androidx.compose.animation.core.animateInt import androidx.compose.animation.core.tween import androidx.compose.runtime.Composable import androidx.compose.runtime.key /** * By default, an AnimatedVisibility composable created with Transition<T>.AnimatedVisibility will stop rendering child content * even while the parent transition is still active. In the case of dialogs, this can cause a Dialog that's doing a custom * animation from inside of an AnimatedVisibility to exit before the animation is completed. * * This method allows an AnimatedVisibilityScope to bind itself to some other transition, and remain active (and rendering child * content) while the other transition is running. */ @OptIn(ExperimentalAnimationApi::class) @Composable internal fun <T> AnimatedVisibilityScope.KeepVisibleWith( otherTransition: Transition<T> ) { key(otherTransition.currentState, otherTransition.targetState, otherTransition.hashCode()) { if(otherTransition.totalDurationNanos > 0) { transition.animateInt( transitionSpec = { tween((otherTransition.totalDurationNanos / 1000000).toInt()) }, label = "bindVisibilityToTransition", targetValueByState = { it.hashCode() } ).value } } }
1
Kotlin
13
246
fab4af27fd1d0c066f1ad99ded202e1c6b16c575
1,522
Enro
Apache License 2.0
src/main/kotlin/land/src/jvmtb/jvm/oop/ConstMethod.kt
JVMInspect
874,749,033
false
{"Kotlin": 74773, "Java": 6263}
package land.src.jvmtb.jvm.oop import land.src.jvmtb.dsl.int import land.src.jvmtb.dsl.nullableArray import land.src.jvmtb.dsl.short import land.src.jvmtb.jvm.Address import land.src.jvmtb.jvm.Struct class ConstMethod(address: Address) : Struct(address) { val maxStack: Short by short("_max_stack") val maxLocals: Short by short("_max_locals") val stackMapData: Array<Byte>? by nullableArray("_stackmap_data") val hasStackMapTable: Boolean get() = stackMapData != null val nameIndex: Short by short("_name_index") val signatureIndex: Short by short("_signature_index") val codeSize: Short by short("_code_size") val constMethodSize: Int by int("_constMethod_size") val flags: Int by int("_flags") val hasLineNumberTable: Boolean get() = flags and (1 shl 0) != 0 val hasCheckedExceptions: Boolean get() = flags and (1 shl 1) != 0 val hasLocalVariableTable: Boolean get() = flags and (1 shl 2) != 0 val hasExceptionTable: Boolean get() = flags and (1 shl 3) != 0 val hasGenericSignature: Boolean get() = flags and (1 shl 4) != 0 val hasMethodParameters: Boolean get() = flags and (1 shl 5) != 0 val isOverpass: Boolean get() = flags and (1 shl 6) != 0 val hasMethodAnnotations: Boolean get() = flags and (1 shl 7) != 0 val hasParameterAnnotations: Boolean get() = flags and (1 shl 8) != 0 val hasTypeAnnotations: Boolean get() = flags and (1 shl 9) != 0 val hasDefaultAnnotations: Boolean get() = flags and (1 shl 10) != 0 val methodAnnotationsAddr: Long get() { return constMethodEnd - pointerSize; } val methodAnnotations: Array<Byte>? get() { if (!hasMethodAnnotations) return null return arrays(methodAnnotationsAddr, false) } val parameterAnnotationsAddr: Long get() { var offset = 1 if (hasMethodAnnotations) offset++ return constMethodEnd - (offset * pointerSize) } val parameterAnnotations: Array<Byte>? get() { if (!hasParameterAnnotations) return null return arrays(parameterAnnotationsAddr, false) } val typeAnnotationsAddr: Long get() { var offset = 1 if (hasMethodAnnotations) offset++ if (hasParameterAnnotations) offset++ return constMethodEnd - (offset * pointerSize) } val typeAnnotations: Array<Byte>? get() { if (!hasTypeAnnotations) return null return arrays(typeAnnotationsAddr, false) } val defaultAnnotationsAddr: Long get() { var offset = 1 if (hasMethodParameters) offset++ if (hasParameterAnnotations) offset++ if (hasTypeAnnotations) offset++ return constMethodEnd - (offset * pointerSize) } val defaultAnnotations: Array<Byte>? get() { if (!hasDefaultAnnotations) return null return arrays(defaultAnnotationsAddr, false) } val lineNumberTableEntries: Int get() = TODO() val constMethodEnd get(): Long { return address.base + constMethodSize } val codeBase: Long get() = address.base + pointerSize val codeEnd: Long get() = codeBase + codeSize val compressedLineNumberTable: Array<Short> get() { return arrays(address = address.base + codeEnd, isElementPointer = false)!! } val lastU2Element: Long get() { var offset = 0 if (hasMethodAnnotations) offset++ if (hasParameterAnnotations) offset++ if (hasTypeAnnotations) offset++ if (hasDefaultAnnotations) offset++ return constMethodEnd - (offset * pointerSize) - pointerSize } val genericSignatureIndexAddress: Long get() = lastU2Element val genericSignatureIndex: Short get() = if (hasGenericSignature) unsafe.getShort(genericSignatureIndexAddress) else 0 val methodParametersLengthAddr: Long get() = if (hasGenericSignature) lastU2Element - pointerSize else lastU2Element val methodParametersLength: Short get() = if (hasMethodParameters) unsafe.getShort(methodParametersLengthAddr) else 0 val methodParametersStart: Long get() { val addr = methodParametersLengthAddr val length = unsafe.getLong(addr) return addr - length * /* sizeof(MethodParametersElement) */ 4 / /* sizeof(u2) */ 2 } val checkedExceptionsStart: Long get() { val addr = checkedExceptionsLengthAddr val length = unsafe.getLong(addr) return addr - length * /* sizeof(CheckedExceptionElement) */ 2 / /* sizeof(u2) */ 2 } val checkedExceptionsLength: Short get() = if (hasCheckedExceptions) unsafe.getShort(checkedExceptionsLengthAddr) else 0 val exceptionTableStart: Long get() { val addr = exceptionTableLengthAddr val length = unsafe.getLong(addr) return addr - length * /* sizeof(ExceptionTableElement) */ 8 / /* sizeof(u2) */ 2 } val localVariableTableLengthAddr: Long get() = if (hasExceptionTable) exceptionTableStart - pointerSize else if (hasCheckedExceptions) checkedExceptionsStart - pointerSize else if (hasMethodParameters) methodParametersStart - pointerSize else if (hasGenericSignature) lastU2Element - pointerSize else lastU2Element val localVariableTableLength: Short get() = if (hasLocalVariableTable) unsafe.getShort(localVariableTableLengthAddr) else 0 val localVariableTableStart: Long get() { val addr = localVariableTableLengthAddr val length = unsafe.getLong(addr) return addr - length * /* sizeof(LocalVariableTableElement) */ 12 / /* sizeof(u2) */ 2 } val exceptionTableLength: Short get() = if (hasExceptionTable) unsafe.getShort(exceptionTableLengthAddr) else 0 val exceptionTableLengthAddr: Long get() = if (hasCheckedExceptions) checkedExceptionsStart - pointerSize else if (hasMethodParameters) methodParametersStart - pointerSize else if (hasGenericSignature) lastU2Element - pointerSize else lastU2Element val checkedExceptionsLengthAddr: Long get() = if (hasMethodParameters) methodParametersStart - pointerSize else if (hasGenericSignature) lastU2Element - pointerSize else lastU2Element }
0
Kotlin
0
3
f52610ec94257236864c0851c51ed0b97850dbbf
6,282
toolbox
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsoneplanapi/objective/ObjectiveController.kt
ministryofjustice
746,586,556
false
{"Kotlin": 120194, "Dockerfile": 1320, "Shell": 293}
package uk.gov.justice.digital.hmpps.hmppsoneplanapi.objective import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.media.Content import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.tags.Tag import jakarta.validation.Valid import kotlinx.coroutines.flow.Flow import org.springframework.http.ResponseEntity import org.springframework.validation.annotation.Validated import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RestController import uk.gov.justice.digital.hmpps.hmppsoneplanapi.common.CaseReferenceNumber import uk.gov.justice.digital.hmpps.hmppsoneplanapi.common.CreateEntityResponse import uk.gov.justice.digital.hmpps.hmppsoneplanapi.common.Crn import uk.gov.justice.digital.hmpps.hmppsoneplanapi.config.ErrorResponse import uk.gov.justice.digital.hmpps.hmppsoneplanapi.plan.PlanKey import java.util.UUID @RestController @Validated @Tag(name = "Objective", description = "Manage Objectives") class ObjectiveController(private val service: ObjectiveService) { @Operation( summary = "Create an Objective", responses = [ ApiResponse( responseCode = "200", description = "Objective successfully created, response contains the unique reference that identifies the created Objective", content = [Content(mediaType = "application/json", schema = Schema(implementation = CreateEntityResponse::class))], ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Incorrect permissions to use this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "404", description = "Plan not found", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) @PostMapping("/person/{crn}/objectives") suspend fun createObjective( @PathVariable(value = "crn") @Crn crn: CaseReferenceNumber, @RequestBody @Valid request: CreateObjectiveRequest, ): CreateEntityResponse { val entity = service.createObjective(crn, request) return CreateEntityResponse(entity.reference) } @Operation( summary = "Get data for a single Objective", responses = [ ApiResponse( responseCode = "200", description = "Objective data is returned", ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Incorrect permissions to use this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "404", description = "Objective or plan not found", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) @GetMapping("/person/{crn}/objectives/{objectiveReference}") suspend fun getObjective( @PathVariable(value = "crn") @Crn crn: CaseReferenceNumber, @PathVariable(value = "objectiveReference") objectiveReference: UUID, ): ObjectiveEntity { return service.getObjective(ObjectiveKey(crn, objectiveReference)) } @Operation( summary = "Get all objectives for a Plan", responses = [ ApiResponse( responseCode = "200", description = "Objective data is returned, empty array if no objectives found for the Plan", ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Incorrect permissions to use this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "404", description = "Plan not found", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) @GetMapping("/person/{crn}/plans/{planReference}/objectives") suspend fun getObjectives( @PathVariable(value = "crn") @Crn crn: CaseReferenceNumber, @PathVariable(value = "planReference") planReference: UUID, ): Flow<ObjectiveEntity> { return service.getObjectives(PlanKey(crn, planReference)) } @Operation( summary = "Update data for a single Objective", responses = [ ApiResponse( responseCode = "200", description = "Objective data is returned", ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Incorrect permissions to use this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "404", description = "Objective or plan not found", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) @PutMapping("/person/{crn}/objectives/{objectiveReference}") suspend fun putObjective( @PathVariable(value = "crn") @Crn crn: CaseReferenceNumber, @PathVariable(value = "objectiveReference") objectiveReference: UUID, @RequestBody @Valid request: UpdateObjectiveRequest, ): ObjectiveEntity { return service.updateObjective(ObjectiveKey(crn, objectiveReference), request) } @Operation( summary = "Remove an Objective", responses = [ ApiResponse( responseCode = "204", description = "Objective data is removed", ), ApiResponse( responseCode = "401", description = "Unauthorized to access this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "403", description = "Incorrect permissions to use this endpoint", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ApiResponse( responseCode = "404", description = "Objective or plan not found", content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorResponse::class))], ), ], ) @DeleteMapping("/person/{crn}/objectives/{objectiveReference}") suspend fun deleteObjective( @PathVariable(value = "objectiveReference") objectiveReference: UUID, @PathVariable(value = "crn") @Crn crn: CaseReferenceNumber, ): ResponseEntity<Nothing> { service.deleteObjective(ObjectiveKey(crn, objectiveReference)) return ResponseEntity.noContent().build() } }
1
Kotlin
0
0
a86352c1759132bedaa40196f4a9f66c5bc390ed
7,961
hmpps-one-plan-api
MIT License
MyViewTest/app/src/main/java/com/wpf/myviewtest/ScrollingActivity.kt
wangpengfei1992
444,720,156
false
{"C": 15356987, "Kotlin": 1926516, "Java": 1439280, "Makefile": 697532, "Shell": 397449, "C++": 160245, "GLSL": 104693, "CMake": 58126, "M4": 43504, "Assembly": 40776, "CSS": 20448, "Perl": 10762, "Groovy": 9011, "HTML": 2612, "Batchfile": 789}
package com.wpf.myviewtest import android.content.Context import android.os.Bundle import android.text.SpannableString import android.text.Spanned import android.text.method.LinkMovementMethod import android.text.style.ClickableSpan import android.util.Log import com.google.android.material.appbar.CollapsingToolbarLayout import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import androidx.appcompat.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.TextView import android.widget.Toast import com.wpf.myviewtest.bean.Sentence class ScrollingActivity : AppCompatActivity() { private var context: Context? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_scrolling) setSupportActionBar(findViewById(R.id.toolbar)) findViewById<CollapsingToolbarLayout>(R.id.toolbar_layout).title = title findViewById<FloatingActionButton>(R.id.fab).setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } context = this var contentText = findViewById<TextView>(R.id.content_text) var txt = this.getString(R.string.large_text) var spannableString:SpannableString = SpannableString(txt); var sentenceList = StringHelper.dealWith(txt) for (bean in sentenceList) { spannableString.setSpan(object : ClickableSpan() { override fun onClick(widget: View) { Log.e("wpf", "点击事件,${bean.content}") Toast.makeText(context,"${bean.content}",Toast.LENGTH_SHORT).show() } }, bean.startPoint, bean.endPoint, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } /* spannableString.setSpan(object: ClickableSpan() { override fun onClick(widget: View) { Log.e("wpf","点击事件1") StringHelper.dealWith(txt) } },0,31, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);*/ /* spannableString.setSpan(object: ClickableSpan() { override fun onClick(widget: View) { Log.e("wpf","点击事件2") } },31,70, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);*/ contentText.setMovementMethod(LinkMovementMethod.getInstance()); contentText.setText(spannableString); } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_scrolling, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } }
0
C
0
0
2e078f0c510515be47e6713357fa87089af8fdae
3,213
TestDemoList
Apache License 2.0
sample/shared/src/commonMain/kotlin/by/overpass/treemapchart/sample/shared/complex/Formatting.kt
overpas
425,566,488
false
{"Kotlin": 23097}
package by.overpass.treemapchart.sample.shared.complex internal expect fun Double.formatPercentage(): String internal fun Double.formatTradeValue(): String { val billions = this / 1000000000 val millions = this / 1000000 return if (billions >= 1) { "${billions.formatDollarAmount()}B" } else if (millions >= 1) { "${millions.formatDollarAmount()}M" } else { formatDollarAmount() } } internal expect fun Double.formatDollarAmount(): String
4
Kotlin
4
60
6f44260813f521bedd19f369e9ec1fc7689724ec
491
compose-treemap-chart
MIT License
correlation/core/test/utils/src/main/kotlin/org/sollecitom/chassis/correlation/core/test/utils/customer/CustomerTestFactory.kt
sollecitom
669,483,842
false
{"Kotlin": 868904, "Java": 30834}
package org.sollecitom.chassis.correlation.core.test.utils.customer import org.sollecitom.chassis.core.domain.identity.Id import org.sollecitom.chassis.core.utils.UniqueIdGenerator import org.sollecitom.chassis.correlation.core.domain.access.customer.Customer import org.sollecitom.chassis.correlation.core.domain.tenancy.Tenant context(UniqueIdGenerator) fun Customer.Companion.create(id: Id = newId.internal()): Customer = Customer(id)
0
Kotlin
0
2
d11bf12bc66105bbf7edd35d01fbbadc200c3ee8
439
chassis
MIT License
correlation/core/test/utils/src/main/kotlin/org/sollecitom/chassis/correlation/core/test/utils/customer/CustomerTestFactory.kt
sollecitom
669,483,842
false
{"Kotlin": 868904, "Java": 30834}
package org.sollecitom.chassis.correlation.core.test.utils.customer import org.sollecitom.chassis.core.domain.identity.Id import org.sollecitom.chassis.core.utils.UniqueIdGenerator import org.sollecitom.chassis.correlation.core.domain.access.customer.Customer import org.sollecitom.chassis.correlation.core.domain.tenancy.Tenant context(UniqueIdGenerator) fun Customer.Companion.create(id: Id = newId.internal()): Customer = Customer(id)
0
Kotlin
0
2
d11bf12bc66105bbf7edd35d01fbbadc200c3ee8
439
chassis
MIT License
kotlin-node/src/jsMain/generated/node/fs/copyFile.suspend.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package node.fs import js.core.Void suspend fun copyFile(src: PathLike, dest: PathLike, mode: Number = undefined.unsafeCast<Nothing>()): Void = copyFileAsync( src, dest, mode ).await()
39
Kotlin
165
1,347
997ed3902482883db4a9657585426f6ca167d556
258
kotlin-wrappers
Apache License 2.0
src/main/java/de/Jan/SlashCommands/Interaction.kt
Kyro-Music
349,452,961
false
{"Kotlin": 35313, "Java": 1174}
package de.Jan.SlashCommands import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import org.json.JSONArray import org.json.JSONObject class Interaction(private val builder: SlashCommandBuilder, val interactionToken: String, private val token: String, private val id: String, private val interactionID: String) { private val callback_url = "https://discord.com/api/v8/interactions/$interactionID/$interactionToken/callback" private val client = OkHttpClient() private val JSON = "application/json; charset=utf-8".toMediaType() private var callback = false fun callback(type: Int, value: String) : InteractionMessage? { if(callback) { return null } callback = true val i = JSONObject() i.put("type", type) if(value != null) { val data = JSONObject() .put("tts", false) .put("content", value) .put("embeds", JSONArray()) .put("allowed_mentions", JSONArray()) i.put("data", data) } val r = Request.Builder() .url(callback_url) .addHeader("Authorization", "Bot $token") .post(i.toString().toRequestBody(JSON)) val call = client.newCall(r.build()).execute() val result = call.body!!.string() builder.checkIfError(result) val message = JSONObject(result) if(value != null) { return InteractionMessage(value, message.getString("id"), builder, this, true) } else { return null } } fun callback(type: Int) : Interaction { callback = true val i = JSONObject() i.put("type", type) val r = Request.Builder() .url(callback_url) .addHeader("Authorization", "Bot $token") .post(i.toString().toRequestBody(JSON)) val call = client.newCall(r.build()).execute() val result = call.body!!.string() builder.checkIfError(result) return this } fun callback(type: Int, value: InteractionEmbed) : InteractionMessage? { if(callback) { return null } callback = true val i = JSONObject() i.put("type", type) if(value != null) { val data = JSONObject() .put("tts", false) .put("embeds", JSONArray().put(value.toJSONObject())) .put("allowed_mentions", JSONArray()) i.put("data", data) } val r = Request.Builder() .url(callback_url) .addHeader("Authorization", "Bot $token") .post(i.toString().toRequestBody(JSON)) val call = client.newCall(r.build()).execute() val result = call.body!!.string() builder.checkIfError(result) if(value != null) { return InteractionMessage("", "", builder, this, true) } else { return null } } fun sendMessage(value: String) : InteractionMessage { val createURL = "https://discord.com/api/v8/webhooks/${builder.botID}/$interactionToken" val data = JSONObject() .put("tts", false) .put("content", value) .put("embeds", JSONArray()) .put("allowed_mentions", JSONArray()) val r = Request.Builder() .url(createURL) .addHeader("Authorization", "Bot $token") .post(data.toString().toRequestBody(JSON)) val call = client.newCall(r.build()).execute() val result = call.body!!.string() builder.checkIfError(result) val message = JSONObject(result) return InteractionMessage(message.getString("content"), message.getString("id"), builder, this, false) } fun sendMessage(value: InteractionEmbed) : InteractionMessage { val createURL = "https://discord.com/api/v8/webhooks/${builder.botID}/$interactionToken" val data = JSONObject() .put("tts", false) .put("embeds", JSONArray().put(value.toJSONObject())) .put("allowed_mentions", JSONArray()) val r = Request.Builder() .url(createURL) .addHeader("Authorization", "Bot $token") .post(data.toString().toRequestBody(JSON)) val call = client.newCall(r.build()).execute() val result = call.body!!.string() builder.checkIfError(result) val message = JSONObject(result) return InteractionMessage(message.getString("content"), message.getString("id"), builder, this, false) } }
0
Kotlin
0
0
da0362593604896aa750413dacb4a815cecb2052
4,827
Discord-SlashCommands-Java
Apache License 2.0
app/src/main/java/com/confinapptilus/confinpinboard/domain/models/AnnouncementModel.kt
NemaSoft
253,593,957
false
{"Kotlin": 25491}
package com.confinapptilus.confinpinboard.domain.models data class AnnouncementModel( val id: String, val announcer: String, val title: String, val description: String, val place: String, val categories: List<Category>, val startDate: String, val startTime: String, val endDate: String, val endTime: String ) { sealed class Category(val type: Int) { object Sport : Category(1) object Cook : Category(2) object Music : Category(3) object Dance : Category(4) object Theater : Category(5) object Literature : Category(6) object Cinema : Category(7) object Conference : Category(8) object Interview : Category(9) object Workshop : Category(10) object Formation : Category(11) object Donation : Category(12) object Crafts : Category(13) object StoryTelling : Category(14) object Others : Category(15) } }
0
Kotlin
0
3
c8f17bdb8f20d01b865ac56a274d1107219c79c6
970
ConfinPinBoard
Apache License 2.0
src/main/kotlin/controllers/base/responses/BaseOkResponse.kt
booleanull
176,114,644
false
null
package controllers.base.responses /** @author boolenull on 17.03.2019 */ open class BaseOkResponse(httpStatus: Int = 200): BaseResponse("ok", httpStatus = httpStatus)
0
Kotlin
0
0
81b96a415efba567d404571b7f8fa7095f891eba
170
FoxramAlpha-Backend
MIT License
app/src/main/java/com/example/enebronotes/data/cell/CellDao.kt
adrianja5
655,452,991
false
null
package com.example.enebronotes.data.cell import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import kotlinx.coroutines.flow.Flow @Dao interface CellDao { @Query("SELECT * FROM cells WHERE note_id = :noteId ORDER BY id ASC") fun getAllCellsByNote(noteId: Long): Flow<List<Cell>> @Query("SELECT * from cells WHERE id = :id") fun getCell(id: Long): Flow<Cell> // Specify the conflict strategy as IGNORE, when the user tries to add an // existing Item into the database Room ignores the conflict. @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insert(item: Cell): Long @Update suspend fun update(item: Cell) @Delete suspend fun delete(item: Cell) }
0
Kotlin
0
0
27aa9002d1850357c9d8fc5f26e34b0cff7ad3c3
836
EnebroNotes-PAS
MIT License
app/src/androidTest/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksFragmentTest.kt
VitorMakiyama
759,217,442
false
{"Kotlin": 123176}
package com.example.android.architecture.blueprints.todoapp.tasks import FakeAndroidTestRepository import android.content.Context import android.os.Bundle import androidx.fragment.app.testing.launchFragmentInContainer import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.recyclerview.widget.RecyclerView import androidx.test.core.app.ApplicationProvider.getApplicationContext import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.contrib.RecyclerViewActions import androidx.test.espresso.matcher.ViewMatchers.hasDescendant import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.example.android.architecture.blueprints.todoapp.R import com.example.android.architecture.blueprints.todoapp.ServiceLocator import com.example.android.architecture.blueprints.todoapp.data.Task import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.mock import org.mockito.Mockito.verify @RunWith(AndroidJUnit4::class) @MediumTest @ExperimentalCoroutinesApi class TasksFragmentTest { private lateinit var repository: TasksRepository @Before fun initRepository() { repository = FakeAndroidTestRepository() ServiceLocator.tasksRepository = repository } @After fun cleanupDb() = runTest { /** Differences between runBlocking and runTest: * runTest: * 1 - It skips delay, so your tests run faster. * 2 -It adds testing related assertions to the end of the coroutine.These assertions fail if you * launch a coroutine and it continues running after the end of the runBlocking lambda (which is a * possible coroutine leak) or if you have an uncaught exception. * 3 - It gives you timing control over the coroutine execution. * runBlocking: should be used to block the current thread, for example: to create test doubles * that will be used in test cases * */ ServiceLocator.resetRepository() } @Test fun cliclTask_navigateToDetailFragmentOne() = runTest { repository.saveTask(Task("TITLE1", "DESCRIPTION1", false, "id1")) repository.saveTask(Task("TITLE2", "DESCRIPTION2", true, "id2")) val navController = mock(NavController::class.java) // mocks the navController //GIVEN - On the home screen val scenario = launchFragmentInContainer<TasksFragment>(Bundle(), R.style.AppTheme) scenario.onFragment { // sets the navController to the mocked one Navigation.setViewNavController(it.view!!, navController) } //WHEN - Click on the first list item onView(withId(R.id.tasks_list)) .perform(RecyclerViewActions.actionOnItem<RecyclerView.ViewHolder>( // RecyclerViewActions is part of the espresso-contrib library and lets you perform Espresso actions on a RecyclerView. hasDescendant(withText("TITLE1")), click())) //THEN - Verify that we navigate tro the first detail screen verify(navController).navigate( TasksFragmentDirections.actionTasksFragmentToTaskDetailFragment("id1") ) } @Test fun clickAddTaskButton_navigateToEditFragment() { val navController = mock(NavController::class.java) // mocks the navController //GIVEN - On the home screen val scenario = launchFragmentInContainer<TasksFragment>(Bundle(), R.style.AppTheme) scenario.onFragment { // sets the navController to the mocked one Navigation.setViewNavController(it.view!!, navController) } //WHEN - Click on the first list item onView(withId(R.id.add_task_fab)).perform(click()) //THEN - Verify that we navigate tro the first detail screen verify(navController).navigate( TasksFragmentDirections.actionTasksFragmentToAddEditTaskFragment(null, getApplicationContext<Context>().getString(R.string.add_task)) ) } }
0
Kotlin
0
0
a5984cc1f3bc36b921e951a86240ca9405407f35
4,414
Android-Advanced-Testing-Codelab
Apache License 2.0
project/src/main/java/com/sinx/project/domain/AddNewProgectUseCaseImpl.kt
AlexeyGvozdev
590,118,664
false
null
package com.sinx.project.domain import com.sinx.project.data.ProjectListModel internal class AddNewProjectUseCaseImpl(private val projectRepository: ProjectRepository) : AddNewProjectUseCase { override fun invoke(newProject: ProjectListModel) = projectRepository.addNewProject(newProject) } internal interface AddNewProjectUseCase { operator fun invoke(newProject: ProjectListModel) }
5
Kotlin
2
0
4c5dbc01e18221e9755f3e1954dcc33a97af6e89
399
TodoApp
Apache License 2.0
j2k/tests/testData/ast/boxedType/statement/character.kt
chirino
3,596,099
true
null
var i : Char? = 10
0
Java
28
71
ac434d48525a0e5b57c66b9f61b388ccf3d898b5
18
kotlin
Apache License 2.0
server/microservices/stock_arrangement/src/main/kotlin/server/circlehelp/repositories/InventoryRepository.kt
NamSellsFish
844,310,986
false
{"Kotlin": 38389, "TypeScript": 27847, "JavaScript": 1037, "Dockerfile": 115, "CSS": 59, "Batchfile": 24}
package server.circlehelp.repositories import jakarta.persistence.ManyToOne import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository import server.circlehelp.api.response.InventoryStockItem import server.circlehelp.entities.ArrivedPackage import server.circlehelp.entities.InventoryStock import server.circlehelp.entities.Product @Repository interface InventoryRepository : JpaRepository<InventoryStock, Long> { fun findByProductAndOrderedPackage(product: Product, orderedPackage: ArrivedPackage): InventoryStock? }
2
Kotlin
1
0
0eeb41af2c512e5e43c3dac57d2b106cc59a7381
602
circle-help
Freetype Project License
src/main/kotlin/com/pineypiney/game_engine/objects/transforms/Quaternion.kt
PineyPiney
491,900,499
false
{"Kotlin": 564450, "GLSL": 31735}
package com.pineypiney.game_engine.objects.transforms import glm_.vec3.Vec3 import glm_.vec4.Vec4 import kotlin.math.* class Quaternion(val r: Float, val i: Float, val j: Float, val k: Float) { constructor(vec: Vec4): this(vec.x, vec.y, vec.z, vec.w) constructor(eulerAngles: Vec3): this(eulerToValues(eulerAngles)) // https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles#Quaternion_to_Euler_angles_(in_3-2-1_sequence)_conversion fun toEulerAngles(): Vec3 { val x = atan2(2 * ((r * i) + (j * k)), 1 - (2 * ((i * i) + (j * j)))) val a = 2 * ((r * j) - (i * k)) val y = -PI /2 + (2 * atan2(sqrt(1 + a), sqrt(1 - a))) val z = atan2(2 * ((r * k) + (i * j)), 1 - (2 * ((j * j) + (k * k)))) return Vec3(x, y, z) } infix operator fun plus(q: Quaternion): Quaternion{ return Quaternion(r + q.r, i + q.i, j + q.j, k + q.k) } // https://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/arithmetic/index.htm infix operator fun times(q: Quaternion): Quaternion{ val nr = r*q.r - i*q.i - j*q.j - k*q.k val ni = i*q.r + r*q.i + j*q.k- k*q.j val nj = r*q.j - i*q.k+ j*q.r + k*q.i val nk = r*q.k + i*q.j - j*q.i + k*q.r return Quaternion(nr, ni, nj, nk) } infix operator fun times(f: Float): Quaternion{ return Quaternion(r * f, i*f, j*f, k*f) } fun size(): Float{ return sqrt(size2()) } fun size2(): Float{ return (r*r)+(i*i)+(j*j)+(k*k) } fun conjugate(): Quaternion{ return Quaternion(r, -i, -j, -k) } fun normalize(): Quaternion{ return this * (1 / size()) } fun slerp(other: Quaternion, delta: Float): Quaternion{ return this * (conjugate() * other).pow(delta) } // https://math.stackexchange.com/a/939288 infix fun pow(power: Float): Quaternion{ return (ln() * power).exp().normalize() } fun exp(): Quaternion{ val v = Vec3(i, j, k) val vs = v.length() val er = exp(r) val s = if (vs >= 0.00001f) er * sin(vs) / vs else 0f return Quaternion(er * cos(vs), i*s, j*s, k*s) } fun ln(): Quaternion{ val v = Vec3(i, j, k) val ijk = v.length2() val vs = sqrt(ijk) val t = if (vs > 0.00001f) atan2(vs, this.r) / vs else 0f return Quaternion(0.5f * ln((this.r * this.r) + ijk), i*t, j*t, k*t) } companion object{ // https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles#Euler_angles_(in_3-2-1_sequence)_to_quaternion_conversion fun eulerToValues(euler: Vec3): Vec4{ val cr: Double = cos(euler.x * 0.5) val sr: Double = sin(euler.x * 0.5) val cp: Double = cos(euler.y * 0.5) val sp: Double = sin(euler.y * 0.5) val cy: Double = cos(euler.z * 0.5) val sy: Double = sin(euler.z * 0.5) return Vec4(cr * cp * cy + sr * sp * sy ,sr * cp * cy - cr * sp * sy ,cr * sp * cy + sr * cp * sy ,cr * cp * sy - sr * sp * cy).normalize() } } }
0
Kotlin
0
0
f927b3d9fa5f402fc85db008e46d876f397e5cf7
3,150
GameEngine
MIT License
app/src/main/java/com/piticlistudio/playednext/data/entity/mapper/datasources/game/RoomGameMapper.kt
Yorxxx
105,007,126
false
null
package com.piticlistudio.playednext.data.entity.mapper.datasources.game import com.piticlistudio.playednext.data.entity.mapper.DataLayerMapper import com.piticlistudio.playednext.data.entity.mapper.DomainLayerMapper import com.piticlistudio.playednext.data.entity.mapper.datasources.timetobeat.RoomTimeToBeatMapper import com.piticlistudio.playednext.data.entity.room.RoomGame import com.piticlistudio.playednext.data.entity.room.RoomGameProxy import com.piticlistudio.playednext.data.entity.room.RoomImage import com.piticlistudio.playednext.domain.model.Game import com.piticlistudio.playednext.domain.model.Image import javax.inject.Inject /** * Mapper for converting [RoomGameProxy] and [Game] * This mapperIGDB implements both [DataLayerMapper] and [DomainLayerMapper], which allows to map entities * from datalayer into domain layer, and viceversa */ class RoomGameMapper @Inject constructor(private val timeToBeatMapper: RoomTimeToBeatMapper) : DataLayerMapper<RoomGameProxy, Game>, DomainLayerMapper<Game, RoomGameProxy> { override fun mapFromDataLayer(model: RoomGameProxy): Game { with(model) { return Game(id = game.id, name = game.name, createdAt = game.createdAt, updatedAt = game.updatedAt, summary = game.summary, storyline = game.storyline, url = game.url, rating = game.rating, ratingCount = game.ratingCount, aggregatedRating = game.agregatedRating, aggregatedRatingCount = game.aggregatedRatingCount, totalRating = game.totalRating, totalRatingCount = game.totalRatingCount, releasedAt = game.firstReleaseAt, cover = game.cover?.let { Image(it.url, it.width, it.height) }, timeToBeat = game.timeToBeat?.let { timeToBeatMapper.mapFromDataLayer(it) }, developers = developers, publishers = publishers, genres = genres, platforms = platforms, syncedAt = game.syncedAt, collection = collection, images = images) } } override fun mapIntoDataLayerModel(model: Game): RoomGameProxy { with(model) { val game = RoomGame(id = id, collection = collection?.id, syncedAt = syncedAt, timeToBeat = timeToBeat?.let { timeToBeatMapper.mapIntoDataLayerModel(it) }, cover = cover?.let { RoomImage(it.url, it.width, it.height) }, totalRatingCount = totalRatingCount, totalRating = totalRating, aggregatedRatingCount = aggregatedRatingCount, ratingCount = ratingCount, rating = rating, url = url, storyline = storyline, summary = summary, updatedAt = updatedAt, createdAt = createdAt, name = name, popularity = null, hypes = null, franchise = null, agregatedRating = aggregatedRating, firstReleaseAt = releasedAt) return RoomGameProxy(game = game) } } }
2
Kotlin
0
1
24f9fe251437fbbb0a493760e63b31f5c7895738
3,484
played-next-kotlin
MIT License
consumer/src/main/kotlin/com/glinboy/tapsell/consumer/entity/ImpressionEventModel.kt
GLinBoy
398,836,478
false
null
package com.glinboy.tapsell.consumer.entity import org.bson.types.ObjectId import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document @Document data class ImpressionEventModel( @Id val requestId: String, val timestamp: Long, val adId: String, val adTitle: String, val advertiserCost: Double, val appId: String, val appTitle: String )
0
Kotlin
0
0
44e7152ffdab01104439e7d0002b4d889777a3f0
417
tapsell-assignment
MIT License
src/main/kotlin/com/intellij/ml/llm/template/testdata/TestMethods.kt
JetBrains-Research
616,565,282
false
null
/* * File serves the purpose of testing the plugin. */ package com.intellij.ml.llm.template.testdata fun floydWarshall(graph: Array<IntArray>): Array<IntArray> { val n = graph.size val dist = Array(n) { i -> graph[i].clone() } for (k in 0 until n) { for (i in 0 until n) { for (j in 0 until n) { if (dist[i][k] != Int.MAX_VALUE && dist[k][j] != Int.MAX_VALUE && dist[i][k] + dist[k][j] < dist[i][j] ) { dist[i][j] = dist[i][k] + dist[k][j] } } } } return dist } class CentroidDecomposition(val graph: List<List<Int>>) { private val size = graph.size private val subSize = IntArray(size) private val isCentroid = BooleanArray(size) private var root = 0 init { decompose(0, -1) } private fun decompose(node: Int, parent: Int) { subSize[node] = 1 var centroid = -1 for (child in graph[node]) { if (child != parent) { decompose(child, node) subSize[node] += subSize[child] if (centroid == -1 || subSize[child] > subSize[centroid]) { centroid = child } } } if (size - subSize[node] > 0 && size - subSize[node] < subSize[centroid]) { centroid = parent } if (centroid != -1) { isCentroid[centroid] = true if (parent == -1) { root = centroid } } } fun getCentroids(): List<Int> { val centroids = mutableListOf<Int>() for (node in 0 until size) { if (isCentroid[node]) { centroids.add(node) } } return centroids } }
0
Kotlin
0
0
6ea7ebaaf9b3a6bd2585a1f10c44273d8890263c
1,820
llm-guide-refactorings
MIT License
app/src/main/java/se/isotop/lupin/page/PageFragment.kt
BenjaminChrist84
215,296,465
false
null
package se.isotop.lupin.page import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.core.content.ContextCompat import androidx.core.view.isGone import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.navigation.fragment.navArgs import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.fragment_page.* import se.isotop.lupin.R import se.isotop.lupin.events.EventsViewModel class PageFragment : Fragment(R.layout.fragment_page) { private val args: PageFragmentArgs by navArgs() private lateinit var eventsViewModel: EventsViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) eventsViewModel = ViewModelProviders.of(this).get(EventsViewModel::class.java) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val id = args.id eventsViewModel.getEvent(id).observe(viewLifecycleOwner, Observer { event -> toolbarTitle.text = event.title val cardColor = ContextCompat.getColor(requireContext(), R.color.pink) calendarCard.setBackgroundColor(cardColor) val cardTextColor = ContextCompat.getColor(requireContext(), R.color.white) val startTimeText = calendarCard.findViewById<TextView>(R.id.startTimeView) startTimeText.text = event.startTimeAsString startTimeText.setTextColor(cardTextColor) val titleText = calendarCard.findViewById<TextView>(R.id.eventTitle) titleText.text = event.title titleText.setTextColor(cardTextColor) val timeText = calendarCard.findViewById<TextView>(R.id.eventTime) timeText.text = "${event.startTimeAsString} - ${event.endTimeAsString}" timeText.setTextColor(cardTextColor) val locationText = calendarCard.findViewById<TextView>(R.id.eventLocation) locationText.text = event.distanceFromIsotop locationText.setTextColor(cardTextColor) val arrow = calendarCard.findViewById<ImageView>(R.id.arrowView) arrow.isGone = true preamble.text = event.ingress Glide.with(this).load(event.image).into(image) body.text = event.body }) } }
3
Kotlin
1
0
23628ab3b3c2cabb742f5fc1b9fc0e75f47b8661
2,462
lupin
MIT License
reflekt-plugin/src/test/kotlin/org/jetbrains/reflekt/plugin/analysis/util/SmartReflektExpressionProcessor.kt
JetBrains-Research
293,503,377
false
null
package org.jetbrains.reflekt.plugin.analysis.util import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.reflekt.SmartReflekt import org.jetbrains.reflekt.plugin.analysis.common.ReflektEntity import org.jetbrains.reflekt.plugin.analysis.processor.FileId import org.jetbrains.reflekt.plugin.analysis.processor.fullName import org.jetbrains.reflekt.plugin.analysis.processor.source.Processor import org.jetbrains.reflekt.plugin.analysis.psi.getFqName import org.jetbrains.reflekt.plugin.utils.enumToRegexOptions class SmartReflektExpressionProcessor(override val binding: BindingContext) : Processor<MutableList<KtNameReferenceExpression>>(binding) { val fileToExpressions: HashMap<FileId, MutableList<KtNameReferenceExpression>> = HashMap() override fun process(element: KtElement, file: KtFile): HashMap<FileId, MutableList<KtNameReferenceExpression>> { (element as? KtNameReferenceExpression)?.let { fileToExpressions.getOrPut(file.fullName) { ArrayList() }.add(it) } return fileToExpressions } private fun isValidExpression(expression: KtNameReferenceExpression): Boolean { val names = enumToRegexOptions(ReflektEntity.values(), ReflektEntity::entityType) val fqName = expression.getFqName(binding) ?: return false Regex("${SmartReflekt::class.qualifiedName}\\.$names").matchEntire(fqName) ?: return false return true } override fun shouldRunOn(element: KtElement): Boolean = (element as? KtNameReferenceExpression)?.let { isValidExpression(it) } ?: false }
7
Kotlin
5
246
c389fa8b1f3aedd5ea990793300b4e15e9670db9
1,609
reflekt
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/model/Puppy.kt
giolaq
342,282,267
false
{"Kotlin": 27470}
/* * 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 * * 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.androiddevchallenge.model import androidx.annotation.DrawableRes import com.example.androiddevchallenge.R data class Puppy( val id: String, val name: String, val breed: String, val age: String, val sex: String, val description: String? = null, @DrawableRes val imageId: Int, @DrawableRes val imageThumbId: Int ) val puppiesList = listOf( Puppy( id = "", name = "Rex", breed = "<NAME>", age = "6mo", sex = "Male", description = "Good one", imageId = R.drawable.p1, imageThumbId = R.drawable.p1 ), Puppy( id = "", name = "Flash", breed = "Labrador", age = "6mo", sex = "Male", description = "Cute one", imageId = R.drawable.p2, imageThumbId = R.drawable.p2 ), Puppy( id = "", name = "Boba", breed = "Chiwi", age = "6mo", sex = "Female", description = "Cute one", imageId = R.drawable.p3, imageThumbId = R.drawable.p3 ), Puppy( id = "", name = "Ray", breed = "Labrador", age = "6mo", sex = "Male", description = "Cute one", imageId = R.drawable.p4, imageThumbId = R.drawable.p4 ), Puppy( id = "", name = "Henry", breed = "Labrador", age = "6mo", sex = "Male", description = "Cute one", imageId = R.drawable.p5, imageThumbId = R.drawable.p5 ), Puppy( id = "", name = "Frankie", breed = "Labrador", age = "6mo", sex = "Male", description = "Cute one", imageId = R.drawable.p6, imageThumbId = R.drawable.p6 ), Puppy( id = "", name = "Ornella", breed = "Stuffy", age = "6mo", sex = "Female", description = "Cute one", imageId = R.drawable.p7, imageThumbId = R.drawable.p7 ), Puppy( id = "", name = "Flash", breed = "Jadgterrier", age = "6mo", sex = "Male", description = "Cute one", imageId = R.drawable.p8, imageThumbId = R.drawable.p8 ), Puppy( id = "", name = "Superman", breed = "Doberman", age = "6mo", sex = "Male", description = "Cute one", imageId = R.drawable.p9, imageThumbId = R.drawable.p9 ), Puppy( id = "", name = "Superman", breed = "Doberman", age = "6mo", sex = "Male", description = "Cute one", imageId = R.drawable.p10, imageThumbId = R.drawable.p10 ) )
0
Kotlin
0
0
79987912353fa679fcee05b1aa6eb7d8ee8ef68c
3,366
puppy-pack
Apache License 2.0
simple-icons/src/commonMain/kotlin/compose/icons/simpleicons/Scrimba.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.simpleicons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.SimpleIcons public val SimpleIcons.Scrimba: ImageVector get() { if (_scrimba != null) { return _scrimba!! } _scrimba = Builder(name = "Scrimba", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(24.0f, 6.222f) arcToRelative(2.222f, 2.222f, 0.0f, false, true, -2.222f, 2.222f) horizontalLineToRelative(-8.89f) arcToRelative(2.222f, 2.222f, 0.0f, false, true, 0.0f, -4.444f) horizontalLineToRelative(8.89f) curveTo(23.005f, 4.0f, 24.0f, 4.995f, 24.0f, 6.222f) close() moveTo(16.667f, 15.556f) horizontalLineToRelative(-8.89f) arcToRelative(2.222f, 2.222f, 0.0f, false, false, 0.0f, 4.444f) horizontalLineToRelative(8.89f) arcToRelative(2.222f, 2.222f, 0.0f, false, false, 0.0f, -4.444f) close() moveTo(16.667f, 9.778f) lineTo(13.11f, 9.778f) arcToRelative(2.222f, 2.222f, 0.0f, false, false, 0.0f, 4.444f) horizontalLineToRelative(3.556f) arcToRelative(2.222f, 2.222f, 0.0f, false, false, 0.0f, -4.444f) close() moveTo(2.222f, 15.556f) arcToRelative(2.222f, 2.222f, 0.0f, true, false, 0.0f, 4.444f) arcToRelative(2.222f, 2.222f, 0.0f, false, false, 0.0f, -4.444f) close() } } .build() return _scrimba!! } private var _scrimba: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
2,439
compose-icons
MIT License
app/src/main/java/com/greybox/projectmesh/extension/ListExtension.kt
grey-box
798,619,491
false
{"Kotlin": 106988}
package com.greybox.projectmesh.extension /* This is an extension function on Kotlin's List class, allowing to apply an update to the first element in a list that matches a given condition, then returning a updated list */ inline fun <T> List<T>.updateItem( condition: (T) -> Boolean, function: (T) -> T, ): List<T> { // Find the index of the first element that matches the condition val index = indexOfFirst(condition) // If no such element is found, return the original list return if(index == -1){ this } // Otherwise, create a new list with the element at the found index updated using the provided function else{ toMutableList().also { newList -> newList[index] = function(this[index]) }.toList() } }
2
Kotlin
3
0
c8afb05d70bac770eda44fcaee45d194a89b9414
789
Project-Mesh
MIT License
src/main/kotlin/com/zhangke/activitypub/entities/ActivityPubNotificationsEntity.kt
0xZhangKe
594,285,909
false
{"Kotlin": 84813}
package com.zhangke.activitypub.entities import com.google.gson.annotations.SerializedName data class ActivityPubNotificationsEntity( val id: String, val type: String, @SerializedName("created_at") val createdAt: String, val account: ActivityPubAccountEntity, @SerializedName("status") val status: ActivityPubStatusEntity?, @SerializedName("relationship_severance_event") val relationshipSeveranceEvent: ActivityPubRelationshipSeveranceEventEntity?, ) { companion object Type { const val mention = "mention" const val status = "status" const val reblog = "reblog" const val follow = "follow" const val followRequest = "follow_request" const val favourite = "favourite" const val poll = "poll" const val update = "update" const val severedRelationships = "severed_relationships" } }
0
Kotlin
0
3
09e0af522b9d2947ef5a53293863eb93b7e14478
902
ActivityPub-Kotlin
Apache License 2.0
app/src/main/java/com/example/android/pixelperfectnative/framework/network/RemotePhotosSource.kt
cleverSheep
227,503,938
true
{"Kotlin": 39657}
package com.example.android.pixelperfectnative.framework.network import com.example.android.core.data.PhotoDataSource import com.example.android.core.domain.Photo import javax.inject.Inject class RemotePhotosSource @Inject constructor(private val apiService: UnsplashService) : PhotoDataSource { override suspend fun fetchPhotos(imageName: String): List<Photo> { return apiService.getImagesBySearch(query = imageName).results.map { Photo( photoUrl = it.urls.regular, profileUrl = it.user.profileImage.small, authorName = it.user.name ) } } }
0
null
0
0
704bdb2d13dca58622e11d5612a32b6e7e6ede03
644
PixelPerfectNative
MIT License
aws-ses-request-builder/src/main/kotlin/com/johnturkson/aws/ses/requestbuilder/builder/BodyBuilder.kt
JohnTurkson
293,227,996
false
null
package com.johnturkson.aws.ses.requestbuilder.builder import com.johnturkson.aws.ses.requestbuilder.components.Body import com.johnturkson.aws.ses.requestbuilder.components.Body.HtmlBody import com.johnturkson.aws.ses.requestbuilder.components.Body.TextBody import com.johnturkson.aws.ses.requestbuilder.components.Content class BodyBuilder(var text: Content? = null, var html: Content? = null) { fun getData(): Body { val text = this.text val html = this.html val data = listOfNotNull(text, html) return when { data.count() > 1 -> throw Exception("Repeated Text or Html data") text != null -> TextBody(text) html != null -> HtmlBody(html) else -> throw Exception("Missing Text or Html data") } } fun Text(build: TextContentBuilder.() -> TextContentBuilder): BodyBuilder { this.text = TextContentBuilder().build().getData() return this } fun Html(build: HtmlContentBuilder.() -> HtmlContentBuilder): BodyBuilder { this.html = HtmlContentBuilder().build().getData() return this } }
0
Kotlin
0
0
f89c32631f230660fcdea6a0974d5f297a5cb76e
1,147
aws-tools
Apache License 2.0
auth-foundation/src/test/java/com/okta/authfoundation/jwt/TestKeyFactory.kt
okta
445,628,677
false
{"Kotlin": 846264, "Shell": 884}
/* * Copyright 2022-Present Okta, 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.okta.authfoundation.jwt import okio.ByteString.Companion.decodeBase64 import java.security.KeyFactory import java.security.PrivateKey import java.security.PublicKey import java.security.spec.PKCS8EncodedKeySpec import java.security.spec.X509EncodedKeySpec object TestKeyFactory { private val privateKeyString = """ -----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDbFwJnJx6l4Lq1 tsiV0np3aow39puw2S/ziH00D9TM6WtsGKXdmWFn/XjvV85JDe0mNP7o5w4gfVan cm866vOm6gaspHIcl+Q8PqM2gZv7kKbacIzmTgEmMrilL9fp+Q2Fhk7rZXWNHytU 1C24T44AaMNfpCp+EEVmyKZJx8EXWgDjCZ1Mgd1+bLDB5PS5CgaabQrKadzwDhGf caunqtuYyb1yuUXfEL4CCVviQdvktGeDI++8/Udwjm82mHsOjT23/oub5Zzn1ksq GB4ktcSEJk55TEyjTjxH+8uQ22rlJQr2CVDe+U5keXiV2G8JKEq4G3IWKaSqeQvo BGNgOwz5AgMBAAECggEAZHXZiTk76W3xz08ADQsVUtqNbz/qRh5gyXfFiXDU8Bz8 P/XRYJprOsbUhFMr6P20x3c3h84jASzX5jIn5MlFbj0TUGibVpcjdah3KJAn2SOM Ds/bG+OazUwmtMAKbmPgGmDqoS/Fxi8LrHsad9Aq2e8v3xQk0+dcG3RYI66v0KeA Rdq1GQ4DsFyICwWqhbjz0gBx45QGn5U9PPmXrpQpXR//HdUQWmYqth/549Udpt+A 2S5QSpeK+7kZKzGK1RyOO+Guw4gku1V8NrqKEhCexgGneEXyYc35v1Sie0Zhtn6H 4yg5zmBMi/KZZFSqEHv46dXgckPJDo0Gb8lUV/JgXQKBgQDz5iQE8zfEkUH3f+Oi vuiNzNlBucZEfAvgke+NDu9PNV6wJdUlU21CteDcRBeJIcGrVs8CxgZRIx6JDon3 sBacykf5JvjZDEbvNs3h6/nuAtMx7PtRFRsyP3swC5KqRDP8Uq6PfE4aE5FsPHah 97u+FnpI826OyNf/gnwMNXb/pwKBgQDl9cIbIdkJkFFr3iza/bAFj3bOIi4aD/KC itJwK/K+FbtQg/sijU3KIOKVjAdVDZ1WADG2lMcftdoav9brPgdgxPWuyeJYIfmX 1gei9luEQkO0k36CpBkpqT3HWdSoXAoBce+JlyCARssW+zSl1Dc8J8lD2X4FBQqQ IjxTX7IiXwKBgQC7iE5TvAs6ShI10pDeNvoq5cJ7BfPL/rFHOA7AICajeb7XpA9S huYw8BX4ZybNmzYFn1bGpCqBQoadDZ/J4gxQ/DwA+BVJFmaIUlRVjRL8DhIDhlrq ylbB+QuoMo3P+2cZcR2lWAfZhwg+9/KjsQ8bJr9ZzktI4GcsoFDvNkDMawKBgG9X 0yg391J+Ii5MYQOXmcbXc/rS6eeMmStD9CiD3wDSnOObQ9my+VtJGOy35ET2Vpvx dCCnYNKlxnj1Mias3f2o4BxFe+aYbLVr2D67cgxT2Vxxneu7cMOPQm5nvGPYTK/u bsD7/6ycmnECKLeyTRw/V2AWysG7cyXerb7gsuuZAoGBAKt6NNVpxqmHB6/Wdqsi sct6YBeZSLPuK/PtK5anVwTYlN7Omg2BjS+/yCygNuDp+px9ykHwYicSgDsJxyOt 1Spw+uMVoNG6yvIE3q7mjhDoHDu5lUA8s6uzzcTsvDnSLR6uNV2iqDzR/Osu3+bp QjRCFXd0Tr5PlKpAHb6dk+aI -----END PRIVATE KEY----- """.trimIndent() private val publicKeyString = """ -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2xcCZycepeC6tbbIldJ6 d2qMN/absNkv84h9NA/UzOlrbBil3ZlhZ/1471fOSQ3tJjT+6OcOIH1Wp3JvOurz puoGrKRyHJfkPD6jNoGb+5Cm2nCM5k4BJjK4pS/X6fkNhYZO62V1jR8rVNQtuE+O AGjDX6QqfhBFZsimScfBF1oA4wmdTIHdfmywweT0uQoGmm0Kymnc8A4Rn3Grp6rb mMm9crlF3xC+Aglb4kHb5LRngyPvvP1HcI5vNph7Do09t/6Lm+Wc59ZLKhgeJLXE hCZOeUxMo048R/vLkNtq5SUK9glQ3vlOZHl4ldhvCShKuBtyFimkqnkL6ARjYDsM +QIDAQAB -----END PUBLIC KEY----- """.trimIndent() fun privateKey(): PrivateKey { val privateKeyBytes = privateKeyString.replace("-----END PRIVATE KEY-----", "") .replace("-----BEGIN PRIVATE KEY-----", "") .replace("\n", "") .decodeBase64()?.toByteArray() ?: throw IllegalStateException("Invalid private key.") val keySpec = PKCS8EncodedKeySpec(privateKeyBytes) val keyFactory = KeyFactory.getInstance("RSA") return keyFactory.generatePrivate(keySpec) } fun publicKey(): PublicKey { val publicKeyBytes = publicKeyString.replace("-----END PUBLIC KEY-----", "") .replace("-----BEGIN PUBLIC KEY-----", "") .replace("\n", "") .decodeBase64()?.toByteArray() ?: throw IllegalStateException("Invalid public key.") val keySpec = X509EncodedKeySpec(publicKeyBytes) val keyFactory = KeyFactory.getInstance("RSA") return keyFactory.generatePublic(keySpec) } }
15
Kotlin
11
33
72776583e6e4066d576f36b4d73ed83216e61584
4,273
okta-mobile-kotlin
Apache License 2.0
app/app/src/main/java/app/emmabritton/cibusana/DateTimePrinter.kt
emmabritton
559,135,688
false
null
package app.emmabritton.cibusana import android.content.Context import android.text.format.DateFormat import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.util.* class DateTimePrinter(private val context: Context) { fun formatTime(zonedDateTime: ZonedDateTime): String { val is24Hour = DateFormat.is24HourFormat(context) val isAmerican = Locale.getDefault() == Locale.US //handle 24 hour and american variants return DateTimeFormatter.ofPattern("HH:mm").format(zonedDateTime) } fun formatShortDate(zonedDateTime: ZonedDateTime): String { val isAmerican = Locale.getDefault() == Locale.US return DateTimeFormatter.ofPattern("dd/MM/yyyy").format(zonedDateTime) } fun formatDate(zonedDateTime: ZonedDateTime): String { return DateTimeFormatter.ofPattern("dd MMM yyyy").format(zonedDateTime) } }
0
Kotlin
0
0
1e2bf6836a97b8f4b92d00656c113a27ace1185c
907
cibusana
MIT License
app/src/main/java/com/wavesplatform/wallet/v2/data/model/service/coinomat/LimitResponse.kt
wavesplatform
98,419,999
false
null
package com.wavesplatform.wallet.v2.data.model.service.coinomat import com.google.gson.annotations.SerializedName data class LimitResponse( @SerializedName("min") var min: String? = null, @SerializedName("max") var max: String? = null)
2
Kotlin
52
55
5f4106576dc4fe377a355d045f638e7469cd6abe
253
WavesWallet-android
MIT License
app/src/main/java/com/renaisn/reader/model/rss/RssParserDefault.kt
RenaisnNce
598,532,496
false
null
package com.renaisn.reader.model.rss import com.renaisn.reader.data.entities.RssArticle import com.renaisn.reader.model.Debug import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserException import org.xmlpull.v1.XmlPullParserFactory import java.io.IOException import java.io.StringReader @Suppress("unused") object RssParserDefault { @Throws(XmlPullParserException::class, IOException::class) fun parseXML( sortName: String, xml: String, sourceUrl: String ): Pair<MutableList<RssArticle>, String?> { val articleList = mutableListOf<RssArticle>() var currentArticle = RssArticle() val factory = XmlPullParserFactory.newInstance() factory.isNamespaceAware = false val xmlPullParser = factory.newPullParser() xmlPullParser.setInput(StringReader(xml)) // A flag just to be sure of the correct parsing var insideItem = false var eventType = xmlPullParser.eventType // Start parsing the xml loop@ while (eventType != XmlPullParser.END_DOCUMENT) { // Start parsing the item if (eventType == XmlPullParser.START_TAG) { when { xmlPullParser.name.equals(RSS_ITEM, true) -> insideItem = true xmlPullParser.name.equals(RSS_ITEM_TITLE, true) -> if (insideItem) currentArticle.title = xmlPullParser.nextText().trim() xmlPullParser.name.equals(RSS_ITEM_LINK, true) -> if (insideItem) currentArticle.link = xmlPullParser.nextText().trim() xmlPullParser.name.equals(RSS_ITEM_THUMBNAIL, true) -> if (insideItem) currentArticle.image = xmlPullParser.getAttributeValue(null, RSS_ITEM_URL) xmlPullParser.name.equals(RSS_ITEM_ENCLOSURE, true) -> if (insideItem) { val type = xmlPullParser.getAttributeValue(null, RSS_ITEM_TYPE) if (type != null && type.contains("image/")) { currentArticle.image = xmlPullParser.getAttributeValue(null, RSS_ITEM_URL) } } xmlPullParser.name .equals(RSS_ITEM_DESCRIPTION, true) -> if (insideItem) { val description = xmlPullParser.nextText() currentArticle.description = description.trim() if (currentArticle.image == null) { currentArticle.image = getImageUrl(description) } } xmlPullParser.name.equals(RSS_ITEM_CONTENT, true) -> if (insideItem) { val content = xmlPullParser.nextText().trim() currentArticle.content = content if (currentArticle.image == null) { currentArticle.image = getImageUrl(content) } } xmlPullParser.name .equals(RSS_ITEM_PUB_DATE, true) -> if (insideItem) { val nextTokenType = xmlPullParser.next() if (nextTokenType == XmlPullParser.TEXT) { currentArticle.pubDate = xmlPullParser.text.trim() } // Skip to be able to find date inside 'tag' tag continue@loop } xmlPullParser.name.equals(RSS_ITEM_TIME, true) -> if (insideItem) currentArticle.pubDate = xmlPullParser.nextText() } } else if (eventType == XmlPullParser.END_TAG && xmlPullParser.name.equals("item", true) ) { // The item is correctly parsed insideItem = false currentArticle.origin = sourceUrl currentArticle.sort = sortName articleList.add(currentArticle) currentArticle = RssArticle() } eventType = xmlPullParser.next() } articleList.firstOrNull()?.let { Debug.log(sourceUrl, "┌获取标题") Debug.log(sourceUrl, "└${it.title}") Debug.log(sourceUrl, "┌获取时间") Debug.log(sourceUrl, "└${it.pubDate}") Debug.log(sourceUrl, "┌获取描述") Debug.log(sourceUrl, "└${it.description}") Debug.log(sourceUrl, "┌获取图片url") Debug.log(sourceUrl, "└${it.image}") Debug.log(sourceUrl, "┌获取文章链接") Debug.log(sourceUrl, "└${it.link}") } return Pair(articleList, null) } /** * Finds the first img tag and get the src as featured image * * @param input The content in which to search for the tag * @return The url, if there is one */ private fun getImageUrl(input: String): String? { var url: String? = null val patternImg = "(<img [^>]*>)".toPattern() val matcherImg = patternImg.matcher(input) if (matcherImg.find()) { val imgTag = matcherImg.group(1) val patternLink = "src\\s*=\\s*\"([^\"]+)\"".toPattern() val matcherLink = patternLink.matcher(imgTag!!) if (matcherLink.find()) { url = matcherLink.group(1)!!.trim() } } return url } private const val RSS_ITEM = "item" private const val RSS_ITEM_TITLE = "title" private const val RSS_ITEM_LINK = "link" private const val RSS_ITEM_CATEGORY = "category" private const val RSS_ITEM_THUMBNAIL = "media:thumbnail" private const val RSS_ITEM_ENCLOSURE = "enclosure" private const val RSS_ITEM_DESCRIPTION = "description" private const val RSS_ITEM_CONTENT = "content:encoded" private const val RSS_ITEM_PUB_DATE = "pubDate" private const val RSS_ITEM_TIME = "time" private const val RSS_ITEM_URL = "url" private const val RSS_ITEM_TYPE = "type" }
1
Kotlin
1
4
4ac03e214e951f7f4f337d4da1f7e39fa715d1c0
6,407
Renaisn_Android
MIT License
src/main/kotlin/net/adriantodt/winged/item/GiftWingItem.kt
qsefthuopq
360,903,827
true
{"Kotlin": 84355, "Java": 7673}
package net.adriantodt.winged.item import net.adriantodt.winged.WingItems import net.fabricmc.api.EnvType import net.fabricmc.api.Environment import net.minecraft.client.item.TooltipContext import net.minecraft.entity.player.PlayerEntity import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraft.sound.SoundEvents import net.minecraft.text.Text import net.minecraft.text.TranslatableText import net.minecraft.util.Hand import net.minecraft.util.TypedActionResult import net.minecraft.world.World import kotlin.random.asKotlinRandom class GiftWingItem(settings: Settings) : Item(settings) { override fun use(world: World, user: PlayerEntity, hand: Hand): TypedActionResult<ItemStack> { user.playSound(SoundEvents.BLOCK_WOOL_BREAK, 1.0f, 0.0f) return TypedActionResult.success(ItemStack(WingItems.giftableWings.random(user.random.asKotlinRandom()))) } @Environment(EnvType.CLIENT) override fun appendTooltip(stack: ItemStack?, world: World?, tooltip: MutableList<Text?>, ctx: TooltipContext?) { tooltip += TranslatableText("$translationKey.description") tooltip += TranslatableText("tooltip.winged.gift_wing_item") } }
0
null
0
0
fb7b03a9078d8006551ede891b6f8ceec5fadbe2
1,203
Winged
Apache License 2.0
k9mail/src/main/java/com/fsck/k9/ui/endtoend/AutocryptKeyTransferPresenter.kt
jmsecurity05
139,341,075
true
{"Java": 4634779, "Kotlin": 217356, "Shell": 2775, "HTML": 292}
package com.fsck.k9.ui.endtoend import android.app.PendingIntent import android.arch.lifecycle.LifecycleOwner import android.arch.lifecycle.Observer import android.content.Context import com.fsck.k9.Account import com.fsck.k9.Preferences import com.fsck.k9.mail.TransportProvider import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.delay import kotlinx.coroutines.experimental.launch import org.openintents.openpgp.OpenPgpApiManager import org.openintents.openpgp.OpenPgpApiManager.OpenPgpApiManagerCallback import org.openintents.openpgp.OpenPgpApiManager.OpenPgpProviderError import timber.log.Timber class AutocryptKeyTransferPresenter internal constructor( lifecycleOwner: LifecycleOwner, private val context: Context, private val openPgpApiManager: OpenPgpApiManager, private val transportProvider: TransportProvider, private val preferences: Preferences, private val viewModel: AutocryptKeyTransferViewModel, private val view: AutocryptKeyTransferActivity ) { private lateinit var account: Account private lateinit var showTransferCodePi: PendingIntent init { viewModel.autocryptSetupMessageLiveEvent.observe(lifecycleOwner, Observer { msg -> msg?.let { onEventAutocryptSetupMessage(it) } }) viewModel.autocryptSetupTransferLiveEvent.observe(lifecycleOwner, Observer { pi -> onLoadedAutocryptSetupTransfer(pi) }) } fun initFromIntent(accountUuid: String?) { if (accountUuid == null) { view.finishWithInvalidAccountError() return } account = preferences.getAccount(accountUuid) openPgpApiManager.setOpenPgpProvider(account.openPgpProvider, object : OpenPgpApiManagerCallback { override fun onOpenPgpProviderStatusChanged() { if (openPgpApiManager.openPgpProviderState == OpenPgpApiManager.OpenPgpProviderState.UI_REQUIRED) { view.finishWithProviderConnectError(openPgpApiManager.readableOpenPgpProviderName) } } override fun onOpenPgpProviderError(error: OpenPgpProviderError) { view.finishWithProviderConnectError(openPgpApiManager.readableOpenPgpProviderName) } }) view.setAddress(account.identities[0].email) viewModel.autocryptSetupTransferLiveEvent.recall() } fun onClickHome() { view.finishAsCancelled() } fun onClickTransferSend() { view.sceneGeneratingAndSending() launch(UI) { view.uxDelay() view.setLoadingStateGenerating() viewModel.autocryptSetupMessageLiveEvent.loadAutocryptSetupMessageAsync(openPgpApiManager.openPgpApi, account) } } fun onClickShowTransferCode() { view.launchUserInteractionPendingIntent(showTransferCodePi) } private fun onEventAutocryptSetupMessage(setupMsg: AutocryptSetupMessage) { view.setLoadingStateSending() view.sceneGeneratingAndSending() val transport = transportProvider.getTransport(context, account) viewModel.autocryptSetupTransferLiveEvent.sendMessageAsync(transport, setupMsg) } private fun onLoadedAutocryptSetupTransfer(result: AutocryptSetupTransferResult?) { when (result) { null -> view.sceneBegin() is AutocryptSetupTransferResult.Success -> { showTransferCodePi = result.showTransferCodePi view.setLoadingStateFinished() view.sceneFinished() } is AutocryptSetupTransferResult.Failure -> { Timber.e(result.exception, "Error sending setup message") view.setLoadingStateSendingFailed() view.sceneSendError() } } } }
0
Java
0
0
705ca3e69ddc611796e1e028a5513d9a6d089bd1
3,844
k-9
Apache License 2.0
app/src/main/java/com/appzeto/lms/presenterImpl/SearchResultPresenterImpl.kt
Prashant-ranjan-singh-123
815,819,154
false
{"Kotlin": 1527382, "Java": 137045}
package com.appzeto.lms.presenterImpl import com.appzeto.lms.manager.net.ApiService import com.appzeto.lms.manager.net.CustomCallback import com.appzeto.lms.manager.net.RetryListener import com.appzeto.lms.model.Data import com.appzeto.lms.model.SearchObject import com.appzeto.lms.presenter.Presenter import com.appzeto.lms.ui.frag.SearchResultFrag import retrofit2.Call import retrofit2.Response class SearchResultPresenterImpl(private val searchFrag: SearchResultFrag) : Presenter.SearchResultPresenter { override fun search(s: String) { val searchCoursesAndUsers = ApiService.apiClient!!.searchCoursesAndUsers(s) searchFrag.addNetworkRequest(searchCoursesAndUsers) searchCoursesAndUsers.enqueue(object : CustomCallback<Data<SearchObject>> { override fun onResponse( call: Call<Data<SearchObject>>, response: Response<Data<SearchObject>> ) { if (response.body() != null) { searchFrag.onSearchResultReceived(response.body()!!) } } override fun onStateChanged(): RetryListener? { return RetryListener { search(s) } } }) } }
0
Kotlin
0
0
73c9944e49064cf583ab3717ca829b8464ceff0f
1,269
StudySync
MIT License
build-logic/convention/src/main/kotlin/extensions/Plugins.kt
Midnight-Danger
750,764,030
false
{"Kotlin": 18224}
@file:Suppress("unused") package extensions import DependencyConfig import com.android.build.api.dsl.ApplicationExtension import com.android.build.api.dsl.LibraryExtension import com.android.build.gradle.BaseExtension import org.gradle.api.Project import org.gradle.api.artifacts.ExternalModuleDependencyBundle import org.gradle.api.artifacts.MinimalExternalModuleDependency import org.gradle.api.artifacts.VersionConstraint import org.gradle.api.provider.Provider import org.gradle.kotlin.dsl.DependencyHandlerScope import org.gradle.kotlin.dsl.getByType internal val Project.applicationExtension: ApplicationExtension get() = extensions.getByType<ApplicationExtension>() internal val Project.libraryExtension: LibraryExtension get() = extensions.getByType<LibraryExtension>() internal fun Project.vcVersion(alias: String): VersionConstraint { return versionCatalog().findVersion(alias).get() } internal fun Project.vcLibrary(alias: String): Provider<MinimalExternalModuleDependency> { return versionCatalog().findLibrary(alias).get() } internal fun Project.vcBundle(alias: String): Provider<ExternalModuleDependencyBundle> { return versionCatalog().findBundle(alias).get() } internal val Project.androidExtension get() = project.extensions.getByName("android") as? BaseExtension internal fun DependencyHandlerScope.implementation(dependency: Any) { add(DependencyConfig.IMPL, dependency) } internal fun DependencyHandlerScope.debugImplementation(dependency: Any) { add(DependencyConfig.DEBUG_IMPL, dependency) } internal fun DependencyHandlerScope.testImplementation(dependency: Any) { add(DependencyConfig.TEST_IMPL, dependency) } internal fun DependencyHandlerScope.implementationProject(dependency: Any) { add(DependencyConfig.IMPL, project(mapOf(DependencyConfig.PATH to dependency))) } internal fun DependencyHandlerScope.debugImplementationProject(dependency: Any) { add(DependencyConfig.DEBUG_IMPL, project(mapOf(DependencyConfig.PATH to dependency))) } internal fun DependencyHandlerScope.androidTestImplementation(dependency: Any) { add(DependencyConfig.ANDROID_TEST_IMP, dependency) } internal fun DependencyHandlerScope.coreLibraryDesugaring(dependency: Any) { add(DependencyConfig.CORE_LIB_DESUGARING, dependency) }
0
Kotlin
0
0
2e267de447ea58b1d65066e1a24acca3cbd43a70
2,295
cell-cascades
Creative Commons Zero v1.0 Universal
src/nativeMain/kotlin/io/github/tscholze/kblinkt/server/Server.kt
tscholze
718,624,241
false
{"Kotlin": 11605, "Shell": 376}
package io.github.tscholze.kblinkt.server import io.github.tscholze.kblinkt.apa102.Command import io.ktor.server.application.* import io.ktor.server.cio.* import io.ktor.server.engine.* import io.ktor.server.response.* import io.ktor.server.routing.* import kotlinx.coroutines.flow.MutableSharedFlow /** * Starts and runs the embedded server. * * @param actions: Flow in which requested action via API should be emitted. */ fun runServer(actions: MutableSharedFlow<Command>): ApplicationEngine { return embeddedServer(CIO, port = 8080) { routing { // Listen to GET requests on root get("/") { call.respondText("Hi from KBlinkt") } // Listen to POST requests on /on post("on") { actions.emit(Command.TurnOn) } // Listen to POST requests on /off post("off") { actions.emit(Command.TurnOff) } } }.start() }
0
Kotlin
0
0
175bb943cba7ed3c649449ebe08aec4952237f6e
994
kotlin-kpi-native-blinkt
MIT License
idea/testData/addImport/ConflictingNameHasExplicitImportAlready.kt
JakeWharton
99,388,807
true
null
// IMPORT: java.util.Calendar package p import java.sql.* import java.sql.Date val d: Date? = null
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
101
kotlin
Apache License 2.0
app/src/main/java/com/example/summerpractics/storage/DataBaseHelper.kt
HoofedDragon417
506,624,330
false
null
package com.example.summerpractics.storage import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import com.example.summerpractics.models.DatePeriodModel import com.example.summerpractics.models.MeetingDataModel import com.example.summerpractics.models.TaskDataModel class DataBaseHelper(context: Context?) : SQLiteOpenHelper( context, DATABASE_NAME, null, DATABASE_VERSION ) { companion object { private const val DATABASE_NAME = "MeetingsAndTasks" private const val DATABASE_VERSION = 1 private const val KEY_ID = "id" private const val KEY_TITLE = "title" private const val KEY_NOTE = "note" private const val TABLE_NAME_TASKS = "Tasks" private const val KEY_DURATION = "duration" private const val KEY_PRIORITY = "priority" private const val KEY_COMPLETED = "completed" private const val KEY_FOR_DELETE = "time_of_creation" private const val TABLE_NAME_MEETINGS = "Meetings" private const val KEY_TIME_BEGIN = "timeBegin" private const val KEY_TIME_END = "timeEnd" } private val CREATE_TABLE_TASKS = "create table $TABLE_NAME_TASKS(" + "$KEY_ID integer primary key autoincrement," + "$KEY_TITLE text," + "$KEY_NOTE text," + "$KEY_DURATION real," + "$KEY_PRIORITY integer," + "$KEY_COMPLETED integer," + "$KEY_FOR_DELETE real" + ")" private val CREATE_TABLE_MEETING = "create table $TABLE_NAME_MEETINGS(" + "$KEY_ID integer primary key autoincrement," + "$KEY_TITLE text," + "$KEY_NOTE text," + "$KEY_TIME_BEGIN real," + "$KEY_TIME_END real" + ")" override fun onCreate(db: SQLiteDatabase?) { db?.execSQL(CREATE_TABLE_TASKS) db?.execSQL(CREATE_TABLE_MEETING) } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { //Бесполезно(пока) } fun addMeeting(meeting: MeetingDataModel) { val db = this.writableDatabase val values = ContentValues() values.put(KEY_TITLE, meeting.title) values.put(KEY_NOTE, meeting.note) values.put(KEY_TIME_BEGIN, meeting.duration.periodBegin) values.put(KEY_TIME_END, meeting.duration.periodEnd) db.insert(TABLE_NAME_MEETINGS, null, values) db.close() } fun viewMeetings(dates: DatePeriodModel): ArrayList<MeetingDataModel> { val listOfMeetings = ArrayList<MeetingDataModel>() val db = this.readableDatabase val query = "select * from $TABLE_NAME_MEETINGS " + "where $KEY_TIME_BEGIN between ${dates.periodBegin} and ${dates.periodEnd}" + " order by $KEY_TIME_BEGIN" val cursor = db.rawQuery(query, null) if (cursor.moveToFirst()) { do { val id = cursor.getInt(0) val title = cursor.getString(1) val note = cursor.getString(2) val timeBegin = cursor.getLong(3) val timeEnd = cursor.getLong(4) val meeting = MeetingDataModel(id, title, note, DatePeriodModel(timeBegin, timeEnd)) listOfMeetings.add(meeting) } while (cursor.moveToNext()) } cursor.close() db.close() return listOfMeetings } fun deleteMeetings(border: Long) { val db = this.writableDatabase db.delete(TABLE_NAME_MEETINGS, "$KEY_TIME_BEGIN <= $border ", null) } fun addTask(task: TaskDataModel) { val db = this.writableDatabase val values = ContentValues() values.put(KEY_TITLE, task.title) values.put(KEY_NOTE, task.note) values.put(KEY_DURATION, task.duration) values.put(KEY_PRIORITY, task.priority) values.put(KEY_COMPLETED, task.completed) db.insert(TABLE_NAME_TASKS, null, values) db.close() } fun viewTasksWithParameter(parameter: Int): ArrayList<TaskDataModel> { val listOfTasks = ArrayList<TaskDataModel>() val db = this.readableDatabase val query = "select * from $TABLE_NAME_TASKS " + "where $KEY_COMPLETED like $parameter " + "order by $KEY_PRIORITY" val cursor = db.rawQuery(query, null) if (cursor.moveToFirst()) { do { val id = cursor.getInt(0) val title = cursor.getString(1) val note = cursor.getString(2) val duration = cursor.getDouble(3) val priority = cursor.getInt(4) val completed = cursor.getInt(5) val timeOfCreation = cursor.getLong(6) val task = TaskDataModel(id, title, note, duration, priority, completed, timeOfCreation) listOfTasks.add(task) } while (cursor.moveToNext()) } cursor.close() db.close() return listOfTasks } fun viewAllTasks(): ArrayList<TaskDataModel> { val listOfTasks = ArrayList<TaskDataModel>() val db = this.readableDatabase val query = "select * from $TABLE_NAME_TASKS " + "order by $KEY_PRIORITY" val cursor = db.rawQuery(query, null) if (cursor.moveToFirst()) { do { val id = cursor.getInt(0) val title = cursor.getString(1) val note = cursor.getString(2) val duration = cursor.getDouble(3) val priority = cursor.getInt(4) val completed = cursor.getInt(5) val timeOfCreation = cursor.getLong(6) val task = TaskDataModel(id, title, note, duration, priority, completed, timeOfCreation) listOfTasks.add(task) } while (cursor.moveToNext()) } cursor.close() db.close() return listOfTasks } fun updateTasks(task: TaskDataModel) { val db = this.writableDatabase val values = ContentValues() values.put(KEY_TITLE, task.title) values.put(KEY_NOTE, task.note) values.put(KEY_DURATION, task.duration) values.put(KEY_PRIORITY, task.priority) values.put(KEY_COMPLETED, task.completed) db.update(TABLE_NAME_TASKS, values, "$KEY_ID = ${task.id}", null) } fun deleteTasks(border: Long) { val db = this.writableDatabase db.delete(TABLE_NAME_TASKS, "$KEY_FOR_DELETE <= $border and $KEY_COMPLETED like 1", null) } }
0
Kotlin
0
0
5ca026a69e4bfcf3056765b2ed32cfb5e6b8edcf
6,789
SummerPractices
MIT License
src/main/kotlin/com/ffaero/openrocketassembler/controller/HistoryListenerList.kt
wildcat-rocketry
313,389,669
false
{"Kotlin": 162168}
package com.ffaero.openrocketassembler.controller class HistoryListenerList : ListenerListBase<HistoryListener>(), HistoryListener { override fun onStatus(sender: HistoryController, modified: Boolean) = forEach { it.onStatus(sender, modified) } override fun onHistoryUpdate(sender: HistoryController, undoAction: String?, redoAction: String?) = forEach { it.onHistoryUpdate(sender, undoAction, redoAction) } }
5
Kotlin
0
0
4c12948ed3b2fd5656a88ceb0cb2fcaa72d738ef
419
openrocket-assembler
MIT License
collector/test-data-uploader/src/main/kotlin/com/buildkite/test/collector/android/util/Constants.kt
buildkite
519,058,398
false
null
package com.buildkite.test.collector.android.util object Constants { object Collector { const val TEST_DATA_UPLOAD_LIMIT = 5000 } object Network { const val BASE_URL = "https://analytics-api.buildkite.com" const val TEST_UPLOADER_ENDPOINT = "/v1/uploads" } }
8
Kotlin
4
3
3a6165ce7c75e3612c95a9ca126829ddb07b4868
302
test-collector-android
MIT License
app/src/main/java/com/ai/covid19/tracking/android/ui/check/CheckViewModel.kt
AID-COVID-19
251,714,738
false
null
package com.ai.covid19.tracking.android.ui.check import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.amazonaws.mobileconnectors.appsync.AWSAppSyncClient import kotlin.properties.Delegates class CheckViewModel : ViewModel() { lateinit var riskResult: RiskAlgorithm.RiskClassification var riskScore: Double = 0.0 internal var mAWSAppSyncClient: AWSAppSyncClient? = null var timeStampLongId by Delegates.notNull<Long>() var howYouFeelSelectedId: Int = -1 var temperatureRangeSelectedId: Int = -1 var breathRangeSelectedId: Int = -1 var howYouFeel: String? = null var generalDiscomfort: Boolean = false var itchyOrSoreThroat: Boolean = false var diarrhea: Boolean = false var badTasteInTheMouth: Boolean = false var lossOfTasteInFood: Boolean = false var lossOfSmell: Boolean = false var musclePains: Boolean = false var chestOrBackPain: Boolean = false var headache: Boolean = false var wetCoughWithPhlegm: Boolean = false var dryCough: Boolean = false var chill: Boolean = false var fever: Boolean = false var fatigueWhenWalkingOrClimbingStairs: Boolean = false var feelingShortOfBreathWithDailyActivities: Boolean = false var respiratoryDistress: Boolean = false var newConfusionOrInabilityToArouse: Boolean = false var bluishLipsOrFace: Boolean = false var otherSymptomsOrDiscomfort: String? = null var temperatureRange: String? = null var breathsPerMinuteRange: String? = null var haveYouBeenNervousOrAnxious: String? = null var couldntStopBeingWorried: String? = null var haveYouWorriedTooMuchAboutDifferentThings: String? = null var haveYouHadDifficultyRelaxing: String? = null var haveYouBeenSoRestlessThatItIsDifficultToStayStill: String? = null var haveYouBecomeEasilyAnnoyedOrIrritable: String? = null var haveYouFeltFearAsIfSomethingHorribleWasGoingToHappen: String? = null var areYouTakingYourMedications: String? = null init { // AWSMobileClient.getInstance().userAttributes[""] } private val _text = MutableLiveData<String>().apply { value = "This is Check Fragment" } val text: LiveData<String> = _text }
5
Kotlin
0
2
82e7e9a3b92d72e4fecb91ccd4a4d8a0cfe5c1f0
2,282
carlosalbertomurillo-gmail.com
MIT License
src/main/kotlin/truesight/Highlights.kt
BinaryAlien
527,025,898
false
{"Kotlin": 94793, "TeX": 11847}
package truesight import java.awt.Color object Highlights { val red = Color(255, 100, 100) val orange = Color(255, 200, 100) val yellow = Color(255, 255, 100) val green = Color(100, 255, 100) val cyan = Color(100, 255, 255) val blue = Color(100, 100, 255) val pink = Color(255, 200, 200) val magenta = Color(255, 100, 255) val gray = Color(180, 180, 180) val none = Color.WHITE // null val selection = Color(255, 197, 153) private val highlights = mapOf( Pair("red", red), Pair("orange", orange), Pair("yellow", yellow), Pair("green", green), Pair("cyan", cyan), Pair("blue", blue), Pair("pink", pink), Pair("magenta", magenta), Pair("gray", gray), Pair(null, none) ) fun get(highlight: String?): Color = highlights.getOrDefault(highlight, none) }
0
Kotlin
0
1
32c73d627322c340e7a82bb8862ba5bfa0d3b664
888
True-Sight
MIT License
app/src/main/java/pl/better/foodzilla/ui/components/ComboBox.kt
kambed
612,140,416
false
null
package pl.better.foodzilla.ui.components import androidx.compose.foundation.background import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @OptIn(ExperimentalMaterialApi::class) @Composable fun ComboBox( modifier: Modifier = Modifier, items: List<String>, onItemSelected: (String) -> Unit, ) { var expanded by remember { mutableStateOf(false) } var selectedItem by remember { mutableStateOf("") } ExposedDropdownMenuBox( modifier = modifier, expanded = expanded, onExpandedChange = { expanded = !expanded } ) { TextField( value = selectedItem, onValueChange = {}, readOnly = true, label = { Text(text = "Sort opinions") }, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon( expanded = expanded ) }, colors = ExposedDropdownMenuDefaults.textFieldColors() ) // menu ExposedDropdownMenu( modifier = Modifier.background(MaterialTheme.colors.background), expanded = expanded, onDismissRequest = { expanded = false } ) { // this is a column scope // all the items are added vertically items.forEach { selectedOption -> // menu item DropdownMenuItem( onClick = { selectedItem = selectedOption onItemSelected(selectedOption) expanded = false }) { Text(text = selectedOption, color = Color.Black) } } } } }
1
Kotlin
0
3
94a8993b3aefc6271cea6ffd95546cb8c02802f4
1,853
FoodzillaFrontendAndroid
Apache License 2.0
xnet/src/main/java/com/gfms/xnet/utils/EncodingUtils.kt
r3tr056
875,356,073
false
{"Kotlin": 382790, "C++": 177456, "C": 140193, "CMake": 3494}
package com.gfms.xnet.utils import java.math.BigInteger object EncodingUtils { private const val VERSION_A = 'a' private const val ASCII_DIGITS_START = 48 private const val ASCII_DIGITS_END = 57 /* * Type prefixes */ private const val TYPE_INT = "i" private const val TYPE_LONG = "J" private const val TYPE_FLOAT = "f" private const val TYPE_STRING = "s" private const val TYPE_BYTES = "b" private const val TYPE_LIST = "l" private const val TYPE_SET = "L" private const val TYPE_TUPLE = "t" private const val TYPE_DICTIONARY = "d" private const val TYPE_NONE = "n" private const val TYPE_TRUE = "T" private const val TYPE_FALSE = "F" /** * Encodes data into version "a" binary stream. */ fun encode(value: Any?): ByteArray { val encoded = encodeValue(value) return "$VERSION_A$encoded".toByteArray(Charsets.UTF_8) } @Suppress("UNCHECKED_CAST") private fun encodeValue(value: Any?): String { return when (value) { is Int -> encodeInt(value) is BigInteger -> encodeInt(value) is Long -> encodeLong(value) is String -> encodeString(value) is Float -> encodeFloat(value) is List<*> -> encodeList(value) is Set<*> -> encodeSet(value) is Map<*, *> -> encodeDictionary(value as Map<Any?, Any?>) is Boolean -> encodeBoolean(value) null -> encodeNone() else -> throw TransactionSerializationException("Unsupported value type") } } /** * Decodes data from version "a" binary stream. Returns the pair containing the offset and * the decoded value. */ fun decode(buffer: ByteArray, offset: Int = 0): Pair<Int, Any?> { val version = buffer[offset] if (version.toInt().toChar() == VERSION_A) { return decodeValue(buffer, offset + 1) } else { throw TransactionSerializationException("Unknown version found: $version") } } private fun decodeValue(buffer: ByteArray, offset: Int): Pair<Int, Any?> { var index = offset while (buffer[index] in ASCII_DIGITS_START..ASCII_DIGITS_END) { index++ } val count = buffer.copyOfRange(offset, index).toString(Charsets.UTF_8).toInt() return when (val type = buffer[index].toInt().toChar().toString()) { TYPE_INT -> decodeInt(buffer, index + 1, count) TYPE_LONG -> decodeLong(buffer, index + 1, count) TYPE_STRING, TYPE_BYTES -> decodeString(buffer, index + 1, count) TYPE_FLOAT -> decodeFloat(buffer, index + 1, count) TYPE_LIST, TYPE_TUPLE -> decodeList(buffer, index + 1, count) TYPE_SET -> decodeSet(buffer, index + 1, count) TYPE_DICTIONARY -> decodeDictionary(buffer, index + 1, count) TYPE_TRUE -> decodeTrue(index + 1) TYPE_FALSE -> decodeFalse(index + 1) TYPE_NONE -> decodeNone(index + 1) else -> throw IllegalArgumentException("Unknown value type: $type") } } private fun encodeInt(value: Int): String { val str = value.toString() return "" + str.length + TYPE_INT + str } private fun encodeInt(value: BigInteger): String { val str = value.toString() return "" + str.length + TYPE_INT + str } private fun decodeInt(buffer: ByteArray, offset: Int, count: Int): Pair<Int, BigInteger> { val value = buffer.copyOfRange(offset, offset + count) .toString(Charsets.UTF_8) .toBigInteger() return Pair(offset + count, value) } private fun encodeLong(value: Long): String { val str = value.toString() return "" + str.length + TYPE_LONG + str } private fun decodeLong(buffer: ByteArray, offset: Int, count: Int): Pair<Int, Long> { val value = buffer.copyOfRange(offset, offset + count) .toString(Charsets.UTF_8) .toLong() return Pair(offset + count, value) } private fun encodeFloat(value: Float): String { val str = value.toString() return "" + str.length + TYPE_FLOAT + str } private fun decodeFloat(buffer: ByteArray, offset: Int, count: Int): Pair<Int, Float> { val value = buffer.copyOfRange(offset, offset + count) .toString(Charsets.UTF_8) .toFloat() return Pair(offset + count, value) } private fun encodeString(value: String): String { return "" + value.toByteArray(Charsets.UTF_8).size + TYPE_STRING + value } private fun decodeString(buffer: ByteArray, offset: Int, count: Int): Pair<Int, String> { val value = buffer.copyOfRange(offset, offset + count) .toString(Charsets.UTF_8) return Pair(offset + count, value) } private fun encodeList(values: List<Any?>): String { val encoded = StringBuilder() encoded.append(values.size) encoded.append(TYPE_LIST) for (value in values) { encoded.append(encodeValue(value)) } return encoded.toString() } private fun decodeList(buffer: ByteArray, offset: Int, count: Int): Pair<Int, List<Any?>> { val container = mutableListOf<Any?>() var localOffset = offset for (i in 0 until count) { val (newOffset, value) = decodeValue(buffer, localOffset) localOffset = newOffset container += value } return Pair(localOffset, container) } private fun encodeSet(values: Set<Any?>): String { val encoded = StringBuilder() encoded.append(values.size) encoded.append(TYPE_SET) for (value in values) { encoded.append(encodeValue(value)) } return encoded.toString() } private fun decodeSet(buffer: ByteArray, offset: Int, count: Int): Pair<Int, Set<Any?>> { val container = mutableSetOf<Any?>() var localOffset = offset for (i in 0 until count) { val (newOffset, value) = decodeValue(buffer, localOffset) localOffset = newOffset container += value } return Pair(localOffset, container) } private fun encodeDictionary(values: Map<Any?, Any?>): String { val encoded = StringBuilder() encoded.append(values.size) encoded.append(TYPE_DICTIONARY) for ((key, value) in values) { encoded.append(encodeValue(key)) encoded.append(encodeValue(value)) } return encoded.toString() } private fun decodeDictionary(buffer: ByteArray, offset: Int, count: Int): Pair<Int, Map<Any?, Any?>> { val container = mutableMapOf<Any?, Any?>() var localOffset = offset for (i in 0 until count) { val (keyOffset, key) = decodeValue(buffer, localOffset) localOffset = keyOffset val (valueOffset, value) = decodeValue(buffer, localOffset) localOffset = valueOffset container[key] = value } return Pair(localOffset, container) } private fun encodeNone(): String { return "0$TYPE_NONE" } private fun decodeNone(offset: Int): Pair<Int, Any?> { return Pair(offset, null) } private fun encodeBoolean(value: Boolean): String { return "0" + if (value) TYPE_TRUE else TYPE_FALSE } private fun decodeTrue(offset: Int): Pair<Int, Boolean> { return Pair(offset, true) } private fun decodeFalse(offset: Int): Pair<Int, Boolean> { return Pair(offset, false) } } class TransactionSerializationException(message: String) : Exception(message)
0
Kotlin
0
0
d76c8c1f2c9a426354d88065f37c15e1c6a51b02
7,814
koinoor
MIT License
app/src/main/java/com/example/chart/GeneratePass.kt
Iamsdt
187,832,967
false
null
package com.example.chart import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import cc.duduhuo.util.digest.Digest import com.example.chart.db.DbHelper import com.example.chart.db.MyTable import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.content_main.* import kotlinx.coroutines.* import lecho.lib.hellocharts.listener.PieChartOnValueSelectListener import lecho.lib.hellocharts.model.PieChartData import lecho.lib.hellocharts.model.SliceValue class GeneratePass : AppCompatActivity() { var pass = "" var color = "" private val job = SupervisorJob() val uiScope = CoroutineScope(Dispatchers.Default + job) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val status = intent.getBooleanExtra("Login", true) val email = intent.getStringExtra("Email") ?: "" val name = intent.getStringExtra("Name") ?: "" //pyChartGenerate(Generator.generateColorList()) pyChartGenerate2(Generator.generateCapWordList()) cap_button?.setOnClickListener { pyChartGenerate2(Generator.generateCapWordList()) } small_button?.setOnClickListener { pyChartGenerate2(Generator.generateSmallWordList()) } num_button?.setOnClickListener { pyChartGenerate2(Generator.generateNumberList()) } symbol_button?.setOnClickListener { pyChartGenerate2(Generator.generateSymbolsList()) } imageView2.setOnClickListener { if (pass.isNotEmpty()) { pass = pass.removeRange(pass.length - 1, pass.length) } } fab.setOnClickListener { if (status) { sigin(pass, email) } else { checkValid(pass, name, email) } } } private fun sigin(pass: String, email: String) { uiScope.launch { val dao = DbHelper.getDatabase(this@GeneratePass) val data = withContext(Dispatchers.IO) { dao.search(email) } if (data == null) { withContext(Dispatchers.Main) { Toast.makeText(this@GeneratePass, "No account found, Please create one!", Toast.LENGTH_SHORT).show() finish() } } else { val text = color + pass val pas = Digest.sha1Hex(text, true) if (pas == data.pass) { val intent = Intent(this@GeneratePass, SuccessActivity::class.java) intent.putExtra("Email", email) startActivity(intent) finish() } else { withContext(Dispatchers.Main) { Toast.makeText(this@GeneratePass, "Password don't match", Toast.LENGTH_SHORT).show() } } } } } private fun pyChartGenerate(list: List<SliceValue>) { val data = PieChartData(list) data.setHasLabels(false) data.isValueLabelBackgroundAuto = false data.isValueLabelBackgroundEnabled = false data.setHasCenterCircle(true) data.centerCircleScale = 0.80f pieChart.pieChartData = data pieChart.isChartRotationEnabled = false pieChart.onValueTouchListener = object : PieChartOnValueSelectListener { override fun onValueSelected(arcIndex: Int, value: SliceValue?) { value?.let { val v = String(value.labelAsChars) color = v } } override fun onValueDeselected() { //nothing to do } } } private fun pyChartGenerate2(list: List<SliceValue>) { val data = PieChartData(list) data.setHasLabels(true) data.isValueLabelBackgroundAuto = false data.isValueLabelBackgroundEnabled = false data.setHasCenterCircle(true) inner.pieChartData = data inner.onValueTouchListener = object : PieChartOnValueSelectListener { override fun onValueSelected(arcIndex: Int, value: SliceValue?) { value?.let { val v = String(value.labelAsChars) pass += v } } override fun onValueDeselected() { //nothing to do } } } private fun checkValid(pass: String, name: String, email: String) { if (color.isEmpty()) { Toast.makeText(this, "Please select color", Toast.LENGTH_SHORT).show() return } //check length is if (pass.length >= 8) { if (pass.contains(Regex(".*[a-z].*"))) { if (pass.contains(Regex(".*[A-Z].*"))) { val pattern = ".*[@#$%&*?<>|].*" if (pass.contains(Regex(pattern))) { if (pass.contains(Regex(".*[1-9].*"))) { val data = color + pass val en = Digest.sha1Hex(data, true) createAccount(en, name, email) } else { Toast.makeText(this, "Password must contains numbers", Toast.LENGTH_SHORT).show() } } else { Toast.makeText(this, "Password must contains special symbols", Toast.LENGTH_SHORT).show() } } else { Toast.makeText(this, "Password must contains capital characters", Toast.LENGTH_SHORT).show() } } else { Toast.makeText(this, "Password must contains Small characters", Toast.LENGTH_SHORT).show() } } else { Toast.makeText(this, "Password is too short", Toast.LENGTH_SHORT).show() } } private fun createAccount(pass: String, name: String, email: String) { uiScope.launch { val table = MyTable(0, name, pass, email) val dao = DbHelper.getDatabase(this@GeneratePass) val status = withContext(Dispatchers.IO) { dao.add(table) } if (status > 0) { val intent = Intent(this@GeneratePass, SuccessActivity::class.java) intent.putExtra("Email", email) startActivity(intent) finish() } else { Toast.makeText(this@GeneratePass, "Something went wrong", Toast.LENGTH_SHORT).show() } } } override fun onDestroy() { super.onDestroy() uiScope.cancel(CancellationException("Activity destroyed")) } }
0
Kotlin
0
0
06ef64788e3e2d21265df639f5d5ac96166e680b
6,958
Chart
Apache License 2.0
frontend/src/main/kotlin/externals/redux-logger_impls.kt
NikkyAI
182,227,647
false
null
package externals data class ReduxLoggerOptionsImpl( override var level: String /* String | ActionToString | LevelObject */, override var duration: Boolean? = null, override var timestamp: Boolean? = null, override var colors: ColorsObject = ColorsObjectImpl(), /* ColorsObject | false */ override val titleFormatter: ((formattedAction: Any, formattedTime: String, took: Number) -> String)? = null, override var logger: Any? = null, override var logErrors: Boolean? = null, override var collapsed: Boolean = true, /* Boolean | LoggerPredicate */ override var predicate: LoggerPredicate? = null, override var diff: Boolean? = null, override var diffPredicate: LoggerPredicate? = null, override val stateTransformer: ((state: Any) -> Any)? = null, override val actionTransformer: ((action: Any) -> Any)? = null, override val errorTransformer: ((error: Any) -> Any)? = null ): ReduxLoggerOptions data class ColorsObjectImpl ( override var title: Boolean = true, /* Boolean | ActionToString */ override var prevState: Boolean = true, /* Boolean | StateToString */ override var action: Boolean = true, /* Boolean | ActionToString */ override var nextState: Boolean = true, /* Boolean | StateToString */ override var error: Boolean = true /* Boolean | ErrorToString */ ): ColorsObject
1
Kotlin
3
10
2c26c2ea122525ba2825f32cbf24bde3c78afa6a
1,358
pentagame
MIT License