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
sources/libraries/extensions/src/main/kotlin/com/egoriku/ladyhappy/extensions/View.kt
egorikftp
102,286,802
false
null
@file:Suppress("NOTHING_TO_INLINE") package com.egoriku.ladyhappy.extensions import android.content.res.ColorStateList import android.content.res.TypedArray import android.util.AttributeSet import android.view.View import android.widget.ImageView import androidx.annotation.AttrRes import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.core.content.withStyledAttributes import com.google.android.material.snackbar.Snackbar import kotlin.math.roundToInt inline fun View.gone() { if (visibility != View.GONE) visibility = View.GONE } inline fun View.invisible() { if (visibility != View.INVISIBLE) visibility = View.INVISIBLE } inline fun View.visible() { if (visibility != View.VISIBLE) visibility = View.VISIBLE } fun View.colorCompat(@ColorRes colorInt: Int) = context.colorCompat(colorInt) fun View.colorStateListCompat(@ColorRes resId: Int): ColorStateList? = context.colorStateListCompat(resId) fun View.colorFromAttr(@AttrRes attribute: Int) = context.colorFromAttr(attribute) inline fun View.resIdFromAttr(@AttrRes attr: Int) = context.resIdFromAttr(attr) fun View.drawableCompat(@DrawableRes drawableRes: Int) = context.drawableCompat(drawableRes) ?: throw IllegalArgumentException("Wrong drawable id $drawableRes") fun View.withStyledAttributes( attributeSet: AttributeSet? = null, styleArray: IntArray, defStyleAttr: Int = 0, defStyleRes: Int = 0, block: TypedArray.() -> Unit ) = context.withStyledAttributes( set = attributeSet, attrs = styleArray, defStyleAttr = defStyleAttr, defStyleRes = defStyleRes, block = block ) inline fun View.indefiniteSnackBar( @StringRes message: Int, @StringRes actionText: Int, anchorView: View = this, noinline action: (View) -> Unit ) = Snackbar .make(this, message, Snackbar.LENGTH_INDEFINITE) .setAnchorView(anchorView) .setAction(actionText, action) .show() inline fun View.longSnackBar( @StringRes message: Int, @StringRes actionText: Int, anchorView: View = this, noinline action: (View) -> Unit ) = Snackbar .make(this, message, Snackbar.LENGTH_LONG) .setAnchorView(anchorView) .setAction(actionText, action) .show() inline fun View.addRipple() { isClickable = true setBackgroundResource(resIdFromAttr(android.R.attr.selectableItemBackground)) } fun View.pxToDp(value: Int): Int = (value.toFloat() / context.resources.displayMetrics.density).roundToInt() inline fun View.activated() { isActivated = true } inline fun View.resetActivated() { isActivated = false } inline fun View.toImageView() = this as ImageView
12
null
22
261
da53bf026e104b84eebb7c2660c2feae26c6d965
2,700
Lady-happy-Android
Apache License 2.0
src/main/kotlin/com/imoonday/entity/TornadoEntity.kt
iMoonDay
759,188,611
false
{"Kotlin": 472450, "Java": 57363}
package com.imoonday.entity import com.imoonday.init.ModEntities import com.imoonday.util.blockPosSet import net.minecraft.entity.Entity import net.minecraft.entity.EntityType import net.minecraft.entity.LivingEntity import net.minecraft.entity.MovementType import net.minecraft.entity.projectile.ProjectileEntity import net.minecraft.particle.ParticleTypes import net.minecraft.server.world.ServerWorld import net.minecraft.util.math.Vec3d import net.minecraft.world.World class TornadoEntity(type: EntityType<out ProjectileEntity>, world: World) : ProjectileEntity(type, world) { constructor(world: World, owner: Entity, velocity: Vec3d) : this(ModEntities.TORNADO, world) { this.owner = owner this.velocity = velocity noClip = true } override fun initDataTracker() = Unit override fun tick() { super.tick() if (!world.isClient && (age > 100 || !world.isChunkLoaded(blockPos))) { discard() return } move(MovementType.SELF, velocity) world.getNonSpectatingEntities(LivingEntity::class.java, boundingBox.expand(1.0)).forEach { if (it != owner) it.addVelocity(velocity) } val posSet = boundingBox.expand(1.0).blockPosSet posSet.filter { world.getBlockState(it).block.hardness == 0f } .forEach { world.breakBlock(it, true, this) } if (world.getBlockCollisions(this, boundingBox).toList().isNotEmpty()) { (world as? ServerWorld)?.spawnParticles( ParticleTypes.CLOUD, pos.x, pos.y + height / 2, pos.z, 100, (width + 1) / 2.0, height / 2.0, (width + 1) / 2.0, 0.0 ) discard() } else if (age % 5 == 0) { repeat(5) { world.addParticle( ParticleTypes.CLOUD, pos.x + (random.nextFloat() - 0.5f) * (width + 1) / 2.0, pos.y + height / 2 + (random.nextFloat() - 0.5f) * height / 2.0, pos.z + (random.nextFloat() - 0.5f) * (width + 1) / 2.0, -velocity.x, 0.0, -velocity.z ) } } } }
0
Kotlin
0
0
3a2660afca6d625c6ce4c08553817eac7960bfec
2,333
AdvancedSkills
Creative Commons Zero v1.0 Universal
app/src/main/java/com/opensource/marvelcharacters/framework/persistance/Migrations.kt
Mohammad-Tabbara
219,486,106
false
null
package com.opensource.marvelcharacters.framework.persistance
0
Kotlin
0
0
71b2036b6ee85c305c6fb3a66fe8d55f32a91245
63
MarvelAndroidApp
Apache License 2.0
kotlin-js/src/jsMain/kotlin/js/collections/JsSet.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
package js.collections import js.array.JsTuple2 import js.array.ReadonlyArray import js.iterable.JsIterable import js.iterable.JsIterator @JsName("Set") open external class JsSet<T>( values: JsIterable<T> = definedExternally, ) : MutableSetLike<T> { constructor(values: ReadonlyArray<T>) override val size: Int override fun add(value: T) override fun clear() override fun delete(value: T): Boolean fun difference(other: ReadonlySetLike<T>): JsSet<T> override fun entries(): JsIterator<JsTuple2<T, T>> override fun forEach(action: (value: T) -> Unit) override fun has(key: T): Boolean fun intersection(other: ReadonlySetLike<T>): JsSet<T> fun isDisjointFrom(other: ReadonlySetLike<T>): Boolean fun isSubsetOf(other: ReadonlySetLike<T>): Boolean fun isSupersetOf(other: ReadonlySetLike<T>): Boolean override fun keys(): JsIterator<T> fun symmetricDifference(other: ReadonlySetLike<T>): JsSet<T> fun union(other: ReadonlySetLike<T>): JsSet<T> override fun values(): JsIterator<T> }
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
1,055
kotlin-wrappers
Apache License 2.0
app/location/src/main/java/net/c7j/wna/huawei/LocationMainActivity.kt
careful7j
604,723,393
false
{"Kotlin": 271725}
package net.c7j.wna.huawei import android.os.Bundle import com.google.android.material.button.MaterialButton import net.c7j.wna.huawei.location.R class LocationMainActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.locationmain_activity) findViewById<MaterialButton>(R.id.btnSimpleLocation).setOnClickListener { navigate("net.c7j.wna.huawei.SimpleLocationActivity") } findViewById<MaterialButton>(R.id.btnActivityIdentification).setOnClickListener { navigate("net.c7j.wna.huawei.ActivityRecognitionAndPeriodicLocationActivity") } findViewById<MaterialButton>(R.id.btnGeofence).setOnClickListener { navigate("net.c7j.wna.huawei.GeofenceActivity") } } }
0
Kotlin
1
5
e563f3eb0e7c21088c7139177f9f4ca786f43232
855
HMSExamples
Apache License 2.0
app/src/main/java/com/onurcankoroglu/weatherforecastapp/network/MetaWeatherService.kt
korogluOnurcan
355,887,041
false
null
package com.onurcankoroglu.weatherforecastapp.network import com.onurcankoroglu.weatherforecastapp.data.model.Location import com.onurcankoroglu.weatherforecastapp.data.model.LocationInfo import com.onurcankoroglu.weatherforecastapp.data.model.Weather import com.onurcankoroglu.weatherforecastapp.BuildConfig import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface MetaWeatherService { companion object { fun getImageUrl(abbr: String): String { return BuildConfig.DOMAIN + "static/img/weather/png/" + abbr + ".png" } } @GET("location/search") fun searchLocation(@Query("lattlong") lattLong: String): Call<List<Location>> @GET("location/{woeid}") fun getLocationInfo(@Path("woeid") woeid: Int): Call<LocationInfo> }
0
Kotlin
0
0
75c6b198c25ea63b733e79ea0f64eab480dfd3f1
908
WeatherForecastApp
Apache License 2.0
analysis/analysis-api/testData/annotations/annotationsOnTypes/annotaionWithLiteralArgumentOnType.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
@Target(AnnotationTarget.TYPE) annotation class TypeAnnotation(val value: Int) fun x(): @TypeAnnotation(1 + 1) Li<caret>st<Int> { TODO() }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
143
kotlin
Apache License 2.0
android-core/src/main/kotlin/org/mint/android/oracle/accessibility/TextSizeCheckOracle.kt
ing-bank
620,378,707
false
{"Kotlin": 375172, "XSLT": 61849}
package com.ing.mint.android.oracle.accessibility import com.ing.mint.lib.OracleCategory class TextSizeCheckOracle : AccessibilityOracle() { override val checkType = "TextSizeCheck" override val name = "text-size-check-oracle" override val version = "1.0.0" override val description = "Looks for text that may have visibility problems " + "related to text scaling." override val categories = setOf( OracleCategory.A11Y, ) }
0
Kotlin
2
4
abf96d311b3ebb1bba2a331a353126c653225be9
466
mint
MIT License
app/src/main/java/com/makalaster/ethereal_dialpad/dsp/Flange.kt
Makalaster
235,464,029
false
null
package com.makalaster.ethereal_dialpad.dsp class Flange(length: Int, freq: Float): UGen() { private var line: FloatArray = FloatArray(length) private var phase = 0f private var cyclesPerSample = freq / SAMPLE_RATE private var pointer = 0 override fun render(buffer: FloatArray): Boolean { renderKids(buffer) var localPhase = phase var localPointer = pointer val length = line.size for (i in 0 until CHUNK_SIZE) { line[localPointer] = buffer[i] val samplePointer = (localPointer + length * (1.0f - localPhase * (1.0f - localPhase))).toInt() % length buffer[i] = 0.5f * buffer[i] - 0.5f * line[samplePointer] localPointer = (localPointer + 1) % length localPhase += cyclesPerSample localPhase -= localPhase.toInt() } pointer = localPointer phase = localPhase return true } }
1
null
1
6
ce10e8be5710025a2e183a1136d29c8594157ad4
959
ethereal-dialpad
MIT License
app/src/main/java/org/stepik/android/domain/course_list/interactor/RemindAppNotificationInteractor.kt
StepicOrg
42,045,161
false
null
package org.stepik.android.domain.course_list.interactor import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.user_courses.repository.UserCoursesRepository import javax.inject.Inject class RemindAppNotificationInteractor @Inject constructor( private val sharedPreferenceHelper: SharedPreferenceHelper, private val userCoursesRepository: UserCoursesRepository ) { fun isNotificationShown(): Boolean { val isFirstDayNotificationShown = sharedPreferenceHelper.isNotificationWasShown(SharedPreferenceHelper.NotificationDay.DAY_ONE) val isSevenDayNotificationShown = sharedPreferenceHelper.isNotificationWasShown(SharedPreferenceHelper.NotificationDay.DAY_SEVEN) // already shown. // do not show again return isFirstDayNotificationShown && isSevenDayNotificationShown } fun hasUserInteractedWithApp(): Boolean = sharedPreferenceHelper.authResponseFromStore == null || sharedPreferenceHelper.isStreakNotificationEnabled || hasEnrolledCourses() || sharedPreferenceHelper.anyStepIsSolved() private fun hasEnrolledCourses(): Boolean = userCoursesRepository .getUserCourses(sourceType = DataSourceType.CACHE) .blockingGet() .isNotEmpty() }
13
null
54
189
dd12cb96811a6fc2a7addcd969381570e335aca7
1,365
stepik-android
Apache License 2.0
app/src/main/java/org/japancv/multiplescreens/SecondActivity.kt
japancv
519,971,034
false
null
package org.japancv.multiplescreens import android.content.Context import android.content.Intent import android.hardware.display.DisplayManager import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import org.japancv.multiplescreens.databinding.ActivitySecondBinding class SecondActivity : AppCompatActivity() { private lateinit var binding: ActivitySecondBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySecondBinding.inflate(layoutInflater) setContentView(binding.root) val displayManager = getSystemService(Context.DISPLAY_SERVICE) as DisplayManager val displays = displayManager.displays if (displays.size > 1) { logDisplayInfo(TAG, displays[1]) } // Show the Intent data when this activity is initiated showIntentData(intent) } /** * Since SecondActivity's launch mode should be SingleTask or SingleInstance, once this Activity has been initiated * the Intent would be pass through this callback. */ override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) showIntentData(intent) } private fun showIntentData(intent: Intent?) { intent?.let { binding.textviewCounter.text = it.getIntExtra(EXTRA_COUNTER, -1).toString() } } companion object { private const val TAG = "SecondActivity" private const val EXTRA_COUNTER = "EXTRA_COUNTER" } }
0
Kotlin
0
0
41600b564ad71427b413715ba7d744a4934a3fea
1,545
android-multiple-screens-sample
MIT License
src/main/kotlin/org/arend/actions/SearchArendFilesContributor.kt
JetBrains
96,068,447
false
null
package org.arend.actions import com.intellij.ide.actions.searcheverywhere.AbstractGotoSEContributor import com.intellij.ide.actions.searcheverywhere.FileSearchEverywhereContributor import com.intellij.ide.actions.searcheverywhere.SearchEverywhereContributor import com.intellij.ide.actions.searcheverywhere.SearchEverywhereContributorFactory import com.intellij.ide.util.gotoByName.FileTypeRef import com.intellij.ide.util.gotoByName.FilteringGotoByModel import com.intellij.ide.util.gotoByName.GotoFileModel import com.intellij.navigation.NavigationItem import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import org.arend.ArendFileType import org.arend.util.arendModules import java.util.Collections.singletonList class SearchArendFilesContributor(val event: AnActionEvent) : AbstractGotoSEContributor(event) { override fun getGroupName(): String = "Arend files" override fun getSortWeight(): Int = 201 override fun isShownInSeparateTab(): Boolean { return event.project?.arendModules?.isNotEmpty() ?: false } override fun createModel(project: Project): FilteringGotoByModel<*> { val model = object : GotoFileModel(project) { override fun acceptItem(item: NavigationItem?): Boolean { if (item !is PsiFile) return false return super.acceptItem(item) } } model.setFilterItems(singletonList(FileTypeRef.forFileType(ArendFileType))) return model } override fun getActions(onChanged: Runnable): MutableList<AnAction> { return singletonList(doGetActions("Lol", FileSearchEverywhereContributor.createFileTypeFilter(this.myProject), onChanged).first()) } } class ArendSECFactory<T> : SearchEverywhereContributorFactory<Any> { override fun createContributor(initEvent: AnActionEvent): SearchEverywhereContributor<Any> { return SearchArendFilesContributor(initEvent) } }
68
null
13
90
bf797990c98da41f192e7e1d9a35694b796676ea
2,051
intellij-arend
Apache License 2.0
src/test/kotlin/com/contentful/java/cma/WebhookTests.kt
contentful
26,211,601
false
{"Batchfile": 1, "XML": 2, "Shell": 90, "Maven POM": 1, "Markdown": 2, "YAML": 4, "Ignore List": 1, "Text": 1, "INI": 1, "JSON": 155, "Kotlin": 48, "Java": 139, "CODEOWNERS": 1}
/* * Copyright (C) 2019 Contentful GmbH * * 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.contentful.java.cma import com.contentful.java.cma.lib.TestCallback import com.contentful.java.cma.lib.TestUtils import com.contentful.java.cma.model.* import com.google.gson.Gson import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.junit.After import org.junit.Before import java.io.IOException import java.util.logging.LogManager import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue import org.skyscreamer.jsonassert.JSONAssert.assertEquals as assertEqualJsons import org.junit.Test as test class WebhookTests { var server: MockWebServer? = null var client: CMAClient? = null var gson: Gson? = null @Before fun setUp() { LogManager.getLogManager().reset() // MockWebServer server = MockWebServer() server!!.start() // Client client = CMAClient.Builder() .setAccessToken("token") .setCoreEndpoint(server!!.url("/").toString()) .setUploadEndpoint(server!!.url("/").toString()) .setSpaceId("configuredSpaceId") .build() gson = CMAClient.createGson() } @After fun tearDown() { server!!.shutdown() } @test fun testCreate() { val requestBody = TestUtils.fileToString("webhook_create_request.json") val responseBody = TestUtils.fileToString("webhook_create.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val webhookTransformation = CMAWebhookTransformation() .setMethod("PUT") .setContentType("application/json; charset=utf-8") .setIncludeContentLength(true) .setBody("{ /payload/sys/id }: { /payload/fields/title }") val webhook = CMAWebhook() .setName("cma-created") .setUrl("https://contentful.com") .addTopic(CMAWebhookTopic.EntryAll) .addHeader("key", "value") .setBasicAuthorization("user", "password") .setTransformation(webhookTransformation) assertTestCallback(client!!.webhooks().async().create( "spaceid", webhook, TestCallback()) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("POST", recordedRequest.method) assertEquals("/spaces/spaceid/webhook_definitions", recordedRequest.path) assertEqualJsons(requestBody, recordedRequest.body.readUtf8(), false) } @test fun testCreateWithConfiguredSpaceAndEnvironment() { val responseBody = TestUtils.fileToString("webhook_create.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val webhook = CMAWebhook() .setName("cma-created") .setUrl("http://lorempixel.com/200/200/cats") .addTopic(CMAWebhookTopic.All) .addHeader("key", "value") .setBasicAuthorization("user", "password") assertTestCallback(client!!.webhooks().async().create(webhook, TestCallback()) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("POST", recordedRequest.method) assertEquals("/spaces/configuredSpaceId/webhook_definitions", recordedRequest.path) } @test fun testCreateWithId() { val requestBody = TestUtils.fileToString("webhook_create_with_id_request.json") val responseBody = TestUtils.fileToString("webhook_create_with_id_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val webhook = CMAWebhook() .setId("webhookid") .setName("cma-created") .setUrl("http://lorempixel.com/200/200/cats") .addTopic(CMAWebhookTopic.EntrySave) .addHeader("key", "value") .setBasicAuthorization("user", "password") assertTestCallback(client!!.webhooks().async().create( "spaceid", webhook, TestCallback()) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.method) assertEquals("/spaces/spaceid/webhook_definitions/webhookid", recordedRequest.path) assertEqualJsons(requestBody, recordedRequest.body.readUtf8(), true) } @test fun testDelete() { val responseBody = TestUtils.fileToString("webhook_delete.json") server!!.enqueue(MockResponse().setResponseCode(204).setBody(responseBody)) val webhook = CMAWebhook().apply { spaceId = "spaceid" id = "webhookid" } val callback: TestCallback<Int> = TestCallback(true) assertTestCallback(client!!.webhooks().async().delete( webhook, callback) as TestCallback) assertEquals(204, callback.value) // Request val recordedRequest = server!!.takeRequest() assertEquals("DELETE", recordedRequest.method) assertEquals("/spaces/spaceid/webhook_definitions/webhookid", recordedRequest.path) } @test fun testFetchAll() { val responseBody = TestUtils.fileToString("webhook_get_all.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback(client!!.webhooks().async().fetchAll( "spaceid", TestCallback()) as TestCallback)!! assertEquals(CMAType.Array, result.system.type) assertEquals(4, result.total) val items = result.items assertEquals(4, items.size) assertEquals("cma-created", items[0].name) assertEquals("https://contentful.com", items[0].url) assertEquals(1, items[0].topics.size) assertEquals(CMAWebhookTopic.EntryAll, items[0].topics[0]) assertEquals(1, items[0].headers.size) assertEquals("user", items[0].user) val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals("/spaces/spaceid/webhook_definitions", request.path) } @test fun testFetchAllWithConfiguredSpaceAndEnvironment() { val responseBody = TestUtils.fileToString("webhook_get_all.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) assertTestCallback(client!!.webhooks().async().fetchAll(TestCallback()) as TestCallback)!! val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals("/spaces/configuredSpaceId/webhook_definitions", request.path) } @test fun testFetchAllWithQuery() { val responseBody = TestUtils.fileToString("webhook_get_all.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) assertTestCallback(client!!.webhooks().async().fetchAll( "spaceid", hashMapOf("limit" to "4"), TestCallback()) as TestCallback)!! val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals("/spaces/spaceid/webhook_definitions?limit=4", request.path) } @test fun testFetchAllWithQueryWithConfiguredSpaceAndEnvironment() { val responseBody = TestUtils.fileToString("webhook_get_all.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) assertTestCallback(client!!.webhooks().async().fetchAll( hashMapOf("limit" to "4"), TestCallback()) as TestCallback)!! val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals("/spaces/configuredSpaceId/webhook_definitions?limit=4", request.path) } @test fun testFetchWithId() { val responseBody = TestUtils.fileToString("webhook_get_one.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val result = assertTestCallback(client!!.webhooks().async().fetchOne( "spaceid", "webhookid", TestCallback()) as TestCallback) // Request val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals("/spaces/spaceid/webhook_definitions/webhookid", request.path) assertEquals(CMAType.WebhookDefinition, result!!.system.type) assertNotNull(result) assertEquals("cma-created", result.name) assertEquals("https://contentful.com", result.url) assertEquals(1, result.topics.size) assertEquals(1, result.headers.size) assertEquals("user", result.user) } @test fun testFetchWithIdWithConfiguredSpaceAndEnvironment() { val responseBody = TestUtils.fileToString("webhook_get_one.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) assertTestCallback(client!!.webhooks().async().fetchOne("webhookid", TestCallback()) as TestCallback) // Request val request = server!!.takeRequest() assertEquals("GET", request.method) assertEquals("/spaces/configuredSpaceId/webhook_definitions/webhookid", request.path) } @test fun testUpdate() { val requestBody = TestUtils.fileToString("webhook_update_request.json") val responseBody = TestUtils.fileToString("webhook_update.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val webhookTransformation = CMAWebhookTransformation() .setBody("{ /payload/sys/id }: { /payload/fields/new }") assertTestCallback(client!!.webhooks().async().update(CMAWebhook() .setId("webhookid") .setSpaceId("spaceid") .setVersion(3) .addHeader("my_new_header_name", "header_value") .setTransformation(webhookTransformation) , TestCallback(true)) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("PUT", recordedRequest.method) assertEquals("/spaces/spaceid/webhook_definitions/webhookid", recordedRequest.path) assertEquals(recordedRequest.getHeader("X-Contentful-Version"), "3") assertEqualJsons(requestBody, recordedRequest.body.readUtf8(), false) } @test(expected = RuntimeException::class) fun testRetainsSysOnNetworkError() { val badClient = CMAClient.Builder() .setAccessToken("accesstoken") .setCoreCallFactory { throw IOException(it.url().toString(), IOException()) } .build() val webhook = CMAWebhook().setVersion(31337) try { badClient.webhooks().create("spaceid", webhook) } catch (e: RuntimeException) { assertEquals(31337, webhook.version) throw e } } @test fun testCallsOverview() { val responseBody = TestUtils.fileToString("webhook_calls_overview_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) assertTestCallback(client!!.webhooks().async().calls( CMAWebhook().setSpaceId("spaceid").setId("webhookid"), TestCallback(true)) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("GET", recordedRequest.method) assertEquals("/spaces/spaceid/webhooks/webhookid/calls", recordedRequest.path) } @test fun testCallDetails() { val responseBody = TestUtils.fileToString("webhook_calls_detail_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) val call: CMAWebhookCall = CMAWebhookCall().setSpaceId("spaceid").setId("callid") call.system.setCreatedBy(CMALink(CMAType.Webhook).setId("webhookid")) assertTestCallback(client!!.webhooks().async().callDetails( call, TestCallback(true)) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("GET", recordedRequest.method) assertEquals("/spaces/spaceid/webhooks/webhookid/calls/callid", recordedRequest.path) } @test fun testCallHealth() { val responseBody = TestUtils.fileToString("webhook_health_response.json") server!!.enqueue(MockResponse().setResponseCode(200).setBody(responseBody)) assertTestCallback(client!!.webhooks().async().health( CMAWebhook().setSpaceId("spaceid").setId("webhookid"), TestCallback(true)) as TestCallback) // Request val recordedRequest = server!!.takeRequest() assertEquals("GET", recordedRequest.method) assertEquals("/spaces/spaceid/webhooks/webhookid/health", recordedRequest.path) } @test fun testWebhookToString() { val webhook = CMAWebhook() .setId("helpText") .setName("Help text") assertTrue(webhook.toString().contains("id = helpText")) } @test fun testWebhookTransformationToString() { val webhookTransformation = CMAWebhookTransformation() .setMethod("PUT") .setContentType("application/json; charset=utf-8") assertTrue(webhookTransformation.toString().contains("method=PUT")) } @test fun testWebhookTransformation() { val webhookTransformation = CMAWebhookTransformation() .setMethod("PUT") .setContentType("application/json; charset=utf-8") .setIncludeContentLength(true) .setBody("{ /payload/test }: { /payload/test }") assertEquals("PUT", webhookTransformation.getMethod()) assertEquals("application/json; charset=utf-8", webhookTransformation.getContentType()) assertEquals(true, webhookTransformation.getIncludeContentLength()) assertEquals("{ /payload/test }: { /payload/test }", webhookTransformation.getBody()) } }
5
Java
24
26
84d4a9ff9dafa99eba345eaa7988375e98f625e8
14,819
contentful-management.java
Apache License 2.0
src/main/kotlin/team/yi/rsql/querydsl/util/DateUtil.kt
ymind
268,996,653
false
null
package team.yi.rsql.querydsl.util import java.text.SimpleDateFormat import java.time.* import java.time.format.DateTimeFormatter import java.util.* @Suppress("MemberVisibilityCanBePrivate", "SpellCheckingInspection") object DateUtil { private val regexOptions = setOf(RegexOption.IGNORE_CASE) val DATE_FORMATS: Map<String, Regex> = mapOf( "dd MMMM yyyy HH:mm:ss" to Regex("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}\\s\\d{1,2}:\\d{1,2}:\\d{1,2}$", regexOptions), "dd MMM yyyy HH:mm:ss" to Regex("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}\\s\\d{1,2}:\\d{1,2}:\\d{1,2}$", regexOptions), "yyyy/MM/dd HH:mm:ss" to Regex("^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{1,2}:\\d{1,2}$", regexOptions), "MM/dd/yyyy HH:mm:ss" to Regex("^\\d{1,2}/\\d{1,2}/\\d{4}\\s\\d{1,2}:\\d{1,2}:\\d{1,2}$", regexOptions), "yyyy-MM-dd'T'HH:mm:ss" to Regex("^\\d{4}-\\d{1,2}-\\d{1,2}'?T'?\\d{1,2}:\\d{1,2}:\\d{1,2}$", regexOptions), "yyyy-MM-dd'T'HH:mm:ss'Z'" to Regex("^\\d{4}-\\d{1,2}-\\d{1,2}'?T'?\\d{1,2}:\\d{1,2}:\\d{1,2}'?Z'?$", regexOptions), "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" to Regex("^\\d{4}-\\d{1,2}-\\d{1,2}'?T'?\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{3}'?Z'?$", regexOptions), "yyyy-MM-dd'T'HH:mm:ss.SSS" to Regex("^\\d{4}-\\d{1,2}-\\d{1,2}'?T'?\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{3}$", regexOptions), "yyyy-MM-dd HH:mm:ss.SSS" to Regex("^\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{3}$", regexOptions), "yyyy-MM-dd HH:mm:ss" to Regex("^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}:\\d{1,2}$", regexOptions), "dd-MM-yyyy HH:mm:ss" to Regex("^\\d{1,2}-\\d{1,2}-\\d{4}\\s\\d{1,2}:\\d{1,2}:\\d{1,2}$", regexOptions), "yyyyMMdd HHmmss" to Regex("^\\d{8}\\s\\d{6}$", regexOptions), "dd MMMM yyyy HH:mm" to Regex("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}\\s\\d{1,2}:\\d{1,2}$", regexOptions), "dd MMM yyyy HH:mm" to Regex("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}\\s\\d{1,2}:\\d{1,2}$", regexOptions), "yyyy/MM/dd HH:mm" to Regex("^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{1,2}$", regexOptions), "MM/dd/yyyy HH:mm" to Regex("^\\d{1,2}/\\d{1,2}/\\d{4}\\s\\d{1,2}:\\d{1,2}$", regexOptions), "yyyy-MM-dd HH:mm" to Regex("^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}$", regexOptions), "yyyy.MM.dd HH:mm" to Regex("^\\d{4}.\\d{1,2}.\\d{1,2}\\s\\d{1,2}:\\d{1,2}$", regexOptions), "dd-MM-yyyy HH:mm" to Regex("^\\d{1,2}-\\d{1,2}-\\d{4}\\s\\d{1,2}:\\d{1,2}$", regexOptions), "yyyyMMdd HHmm" to Regex("^\\d{8}\\s\\d{4}$", regexOptions), "dd MMMM yyyy" to Regex("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}$", regexOptions), "dd MMM yyyy" to Regex("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}$", regexOptions), "yyyy/MM/dd" to Regex("^\\d{4}/\\d{1,2}/\\d{1,2}$", regexOptions), "MM/dd/yyyy" to Regex("^\\d{1,2}/\\d{1,2}/\\d{4}$", regexOptions), "yyyy.MM.dd" to Regex("^\\d{4}\\.\\d{1,2}\\.\\d{1,2}$", regexOptions), "yyyy-MM-dd" to Regex("^\\d{4}-\\d{1,2}-\\d{1,2}$", regexOptions), "dd.MM.yyyy" to Regex("^\\d{1,2}\\.\\d{1,2}\\.\\d{4}$", regexOptions), "dd-MM-yyyy" to Regex("^\\d{1,2}-\\d{1,2}-\\d{4}$", regexOptions), "yyyy" to Regex("^\\d{4}$", regexOptions), "yy-MM-dd HH:mm" to Regex("^\\d{2}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}$", regexOptions), "yy.MM.dd" to Regex("^\\d{2}\\.\\d{1,2}\\.\\d{1,2}$", regexOptions), "yy-MM-dd" to Regex("^\\d{2}-\\d{1,2}-\\d{1,2}$", regexOptions), "yy-MM" to Regex("^\\d{2}-\\d{1,2}\$", regexOptions), "yyyy.MM" to Regex("^\\d{4}\\.\\d{1,2}\$", regexOptions), "yyyy-MM" to Regex("^\\d{4}-\\d{1,2}\$", regexOptions), "MM.yyyy" to Regex("^\\d{1,2}\\.\\d{4}$", regexOptions), "MM-yyyy" to Regex("^\\d{1,2}-\\d{4}$", regexOptions), "HH:mm:ss.SSS'Z'" to Regex("^\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{3}'?Z'?$", regexOptions), "HH:mm:ss'Z'" to Regex("^\\d{1,2}:\\d{1,2}:\\d{1,2}'?Z'?$", regexOptions), "HH:mm:ss.SSS" to Regex("^\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{3}$", regexOptions), "HH:mm:ss" to Regex("^\\d{1,2}:\\d{1,2}:\\d{1,2}$", regexOptions), "HH:mm" to Regex("^\\d{1,2}:\\d{1,2}$", regexOptions), ) val formatters = listOf( DateTimeFormatter.ISO_LOCAL_DATE_TIME, DateTimeFormatter.ISO_DATE_TIME, DateTimeFormatter.ISO_INSTANT, DateTimeFormatter.ISO_OFFSET_DATE_TIME, DateTimeFormatter.ISO_ZONED_DATE_TIME, DateTimeFormatter.ISO_LOCAL_DATE, DateTimeFormatter.ISO_DATE, DateTimeFormatter.ISO_OFFSET_DATE, DateTimeFormatter.ISO_LOCAL_TIME, DateTimeFormatter.ISO_TIME, DateTimeFormatter.ISO_OFFSET_TIME, DateTimeFormatter.ISO_ORDINAL_DATE, DateTimeFormatter.ISO_WEEK_DATE, DateTimeFormatter.BASIC_ISO_DATE, DateTimeFormatter.RFC_1123_DATE_TIME, ) fun parse(dateString: String): Date? { return parse(dateString, determineDateFormat(dateString)) } @Suppress("ReturnCount") fun parse(dateString: String, dateFormat: String?): Date? { val dateStr = dateString.ifBlank { return null }.trim() try { val offsetDateTime = parseOffsetDateTime(dateStr) if (offsetDateTime == null) { if (dateFormat.isNullOrEmpty()) return null val format = dateFormat.ifBlank { return null }.trim() val sdf = SimpleDateFormat(format) sdf.isLenient = false if (dateStr.endsWith('Z')) { sdf.timeZone = TimeZone.getTimeZone("+00:00:00") } return sdf.parse(dateStr) } return Date.from(offsetDateTime.toInstant()) } catch (_: Exception) { val offsetDateTime = parseOffsetDateTime(dateStr) ?: return null return Date.from(offsetDateTime.toInstant()) } } fun determineDateFormat(dateString: String): String? { return DATE_FORMATS.asSequence() .filter { it.value.matches(dateString) } .map { it.key } .firstOrNull() } fun parseOffsetDateTime(dateStr: String): OffsetDateTime? { for (formatter in formatters) { try { return OffsetDateTime.parse(dateStr, formatter) } catch (_: Exception) { continue } } return null } }
0
Kotlin
0
6
7a5c81e64bb2f3b53e012c899a2d7f6d9def6a2d
6,425
rsql-querydsl
MIT License
Chapter09/MarvelGallery_Source-code/app/src/main/java/com/sample/marvelgallery/view/common/BaseActivityWithPresenter.kt
PacktPublishing
101,964,449
false
null
package com.sample.marvelgallery.view.common import android.support.v7.app.AppCompatActivity import com.sample.marvelgallery.presenter.Presenter abstract class BaseActivityWithPresenter : BaseActivity() { abstract val presenter: Presenter override fun onDestroy() { super.onDestroy() presenter.onViewDestroyed() } }
1
null
30
53
b079ae28083fc68555f05af0f83dca6414ceec3f
348
Android-Development-with-Kotlin
MIT License
app/src/main/java/com/szoldapps/bitcoin/ui/main/MainViewModel.kt
soldmachine
189,402,408
false
null
package com.szoldapps.bitcoin.ui.main import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.szoldapps.bitcoin.repository.BlockchainRepository import com.szoldapps.bitcoin.repository.model.MarketPriceData import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.addTo import io.reactivex.rxkotlin.subscribeBy import io.reactivex.schedulers.Schedulers import timber.log.Timber /** * Main view model, used by [MainActivity] */ class MainViewModel( private val blockchainRepository: BlockchainRepository ) : ViewModel() { private val _state = MutableLiveData<MainActivityState>() val state: LiveData<MainActivityState> = _state private val _marketPriceData = MutableLiveData<MarketPriceData>() val marketPriceData: LiveData<MarketPriceData> = _marketPriceData private val disposables = CompositeDisposable() /** * Loads market price data and updates [state] accordingly */ fun loadMarketPriceData() { _state.postValue(MainActivityState.LOADING) blockchainRepository.getMarketPriceData() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeBy( onSuccess = { marketPriceDataTemp -> _marketPriceData.postValue(marketPriceDataTemp) _state.postValue(MainActivityState.SHOW_CHART) }, onError = { throwable -> Timber.e(throwable, "Failed to retrieve the market price data") _state.postValue(MainActivityState.ERROR) } ) .addTo(disposables) } override fun onCleared() { super.onCleared() disposables.clear() } }
0
Kotlin
0
0
0eb2419406ea1e6c873062550becc9c83d764111
1,881
BitcoinCodingChallenge
MIT License
app/src/main/java/com/jio/jetpack/compose/dashboard/widgets/DashboardNavigationDrawer.kt
SanjuChauhan
801,980,601
false
{"Kotlin": 134752}
package com.jio.jetpack.compose.dashboard.widgets import android.util.Log import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Divider import androidx.compose.material3.DrawerValue import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ModalNavigationDrawer import androidx.compose.material3.Text import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.jio.jetpack.compose.R import com.jio.jetpack.compose.data.DataProvider import com.jio.jetpack.compose.ui.theme.* @OptIn(ExperimentalMaterial3Api::class) @Composable fun DashboardNavigationDrawer() { val drawerState = rememberDrawerState(DrawerValue.Open) ModalNavigationDrawer( drawerContent = { DrawerContentComponent() }, drawerState = drawerState, gesturesEnabled = drawerState.isOpen, ) {} } @Composable fun DrawerContentComponent(closeDrawer: () -> Unit = {}) { LazyColumn( modifier = Modifier .requiredWidth(300.dp) .fillMaxHeight() .background(primaryColorLight), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.Start, content = { item { Column { Image( painterResource(id = R.drawable.account_profile_pic), contentDescription = "profile icon", modifier = Modifier .size(80.dp) .padding(top = 20.dp) .align(Alignment.CenterHorizontally) ) Text( text = "Phone Number", fontSize = 12.sp, color = Color.White, fontWeight = FontWeight.Bold, modifier = Modifier .wrapContentSize() .padding(top = 10.dp) .align(Alignment.CenterHorizontally) ) Box( modifier = Modifier .fillMaxWidth() .padding(top = 10.dp, bottom = 10.dp) ) { Divider( color = dividerOne, modifier = Modifier .height(1.dp) .fillMaxWidth() ) } } } items(DataProvider.getInstance().getDrawerList()) { Row( modifier = Modifier .fillMaxWidth() .padding(start = 10.dp, top = 10.dp, bottom = 10.dp) .clickable { closeDrawer() Log.e("DrawerContentComponent", "Drawer item click= ${it.itemName}") }, verticalAlignment = Alignment.CenterVertically ) { Image( painterResource(id = it.icon), contentDescription = "nav icon icon", modifier = Modifier .size(35.dp) ) Text( text = it.itemName, fontSize = 14.sp, color = Color.White, fontWeight = FontWeight.Bold, modifier = Modifier .wrapContentSize() .align(Alignment.CenterVertically) .padding(start = 20.dp) ) } } }) // Column( // modifier = Modifier // .requiredWidth(300.dp) // .fillMaxHeight() // .background(primaryColorLight) // ) { // } } @Preview @Composable fun DashboardNavigationDrawerPreview() { Column { DashboardNavigationDrawer() } }
0
Kotlin
0
0
6164813e7a3f3a2398ff48f1c679b388d267060a
5,284
JetpackComposeUI
Apache License 2.0
core-sdk/src/main/java/com/frogobox/coresdk/source/FrogoApiClient.kt
frogobox
463,917,159
false
null
package com.frogobox.coresdk.source import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit /** * Created by faisalamir on 26/07/21 * FrogoSDK * ----------------------------------------- * Name : <NAME> * E-mail : <EMAIL> * Github : github.com/amirisback * ----------------------------------------- * Copyright (C) 2021 FrogoBox Inc. * All rights reserved * */ object FrogoApiClient { private val httpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } fun client(timeout: Long? = 30L): OkHttpClient { return OkHttpClient.Builder() .readTimeout(timeout ?: 30L, TimeUnit.SECONDS) .connectTimeout(timeout ?: 30L, TimeUnit.SECONDS) .build() } fun clientWithInterceptor(timeout: Long? = 30L): OkHttpClient { return OkHttpClient.Builder() .readTimeout(timeout ?: 30L, TimeUnit.SECONDS) .connectTimeout(timeout ?: 30L, TimeUnit.SECONDS) .addInterceptor(httpLoggingInterceptor) .build() } fun clientWithInterceptor(chuckInterceptor: Interceptor): OkHttpClient { return OkHttpClient.Builder() .readTimeout(30, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS) .addInterceptor(httpLoggingInterceptor) .addInterceptor(chuckInterceptor) .build() } // --------------------------------------------------------------------------------------------- inline fun <reified T> create(url: String, timeout: Long? = 30L): T { return Retrofit.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) .client(client(timeout)) .build().create(T::class.java) } inline fun <reified T> create(url: String, isDebug: Boolean, timeout: Long? = 30L): T { return if (isDebug) { Retrofit.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) .client(clientWithInterceptor(timeout)) .build().create(T::class.java) } else { Retrofit.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) .client(client(timeout)) .build().create(T::class.java) } } inline fun <reified T> create( url: String, isDebug: Boolean, chuckInterceptor: Interceptor, timeout: Long? = 30L, ): T { return if (isDebug) { Retrofit.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) .client(clientWithInterceptor(chuckInterceptor)) .build().create(T::class.java) } else { Retrofit.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) .client(client(timeout)) .build().create(T::class.java) } } }
0
null
5
18
51696259b36210af8d251432fb5339922efff795
3,698
frogo-sdk
Apache License 2.0
app/src/main/java/ru/ifmo/rain/listvin/dsl/DSL.kt
listvin
130,500,124
true
{"Kotlin": 70854, "JavaScript": 6295, "HTML": 1602, "CSS": 659}
package ru.ifmo.rain.listvin.dsl import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.graphics.drawable.Drawable import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.text.InputType import android.util.TypedValue import android.view.Menu import android.view.MenuItem import android.view.View import android.webkit.WebView import android.widget.* import android.widget.LinearLayout.HORIZONTAL import android.widget.LinearLayout.LayoutParams.WRAP_CONTENT import android.widget.LinearLayout.LayoutParams.MATCH_PARENT import android.widget.LinearLayout.LayoutParams import org.w3c.dom.Text @DslMarker annotation class UIConstructor @UIConstructor fun AppCompatActivity.verticalLayout(init: LinearLayout.() -> Unit): LinearLayout { val layout = LinearLayout(this) layout.layoutParams = LayoutParams(MATCH_PARENT, MATCH_PARENT) layout.orientation = LinearLayout.VERTICAL layout.init() this.setContentView(layout) return layout } //class ConstraintLayoutBuilder(context: Context): ConstraintLayout(context) { private fun <T: View> LinearLayout.element(element: T, init: T.() -> Unit): T { this.addView(element, WRAP_CONTENT, WRAP_CONTENT) element.init() return element } val DONT_CHANGE = -1830472708 @UIConstructor fun <T:View> T.lparams( width: Int = DONT_CHANGE, height: Int = DONT_CHANGE, leftMargin: Int = DONT_CHANGE, topMargin: Int = DONT_CHANGE, rightMargin: Int = DONT_CHANGE, bottomMargin: Int = DONT_CHANGE, gravity: Int = DONT_CHANGE, weight: Float = DONT_CHANGE.toFloat(), focusable: Boolean = isFocusableInTouchMode, visibility: Int = this.visibility ): T { val lp = LayoutParams( if (width == DONT_CHANGE) layoutParams.width else width, if (height == DONT_CHANGE) layoutParams.height else height ) lp.setMargins( this.context.dp(if (leftMargin == DONT_CHANGE) lp.leftMargin else leftMargin), this.context.dp(if (topMargin == DONT_CHANGE) lp.leftMargin else topMargin), this.context.dp(if (rightMargin == DONT_CHANGE) lp.leftMargin else rightMargin), this.context.dp(if (bottomMargin == DONT_CHANGE) lp.leftMargin else bottomMargin)) if (weight != DONT_CHANGE.toFloat()) lp.weight = weight if (gravity != DONT_CHANGE) lp.gravity = gravity layoutParams = lp isFocusableInTouchMode = focusable this.visibility = visibility return this } @UIConstructor fun LinearLayout.button(init: Button.() -> Unit): Button = element(Button(this.context), init) @UIConstructor fun LinearLayout.imageButton(init: ImageButton.() -> Unit): ImageButton = element(ImageButton(this.context), init) @UIConstructor fun Button.onClick(listener: () -> Unit): Button { setOnClickListener { listener() } return this } @UIConstructor fun LinearLayout.textView(init: TextView.() -> Unit): TextView = element(TextView(this.context), init) @UIConstructor fun LinearLayout.editNumber(ems: Int, init: EditText.() -> Unit): EditText{ val editText = element(EditText(this.context), init) editText.inputType = InputType.TYPE_CLASS_NUMBER editText.setEms(ems) return editText } @UIConstructor fun EditText.onFocusChange(listener: (Boolean) -> Unit): EditText { onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus -> listener(hasFocus) } return this } @UIConstructor fun LinearLayout.spinner(init: Spinner.() -> Unit): Spinner = element(Spinner(this.context), init) @UIConstructor fun LinearLayout.space(init: Space.() -> Unit): Space = element(Space(this.context), init) @UIConstructor fun Spinner.onItemSelected(listener: (String) -> Unit): Spinner { onItemSelectedListener = object : AdapterView.OnItemSelectedListener{ override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { listener(parent!!.getItemAtPosition(position) as String) } override fun onNothingSelected(parent: AdapterView<*>?) { throw IllegalStateException() } } return this } @UIConstructor fun LinearLayout.webView(init: WebView.() -> Unit): WebView = element(WebView(this.context), init) @UIConstructor fun LinearLayout.horizontalLayout(init: LinearLayout.() -> Unit): LinearLayout{ val layout = element(LinearLayout(this.context), init) layout.orientation = HORIZONTAL layout.lparams(width = MATCH_PARENT) return layout } @UIConstructor fun Menu.items(init: Menu.() -> Unit): Unit { this.init() } @UIConstructor fun Menu.menuItem(title: String, init: MenuItem.() -> Unit): MenuItem { val item = this.add(title) item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) item.init() return item } @UIConstructor fun MenuItem.imageView(verticalPad: Int, context: Context, drawable: Drawable): ImageView { val iv = ImageView(context) iv.setImageDrawable(drawable) val icon = context.dp(26) val horizontalPad = context.dp(8) iv.lparams( width = 2*horizontalPad + icon, height = 2*verticalPad + icon ) iv.setPadding(horizontalPad, verticalPad, horizontalPad, verticalPad) val outValue = TypedValue() context.theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, outValue, true) iv.setBackgroundResource(outValue.resourceId) actionView = iv return iv } @UIConstructor fun <T:View> T.onClick(listener: T.() -> Unit): T { setOnClickListener { v -> @Suppress("UNCHECKED_CAST") (v as T).listener() } return this } @UIConstructor fun Context.dp(dps: Int): Int { return (dps * resources.displayMetrics.density + 0.5f).toInt() } @UIConstructor fun AppCompatActivity.alertDialog(init: AlertDialog.Builder.() -> Unit): AlertDialog.Builder{ val aldiag = AlertDialog.Builder(this) aldiag.init() return aldiag } @UIConstructor fun AlertDialog.Builder.linearLayout(init: LinearLayout.() -> Unit): LinearLayout { val ll = LinearLayout(this.context) this.setView(ll) ll.init() return ll } //@UIConstructor //fun FrameLayout.textView(init: TextView.() -> Unit): TextView { // val tv = TextView(this.context) // this.addView(tv) // tv.init() // return tv //}
0
Kotlin
0
0
2e12c3016d33500557b0fe69fcc143b5403d3228
6,386
ctddev-kotlin-demo-2017
MIT License
product/web3modal/src/main/kotlin/com/walletconnect/web3/modal/ui/Web3ModalView.kt
WalletConnect
435,951,419
false
{"Kotlin": 2461647, "Java": 4366, "Shell": 1892}
package com.walletconnect.web3.modal.ui import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.FrameLayout import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy import com.walletconnect.web3.modal.R import com.walletconnect.web3.modal.ui.components.internal.Web3ModalComponent class Web3ModalView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { private var shouldOpenNetwork: Boolean private var closeModal: () -> Unit = {} fun setOnCloseModal(onCloseModal: () -> Unit) { closeModal = onCloseModal } init { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.Web3ModalView, 0, 0) shouldOpenNetwork = typedArray.getBoolean(R.styleable.Web3ModalView_open_network_select, false) typedArray.recycle() context.setTheme(R.style.Web3ModalTheme) val mode = context.getThemeMode() val colors = context.getColorMap() LayoutInflater.from(context) .inflate(R.layout.view_web3modal, this, true) .findViewById<ComposeView>(R.id.root) .apply { setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) setContent { Web3ModalTheme( mode = mode, lightColors = colors.getLightModeColors(), darkColors = colors.getDarkModeColors() ) { Web3ModalComponent( shouldOpenChooseNetwork = shouldOpenNetwork, closeModal = closeModal ) } } } } }
78
Kotlin
70
197
743ff1e06def59a721a299a8e76c67e96b9441f6
1,918
WalletConnectKotlinV2
Apache License 2.0
boneslibrary/src/main/java/com/eudycontreras/boneslibrary/extensions/ViewExtensions.kt
EudyContreras
253,115,353
false
null
package com.eudycontreras.boneslibrary.extensions import android.graphics.drawable.ColorDrawable import android.graphics.drawable.GradientDrawable import android.os.Build import android.view.View import android.view.View.NO_ID import android.view.ViewGroup import androidx.core.view.* import com.eudycontreras.boneslibrary.bindings.addBoneLoader import com.eudycontreras.boneslibrary.bindings.addSkeletonLoader import com.eudycontreras.boneslibrary.bindings.getParentSkeletonDrawable import com.eudycontreras.boneslibrary.doWith import com.eudycontreras.boneslibrary.framework.bones.BoneDrawable import com.eudycontreras.boneslibrary.framework.bones.BoneProperties import com.eudycontreras.boneslibrary.framework.skeletons.SkeletonDrawable import com.eudycontreras.boneslibrary.properties.Bounds import com.eudycontreras.boneslibrary.properties.MutableColor import java.lang.ref.WeakReference /** * Copyright (C) 2019 Project X * * @Project ProjectX * @author <NAME>. * @since January 2019 */ internal val View.horizontalMargin: Float get() = (this.marginStart + this.marginEnd).toFloat() internal val View.horizontalPadding: Float get() = (this.paddingStart + this.paddingEnd).toFloat() internal val View.verticalMargin: Float get() = (this.marginTop + this.marginBottom).toFloat() internal val View.verticalPadding: Float get() = (this.paddingTop + this.paddingBottom).toFloat() internal fun View.generateId(): Int { return if (id == NO_ID) { View.generateViewId().apply { id = this } } else id } /** * Applies a skeleton drawable to this ViewGroup */ fun ViewGroup.applySkeletonDrawable(): SkeletonDrawable { return SkeletonDrawable.create(this) } /** * Applies a bone drawable to this View */ fun View.applyBoneDrawable(): BoneDrawable { return BoneDrawable.create(this) } internal fun View.compareBounds(bounds: Bounds): Int { val xDiff = left - bounds.left.toInt() val yDiff = top - bounds.top.toInt() val widthDiff = measuredWidth - bounds.width.toInt() val heightDiff = measuredHeight - bounds.height.toInt() return xDiff + yDiff + widthDiff + heightDiff } internal fun View.getBounds(): Bounds { return Bounds( x = this.left.toFloat(), y = this.top.toFloat(), width = this.measuredWidth.toFloat(), height = this.measuredHeight.toFloat() ) } internal fun View.hasValidMinBounds(boneProps: BoneProperties): Boolean { boneProps.minHeight?.let { if (measuredHeight < it) { return false } } boneProps.minWidth?.let { if (measuredWidth < it) { return false } } return true } internal fun View.hasValidBounds(): Boolean { return (measuredWidth > 0 && measuredHeight > 0) } internal fun View.hasDrawableBounds(boneProps: BoneProperties): Boolean { return minimumWidth > 0 || (measuredWidth > 0 && measuredHeight > boneProps.minThickness) } internal fun View.getBackgroundColor(): MutableColor? { if (backgroundTintList != null) { return MutableColor.fromColor(backgroundTintList?.defaultColor) } else { background?.let { if (it is ColorDrawable) { return MutableColor.fromColor(it.color) } else if (it is GradientDrawable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { if (it.color != null) { return MutableColor.fromColor(it.color?.defaultColor) } } } } } return null } @Suppress("UNCHECKED_CAST") internal inline fun <reified T> View.getProps(propId: Int): T? { val props = getTag(propId) if (props != null) { if (props is WeakReference<*>) { val reference: WeakReference<T> = props as WeakReference<T> return reference.get() } else if (props is T) { return props } } return null } internal fun View.hasProps(propId: Int): Boolean { val props = getTag(propId) if (props != null) { return true } return false } internal inline fun <reified T> View.saveProps(propId: Int, props: T, weak: Boolean = false) { if (weak) { val reference = WeakReference(props) setTag(propId, reference) } else { setTag(propId, props) } } internal fun View.clearProps(propId: Int) { setTag(propId, null) } internal tailrec fun View.findParent(criteria: ((parent: View) -> Boolean)? = null): ViewGroup? { val parent: ViewGroup? = this.parent as? ViewGroup? if (parent != null) { if (criteria?.invoke(parent) == true) { return parent } } else { return if (criteria != null) { null } else this as ViewGroup } return parent.findParent(criteria) } internal fun View.findView(criteria: (child: View) -> Boolean): View? { if (criteria(this)) { return this } if (this is ViewGroup) { for (child in children) { val match = child.findView(criteria) if (match != null) { if (criteria.invoke(match)) { return match } } } } return null } internal fun ViewGroup.descendantViews(predicate: ((view: View) -> Boolean)? = null): List<View> { val views = mutableListOf<View>() findViews(this, predicate, views) return views } internal fun ViewGroup.removeAllViews(predicate: ((view: View) -> Boolean)? = null) { val views = mutableListOf<View>() findViews(this, predicate, views) views.forEach { it.removeFromHierarchy() } } internal fun View.removeFromHierarchy() { val parent = parent as? ViewGroup? parent?.removeView(this) } private fun findViews( viewGroup: ViewGroup, predicate: ((View) -> Boolean)? = null, views: MutableList<View> ) { viewGroup.children.forEach { if (it !is ViewGroup) { if (predicate != null) { if (predicate(it)) { views.add(it) } } else { views.add(it) } } else { findViews(it, predicate, views) } } } /** * @Project Project Bones * @author <NAME> * @since Feburary 2021 * * Enables skeleton loading for this view and its descendants */ fun View.enableSkeletonLoading() = this.toggleSkeletonLoading(true) /** * @Project Project Bones * @author <NAME> * @since Feburary 2021 * * Disables skeleton loading for this view and its descendants */ fun View.disableSkeletonLoading() = this.toggleSkeletonLoading(false) /** * @Project Project Bones * @author <NAME> * @since Feburary 2021 * * Enables skeleton loading for this view and its descendants */ fun ViewGroup.enableSkeletonLoading() = this.toggleSkeletonLoading(true) /** * @Project Project Bones * @author <NAME> * @since Feburary 2021 * * Disables skeleton loading for this view and its descendants */ fun ViewGroup.disableSkeletonLoading() = this.toggleSkeletonLoading(false) /** * @Project Project Bones * @author <NAME> * @since Feburary 2021 * * Toggles skeleton loading for this view and its descendants * * @return The bone loader associated with this View or null if known is found */ fun View.toggleSkeletonLoading(enabled: Boolean): BoneDrawable? { val id = generateId() val parent = getParentSkeletonDrawable() if (parent != null) { parent.getProps().setStateOwner(id, false) parent.getProps().getBoneProps(id).apply { this.enabled = enabled } return null } else { var loaderDrawable: BoneDrawable? = null doWith(foreground) { if (it is BoneDrawable) { it.enabled = enabled loaderDrawable = it } else { loaderDrawable = addBoneLoader(enabled = enabled) } } return loaderDrawable } } /** * @Project Project Bones * @author <NAME> * @since Feburary 2021 * * Toggles skeleton loading for this view and its descendants * * @return The skeleton associated with this ViewGroup or null if known is found */ fun ViewGroup.toggleSkeletonLoading(enabled: Boolean): SkeletonDrawable? { val id = generateId() val parent = getParentSkeletonDrawable() if (parent != null) { parent.getProps().setStateOwner(id, false) parent.getProps().getBoneProps(id).apply { this.enabled = enabled } return null } else { var loaderDrawable: SkeletonDrawable? = null doWith(foreground) { if (it is SkeletonDrawable) { it.enabled = enabled loaderDrawable = it } else { loaderDrawable = addSkeletonLoader(enabled = enabled) } } return loaderDrawable } }
3
Kotlin
15
88
9608f59e023256419777c552f64ffc699433e070
8,957
Skeleton-Bones
MIT License
atala-prism-sdk/src/commonMain/kotlin/io/iohk/atala/prism/walletsdk/domain/models/keyManagement/KeyPair.kt
input-output-hk
564,174,099
false
{"Kotlin": 610578, "Gherkin": 1987, "ANTLR": 1440, "JavaScript": 375}
package io.iohk.atala.prism.walletsdk.domain.models.keyManagement import kotlinx.serialization.Serializable /** * Data class representing a pair of private and public keys for a specific key curve. */ @Serializable abstract class KeyPair { abstract var privateKey: PrivateKey abstract var publicKey: PublicKey fun getCurve(): String { return this.privateKey.getProperty(CurveKey().property) } }
1
Kotlin
0
5
416c3ee1fb4a9b1e39344f911d4df9f815850cd7
424
atala-prism-wallet-sdk-kmm
Apache License 2.0
aws-crt-kotlin/common/src/aws/sdk/kotlin/crt/http/HttpMonitoringOptions.kt
awslabs
267,704,046
false
null
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package aws.sdk.kotlin.crt.http /** * This class provides access to basic http connection monitoring controls in lieu of the more traditional * timeouts. * * The user can set a throughput threshold (in bytes per second) for the a connection to be considered healthy. If * the connection falls below this threshold for a configurable amount of time, then the connection is considered * unhealthy and shut down. Throughput/health is only measured when the connection has work (read or write) that * needs to be done. */ public data class HttpMonitoringOptions( /** * minimum amount of throughput, in bytes per second, for a connection to be considered healthy */ val minThroughputBytesPerSecond: Int = 0, /** * How long, in seconds, a connection is allowed to be unhealthy before getting shut down. Must be at least two */ val allowableThroughputFailureIntervalSeconds: Int = 2 ) { init { require(minThroughputBytesPerSecond >= 0) { "Http monitoring minimum throughput must be non-negative" } require(allowableThroughputFailureIntervalSeconds >= 2) { "Http monitoring failure interval must be at least two" } } }
5
null
2
6
d0e62ccdb99eb016bf7c7cb52a8f9a6fc12929d3
1,302
aws-crt-kotlin
Apache License 2.0
src/main/kotlin/no/nav/klage/oppgave/domain/klage/KlagerHistorikk.kt
navikt
297,650,936
false
null
package no.nav.klage.oppgave.domain.klage import jakarta.persistence.* import java.time.LocalDateTime import java.util.* @Entity @Table(name = "fullmektighistorikk", schema = "klage") class FullmektigHistorikk( @Id val id: UUID = UUID.randomUUID(), @Embedded @AttributeOverrides( value = [ AttributeOverride(name = "type", column = Column(name = "fullmektig_type")), AttributeOverride(name = "value", column = Column(name = "fullmektig_value")) ] ) var partId: PartId?, @Column(name = "tidspunkt") val tidspunkt: LocalDateTime, @Column(name = "utfoerende_ident") val utfoerendeIdent: String?, ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as FullmektigHistorikk if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } override fun toString(): String { return "FullmektigHistorikk(id=$id, partId=$partId, tidspunkt=$tidspunkt, utfoerendeIdent='$utfoerendeIdent')" } }
3
null
4
1
b4036f342d57a21140813fbeb698c1d4f3f33764
1,168
kabal-api
MIT License
app/src/main/java/com/example/mydiagnosis/viewmodel/DiagnosisResultViewModel.kt
VishwaP98
190,676,831
false
null
package com.example.mydiagnosis.viewmodel import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import android.content.Context import com.example.mydiagnosis.model.Condition import com.example.mydiagnosis.usecase.DiagnoseUseCase import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class DiagnosisResultViewModel : ViewModel() { var conditions : MutableLiveData<List<Condition>> = MutableLiveData() fun getDiagnosis(context: Context, userAge : Int?, userGender : String?) { CoroutineScope(Dispatchers.IO).launch { val useCase = DiagnoseUseCase(context, userAge, userGender) conditions.postValue(useCase.run()) } } }
1
Kotlin
1
0
ccd4ae5cfa2ca7e081ab029943f4c12438def024
768
MyDiagnosis
MIT License
fuzzer/src/test/resources/compilerTestData/codegen/box/coroutines/statementLikeLastExpression.kt
gigliovale
102,885,402
false
null
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* var globalResult = "" suspend fun suspendWithValue(v: String): String = suspendCoroutineOrReturn { x -> x.resume(v) COROUTINE_SUSPENDED } fun builder(c: suspend () -> String) { c.startCoroutine(handleResultContinuation { globalResult = it }) } fun box(): String { var condition = true builder { if (condition) { suspendWithValue("OK") } else { suspendWithValue("fail 1") } } return globalResult }
2
null
5748
6
ce145c015d6461c840050934f2200dbc11cb3d92
634
kotlin
MIT License
pseudonym-server/src/main/kotlin/org/ostelco/pseudonym/PseudonymModule.kt
mdheyab
157,444,239
true
{"Kotlin": 613166, "Java": 82884, "Shell": 48278, "Dockerfile": 4589}
package org.ostelco.pseudonym import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonTypeName import io.dropwizard.Configuration import io.dropwizard.setup.Environment import org.ostelco.prime.module.PrimeModule import org.ostelco.pseudonym.resources.PseudonymResource import org.ostelco.pseudonym.service.PseudonymizerServiceSingleton @JsonTypeName("pseudonymizer") class PseudonymModule : PrimeModule { @JsonProperty fun setConfig(config: PseudonymServerConfig) { ConfigRegistry.config = config } override fun init(env: Environment) { PseudonymizerServiceSingleton.init(env = env) env.jersey().register(PseudonymResource()) } } object ConfigRegistry { var config = PseudonymServerConfig() } /** * The configuration for Pseudonymiser. */ class PseudonymServerConfig : Configuration() { var datastoreType = "default" var namespace = "" }
0
Kotlin
0
0
dd306f17137828cc177836e1be4addccaef5982e
943
ostelco-core
Apache License 2.0
bidon/src/main/java/org/bidon/sdk/databinders/device/DeviceBinder.kt
bidon-io
654,165,570
false
null
package org.bidon.sdk.databinders.device import org.bidon.sdk.config.models.Device import org.bidon.sdk.databinders.DataBinder import org.bidon.sdk.utils.serializer.serialize import org.json.JSONObject /** * Created by <NAME> on 06/02/2023. */ internal class DeviceBinder( private val dataSource: DeviceDataSource, ) : DataBinder<JSONObject> { override val fieldName: String = "device" override suspend fun getJsonObject(): JSONObject = createDevice().serialize() private fun createDevice(): Device { return Device( userAgent = dataSource.getUserAgent(), manufacturer = dataSource.getManufacturer(), deviceModel = dataSource.getDeviceModel(), os = dataSource.getOs(), osVersion = dataSource.getOsVersion(), hardwareVersion = dataSource.getHardwareVersion(), width = dataSource.getScreenWidth(), height = dataSource.getScreenHeight(), ppi = dataSource.getPpi(), pxRatio = dataSource.getPxRatio(), javaScriptSupport = dataSource.getJavaScriptSupport(), language = dataSource.getLanguage(), carrier = dataSource.getCarrier(), mccmnc = dataSource.getPhoneMCCMNC(), connectionType = dataSource.getConnectionTypeCode() ) } }
1
Kotlin
0
0
a624344c96c08ee05c026daed8ca7634f56daf0f
1,340
bidon_sdk_android
Apache License 2.0
projects/Kotlin/src/proto/protoex/fbe/Proxy.kt
stinnux
179,512,303
false
{"Markdown": 3, "CMake": 7, "YAML": 4, "Text": 1, "Ignore List": 12, "Git Attributes": 1, "C++": 55, "Maven POM": 1, "XML": 114, "Java": 443, "Ruby": 26, "Microsoft Visual Studio Solution": 2, "C#": 64, "Go": 419, "Kotlin": 458, "JSON": 2, "JavaScript": 35, "Python": 31, "C": 1, "Yacc": 1, "Lex": 1}
// Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: protoex.fbe // Version: 1.2.0.0 @file:Suppress("UnusedImport", "unused") package protoex.fbe import java.io.* import java.lang.* import java.lang.reflect.* import java.math.* import java.nio.charset.* import java.time.* import java.util.* import fbe.* import protoex.* // Fast Binary Encoding protoex proxy @Suppress("MemberVisibilityCanBePrivate", "PrivatePropertyName", "UNUSED_PARAMETER") open class Proxy : fbe.Receiver { // Imported proxy var protoProxy: proto.fbe.Proxy? = null // Proxy models accessors private val OrderModel: OrderModel private val BalanceModel: BalanceModel private val AccountModel: AccountModel constructor() : super(false) { protoProxy = proto.fbe.Proxy(buffer) OrderModel = OrderModel() BalanceModel = BalanceModel() AccountModel = AccountModel() } constructor(buffer: Buffer) : super(buffer, false) { protoProxy = proto.fbe.Proxy(buffer) OrderModel = OrderModel() BalanceModel = BalanceModel() AccountModel = AccountModel() } // Proxy handlers protected open fun onProxy(model: OrderModel, type: Long, buffer: ByteArray, offset: Long, size: Long) {} protected open fun onProxy(model: BalanceModel, type: Long, buffer: ByteArray, offset: Long, size: Long) {} protected open fun onProxy(model: AccountModel, type: Long, buffer: ByteArray, offset: Long, size: Long) {} override fun onReceive(type: Long, buffer: ByteArray, offset: Long, size: Long): Boolean { when (type) { protoex.fbe.OrderModel.fbeTypeConst -> { // Attach the FBE stream to the proxy model OrderModel.attach(buffer, offset) assert(OrderModel.verify()) { "protoex.Order validation failed!" } val fbeBegin = OrderModel.model.getBegin() if (fbeBegin == 0L) return false // Call proxy handler onProxy(OrderModel, type, buffer, offset, size) OrderModel.model.getEnd(fbeBegin) return true } protoex.fbe.BalanceModel.fbeTypeConst -> { // Attach the FBE stream to the proxy model BalanceModel.attach(buffer, offset) assert(BalanceModel.verify()) { "protoex.Balance validation failed!" } val fbeBegin = BalanceModel.model.getBegin() if (fbeBegin == 0L) return false // Call proxy handler onProxy(BalanceModel, type, buffer, offset, size) BalanceModel.model.getEnd(fbeBegin) return true } protoex.fbe.AccountModel.fbeTypeConst -> { // Attach the FBE stream to the proxy model AccountModel.attach(buffer, offset) assert(AccountModel.verify()) { "protoex.Account validation failed!" } val fbeBegin = AccountModel.model.getBegin() if (fbeBegin == 0L) return false // Call proxy handler onProxy(AccountModel, type, buffer, offset, size) AccountModel.model.getEnd(fbeBegin) return true } } if ((protoProxy != null) && protoProxy!!.onReceive(type, buffer, offset, size)) return true return false } }
1
null
1
1
8e11fece6509af3299c29edd1b14d246c0a4574e
3,630
FastBinaryEncoding
MIT License
y2016/src/main/kotlin/adventofcode/y2016/Day04.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 453707}
package adventofcode.y2016 import adventofcode.io.AdventSolution object Day04 : AdventSolution(2016, 4, "Security Through Obscurity") { override fun solvePartOne(input: String) = parseRooms(input) .sumOf { it.id } .toString() override fun solvePartTwo(input: String) = parseRooms(input) .map { it.decrypt() to it.id } .first { "north" in it.first } .second .toString() private fun parseRooms(input: String): Sequence<Room> { return input.lineSequence() .map { Room( name = it.substringBeforeLast("-"), id = it.substringAfterLast("-").substringBefore("[").toInt(), checksum = it.substringAfterLast("[").dropLast(1) ) } .filter { it.isValid() } } data class Room(val name: String, val id: Int, val checksum: String) { fun isValid(): Boolean = name.groupingBy { it } .eachCount() .toSortedMap() .asSequence() .sortedByDescending { it.value } .map { it.key } .filterNot { it == '-' } .take(5) .joinToString("") == checksum fun decrypt(): String = name.map { when (it) { '-' -> '-' in 'a'..'z' -> ((((it - 'a') + id) % 26) + 'a'.code).toChar() else -> '?' } } .joinToString("") } }
0
Kotlin
0
3
f988b7b77f7b03b7ef4b1269192c9a41abe789f4
1,600
advent-of-code
MIT License
app/src/main/kotlin/com/akagiyui/common/GeetestCaptchaV4Template.kt
AkagiYui
647,653,830
false
{"Kotlin": 306901, "Java": 87795, "HTML": 812, "Dockerfile": 658}
package com.akagiyui.common import com.akagiyui.common.crypto.DataSigner import com.akagiyui.common.crypto.HmacSHA256DataSigner import com.akagiyui.common.exception.GeetestCaptchaValidateException import com.akagiyui.common.model.CaptchaType import com.akagiyui.common.model.ClientType import com.akagiyui.common.model.GeetestCaptchaV4ValidateResponse import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import org.springframework.util.LinkedMultiValueMap import org.springframework.web.client.RestTemplate /** * 极验验证码 V4 模板 * @author AkagiYui */ class GeetestCaptchaV4Template( /** * 验证ID */ private val captchaId: String, /** * 验证Key */ private val captchaKey: String, ) { private val restTemplate = RestTemplate() private val url = "https://gcaptcha4.geetest.com/validate" private val objectMapper = ObjectMapper() private val signer: DataSigner = HmacSHA256DataSigner(captchaKey) /** * 二次验证 * * @param lotNumber 流水号 * @param captchaOutput 验证码输出 * @param passToken 验证通过令牌 * @param genTime 时间戳 * @return 验证响应 */ fun validate( lotNumber: String, captchaOutput: String, passToken: String, genTime: String, ): GeetestCaptchaV4ValidateResponse { val params = LinkedMultiValueMap<String, String>().apply { add("lot_number", lotNumber) add("captcha_output", captchaOutput) add("pass_token", passToken) add("gen_time", genTime) add("sign_token", signer.sign(lotNumber)) } val url = "${this.url}?captcha_id=$captchaId" val headers = HttpHeaders().apply { contentType = MediaType.APPLICATION_FORM_URLENCODED } val request = HttpEntity(params, headers) val response = restTemplate.postForObject(url, request, String::class.java) val result: JsonNode = objectMapper.readTree(response) require(result["status"].asText() == "success") { "Captcha validation failed" } if (result["result"].asText() != "success") { throw GeetestCaptchaValidateException(result["reason"].asText()) } val data = result["captcha_args"] return GeetestCaptchaV4ValidateResponse( captchaType = CaptchaType.valueOf(data["used_type"].asText().uppercase()), userIp = data["user_ip"].asText(), lotNumber = data["lot_number"].asText(), scene = data["scene"].asText(), referer = data["referer"].asText(), ipType = data["ip_type"].asInt(), userInfo = data["user_info"].asText(), clientType = ClientType.valueOf(data["client_type"].asText().uppercase()), userAgent = data["ua"].asText(), failCount = data["fail_count"].asInt(), ) } }
4
Kotlin
3
17
cad68a3376fd8ba44cbb1cf5fb319627932c347b
3,028
KenkoDrive
MIT License
sw-server/src/main/kotlin/org/luxons/sevenwonders/server/repositories/PlayerRepository.kt
starsep
345,459,240
true
{"Kotlin": 541243, "HTML": 785, "Dockerfile": 457}
package org.luxons.sevenwonders.server.repositories import io.micrometer.core.instrument.MeterRegistry import org.luxons.sevenwonders.model.api.actions.Icon import org.luxons.sevenwonders.server.ApiMisuseException import org.luxons.sevenwonders.server.lobby.Player import org.springframework.stereotype.Repository import java.util.concurrent.ConcurrentHashMap @Repository class PlayerRepository( meterRegistry: MeterRegistry, ) { private val players = meterRegistry.gaugeMapSize("players.count", emptyList(), ConcurrentHashMap<String, Player>())!! operator fun contains(username: String): Boolean = players.containsKey(username) fun createOrUpdate(username: String, displayName: String, isHuman: Boolean = true, icon: Icon? = null): Player { val p = players.computeIfAbsent(username) { Player(username, displayName, isHuman, icon) } p.displayName = displayName p.icon = icon return p } fun find(username: String): Player? = players[username] fun get(username: String): Player = find(username) ?: throw PlayerNotFoundException(username) fun remove(username: String): Player = players.remove(username) ?: throw PlayerNotFoundException(username) } internal class PlayerNotFoundException(username: String) : ApiMisuseException("Player '$username' doesn't exist")
0
null
0
0
4647f3ad469b527c0716be30f8bb7ff382eba3bd
1,331
seven-wonders
MIT License
src/main/kotlin/feature/tasklist/TaskListSlice.kt
AKJAW
273,694,612
false
null
package feature.tasklist import feature.tasklist.thunk.FetchTaskThunk import redux.RAction import store.RThunk object TaskListSlice { data class State( val tasks: Array<Task> = emptyArray(), val isLoading: Boolean = true ) private val fetchTaskThunk = FetchTaskThunk() fun fetchTasks(): RThunk = fetchTaskThunk data class SetIsLoading(val isLoading: Boolean): RAction data class SetTasks(val tasks: Array<Task>): RAction data class AddTask(val task: Task): RAction data class RemoveTask(val task: Task): RAction fun reducer(state: State = State(), action: RAction): State { return when (action) { is SetIsLoading -> state.copy(isLoading = action.isLoading) is SetTasks -> state.copy(tasks = action.tasks) is AddTask -> state.copy(tasks = state.tasks + action.task) is RemoveTask -> state.copy(tasks = state.tasks.filterNot { task -> task == action.task }.toTypedArray()) else -> state } } }
0
Kotlin
1
3
5b45a3bc57669f920fdada004ca3861382638441
1,031
kotlin-react-example
MIT License
misk-jdbc/src/test/kotlin/misk/jdbc/DeclarativeSchemaMigratorTest.kt
cashapp
113,107,217
false
{"Kotlin": 3916547, "TypeScript": 285736, "Java": 83564, "JavaScript": 6613, "Shell": 5536, "HTML": 2323, "CSS": 58, "HCL": 20}
package misk.jdbc import jakarta.inject.Inject import misk.MiskTestingServiceModule import misk.config.MiskConfig import misk.database.StartDatabaseService import misk.environment.DeploymentModule import misk.resources.ResourceLoader import misk.testing.MiskTest import misk.testing.MiskTestModule import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import wisp.config.Config import wisp.deployment.TESTING import kotlin.test.assertFailsWith @MiskTest(startService = false) internal class MySQLDeclarativeSchemaMigratorTest : DeclarativeSchemaMigratorTest(DataSourceType.MYSQL) @MiskTest(startService = false) internal class PostgreSQLDeclarativeSchemaMigratorTest : DeclarativeSchemaMigratorTest(DataSourceType.POSTGRESQL) @MiskTest(startService = false) internal class CockroachdbDeclarativeSchemaMigratorTest : DeclarativeSchemaMigratorTest(DataSourceType.COCKROACHDB) @MiskTest(startService = false) internal class TidbDeclarativeSchemaMigratorTest : DeclarativeSchemaMigratorTest(DataSourceType.TIDB) internal abstract class DeclarativeSchemaMigratorTest(val type: DataSourceType) { val appConfig = MiskConfig.load<RootConfig>("test_declarative_schemamigrator_app", TESTING) val config = selectDataSourceConfig(appConfig) @MiskTestModule val deploymentModule = DeploymentModule(TESTING) @MiskTestModule val testingModule = MiskTestingServiceModule() @MiskTestModule val jdbcModule = JdbcModule(Movies::class, config) private fun selectDataSourceConfig(config: RootConfig): DataSourceConfig { return when (type) { DataSourceType.MYSQL -> config.mysql_data_source DataSourceType.COCKROACHDB -> config.cockroachdb_data_source DataSourceType.POSTGRESQL -> config.postgresql_data_source DataSourceType.TIDB -> config.tidb_data_source DataSourceType.HSQLDB -> throw RuntimeException("Not supported (yet?)") else -> throw java.lang.RuntimeException("unexpected data source type $type") } } data class RootConfig( val mysql_data_source: DataSourceConfig, val cockroachdb_data_source: DataSourceConfig, val postgresql_data_source: DataSourceConfig, val tidb_data_source: DataSourceConfig, ) : Config @Inject lateinit var resourceLoader: ResourceLoader @Inject @Movies lateinit var dataSourceService: DataSourceService @Inject @Movies lateinit var schemaMigrator: SchemaMigrator @Inject @Movies lateinit var schemaMigratorService: SchemaMigratorService @Inject @Movies lateinit var startDatabaseService: StartDatabaseService private lateinit var declarativeSchemaMigrator : DeclarativeSchemaMigrator @AfterEach internal fun tearDown() { if (dataSourceService.isRunning) { dropTables() dataSourceService.stopAsync() dataSourceService.awaitTerminated() } if (startDatabaseService.isRunning) { startDatabaseService.stopAsync() startDatabaseService.awaitTerminated() } } @BeforeEach internal fun setUp() { declarativeSchemaMigrator = schemaMigrator as DeclarativeSchemaMigrator startDatabaseService.startAsync() startDatabaseService.awaitRunning() dataSourceService.startAsync() dataSourceService.awaitRunning() dropTables() } private fun dropTables() { dataSourceService.dataSource.connection.use { connection -> val statement = connection.createStatement() statement.addBatch("DROP TABLE IF EXISTS schema_version") statement.executeBatch() connection.commit() } } //@Test TODO enable when implemented fun failsOnInvalidMigrations() { val mainSource = config.migrations_resources!![0] resourceLoader.put( "$mainSource/v1001__movies.sql", """ |CREATE TABLE table_1 (name varchar(255)) |""".trimMargin() ) assertFailsWith<IllegalArgumentException>(message = "unexpected resource: $mainSource/v1001__movies.sql") { declarativeSchemaMigrator.requireAll() } } }
168
Kotlin
169
399
76aa8e38a05c913d86cffc581363f82fd132e5c4
3,965
misk
Apache License 2.0
agp-compatibility/agp-compatibility-api/src/main/java/com/likethesalad/tools/agpcompat/api/AgpCompatibilityEntrypoint.kt
LikeTheSalad
413,299,542
false
null
package com.likethesalad.tools.agpcompat.api import com.likethesalad.tools.agpcompat.api.utilities.AgpVersion import org.gradle.api.Project import org.gradle.api.logging.Logging import java.util.ServiceLoader abstract class AgpCompatibilityEntrypoint { abstract fun getDescription(): String abstract fun isCompatible(currentVersion: AgpVersion?): Boolean abstract fun providePluginStrategy(project: Project): PluginStrategy companion object { @JvmStatic fun findCompatibleStrategy(project: Project): PluginStrategy { val entrypoints = ServiceLoader.load(AgpCompatibilityEntrypoint::class.java) check( entrypoints.iterator().hasNext() ) { "No implementations found for " + AgpCompatibilityEntrypoint::class.java.name } val currentVersion = getCurrentAgpVersion(project) for (entrypoint in entrypoints) { if (entrypoint.isCompatible(currentVersion)) { Logging.getLogger(AgpCompatibilityEntrypoint::class.java) .debug("Found AGP compatible entrypoint with description: '{}'", entrypoint.getDescription()) return entrypoint.providePluginStrategy(project) } } throw UnsupportedOperationException("Could not find compatible strategy for agp version $currentVersion") } private fun getCurrentAgpVersion(project: Project): AgpVersion? { return try { val componentsExtensionType = Class.forName("com.android.build.api.variant.AndroidComponentsExtension") val componentsExtension = project.extensions.findByType(componentsExtensionType) val pluginVersionGetter = componentsExtensionType.getDeclaredMethod("getPluginVersion") val currentVersion = pluginVersionGetter.invoke(componentsExtension) androidPluginVersionToAgpVersion(currentVersion) } catch (e: ClassNotFoundException) { null } } private fun androidPluginVersionToAgpVersion(currentVersion: Any): AgpVersion { val majorGetter = currentVersion.javaClass.getDeclaredMethod("getMajor") val minorGetter = currentVersion.javaClass.getDeclaredMethod("getMinor") val microGetter = currentVersion.javaClass.getDeclaredMethod("getMicro") return AgpVersion( majorGetter.invoke(currentVersion) as Int, minorGetter.invoke(currentVersion) as Int, microGetter.invoke(currentVersion) as Int ) } } }
0
null
0
1
1b5c210315a549e727511850320456cad559cfe3
2,653
android-gradle-tools
MIT License
vector/src/main/java/im/vector/riotx/features/crypto/recover/BackupToQuadSMigrationTask.kt
aalzehla
287,565,471
false
{"Gradle": 8, "Markdown": 12, "Java Properties": 2, "Shell": 18, "Text": 3, "Ignore List": 7, "Batchfile": 1, "EditorConfig": 1, "YAML": 1, "INI": 2, "Proguard": 5, "XML": 787, "Kotlin": 2101, "Java": 12, "JavaScript": 4, "JSON": 5, "HTML": 2, "FreeMarker": 2, "Fluent": 7, "Python": 1}
/* * Copyright (c) 2020 New Vector Ltd * * 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 im.vector.riotx.features.crypto.recover import im.vector.matrix.android.api.NoOpMatrixCallback import im.vector.matrix.android.api.listeners.ProgressListener import im.vector.matrix.android.api.session.Session import im.vector.matrix.android.api.session.crypto.crosssigning.KEYBACKUP_SECRET_SSSS_NAME import im.vector.matrix.android.api.session.securestorage.EmptyKeySigner import im.vector.matrix.android.api.session.securestorage.RawBytesKeySpec import im.vector.matrix.android.api.session.securestorage.SharedSecretStorageService import im.vector.matrix.android.api.session.securestorage.SsssKeyCreationInfo import im.vector.matrix.android.internal.crypto.crosssigning.toBase64NoPadding import im.vector.matrix.android.internal.crypto.keysbackup.deriveKey import im.vector.matrix.android.internal.crypto.keysbackup.util.computeRecoveryKey import im.vector.matrix.android.internal.crypto.keysbackup.util.extractCurveKeyFromRecoveryKey import im.vector.matrix.android.internal.util.awaitCallback import im.vector.riotx.R import im.vector.riotx.core.platform.ViewModelTask import im.vector.riotx.core.platform.WaitingViewData import im.vector.riotx.core.resources.StringProvider import timber.log.Timber import java.util.UUID import javax.inject.Inject class BackupToQuadSMigrationTask @Inject constructor( val session: Session, val stringProvider: StringProvider ) : ViewModelTask<BackupToQuadSMigrationTask.Params, BackupToQuadSMigrationTask.Result> { sealed class Result { object Success : Result() abstract class Failure(val throwable: Throwable?) : Result() object InvalidRecoverySecret : Failure(null) object NoKeyBackupVersion : Failure(null) object IllegalParams : Failure(null) class ErrorFailure(throwable: Throwable) : Failure(throwable) } data class Params( val passphrase: String?, val recoveryKey: String?, val progressListener: BootstrapProgressListener? = null ) override suspend fun execute(params: Params): Result { try { // We need to use the current secret for keybackup and use it as the new master key for SSSS // Then we need to put back the backup key in sss val keysBackupService = session.cryptoService().keysBackupService() val quadS = session.sharedSecretStorageService val version = keysBackupService.keysBackupVersion ?: return Result.NoKeyBackupVersion reportProgress(params, R.string.bootstrap_progress_checking_backup) val curveKey = (if (params.recoveryKey != null) { extractCurveKeyFromRecoveryKey(params.recoveryKey) } else if (!params.passphrase.isNullOrEmpty() && version.getAuthDataAsMegolmBackupAuthData()?.privateKeySalt != null) { version.getAuthDataAsMegolmBackupAuthData()?.let { authData -> deriveKey(params.passphrase, authData.privateKeySalt!!, authData.privateKeyIterations!!, object : ProgressListener { override fun onProgress(progress: Int, total: Int) { params.progressListener?.onProgress(WaitingViewData( stringProvider.getString(R.string.bootstrap_progress_checking_backup_with_info, "$progress/$total") )) } }) } } else null) ?: return Result.IllegalParams reportProgress(params, R.string.bootstrap_progress_compute_curve_key) val recoveryKey = computeRecoveryKey(curveKey) val isValid = awaitCallback<Boolean> { keysBackupService.isValidRecoveryKeyForCurrentVersion(recoveryKey, it) } if (!isValid) return Result.InvalidRecoverySecret val info: SsssKeyCreationInfo = when { params.passphrase?.isNotEmpty() == true -> { reportProgress(params, R.string.bootstrap_progress_generating_ssss) awaitCallback<SsssKeyCreationInfo> { quadS.generateKeyWithPassphrase( UUID.randomUUID().toString(), "ssss_key", params.passphrase, EmptyKeySigner(), object : ProgressListener { override fun onProgress(progress: Int, total: Int) { params.progressListener?.onProgress( WaitingViewData( stringProvider.getString( R.string.bootstrap_progress_generating_ssss_with_info, "$progress/$total") )) } }, it ) } } params.recoveryKey != null -> { reportProgress(params, R.string.bootstrap_progress_generating_ssss_recovery) awaitCallback { quadS.generateKey( UUID.randomUUID().toString(), extractCurveKeyFromRecoveryKey(params.recoveryKey)?.let { RawBytesKeySpec(it) }, "ssss_key", EmptyKeySigner(), it ) } } else -> { return Result.IllegalParams } } // Ok, so now we have migrated the old keybackup secret as the quadS key // Now we need to store the keybackup key in SSSS in a compatible way reportProgress(params, R.string.bootstrap_progress_storing_in_sss) awaitCallback<Unit> { quadS.storeSecret( KEYBACKUP_SECRET_SSSS_NAME, curveKey.toBase64NoPadding(), listOf(SharedSecretStorageService.KeyRef(info.keyId, info.keySpec)), it ) } // save for gossiping keysBackupService.saveBackupRecoveryKey(recoveryKey, version.version) // while we are there let's restore, but do not block session.cryptoService().keysBackupService().restoreKeysWithRecoveryKey( version, recoveryKey, null, null, null, NoOpMatrixCallback() ) return Result.Success } catch (failure: Throwable) { Timber.e(failure, "## BackupToQuadSMigrationTask - Failed to migrate backup") return Result.ErrorFailure(failure) } } private fun reportProgress(params: Params, stringRes: Int) { params.progressListener?.onProgress(WaitingViewData(stringProvider.getString(stringRes))) } }
1
null
1
1
ee1d5faf0d59f9cc1c058d45fae3e811d97740fd
8,481
element-android
Apache License 2.0
intellij/src/main/kotlin/com/mintlify/document/services/MyProjectService.kt
mintlify
441,005,943
false
{"TypeScript": 290835, "Kotlin": 11244, "Java": 4632, "JavaScript": 2061, "Procfile": 37}
package com.mintlify.document.services import com.intellij.openapi.project.Project import com.mintlify.document.MyBundle class MyProjectService(project: Project) { init { println(MyBundle.message("projectService", project.name)) } }
60
TypeScript
118
2,564
2be13bd17e26e698ef406eddc8491facb8ae1c04
252
writer
MIT License
app/src/main/java/com/srg/citibox/post_detail/ui/PostDetailViewModel.kt
sebrodgar
233,223,889
false
null
package com.srg.citibox.post_detail.ui import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.srg.citibox.common.data.model.* import com.srg.citibox.post_detail.domain.usecase.GetAuthorByPost import com.srg.citibox.post_detail.domain.usecase.GetNumberOfCommentByPost import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.launch import javax.inject.Inject /** * Created by <NAME> on 16,January,2020 */ class PostDetailViewModel @Inject constructor( private val getAuthorByPost: GetAuthorByPost, private val getNumberOfCommentByPost: GetNumberOfCommentByPost ) : ViewModel() { var author: MutableLiveData<User> = MutableLiveData() var numberOfComment: MutableLiveData<Int> = MutableLiveData() var post: MutableLiveData<Post> = MutableLiveData() var errorLive: MutableLiveData<CitiboxError> = MutableLiveData() fun getPostDetails(post: Post) { this.post.value = post viewModelScope.launch { val calls = listOf( // fetch two call at the same time async { getAuthorByPost.getAuthorByPost(post.userId) { result -> if(result.isSuccess) author.postValue(result.foldSuccess()) else errorLive.postValue(result.foldFailure()) } }, // async returns a result for the first call async { getNumberOfCommentByPost.getNumberOfCommentByPost(post.id) { result -> if(result.isSuccess) numberOfComment.postValue(result.foldSuccess()) else errorLive.postValue(result.foldFailure()) } } // async returns a result for the second call ) calls.awaitAll() } } }
0
Kotlin
0
0
d5e4c74d9564a8dae7e3406775687f42acaecb81
2,010
candidate-test-citibox
Apache License 2.0
toolkit/compass/src/main/java/com/arcgismaps/toolkit/compass/Compass.kt
Esri
585,717,773
false
{"Kotlin": 1190928, "Shell": 13696}
/* * * Copyright 2023 Esri * * 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.arcgismaps.toolkit.compass import androidx.annotation.DrawableRes import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp /** * Creates a Compass that shows the geographic orientation of a [ComposableMap] using the * [rotation] property. By default, the compass hides when the map is pointing to it's default * North orientation. This auto hide behavior can be changed using the [autoHide] property. * Size and color of the icon can be customized using [size] and [color]. Resetting behavior can * be implemented using the [onClick] callback which is raised when the Compass is tapped. */ @Composable public fun Compass( rotation: Double, modifier: Modifier = Modifier, autoHide: Boolean = true, size: Dp = 50.dp, color: Color = Color.White, borderColor: Color = Color.Gray, onClick: () -> Unit = {} ) { val heading = -rotation.toFloat() val visible = if (autoHide) heading != 0f else true AnimatedVisibility( visible = visible, enter = fadeIn(), exit = fadeOut(animationSpec = tween(delayMillis = 500)) ) { CompassButtonIcon( icon = R.drawable.ic_compass, color = color, borderColor = borderColor, modifier = modifier .size(size) .rotate(heading) .semantics { contentDescription = "CompassButtonIcon" }, onClick = onClick ) } } /** * A composable ButtonIcon for the Compass with the [icon] and [color] for container color. * Tap events can be handled using the [onClick] callback. */ @Composable internal fun CompassButtonIcon( @DrawableRes icon: Int, color: Color, borderColor: Color, modifier: Modifier = Modifier, onClick: () -> Unit = {} ) { val borderWidth = 2.dp Button( modifier = modifier .border( BorderStroke(borderWidth, borderColor), CircleShape ) .padding(borderWidth) .clip(CircleShape), colors = ButtonDefaults.buttonColors(containerColor = color), contentPadding = PaddingValues(10.dp), onClick = onClick ) { Image( modifier = Modifier.fillMaxSize(), painter = painterResource(icon), contentDescription = "CompassIcon" ) } }
7
Kotlin
3
9
7ad544f720b25b5969848e786cb26f2a83b5aa7e
3,989
arcgis-maps-sdk-kotlin-toolkit
Apache License 2.0
08.Local-Storage/02.Local-Storage-HW/app/src/main/java/com/example/workwithapi/fragments/list/FirstFragment.kt
kostadinlambov
555,440,264
false
{"Kotlin": 114361}
package com.example.workwithapi.fragments.list import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.example.workwithapi.data.country.Country import com.example.workwithapi.data.dataInfo.DataInfo import com.example.workwithapi.databinding.FragmentFirstBinding import com.example.workwithapi.viewmodel.CountyViewModel import com.example.workwithapi.web.CountriesRepository import com.example.workwithapi.web.CountryData import com.example.workwithapi.web.CountryService import com.google.android.material.snackbar.Snackbar import okhttp3.OkHttpClient import retrofit2.Call import retrofit2.Callback import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.* class FirstFragment : Fragment() { lateinit var binding: FragmentFirstBinding lateinit var mCountryViewModel: CountyViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentFirstBinding.inflate(inflater, container, false) mCountryViewModel = ViewModelProvider(this).get(CountyViewModel::class.java) val retrofit = Retrofit.Builder() .baseUrl("https://restcountries.com/v2/") .addConverterFactory(GsonConverterFactory.create()) .client(OkHttpClient()) .build() val countryService = retrofit.create(CountryService::class.java) val countryRepository = CountriesRepository(countryService) val hasInternet = context?.let { checkForInternet(it) } ?: false // val databaseName = "country_db" // val deleteDatabase = context?.deleteDatabase(databaseName) if (hasInternet) { countryRepository.getCountries()?.enqueue(object : Callback<List<CountryData>> { override fun onResponse( call: Call<List<CountryData>>, response: Response<List<CountryData>> ) { val countries = response.body() ?: return val adapter = CountryDataAdapter(countries) binding.countriesList.adapter = adapter binding.progressBar.visibility = View.GONE insertCountriesToDatabase(countries) val date = Date() mCountryViewModel.addDataInfo(DataInfo(date)) Snackbar.make( binding.root, "Updated countries at: $date", Snackbar.LENGTH_LONG ).show() binding.updateTime = "Lats update time: $date" } override fun onFailure(call: Call<List<CountryData>>, t: Throwable) { Snackbar.make(binding.root, "Failed to fetch countries", Snackbar.LENGTH_LONG) .show() } }) } else { loadCountriesFromDatabase() } return binding.root } // Save all coutries in the DB private fun insertCountriesToDatabase(countries: List<CountryData>) { val mappedCountryDataList = countries.map { // if(inputCheck(it.name, it.capital, it.flags.png, it.flags.svg)){ Country( it.name, it.capital, it.region, it.population, it.area, it.flags.png, it.flags.svg ) // } } // // Clear database // val databaseName = "country_db" // val deleteDatabase = context?.deleteDatabase(databaseName) // mCountryViewModel.addCountries(mappedCountryDataList) mCountryViewModel.insertOrUpdateCountries(mappedCountryDataList) println("##### countryDataListAfterFetch: $mappedCountryDataList") // Toast.makeText(requireContext(), "Successfully added ${mappedCountryDataList.size} countries!", Toast.LENGTH_LONG).show() Snackbar.make( binding.root, "Successfully added ${mappedCountryDataList.size} countries!", Snackbar.LENGTH_LONG ).show() binding.count = "Country count: ${mappedCountryDataList.size}" } private fun loadCountriesFromDatabase() { mCountryViewModel.readAllCountries.observe(viewLifecycleOwner, Observer { countries -> val adapter = CountryAdapter(countries) binding.countriesList.adapter = adapter binding.progressBar.visibility = View.GONE Snackbar.make( binding.root, "Missing internet connection! Country list might be outdated!", Snackbar.LENGTH_LONG ).show() binding.count = "Country count: ${countries.size}" }) mCountryViewModel.getLastDataInfo().observe(viewLifecycleOwner, Observer{ binding.updateTime = "Lats update time: $it" }) } private fun inputCheck( name: String, capital: String, flagPng: String, flagSvg: String ): Boolean { return !(TextUtils.isEmpty(name) && TextUtils.isEmpty(capital) && TextUtils.isEmpty(flagPng) && TextUtils.isEmpty( flagSvg )) } private fun checkForInternet(context: Context): Boolean { // register activity with the connectivity manager service val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager // if the android version is equal to M // or greater we need to use the // NetworkCapabilities to check what type of // network has the internet connection // Returns a Network object corresponding to // the currently active default data network. val network = connectivityManager.activeNetwork ?: return false // Representation of the capabilities of an active network. val activeNetwork = connectivityManager.getNetworkCapabilities(network) ?: return false return when { // Indicates this network uses a Wi-Fi transport, // or WiFi has network connectivity activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true // Indicates this network uses a Cellular transport. or // Cellular has network connectivity activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true // else return false else -> false } } }
0
Kotlin
0
0
459b44cefa3fee2b6bcf210a967c1a05aea21a90
6,945
Android-Development-with-Kotlin
MIT License
Kotlin Koans/Introduction/Data classes/Solution.kt
Kotlin
50,311,744
false
null
package introduction.data_classes /*<answer><taskWindow>*/data class Person(val name: String, val age: Int)/*</taskWindow></answer>*/ fun getPeople(): List<Person> { return listOf(Person("Alice", 29), Person("Bob", 31)) }
14
Kotlin
18
55
9028a7b3d5c7fc6f9b669deee4596f97f4272b8b
227
kotlin-koans-edu-obsolete
MIT License
src/main/java/com/tang/intellij/lua/codeInsight/inspection/DuplicateClassDeclaration.kt
caniouff
251,665,370
false
null
/* * Copyright (c) 2017. tangzx(love.tangzx@qq.com) * * 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.tang.intellij.lua.codeInsight.inspection import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.Processor import com.tang.intellij.lua.LuaBundle import com.tang.intellij.lua.comment.psi.LuaDocTagClass import com.tang.intellij.lua.comment.psi.LuaDocVisitor import com.tang.intellij.lua.stubs.index.LuaClassIndex /** * 重复定义class * Created by TangZX on 2016/12/16. */ class DuplicateClassDeclaration : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { return object : LuaDocVisitor() { override fun visitTagClass(o: LuaDocTagClass) { val useScope = o.useScope as? GlobalSearchScope ?: return val identifier = o.nameIdentifier LuaClassIndex.process(identifier.text, o.project, useScope, Processor { if (it != o) holder.registerProblem(identifier, LuaBundle.message("inspection.duplicate_class", it.containingFile.virtualFile.canonicalPath), ProblemHighlightType.GENERIC_ERROR) true }) } } } }
0
null
0
1
b70bfb0ea20c1e00327eff25453ed0bf9349d0dc
2,081
typeLuaPlugin
Apache License 2.0
vector/src/main/java/im/vector/riotx/features/settings/devices/DevicesViewModel.kt
tchigher
235,243,831
true
{"Kotlin": 4474324, "Java": 113304, "HTML": 23530, "Shell": 21130}
/* * Copyright 2019 New Vector Ltd * * 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 im.vector.riotx.features.settings.devices import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.airbnb.mvrx.* import com.squareup.inject.assisted.Assisted import com.squareup.inject.assisted.AssistedInject import im.vector.matrix.android.api.MatrixCallback import im.vector.matrix.android.api.failure.Failure import im.vector.matrix.android.api.session.Session import im.vector.matrix.android.internal.auth.data.LoginFlowTypes import im.vector.matrix.android.internal.crypto.model.rest.DeviceInfo import im.vector.matrix.android.internal.crypto.model.rest.DevicesListResponse import im.vector.riotx.core.extensions.postLiveEvent import im.vector.riotx.core.platform.VectorViewModel import im.vector.riotx.core.platform.VectorViewModelAction import im.vector.riotx.core.utils.LiveEvent import timber.log.Timber data class DevicesViewState( val myDeviceId: String = "", val devices: Async<List<DeviceInfo>> = Uninitialized, val currentExpandedDeviceId: String? = null, val request: Async<Unit> = Uninitialized ) : MvRxState sealed class DevicesAction : VectorViewModelAction { object Retry : DevicesAction() data class Delete(val deviceInfo: DeviceInfo) : DevicesAction() data class Password(val password: String) : DevicesAction() data class Rename(val deviceInfo: DeviceInfo, val newName: String) : DevicesAction() data class ToggleDevice(val deviceInfo: DeviceInfo) : DevicesAction() } class DevicesViewModel @AssistedInject constructor(@Assisted initialState: DevicesViewState, private val session: Session) : VectorViewModel<DevicesViewState, DevicesAction>(initialState) { @AssistedInject.Factory interface Factory { fun create(initialState: DevicesViewState): DevicesViewModel } companion object : MvRxViewModelFactory<DevicesViewModel, DevicesViewState> { @JvmStatic override fun create(viewModelContext: ViewModelContext, state: DevicesViewState): DevicesViewModel? { val fragment: VectorSettingsDevicesFragment = (viewModelContext as FragmentViewModelContext).fragment() return fragment.devicesViewModelFactory.create(state) } } // temp storage when we ask for the user password private var _currentDeviceId: String? = null private var _currentSession: String? = null private val _requestPasswordLiveData = MutableLiveData<LiveEvent<Unit>>() val requestPasswordLiveData: LiveData<LiveEvent<Unit>> get() = _requestPasswordLiveData init { refreshDevicesList() } /** * Force the refresh of the devices list. * The devices list is the list of the devices where the user is logged in. * It can be any mobile devices, and any browsers. */ private fun refreshDevicesList() { if (session.isCryptoEnabled() && !session.sessionParams.credentials.deviceId.isNullOrEmpty()) { setState { copy( devices = Loading() ) } session.getDevicesList(object : MatrixCallback<DevicesListResponse> { override fun onSuccess(data: DevicesListResponse) { setState { copy( myDeviceId = session.sessionParams.credentials.deviceId ?: "", devices = Success(data.devices.orEmpty()) ) } } override fun onFailure(failure: Throwable) { setState { copy( devices = Fail(failure) ) } } }) } else { // Should not happen } } override fun handle(action: DevicesAction) { return when (action) { is DevicesAction.Retry -> refreshDevicesList() is DevicesAction.Delete -> handleDelete(action) is DevicesAction.Password -> handlePassword(action) is DevicesAction.Rename -> handleRename(action) is DevicesAction.ToggleDevice -> handleToggleDevice(action) } } private fun handleToggleDevice(action: DevicesAction.ToggleDevice) { withState { setState { copy( currentExpandedDeviceId = if (it.currentExpandedDeviceId == action.deviceInfo.deviceId) null else action.deviceInfo.deviceId ) } } } private fun handleRename(action: DevicesAction.Rename) { session.setDeviceName(action.deviceInfo.deviceId!!, action.newName, object : MatrixCallback<Unit> { override fun onSuccess(data: Unit) { setState { copy( request = Success(data) ) } // force settings update refreshDevicesList() } override fun onFailure(failure: Throwable) { setState { copy( request = Fail(failure) ) } _requestErrorLiveData.postLiveEvent(failure) } }) } /** * Try to delete a device. */ private fun handleDelete(action: DevicesAction.Delete) { val deviceId = action.deviceInfo.deviceId if (deviceId == null) { Timber.e("## handleDelete(): sanity check failure") return } setState { copy( request = Loading() ) } session.deleteDevice(deviceId, object : MatrixCallback<Unit> { override fun onFailure(failure: Throwable) { var isPasswordRequestFound = false if (failure is Failure.RegistrationFlowError) { // We only support LoginFlowTypes.PASSWORD // Check if we can provide the user password failure.registrationFlowResponse.flows?.forEach { interactiveAuthenticationFlow -> isPasswordRequestFound = isPasswordRequestFound || interactiveAuthenticationFlow.stages?.any { it == LoginFlowTypes.PASSWORD } == true } if (isPasswordRequestFound) { _currentDeviceId = deviceId _currentSession = failure.registrationFlowResponse.session setState { copy( request = Success(Unit) ) } _requestPasswordLiveData.postLiveEvent(Unit) } } if (!isPasswordRequestFound) { // LoginFlowTypes.PASSWORD not supported, and this is the only one RiotX supports so far... setState { copy( request = Fail(failure) ) } _requestErrorLiveData.postLiveEvent(failure) } } override fun onSuccess(data: Unit) { setState { copy( request = Success(data) ) } // force settings update refreshDevicesList() } }) } private fun handlePassword(action: DevicesAction.Password) { val currentDeviceId = _currentDeviceId if (currentDeviceId.isNullOrBlank()) { // Abort return } setState { copy( request = Loading() ) } session.deleteDeviceWithUserPassword(currentDeviceId, _currentSession, action.password, object : MatrixCallback<Unit> { override fun onSuccess(data: Unit) { _currentDeviceId = null _currentSession = null setState { copy( request = Success(data) ) } // force settings update refreshDevicesList() } override fun onFailure(failure: Throwable) { _currentDeviceId = null _currentSession = null // Password is maybe not good setState { copy( request = Fail(failure) ) } _requestErrorLiveData.postLiveEvent(failure) } }) } }
0
null
0
0
d1699279febb15c9a943bdd71d1eb71656c521cf
9,487
riotX-android
Apache License 2.0
api/src/main/kotlin/com/example/in/api/sign/adapter/in/request/SignUpTrainerWithEmailRequest.kt
PARKPARKWOO
737,782,254
false
{"Kotlin": 332477, "Dockerfile": 124}
package com.example.api.sign.adapter.`in`.request import com.example.core.sign.port.`in`.command.SignUpUserWithEmailCommand import com.example.core.sign.port.`in`.command.SignUpTrainerWithEmailCommand import com.example.core.user.model.Gender import java.util.UUID data class SignUpTrainerWithEmailRequest( val email: String, val nickname: String, val password: String, val gender: Gender, val exerciseYears: Int, val gymName: String, val street: String, val city: String, val country: String, val introduce: String, val authenticationString: UUID, ) { fun toCommand(): SignUpUserWithEmailCommand { return SignUpTrainerWithEmailCommand( email = email, nickname = nickname, password = <PASSWORD>, exerciseYears = exerciseYears, gymName = gymName, street = street, city = city, country = country, introduce = introduce, authenticationString = authenticationString, gender = gender, ) } }
9
Kotlin
0
0
fbf1272971e226519cd9919011fff785650994d3
1,088
barbellrobot-backend
Apache License 2.0
server/src/test/kotlin/dev/cuvar/tcserver/TcServerApplicationTests.kt
cuvar
526,288,202
false
null
package dev.cuvar.tcserver import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class TcServerApplicationTests { @Test fun contextLoads() { } }
1
Kotlin
0
0
8c29376d1fd0c9f668abdac2bcc464558dba6e5f
208
twitter-clone
MIT License
mysoothe/src/main/java/com/fjoglar/composechallenge/mysoothe/ui/screens/WelcomeScreen.kt
felipejoglar
412,404,654
false
null
package com.fjoglar.composechallenge.mysoothe.ui.screens import android.content.res.Configuration import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.fjoglar.composechallenge.mysoothe.R import com.fjoglar.composechallenge.mysoothe.ui.components.MySootheButton import com.fjoglar.composechallenge.mysoothe.ui.components.MySootheLogoImage import com.fjoglar.composechallenge.mysoothe.ui.components.MySootheTemplate import com.fjoglar.composechallenge.mysoothe.ui.components.VerticalSpacer @Composable fun WelcomeScreen( onLoginClick: () -> Unit = {} ) { BackgroundImage() Box( contentAlignment = Alignment.Center, modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) ) { Column { MySootheLogoImage( modifier = Modifier .align(alignment = Alignment.CenterHorizontally) ) VerticalSpacer(height = 32.dp) MySootheButton( text = stringResource(id = R.string.sign_up), modifier = Modifier.padding(horizontal = 16.dp) ) VerticalSpacer(height = 8.dp) MySootheButton( text = stringResource(id = R.string.log_in), color = MaterialTheme.colors.secondary, onClick = onLoginClick, modifier = Modifier.padding(horizontal = 16.dp) ) } } } @Composable private fun BackgroundImage() { Image( painter = painterResource(id = R.drawable.welcome_background), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .fillMaxSize() ) } @Preview( name = "Day Mode", widthDp = 360, heightDp = 640, uiMode = Configuration.UI_MODE_NIGHT_NO, ) @Preview( name = "Night Mode", widthDp = 360, heightDp = 640, uiMode = Configuration.UI_MODE_NIGHT_YES, ) @Composable private fun WelcomeScreenPreview() { MySootheTemplate { WelcomeScreen() } }
0
Kotlin
0
0
688692b44e59e9e25f966426ff08beaf1dd50d27
2,754
jetpack-compose-challenge
MIT License
intellijPlugin/src/main/kotlin/pw/binom/fbx/file/FbxVisiter.kt
caffeine-mgn
223,796,620
false
null
package pw.binom.fbx.file interface ElementContener { fun element(id: String): ElementVisiter? } interface ElementVisiter : ElementContener { fun property(value: Any) fun elementEnd() } interface FbxVisiter : ElementContener { fun start() fun version(version: UInt) fun end() }
6
Kotlin
0
4
e673acfcb20e2d62d8e68c43d395731bd9d9d882
304
mogot
Apache License 2.0
lib/src/main/kotlin/com/lemonappdev/konsist/core/verify/KoDeclarationAndProviderAssertCore.kt
LemonAppDev
621,181,534
false
null
package com.lemonappdev.konsist.core.verify import com.lemonappdev.konsist.api.declaration.KoAnnotationDeclaration import com.lemonappdev.konsist.api.declaration.KoFileDeclaration import com.lemonappdev.konsist.api.provider.KoAnnotationProvider import com.lemonappdev.konsist.api.provider.KoBaseProvider import com.lemonappdev.konsist.api.provider.KoContainingDeclarationProvider import com.lemonappdev.konsist.api.provider.KoLocationProvider import com.lemonappdev.konsist.api.provider.KoNameProvider import com.lemonappdev.konsist.core.exception.KoCheckFailedException import com.lemonappdev.konsist.core.exception.KoException import com.lemonappdev.konsist.core.exception.KoInternalException import com.lemonappdev.konsist.core.exception.KoPreconditionFailedException fun <E : KoBaseProvider> List<E>.assert(function: (E) -> Boolean?) { assert(function, positiveCheck = true) } fun <E : KoBaseProvider> List<E>.assertNot(function: (E) -> Boolean?) { assert(function, positiveCheck = false) } fun <E : KoBaseProvider> Sequence<E>.assert(function: (E) -> Boolean?) { this.toList().assert(function, true) } fun <E : KoBaseProvider> Sequence<E>.assertNot(function: (E) -> Boolean?) { this.toList().assert(function, false) } @Suppress("detekt.ThrowsCount") private fun <E : KoBaseProvider> List<E>.assert(function: (E) -> Boolean?, positiveCheck: Boolean) { var lastDeclaration: KoBaseProvider? = null try { val testMethodName = getTestMethodNameFromFifthIndex() checkIfLocalListIsEmpty(this, getTestMethodNameFromFourthIndex()) val notSuppressedDeclarations = checkIfAnnotatedWithSuppress(this, testMethodName) val result = notSuppressedDeclarations.groupBy { lastDeclaration = it if (function(it) == null) { positiveCheck } else { function(it) } } getResult(notSuppressedDeclarations, result, positiveCheck, testMethodName) } catch (e: KoException) { throw e } catch (@Suppress("detekt.TooGenericExceptionCaught") e: Exception) { throw KoInternalException(e.message.orEmpty(), e, lastDeclaration) } } private fun checkIfLocalListIsEmpty(localList: List<*>, testMethodName: String) { if (localList.isEmpty()) { throw KoPreconditionFailedException( "Declaration list is empty. Please make sure that list of declarations contain items " + "before calling the '$testMethodName' method.", ) } } private fun <E : KoBaseProvider> checkIfAnnotatedWithSuppress(localList: List<E>, testMethodName: String): List<E> { val declarations: MutableMap<E, Boolean> = mutableMapOf() // First we need to exclude (if exist) file suppress test annotation localList .filterNot { it is KoAnnotationDeclaration && ( it.name == "Suppress" && it.text.contains("\"konsist.$testMethodName\"") || it.text.contains("\"$testMethodName\"") ) } .forEach { declarations[it] = checkIfDeclarationIsAnnotatedWithSuppress(it, testMethodName) } val withoutSuppress = mutableListOf<E>() declarations.forEach { if (!it.value) withoutSuppress.add(it.key) } return withoutSuppress } private fun checkIfDeclarationIsAnnotatedWithSuppress(declaration: KoBaseProvider, testMethodName: String): Boolean = if (declaration is KoAnnotationProvider) { checkIfSuppressed(declaration, testMethodName) || checkIfParentIsAnnotatedWithSuppress(declaration, testMethodName) } else { checkIfParentIsAnnotatedWithSuppress(declaration, testMethodName) } private fun checkIfParentIsAnnotatedWithSuppress(declaration: KoBaseProvider, testMethodName: String): Boolean = if (declaration is KoContainingDeclarationProvider) { declaration.containingDeclaration?.let { checkIfDeclarationIsAnnotatedWithSuppress(it, testMethodName) } ?: false } else { false } private fun checkIfSuppressed(item: KoAnnotationProvider, testMethodName: String): Boolean { val annotationParameter = item .annotations .firstOrNull { it.name == "Suppress" } ?.text ?.removePrefix("@file:Suppress(") ?.removePrefix("@Suppress(") ?.substringBeforeLast(")") ?.split(",") ?.map { it.trim() } ?.map { it.removePrefix("\"") } ?.map { it.removeSuffix("\"") } ?: emptyList() return annotationParameter.any { it == testMethodName } || annotationParameter.any { it == "konsist.$testMethodName" } } private fun getResult(items: List<*>, result: Map<Boolean?, List<Any>>, positiveCheck: Boolean, testMethodName: String) { val allChecksPassed = (result[positiveCheck]?.size ?: 0) == items.size if (!allChecksPassed) { val failedItems = result[!positiveCheck] ?: emptyList() throw KoCheckFailedException(getCheckFailedMessage(failedItems, testMethodName)) } } private fun getCheckFailedMessage(failedItems: List<*>, testMethodName: String): String { var types = "" val failedDeclarationsMessage = failedItems.joinToString("\n") { val konsistDeclarationClassNamePrefix = "Ko" when (it) { is KoFileDeclaration -> { types = "files" val name = it.name val declarationType = it::class.simpleName?.substringAfter(konsistDeclarationClassNamePrefix) "${it.path} ($name $declarationType)" } is KoBaseProvider -> { types = "declarations" val name = (it as KoNameProvider).name val declarationType = it::class.simpleName?.substringAfter(konsistDeclarationClassNamePrefix) "${(it as KoLocationProvider).location} ($name $declarationType)" } else -> { "" } } } return "Assert '$testMethodName' has failed. Invalid $types (${failedItems.size}):\n$failedDeclarationsMessage" }
8
null
11
71
c3cf91622bab1938fecbc96c119cbbb70e372451
6,120
konsist
Apache License 2.0
src/test/java/com/tibagni/logviewer/rc/LogLevelConfigTests.kt
tibagni
108,044,981
false
null
package com.tibagni.logviewer.rc import org.junit.Test import org.junit.Assert.assertEquals class LogLevelConfigTests { @Test fun testVerboseConfig() { val config1 = Pair(LogLevelConfig("v"), "lower case single letter") val config2 = Pair(LogLevelConfig("V"), "upper case single letter") val config3 = Pair(LogLevelConfig("verbose"), "lower case word") val config4 = Pair(LogLevelConfig("VERBOSE"), "upper case word") assertEquals(config1.second, LogLevelConfig.Level.VERBOSE, config1.first.configValue) assertEquals(config2.second, LogLevelConfig.Level.VERBOSE, config2.first.configValue) assertEquals(config3.second, LogLevelConfig.Level.VERBOSE, config3.first.configValue) assertEquals(config4.second, LogLevelConfig.Level.VERBOSE, config4.first.configValue) } @Test fun testDebugConfig() { val config1 = Pair(LogLevelConfig("d"), "lower case single letter") val config2 = Pair(LogLevelConfig("D"), "upper case single letter") val config3 = Pair(LogLevelConfig("debug"), "lower case word") val config4 = Pair(LogLevelConfig("DEBUG"), "upper case word") assertEquals(config1.second, LogLevelConfig.Level.DEBUG, config1.first.configValue) assertEquals(config2.second, LogLevelConfig.Level.DEBUG, config2.first.configValue) assertEquals(config3.second, LogLevelConfig.Level.DEBUG, config3.first.configValue) assertEquals(config4.second, LogLevelConfig.Level.DEBUG, config4.first.configValue) } @Test fun testInfoConfig() { val config1 = Pair(LogLevelConfig("i"), "lower case single letter") val config2 = Pair(LogLevelConfig("I"), "upper case single letter") val config3 = Pair(LogLevelConfig("info"), "lower case word") val config4 = Pair(LogLevelConfig("INFO"), "upper case word") assertEquals(config1.second, LogLevelConfig.Level.INFO, config1.first.configValue) assertEquals(config2.second, LogLevelConfig.Level.INFO, config2.first.configValue) assertEquals(config3.second, LogLevelConfig.Level.INFO, config3.first.configValue) assertEquals(config4.second, LogLevelConfig.Level.INFO, config4.first.configValue) } @Test fun testWarningConfig() { val config1 = Pair(LogLevelConfig("w"), "lower case single letter") val config2 = Pair(LogLevelConfig("W"), "upper case single letter") val config3 = Pair(LogLevelConfig("warning"), "lower case word") val config4 = Pair(LogLevelConfig("WARNING"), "upper case word") assertEquals(config1.second, LogLevelConfig.Level.WARNING, config1.first.configValue) assertEquals(config2.second, LogLevelConfig.Level.WARNING, config2.first.configValue) assertEquals(config3.second, LogLevelConfig.Level.WARNING, config3.first.configValue) assertEquals(config4.second, LogLevelConfig.Level.WARNING, config4.first.configValue) } @Test fun testErrorConfig() { val config1 = Pair(LogLevelConfig("e"), "lower case single letter") val config2 = Pair(LogLevelConfig("E"), "upper case single letter") val config3 = Pair(LogLevelConfig("error"), "lower case word") val config4 = Pair(LogLevelConfig("ERROR"), "upper case word") assertEquals(config1.second, LogLevelConfig.Level.ERROR, config1.first.configValue) assertEquals(config2.second, LogLevelConfig.Level.ERROR, config2.first.configValue) assertEquals(config3.second, LogLevelConfig.Level.ERROR, config3.first.configValue) assertEquals(config4.second, LogLevelConfig.Level.ERROR, config4.first.configValue) } @Test fun testInvalidConfig() { val config1 = Pair(LogLevelConfig(""), "empty") val config2 = Pair(LogLevelConfig("4"), "invalid char") val config3 = Pair(LogLevelConfig("invalid"), "invalid word") val config4 = Pair(LogLevelConfig("INVALID"), "upper case word") assertEquals(config1.second, LogLevelConfig.DEFAULT_LEVEL, config1.first.configValue) assertEquals(config2.second, LogLevelConfig.DEFAULT_LEVEL, config2.first.configValue) assertEquals(config3.second, LogLevelConfig.DEFAULT_LEVEL, config3.first.configValue) assertEquals(config4.second, LogLevelConfig.DEFAULT_LEVEL, config4.first.configValue) } }
2
null
5
8
0926a68d59fefff60c57a8637a35378695c8983e
4,371
LogViewer
MIT License
app/src/main/java/com/hxbreak/animalcrossingtools/adapter/LightAdapter.kt
HxBreak
268,269,758
false
null
package com.hxbreak.animalcrossingtools.adapter import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import java.lang.IllegalStateException interface ItemComparable<T>{ fun id(): T } internal class PlaceHolderViewBinder : ItemViewDelegate<Any, PlaceHolderViewBinder.PlaceHolderViewHolder>{ override fun onCreateViewHolder(parent: ViewGroup): PlaceHolderViewHolder { return PlaceHolderViewHolder( LayoutInflater.from(parent.context) .inflate(android.R.layout.simple_list_item_1, parent, false)) } override fun onBindViewHolder(data: Any?, vh: PlaceHolderViewHolder) { vh.view.findViewById<TextView>(android.R.id.text1).text = "PlaceHolder" } class PlaceHolderViewHolder(val view: View): RecyclerView.ViewHolder(view) } class PlaceHolder data class ViewItemRelation( val clazz: Class<*>, val delegate: ItemViewDelegate<Any, RecyclerView.ViewHolder> ) interface ItemViewDelegate<T, VH: RecyclerView.ViewHolder>{ fun onCreateViewHolder(parent: ViewGroup): VH fun onBindViewHolder(data: T?, vh: VH) } internal object DefaultItemComparableDiffUtil : DiffUtil.ItemCallback<ItemComparable<*>>() { override fun areItemsTheSame( oldItem: ItemComparable<*>, newItem: ItemComparable<*> ): Boolean { return oldItem.id() == newItem.id() } override fun areContentsTheSame( oldItem: ItemComparable<*>, newItem: ItemComparable<*> ): Boolean { return oldItem.equals(newItem) } } object CommonItemComparableDiffUtil : DiffUtil.ItemCallback<Any>() { override fun areItemsTheSame(oldItem: Any, newItem: Any): Boolean { if(oldItem is ItemComparable<*> && newItem is ItemComparable<*>){ return (oldItem.javaClass == newItem.javaClass && oldItem.id() == newItem.id()) } return false } @SuppressLint("DiffUtilEquals") override fun areContentsTheSame(oldItem: Any, newItem: Any): Boolean { return oldItem == newItem } } class Typer { private val indexer = mutableListOf<ViewItemRelation>() fun register(clazz: Class<*>, delegate: ItemViewDelegate<*, out RecyclerView.ViewHolder>){ @Suppress("UNCHECKED_CAST") indexer.add(ViewItemRelation(clazz, delegate as ItemViewDelegate<Any, RecyclerView.ViewHolder>)) } inline fun <reified T : ItemComparable<*>> register(delegate: ItemViewDelegate<T, out RecyclerView.ViewHolder>){ register(T::class.java, delegate) } operator fun get(index: Int) = indexer[index] fun indexOfFirst(predicate: (ViewItemRelation) -> Boolean): Int { return indexer.indexOfFirst(predicate) } } class LightAdapter(val typer: Typer = Typer(), diffCallback: DiffUtil.ItemCallback<ItemComparable<*>> = DefaultItemComparableDiffUtil): ListAdapter<ItemComparable<*>, RecyclerView.ViewHolder>(diffCallback) { init { register(PlaceHolder::class.java, PlaceHolderViewBinder()) } fun register(clazz: Class<*>, delegate: ItemViewDelegate<*, out RecyclerView.ViewHolder>){ typer.register(clazz, delegate) } inline fun <reified T : ItemComparable<*>> register(delegate: ItemViewDelegate<T, out RecyclerView.ViewHolder>){ typer.register(T::class.java, delegate) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { typer[getItemViewType(position)].delegate.onBindViewHolder(getItem(position) as Any?, holder) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return typer[viewType].delegate.onCreateViewHolder(parent) } override fun getItemViewType(position: Int): Int { return indexViewType(position) } private fun indexViewType(position: Int): Int { val clazz = getItem(position)?.javaClass ?: PlaceHolder::class.java val index = typer.indexOfFirst { it.clazz.isAssignableFrom(clazz) } if (index > -1){ return index } throw IllegalStateException("viewType cannot locate class:$clazz") } } //class PagingLightAdapter: PagingDataAdapter<ItemComparable<*>, RecyclerView.ViewHolder> { // // constructor(diffCallback: DiffUtil.ItemCallback<ItemComparable<*>> = DefaultItemComparableDiffUtil) : super(diffCallback) {} // // private val indexer = mutableListOf<ViewItemRelation>() // // init { // register(PlaceHolder::class.java, PlaceHolderViewBinder()) // } // // fun register(clazz: Class<*>, delegate: ItemViewDelegate<*, out RecyclerView.ViewHolder>){ // @Suppress("UNCHECKED_CAST") // indexer.add(ViewItemRelation(clazz, delegate as ItemViewDelegate<Any, RecyclerView.ViewHolder>)) // } // // inline fun <reified T : ItemComparable<*>> register(delegate: ItemViewDelegate<T, out RecyclerView.ViewHolder>){ // register(T::class.java, delegate) // } // // override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { // indexer[getItemViewType(position)].delegate.onBindViewHolder(getItem(position) as Any?, holder) // } // // override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { // return indexer[viewType].delegate.onCreateViewHolder(parent) // } // // override fun getItemViewType(position: Int): Int { // return indexViewType(position) // } // // private fun indexViewType(position: Int): Int { // val clazz = getItem(position)?.javaClass ?: PlaceHolder::class.java // val index = indexer.indexOfFirst { it.clazz.isAssignableFrom(clazz) } // if (index > -1){ // return index // } // throw IllegalStateException("viewType cannot locate class:$clazz") // } // // fun all() = (0 until itemCount).map { getItem(it) } // //}
0
Kotlin
1
6
ced2cb55e8d6c33da4678b48957428c593c95dbe
6,148
AnimalCrossingTools-Android
MIT License
one.lfa.updater.inventory.api/src/main/java/one/lfa/updater/inventory/api/InventoryEvent.kt
AULFA
189,855,520
false
null
package one.lfa.updater.inventory.api import java.util.UUID sealed class InventoryEvent { object InventoryStateChanged : InventoryEvent() sealed class InventoryRepositoryEvent : InventoryEvent() { abstract val repositoryId: UUID sealed class InventoryRepositoryItemEvent : InventoryRepositoryEvent() { abstract val itemId: String data class ItemBecameVisible( override val repositoryId: UUID, override val itemId: String) : InventoryRepositoryItemEvent() data class ItemChanged( override val repositoryId: UUID, override val itemId: String) : InventoryRepositoryItemEvent() data class ItemBecameInvisible( override val repositoryId: UUID, override val itemId: String) : InventoryRepositoryItemEvent() } data class RepositoryChanged( override val repositoryId: UUID) : InventoryRepositoryEvent() } }
2
null
1
1
5cde488e4e9f9e60f5737d9e1a8fc8817f6b22a8
940
updater
Apache License 2.0
app/src/main/java/inoxoft/simon/shop/model/cash/CashDatabase.kt
Sighmore
872,072,217
false
{"Kotlin": 22850}
package inoxoft.simon.shop.model.cash import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [Record::class], version = 1) abstract class CashDatabase : RoomDatabase(){ abstract val dao: CashDao }
0
Kotlin
0
0
2670e304a51282f79134e01ad53253c321b72e62
234
Rizz-Shop
MIT License
src/main/kotlin/no/nav/hjelpemidler/service/oebsdatabase/HjelpemiddeloversiktDao.kt
navikt
371,349,324
false
null
package no.nav.hjelpemidler.service.oebsdatabase import kotlinx.coroutines.runBlocking import kotliquery.queryOf import kotliquery.sessionOf import no.nav.hjelpemidler.client.hmdb.HjelpemiddeldatabaseClient import no.nav.hjelpemidler.client.hmdb.hentprodukter.Produkt import no.nav.hjelpemidler.configuration.Configuration import no.nav.hjelpemidler.models.HjelpemiddelBruker import no.nav.hjelpemidler.models.Utlån import org.intellij.lang.annotations.Language import org.slf4j.LoggerFactory import javax.sql.DataSource class HjelpemiddeloversiktDao(private val dataSource: DataSource = Configuration.dataSource) { fun hentHjelpemiddeloversikt(fnr: String): List<HjelpemiddelBruker> { @Language("OracleSQL") val query = """ SELECT ANTALL, ENHET, KATEGORI3_BESKRIVELSE, ARTIKKEL_BESKRIVELSE, ARTIKKELNUMMER, SERIE_NUMMER, UTLÅNS_DATO, ORDRE_NUMMER, KATEGORI3_NUMMER, ARTIKKELSTATUS FROM XXRTV_DIGIHOT_HJM_UTLAN_FNR_V WHERE FNR = ? ORDER BY UTLÅNS_DATO DESC """.trimIndent() val items = sessionOf(dataSource).use { it.run( queryOf(query, fnr).map { row -> HjelpemiddelBruker( antall = row.string("ANTALL"), antallEnhet = row.string("ENHET"), kategoriNummer = row.string("KATEGORI3_NUMMER"), kategori = row.string("KATEGORI3_BESKRIVELSE"), artikkelBeskrivelse = row.string("ARTIKKEL_BESKRIVELSE"), artikkelNr = row.string("ARTIKKELNUMMER"), serieNr = row.stringOrNull("SERIE_NUMMER"), datoUtsendelse = row.string("UTLÅNS_DATO"), ordrenummer = row.stringOrNull("ORDRE_NUMMER"), artikkelStatus = row.string("ARTIKKELSTATUS") ) }.asList ) } return berikOrdrelinjer(items) } fun utlånPåIsokode(fnr: String, isokode: String): List<UtlånPåIsokode> { @Language("OracleSQL") val query = """ SELECT KATEGORI3_NUMMER, UTLÅNS_DATO FROM XXRTV_DIGIHOT_HJM_UTLAN_FNR_V WHERE FNR = ? AND KATEGORI3_NUMMER = ? ORDER BY UTLÅNS_DATO DESC """.trimIndent() val items = sessionOf(dataSource).use { it.run( queryOf(query, fnr, isokode).map { row -> UtlånPåIsokode( kategoriNummer = row.string("KATEGORI3_NUMMER"), datoUtsendelse = row.string("UTLÅNS_DATO") ) }.asList ) } return items } fun utlånPåArtnrOgSerienr(artnr: String, serienr: String): Utlån? { @Language("OracleSQL") val query = """ SELECT FNR, ARTIKKELNUMMER, SERIE_NUMMER, UTLÅNS_DATO FROM XXRTV_DIGIHOT_HJM_UTLAN_FNR_V WHERE ARTIKKELNUMMER = ? AND SERIE_NUMMER = ? ORDER BY UTLÅNS_DATO DESC """.trimIndent() val item = sessionOf(dataSource).use { it.run( queryOf(query, artnr, serienr).map { row -> Utlån( fnr = row.string("FNR"), artnr = row.string("ARTIKKELNUMMER"), serienr = row.string("SERIE_NUMMER"), utlånsDato = row.string("UTLÅNS_DATO") ) }.asSingle ) } return item } data class UtlånPåIsokode( val kategoriNummer: String, val datoUtsendelse: String ) private fun berikOrdrelinjer(items: List<HjelpemiddelBruker>): List<HjelpemiddelBruker> = runBlocking { // Unique set of hmsnr to fetch data for val hmsnr = items.filter { it.artikkelNr.isNotEmpty() }.map { it.artikkelNr }.toSet() // Fetch data for hmsnr from hm-grunndata-api val produkter: List<Produkt> = HjelpemiddeldatabaseClient.hentProdukter(hmsnr) // Apply data to items val produkterByHmsnr = produkter.groupBy { it.hmsnr } items.map { item -> val produkt = produkterByHmsnr[item.artikkelNr]?.firstOrNull() if (produkt == null) { item } else { berikOrdrelinje(item, produkt) } } } private fun berikOrdrelinje(item: HjelpemiddelBruker, produkt: Produkt): HjelpemiddelBruker { item.apply { item.hmdbBeriket = true item.hmdbProduktNavn = produkt.artikkelnavn item.hmdbBeskrivelse = produkt.produktbeskrivelse item.hmdbKategori = produkt.isotittel item.hmdbBilde = produkt.blobUrlLite item.hmdbURL = produkt.artikkelUrl item.hmdbKategoriKortnavn = produkt.isokortnavn } return item } companion object { private val log = LoggerFactory.getLogger("HjelpemiddeloversiktDao") } }
1
Kotlin
0
0
f69d717d1cec837d3a815d8f4036880e5626cd65
5,185
hm-oebs-api-proxy
MIT License
library/kotlin/src/io/envoyproxy/envoymobile/RequestMapper.kt
alashow
215,869,809
false
null
package io.envoyproxy.envoymobile internal fun Request.outboundHeaders(): Map<String, List<String>> { val retryPolicyHeaders = retryPolicy?.outboundHeaders() ?: emptyMap() val result = mutableMapOf<String, List<String>>() result.putAll(headers.filter { entry -> !entry.key.startsWith(":") && !entry.key.startsWith("x-envoy-mobile")}) result.putAll(retryPolicyHeaders) result[":method"] = listOf(method.stringValue()) result[":scheme"] = listOf(scheme) result[":authority"] = listOf(authority) result[":path"] = listOf(path) if (upstreamHttpProtocol != null) { result["x-envoy-mobile-upstream-protocol"] = listOf(upstreamHttpProtocol.stringValue) } return result } private fun RequestMethod.stringValue(): String { return when (this) { RequestMethod.DELETE -> "DELETE" RequestMethod.GET -> "GET" RequestMethod.HEAD -> "HEAD" RequestMethod.OPTIONS -> "OPTIONS" RequestMethod.PATCH -> "PATCH" RequestMethod.POST -> "POST" RequestMethod.PUT -> "PUT" RequestMethod.TRACE -> "TRACE" } }
1
null
2
1
9c7a1839f8196211af20f7f86cdb80872f719856
1,048
envoy-mobile
Apache License 2.0
shuttle/predictions/domain/src/main/kotlin/shuttle/predictions/domain/usecase/ObserveSuggestedApps.kt
fardavide
462,194,990
false
null
package shuttle.predictions.domain.usecase import arrow.core.Either import arrow.core.left import arrow.core.right import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import shuttle.apps.domain.model.SuggestedAppModel import shuttle.coordinates.domain.model.fold import shuttle.coordinates.domain.usecase.ObserveCurrentCoordinates import shuttle.predictions.domain.error.ObserveSuggestedAppsError class ObserveSuggestedApps( private val observeCurrentCoordinates: ObserveCurrentCoordinates, private val observeSuggestedApps: ObserveSuggestedAppsByCoordinates ) { operator fun invoke(): Flow<Either<ObserveSuggestedAppsError, List<SuggestedAppModel>>> = observeCurrentCoordinates().flatMapLatest { coordinatesResult -> coordinatesResult.fold( ifLeft = { flowOf(ObserveSuggestedAppsError.LocationNotAvailable.left()) }, ifRight = { coordinates -> observeSuggestedApps(coordinates).map { it.right() } } ) } }
14
Kotlin
1
14
ce2910eae0ec07880184628e2b2cc34e09da3ab2
1,096
Shuttle
Apache License 2.0
apps/etterlatte-brev-api/src/main/kotlin/no/nav/etterlatte/brev/behandling/SakOgBehandlingService.kt
navikt
417,041,535
false
null
package no.nav.etterlatte.brev.behandling import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import no.nav.etterlatte.brev.behandlingklient.BehandlingKlient import no.nav.etterlatte.brev.beregning.BeregningKlient import no.nav.etterlatte.brev.grunnlag.GrunnlagKlient import no.nav.etterlatte.brev.vedtak.VedtaksvurderingKlient import no.nav.etterlatte.libs.common.behandling.SakType import no.nav.etterlatte.libs.common.grunnlag.Grunnlag import no.nav.etterlatte.libs.common.sak.Sak import no.nav.etterlatte.libs.common.vedtak.VedtakDto import no.nav.etterlatte.libs.common.vedtak.VedtakType import no.nav.etterlatte.token.BrukerTokenInfo import no.nav.pensjon.brevbaker.api.model.Kroner import java.time.LocalDate import java.time.YearMonth import java.util.* class SakOgBehandlingService( private val vedtaksvurderingKlient: VedtaksvurderingKlient, private val grunnlagKlient: GrunnlagKlient, private val beregningKlient: BeregningKlient, private val behandlingKlient: BehandlingKlient ) { suspend fun hentSak(sakId: Long, bruker: BrukerTokenInfo) = behandlingKlient.hentSak(sakId, bruker) suspend fun hentSoeker(sakId: Long, bruker: BrukerTokenInfo): Soeker = grunnlagKlient.hentGrunnlag(sakId, bruker) .mapSoeker() suspend fun hentBehandling( sakId: Long, behandlingId: UUID, brukerTokenInfo: BrukerTokenInfo ): Behandling = coroutineScope { val vedtak = async { vedtaksvurderingKlient.hentVedtak(behandlingId, brukerTokenInfo) } val grunnlag = async { grunnlagKlient.hentGrunnlag(sakId, brukerTokenInfo) } val sak = async { behandlingKlient.hentSak(sakId, brukerTokenInfo) } val innvilgelsesdato = { async { vedtaksvurderingKlient.hentInnvilgelsesdato(sakId, brukerTokenInfo) } } mapBehandling( vedtak.await(), grunnlag.await(), sak.await(), innvilgelsesdato, brukerTokenInfo ) } private suspend fun mapBehandling( vedtak: VedtakDto, grunnlag: Grunnlag, sak: Sak, innvilgelsesdato: () -> Deferred<LocalDate?>, brukerTokenInfo: BrukerTokenInfo ): Behandling { val innloggetSaksbehandlerIdent = brukerTokenInfo.ident() val ansvarligEnhet = vedtak.vedtakFattet?.ansvarligEnhet ?: sak.enhet val saksbehandlerIdent = vedtak.vedtakFattet?.ansvarligSaksbehandler ?: innloggetSaksbehandlerIdent val attestantIdent = vedtak.vedtakFattet?.let { vedtak.attestasjon?.attestant ?: innloggetSaksbehandlerIdent } val datoInnvilgelse = if (vedtak.behandling.revurderingInfo != null) { innvilgelsesdato().await() } else { null } return Behandling( sakId = vedtak.sak.id, sakType = vedtak.sak.sakType, behandlingId = vedtak.behandling.id, spraak = grunnlag.mapSpraak(), persongalleri = Persongalleri( innsender = grunnlag.mapInnsender(), soeker = grunnlag.mapSoeker(), avdoed = grunnlag.mapAvdoed(), // TODO: Avdød kan potensielt være liste (begge foreldre døde). verge = grunnlag.mapVerge(vedtak.sak.sakType) ), vedtak = ForenkletVedtak( vedtak.vedtakId, vedtak.status, vedtak.type, ansvarligEnhet, saksbehandlerIdent, attestantIdent ), utbetalingsinfo = finnUtbetalingsinfo(vedtak.behandling.id, vedtak.virkningstidspunkt, brukerTokenInfo), avkortingsinfo = finnYtelseMedGrunnlag( vedtak.behandling.id, vedtak.sak.sakType, vedtak.virkningstidspunkt, vedtak.type, brukerTokenInfo ), revurderingsaarsak = vedtak.behandling.revurderingsaarsak, revurderingInfo = vedtak.behandling.revurderingInfo, virkningsdato = vedtak.virkningstidspunkt, innvilgelsesdato = datoInnvilgelse ) } private suspend fun finnUtbetalingsinfo( behandlingId: UUID, virkningstidspunkt: YearMonth, brukerTokenInfo: BrukerTokenInfo ): Utbetalingsinfo { val beregning = beregningKlient.hentBeregning(behandlingId, brukerTokenInfo) val beregningsperioder = beregning.beregningsperioder.map { Beregningsperiode( datoFOM = it.datoFOM.atDay(1), datoTOM = it.datoTOM?.atEndOfMonth(), grunnbeloep = Kroner(it.grunnbelop), antallBarn = (it.soeskenFlokk?.size ?: 0) + 1, // Legger til 1 pga at beregning fjerner soeker utbetaltBeloep = Kroner(it.utbetaltBeloep), trygdetid = it.trygdetid ) } val soeskenjustering = beregning.beregningsperioder.any { !it.soeskenFlokk.isNullOrEmpty() } val antallBarn = if (soeskenjustering) beregningsperioder.last().antallBarn else 1 return Utbetalingsinfo( antallBarn, Kroner(beregningsperioder.hentUtbetaltBeloep()), virkningstidspunkt.atDay(1), soeskenjustering, beregningsperioder ) } private suspend fun finnYtelseMedGrunnlag( behandlingId: UUID, sakType: SakType, virkningstidspunkt: YearMonth, vedtakType: VedtakType, brukerTokenInfo: BrukerTokenInfo ): Avkortingsinfo? { // TODO: Fjern sjekken når avkorting støttes for barnepensjon if (sakType == SakType.BARNEPENSJON || vedtakType == VedtakType.OPPHOER) return null val ytelseMedGrunnlag = beregningKlient.hentYtelseMedGrunnlag(behandlingId, brukerTokenInfo) val beregningsperioder = ytelseMedGrunnlag.perioder.map { AvkortetBeregningsperiode( datoFOM = it.periode.fom.atDay(1), datoTOM = it.periode.tom?.atEndOfMonth(), inntekt = Kroner(it.aarsinntekt - it.fratrekkInnAar), utbetaltBeloep = Kroner(it.ytelseEtterAvkorting) ) } val aarsInntekt = ytelseMedGrunnlag.perioder.first().aarsinntekt val grunnbeloep = ytelseMedGrunnlag.perioder.first().grunnbelop return Avkortingsinfo( grunnbeloep = Kroner(grunnbeloep), inntekt = Kroner(aarsInntekt), virkningsdato = virkningstidspunkt.atDay(1), beregningsperioder ) } }
8
Kotlin
0
3
5c79aa753584026a360f097f449e677e2f125759
6,630
pensjon-etterlatte-saksbehandling
MIT License
accsaber-api/src/main/kotlin/de/ixsen/accsaber/api/controllers/staff/CurveController.kt
accsaber
317,599,110
false
{"Kotlin": 122506, "Shell": 37}
package de.ixsen.accsaber.api.controllers.staff import de.ixsen.accsaber.api.dtos.staff.CurveDto import de.ixsen.accsaber.business.staff.CurveService import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* /** * Disabled for prod environment, needs to be enabled via config */ @RestController @RequestMapping("curve") @ConditionalOnExpression("\${accsaber.enable-curve-query}") class CurveController( private val curveService: CurveService ) { @PostMapping fun saveNewCurve(@RequestBody curveDto: CurveDto): ResponseEntity<Any> { this.curveService.saveNewCurve(curveDto.curve) return ResponseEntity.noContent().build() } @DeleteMapping fun resetCurve(@RequestBody curveDto: CurveDto): ResponseEntity<Any> { this.curveService.resetCurve() return ResponseEntity.noContent().build() } }
3
Kotlin
0
3
380ee6537cf0d355b6a896544d4c65dc387214d0
970
accsaber-backend
MIT License
src/test/kotlin/no/nav/hm/grunndata/register/iso/IsoCategoryRegistrationRepositoryTest.kt
navikt
572,421,718
false
{"Kotlin": 358035, "Dockerfile": 113, "Shell": 111}
package no.nav.hm.grunndata.register.iso import io.kotest.common.runBlocking import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import io.micronaut.test.extensions.junit5.annotation.MicronautTest import no.nav.hm.grunndata.register.REGISTER import org.junit.jupiter.api.Test @MicronautTest class IsoCategoryRegistrationRepositoryTest(private val isoCategoryRepository: IsoCategoryRegistrationRepository) { @Test fun testCrudIsoCategory() { val testCategory = IsoCategoryRegistration( isoCode ="30300001", isoLevel = 4, isoTitle = "Hjelpemidler for røyking", isoTextShort = "Hjelpemidler for røyking", isoText = "Hjelpemidler som gjør det mulig for en person å røyke. Omfatter f.eks tilpassede askebegre, lightere og sigarettholdere. Smekker og forklær, se 09 03 39", isoTranslations = IsoTranslations(titleEn = "English title", textEn = "English text"), isActive = true, showTech = true, allowMulti = true, createdByUser = "tester", updatedByUser = "tester", ) runBlocking { val saved = isoCategoryRepository.save(testCategory) saved.shouldNotBeNull() val read = isoCategoryRepository.findById("30300001") read.shouldNotBeNull() read.isoLevel shouldBe testCategory.isoLevel read.isoTitle shouldBe testCategory.isoTitle read.isoText shouldBe testCategory.isoText read.isActive shouldBe testCategory.isActive read.showTech shouldBe testCategory.showTech read.allowMulti shouldBe testCategory.allowMulti read.isoTranslations.titleEn shouldBe testCategory.isoTranslations.titleEn read.isoTranslations.textEn shouldBe testCategory.isoTranslations.textEn read.updated.shouldNotBeNull() read.created.shouldNotBeNull() read.updatedBy shouldBe REGISTER read.createdBy shouldBe REGISTER read.updatedByUser shouldBe "tester" read.createdByUser shouldBe "tester" } } }
0
Kotlin
0
2
66033b2f39c3bda7b1768b516e75b7976fd7adb1
2,185
hm-grunndata-register
MIT License
src/main/kotlin/net/voldrich/aoc2021/Day1.kt
MavoCz
434,703,997
false
{"Kotlin": 116214}
package net.voldrich.aoc2021 import net.voldrich.BaseDay // https://adventofcode.com/2021/day/1 fun main() { Day1().run() } class Day1 : BaseDay() { private val elevations: IntArray = input.lines() .map { it.toInt() } .toIntArray() override fun task1() : Int { var incrementCount = 0 for (i in 1 until elevations.size) { if (elevations[i-1] < elevations[i]) { incrementCount++ } } return incrementCount } override fun task2() : Int { var incrementCount = 0 var lastAggregatedElevation = getAggregate(elevations,0) for (i in 1 until elevations.size - 2) { val elev = getAggregate(elevations, i) if (lastAggregatedElevation < elev) { incrementCount++ } lastAggregatedElevation = elev } return incrementCount } private fun getAggregate(elevations: IntArray, i: Int) = elevations[i] + elevations[i+1] + elevations[i+2] }
0
Kotlin
0
0
8a1472434f78b01a7ca6eaf8e312d3371f13b1c8
1,049
advent-of-code
Apache License 2.0
feature/profile/domain/src/main/java/com/montfel/pokfinder/feature/profile/domain/model/HatchCounter.kt
Montfel
489,497,209
false
{"Kotlin": 179677}
package com.montfel.pokfinder.feature.profile.domain.model data class HatchCounter( val cycles: Int?, val steps: Int? )
24
Kotlin
1
10
9eaa88c7c1c049e180e6097a9ad28a69fecd4c62
129
pokfinder
MIT License
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/reader/Decoder.kt
hazuki0x0
84,384,224
false
{"Gradle": 19, "Markdown": 5, "Java Properties": 3, "Shell": 1, "Text": 5, "Ignore List": 17, "Batchfile": 1, "EditorConfig": 1, "Proguard": 16, "Java": 172, "XML": 519, "Kotlin": 613, "YAML": 1, "HTML": 16, "CSS": 6, "JavaScript": 5, "Gradle Kotlin DSL": 1, "JSON": 91, "INI": 1}
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.legacy.reader import android.content.Context import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.os.Build import android.text.Html import android.text.Spanned import android.text.TextUtils import android.webkit.WebSettings import jp.hazuki.yuzubrowser.core.utility.log.Logger import jp.hazuki.yuzubrowser.core.utility.utils.ImageUtils import jp.hazuki.yuzubrowser.download.getImage import jp.hazuki.yuzubrowser.legacy.reader.snacktory.HtmlFetcher import okhttp3.OkHttpClient import java.util.* fun OkHttpClient.decodeToReaderData(context: Context, url: String, userAgent: String?): ReaderData? { val fetcher = HtmlFetcher() if (userAgent.isNullOrEmpty()) { fetcher.userAgent = WebSettings.getDefaultUserAgent(context) } else { fetcher.userAgent = userAgent } fetcher.referrer = url val locale = Locale.getDefault() val language = locale.language + "-" + locale.country if (language.length >= 5) { fetcher.language = language } try { val result = fetcher.fetchAndExtract(this, url, 2500, true) if (!TextUtils.isEmpty(result.text)) { val html: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(result.text, Html.FROM_HTML_MODE_LEGACY, Html.ImageGetter { getImage(context, it, url, userAgent) }, null) } else { @Suppress("DEPRECATION") Html.fromHtml(result.text, Html.ImageGetter { getImage(context, it, url, userAgent) }, null) } return ReaderData(result.title, html) } } catch (e: Exception) { e.printStackTrace() } catch (e: OutOfMemoryError) { System.gc() Logger.w("reader", e, "Out of memory") } return null } private fun OkHttpClient.getImage(context: Context, imageUrl: String, url: String, userAgent: String?): Drawable { val drawable = ImageUtils.getDrawable(context, getImage(imageUrl, userAgent, url)) return drawable ?: ColorDrawable(0) }
115
Kotlin
95
301
6a867f406b7fc6b29f1899c7ca622e7ce75fafa0
2,696
YuzuBrowser
Apache License 2.0
chazm-api/src/main/kotlin/runtimemodels/chazm/api/relation/Needs.kt
RuntimeModels
32,474,965
false
{"Git Config": 1, "Gradle Kotlin DSL": 4, "Gradle": 5, "Markdown": 4, "INI": 3, "YAML": 4, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "XML": 23, "Kotlin": 156, "Java": 15}
package runtimemodels.chazm.api.relation import runtimemodels.chazm.api.entity.Attribute import runtimemodels.chazm.api.entity.Role import runtimemodels.chazm.api.organization.Organization /** * The [Needs] interface defines a needs relation, where a [Role] needs an [Attribute], of an [Organization]. * * @author <NAME> * @since 7.0.0 */ interface Needs { /** * The [Role] of this [Needs]. */ val role: Role /** * The [Attribute] of this [Needs]. */ val attribute: Attribute }
7
null
1
1
e64c35dbd0a11a0f3759305e1cae4b2b593005c8
522
chazm
Apache License 2.0
serialization/src/commonMain/kotlin/nl/adaptivity/xmlutil/serialization/XMLDecoder.kt
Xfel
216,806,374
true
{"Kotlin": 553019, "Java": 81}
/* * Copyright (c) 2018. * * This file is part of XmlUtil. * * This file is licenced to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You should have received a copy of the license with the source distribution. * Alternatively, 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 nl.adaptivity.xmlutil.serialization import kotlinx.serialization.* import kotlinx.serialization.internal.EnumDescriptor import kotlinx.serialization.modules.SerialModule import nl.adaptivity.xmlutil.* import nl.adaptivity.xmlutil.core.impl.multiplatform.assert import nl.adaptivity.xmlutil.serialization.canary.Canary import nl.adaptivity.xmlutil.serialization.canary.ExtSerialDescriptor import nl.adaptivity.xmlutil.serialization.canary.PolymorphicParentDescriptor import nl.adaptivity.xmlutil.serialization.canary.getSafeElementDescriptor import nl.adaptivity.xmlutil.serialization.impl.ChildCollector import nl.adaptivity.xmlutil.util.CompactFragment import kotlin.collections.set internal open class XmlDecoderBase internal constructor( context: SerialModule, config: XmlConfig, val input: XmlReader ) : XmlCodecBase(context, config) { var skipRead = false internal open inner class XmlDecoder( parentNamespace: Namespace, parentDesc: SerialDescriptor, elementIndex: Int, val deserializer: DeserializationStrategy<*>, childDesc: SerialDescriptor? = deserializer.descriptor, protected val polyInfo: PolyInfo? = null, private val attrIndex: Int = -1 ) : XmlCodec(parentNamespace, parentDesc, elementIndex, childDesc), Decoder { override val context get() = this@XmlDecoderBase.context override val updateMode: UpdateMode get() = UpdateMode.BANNED override fun decodeNotNullMark(): Boolean { // No null values unless the entire document is empty (not sure the parser is happy with it) return input.eventType != EventType.END_DOCUMENT } override fun decodeNull(): Nothing? { // We don't write nulls, so if we know that we have a null we just return it return null } override fun decodeUnit() { val position = input.locationInfo val stringContent = decodeStringImpl(true) if (stringContent != "kotlin.Unit") throw XmlParsingException(position, "Did not find kotlin.Unit where expected $stringContent") } override fun decodeBoolean(): Boolean = decodeStringImpl(true).toBoolean() override fun decodeByte(): Byte = decodeStringImpl(true).toByte() override fun decodeShort(): Short { return decodeStringImpl(true).toShort() } override fun decodeInt(): Int { return decodeStringImpl(true).toInt() } override fun decodeLong(): Long { return decodeStringImpl(true).toLong() } override fun decodeFloat(): Float { return decodeStringImpl(true).toFloat() } override fun decodeDouble(): Double { return decodeStringImpl(true).toDouble() } override fun decodeChar(): Char { return decodeStringImpl(true).single() } override fun decodeString(): String { return decodeStringImpl(false) } override fun decodeEnum(enumDescription: EnumDescriptor): Int { val name = decodeString() return enumDescription.getElementIndex(name) } private fun decodeStringImpl(defaultOverEmpty: Boolean): String { val defaultString = parentDesc.getElementAnnotations(elementIndex).firstOrNull<XmlDefault>()?.value val stringValue = if (attrIndex >= 0) { input.getAttributeValue(attrIndex) } else when (parentDesc.outputKind(elementIndex, childDesc)) { OutputKind.Element -> { // This may occur with list values. input.require(EventType.START_ELEMENT, serialName.namespaceURI, serialName.localPart) input.readSimpleElement() } OutputKind.Attribute -> throw SerializationException( "Attribute parsing without a concrete index is unsupported" ) OutputKind.Text -> input.allText() } return when { defaultOverEmpty && stringValue.isEmpty() && defaultString != null -> defaultString else -> stringValue } } override fun beginStructure(desc: SerialDescriptor, vararg typeParams: KSerializer<*>): CompositeDecoder { throw AssertionError("This should not happen as decodeSerializableValue should be called first") } override fun <T> decodeSerializableValue(deserializer: DeserializationStrategy<T>): T { val extDesc = childDesc as? ExtSerialDescriptor ?: Canary.serialDescriptor(deserializer) return deserializer.deserialize( SerialValueDecoder( parentNamespace, parentDesc, elementIndex, deserializer, extDesc, polyInfo, attrIndex ) ) } override fun <T> updateSerializableValue(deserializer: DeserializationStrategy<T>, old: T): T { val extDesc = childDesc as? ExtSerialDescriptor ?: Canary.serialDescriptor(deserializer) val oldSize = (old as? Collection<*>)?.size ?: -1 return deserializer.deserialize( SerialValueDecoder( parentNamespace, parentDesc, elementIndex, deserializer, extDesc, polyInfo, attrIndex, oldSize ) ) } } internal open inner class SerialValueDecoder( parentNamespace: Namespace, parentDesc: SerialDescriptor, elementIndex: Int, deserializer: DeserializationStrategy<*>, private val extDesc: ExtSerialDescriptor, polyInfo: PolyInfo?/* = null*/, attrIndex: Int/* = -1*/, private val nextListIndex: Int = 0 ) : XmlDecoder( parentNamespace, parentDesc, elementIndex, deserializer, extDesc, polyInfo, attrIndex ) { override fun beginStructure(desc: SerialDescriptor, vararg typeParams: KSerializer<*>): CompositeDecoder { if (extDesc.isNullable) return TagDecoder( serialName, parentNamespace, parentDesc, elementIndex, deserializer ) return when (extDesc.kind) { is PrimitiveKind -> throw AssertionError("A primitive is not a composite") StructureKind.MAP, StructureKind.CLASS -> TagDecoder(serialName, serialName.toNamespace(), parentDesc, elementIndex, deserializer) StructureKind.LIST -> { val childName = parentDesc.requestedChildName(elementIndex) if (childName != null) { NamedListDecoder( serialName, serialName.toNamespace(), parentDesc, elementIndex, deserializer, childName ) } else { AnonymousListDecoder( serialName, parentNamespace, parentDesc, elementIndex, deserializer, polyInfo, nextListIndex ) } } UnionKind.OBJECT, UnionKind.ENUM_KIND -> TagDecoder(serialName, serialName.toNamespace(), parentDesc, elementIndex, deserializer) UnionKind.SEALED, UnionKind.POLYMORPHIC -> PolymorphicDecoder( serialName, serialName.toNamespace(), parentDesc, elementIndex, deserializer, polyInfo ) } } } internal fun <T> DeserializationStrategy<T>.parseDefaultValue( parentNamespace: Namespace, desc: SerialDescriptor, index: Int, default: String, childDesc: SerialDescriptor? ): T { val decoder = XmlDecoderBase(context, config, CompactFragment(default).getXmlReader()).XmlDecoder( parentNamespace = parentNamespace, parentDesc = desc, elementIndex = index, deserializer = this, childDesc = childDesc ) return deserialize(decoder) } /** * Special class that handles null values that are not mere primitives. Nice side-effect is that XmlDefault values * are actually parsed as XML and can be complex */ internal inner class NullDecoder( parentNamespace: Namespace, parentDesc: SerialDescriptor, elementIndex: Int, deserializer: DeserializationStrategy<*>, childDesc: SerialDescriptor? = deserializer.descriptor ) : XmlDecoder(parentNamespace, parentDesc, elementIndex, deserializer, childDesc), CompositeDecoder { override fun decodeNotNullMark() = false override fun <T> decodeSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T> ): T { val default = desc.getElementAnnotations(index).firstOrNull<XmlDefault>()?.value @Suppress("UNCHECKED_CAST") return when (default) { null -> null as T else -> { val decoder = XmlDecoderBase(context, config, CompactFragment(default).getXmlReader()) .XmlDecoder( parentNamespace = parentNamespace, parentDesc = parentDesc, elementIndex = elementIndex, deserializer = deserializer, childDesc = childDesc ) deserializer.deserialize(decoder) } } } override fun beginStructure(desc: SerialDescriptor, vararg typeParams: KSerializer<*>): CompositeDecoder { return this } override fun endStructure(desc: SerialDescriptor) {} override fun decodeElementIndex(desc: SerialDescriptor): Int { return CompositeDecoder.READ_ALL // Let the reader worry about position (and only read the size: 0) } override fun <T> updateSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T>, old: T ): T = throw AssertionError("Null objects have no members") override fun decodeUnitElement(desc: SerialDescriptor, index: Int): Unit = throw AssertionError("Null objects have no members") override fun decodeBooleanElement(desc: SerialDescriptor, index: Int): Boolean = throw AssertionError("Null objects have no members") override fun decodeByteElement(desc: SerialDescriptor, index: Int): Byte = throw AssertionError("Null objects have no members") override fun decodeShortElement(desc: SerialDescriptor, index: Int): Short = throw AssertionError("Null objects have no members") override fun decodeIntElement(desc: SerialDescriptor, index: Int): Int = // Size of map/list throw AssertionError("Null objects have no members") override fun decodeCollectionSize(desc: SerialDescriptor): Int { return 0 } override fun decodeLongElement(desc: SerialDescriptor, index: Int): Long = throw AssertionError("Null objects have no members") override fun decodeFloatElement(desc: SerialDescriptor, index: Int): Float = throw AssertionError("Null objects have no members") override fun decodeDoubleElement(desc: SerialDescriptor, index: Int): Double = throw AssertionError("Null objects have no members") override fun decodeCharElement(desc: SerialDescriptor, index: Int): Char = throw AssertionError("Null objects have no members") override fun decodeStringElement(desc: SerialDescriptor, index: Int): String = throw AssertionError("Null objects have no members") override fun <T : Any> decodeNullableSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T?> ): T? { throw AssertionError("Null objects have no members") } override fun <T : Any> updateNullableSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T?>, old: T? ): T? { throw AssertionError("Null objects have no members") } } internal inner class RenamedDecoder( override val serialName: QName, parentNamespace: Namespace, parentDesc: SerialDescriptor, elementIndex: Int, deserializer: DeserializationStrategy<*>, extDesc: ExtSerialDescriptor, polyInfo: PolyInfo? = null, attrIndex: Int = Int.MIN_VALUE ) : SerialValueDecoder( parentNamespace, parentDesc, elementIndex, deserializer, extDesc, polyInfo, attrIndex ) internal open inner class TagDecoder( serialName: QName, parentNamespace: Namespace, parentDesc: SerialDescriptor, elementIndex: Int, val deserializer: DeserializationStrategy<*> ) : XmlTagCodec(parentDesc, elementIndex, Canary.serialDescriptor(deserializer), parentNamespace), CompositeDecoder, XML.XmlInput { final override val serialName: QName = serialName override val updateMode: UpdateMode get() = UpdateMode.BANNED private var nameToMembers: Map<QName, Int> private var polyChildren: Map<QName, PolyInfo> private val seenItems = BooleanArray(desc.elementsCount) private var nulledItemsIdx = -1 // We need to do this here so we can move up when reading (allowing for repeated queries for nullable values) protected var lastAttrIndex: Int = -1 private set var currentPolyInfo: PolyInfo? = null init { val polyMap: MutableMap<QName, PolyInfo> = mutableMapOf() val nameMap: MutableMap<QName, Int> = mutableMapOf() val desc = this.desc as ExtSerialDescriptor for (idx in 0 until desc.elementsCount) { desc.getElementAnnotations(idx).firstOrNull<XmlPolyChildren>().let { xmlPolyChildren -> if (xmlPolyChildren != null) { for (child in xmlPolyChildren.value) { val polyInfo = polyTagName(serialName, child, idx) polyMap[polyInfo.tagName.normalize()] = polyInfo } } else { val actualElementDesc = desc.getSafeElementDescriptor(idx) val effectiveElementDesc = when { actualElementDesc?.kind == StructureKind.LIST -> actualElementDesc.getElementDescriptor(0) else -> actualElementDesc } if (config.autoPolymorphic && effectiveElementDesc is PolymorphicParentDescriptor) { val baseClass = effectiveElementDesc.baseClass val childCollector = ChildCollector(baseClass) context.dumpTo(childCollector) if (childCollector.children.isEmpty()) { val n = desc.requestedName(serialName.toNamespace(), idx, effectiveElementDesc).normalize() nameMap[n] = idx } else { for (actualSerializer in childCollector.children) { val name = actualSerializer.descriptor.declRequestedName(serialName.toNamespace()) .normalize() polyMap[name] = PolyInfo(actualSerializer.descriptor.name, name, idx, actualSerializer) } } } else { val tagName = when (actualElementDesc?.kind) { UnionKind.SEALED, // For now sealed is treated like polymorphic. We can't enumerate elements yet. UnionKind.POLYMORPHIC -> desc.getElementName(idx).toQname(serialName.toNamespace()) else -> desc.requestedName( serialName.toNamespace(), idx, actualElementDesc ) } nameMap[tagName.normalize()] = idx } } } } polyChildren = polyMap nameToMembers = nameMap } override val input: XmlReader get() = this@XmlDecoderBase.input override val namespaceContext: NamespaceContext get() = input.namespaceContext override fun <T> decodeSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T> ): T { val decoder = when { nulledItemsIdx >= 0 -> NullDecoder(parentNamespace, desc, index, deserializer) desc.kind is PrimitiveKind -> XmlDecoder( parentNamespace, desc, index, deserializer, deserializer.descriptor, currentPolyInfo, lastAttrIndex ) else -> SerialValueDecoder( parentNamespace, desc, index, deserializer, Canary.serialDescriptor(deserializer), currentPolyInfo, lastAttrIndex ) } return deserializer.deserialize(decoder).also { seenItems[index] = true } } override fun <T : Any> decodeNullableSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T?> ): T? { val decoder = when { nulledItemsIdx >= 0 -> return null deserializer.descriptor.kind is PrimitiveKind -> XmlDecoder( parentNamespace, desc, index, deserializer, deserializer.descriptor, currentPolyInfo, lastAttrIndex ) else -> SerialValueDecoder( parentNamespace, desc, index, deserializer, Canary.serialDescriptor(deserializer), currentPolyInfo, lastAttrIndex ) } return deserializer.deserialize(decoder).also { seenItems[index] = true } } override fun <T> updateSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T>, old: T ): T { val decoder: XmlDecoder = when { nulledItemsIdx >= 0 -> NullDecoder(parentNamespace, desc, index, deserializer) desc.kind is PrimitiveKind -> XmlDecoder( parentNamespace, desc, index, deserializer, deserializer.descriptor, currentPolyInfo, lastAttrIndex ) else -> SerialValueDecoder( parentNamespace, desc, index, deserializer, Canary.serialDescriptor(deserializer), currentPolyInfo, lastAttrIndex ) } return deserializer.patch(decoder, old).also { seenItems[index] = true } } override fun <T : Any> updateNullableSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T?>, old: T? ): T? { val decoder = when { nulledItemsIdx >= 0 -> return null else -> XmlDecoder( parentNamespace, desc, index, deserializer, deserializer.descriptor, currentPolyInfo, lastAttrIndex ) } return (if (old == null) deserializer.deserialize(decoder) else deserializer.patch(decoder, old)).also { seenItems[index] = true } } open fun indexOf(name: QName, isNameOfAttr: Boolean): Int { currentPolyInfo = null val polyMap = polyChildren val nameMap = nameToMembers val normalName = name.normalize() nameMap[normalName]?.let { return it } polyMap[normalName]?.let { currentPolyInfo = it return it.index } val containingNamespaceUri = serialName.namespaceURI // Allow attributes in the null namespace to match candidates with a name that is that of the parent tag if (isNameOfAttr && name.namespaceURI.isEmpty()) { val attrName = normalName.copy(namespaceURI = containingNamespaceUri) nameMap[attrName]?.let { return it } polyMap[normalName.copy(namespaceURI = containingNamespaceUri)]?.let { return it.index } } // If the parent namespace uri is the same as the namespace uri of the element, try looking for an element // with a null namespace instead if (containingNamespaceUri.isNotEmpty() && containingNamespaceUri == name.namespaceURI) { nameMap[QName(name.getLocalPart())]?.let { return it } } // Hook that will normally throw an exception on an unknown name. config.unknownChildHandler( input, isNameOfAttr, name, (nameMap.keys + polyMap.keys) ) return CompositeDecoder.UNKNOWN_NAME // Special value to indicate the element is unknown (but possibly ignored) } override fun decodeElementIndex(desc: SerialDescriptor): Int { /* Decoding works in 3 stages: attributes, child content, null values. * Attribute decoding is finished when attrIndex<0 * child content is finished when nulledItemsIdx >=0 * Fully finished when the nulled items returns a DONE value */ if (nulledItemsIdx >= 0) { input.require(EventType.END_ELEMENT, null, null) if (nulledItemsIdx >= seenItems.size) return CompositeDecoder.READ_DONE val i = nulledItemsIdx nextNulledItemsIdx() return i } lastAttrIndex++ if (lastAttrIndex >= 0 && lastAttrIndex < input.attributeCount) { val name = input.getAttributeName(lastAttrIndex) return if (name.getNamespaceURI() == XMLConstants.XMLNS_ATTRIBUTE_NS_URI || name.prefix == XMLConstants.XMLNS_ATTRIBUTE || (name.prefix.isEmpty() && name.localPart == XMLConstants.XMLNS_ATTRIBUTE) ) { // Ignore namespace decls decodeElementIndex(desc) } else { return indexOf(name, true).ifNegative { decodeElementIndex(desc) } } } lastAttrIndex = Int.MIN_VALUE // Ensure to reset here, this should not practically get bigger than 0 if (skipRead) { // reading values will already move to the end tag. assert(input.isEndElement()) skipRead = false return readElementEnd(desc) } for (eventType in input) { if (!eventType.isIgnorable) { // The android reader doesn't check whitespaceness when (eventType) { EventType.END_ELEMENT -> return readElementEnd(desc) EventType.CDSECT, EventType.TEXT -> if (!input.isWhitespace()) return desc.getValueChild() EventType.ATTRIBUTE -> return indexOf( input.name, true ).ifNegative { decodeElementIndex(desc) } EventType.START_ELEMENT -> when (val i = indexOf(input.name, false)) { CompositeDecoder.UNKNOWN_NAME -> input.elementContentToFragment() // Create a content fragment and drop it. else -> return i } else -> throw AssertionError("Unexpected event in stream") } } } return CompositeDecoder.READ_DONE } private fun nextNulledItemsIdx() { for (i in (nulledItemsIdx + 1) until seenItems.size) { // Items that have been seen don't need to be passed as null // Items that are declared as optional, don't need to be passed as ull if (!(seenItems[i] || desc.isElementOptional(i))) { val default = desc.getElementAnnotations(i).firstOrNull<XmlDefault>() val defaultOrList = when { default != null -> true else -> { val childDesc = try { desc.getElementDescriptor(i) } catch (e: Exception) { null } val kind = childDesc?.kind // If there is no child descriptor and it is missing this can only be because it is // either a list or nullable. It can be treated as such. childDesc == null || childDesc.isNullable || when (kind) { StructureKind.LIST, StructureKind.MAP -> true else -> false } } } if (defaultOrList) { nulledItemsIdx = i return } } } nulledItemsIdx = seenItems.size } override fun endStructure(desc: SerialDescriptor) { // TODO record the tag name used to be able to validate leaving // input.require(EventType.END_ELEMENT, serialName.namespaceURI, serialName.localPart) input.require(EventType.END_ELEMENT, null, null) } open fun readElementEnd(desc: SerialDescriptor): Int { nextNulledItemsIdx() return when { nulledItemsIdx < seenItems.size -> nulledItemsIdx else -> CompositeDecoder.READ_DONE } } open fun doReadAttribute(desc: SerialDescriptor, index: Int): String { return input.getAttributeValue(lastAttrIndex) } override fun decodeStringElement(desc: SerialDescriptor, index: Int): String { seenItems[index] = true val isAttribute = lastAttrIndex >= 0 if (isAttribute) { return doReadAttribute(desc, index) } else if (nulledItemsIdx >= 0) { // Now reading nulls return desc.getElementAnnotations(index).firstOrNull<XmlDefault>()?.value ?: throw MissingFieldException("${desc.getElementName(index)}:$index") } val outputKind = desc.outputKind(index, null) return when (outputKind) { OutputKind.Element -> input.readSimpleElement() OutputKind.Text -> { skipRead = true input.allText() } OutputKind.Attribute -> error("Attributes should already be read now") } } override fun decodeIntElement(desc: SerialDescriptor, index: Int): Int { when (desc.kind) { is StructureKind.MAP, is StructureKind.LIST -> if (index == 0) { seenItems[0] = true; return 1 }// Always read a list element by element } return decodeStringElement(desc, index).toInt() } override fun decodeUnitElement(desc: SerialDescriptor, index: Int) { val location = input.locationInfo if (decodeStringElement(desc, index) != "kotlin.Unit") throw XmlParsingException( location, "Kotlin Unit not valid" ) } override fun decodeBooleanElement(desc: SerialDescriptor, index: Int): Boolean { return decodeStringElement(desc, index).toBoolean() } override fun decodeByteElement(desc: SerialDescriptor, index: Int): Byte { return decodeStringElement(desc, index).toByte() } override fun decodeShortElement(desc: SerialDescriptor, index: Int): Short { return decodeStringElement(desc, index).toShort() } override fun decodeLongElement(desc: SerialDescriptor, index: Int): Long { return decodeStringElement(desc, index).toLong() } override fun decodeFloatElement(desc: SerialDescriptor, index: Int): Float { return decodeStringElement(desc, index).toFloat() } override fun decodeDoubleElement(desc: SerialDescriptor, index: Int): Double { return decodeStringElement(desc, index).toDouble() } override fun decodeCharElement(desc: SerialDescriptor, index: Int): Char { return decodeStringElement(desc, index).single() } } internal inner class AnonymousListDecoder( serialName: QName, parentNamespace: Namespace, parentDesc: SerialDescriptor, elementIndex: Int, deserializer: DeserializationStrategy<*>, private val polyInfo: PolyInfo?, private val listIndex: Int ) : TagDecoder(serialName, parentNamespace, parentDesc, elementIndex, deserializer) { override val updateMode: UpdateMode get() = UpdateMode.UPDATE private var finished: Boolean = false override fun decodeElementIndex(desc: SerialDescriptor): Int { return when { finished -> CompositeDecoder.READ_DONE else -> { finished = true; listIndex } } } override fun <T> decodeSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T> ): T { val childName = polyInfo?.tagName ?: parentDesc.requestedChildName(elementIndex) ?: serialName // This is an anonymous list decoder. The descriptor passed here is for a list, not the xml parent element. val decoder = RenamedDecoder( childName, parentNamespace, parentDesc, elementIndex, deserializer, Canary.serialDescriptor(deserializer), polyInfo, Int.MIN_VALUE ) return deserializer.deserialize(decoder) } override fun <T> updateSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T>, old: T ): T { val childName = polyInfo?.tagName ?: parentDesc.requestedChildName(elementIndex) ?: serialName val decoder = RenamedDecoder( childName, parentNamespace, desc, index, deserializer, Canary.serialDescriptor(deserializer), polyInfo, Int.MIN_VALUE ) return deserializer.patch(decoder, old) } override fun decodeCollectionSize(desc: SerialDescriptor): Int { return 1 } } internal inner class NamedListDecoder( serialName: QName, parentNamespace: Namespace, parentDesc: SerialDescriptor, elementIndex: Int, deserializer: DeserializationStrategy<*>, private val childName: QName ) : TagDecoder(serialName, parentNamespace, parentDesc, elementIndex, deserializer) { override val updateMode: UpdateMode get() = UpdateMode.UPDATE private var childCount = 0 override fun decodeElementIndex(desc: SerialDescriptor): Int { return when (input.nextTag()) { EventType.END_ELEMENT -> CompositeDecoder.READ_DONE else -> childCount++ // This is important to ensure appending in the list. } } override fun <T> decodeSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T> ): T { val decoder = RenamedDecoder( childName, serialName.toNamespace(), desc, index, deserializer, Canary.serialDescriptor(deserializer), super.currentPolyInfo, super.lastAttrIndex ) return deserializer.deserialize(decoder) } override fun <T> updateSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T>, old: T ): T { val decoder = RenamedDecoder( childName, serialName.toNamespace(), desc, index, deserializer, Canary.serialDescriptor(deserializer), super.currentPolyInfo, super.lastAttrIndex ) return deserializer.patch(decoder, old) } } internal inner class PolymorphicDecoder( serialName: QName, parentNamespace: Namespace, parentDesc: SerialDescriptor, elementIndex: Int, deserializer: DeserializationStrategy<*>, private val polyInfo: PolyInfo? ) : TagDecoder(serialName, parentNamespace, parentDesc, elementIndex, deserializer) { private val transparent get() = polyInfo != null override fun decodeElementIndex(desc: SerialDescriptor): Int { return CompositeDecoder.READ_ALL // We don't need housekeeping this way } override fun decodeStringElement(desc: SerialDescriptor, index: Int): String { return when (index) { 0 -> when (polyInfo) { null -> input.getAttributeValue(null, "type")?.expandTypeNameIfNeeded(parentDesc.name) ?: throw XmlParsingException(input.locationInfo, "Missing type for polymorphic value") else -> polyInfo.describedName } else -> super.decodeStringElement(desc, index) } } override fun doReadAttribute(desc: SerialDescriptor, index: Int): String { return if (!transparent) { input.getAttributeValue(null, "type") ?: throw XmlParsingException(input.locationInfo, "Missing type for polymorphic value") } else { polyInfo?.describedName ?: input.name.localPart // Likely to fail unless the tagname matches the type } } override fun indexOf(name: QName, isNameOfAttr: Boolean): Int { return if (name.namespaceURI == "" && name.localPart == "type") 0 else 1 } override fun <T> decodeSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T> ): T { if (!transparent) { input.nextTag() input.require(EventType.START_ELEMENT, null, "value") } return super.decodeSerializableElement(desc, index, deserializer) } override fun <T> updateSerializableElement( desc: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T>, old: T ): T { if (!transparent) { input.nextTag() input.require(EventType.START_ELEMENT, null, "value") } return super.updateSerializableElement(desc, index, deserializer, old) } override fun endStructure(desc: SerialDescriptor) { if (!transparent) { input.nextTag() input.require(EventType.END_ELEMENT, serialName.namespaceURI, serialName.localPart) } super.endStructure(desc) } } } inline fun Int.ifNegative(body: () -> Int) = if (this >= 0) this else body()
0
null
0
0
dcdb686c02096cc5417785295e8b273f7f6b26a2
42,033
xmlutil
Apache License 2.0
concrete-sample/src/main/java/com/jaynewstrom/concretesample/details/DetailsListItemView.kt
JayNewstrom
46,246,249
false
null
package com.jaynewstrom.concretesample.details import android.content.Context import android.view.LayoutInflater import android.widget.LinearLayout import android.widget.TextView import com.jaynewstrom.concrete.Concrete import com.jaynewstrom.concretesample.R import javax.inject.Inject import javax.inject.Named class DetailsListItemView(context: Context) : LinearLayout(context) { @Inject @field:Named("detailsTitle") lateinit var detailsTitle: String private val positionTextView: TextView init { Concrete.getComponent<DetailComponent>(context).inject(this) LayoutInflater.from(context).inflate(R.layout.details_list_item, this, true) val titleTextView = findViewById<TextView>(R.id.tv_title) titleTextView.text = detailsTitle positionTextView = findViewById(R.id.tv_position) } fun setPosition(position: Int) { positionTextView.text = position.toString() } }
1
Kotlin
1
4
b9735cbf5f1d4725240cbe06a9cb8ce1eb752686
942
Concrete
Apache License 2.0
decoder/wasm/src/commonMain/kotlin/io/github/charlietap/chasm/decoder/wasm/decoder/type/result/ResultTypeDecoder.kt
CharlieTap
743,980,037
false
{"Kotlin": 1667685, "WebAssembly": 75136}
package io.github.charlietap.chasm.decoder.wasm.decoder.type.result import com.github.michaelbull.result.Result import io.github.charlietap.chasm.ast.type.ResultType import io.github.charlietap.chasm.decoder.wasm.error.WasmDecodeError import io.github.charlietap.chasm.decoder.wasm.reader.WasmBinaryReader internal typealias ResultTypeDecoder = (WasmBinaryReader) -> Result<ResultType, WasmDecodeError>
2
Kotlin
2
43
4cb170e73e120a15de6397ad24d2f23c1fae3f87
405
chasm
Apache License 2.0
app/src/main/java/com/geekymusketeers/uncrack/ui/fragments/GeneratePasswordFragment.kt
aritra-tech
569,328,395
false
null
package com.geekymusketeers.uncrack.fragments import android.content.ClipData import android.content.ClipboardManager import android.os.Bundle import androidx.fragment.app.Fragment import android.view.View import androidx.core.content.ContextCompat import com.geekymusketeers.uncrack.R import com.geekymusketeers.uncrack.databinding.FragmentGeneratePasswordBinding import com.google.android.material.slider.LabelFormatter import com.google.android.material.slider.Slider import com.google.android.material.snackbar.Snackbar import nu.aaro.gustav.passwordstrengthmeter.PasswordStrengthCalculator import java.util.* class GeneratePasswordFragment : Fragment(R.layout.fragment_generate_password) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = FragmentGeneratePasswordBinding.bind(view) var passwordLength = 13 binding.passwordInputMeter.setPasswordStrengthCalculator(object : PasswordStrengthCalculator{ override fun calculatePasswordSecurityLevel(password: String?): Int { if (password!=null){ return getPasswordScope(password) }else{ return 0 } } override fun getMinimumLength(): Int { return 1 } override fun passwordAccepted(level: Int): Boolean { return true } override fun onPasswordAccepted(password: String?) { } }) val generatedPassword = generatePassword(passwordLength, includeUpperCaseLetters = binding.cbUppercase.isChecked, includeLowerCaseLetters = binding.cbLowercase.isChecked, includeSymbols = binding.cbSymbols.isChecked, includeNumbers = binding.cbNumbers.isChecked) binding.passwordInputMeter.setEditText(binding.etGeneratedPassword) binding.etGeneratedPassword.setText(generatedPassword) binding.sliderPasswordStrength.addOnSliderTouchListener(object : Slider.OnSliderTouchListener{ override fun onStartTrackingTouch(slider: Slider) { } override fun onStopTrackingTouch(slider: Slider) { passwordLength = slider.value.toInt() } }) binding.sliderPasswordStrength.addOnChangeListener(object : Slider.OnChangeListener{ override fun onValueChange(slider: Slider, value: Float, fromUser: Boolean) { slider.setLabelFormatter(LabelFormatter { it-> return@LabelFormatter "${value.toInt()} Letters" }) } }) binding.btnGeneratePassword.setOnClickListener { val generatedPassword = generatePassword(passwordLength, includeUpperCaseLetters = binding.cbUppercase.isChecked, includeLowerCaseLetters = binding.cbLowercase.isChecked, includeSymbols = binding.cbSymbols.isChecked, includeNumbers = binding.cbNumbers.isChecked) if (generatedPassword.isBlank()){ if (passwordLength==0){ Snackbar.make(view,"Password length cannot be zero", Snackbar.LENGTH_SHORT).show() } else { Snackbar.make(view, "Please check at least one item", Snackbar.LENGTH_SHORT) .show() } }else{ binding.etGeneratedPassword.setText(generatedPassword) } } binding.btnCopyPassword.setOnClickListener { val clipboard: ClipboardManager? = ContextCompat.getSystemService( requireContext(), ClipboardManager::class.java ) val clip = ClipData.newPlainText("Generated Password", binding.etGeneratedPassword.text.toString()) clipboard?.setPrimaryClip(clip) Snackbar.make(view, "Password Copied to Clipboard", Snackbar.LENGTH_SHORT).show() } } fun<E> MutableList<E>.mRandom(): E? = if (size>0) get(Random().nextInt(size)) else null private fun generatePassword(length: Int, includeUpperCaseLetters: Boolean,includeLowerCaseLetters : Boolean, includeSymbols : Boolean, includeNumbers : Boolean): String { var password = "" val list = mutableListOf<Int>() if (includeUpperCaseLetters) list.add(0) if (includeLowerCaseLetters) list.add(1) if (includeNumbers) list.add(2) if (includeSymbols) list.add(3) for(i in 1..length){ when(list.toMutableList().mRandom()){ 0-> password += ('A'..'Z').toMutableList().mRandom().toString() 1-> password += ('a'..'z').toMutableList().mRandom().toString() 2-> password += ('0'..'9').toMutableList().mRandom().toString() 3-> password += listOf('!','@','#','$','%','&','*','+','=','-','~','?','/','_').toMutableList().mRandom().toString() } } return password } private fun getPasswordScope(password: String): Int { if(password.isEmpty() || password.isBlank()) { return 0 } else { if(password.length == 0) { return 0 } else if (password.length in 1..3) { return 1 } else if (password.length in 4..6) { return 2 } else if (password.length in 7..9) { return 3 } else if (password.length in 10..12) { return 4 } else { return 5 } } } }
0
Kotlin
0
4
0a9d09d89adfa8326f65051467bdd6f32aeaef2e
5,788
UnCrack
MIT License
app/src/main/java/com/zsoltbertalan/flickslate/data/db/UpcomingMoviesDataSource.kt
herrbert74
779,374,786
false
{"Kotlin": 227177}
package com.zsoltbertalan.flickslate.data.db import com.zsoltbertalan.flickslate.domain.model.Movie import com.zsoltbertalan.flickslate.domain.model.PageData import com.zsoltbertalan.flickslate.domain.model.PagingReply import kotlinx.coroutines.flow.Flow interface UpcomingMoviesDataSource { suspend fun purgeDatabase() suspend fun insertUpcomingMovies(movies: List<Movie>, page: Int) suspend fun insertUpcomingMoviesPageData(page: PageData) fun getUpcomingMovies(page: Int): Flow<PagingReply<Movie>?> }
1
Kotlin
2
6
26ed9b8411ad4ff512ee53ac666ac894caba9293
515
FlickSlate
Apache License 2.0
app/src/main/kotlin/com/demo/justapp/exchanger/di/application/NetModule.kt
putnik-busy
141,900,889
false
null
package com.demo.justapp.exchanger.di.application import com.demo.justapp.exchanger.data.interceptor.LoggingInterceptor import com.demo.justapp.exchanger.data.api.CurrencyRatesApi import com.google.gson.* import dagger.Module import dagger.Provides import io.reactivex.schedulers.Schedulers import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.lang.reflect.Type import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Singleton private const val BASE_URL = "https://revolut.duckdns.org/" private const val TIMEOUT = 20L @Module object NetModule { @Singleton @Provides @JvmStatic internal fun provideOkHttpClient(): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(LoggingInterceptor()) .connectTimeout(TIMEOUT, TimeUnit.SECONDS) .readTimeout(TIMEOUT, TimeUnit.SECONDS) .build() } @Singleton @Provides @JvmStatic internal fun provideRetrofit(client: OkHttpClient, gson: Gson): Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .client(client) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory .createWithScheduler(Schedulers.io())) .build() } @Singleton @Provides @JvmStatic internal fun provideGSON(): Gson { return GsonBuilder() .registerTypeAdapter(Date::class.java, DateDeserializer()) .registerTypeAdapter(Date::class.java, DateSerializer()) .create() } @Singleton @Provides @JvmStatic internal fun provideRestApi(retrofit: Retrofit): CurrencyRatesApi { return retrofit.create(CurrencyRatesApi::class.java) } private class DateSerializer : JsonSerializer<Date> { override fun serialize(src: Date, typeOfSrc: Type, context: JsonSerializationContext): JsonPrimitive { return JsonPrimitive(src.time.div(1000)) } } private class DateDeserializer : JsonDeserializer<Date> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Date { return Date(json.asLong.times(1000)) } } }
0
Kotlin
0
0
756f835ee63164bbb9832ee614f8f4be18449748
2,447
Exchanger
Apache License 2.0
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/areas/lumbridge/take_hatchet.plugin.kts
2011Scape
578,880,245
false
null
package gg.rsmod.plugins.content.areas.lumbridge val RESPAWN_DELAY = 100 on_obj_option(obj = Objs.LOGS_36974, option = "take-hatchet") { val obj = player.getInteractingGameObj() val replacementObject = DynamicObject(obj, Objs.LOGS_36975) val world = player.world if (obj.isSpawned(world)) { if (player.inventory.hasSpace) { world.remove(obj) world.queue { world.spawn(replacementObject) wait(RESPAWN_DELAY) world.remove(replacementObject) world.spawn(DynamicObject(obj)) } player.playSound(Sfx.PICK2) player.inventory.add(Item(Items.BRONZE_HATCHET, 1)) } else { player.filterableMessage("You don't have enough free inventory space to take that.") } } }
39
null
27
34
e5400cc71bfa087164153d468979c5a3abc24841
835
game
Apache License 2.0
src/main/kotlin/com/mazekine/nova/models/DepositMeta.kt
mazekine
321,032,816
false
null
package com.mazekine.nova.models import com.google.gson.annotations.Expose data class DepositMeta( @Expose val currency: String, @Expose val min: String? = null, @Expose val max: String? = null, @Expose val scale: Int? = null )
0
Kotlin
0
0
f89a7ff2669691923ea7b00312df213ada80ae09
246
nova-lib
Apache License 2.0
src/main/kotlin/br/com/zup/academy/alissonprado/handler/ErrorAroundHandler.kt
alissonkbprado
408,172,599
true
{"Kotlin": 147506}
package br.com.zup.academy.alissonprado.handler import io.micronaut.aop.Around import kotlin.annotation.AnnotationRetention.* import kotlin.annotation.AnnotationTarget.* @MustBeDocumented @Retention(RUNTIME) @Target(CLASS, FIELD, TYPE) @Around annotation class ErrorAroundHandler { }
0
Kotlin
0
0
b2d60c6f4ab309351adf20aac75048216e067872
285
orange-talents-07-template-pix-keymanager-grpc
Apache License 2.0
core/src/org/river/exertion/btree/v0_1/task_cond/IsExtAnxietyHigherCondition.kt
exertionriver
345,650,250
false
null
package org.river.exertion.btree.v0_1.task_cond; import com.badlogic.gdx.Gdx import org.river.exertion.btree.v0_1.ExecLeafCondition import org.river.exertion.btree.v0_1.IBTCharacter class IsExtAnxietyHigherCondition : ExecLeafCondition() { override fun checkCondition(): Status { statusUpdate("${isExtHigher(`object`)}") return if ( isExtHigher(`object`) ) Status.SUCCEEDED else Status.FAILED } companion object { fun isExtHigher(character : IBTCharacter) = false // placeholder for polling external manifest } }
0
Kotlin
0
2
e554d700d5fbc16953a61d782cbe63162072483a
556
koboldCave
MIT License
http4k-core/src/main/kotlin/org/http4k/websocket/websocket.kt
s4nchez
258,724,328
false
{"Shell": 17, "Gradle Kotlin DSL": 3, "Text": 12, "JSON": 5, "Markdown": 94, "Java Properties": 3, "INI": 2, "Gradle": 67, "Ignore List": 3, "Batchfile": 1, "EditorConfig": 1, "Kotlin": 932, "Java": 24, "XML": 5, "JavaScript": 9, "YAML": 11, "Handlebars": 13, "SVG": 37, "CSS": 4, "HTML": 25, "OASv3-json": 3, "HTTP": 1, "Pug": 7, "Python": 1}
package org.http4k.websocket import org.http4k.core.Body import org.http4k.core.Request import org.http4k.websocket.WsStatus.Companion.NORMAL import java.io.InputStream /** * Represents a connected Websocket instance, and can be passed around an application. This is configured * to react to events on the WS event stream by attaching listeners. */ interface Websocket { val upgradeRequest: Request fun send(message: WsMessage) fun close(status: WsStatus = NORMAL) fun onError(fn: (Throwable) -> Unit) fun onClose(fn: (WsStatus) -> Unit) fun onMessage(fn: (WsMessage) -> Unit) } typealias WsConsumer = (Websocket) -> Unit typealias WsHandler = (Request) -> WsConsumer? data class WsMessage(val body: Body) { constructor(value: String) : this(Body(value)) constructor(value: InputStream) : this(Body(value)) fun body(new: Body): WsMessage = copy(body = new) fun bodyString(): String = String(body.payload.array()) companion object }
1
null
1
1
220590204fe37a9a22723dbdc9b6cfbbcaf5f975
986
http4k
Apache License 2.0
jvm/core/src/main/kotlin/com/intuit/playerui/core/bridge/serialization/serializers/NodeSerializableField.kt
player-ui
513,673,239
false
null
package com.intuit.playerui.core.bridge.serialization.serializers import com.intuit.playerui.core.bridge.Node import com.intuit.playerui.core.bridge.NodeWrapper import com.intuit.playerui.core.bridge.serialization.format.serializer import com.intuit.playerui.core.experimental.ExperimentalPlayerApi import com.intuit.playerui.core.player.PlayerException import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PolymorphicKind import kotlinx.serialization.descriptors.StructureKind import kotlinx.serialization.serializer import kotlin.reflect.KProperty /** Delegate for automatic deserialization of [Node] values */ public class NodeSerializableField<T> private constructor( private val provider: () -> Node, private val serializer: KSerializer<T>, internal val strategy: CacheStrategy, private val name: String?, private val defaultValue: Node.(String) -> T, ) { /** Caching strategy for determining how to pull the value from [Node] on subsequent attempts */ public enum class CacheStrategy { None, Smart, Full, } /** Cache of container [Node] that will reset the [value] cache if out-of-date with the [provider] */ private var cache: Node = provider(); get() { val provided = provider() if (provided.nativeReferenceEquals(field)) { field } else { field = provided value = null } return field } /** Cache of the [T] value, along with the backing [Node] for objects */ private var value: Pair<Node?, T>? = null public operator fun getValue(thisRef: Any?, property: KProperty<*>): T { // early exit if we have a value and explicitly using the cache value?.takeIf { strategy == CacheStrategy.Full }?.let { (_, value) -> return value } val key = name ?: property.name // will reset cache and value if mismatch val node = cache // early exit if we have a value still and referentially match the backing [Node] value?.takeIf { strategy == CacheStrategy.Smart } ?.takeIf { (backing) -> backing?.nativeReferenceEquals(node[key]) == true } ?.let { (_, value) -> return value } // else get and deserialize the value return node .getSerializable(key, serializer) ?.also { value = node.getObject(key) to it } ?: node.defaultValue(key) } public companion object { /** Smart constructor responsible for determining the correct [CacheStrategy] and [defaultValue] from the [serializer], if either are not provided */ @ExperimentalPlayerApi public operator fun <T> invoke( provider: () -> Node, serializer: KSerializer<T>, strategy: CacheStrategy? = null, name: String? = null, defaultValue: (Node.(String) -> T)? = null, ): NodeSerializableField<T> = NodeSerializableField( provider, serializer, strategy ?: when (serializer.descriptor.kind) { is StructureKind, is PolymorphicKind, -> CacheStrategy.Smart else -> CacheStrategy.None }, name, defaultValue ?: { @Suppress("UNCHECKED_CAST") if (serializer.descriptor.isNullable) { null as T } else { throw throw PlayerException("""Could not deserialize "$it" as "${serializer.descriptor}"""") } }, ) /** Smart constructor to automatically determine the [KSerializer] to use for [T] */ @ExperimentalPlayerApi public inline operator fun <reified T> invoke( noinline provider: () -> Node, strategy: CacheStrategy? = null, name: String? = null, noinline defaultValue: (Node.(String) -> T)? = null, ): NodeSerializableField<T> = NodeSerializableField(provider, serializer<T>(), strategy, name, defaultValue) } } @ExperimentalPlayerApi public fun <T> NodeWrapper.NodeSerializableField( serializer: KSerializer<T>, strategy: NodeSerializableField.CacheStrategy? = null, name: String? = null, defaultValue: (Node.(String) -> T)? = null, ): NodeSerializableField<T> = NodeSerializableField(::node, serializer, strategy, name, defaultValue) @ExperimentalPlayerApi public inline fun <reified T> NodeWrapper.NodeSerializableField( strategy: NodeSerializableField.CacheStrategy? = null, name: String? = null, noinline defaultValue: (Node.(String) -> T)? = null, ): NodeSerializableField<T> = NodeSerializableField(node.format.serializer<T>(), strategy, name, defaultValue)
82
null
46
71
a363556f629d0556568fe2696338ec7f57ff2ccc
4,814
player
MIT License
app/src/test/java/com/okanaydin/assignment/features/posts/PostListUseCaseTest.kt
okanaydin
358,368,399
false
null
package com.okanaydin.assignment.features.posts import com.google.common.truth.Truth.assertThat import com.okanaydin.assignment.data.remote.datasource.model.PhotoModelFactory.getPhoto import com.okanaydin.assignment.data.remote.datasource.model.PostAndPhotoModelFactory.getPostAndPhoto import com.okanaydin.assignment.data.remote.datasource.model.PostModelFactory.getPost import com.okanaydin.assignment.features.core.Resource import com.okanaydin.assignment.features.core.Resource.Success import com.okanaydin.assignment.features.posts.repository.PostRepository import com.okanaydin.assignment.features.posts.usecase.PostListUseCase import com.okanaydin.assignment.util.MainCoroutineRule import com.okanaydin.assignment.util.second import io.mockk.MockKAnnotations import io.mockk.coEvery import io.mockk.coVerify import io.mockk.impl.annotations.MockK import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test @ExperimentalCoroutinesApi class PostListUseCaseTest { @get:Rule var mainCoroutineRule = MainCoroutineRule() @MockK private lateinit var postRepository: PostRepository private lateinit var postListUseCase: PostListUseCase @Before fun setUp() { MockKAnnotations.init(this) postListUseCase = PostListUseCase(postRepository) } @Test fun `when state is loading, then getCombinedPostsAndPhotos returns loading`() = runBlocking { // given coEvery { postRepository.getPosts() } // when val result = postListUseCase.getCombinedPostsAndPhotos().first() // then assertThat(result).isInstanceOf(Resource.Loading::class.java) } @Test fun `when state is success, then getCombinedPostsAndPhotos returns post and photo`() = runBlocking { // given coEvery { postRepository.getPosts() } returns listOf(getPost()) coEvery { postRepository.getPhotos() } returns listOf(getPhoto()) // when val result = postListUseCase.getCombinedPostsAndPhotos().toList() // then coVerify { postRepository.getPhotos() } coVerify { postRepository.getPosts() } assertThat(result).hasSize(2) assertThat(result.first()).isInstanceOf(Resource.Loading::class.java) assertThat((result.second() as Success<*>).data).isEqualTo(listOf(getPostAndPhoto())) } @Test fun `when state is failed, then getCombinedPostsAndPhotos returns error`() = runBlocking { // given val errorMessage = "ERROR_MESSAGE" val throwable = Throwable(errorMessage) coEvery { postRepository.getPosts() } throws throwable coEvery { postRepository.getPhotos() } throws throwable // when val result = postListUseCase.getCombinedPostsAndPhotos().toList() // then assertThat(result).hasSize(2) assertThat(result.first()).isInstanceOf(Resource.Loading::class.java) assertThat((result.second() as Resource.Failed<*>).throwable.message).isEqualTo( errorMessage ) } }
0
Kotlin
0
32
59e04e539678e3bce7516e4f3c501be921932ef4
3,336
Android-Assignment
Apache License 2.0
creator/src/main/kotlin/io/fabric8/launcher/creator/core/template/Transform.kt
fabric8-launcher
111,528,311
false
null
package io.fabric8.launcher.creator.core.template import io.fabric8.launcher.creator.core.writeLines import java.io.File import java.nio.file.* typealias Transformer = (Sequence<String>) -> Sequence<String> fun transform(inText: String, transform: Transformer): String { return transform(inText.lineSequence()).joinToString("\n") } fun transform(inFile: Path, outFile: Path, transform: Transformer): Path { val actualOutFile = if (Files.isSameFile(outFile, inFile)) File.createTempFile("transform", "tmp").toPath() else outFile Files.newBufferedWriter(actualOutFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING).use { out -> inFile.toFile().useLines { lines -> transform(lines).writeLines(out) } } if (!Files.isSameFile(outFile, actualOutFile)) { Files.setPosixFilePermissions(actualOutFile, Files.getPosixFilePermissions(outFile)) Files.move(actualOutFile, outFile, StandardCopyOption.REPLACE_EXISTING) } return outFile } fun transformFiles(dir: Path, pattern: String, transformer: Transformer): Int { var result = 0 // This makes the ** glob pattern behave more like expected val pattern2 = pattern.replace("**/", "{,**/}") val matcher = FileSystems.getDefault().getPathMatcher("glob:$pattern2") Files.walk(dir).use { it.forEach { val rel = dir.relativize(it) if (Files.isRegularFile(it) && matcher.matches(rel)) { transform(it, it, transformer) result++ } } } return result } fun transformFiles(dir: Path, patterns: List<String>, transformer: Transformer): Int { return patterns.fold(0) { acc: Int, cur: String -> acc + transformFiles(dir, cur, transformer) } }
105
HTML
56
18
4dbc9e04bddaf31e045701a8d89e518f3425aaff
1,799
launcher-application
Apache License 2.0
src/main/kotlin/net/pdevita/creeperheal2/core/Explosion.kt
pmdevita
273,936,043
false
null
package net.pdevita.creeperheal2.core import kotlinx.coroutines.* import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import net.pdevita.creeperheal2.CreeperHeal2 import net.pdevita.creeperheal2.data.MergeableLinkedList import net.pdevita.creeperheal2.utils.async import net.pdevita.creeperheal2.utils.minecraft import org.bukkit.Location import org.bukkit.Material import org.bukkit.block.Block import org.bukkit.block.BlockFace import org.bukkit.block.Chest import org.bukkit.block.Container import org.bukkit.block.data.type.BigDripleaf import java.util.* import java.util.concurrent.atomic.AtomicBoolean import kotlin.math.max import kotlin.math.min import kotlin.math.round class Explosion() { lateinit var plugin: CreeperHeal2 // List of all blocks involved in explosion, dependents included val totalBlockList = MergeableLinkedList<ExplodedBlock>() private var replaceList = MergeableLinkedList<ExplodedBlock>() val gravityBlocks = HashSet<Location>() val locations = HashMap<Location, ExplodedBlock>() var boundary: Boundary? = null var postProcessComplete = AtomicBoolean(false) private var cancelReplace = AtomicBoolean(false) var replaceCounter = 0 private var postProcessTask: Deferred<Unit>? = null private var delayJob: Deferred<Unit>? = null private var relinkJob: Job? = null private var sortJob: Deferred<Unit>? = null var isAdded = Mutex(true) // Initialize the class, create the finalBlockList of every single block that is affected in this explosion and link // it's dependencies constructor(plugin: CreeperHeal2, initialBlockList: List<Block>) : this() { this.plugin = plugin // List of all blocks, including dependencies, in this stage of search // When we search out for other dependencies, this list will be cleared to hold the next layer var blockList = MergeableLinkedList<ExplodedBlock>() // First pass, get blocks and make changes to them individually for (block in initialBlockList) { val state = block.state val explodedBlock = ExplodedBlock.from(this, state) blockList.add(explodedBlock) locations[block.location] = explodedBlock // Clear containers since we keep inventory // Even though we are destroying the container block, this is still necessary for some reason if (state is Container) { // plugin.debugLogger("Container destroyed") if (state is Chest) { state.blockInventory.clear() } else { state.inventory.clear() } } } // Put the extra dependent blocks in here to differentiate them from the previous layer var secondaryList = MergeableLinkedList<ExplodedBlock>() // Third pass, prepare blocks around the exploded blocks // While we still have blocks to check while (blockList.isNotEmpty()) { // Check them for (explodedBlock in blockList) { val block = explodedBlock.state // A few different kinds of blocks could be above, check that first val upBlock = block.block.getRelative(BlockFace.UP) // First, check that the above block is not already accounted for in the explosion if (!locations.containsKey(upBlock.location) && !gravityBlocks.contains(upBlock.location)) { // If the above block is a gravity block, freeze it in place rather than making it a // dependent block if (plugin.constants.gravityBlocks.contains(upBlock.blockData.material)) { gravityBlocks.add(upBlock.location) } } // Check for blocks that depend on this one and add them to our dependencies val dependentBlocks = explodedBlock.findDependentBlocks() if (dependentBlocks.isNotEmpty()) { for (dependentBlock in dependentBlocks) { locations[dependentBlock.state.location] = dependentBlock } secondaryList.addAll(dependentBlocks) // explodedBlock.dependencies.addAll(dependentBlocks) } } // this.blockList.addAll(blockList) // Add total blocks to Bstats if (plugin.stats != null) { val numOfBlocks = blockList.size async(plugin) { plugin.stats!!.totalBlocks.addAndGet(numOfBlocks) } } // The block staging looks like this // Currently found dependencies -> current blocks checking for dependencies -> Final list totalBlockList.append(blockList) blockList = secondaryList secondaryList = MergeableLinkedList() // blockList = secondaryList // secondaryList = ArrayList<ExplodedBlock>() } replaceList.addAll(totalBlockList) // Do final linking of dependencies val itr = replaceList.iterator() while (itr.hasNext()) { val block = itr.next() // Block is dependent, should be removed and linked to parent if (block !is DefaultExplodedBlock) { // If the parent is in the explosion, we need to link this block to it // If the parent is not in the explosion, it should already exist and so we don't need to worry // about placing this block after it // println("Non-default block in list ${block.state.blockData.material}") if (block.parentInExplosion()) { // Attach to it // Add block to it's parent's dependency list. Once the parent is added, it's dependencies will // be added to the replaceList // parentBlock.dependencies.add(block) // println("Attaching to parent...") block.addToParents() itr.remove() } } } // Ready to go, delete all the blocks deleteBlocks(replaceList) updateBlocks(replaceList) // Hand off the gravity blocks to be suspended plugin.gravity.addBlocks(gravityBlocks) if (plugin.stats != null) { async(plugin) { plugin.stats!!.totalExplosions.incrementAndGet() } } postProcess() } constructor( plugin: CreeperHeal2, totalBlockList: MergeableLinkedList<ExplodedBlock>, replaceList: MergeableLinkedList<ExplodedBlock>, gravityBlocks: HashSet<Location>, locations: HashMap<Location, ExplodedBlock>, boundary: Boundary? = null, replaceCounter: Int): this() { this.plugin = plugin this.totalBlockList.append(totalBlockList) this.gravityBlocks.addAll(gravityBlocks) this.locations.putAll(locations) this.replaceList = replaceList this.boundary = boundary this.replaceCounter = replaceCounter this.postProcessComplete.set(true) GlobalScope.launch(Dispatchers.async) { // Delay before starting heal delayJob = async(Dispatchers.async) { delay((plugin.settings.general.initialDelay * 1000).toLong()) } // Start the block linking job and wait linkBlocks(this@Explosion.replaceList) relinkJob!!.join() if (!this@Explosion.cancelReplace.get()) { sortJob = async(Dispatchers.async) { this@Explosion.replaceList.sortBy { it.state.y } } } delayJob!!.await() if (!this@Explosion.cancelReplace.get()) { newReplace() } } } private fun linkBlocks(blockList: MutableList<ExplodedBlock>) { relinkJob = GlobalScope.launch(Dispatchers.async) { // Relink each block so it knows which explosion it belongs to totalBlockList.forEach { it.relinkExplosion(this@Explosion) } // Second pass, link dependent blocks to their parents val itr = blockList.iterator() while (itr.hasNext()) { val block = itr.next() // Block isn't dependent, can be replaced normally if (block !is DefaultExplodedBlock) { // If the parent is in the explosion, we need to link this block to it // If the parent is not in the explosion, it should already exist and so we don't need to worry // about placing this block after it if (block.parentInExplosion()) { // When relinking for a merged explosion, things are a little different // First, gravityBlocks are a part of location list so this block's parent might currently // be suspended in gravity. if (block.parentInExplosion(checkGravity = true)) { // if (gravityBlocks.contains(parentLocation)) { // Parent is in suspended gravity and should already exist, don't worry about linking // } else if (!parentBlock.dependencies.contains(block)) { // This parent doesn't contain this block in its dependencies but it should, move from // the main block list to its parent's dependency list. // If this got cancelled, we would lose the block so it's wrapped as so. withContext(NonCancellable) { block.addToParents() itr.remove() } } } } } } } private fun deleteBlocks(blockList: Collection<ExplodedBlock>) { // Delete blocks, accounting for dependencies first for (block in blockList) { if (block.dependencies.isNotEmpty()) { deleteBlocks(block.dependencies) } // If TNT exploding is on, don't remove the TNT if (block.state.blockData.material == Material.TNT && plugin.settings.general.explodeTNT) { continue } block.state.location.block.setType(Material.AIR, false) block.state.location.block.state.update(true, false) } } private fun updateBlocks(blockList: Collection<ExplodedBlock>) { for (block in blockList) { if (block.dependencies.isNotEmpty()) { updateBlocks(block.dependencies) } // If TNT exploding is on, don't update the TNT if (block.state.blockData.material == Material.TNT && plugin.settings.general.explodeTNT) { continue } block.state.location.block.setType(Material.STONE, false) block.state.location.block.setType(Material.AIR, true) block.state.location.block.state.update(true, true) } } // Further processing on the block list after the initial block list creation private fun postProcess() { GlobalScope.launch(Dispatchers.async) { // Delay before starting heal delayJob = async(Dispatchers.async) { delay((plugin.settings.general.initialDelay * 1000).toLong()) } // Calc boundaries so we can combine with intersecting explosions val calcBoundary = async(Dispatchers.async) { this@Explosion.boundary = Boundary(totalBlockList) } // Post-processing on block list this@Explosion.postProcessTask = async(Dispatchers.async) { // Fix Weeping Vines and Big Dripleafs which have some odd behavior // Could a better optimized system for this be made? if (plugin.constants.version.second >= 16) { for (block in totalBlockList) { if (block.state.type == Material.WEEPING_VINES_PLANT) { block.state.type = Material.WEEPING_VINES } } } if (plugin.constants.version.second >= 17) { for (block in totalBlockList) { if (block.state.type == Material.BIG_DRIPLEAF) { val data = block.state.blockData as BigDripleaf data.tilt = BigDripleaf.Tilt.NONE block.state.blockData = data } else if (block.state.type == Material.BIG_DRIPLEAF_STEM) { block.state.type = Material.BIG_DRIPLEAF } } } // If TNT exploding is on, remove the TNT and dump it's dependents back into the tree if (plugin.settings.general.explodeTNT) { val itr = replaceList.iterator() val newBlocks = LinkedList<ExplodedBlock>() // Store dependencies here intermittently while (itr.hasNext()) { val block = itr.next() if (block.state.blockData.material == Material.TNT) { newBlocks.addAll(block.dependencies) itr.remove() } } replaceList.addAll(newBlocks) if (replaceList.isEmpty()) { // Cancel this explosion plugin.debugLogger("Explosion was only TNT, deleting") calcBoundary.cancel() this@Explosion.cancel() this@Explosion.deleteExplosion() } else { totalBlockList.removeAll { it.state.blockData.material == Material.TNT } } } } this@Explosion.postProcessTask!!.await() calcBoundary.await() this@Explosion.postProcessComplete.set(true) if (!this@Explosion.cancelReplace.get()) { isAdded.withLock { plugin.checkBoundaries() } } if (!this@Explosion.cancelReplace.get()) { sortJob = async(Dispatchers.async) { this@Explosion.replaceList.sortBy { it.state.y } } } delayJob!!.join() if (!this@Explosion.cancelReplace.get()) { newReplace() } } } // Async process to schedule block replacement private fun newReplace() { if (plugin.settings.general.turboThreshold > 0 && plugin.settings.general.turboThreshold < (totalBlockList.size - replaceCounter)) { plugin.debugLogger("Starting off repair in turbo") } else { plugin.debugLogger("Staring repair") } GlobalScope.launch(Dispatchers.async) { // replaceList.duplicateCheck() // Intermediate block list, mostly important for turboing val blocks = LinkedList<ExplodedBlock>() while (replaceList.isNotEmpty()) { // If turbo is enabled and we are over the threshold, turn it on var replaceAmount = if (plugin.settings.general.turboThreshold > 0 && plugin.settings.general.turboThreshold < (totalBlockList.size - replaceCounter)) { when (plugin.settings.general.turboType) { 0 -> plugin.settings.general.turboAmount 1 -> round((plugin.settings.general.turboPercentage / 100.0) * (totalBlockList.size - replaceCounter)).toInt().coerceIn(1..plugin.settings.general.turboCap) else -> plugin.settings.general.turboAmount } } else { 1 } // Peek N number of blocks to replace val itr = replaceList.iterator() for (i in 0 until replaceAmount) { if (itr.hasNext()) { blocks.add(itr.next()) } else { break } } // plugin.debugLogger("Placing ${blocks.size} blocks") withContext(Dispatchers.minecraft) { if (!cancelReplace.get()) { // Only proceed if we aren't cancelling. for (block in blocks) { // Replace block block.placeBlock() // Remove it from the replaceList replaceList.poll() // Dump its dependencies in block.dependencies.forEach { if (it.canBePlaced()) replaceList.add(it) } } } } // Increment the replaceCounter replaceCounter += blocks.size // Clear the intermediate block list blocks.clear() // If we are cancelling, exit, otherwise, keep going if (!cancelReplace.get()) { delayJob = async(Dispatchers.async) { delay((plugin.settings.general.betweenBlocksDelay / 20 * 1000).toLong()) } delayJob!!.join() // Delay is kinda long, could be good to check again if (cancelReplace.get()) break } else { break } } // Clean up // Remove reference to self to be deleted // if (!cancelReplace) { deleteExplosion() plugin.debugLogger("Finished repairing explosion") // } } } private fun deleteExplosion() { GlobalScope.launch(Dispatchers.minecraft) { plugin.gravity.removeBlocks(gravityBlocks) plugin.removeExplosion(this@Explosion) } } // Replace blocks ASAP (used to finish repairs if plugin is being disabled) fun warpReplaceBlocks() { plugin.debugLogger("Warp replacing...") // Signal to async that it needs to stop and sync tasks that they should no longer proceed cancelReplace.set(true) // Block until post-processing is complete if (!postProcessComplete.get()) { runBlocking { postProcessTask?.await() } } if (relinkJob != null) { runBlocking { relinkJob!!.join() } } if (sortJob != null) { runBlocking { sortJob!!.await() } } while (replaceList.isNotEmpty()) { val block = replaceList.peek() // Replace block block.placeBlock() // Remove it from the replaceList replaceList.poll() // Dump its dependencies in block.dependencies.forEach { if (it.canBePlaced()) replaceList.add(it) } } // Clean up plugin.gravity.removeBlocks(gravityBlocks) } fun cancel() { cancelReplace.set(true) relinkJob?.cancel() // Block until post-processing is complete if (!postProcessComplete.get()) { runBlocking { postProcessTask?.await() } } if (relinkJob != null) { runBlocking { relinkJob!!.cancelAndJoin() } } if (sortJob != null) { runBlocking { sortJob!!.await() } } } operator fun plus(other: Explosion): Explosion { // Stop the original explosion objects from repairing // plugin.debugLogger("Adding two explosions") this.cancel() other.cancel() // Create new lists to store merged data val totalBlockList = MergeableLinkedList<ExplodedBlock>() val gravityBlocks = ArrayList<Location>() val locations = HashMap<Location, ExplodedBlock>() val replaceList = MergeableLinkedList<ExplodedBlock>() val replaceCounter = this.replaceCounter + other.replaceCounter // And merge! totalBlockList.append(this.totalBlockList) totalBlockList.append(other.totalBlockList) gravityBlocks.addAll(this.gravityBlocks) gravityBlocks.addAll(other.gravityBlocks) locations.putAll(this.locations) locations.putAll(other.locations) replaceList.append(this.replaceList) replaceList.append(other.replaceList) // replaceList.duplicateCheck() // Recalculate gravity // plugin.debugLogger("Finished merging basic data, cleaning gravity blocks") val removedGravity = getRemovedGravity(gravityBlocks, locations) plugin.gravity.removeBlocks(removedGravity) val gravityBlocksSet = HashSet<Location>(gravityBlocks) gravityBlocksSet.removeAll(removedGravity) var boundary: Boundary? = null if (this.boundary != null && other.boundary != null) { boundary = Boundary(max(this.boundary!!.highX, other.boundary!!.highX), max(this.boundary!!.highY, other.boundary!!.highY), max(this.boundary!!.highZ, other.boundary!!.highZ), min(this.boundary!!.lowX, other.boundary!!.lowX), min(this.boundary!!.lowY, other.boundary!!.lowY), min(this.boundary!!.lowZ, other.boundary!!.lowZ)) } // plugin.debugLogger("Done, initializing from data") return Explosion(plugin, totalBlockList, replaceList, gravityBlocksSet, locations, boundary, replaceCounter) } private fun getRemovedGravity(gravityBlocks: ArrayList<Location>, locations: HashMap<Location, ExplodedBlock>): ArrayList<Location> { val removed = ArrayList<Location>() for (gravityBlock in gravityBlocks) { if (gravityBlock in locations) { removed.add(gravityBlock) } } return removed } } class ExplosionMapping(var explosion: Explosion) { val indices = ArrayList<Int>() }
6
Kotlin
2
6
c0ba7471f3b16d368967541d1a62cfd3b31fabcd
22,737
CreeperHeal2
MIT License
app/src/main/java/alektas/telecomapp/ui/datasource/simulation/EtherSettingsFragment.kt
Alektas
214,780,544
false
null
package alektas.telecomapp.ui.datasource.simulation import androidx.lifecycle.ViewModelProviders import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import alektas.telecomapp.R import alektas.telecomapp.domain.entities.contracts.QpskContract import android.content.Context import android.content.SharedPreferences import android.widget.Toast import androidx.core.widget.doOnTextChanged import androidx.lifecycle.Observer import com.jjoe64.graphview.GraphView import com.jjoe64.graphview.series.DataPoint import com.jjoe64.graphview.series.LineGraphSeries import kotlinx.android.synthetic.main.ether_settings_fragment.* class EtherSettingsFragment : Fragment() { companion object { fun newInstance() = EtherSettingsFragment() } private lateinit var viewModel: EtherSettingsViewModel private lateinit var prefs: SharedPreferences private val graphPoints = LineGraphSeries<DataPoint>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.ether_settings_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { view.findViewById<GraphView>(R.id.ether_chart).apply { addSeries(graphPoints) viewport.apply { isScrollable = true isXAxisBoundsManual = true setMaxX(10 * QpskContract.DEFAULT_DATA_BIT_TIME) } } super.onViewCreated(view, savedInstanceState) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProviders.of(this).get(EtherSettingsViewModel::class.java) prefs = requireContext().getSharedPreferences( getString(R.string.settings_source_key), Context.MODE_PRIVATE ) setupFieldsValidation(viewModel) setInitValues(prefs) observeSettings(viewModel, prefs) setupControls() viewModel.ether.observe(viewLifecycleOwner, Observer { graphPoints.resetData(it) }) } private fun setInitValues(prefs: SharedPreferences) { val isNoiseEnabled = prefs.getBoolean(getString(R.string.source_noise_enable_key), false) noise_checkbox.isChecked = isNoiseEnabled noise_rate_layout.isEnabled = isNoiseEnabled prefs.getFloat( getString(R.string.source_noise_snr_key), QpskContract.DEFAULT_SIGNAL_NOISE_RATE.toFloat() ).let { noise_rate.setText(it.toString()) } val isInterferenceEnabled = prefs.getBoolean(getString(R.string.source_interference_enable_key), false) interference_checkbox.isChecked = isInterferenceEnabled interference_rate_layout.isEnabled = isInterferenceEnabled interference_sparseness_layout.isEnabled = isInterferenceEnabled prefs.getFloat( getString(R.string.source_interference_snr_key), QpskContract.DEFAULT_SIGNAL_NOISE_RATE.toFloat() ).let { interference_rate.setText(it.toString()) } prefs.getFloat( getString(R.string.source_interference_sparseness_key), QpskContract.DEFAULT_INTERFERENCE_SPARSENESS.toFloat() ).let { interference_sparseness.setText(it.toString()) } } private fun observeSettings(viewModel: EtherSettingsViewModel, prefs: SharedPreferences) { viewModel.noiseRate.observe(viewLifecycleOwner, Observer { prefs.edit().putFloat(getString(R.string.source_noise_snr_key), it.toFloat()).apply() }) viewModel.interferenceRate.observe(viewLifecycleOwner, Observer { prefs.edit().putFloat(getString(R.string.source_interference_snr_key), it.toFloat()).apply() }) viewModel.interferenceSparseness.observe(viewLifecycleOwner, Observer { prefs.edit().putFloat(getString(R.string.source_interference_sparseness_key), it.toFloat()).apply() }) } private fun setupControls() { noise_checkbox.setOnCheckedChangeListener { _, isChecked -> if (isChecked) { viewModel.enableNoise() noise_rate_layout.isEnabled = true prefs.edit().putBoolean(getString(R.string.source_noise_enable_key), true).apply() } else { viewModel.disableNoise() noise_rate_layout.isEnabled = false prefs.edit().putBoolean(getString(R.string.source_noise_enable_key), false).apply() } } interference_checkbox.setOnCheckedChangeListener { _, isChecked -> if (isChecked) { viewModel.enableInterference() interference_rate_layout.isEnabled = true interference_sparseness_layout.isEnabled = true prefs.edit().putBoolean(getString(R.string.source_interference_enable_key), true).apply() } else { viewModel.disableInterference() interference_rate_layout.isEnabled = false interference_sparseness_layout.isEnabled = false prefs.edit().putBoolean(getString(R.string.source_interference_enable_key), false).apply() } } noise_rate.setOnEditorActionListener { tv, _, _ -> changeNoiseRate(tv.text.toString()) false } interference_rate.setOnEditorActionListener { tv, _, _ -> changeInterferenceRate(tv.text.toString()) false } interference_sparseness.setOnEditorActionListener { tv, _, _ -> changeInterferenceSparseness(tv.text.toString()) false } } private fun setupFieldsValidation(viewModel: EtherSettingsViewModel) { noise_rate.doOnTextChanged { text, _, _, _ -> if (viewModel.parseSnr(text.toString()) != EtherSettingsViewModel.INVALID_SNR) { noise_rate_layout.error = null } else { noise_rate_layout.error = getString(R.string.error_num) } } interference_rate.doOnTextChanged { text, _, _, _ -> if (viewModel.parseSnr(text.toString()) != EtherSettingsViewModel.INVALID_SNR) { interference_rate_layout.error = null } else { interference_rate_layout.error = getString(R.string.error_num) } } interference_sparseness.doOnTextChanged { text, _, _, _ -> if (viewModel.parseSparseness(text.toString()) >= 0) { interference_sparseness_layout.error = null } else { interference_sparseness_layout.error = getString(R.string.error_positive_num) } } } private fun changeNoiseRate(snr: String) { if (snr.isEmpty() || noise_rate_layout.error != null) { Toast.makeText(requireContext(), getString(R.string.error_num), Toast.LENGTH_SHORT).show() return } viewModel.setNoise(snr) } private fun changeInterferenceSparseness(sparseness: String) { if (sparseness.isEmpty() || interference_sparseness_layout.error != null) { Toast.makeText(requireContext(), getString(R.string.error_positive_num), Toast.LENGTH_SHORT).show() return } viewModel.changeInterferenceSparseness(sparseness) } private fun changeInterferenceRate(rate: String) { if (rate.isEmpty() || interference_rate_layout.error != null) { Toast.makeText(requireContext(), getString(R.string.error_num), Toast.LENGTH_SHORT).show() return } viewModel.changeInterferenceRate(rate) } }
0
Kotlin
0
0
1e83fbe6daa496f4c4f47d41f404d3e66fb200ff
7,967
Telecom-System
Apache License 2.0
app/src/main/java/dev/esnault/bunpyro/android/display/widget/question/TextUnderlineRenderer.kt
esnaultdev
242,479,002
false
null
package dev.esnault.bunpyro.android.display.widget.question import android.graphics.Canvas import android.graphics.Paint import android.text.Layout /** * Base class for single and multi line text underline renderers. */ internal abstract class TextUnderlineRenderer(val underlinePaint: Paint) { /** * Draw the background that starts at the {@code startOffset} and ends at {@code endOffset}. * * @param canvas Canvas to draw onto * @param layout Layout that contains the text * @param startLine the start line for the background * @param endLine the end line for the background * @param startOffset the character offset that the background should start at * @param endOffset the character offset that the background should end at */ abstract fun draw( canvas: Canvas, layout: Layout, startLine: Int, endLine: Int, startOffset: Float, endOffset: Float ) protected fun getLineBottom(layout: Layout, line: Int): Float = layout.getLineBottom(line) - underlinePaint.strokeWidth / 2f } /** * Draws the underline for text that starts and ends on the same line. */ internal class SingleLineRenderer(underlinePaint: Paint) : TextUnderlineRenderer(underlinePaint) { override fun draw( canvas: Canvas, layout: Layout, startLine: Int, endLine: Int, startOffset: Float, endOffset: Float ) { val y = getLineBottom(layout, startLine) canvas.drawLine(startOffset, y, endOffset, y, underlinePaint) } } /** * Draws the underline for text that starts and ends on different lines. */ internal class MultiLineRenderer(underlinePaint: Paint) : TextUnderlineRenderer(underlinePaint) { override fun draw( canvas: Canvas, layout: Layout, startLine: Int, endLine: Int, startOffset: Float, endOffset: Float ) { // draw the first line val paragDir = layout.getParagraphDirection(startLine) val firstLineEndOffset = if (paragDir == Layout.DIR_RIGHT_TO_LEFT) { layout.getLineLeft(startLine) } else { layout.getLineRight(startLine) } var lineBottom: Float = getLineBottom(layout, startLine) canvas.drawLine(startOffset, lineBottom, firstLineEndOffset, lineBottom, underlinePaint) // for the lines in the middle draw the underline for the whole width for (line in startLine + 1 until endLine) { lineBottom = getLineBottom(layout, line) val lineStart = layout.getLineLeft(line) val lineEnd = layout.getLineRight(line) canvas.drawLine(lineStart, lineBottom, lineEnd, lineBottom, underlinePaint) } // draw the last line val lastLineStartOffset = layout.getPrimaryHorizontal(layout.getLineStart(endLine)) lineBottom = getLineBottom(layout, endLine) canvas.drawLine(lastLineStartOffset, lineBottom, endOffset, lineBottom, underlinePaint) } }
2
Kotlin
1
9
89b3c7dad2c37c22648c26500016d6503d27019e
3,059
BunPyro
Intel Open Source License
logic/src/main/java/lt/markmerkk/durak/actions/system/ActionIllegalCannotTranslate.kt
marius-m
733,676,467
false
{"Kotlin": 167943}
package lt.markmerkk.durak.actions.system import lt.markmerkk.durak.actions.Action /** * When action cannot be executed */ data class ActionIllegalCannotTranslate( private val inputAsString: String = "", private val detailDescription: String = "" ) : Action
0
Kotlin
0
0
8f2346cfcbb3c0871fb0db2768fd33d9b2fe277a
277
stupid2
Apache License 2.0
argument/src/main/java/me/reezy/jetpack/argument/ArgumentFloat.kt
czy1121
348,366,676
false
null
package me.reezy.cosmo import android.os.Bundle class ArgumentFloat(default: Float = 0f, key: String? = null): ArgumentField<Float>(default, key) { override fun get(field: String, bundle: Bundle): Float { val o = bundle[field] ?: return default return when(o) { is Number -> o.toFloat() is String -> o.toFloatOrNull() ?: default else -> default } } }
0
Kotlin
0
1
cd284d9ca6234b41eba608218b63b2ed6264876a
421
argument
Apache License 2.0
src/main/kotlin/net/casual/arcade/extensions/DataExtension.kt
CasualChampionships
621,955,934
false
{"Kotlin": 567308, "Java": 106965}
package net.casual.arcade.extensions import net.minecraft.nbt.Tag import org.jetbrains.annotations.ApiStatus.OverrideOnly /** * This interface is an extension of [Extension] that allows * you to further serialize any data in your [Extension]. * * Building off the previous example in [Extension] to now * make it a DataExtension: * ```kotlin * class MyPlayerExtension: DataExtension { * var lastSentMessage = "" * * override fun getName(): String { * return "arcade_my_player_extension" * } * * override fun serialize(): Tag { * return StringTag.valueOf(this.lastSentMessage) * } * * override fun deserialize(element: Tag) { * this.lastSentMessage = (element as StringTag).asString * } * * companion object { * val ServerPlayer.myExtension * get() = this.getExtension(MyPlayerExtension::class.java) * * // This must be called in your ModInitializer * fun registerEvents() { * GlobalEventHandler.register<PlayerCreatedEvent> { (player) -> * player.addExtension(MyPlayerExtension()) * } * GlobalEventHandler.register<PlayerChatEvent> { (player, message) -> * player.myExtension.lastSentMessage = message.signedContent() * } * } * } * } * ``` * * Everything else is handled for you! * * @see Extension */ public interface DataExtension: Extension { /** * This gets the name of your extension. * * This usually follows the format of `"${modid}_${extension_name}"`, * so for example, `"arcade_minigame_extension"`. * * @return The name of your extension. */ public fun getName(): String /** * This method serializes any data in your extension. * * The [Tag] that you serialize will be passed into * [deserialize] when deserializing. * * @return The serialized data. */ @OverrideOnly public fun serialize(): Tag? /** * This method deserializes any data for your extension. * * The [element] that gets passed in is what you previously * serialized with [serialize]. * * @param element The serialized data. */ @OverrideOnly public fun deserialize(element: Tag) }
1
Kotlin
1
1
8e28b455995a74769470cf1fbb82283f7a05c0d7
2,321
arcade
MIT License
src/main/kotlin/com/github/mpe85/grampa/input/StringBuilderInputBuffer.kt
mpe85
138,511,038
false
{"Kotlin": 270203, "Java": 1073}
package com.github.mpe85.grampa.input /** * An [InputBuffer] implementation using a [StringBuilder]. * * @author mpe85 * @param[stringBuilder] A string builder backing the input buffer */ public class StringBuilderInputBuffer(private val stringBuilder: StringBuilder) : CharSequenceInputBuffer(stringBuilder) { override fun getCodePoint(index: Int): Int = stringBuilder.codePointAt(index) }
7
Kotlin
1
13
fba606664241406e268a042550928e9ef8d77ed1
406
grampa
MIT License
app/src/main/java/com/customappsms/to_dolist/models/Task.kt
MaksymSolomkin
687,570,503
false
{"Kotlin": 27828}
package com.customappsms.to_dolist.models import com.google.firebase.Timestamp import com.google.firebase.firestore.DocumentId data class Task( @DocumentId val id: String = "", val title: String = "", val date: Timestamp = Timestamp.now(), val isCompleted: Boolean = false, var userId: String = "" )
0
Kotlin
0
1
c674092ac925224846b9c0e19a74efa3018821ee
322
To-Do-List
MIT License
lambda/src/main/typings/textract.module_aws-sdk.kt
kartoffelsup
252,152,703
false
null
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION") import kotlin.js.* import kotlin.js.Json import org.khronos.webgl.* import org.w3c.dom.* import org.w3c.dom.events.* import org.w3c.dom.parsing.* import org.w3c.dom.svg.* import org.w3c.dom.url.* import org.w3c.fetch.* import org.w3c.files.* import org.w3c.notifications.* import org.w3c.performance.* import org.w3c.workers.* import org.w3c.xhr.* import Textract.Block import Textract.Point import Textract.Relationship import Textract.Warning import Textract.AnalyzeDocumentRequest import Textract.AnalyzeDocumentResponse import Textract.DetectDocumentTextRequest import Textract.DetectDocumentTextResponse import Textract.GetDocumentAnalysisRequest import Textract.GetDocumentAnalysisResponse import Textract.GetDocumentTextDetectionRequest import Textract.GetDocumentTextDetectionResponse import Textract.StartDocumentAnalysisRequest import Textract.StartDocumentAnalysisResponse import Textract.StartDocumentTextDetectionRequest import Textract.StartDocumentTextDetectionResponse import Textract.Document import Textract.HumanLoopConfig import Textract.DocumentMetadata import Textract.HumanLoopActivationOutput import Textract.Geometry import Textract.S3Object import Textract.BoundingBox import Textract.HumanLoopDataAttributes import Textract.DocumentLocation import Textract.NotificationChannel typealias BlockList = Array<Block> typealias ClientRequestToken = String typealias ContentClassifiers = Array<String /* "FreeOfPersonallyIdentifiableInformation" | "FreeOfAdultContent" | String */> typealias EntityTypes = Array<String /* "KEY" | "VALUE" | String */> typealias ErrorCode = String typealias FeatureTypes = Array<String /* "TABLES" | "FORMS" | String */> typealias Float = Number typealias FlowDefinitionArn = String typealias HumanLoopActivationConditionsEvaluationResults = String typealias HumanLoopActivationReason = String typealias HumanLoopActivationReasons = Array<HumanLoopActivationReason> typealias HumanLoopArn = String typealias HumanLoopName = String typealias IdList = Array<NonEmptyString> typealias JobId = String typealias JobTag = String typealias MaxResults = Number typealias NonEmptyString = String typealias Pages = Array<UInteger> typealias PaginationToken = String typealias Percent = Number typealias Polygon = Array<Point> typealias RelationshipList = Array<Relationship> typealias RoleArn = String typealias S3Bucket = String typealias S3ObjectName = String typealias S3ObjectVersion = String typealias SNSTopicArn = String typealias StatusMessage = String typealias String = String typealias UInteger = Number typealias Warnings = Array<Warning> @JsModule("aws-sdk") external open class Textract(options: ServiceConfigurationOptions /* ServiceConfigurationOptions & ClientApiVersions */ = definedExternally) : Service { open var config: ConfigBase /* Config & Textract.Types.ClientConfiguration */ open fun analyzeDocument(params: AnalyzeDocumentRequest, callback: (err: AWSError, data: AnalyzeDocumentResponse) -> Unit = definedExternally): Request<AnalyzeDocumentResponse, AWSError> open fun analyzeDocument(callback: (err: AWSError, data: AnalyzeDocumentResponse) -> Unit = definedExternally): Request<AnalyzeDocumentResponse, AWSError> open fun detectDocumentText(params: DetectDocumentTextRequest, callback: (err: AWSError, data: DetectDocumentTextResponse) -> Unit = definedExternally): Request<DetectDocumentTextResponse, AWSError> open fun detectDocumentText(callback: (err: AWSError, data: DetectDocumentTextResponse) -> Unit = definedExternally): Request<DetectDocumentTextResponse, AWSError> open fun getDocumentAnalysis(params: GetDocumentAnalysisRequest, callback: (err: AWSError, data: GetDocumentAnalysisResponse) -> Unit = definedExternally): Request<GetDocumentAnalysisResponse, AWSError> open fun getDocumentAnalysis(callback: (err: AWSError, data: GetDocumentAnalysisResponse) -> Unit = definedExternally): Request<GetDocumentAnalysisResponse, AWSError> open fun getDocumentTextDetection(params: GetDocumentTextDetectionRequest, callback: (err: AWSError, data: GetDocumentTextDetectionResponse) -> Unit = definedExternally): Request<GetDocumentTextDetectionResponse, AWSError> open fun getDocumentTextDetection(callback: (err: AWSError, data: GetDocumentTextDetectionResponse) -> Unit = definedExternally): Request<GetDocumentTextDetectionResponse, AWSError> open fun startDocumentAnalysis(params: StartDocumentAnalysisRequest, callback: (err: AWSError, data: StartDocumentAnalysisResponse) -> Unit = definedExternally): Request<StartDocumentAnalysisResponse, AWSError> open fun startDocumentAnalysis(callback: (err: AWSError, data: StartDocumentAnalysisResponse) -> Unit = definedExternally): Request<StartDocumentAnalysisResponse, AWSError> open fun startDocumentTextDetection(params: StartDocumentTextDetectionRequest, callback: (err: AWSError, data: StartDocumentTextDetectionResponse) -> Unit = definedExternally): Request<StartDocumentTextDetectionResponse, AWSError> open fun startDocumentTextDetection(callback: (err: AWSError, data: StartDocumentTextDetectionResponse) -> Unit = definedExternally): Request<StartDocumentTextDetectionResponse, AWSError> interface AnalyzeDocumentRequest { var Document: Document var FeatureTypes: FeatureTypes var HumanLoopConfig: HumanLoopConfig? get() = definedExternally set(value) = definedExternally } interface AnalyzeDocumentResponse { var DocumentMetadata: DocumentMetadata? get() = definedExternally set(value) = definedExternally var Blocks: BlockList? get() = definedExternally set(value) = definedExternally var HumanLoopActivationOutput: HumanLoopActivationOutput? get() = definedExternally set(value) = definedExternally var AnalyzeDocumentModelVersion: String? get() = definedExternally set(value) = definedExternally } interface Block { var BlockType: String /* "KEY_VALUE_SET" | "PAGE" | "LINE" | "WORD" | "TABLE" | "CELL" | "SELECTION_ELEMENT" | String */ var Confidence: Percent? get() = definedExternally set(value) = definedExternally var Text: String? get() = definedExternally set(value) = definedExternally var RowIndex: UInteger? get() = definedExternally set(value) = definedExternally var ColumnIndex: UInteger? get() = definedExternally set(value) = definedExternally var RowSpan: UInteger? get() = definedExternally set(value) = definedExternally var ColumnSpan: UInteger? get() = definedExternally set(value) = definedExternally var Geometry: Geometry? get() = definedExternally set(value) = definedExternally var Id: NonEmptyString? get() = definedExternally set(value) = definedExternally var Relationships: RelationshipList? get() = definedExternally set(value) = definedExternally var EntityTypes: EntityTypes? get() = definedExternally set(value) = definedExternally var SelectionStatus: String /* "SELECTED" | "NOT_SELECTED" | String */ var Page: UInteger? get() = definedExternally set(value) = definedExternally } interface BoundingBox { var Width: Float? get() = definedExternally set(value) = definedExternally var Height: Float? get() = definedExternally set(value) = definedExternally var Left: Float? get() = definedExternally set(value) = definedExternally var Top: Float? get() = definedExternally set(value) = definedExternally } interface DetectDocumentTextRequest { var Document: Document } interface DetectDocumentTextResponse { var DocumentMetadata: DocumentMetadata? get() = definedExternally set(value) = definedExternally var Blocks: BlockList? get() = definedExternally set(value) = definedExternally var DetectDocumentTextModelVersion: String? get() = definedExternally set(value) = definedExternally } interface Document { var Bytes: dynamic /* Buffer | Uint8Array | Blob | String */ get() = definedExternally set(value) = definedExternally var S3Object: S3Object? get() = definedExternally set(value) = definedExternally } interface DocumentLocation { var S3Object: S3Object? get() = definedExternally set(value) = definedExternally } interface DocumentMetadata { var Pages: UInteger? get() = definedExternally set(value) = definedExternally } interface Geometry { var BoundingBox: BoundingBox? get() = definedExternally set(value) = definedExternally var Polygon: Polygon? get() = definedExternally set(value) = definedExternally } interface GetDocumentAnalysisRequest { var JobId: JobId var MaxResults: MaxResults? get() = definedExternally set(value) = definedExternally var NextToken: PaginationToken? get() = definedExternally set(value) = definedExternally } interface GetDocumentAnalysisResponse { var DocumentMetadata: DocumentMetadata? get() = definedExternally set(value) = definedExternally var JobStatus: String /* "IN_PROGRESS" | "SUCCEEDED" | "FAILED" | "PARTIAL_SUCCESS" | String */ var NextToken: PaginationToken? get() = definedExternally set(value) = definedExternally var Blocks: BlockList? get() = definedExternally set(value) = definedExternally var Warnings: Warnings? get() = definedExternally set(value) = definedExternally var StatusMessage: StatusMessage? get() = definedExternally set(value) = definedExternally var AnalyzeDocumentModelVersion: String? get() = definedExternally set(value) = definedExternally } interface GetDocumentTextDetectionRequest { var JobId: JobId var MaxResults: MaxResults? get() = definedExternally set(value) = definedExternally var NextToken: PaginationToken? get() = definedExternally set(value) = definedExternally } interface GetDocumentTextDetectionResponse { var DocumentMetadata: DocumentMetadata? get() = definedExternally set(value) = definedExternally var JobStatus: String /* "IN_PROGRESS" | "SUCCEEDED" | "FAILED" | "PARTIAL_SUCCESS" | String */ var NextToken: PaginationToken? get() = definedExternally set(value) = definedExternally var Blocks: BlockList? get() = definedExternally set(value) = definedExternally var Warnings: Warnings? get() = definedExternally set(value) = definedExternally var StatusMessage: StatusMessage? get() = definedExternally set(value) = definedExternally var DetectDocumentTextModelVersion: String? get() = definedExternally set(value) = definedExternally } interface HumanLoopActivationOutput { var HumanLoopArn: HumanLoopArn? get() = definedExternally set(value) = definedExternally var HumanLoopActivationReasons: HumanLoopActivationReasons? get() = definedExternally set(value) = definedExternally var HumanLoopActivationConditionsEvaluationResults: HumanLoopActivationConditionsEvaluationResults? get() = definedExternally set(value) = definedExternally } interface HumanLoopConfig { var HumanLoopName: HumanLoopName var FlowDefinitionArn: FlowDefinitionArn var DataAttributes: HumanLoopDataAttributes? get() = definedExternally set(value) = definedExternally } interface HumanLoopDataAttributes { var ContentClassifiers: ContentClassifiers? get() = definedExternally set(value) = definedExternally } interface NotificationChannel { var SNSTopicArn: SNSTopicArn var RoleArn: RoleArn } interface Point { var X: Float? get() = definedExternally set(value) = definedExternally var Y: Float? get() = definedExternally set(value) = definedExternally } interface Relationship { var Type: String /* "VALUE" | "CHILD" | String */ var Ids: IdList? get() = definedExternally set(value) = definedExternally } interface S3Object { var Bucket: S3Bucket? get() = definedExternally set(value) = definedExternally var Name: S3ObjectName? get() = definedExternally set(value) = definedExternally var Version: S3ObjectVersion? get() = definedExternally set(value) = definedExternally } interface StartDocumentAnalysisRequest { var DocumentLocation: DocumentLocation var FeatureTypes: FeatureTypes var ClientRequestToken: ClientRequestToken? get() = definedExternally set(value) = definedExternally var JobTag: JobTag? get() = definedExternally set(value) = definedExternally var NotificationChannel: NotificationChannel? get() = definedExternally set(value) = definedExternally } interface StartDocumentAnalysisResponse { var JobId: JobId? get() = definedExternally set(value) = definedExternally } interface StartDocumentTextDetectionRequest { var DocumentLocation: DocumentLocation var ClientRequestToken: ClientRequestToken? get() = definedExternally set(value) = definedExternally var JobTag: JobTag? get() = definedExternally set(value) = definedExternally var NotificationChannel: NotificationChannel? get() = definedExternally set(value) = definedExternally } interface StartDocumentTextDetectionResponse { var JobId: JobId? get() = definedExternally set(value) = definedExternally } interface Warning { var ErrorCode: ErrorCode? get() = definedExternally set(value) = definedExternally var Pages: Pages? get() = definedExternally set(value) = definedExternally } interface ClientApiVersions { var apiVersion: String /* "2018-06-27" | "latest" | String */ } }
0
Kotlin
0
0
6c20e6277ea66e531b4b46017faa10270b25b8bc
15,430
kt-js-lambda-cdk-test
Apache License 2.0
compiler/testData/psi/DynamicReceiver.kt
JakeWharton
99,388,807
true
null
fun dynamic.foo() fun dynamic?.foo() val dynamic.foo: Int val dynamic?.foo: Int val foo: dynamic.() -> Unit // testing look-ahead with comments and whitespace fun dynamic . foo() fun dynamic .foo() fun dynamic// line-comment .foo() fun dynamic/* */.foo()
179
Kotlin
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
274
kotlin
Apache License 2.0
java/debugger/impl/src/com/intellij/debugger/memory/filtering/providers.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.debugger.memory.filtering import com.intellij.debugger.memory.ui.JavaReferenceInfo import com.intellij.xdebugger.memory.ui.ReferenceInfo import com.intellij.xdebugger.memory.utils.InstancesProvider import com.sun.jdi.ObjectReference import com.sun.jdi.ReferenceType internal interface InstanceProviderEx : InstancesProvider { fun returnAllInstancesOfAClass(): Boolean /** * Return the number of instances that [getInstances] will return, * or [Int.MAX_VALUE] if the count is unknown. */ fun estimateInstancesCount(): Int } internal class FixedListProvider(private val references: List<ObjectReference>) : InstanceProviderEx { override fun getInstances(limit: Int): MutableList<ReferenceInfo> = references.mapToInfoList() override fun returnAllInstancesOfAClass() = false override fun estimateInstancesCount(): Int = references.size } internal class ClassInstancesProvider(private val referenceType: ReferenceType) : InstanceProviderEx { override fun getInstances(limit: Int): MutableList<ReferenceInfo> = referenceType.instances(limit.toLong()).mapToInfoList() override fun returnAllInstancesOfAClass() = true override fun estimateInstancesCount(): Int = referenceType.virtualMachine().instanceCounts(listOf(referenceType))[0] .let { if (it < 0 || it > Int.MAX_VALUE) Int.MAX_VALUE else it.toInt() } } private fun List<ObjectReference>?.mapToInfoList(): MutableList<ReferenceInfo> = this?.mapTo(ArrayList()) { JavaReferenceInfo(it) } ?: mutableListOf()
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
1,634
intellij-community
Apache License 2.0
src/main/java/me/oriharel/machinery/machine/Machine.kt
Heknon
263,055,461
false
null
package me.oriharel.machinery.machine import me.oriharel.machinery.Buildable import me.oriharel.machinery.OwnableStructure import me.oriharel.machinery.structure.schematic.Schematic import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.inventory.Inventory import org.bukkit.inventory.InventoryHolder import java.util.* class Machine( override val structure: Pair<String, Schematic>, override val owner: UUID, override val allowedAccessors: Set<UUID> ) : OwnableStructure, InventoryHolder, Buildable { override fun getInventory(): Inventory { return Bukkit.createInventory(this, 2) } override fun build(location: Location) { } }
0
Kotlin
0
0
a0dd03ef0773e0d6f4c1a2862486103c4887bb87
696
Machinery-2.0
MIT License
app/src/main/java/com/lyscraft/apparel/compose/components/CustomLoadingSpinner.kt
brahman10
843,088,920
false
{"Kotlin": 47388}
package com.lyscraft.apparel.compose.components import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp /** * Created by <NAME> */ @Composable fun CustomLoadingSpinner() { val infiniteTransition = rememberInfiniteTransition(label = "Shimmer") val animatedIndex by infiniteTransition.animateFloat( initialValue = 0f, targetValue = 12f, animationSpec = infiniteRepeatable( animation = tween(durationMillis = 1200, easing = LinearEasing), repeatMode = RepeatMode.Restart ), label = "Shimmer" ) Box( contentAlignment = Alignment.Center, modifier = Modifier .fillMaxSize() .background(Color(0xFFE0E0E0), shape = RoundedCornerShape(20.dp)) ) { Canvas(modifier = Modifier.size(40.dp)) { val strokeWidth = 4.dp.toPx() val segmentAngle = 30f val totalSegments = 12 val radius = size.minDimension / 2 - strokeWidth / 2 val centerGap = 14.dp.toPx() for (i in 0 until totalSegments) { // Exclude the last segment if (i != animatedIndex.toInt() % totalSegments) { rotate(degrees = i * segmentAngle) { drawLine( color = Color(0xFF888888), start = center.copy(y = center.y - centerGap), end = center.copy(y = center.y - radius), strokeWidth = strokeWidth, cap = StrokeCap.Round ) } } } } } } @Preview @Composable fun CircularProgressBarDemo() { CustomLoadingSpinner() }
0
Kotlin
0
0
fdfbc5a48a48933d667f97aefba8348f11bf56d8
2,692
MovieAppCompose
MIT License
src/main/kotlin/com/query/utils/TrackData.kt
osrsquery
453,886,617
false
{"Kotlin": 183180, "Java": 45630}
package com.query.utils import java.io.File object TrackData { val musicNames = mapOf( 0 to "" ) } fun main() { File("C:\\Users\\Shadow\\Desktop\\track1_by_file\\").listFiles().forEach { val name = it.nameWithoutExtension.substring(4) println("0 to $name ,") } }
1
Kotlin
3
3
00d256ae992ebdf2c2301bfb8b9a684aaeee3412
307
OsrsQuery
MIT License
analysis/analysis-api/testData/components/compilerFacility/compilation/sourceLibModuleInlineFuncOfCompanion.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// DUMP_IR // MODULE: ui // MODULE_KIND: LibraryBinary // FILE: com/example/ui/Text.kt package com.example.ui fun Text(text: String) {} // MODULE: myModule // TARGET_PLATFORM: Common // FILE: com/example/myModule/OtherModule.kt @file:JvmName("SpecialName") package com.example.myModule class OtherModule { companion object { inline fun giveMeString(): String { return secret() } @PublishedApi internal fun secret(): String { return "what is up!!!!!!!" } } companion object Named { inline fun giveMeString(): String { return secret() } @PublishedApi internal fun secret(): String { return "what is up!!!!!!!" } } } object Another { inline fun giveMeString(): String { return secret() } @PublishedApi internal fun secret(): String { return "what is up!!!!!!!" } } // MODULE: main(myModule, ui) // TARGET_PLATFORM: JVM // FILE: main.kt package home import com.example.myModule.Another import com.example.myModule.OtherModule import com.example.ui.Text fun Greeting(name: String) { Text( text = "$name!" + OtherModule.giveMeString() + OtherModule.Named.giveMeString() + Another.giveMeString() ) }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,301
kotlin
Apache License 2.0
egklib/src/commonTest/kotlin/electionguard/protoconvert/ConvertTestUtils.kt
danwallach
425,905,229
false
null
package electionguard.protoconvert import electionguard.core.* import io.kotest.property.Arb import io.kotest.property.arbitrary.map import io.ktor.utils.io.core.* import kotlin.random.Random import kotlin.random.nextUInt fun generateRangeChaumPedersenProofKnownNonce( context: GroupContext ): ChaumPedersenRangeProofKnownNonce { return ChaumPedersenRangeProofKnownNonce( listOf(generateGenericChaumPedersenProof(context)), ) } fun generateGenericChaumPedersenProof(context: GroupContext): ChaumPedersenProof { return ChaumPedersenProof(generateElementModQ(context), generateElementModQ(context),) } fun generateSchnorrProof(context: GroupContext): SchnorrProof { return SchnorrProof( generatePublicKey(context), generateElementModQ(context), generateElementModQ(context), ) } fun generateCiphertext(context: GroupContext): ElGamalCiphertext { return ElGamalCiphertext(generateElementModP(context), generateElementModP(context)) } fun generateHashedCiphertext(context: GroupContext): HashedElGamalCiphertext { return HashedElGamalCiphertext(generateElementModP(context), "what".toByteArray(), generateUInt256(context), 42) } fun generateElementModQ(context: GroupContext): ElementModQ { return context.uIntToElementModQ(Random.nextUInt(134217689.toUInt())) } fun generateUInt256(context: GroupContext): UInt256 { return generateElementModQ(context).toUInt256(); } fun generateElementModP(context: GroupContext) = context.uIntToElementModP(Random.nextUInt(1879047647.toUInt())) fun generatePublicKey(group: GroupContext): ElementModP = group.gPowP(group.randomElementModQ())
31
Kotlin
1
4
ee2f5d1cb0d8866803ccdcd1e139ce9c253ade0a
1,659
electionguard-kotlin-multiplatform
MIT License
app/src/main/java/com/skyd/imomoe/view/adapter/SerializableRecycledViewPool.kt
sheepstar1
379,210,337
true
{"Kotlin": 476398, "Java": 86537}
package com.skyd.imomoe.view.adapter import androidx.recyclerview.widget.RecyclerView import java.io.Serializable class SerializableRecycledViewPool : RecyclerView.RecycledViewPool(), Serializable { }
0
null
0
0
5ea117710af7c74d489e2df131de02b8ce28de4b
202
Imomoe
Apache License 2.0
library/src/main/java/io/karn/notify/utils/Errors.kt
j0lzsnz3
133,006,795
true
{"Kotlin": 64803}
package io.karn.notify.utils internal object Errors { const val INVALID_STACK_KEY_ERROR = "Invalid stack key provided." }
0
Kotlin
0
0
f5d96c310304220062361fbb5462fe1402f2e50f
128
notify
MIT License
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/serenitea_pot/gallery/HomeSeekFurnitureOneRecord.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package org.anime_game_servers.multi_proto.gi.data.serenitea_pot.gallery import org.anime_game_servers.core.base.Version.GI_2_7_0 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.proto.ProtoModel @AddedIn(GI_2_7_0) @ProtoModel internal interface HomeSeekFurnitureOneRecord { var engagedPlayerScoreList: List<HomeSeekFurniturePlayerScore> var timestamp: Int }
0
Kotlin
2
6
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
432
anime-game-multi-proto
MIT License
app/src/main/kotlin/dev/aaa1115910/bv/util/LogCatcherUtil.kt
aaa1115910
571,702,700
false
{"Kotlin": 1683327}
package dev.aaa1115910.bv.util import dev.aaa1115910.bv.BVApp import io.github.oshai.kotlinlogging.KotlinLogging import java.io.BufferedReader import java.io.File import java.io.InputStreamReader import java.io.OutputStreamWriter import java.text.SimpleDateFormat import java.util.Date import java.util.Locale object LogCatcherUtil { private val logger = KotlinLogging.logger("LogCatcher") const val LOG_DIR = "crash_logs" private const val MANUAL_LOG_PREFIX = "logs_manual" private const val CRASH_LOG_PREFIX = "logs_crash" private const val MAX_LOG_COUNT = 10 var manualFiles: List<File> = emptyList() var crashFiles: List<File> = emptyList() fun installLogCatcher() { runCatching { Runtime.getRuntime().exec("logcat -c") logger.info { "clear logcat" } } val originHandler = Thread.getDefaultUncaughtExceptionHandler() Thread.setDefaultUncaughtExceptionHandler { thread, exception -> logger.error(exception) { "======== UncaughtException ========" } logLogcat() originHandler?.uncaughtException(thread, exception) } clearOldLogFiles() } fun logLogcat(manual: Boolean = false) { runCatching { val process = Runtime.getRuntime().exec("logcat -t 10000 -v threadtime") val reader = BufferedReader(InputStreamReader(process.inputStream)) val logDir = File(BVApp.context.filesDir, LOG_DIR) if (!logDir.exists()) logDir.mkdir() val logFile = File(logDir, createFilename(manual)) logFile.createNewFile() logger.info { "Log file: $logFile" } with(logFile.writer()) { writeDeviceInfo() writeAppInfo() appendLine("======== Logs ========") var line: String? while (reader.readLine().also { line = it } != null) { appendLine(line) } flush() close() reader.close() } }.onFailure { logger.error(it) { "write log to file failed" } } } private fun OutputStreamWriter.writeDeviceInfo() { val info = BVApp.context.packageManager.getPackageInfo(BVApp.context.packageName, 0) appendLine("======== Device info ========") appendLine("App Version: ${info.versionName} (${info.versionCode})") appendLine("Android Version: ${android.os.Build.VERSION.RELEASE} (${android.os.Build.VERSION.SDK_INT})") appendLine("Device: ${android.os.Build.DEVICE}") appendLine("Model: ${android.os.Build.MODEL}") appendLine("Manufacturer: ${android.os.Build.MANUFACTURER}") appendLine("Brand: ${android.os.Build.BRAND}") appendLine("Product: ${android.os.Build.PRODUCT}") appendLine("Type: ${android.os.Build.TYPE}") } private fun OutputStreamWriter.writeAppInfo() { appendLine("======== App Prefs ========") appendLine("Login: ${Prefs.isLogin}") appendLine("Incognito Mode: ${Prefs.incognitoMode}") appendLine("Api Type: ${Prefs.apiType.name}") appendLine("Default Resolution: ${Prefs.defaultQuality}") appendLine("Default Codec: ${Prefs.defaultVideoCodec.name}") appendLine("Default Audio: ${Prefs.defaultAudio.name}") appendLine("Enabled Proxy: ${Prefs.enableProxy}") appendLine("Using Old Player: ${Prefs.useOldPlayer}") } private fun createFilename(manual: Boolean): String { var filename = "" filename += if (manual) MANUAL_LOG_PREFIX else CRASH_LOG_PREFIX val date = SimpleDateFormat("yyyy-MM-dd_HH:mm:ss", Locale.getDefault()).format(Date()) filename += "_$date.log" return filename } fun updateLogFiles() { val files = File(BVApp.context.filesDir, LOG_DIR).listFiles() manualFiles = files ?.filter { it.name.startsWith(MANUAL_LOG_PREFIX) } ?.sortedBy { it.lastModified() } ?: emptyList() crashFiles = files ?.filter { it.name.startsWith(CRASH_LOG_PREFIX) } ?.sortedBy { it.lastModified() } ?: emptyList() } private fun clearOldLogFiles() { updateLogFiles() if (manualFiles.size > MAX_LOG_COUNT) { manualFiles.take(manualFiles.size - MAX_LOG_COUNT).forEach { it.delete() } } if (crashFiles.size > MAX_LOG_COUNT) { crashFiles.take(crashFiles.size - MAX_LOG_COUNT).forEach { it.delete() } } } }
22
Kotlin
161
1,429
ac8c6ca424a99840e4073d7aa8fe71ea8a898388
4,623
bv
MIT License
core/src/main/kotlin/br/com/devsrsouza/kotlinbukkitapi/config/parser/ComponentParser.kt
tomocrafter
247,660,549
true
{"Kotlin": 292496}
package br.com.devsrsouza.kotlinbukkitapi.config.parser import com.google.gson.Gson import net.md_5.bungee.api.chat.* import net.md_5.bungee.chat.* import java.lang.IllegalArgumentException import kotlin.reflect.KType import kotlin.reflect.KTypeProjection import kotlin.reflect.full.createType object ComponentParser : ObjectParser<TextComponent> { private val gson = Gson() override fun parse(any: Any): TextComponent { if(any is Map<*,*>) { val json = gson.toJson(any) return TextComponent(*ComponentSerializer.parse(json)) } else if(any is List<*>) { val json = gson.toJson(any) return TextComponent(*ComponentSerializer.parse(json)) } else throw IllegalArgumentException("can't parse ${any::class.simpleName} to TextComponent") } override fun render(element: TextComponent): Pair<Any, KType> { val json = ComponentSerializer.toString(element) return gson.fromJson<Map<*, *>>(json, Map::class.java) to Map::class.createType( listOf( KTypeProjection.invariant(String::class.createType()), KTypeProjection.invariant(Any::class.createType()) ) ) } }
0
null
0
0
9bec673e6ae67f710387cb1d102fa6582be2f191
1,228
KotlinBukkitAPI
MIT License
livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/FixtureChecks.kt
LivingDoc
85,412,044
false
null
package org.livingdoc.engine.execution import java.lang.reflect.Method import java.lang.reflect.Modifier /** * This function tests a list of functions for their number of parameters that should be zero * @param methods The list of methods that should be checked * @param annotationClass the class where the methods are from * @return a list of messages with a message for every method that has more than zero parameters */ internal fun checkThatMethodsHaveNoParameters(methods: List<Method>, annotationClass: Class<*>): List<String> { val annotationName = annotationClass.simpleName return methods .filter { it.parameterCount > 0 } .map { "@$annotationName method <$it> has ${it.parameterCount} parameter(s) - must not have any!" } } /** * This function tests a list of functions for their number of parameters that should be one * @param methods The list of methods that should be checked * @param annotationClass the class where the methods are from * @return a list of messages with a message for every method that has more or less than one parameter */ internal fun checkThatMethodsHaveExactlyOneParameter(methods: List<Method>, annotationClass: Class<*>): List<String> { val annotationName = annotationClass.simpleName return methods .filter { it.parameterCount != 1 } .map { "@$annotationName method <$it> has ${it.parameterCount} parameter(s) - must have exactly 1!" } } /** * This function tests a list of functions for being static * @param methods The list of methods that should be checked * @param annotationClass the class where the methods are from * @return a list of messages with a message for every method that is not static */ internal fun checkThatMethodsAreStatic(methods: List<Method>, annotationClass: Class<*>): List<String> { val annotationName = annotationClass.simpleName return methods .filter { !Modifier.isStatic(it.modifiers) } .map { "@$annotationName method <$it> must be static!" } } /** * This function tests a list of functions for being non-static * @param methods The list of methods that should be checked * @param annotationClass the class where the methods are from * @return a list of messages with a message for every method that is static */ internal fun checkThatMethodsAreNonStatic(methods: List<Method>, annotationClass: Class<*>): List<String> { val annotationName = annotationClass.simpleName return methods .filter { Modifier.isStatic(it.modifiers) } .map { "@$annotationName method <$it> must not be static!" } }
34
null
16
14
f3d52b8bacbdf81905e4b4a753d75f584329b297
2,585
livingdoc
Apache License 2.0
feature/lecture/src/main/java/com/msg/lecture/component/LectureFilterDialog.kt
School-of-Company
700,744,250
false
{"Kotlin": 724178}
package com.msg.lecture.component import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import com.msg.design_system.component.bottomsheet.SelectedIndicator import com.msg.design_system.component.icon.CloseIcon import com.msg.design_system.theme.BitgoeulAndroidTheme @Composable internal fun LectureFilterDialog( modifier: Modifier = Modifier, isVisible: Boolean, onCloseButtonClicked: () -> Unit, onFilterButtonClicked: (String?) -> Unit?, ) { val isFilterSelected = remember { mutableStateOf("0") } if (isVisible) { BitgoeulAndroidTheme { colors, typography -> Dialog(onDismissRequest = { onCloseButtonClicked() }) { Box( modifier = modifier .background(color = colors.WHITE, RoundedCornerShape(8.dp)) .wrapContentHeight() ) { Column( modifier = modifier.padding(horizontal = 24.dp, vertical = 24.dp) ) { Row { Text( text = stringResource(id = com.msg.design_system.R.string.lecture_list), style = typography.titleSmall, color = colors.BLACK, ) Spacer(modifier = modifier.weight(1f)) CloseIcon( modifier = modifier.clickable { onCloseButtonClicked() } ) } Spacer(modifier = modifier.height(24.dp)) Row( verticalAlignment = Alignment.CenterVertically ) { SelectedIndicator( modifier = modifier.size(20.dp), isSelected = isFilterSelected.value == "0", onClicked = { onFilterButtonClicked(null) isFilterSelected.value = "0" } ) Spacer(modifier = modifier.width(8.dp)) Text( text = stringResource(id = com.msg.design_system.R.string.entire), style = typography.bodySmall, color = colors.BLACK ) } Spacer(modifier = modifier.height(16.dp)) Row( verticalAlignment = Alignment.CenterVertically ) { SelectedIndicator( modifier = modifier.size(20.dp), isSelected = isFilterSelected.value == "1", onClicked= { onFilterButtonClicked("상호학점인정교육과정") isFilterSelected.value = "1" } ) Spacer(modifier = modifier.width(8.dp)) Text( text = stringResource(id = com.msg.design_system.R.string.mutual_credit_recognition_curriculum), style = typography.bodySmall, color = colors.BLACK ) } Spacer(modifier = modifier.height(16.dp)) Row( verticalAlignment = Alignment.CenterVertically ) { SelectedIndicator( modifier = modifier.size(20.dp), isSelected = isFilterSelected.value == "2", onClicked = { onFilterButtonClicked("대학탐방프로그램") isFilterSelected.value = "2" } ) Spacer(modifier = modifier.width(8.dp)) Text( text = stringResource(id = com.msg.design_system.R.string.university_visit_program), style = typography.bodySmall, color = colors.BLACK ) } } } } } } }
7
Kotlin
1
22
358bf40188fa2fc2baf23aa6b308b039cb3fbc8c
5,695
Bitgoeul-Android
MIT License
lib/src/main/kotlin/com/ibm/cloud/appconfiguration/android/sdk/core/ServiceImpl.kt
srikanthkm
331,219,771
false
{"Kotlin": 127899}
/** * Copyright 2021 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.cloud.appconfiguration.android.sdk.core import com.google.gson.Gson import com.google.gson.JsonObject import com.ibm.cloud.appconfiguration.android.sdk.AppConfiguration import com.ibm.cloud.appconfiguration.android.sdk.BuildConfig import com.ibm.cloud.appconfiguration.android.sdk.configurations.internal.ConfigConstants import com.ibm.cloud.sdk.core.http.HttpHeaders import com.ibm.cloud.sdk.core.http.HttpMediaType import com.ibm.cloud.sdk.core.http.RequestBuilder import com.ibm.cloud.sdk.core.http.Response import com.ibm.cloud.sdk.core.security.Authenticator import com.ibm.cloud.sdk.core.security.IamAuthenticator import com.ibm.cloud.sdk.core.service.BaseService import com.ibm.cloud.sdk.core.util.ResponseConverterUtils import org.json.JSONObject /** * A wrapper class consisting of methods that perform API request/response handling of the AppConfiguration SDK * by extending the [BaseService]. */ class ServiceImpl(name: String?, authenticator: Authenticator?) : BaseService(name, authenticator) { companion object Factory { private var instance: ServiceImpl? = null /** * @return instance of [ServiceImpl] */ fun getInstance(): ServiceImpl { if (instance == null) instance = ServiceImpl(ConfigConstants.SERVICE_NAME, createIamAuth()) return instance!! } private fun createIamAuth(): IamAuthenticator? { return if (AppConfiguration().getOverrideServiceUrl() != null) { IamAuthenticator.Builder() .url(ConfigConstants.DEFAULT_HTTP_TYPE + ConfigConstants.DEFAULT_IAM_DEV_STAGE_URL) .apikey(AppConfiguration.getInstance().getApikey()) .build() } else { //this automatically calls iam prod url IamAuthenticator.Builder() .apikey(AppConfiguration.getInstance().getApikey()) .build() } } } private fun getServiceHeaders(): HashMap<String, String> { val headers: HashMap<String, String> = HashMap() headers[HttpHeaders.ACCEPT] = HttpMediaType.APPLICATION_JSON headers[HttpHeaders.USER_AGENT] = BuildConfig.LIBRARY_PACKAGE_NAME + "/" + BuildConfig.VERSION_NAME return headers } /** * Execute GET API request. * * @param url url to get configurations * @return the HTTP response */ fun getConfig(url: String?): Response<String>? { return try { Logger.debug("Sending request to AppConfiguration server with url = $url") val builder = RequestBuilder.get(RequestBuilder.resolveRequestUrl(url, null, null)) for ((key, value) in getServiceHeaders()) { builder.header(key, value) } val responseConverter = ResponseConverterUtils.getString() createServiceCall(builder.build(), responseConverter).execute() } catch (e: Exception) { e.localizedMessage?.let { Logger.error(it) } null } } /** * Execute POST API request. * * @param meteringUrl url to send metering data * @param data data to send * @return the HTTP response */ fun postMetering(meteringUrl: String?, data: JSONObject): Response<String>? { return try { val builder = RequestBuilder.post(RequestBuilder.resolveRequestUrl(meteringUrl, null, null)) for ((key, value) in getServiceHeaders()) { builder.header(key, value) } builder.header(HttpHeaders.CONTENT_TYPE, "application/json") val jsonData = Gson().fromJson(data.toString(), JsonObject::class.java) builder.bodyJson(jsonData) val responseConverter = ResponseConverterUtils.getString() createServiceCall(builder.build(), responseConverter).execute() } catch (e: Exception) { e.localizedMessage?.let { Logger.error(it) } null } } }
0
Kotlin
3
0
2fc84a9aae56bb5364f640052d5630f89fc20d06
4,745
appconfiguration-android-client-sdk
Apache License 2.0