path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/jpb/scratchtappy/usp/PlatLogoActivity.kt
jpbandroid
517,991,180
false
{"Kotlin": 128048, "C++": 6528, "Java": 3694, "CMake": 2010, "C": 153}
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jpb.scratchtappy import com.jpb.scratchtappy.getSystemColor import kotlin.jvm.JvmOverloads import android.graphics.drawable.Drawable import android.graphics.drawable.VectorDrawable import android.content.IntentFilter import android.content.Intent import android.view.View.MeasureSpec import android.content.BroadcastReceiver import android.text.format.DateUtils import android.content.res.TypedArray import com.jpb.scratchtappy.R import androidx.core.content.ContextCompat import android.app.Activity import com.jpb.scratchtappy.PlatLogoActivity.SettableAnalogClock import com.jpb.scratchtappy.PlatLogoActivity.BubblesDrawable import android.os.Bundle import android.widget.FrameLayout import android.util.DisplayMetrics import android.view.Gravity import android.graphics.drawable.GradientDrawable import android.graphics.drawable.LayerDrawable import android.view.animation.OvershootInterpolator import android.animation.ObjectAnimator import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.view.MotionEvent import android.view.HapticFeedbackConstants import com.jpb.scratchtappy.PlatLogoActivity import com.jpb.scratchtappy.PlatLogoActivity.Bubble import android.text.format.Time import android.util.Log import android.view.View import android.view.animation.DecelerateInterpolator import android.widget.ImageView import android.widget.Toast import com.google.android.material.color.DynamicColors import java.lang.Exception /** * Android S */ class PlatLogoActivity : Activity() { private val MAX_BUBBS = 2000 // private static final String S_EGG_UNLOCK_SETTING = "egg_mode_s"; private var mClock: SettableAnalogClock? = null private var mLogo: ImageView? = null private var mBg: BubblesDrawable? = null // @Override // protected void onPause() { // super.onPause(); // } override fun onCreate(savedInstanceState: Bundle?) { DynamicColors.applyIfAvailable(this); super.onCreate(savedInstanceState) window.navigationBarColor = 0 window.statusBarColor = 0 val ab = actionBar ab?.hide() val layout = FrameLayout(this) mClock = SettableAnalogClock(this) val dm = resources.displayMetrics val dp = dm.density val minSide = Math.min(dm.widthPixels, dm.heightPixels) val widgetSize = (minSide * 0.75).toInt() val lp = FrameLayout.LayoutParams(widgetSize, widgetSize) lp.gravity = Gravity.CENTER layout.addView(mClock, lp) mLogo = ImageView(this) mLogo!!.visibility = View.GONE // mLogo.setImageResource(R.drawable.s_platlogo); mLogo!!.setImageDrawable(createDrawable()) layout.addView(mLogo, lp) mBg = BubblesDrawable() mBg!!.level = 0 mBg!!.avoid = (widgetSize / 2).toFloat() mBg!!.padding = 0.5f * dp mBg!!.minR = 1 * dp layout.background = mBg setContentView(layout) } @SuppressLint("ResourceAsColor") private fun createDrawable(): Drawable? { var color = -1 try { color = this.getSystemColor("system_accent3_500") } catch (ignore: Exception) { } if (color != -1) { color = R.color.purple_500 val drawable = ContextCompat.getDrawable(this, R.drawable.s_platlogo_nobg) val bg = GradientDrawable() bg.shape = GradientDrawable.OVAL bg.setColor(color) return LayerDrawable(arrayOf(bg, drawable)) } return ContextCompat.getDrawable(this, R.drawable.s_platlogo) } // private boolean shouldWriteSettings() { // return getPackageName().equals("android"); // } @SuppressLint("ObjectAnimatorBinding") private fun launchNextStage(locked: Boolean) { mClock!!.animate() .alpha(0f).scaleX(0.5f).scaleY(0.5f) .withEndAction { mClock!!.visibility = View.GONE } .start() mLogo!!.alpha = 0f mLogo!!.scaleX = 0.5f mLogo!!.scaleY = 0.5f mLogo!!.visibility = View.VISIBLE mLogo!!.animate() .alpha(1f) .scaleX(1f) .scaleY(1f) .setInterpolator(OvershootInterpolator()) .start() mLogo!!.postDelayed( { val anim = ObjectAnimator.ofInt(mBg, "level", 0, 10000) anim.interpolator = DecelerateInterpolator(1f) anim.start() }, 500 ) // final ContentResolver cr = getContentResolver(); // // try { // if (shouldWriteSettings()) { // Log.v(TAG, "Saving egg unlock=" + locked); // syncTouchPressure(); // Settings.System.putLong(cr, // S_EGG_UNLOCK_SETTING, // locked ? 0 : System.currentTimeMillis()); // } // } catch (RuntimeException e) { // Log.e(TAG, "Can't write settings", e); // } // // try { // startActivity(new Intent(Intent.ACTION_MAIN) // .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK // | Intent.FLAG_ACTIVITY_CLEAR_TASK) // .addCategory("com.android.internal.category.PLATLOGO")); // } catch (ActivityNotFoundException ex) { // Log.e("com.android.internal.app.PlatLogoActivity", "No more eggs."); // } //finish(); // no longer finish upon unlock; it's fun to frob the dial } // static final String TOUCH_STATS = "touch.stats"; // double mPressureMin = 0, mPressureMax = -1; // // private void measureTouchPressure(MotionEvent event) { // final float pressure = event.getPressure(); // switch (event.getActionMasked()) { // case MotionEvent.ACTION_DOWN: // if (mPressureMax < 0) { // mPressureMin = mPressureMax = pressure; // } // break; // case MotionEvent.ACTION_MOVE: // if (pressure < mPressureMin) mPressureMin = pressure; // if (pressure > mPressureMax) mPressureMax = pressure; // break; // } // } // // private void syncTouchPressure() { // try { // final String touchDataJson = Settings.System.getString( // getContentResolver(), TOUCH_STATS); // final JSONObject touchData = new JSONObject( // touchDataJson != null ? touchDataJson : "{}"); // if (touchData.has("min")) { // mPressureMin = Math.min(mPressureMin, touchData.getDouble("min")); // } // if (touchData.has("max")) { // mPressureMax = Math.max(mPressureMax, touchData.getDouble("max")); // } // if (mPressureMax >= 0) { // touchData.put("min", mPressureMin); // touchData.put("max", mPressureMax); // if (shouldWriteSettings()) { // Settings.System.putString(getContentResolver(), TOUCH_STATS, // touchData.toString()); // } // } // } catch (Exception e) { // Log.e(TAG, "Can't write touch settings", e); // } // } // // @Override // public void onStart() { // super.onStart(); // syncTouchPressure(); // } // // @Override // public void onStop() { // syncTouchPressure(); // super.onStop(); // } /** * Subclass of AnalogClock that allows the user to flip up the glass and adjust the hands. */ inner class SettableAnalogClock(context: Context) : AnalogClock(context) { private var mOverrideHour = -1 private var mOverrideMinute = -1 private var mOverride = false public override fun now(): Time? { val realNow = super.now() // final Instant realNow = super.now(); // final ZoneId tz = Clock.systemDefaultZone().getZone(); // final ZonedDateTime zdTime = realNow.atZone(tz); if (mOverride) { if (mOverrideHour < 0) { // mOverrideHour = zdTime.getHour(); mOverrideHour = realNow!!.hour } realNow!![0, mOverrideMinute, mOverrideHour, realNow.monthDay, realNow.month] = realNow.year // return Clock.fixed(zdTime // .withHour(mOverrideHour) // .withMinute(mOverrideMinute) // .withSecond(0) // .toInstant(), tz).instant(); // } else { // return realNow; } return realNow } fun toPositiveDegrees(rad: Double): Double { return (Math.toDegrees(rad) + 360 - 90) % 360 } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(ev: MotionEvent): Boolean { when (ev.actionMasked) { MotionEvent.ACTION_DOWN -> { mOverride = true // measureTouchPressure(ev); val x = ev.x val y = ev.y val cx = width / 2f val cy = height / 2f val angle = toPositiveDegrees( Math.atan2( (x - cx).toDouble(), (y - cy).toDouble() ) ).toFloat() val minutes = (75 - (angle / 6).toInt()) % 60 val minuteDelta = minutes - mOverrideMinute if (minuteDelta != 0) { if (Math.abs(minuteDelta) > 45 && mOverrideHour >= 0) { val hourDelta = if (minuteDelta < 0) 1 else -1 mOverrideHour = (mOverrideHour + 24 + hourDelta) % 24 } mOverrideMinute = minutes if (mOverrideMinute == 0) { performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) if (scaleX == 1f) { scaleX = 1.05f scaleY = 1.05f animate().scaleX(1f).scaleY(1f).setDuration(150).start() } } else { performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) } onTimeChanged() postInvalidate() } return true } MotionEvent.ACTION_MOVE -> { val x = ev.x val y = ev.y val cx = width / 2f val cy = height / 2f val angle = toPositiveDegrees( Math.atan2( (x - cx).toDouble(), (y - cy).toDouble() ) ).toFloat() val minutes = (75 - (angle / 6).toInt()) % 60 val minuteDelta = minutes - mOverrideMinute if (minuteDelta != 0) { if (Math.abs(minuteDelta) > 45 && mOverrideHour >= 0) { val hourDelta = if (minuteDelta < 0) 1 else -1 mOverrideHour = (mOverrideHour + 24 + hourDelta) % 24 } mOverrideMinute = minutes if (mOverrideMinute == 0) { performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) if (scaleX == 1f) { scaleX = 1.05f scaleY = 1.05f animate().scaleX(1f).scaleY(1f).setDuration(150).start() } } else { performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) } onTimeChanged() postInvalidate() } return true } MotionEvent.ACTION_UP -> { if (mOverrideMinute == 0 && mOverrideHour % 12 == 0) { val text = "12:00 let's gooooo" val duration = Toast.LENGTH_LONG val toast = Toast.makeText(applicationContext, text, duration) toast.show() Log.v(TAG, "12:00 let's gooooo") performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) launchNextStage(false) } return true } } return false } } internal class Bubble { var x = 0f var y = 0f var r = 0f var color = 0 } internal inner class BubblesDrawable : Drawable() { // private final int[] mColorIds = { // android.R.color.system_accent1_400, // android.R.color.system_accent1_500, // android.R.color.system_accent1_600, // // android.R.color.system_accent2_400, // android.R.color.system_accent2_500, // android.R.color.system_accent2_600, // }; private val mColorIds = arrayOf( "system_accent1_400", "system_accent1_500", "system_accent1_600", "system_accent2_400", "system_accent2_500", "system_accent2_600" ) // private int[] mColors = new int[mColorIds.length]; private val mColors = intArrayOf(-0xa67209, -0xc88e21, -0xdaa644, -0x756e5d, -0x8f8979, -0xa7a191) private val mBubbs = arrayOfNulls<Bubble>(MAX_BUBBS) private var mNumBubbs = 0 private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG) var avoid = 0f var padding = 0f var minR = 0f override fun draw(canvas: Canvas) { val f = level / 10000f mPaint.style = Paint.Style.FILL var drawn = 0 for (j in 0 until mNumBubbs) { if (mBubbs[j]!!.color == 0 || mBubbs[j]!!.r == 0f) continue mPaint.color = mBubbs[j]!!.color canvas.drawCircle(mBubbs[j]!!.x, mBubbs[j]!!.y, mBubbs[j]!!.r * f, mPaint) drawn++ } } override fun onLevelChange(level: Int): Boolean { invalidateSelf() return true } override fun onBoundsChange(bounds: Rect) { super.onBoundsChange(bounds) randomize() } private fun randomize() { val w = bounds.width().toFloat() val h = bounds.height().toFloat() val maxR = Math.min(w, h) / 3f mNumBubbs = 0 if (avoid > 0f) { mBubbs[mNumBubbs]!!.x = w / 2f mBubbs[mNumBubbs]!!.y = h / 2f mBubbs[mNumBubbs]!!.r = avoid mBubbs[mNumBubbs]!!.color = 0 mNumBubbs++ } for (j in 0 until MAX_BUBBS) { // a simple but time-tested bubble-packing algorithm: // 1. pick a spot // 2. shrink the bubble until it is no longer overlapping any other bubble // 3. if the bubble hasn't popped, keep it var tries = 5 while (tries-- > 0) { val x = Math.random().toFloat() * w val y = Math.random().toFloat() * h var r = Math.min(Math.min(x, w - x), Math.min(y, h - y)) // shrink radius to fit other bubbs for (i in 0 until mNumBubbs) { r = Math.min( r.toDouble(), Math.hypot( (x - mBubbs[i]!!.x).toDouble(), (y - mBubbs[i]!!.y).toDouble() ) - mBubbs[i]!!.r - padding ).toFloat() if (r < minR) break } if (r >= minR) { // we have found a spot for this bubble to live, let's save it and move on r = Math.min(maxR, r) mBubbs[mNumBubbs]!!.x = x mBubbs[mNumBubbs]!!.y = y mBubbs[mNumBubbs]!!.r = r mBubbs[mNumBubbs]!!.color = mColors[(Math.random() * mColors.size).toInt()] mNumBubbs++ break } } } Log.v( TAG, String.format( "successfully placed %d bubbles (%d%%)", mNumBubbs, (100f * mNumBubbs / MAX_BUBBS).toInt() ) ) } override fun setAlpha(alpha: Int) {} override fun setColorFilter(colorFilter: ColorFilter?) {} @Deprecated("Deprecated in Java") override fun getOpacity(): Int { return PixelFormat.TRANSLUCENT } init { try { for (i in mColorIds.indices) { mColors[i] = [email protected](mColorIds[i]) } } catch (ignore: Exception) { } for (j in mBubbs.indices) { mBubbs[j] = Bubble() } } } companion object { private const val TAG = "PlatLogoActivity" } }
9
Kotlin
0
1
953017a381bd0d908c4b675fb3adeef0483a0e9a
19,026
USP
Apache License 2.0
app/src/main/java/io/github/wulkanowy/utils/SpinnerExtension.kt
wezuwiusz
827,505,734
false
{"Kotlin": 1759089, "HTML": 1949, "Shell": 257}
package io.github.wulkanowy.utils import android.view.View import android.widget.AdapterView import android.widget.Spinner /** * @see <a href="https://stackoverflow.com/a/29602298">How to keep onItemSelected from firing off on a newly instantiated Spinner?</a> */ @Suppress("UNCHECKED_CAST") inline fun <T : View> Spinner.setOnItemSelectedListener(crossinline listener: (view: T?) -> Unit) { onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { listener(view as T?) } } } } }
1
Kotlin
6
28
82b4ea930e64d0d6e653fb9024201b372cdb5df2
997
neowulkanowy
Apache License 2.0
androidApp/src/main/java/com/mutualmobile/harvestKmp/android/ui/screens/newEntryScreen/components/DatePicker.kt
mutualmobile
495,292,087
false
null
package com.mutualmobile.harvestKmp.android.ui.screens.newEntryScreen.components import android.text.format.DateFormat import android.view.ContextThemeWrapper import android.widget.CalendarView import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.TextButton 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.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import com.mutualmobile.harvestKmp.android.R import java.util.Calendar import java.util.Date @Composable fun DatePicker( minDate: Long? = null, maxDate: Long? = null, onDateSelected: (Date) -> Unit, onDismissRequest: () -> Unit ) { val selDate = remember { mutableStateOf(Calendar.getInstance().time) } Dialog(onDismissRequest = { onDismissRequest() }, properties = DialogProperties()) { Column( modifier = Modifier .wrapContentSize() .background( color = MaterialTheme.colors.surface, shape = RoundedCornerShape(size = 16.dp) ) ) { Column( Modifier .defaultMinSize(minHeight = 72.dp) .fillMaxWidth() .background( color = MaterialTheme.colors.primary, shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp) ) .padding(16.dp) ) { Text( text = "Select date", style = MaterialTheme.typography.body1, color = MaterialTheme.colors.onPrimary ) Spacer(modifier = Modifier.size(24.dp)) Text( text = DateFormat.format("MMM d, yyyy", selDate.value).toString(), style = MaterialTheme.typography.h4, color = MaterialTheme.colors.onPrimary, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.size(16.dp)) } CustomCalendarView( minDate, maxDate, onDateSelected = { selDate.value = it } ) Spacer(modifier = Modifier.size(8.dp)) Row( modifier = Modifier .align(Alignment.End) .padding(bottom = 16.dp, end = 16.dp) ) { TextButton(onClick = onDismissRequest) { Text( text = "Cancel", ) } TextButton( onClick = { val newDate = selDate.value onDateSelected( // This makes sure date is not out of range Date( maxOf( minOf(maxDate ?: Long.MAX_VALUE, newDate.time), minDate ?: Long.MIN_VALUE ) ) ) onDismissRequest() }, ) { Text( text = "OK", ) } } } } } @Composable private fun CustomCalendarView( minDate: Long? = null, maxDate: Long? = null, onDateSelected: (Date) -> Unit ) { AndroidView( modifier = Modifier.wrapContentSize(), factory = { context -> CalendarView(ContextThemeWrapper(context, R.style.CalenderViewCustom)) }, update = { view -> if (minDate != null) view.minDate = minDate if (maxDate != null) view.maxDate = maxDate view.setOnDateChangeListener { _, year, month, dayOfMonth -> onDateSelected( Calendar .getInstance() .apply { set(year, month, dayOfMonth) } .time ) } } ) }
0
Kotlin
4
41
763dd7f45f8271cebe9107c63f3532e1b14c666f
5,156
HarvestTimeKMP
Apache License 2.0
app/templates/app-kotlin/src/main/java/ui/main/MainActivity.kt
heralight
74,270,583
true
{"Java": 131799, "JavaScript": 108752, "Kotlin": 60437}
package <%= appPackage %>.ui.main import android.os.Bundle import <%= appPackage %>.di.ActivityScope import <%= appPackage %>.di.components.MainComponent; import <%= appPackage %>.di.HasComponent import <%= appPackage %>.ui.base.BaseActivity import <%= appPackage %>.R import <%= appPackage %>.application.App import <%= appPackage %>.di.components.DaggerMainComponent import <%= appPackage %>.di.modules.MainModule <% if (nucleus == true) { %>import nucleus.factory.PresenterFactory <% } %> import javax.inject.Inject @ActivityScope class MainActivity : BaseActivity<MainPresenter>(), MainView, HasComponent<MainComponent>{ @Inject lateinit var mainPresenter: MainPresenter lateinit var mainComponent: MainComponent override fun injectModule() { mainComponent = DaggerMainComponent.builder().applicationComponent(App.get(this).getComponent()).mainModule(MainModule(this)).build() mainComponent.inject(this) } <% if (nucleus == true) { %>override fun getPresenterFactory(): PresenterFactory<MainPresenter>? = PresenterFactory { mainPresenter }<% } else { %> override fun getPresenter(): MainPresenter { return mainPresenter }<% } %> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun getLayoutResource(): Int { return R.layout.activity_main } override fun getComponent(): MainComponent { return mainComponent } <% if (nucleus == false) { %> override fun onResume() { super.onResume() getPresenter().takeView(this) } override fun onPause() { super.onPause() getPresenter().dropView() }<% } %> }
0
Java
0
1
c15b1ad2743a5e71c4d900fd8fcb8a7ae809f1cb
1,715
generator-android-hipster
Apache License 2.0
idea/testData/quickfix/inlineTypeParameterFix/function.kt
JakeWharton
99,388,807
true
null
// "Inline type parameter" "true" data class DC(val x: Int, val y: String) { fun <S : Int<caret>> foo() { val a: S = Int.MAX_VALUE } } // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.InlineTypeParameterFix
1
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
231
kotlin
Apache License 2.0
io/http/src/test/kotlin/io/bluetape4k/http/hc5/examples/ClientWithRequestFuture.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.http.hc5.examples import io.bluetape4k.http.hc5.AbstractHc5Test import io.bluetape4k.http.hc5.classic.httpClientConnectionManager import io.bluetape4k.http.hc5.classic.httpClientOf import io.bluetape4k.http.hc5.http.futureRequestExecutionServiceOf import io.bluetape4k.http.hc5.protocol.httpClientContextOf import io.bluetape4k.logging.KLogging import io.bluetape4k.logging.debug import io.bluetape4k.logging.error import org.amshove.kluent.fail import org.apache.hc.client5.http.classic.methods.HttpGet import org.apache.hc.core5.concurrent.FutureCallback import org.apache.hc.core5.http.HttpStatus import org.apache.hc.core5.http.io.HttpClientResponseHandler import org.junit.jupiter.api.Test import java.util.concurrent.CancellationException import java.util.concurrent.Executors import java.util.concurrent.TimeUnit class ClientWithRequestFuture: AbstractHc5Test() { companion object: KLogging() @Test fun `client with request future`() { // the simplest way to create a HttpAsyncClientWithFuture val cm = httpClientConnectionManager { setMaxConnPerRoute(5) setMaxConnTotal(5) } val httpclient = httpClientOf(cm) val executor = Executors.newFixedThreadPool(5) futureRequestExecutionServiceOf(httpclient, executor).use { requestExecService -> // Because things are asynchronous, you must provide a HttpClientResponseHandler val handler = HttpClientResponseHandler { response -> // simply return true if the status was OK response.code == HttpStatus.SC_OK } // Simple request .. val request1 = HttpGet("$httpbinBaseUrl/get") val futureTask1 = requestExecService.execute(request1, httpClientContextOf(), handler) val wasItOk1 = futureTask1.get() log.debug { "It was ok? $wasItOk1" } // Cancel a request try { val request2 = HttpGet("$httpbinBaseUrl/get") val futureTask2 = requestExecService.execute(request2, httpClientContextOf(), handler) futureTask2.cancel(true) Thread.sleep(10) val wasItOk2 = futureTask2.get() fail("여기까지 실행되면 안됩니다. 작업이 취소되어야 합니다.") } catch (e: CancellationException) { log.debug { "We cancelled it, so this is expected" } } // Request with a timeout val request3 = HttpGet("$httpbinBaseUrl/get") val futureTask3 = requestExecService.execute(request3, httpClientContextOf(), handler) val wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS) log.debug { "It was ok? $wasItOk3" } val callback = object: FutureCallback<Boolean> { override fun completed(result: Boolean?) { log.debug { "completed with $result" } } override fun failed(ex: Exception?) { log.error(ex) { "failed." } } override fun cancelled() { log.debug { "cancelled" } } } // Simple request with callback val request4 = HttpGet("$httpbinBaseUrl/get") // using a null HttpContext here since it is optional // the callback will be called when the task completes, fails, or is cancelled val futureTask4 = requestExecService.execute(request4, httpClientContextOf(), handler, callback) val wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS) log.debug { "It was ok? $wasItOk4" } } } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
3,704
bluetape4k
MIT License
cinescout/watchlist/domain/src/commonMain/kotlin/cinescout/watchlist/domain/usecase/SyncWatchlist.kt
fardavide
280,630,732
false
null
package cinescout.watchlist.domain.usecase import arrow.core.Either import cinescout.error.NetworkError import cinescout.screenplay.domain.model.ScreenplayTypeFilter import cinescout.sync.domain.model.RequiredSync interface SyncWatchlist { suspend operator fun invoke( type: ScreenplayTypeFilter, requiredSync: RequiredSync ): Either<NetworkError, Unit> suspend operator fun invoke() = invoke(ScreenplayTypeFilter.All, RequiredSync.Complete) }
8
Kotlin
2
6
dcbd0a0b70d6203a2ba1959b797038564d0f04c4
476
CineScout
Apache License 2.0
tools/blobinspector/src/main/kotlin/net/corda/blobinspector/BlobInspector.kt
renlulu
160,531,644
false
null
package net.corda.blobinspector import com.fasterxml.jackson.core.JsonFactory import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.jcabi.manifests.Manifests import net.corda.client.jackson.JacksonSupport import net.corda.cliutils.CordaCliWrapper import net.corda.cliutils.ExitCodes import net.corda.cliutils.start import net.corda.core.internal.isRegularFile import net.corda.core.internal.rootMessage import net.corda.core.serialization.SerializationContext import net.corda.core.serialization.SerializationDefaults import net.corda.core.serialization.deserialize import net.corda.core.serialization.internal.SerializationEnvironmentImpl import net.corda.core.serialization.internal._contextSerializationEnv import net.corda.core.utilities.base64ToByteArray import net.corda.core.utilities.hexToByteArray import net.corda.core.utilities.sequence import net.corda.serialization.internal.AMQP_P2P_CONTEXT import net.corda.serialization.internal.AMQP_STORAGE_CONTEXT import net.corda.serialization.internal.CordaSerializationMagic import net.corda.serialization.internal.SerializationFactoryImpl import net.corda.serialization.internal.amqp.AbstractAMQPSerializationScheme import net.corda.serialization.internal.amqp.DeserializationInput import net.corda.serialization.internal.amqp.amqpMagic import org.slf4j.event.Level import picocli.CommandLine import picocli.CommandLine.* import java.io.PrintStream import java.net.MalformedURLException import java.net.URL import java.nio.file.Paths import java.util.* import kotlin.system.exitProcess fun main(args: Array<String>) { BlobInspector().start(args) } class BlobInspector : CordaCliWrapper("blob-inspector", "Convert AMQP serialised binary blobs to text") { @Parameters(index = "*..0", paramLabel = "SOURCE", description = ["URL or file path to the blob"], converter = [SourceConverter::class]) var source: MutableList<URL> = mutableListOf() @Option(names = ["--format"], paramLabel = "type", description = ["Output format. Possible values: [YAML, JSON]"]) private var formatType: OutputFormatType = OutputFormatType.YAML @Option(names = ["--input-format"], paramLabel = "type", description = ["Input format. If the file can't be decoded with the given value it's auto-detected, so you should never normally need to specify this. Possible values: [BINARY, HEX, BASE64]"]) private var inputFormatType: InputFormatType = InputFormatType.BINARY @Option(names = ["--full-parties"], description = ["Display the owningKey and certPath properties of Party and PartyAndReference objects respectively"]) private var fullParties: Boolean = false @Option(names = ["--schema"], description = ["Print the blob's schema first"]) private var schema: Boolean = false override fun runProgram() = run(System.out) override fun initLogging() { if (verbose) { loggingLevel = Level.TRACE } val loggingLevel = loggingLevel.name.toLowerCase(Locale.ENGLISH) System.setProperty("logLevel", loggingLevel) // This property is referenced from the XML config file. } fun run(out: PrintStream): Int { require(source.count() == 1) { "You must specify URL or file path to the blob" } val inputBytes = source.first().readBytes() val bytes = parseToBinaryRelaxed(inputFormatType, inputBytes) ?: throw IllegalArgumentException("Error: this input does not appear to be encoded in Corda's AMQP extended format, sorry.") if (schema) { val envelope = DeserializationInput.getEnvelope(bytes.sequence(), SerializationDefaults.STORAGE_CONTEXT.encodingWhitelist) out.println(envelope.schema) out.println() out.println(envelope.transformsSchema) out.println() } val factory = when (formatType) { OutputFormatType.YAML -> YAMLFactory() OutputFormatType.JSON -> JsonFactory() } val mapper = JacksonSupport.createNonRpcMapper(factory, fullParties) initialiseSerialization() try { val deserialized = bytes.deserialize<Any>(context = SerializationDefaults.STORAGE_CONTEXT) out.println(deserialized.javaClass.name) mapper.writeValue(out, deserialized) return ExitCodes.SUCCESS } catch(e: Exception) { return ExitCodes.FAILURE } finally { _contextSerializationEnv.set(null) } } private fun parseToBinaryRelaxed(format: InputFormatType, inputBytes: ByteArray): ByteArray? { // Try the format the user gave us first, then try the others. //@formatter:off return parseToBinary(format, inputBytes) ?: parseToBinary(InputFormatType.HEX, inputBytes) ?: parseToBinary(InputFormatType.BASE64, inputBytes) ?: parseToBinary(InputFormatType.BINARY, inputBytes) //@formatter:on } private fun parseToBinary(format: InputFormatType, inputBytes: ByteArray): ByteArray? { try { val bytes = when (format) { InputFormatType.BINARY -> inputBytes InputFormatType.HEX -> String(inputBytes).trim().hexToByteArray() InputFormatType.BASE64 -> String(inputBytes).trim().base64ToByteArray() } require(bytes.size > amqpMagic.size) { "Insufficient bytes for AMQP blob" } return if (bytes.copyOf(amqpMagic.size).contentEquals(amqpMagic.bytes)) { if (verbose) println("Parsing input as $format") bytes } else { null // Not an AMQP blob. } } catch (t: Throwable) { return null // Failed to parse in some other way. } } private fun initialiseSerialization() { // Deserialise with the lenient carpenter as we only care for the AMQP field getters _contextSerializationEnv.set(SerializationEnvironmentImpl( SerializationFactoryImpl().apply { registerScheme(AMQPInspectorSerializationScheme) }, p2pContext = AMQP_P2P_CONTEXT.withLenientCarpenter(), storageContext = AMQP_STORAGE_CONTEXT.withLenientCarpenter() )) } } private object AMQPInspectorSerializationScheme : AbstractAMQPSerializationScheme(emptyList()) { override fun canDeserializeVersion(magic: CordaSerializationMagic, target: SerializationContext.UseCase): Boolean { return magic == amqpMagic } override fun rpcClientSerializerFactory(context: SerializationContext) = throw UnsupportedOperationException() override fun rpcServerSerializerFactory(context: SerializationContext) = throw UnsupportedOperationException() } private class SourceConverter : ITypeConverter<URL> { override fun convert(value: String): URL { return try { URL(value) } catch (e: MalformedURLException) { val path = Paths.get(value) require(path.isRegularFile()) { "$path is not a file" } path.toUri().toURL() } } } private class CordaVersionProvider : IVersionProvider { override fun getVersion(): Array<String> { return arrayOf( "Version: ${Manifests.read("Corda-Release-Version")}", "Revision: ${Manifests.read("Corda-Revision")}" ) } } private enum class OutputFormatType { YAML, JSON } private enum class InputFormatType { BINARY, HEX, BASE64 }
1
null
1
1
f524ed9af7027004abfa91c0bd3a31d645ef0b3b
7,579
corda
Apache License 2.0
app/src/main/java/com/example/juicetracker/ui/JuiceTrackerApp.kt
codnaTnoraA
812,924,900
false
{"Kotlin": 60926}
package com.example.juicetracker.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.material3.BottomSheetScaffold import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.SheetValue import androidx.compose.material3.Text import androidx.compose.material3.rememberBottomSheetScaffoldState import androidx.compose.material3.rememberStandardBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.lifecycle.viewmodel.compose.viewModel import com.example.juicetracker.ui.bottomsheet.EntryBottomSheet import com.example.juicetracker.ui.homescreen.AddProductButton import com.example.juicetracker.ui.homescreen.CheckAllUI import com.example.juicetracker.ui.homescreen.EditPriceButton import com.example.juicetracker.ui.homescreen.JuiceTrackerList import com.example.juicetracker.ui.homescreen.JuiceTrackerTopAppBar import com.example.juicetracker.ui.homescreen.confirmDialogBox.ConfirmDeleteDialogBox import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun JuiceTrackerApp( juiceTrackerViewModel: JuiceTrackerViewModel = viewModel(factory = AppViewModelProvider.Factory) ) { val bottomSheetScaffoldState = rememberBottomSheetScaffoldState( bottomSheetState = rememberStandardBottomSheetState( initialValue = SheetValue.Hidden, skipHiddenState = false, ) ) val scope = rememberCoroutineScope() val trackerState by juiceTrackerViewModel.productListStream.collectAsState(emptyList()) val testCheckList by juiceTrackerViewModel.testCheckList.collectAsState(emptyList()) EntryBottomSheet( juiceTrackerViewModel = juiceTrackerViewModel, sheetScaffoldState = bottomSheetScaffoldState, modifier = Modifier, onCancel = { scope.launch { bottomSheetScaffoldState.bottomSheetState.hide() } }, onSubmit = { juiceTrackerViewModel.saveJuice() scope.launch { bottomSheetScaffoldState.bottomSheetState.hide() } } ) { // Delete Confirmation function val openDeleteAlertDialog = juiceTrackerViewModel.confirmDeleteState when { // ... openDeleteAlertDialog.value -> { ConfirmDeleteDialogBox( onDismissRequest = { openDeleteAlertDialog.value = false juiceTrackerViewModel.falseDeleteState() }, onConfirmation = { openDeleteAlertDialog.value = false juiceTrackerViewModel.deleteJuice() } ) } } Scaffold( topBar = { JuiceTrackerTopAppBar() }, bottomBar = { Row(verticalAlignment = Alignment.CenterVertically) { CheckAllUI() Spacer(modifier = Modifier.weight(1f)) if (testCheckList.contains(true)) { // TODO add function to button EditPriceButton { juiceTrackerViewModel.editButtonState.value = true scope.launch { bottomSheetScaffoldState.bottomSheetState.expand() } } } else { AddProductButton( onClick = { juiceTrackerViewModel.editButtonState.value = false juiceTrackerViewModel.resetCurrentJuice() scope.launch { bottomSheetScaffoldState.bottomSheetState.expand() } } ) } } } ) { contentPadding -> Column(Modifier.padding(contentPadding)) { JuiceTrackerList( // juiceTrackerViewModel = juiceTrackerViewModel, products = trackerState, onDelete = { juice -> juiceTrackerViewModel.deleteProductConfirm(juice) }, onUpdate = { juice -> juiceTrackerViewModel.updateCurrentJuice(juice) scope.launch { bottomSheetScaffoldState.bottomSheetState.expand() } }, ) } } } }
0
Kotlin
0
0
e1465509e9e70c47d4f9de312d473f90a1b721a9
5,008
Ecommerce_App
Apache License 2.0
app/src/main/java/com/example/mockpropertymanagmentapp/data/repositories/UserRepository.kt
adamcreeves
301,543,820
false
{"Kotlin": 78539}
package com.example.mockpropertymanagmentapp.data.repositories import android.content.Context import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.mockpropertymanagmentapp.data.models.* import com.example.mockpropertymanagmentapp.data.network.MyApi import com.example.mockpropertymanagmentapp.helpers.SessionManager import retrofit2.Call import retrofit2.Callback import retrofit2.Response class UserRepository { lateinit var sessionManager: SessionManager var userId: String? = null fun login(myContext: Context, email: String, password: String): LiveData<String> { var loginResponse = MutableLiveData<String>() var loginUser = LoginUser(email, password) MyApi().login(loginUser) .enqueue(object : Callback<LoginResponse> { override fun onResponse( call: Call<LoginResponse>, response: Response<LoginResponse> ) { if (response.isSuccessful) { sessionManager = SessionManager(myContext) loginResponse.value = response.body()!!.token sessionManager.saveUserLogin( response.body()!!.token, response.body()!!.user._id ) } } override fun onFailure(call: Call<LoginResponse>, t: Throwable) { loginResponse.value = t.message } }) return loginResponse } fun registerTenant( email: String, landlordEmail: String, name: String, password: String, type: String ): LiveData<String> { var registerResponse = MutableLiveData<String>() var registerTenant = Tenant(email, landlordEmail, name, password, type) MyApi().registerTenant(registerTenant) .enqueue(object : Callback<RegisterResponse> { override fun onResponse( call: Call<RegisterResponse>, response: Response<RegisterResponse> ) { if (response.isSuccessful) { registerResponse.value = "Registered Tenant successful" } } override fun onFailure(call: Call<RegisterResponse>, t: Throwable) { registerResponse.value = t.message } }) return registerResponse } fun registerLandlord( email: String, name: String, password: String, type: String ): LiveData<String> { var registerResponse = MutableLiveData<String>() var registerLandlord = Landlord(email, name, password, type) MyApi().registerLandlord(registerLandlord) .enqueue(object : Callback<RegisterResponse> { override fun onResponse( call: Call<RegisterResponse>, response: Response<RegisterResponse> ) { if (response.isSuccessful) { registerResponse.value = "Registered Landlord successful" } } override fun onFailure(call: Call<RegisterResponse>, t: Throwable) { registerResponse.value = t.message } }) return registerResponse } }
0
Kotlin
0
0
13c2013fdb5f689455f4deef7b15c6ca95174bc7
3,522
Mock-Property-Managment-App-kotlin
MIT License
app/src/main/java/com/ali_sajjadi/daneshjooyarapp/mvp/presenter/PresenterRulesFragment.kt
alisajjadi751
847,226,122
false
{"Kotlin": 72156}
package com.ali_sajjadi.daneshjooyarapp.mvp.presenter import com.ali_sajjadi.daneshjooyarapp.mvp.model.ModelRulesFragment import com.ali_sajjadi.daneshjooyarapp.mvp.view.ViewRulesFragment import info.alirezaahmadi.frenchpastry.mvp.ext.BaseLifeCycle class PresenterRulesFragment( private val view: ViewRulesFragment, private val model: ModelRulesFragment ):BaseLifeCycle { override fun onCreate() { view.back() } }
0
Kotlin
0
0
039cbfa4fb82af9d1b5b94f5ddba018d8caacce3
441
daneshjooyar-App
MIT License
app/src/main/java/com/bossed/waej/javebean/MyProductResponse.kt
Ltow
710,230,789
false
{"Kotlin": 2304560, "Java": 395495, "HTML": 71364}
package com.bossed.waej.javebean import com.google.gson.annotations.SerializedName data class MyProductResponse( @SerializedName("code") val code: Int, @SerializedName("data") val `data`: List<MyProductData>, @SerializedName("msg") val msg: String, @SerializedName("succ") val succ: Boolean ) data class MyProductData( @SerializedName("id") val id: String, @SerializedName("menuCheckStrictly") val menuCheckStrictly: Int, @SerializedName("menuIds") val menuIds: String, @SerializedName("menuName") val menuName: String, @SerializedName("packageId") val packageId: String, @SerializedName("packageName") val packageName: String, @SerializedName("priceDay") val priceDay: String, @SerializedName("priceYear") val priceYear: String, @SerializedName("remark") val remark: String, @SerializedName("shopId") val shopId: String, @SerializedName("status") val status: String, @SerializedName("tenantId") val tenantId: String, @SerializedName("termTime") val termTime: String )
0
Kotlin
0
0
8c2e9928f6c47484bec7a5beca32ed4b10200f9c
1,107
wananexiu
Mulan Permissive Software License, Version 2
libs/canvas-api-2/src/main/java/com/instructure/canvasapi2/apis/ModuleAPI.kt
instructure
179,290,947
false
null
/* * Copyright (C) 2017 - present Instructure, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.instructure.canvasapi2.apis import com.instructure.canvasapi2.StatusCallback import com.instructure.canvasapi2.builders.RestBuilder import com.instructure.canvasapi2.builders.RestParams import com.instructure.canvasapi2.models.* import okhttp3.ResponseBody import retrofit2.Call import retrofit2.http.* internal object ModuleAPI { internal interface ModuleInterface { @GET("{contextId}/modules") fun getFirstPageModuleObjects(@Path("contextId") contextId: Long) : Call<List<ModuleObject>> @GET fun getNextPageModuleObjectList(@Url nextURL: String) : Call<List<ModuleObject>> @GET("{contextId}/modules/{moduleId}/items?include[]=content_details&include[]=mastery_paths") fun getFirstPageModuleItems(@Path("contextId") contextId: Long, @Path("moduleId") moduleId: Long) : Call<List<ModuleItem>> @GET fun getNextPageModuleItemList(@Url nextURL: String) : Call<List<ModuleItem>> @POST("{contextId}/modules/{moduleId}/items/{itemId}/mark_read") fun markModuleItemRead(@Path("contextId") contextId: Long, @Path("moduleId") moduleId: Long, @Path("itemId") itemId: Long) : Call<ResponseBody> @PUT("{contextId}/modules/{moduleId}/items/{itemId}/done") fun markModuleAsDone(@Path("contextId") contextId: Long, @Path("moduleId") moduleId: Long, @Path("itemId") itemId: Long) : Call<ResponseBody> @DELETE("{contextId}/modules/{moduleId}/items/{itemId}/done") fun markModuleAsNotDone(@Path("contextId") contextId: Long, @Path("moduleId") moduleId: Long, @Path("itemId") itemId: Long): Call<ResponseBody> @POST("{contextId}/modules/{moduleId}/items/{itemId}/select_mastery_path") fun selectMasteryPath(@Path("contextId") contextId: Long, @Path("moduleId") moduleId: Long, @Path("itemId") itemId: Long, @Query("assignment_set_id") assignmentSetId: Long) : Call<MasteryPathSelectResponse> @GET("{contextId}/module_item_sequence") fun getModuleItemSequence(@Path("contextId") contextId: Long, @Query("asset_type") assetType: String, @Query("asset_id") assetId: String) : Call<ModuleItemSequence> } fun getAllModuleItems(adapter: RestBuilder, params: RestParams, contextId: Long, moduleId: Long, callback: StatusCallback<List<ModuleItem>>) { if (StatusCallback.isFirstPage(callback.linkHeaders)) { callback.addCall(adapter.build(ModuleInterface::class.java, params).getFirstPageModuleItems(contextId, moduleId)).enqueue(callback) } else { callback.addCall(adapter.build(ModuleInterface::class.java, params).getNextPageModuleItemList(callback.linkHeaders?.nextUrl ?: "")).enqueue(callback) } } fun getFirstPageModuleItems(adapter: RestBuilder, params: RestParams, contextId: Long, moduleId: Long, callback: StatusCallback<List<ModuleItem>>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).getFirstPageModuleItems(contextId, moduleId)).enqueue(callback) } fun getNextPageModuleItems(adapter: RestBuilder, params: RestParams, nextUrl: String, callback: StatusCallback<List<ModuleItem>>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).getNextPageModuleItemList(nextUrl)).enqueue(callback) } fun getFirstPageModuleObjects(adapter: RestBuilder, params: RestParams, contextId: Long, callback: StatusCallback<List<ModuleObject>>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).getFirstPageModuleObjects(contextId)).enqueue(callback) } fun getNextPageModuleObjects(adapter: RestBuilder, params: RestParams, nextUrl: String, callback: StatusCallback<List<ModuleObject>>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).getNextPageModuleObjectList(nextUrl)).enqueue(callback) } fun markModuleItemAsRead(adapter: RestBuilder, params: RestParams,canvasContext: CanvasContext, moduleId: Long, itemId: Long, callback: StatusCallback<ResponseBody>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).markModuleItemRead(canvasContext.id, moduleId, itemId)).enqueue(callback) } fun markModuleAsDone(adapter: RestBuilder, params: RestParams,canvasContext: CanvasContext, moduleId: Long, itemId: Long, callback: StatusCallback<ResponseBody>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).markModuleAsDone(canvasContext.id, moduleId, itemId)).enqueue(callback) } fun markModuleAsNotDone(adapter: RestBuilder, params: RestParams,canvasContext: CanvasContext, moduleId: Long, itemId: Long, callback: StatusCallback<ResponseBody>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).markModuleAsNotDone(canvasContext.id, moduleId, itemId)).enqueue(callback) } fun selectMasteryPath(adapter: RestBuilder, params: RestParams,canvasContext: CanvasContext, moduleId: Long, itemId: Long, assignmentSetId: Long, callback: StatusCallback<MasteryPathSelectResponse>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).selectMasteryPath(canvasContext.id, moduleId, itemId, assignmentSetId)).enqueue(callback) } fun getModuleItemSequence(adapter: RestBuilder, params: RestParams,canvasContext: CanvasContext, assetType: String, assetId: String, callback: StatusCallback<ModuleItemSequence>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).getModuleItemSequence(canvasContext.id, assetType, assetId)).enqueue(callback) } }
5
null
94
99
1bac9958504306c03960bdce7fbb87cc63bc6845
6,195
canvas-android
Apache License 2.0
libs/canvas-api-2/src/main/java/com/instructure/canvasapi2/apis/ModuleAPI.kt
instructure
179,290,947
false
null
/* * Copyright (C) 2017 - present Instructure, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.instructure.canvasapi2.apis import com.instructure.canvasapi2.StatusCallback import com.instructure.canvasapi2.builders.RestBuilder import com.instructure.canvasapi2.builders.RestParams import com.instructure.canvasapi2.models.* import okhttp3.ResponseBody import retrofit2.Call import retrofit2.http.* internal object ModuleAPI { internal interface ModuleInterface { @GET("{contextId}/modules") fun getFirstPageModuleObjects(@Path("contextId") contextId: Long) : Call<List<ModuleObject>> @GET fun getNextPageModuleObjectList(@Url nextURL: String) : Call<List<ModuleObject>> @GET("{contextId}/modules/{moduleId}/items?include[]=content_details&include[]=mastery_paths") fun getFirstPageModuleItems(@Path("contextId") contextId: Long, @Path("moduleId") moduleId: Long) : Call<List<ModuleItem>> @GET fun getNextPageModuleItemList(@Url nextURL: String) : Call<List<ModuleItem>> @POST("{contextId}/modules/{moduleId}/items/{itemId}/mark_read") fun markModuleItemRead(@Path("contextId") contextId: Long, @Path("moduleId") moduleId: Long, @Path("itemId") itemId: Long) : Call<ResponseBody> @PUT("{contextId}/modules/{moduleId}/items/{itemId}/done") fun markModuleAsDone(@Path("contextId") contextId: Long, @Path("moduleId") moduleId: Long, @Path("itemId") itemId: Long) : Call<ResponseBody> @DELETE("{contextId}/modules/{moduleId}/items/{itemId}/done") fun markModuleAsNotDone(@Path("contextId") contextId: Long, @Path("moduleId") moduleId: Long, @Path("itemId") itemId: Long): Call<ResponseBody> @POST("{contextId}/modules/{moduleId}/items/{itemId}/select_mastery_path") fun selectMasteryPath(@Path("contextId") contextId: Long, @Path("moduleId") moduleId: Long, @Path("itemId") itemId: Long, @Query("assignment_set_id") assignmentSetId: Long) : Call<MasteryPathSelectResponse> @GET("{contextId}/module_item_sequence") fun getModuleItemSequence(@Path("contextId") contextId: Long, @Query("asset_type") assetType: String, @Query("asset_id") assetId: String) : Call<ModuleItemSequence> } fun getAllModuleItems(adapter: RestBuilder, params: RestParams, contextId: Long, moduleId: Long, callback: StatusCallback<List<ModuleItem>>) { if (StatusCallback.isFirstPage(callback.linkHeaders)) { callback.addCall(adapter.build(ModuleInterface::class.java, params).getFirstPageModuleItems(contextId, moduleId)).enqueue(callback) } else { callback.addCall(adapter.build(ModuleInterface::class.java, params).getNextPageModuleItemList(callback.linkHeaders?.nextUrl ?: "")).enqueue(callback) } } fun getFirstPageModuleItems(adapter: RestBuilder, params: RestParams, contextId: Long, moduleId: Long, callback: StatusCallback<List<ModuleItem>>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).getFirstPageModuleItems(contextId, moduleId)).enqueue(callback) } fun getNextPageModuleItems(adapter: RestBuilder, params: RestParams, nextUrl: String, callback: StatusCallback<List<ModuleItem>>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).getNextPageModuleItemList(nextUrl)).enqueue(callback) } fun getFirstPageModuleObjects(adapter: RestBuilder, params: RestParams, contextId: Long, callback: StatusCallback<List<ModuleObject>>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).getFirstPageModuleObjects(contextId)).enqueue(callback) } fun getNextPageModuleObjects(adapter: RestBuilder, params: RestParams, nextUrl: String, callback: StatusCallback<List<ModuleObject>>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).getNextPageModuleObjectList(nextUrl)).enqueue(callback) } fun markModuleItemAsRead(adapter: RestBuilder, params: RestParams,canvasContext: CanvasContext, moduleId: Long, itemId: Long, callback: StatusCallback<ResponseBody>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).markModuleItemRead(canvasContext.id, moduleId, itemId)).enqueue(callback) } fun markModuleAsDone(adapter: RestBuilder, params: RestParams,canvasContext: CanvasContext, moduleId: Long, itemId: Long, callback: StatusCallback<ResponseBody>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).markModuleAsDone(canvasContext.id, moduleId, itemId)).enqueue(callback) } fun markModuleAsNotDone(adapter: RestBuilder, params: RestParams,canvasContext: CanvasContext, moduleId: Long, itemId: Long, callback: StatusCallback<ResponseBody>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).markModuleAsNotDone(canvasContext.id, moduleId, itemId)).enqueue(callback) } fun selectMasteryPath(adapter: RestBuilder, params: RestParams,canvasContext: CanvasContext, moduleId: Long, itemId: Long, assignmentSetId: Long, callback: StatusCallback<MasteryPathSelectResponse>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).selectMasteryPath(canvasContext.id, moduleId, itemId, assignmentSetId)).enqueue(callback) } fun getModuleItemSequence(adapter: RestBuilder, params: RestParams,canvasContext: CanvasContext, assetType: String, assetId: String, callback: StatusCallback<ModuleItemSequence>) { callback.addCall(adapter.build(ModuleInterface::class.java, params).getModuleItemSequence(canvasContext.id, assetType, assetId)).enqueue(callback) } }
5
null
94
99
1bac9958504306c03960bdce7fbb87cc63bc6845
6,195
canvas-android
Apache License 2.0
src/fr/japscan/src/eu/kanade/tachiyomi/extension/fr/japscan/Japscan.kt
Pavkazzz
148,326,031
true
{"Gradle": 60, "Java Properties": 2, "Shell": 4, "XML": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Markdown": 2, "Kotlin": 82, "Java": 7}
package eu.kanade.tachiyomi.extension.fr.japscan /** * @file Japscan.kt * @brief Defines class Japscan for french source Japscan * @date 2018-09-02 * @version 1.0 * * There is no research page on this source, so searching just returns all mangas from the source * There are also no thumbnails for mangas */ import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.* import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.Request import org.jsoup.nodes.Document import org.jsoup.nodes.Element class Japscan : ParsedHttpSource() { override val id: Long = 11 override val name = "Japscan" override val baseUrl = "https://www.japscan.cc" override val lang = "fr" override val supportsLatest = true override fun popularMangaSelector() = "ul.increment-list > li" override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl", headers) } override fun latestUpdatesSelector() = "#dernieres_sorties > div.manga" override fun latestUpdatesRequest(page: Int): Request { return GET("$baseUrl", headers) } override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() element.select("a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.text() } return manga } override fun latestUpdatesFromElement(element: Element): SManga { return popularMangaFromElement(element) } override fun popularMangaNextPageSelector() = "#theresnone" override fun latestUpdatesNextPageSelector() = "#theresnone" override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { return GET("$baseUrl/mangas/", headers) } override fun searchMangaSelector() = "div#liste_mangas > div.row" override fun searchMangaFromElement(element: Element): SManga { val manga = SManga.create() element.select("a").first().let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.text() } return manga } override fun searchMangaNextPageSelector() = "#theresnone" override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select("div.content").first() val rowElement = infoElement.select("div.table > div.row").first() val manga = SManga.create() manga.author = rowElement.select("div:eq(0)").first()?.text() manga.artist = rowElement.select("div:eq(0)").first()?.text() manga.genre = rowElement.select("div:eq(2)").first()?.text() manga.description = infoElement.select("div#synopsis").text() manga.status = rowElement.select("div:eq(4)").first()?.text().orEmpty().let { parseStatus(it) } return manga } private fun parseStatus(status: String) = when { status.contains("En Cours") -> SManga.ONGOING status.contains("Terminé") -> SManga.COMPLETED else -> SManga.UNKNOWN } override fun chapterListSelector() = "div#liste_chapitres > ul > li" override fun chapterFromElement(element: Element): SChapter { val urlElement = element.select("a").first() val chapter = SChapter.create() chapter.setUrlWithoutDomain(urlElement.attr("href")) chapter.name = urlElement.text() chapter.date_upload = 0 return chapter } override fun pageListParse(document: Document): List<Page> { val pages = mutableListOf<Page>() document.select("select#pages").first()?.select("option")?.forEach { pages.add(Page(pages.size, "$baseUrl${it.attr("value")}")) } return pages } override fun imageUrlParse(document: Document): String { val url = document.getElementById("image").attr("src") return url } }
0
Kotlin
1
0
49daca7ce58f2807a698deffd4f79bb98c192ffc
3,920
tachiyomi-extensions
Apache License 2.0
app/src/main/java/com/vitoraguiardf/bobinabanking/data/repository/UserDao.kt
vitoraguiardf
821,388,218
false
{"Kotlin": 78201}
package com.vitoraguiardf.bobinabanking.data.repository import androidx.room.Dao import androidx.room.Query import com.vitoraguiardf.bobinabanking.data.entity.User @Dao interface UserDao: DaoRepository<User, Int> { @Query("SELECT * FROM User") fun findAll(): List<User> @Query("SELECT * FROM User WHERE id = :id") fun findById(id: Int): List<User> @Query("SELECT * FROM User WHERE id IN (:ids)") fun findAllById(ids: List<Int>): List<User> @Query("DELETE FROM User") fun deleteAll() }
0
Kotlin
0
1
f14a8a2f096e0cd907d46010cdcd3d505e0798f2
518
bobina-banking-mobile
MIT License
DeliBuddy/domain/src/main/java/yapp/android1/domain/interactor/usecase/PartyInformationUseCase.kt
YAPP-19th
399,058,402
false
null
package yapp.android1.domain.interactor.usecase import yapp.android1.domain.NetworkResult import yapp.android1.domain.entity.* import yapp.android1.domain.repository.CommentRepository import yapp.android1.domain.repository.PartyRepository import javax.inject.Inject typealias PartyId = Int class FetchPartyInformationUseCase @Inject constructor( private val partyRepository: PartyRepository ) : BaseUseCase<NetworkResult<PartyInformationEntity>, PartyId>() { override suspend fun run(params: PartyId): NetworkResult<PartyInformationEntity> { return partyRepository.getPartyInformation(id = params) } } class FetchPartyCommentsUseCase @Inject constructor( private val commentRepository: CommentRepository ) : BaseUseCase<NetworkResult<List<CommentEntity>>, PartyId>() { override suspend fun run(params: PartyId): NetworkResult<List<CommentEntity>> { return commentRepository.getCommentsInParty(partyId = params) } } class JoinPartyUseCase @Inject constructor( private val partyRepository: PartyRepository ) : BaseUseCase<NetworkResult<Boolean>, PartyId>() { override suspend fun run(params: PartyId): NetworkResult<Boolean> { return partyRepository.joinParty(params) } } class ChangeStatusUseCase @Inject constructor( private val partyRepository: PartyRepository ) : BaseUseCase<NetworkResult<Boolean>, ChangeStatusUseCase.Params>() { override suspend fun run(params: Params): NetworkResult<Boolean> { return partyRepository.changeStatus( params.partyId, StatusChangeRequestEntity.fromStringToEntity(params.changedStatus) ) } data class Params( val partyId: Int, val changedStatus: String ) } class DeletePartyUseCase @Inject constructor( private val partyRepository: PartyRepository ) : BaseUseCase<NetworkResult<Boolean>, PartyId>() { override suspend fun run(params: PartyId): NetworkResult<Boolean> { return partyRepository.deleteParty(params) } } class EditPartyUseCase @Inject constructor( private val partyRepository: PartyRepository ) : BaseUseCase<NetworkResult<Boolean>, EditPartyUseCase.Params>() { override suspend fun run(params: Params): NetworkResult<Boolean> { return partyRepository.editParty(params.partyId, params.requestEntity) } data class Params( val partyId: PartyId, val requestEntity: PartyEditRequestEntity ) } class BanFromPartyUseCase @Inject constructor( private val partyRepository: PartyRepository ) : BaseUseCase<NetworkResult<Boolean>, BanFromPartyUseCase.Params>() { override suspend fun run(params: Params): NetworkResult<Boolean> { return partyRepository.banFromParty(params.partyId, params.requestEntity) } data class Params( val partyId: Int, val requestEntity: PartyBanRequestEntity ) } class LeavePartyUseCase @Inject constructor( private val partyRepository: PartyRepository ) : BaseUseCase<NetworkResult<Boolean>, PartyId>() { override suspend fun run(params: PartyId): NetworkResult<Boolean> { return partyRepository.leaveParty(params) } }
15
Kotlin
2
14
8967c395e2a8ad346ae24bc2a2fe4fbd3df29376
3,168
Android-Team-1-Frontend
Apache License 2.0
shared/core/network/src/commonMain/kotlin/com/edugma/core/network/CoreNetworkModule.kt
Edugma
474,423,768
false
{"Kotlin": 1050092, "Swift": 1255, "Shell": 331, "HTML": 299}
package com.edugma.core.network import com.edugma.core.api.api.EdugmaHttpClient import com.edugma.core.api.consts.DiConst import com.edugma.core.api.repository.UrlRepository import com.edugma.core.api.repository.UrlTemplateRepository import org.koin.core.module.dsl.bind import org.koin.core.module.dsl.singleOf import org.koin.core.qualifier.named import org.koin.dsl.module val coreNetworkModule = module { singleOf(::UrlRepositoryImpl) { bind<UrlRepository>() bind<UrlTemplateRepository>() } single<EdugmaHttpClient> { EdugmaHttpClientImpl(get(), get(named(DiConst.Account))) } }
1
Kotlin
0
3
d9149728b9dee61606d7c46d80bc474a77f46362
613
app
MIT License
core/src/main/kotlin/edu/umontreal/kotlingrad/numerical/Protocol.kt
shafiahmed
287,769,250
true
{"Kotlin": 238851}
package edu.umontreal.kotlingrad.numerical import edu.umontreal.kotlingrad.functions.Fun import edu.umontreal.kotlingrad.functions.ScalarVar import java.math.BigDecimal object BigDecimalPrecision: Protocol<BigDecimalReal, BigDecimal>() { override fun wrap(default: Number) = BigDecimalReal(BigDecimal(default.toDouble()), 30) } object DoublePrecision: Protocol<DoubleReal, Double>() { override fun wrap(default: Number) = DoubleReal(default.toDouble()) } @Suppress("FunctionName") sealed class Protocol<X: RealNumber<X, Y>, Y> where Y: Number, Y: Comparable<Y> { fun Var() = Var(wrap(0)) fun Var(default: X) = ScalarVar(value = default) fun Var(name: String) = ScalarVar(wrap(0), name = name) fun Var(name: String, default: X) = ScalarVar(default, name) fun Var(default: Number) = Var(wrap(default)) fun Var(name: String, default: Number) = ScalarVar(wrap(default), name) val x = Var("X") val y = Var("Y") val z = Var("Z") abstract fun wrap(default: Number): X fun <T: Fun<T>> sin(angle: Fun<T>) = angle.sin() fun <T: Fun<T>> cos(angle: Fun<T>) = angle.cos() fun <T: Fun<T>> tan(angle: Fun<T>) = angle.tan() fun <T: Fun<T>> exp(exponent: Fun<T>) = exponent.exp() fun <T: Fun<T>> sqrt(radicand: Fun<T>) = radicand.sqrt() class IndVar<X: Fun<X>> constructor(val variable: ScalarVar<X>) class Differential<X: Fun<X>>(private val fn: Fun<X>) { // TODO: make sure this notation works for arbitrary nested functions using the Chain rule infix operator fun div(arg: Differential<X>) = fn.diff(arg.fn.variables.first()) } fun <X: Fun<X>> d(`fun`: Fun<X>) = Differential(`fun`) infix operator fun Fun<X>.plus(number: Number) = this + wrap(number) infix operator fun Number.plus(fn: Fun<X>) = wrap(this) + fn infix operator fun Fun<X>.minus(number: Number) = this - wrap(number) infix operator fun Number.minus(fn: Fun<X>) = wrap(this) - fn infix operator fun Fun<X>.times(number: Number) = this * wrap(number) infix operator fun Number.times(fn: Fun<X>) = wrap(this) * fn infix operator fun Fun<X>.div(number: Number) = this / wrap(number) infix operator fun Number.div(fn: Fun<X>) = wrap(this) / fn // fun <Y: D100> fill(length: Nat<Y>, n: Number) = VectorConst(length, (0 until length.i).map { ScalarConst(wrap(n)) }) // // infix operator fun <Y: D100> VectorFun<ScalarFun<X>, Y>.times(number: Number) = this * fill(length, number) // infix operator fun <Y: D100> Number.times(vector: VectorFun<ScalarFun<X>, Y>) = fill(vector.length, this) * vector // // fun <Y: D100> fill(length: Nat<Y>, s: ScalarFun<X>) = VectorConst(length, (0 until length.i).map { s }) // infix operator fun <F: D100> ScalarFun<X>.plus(addend: VectorFun<ScalarFun<X>, F>) = fill(addend.length, this) + addend // infix operator fun <F: D100> ScalarFun<X>.minus(subtrahend: VectorFun<ScalarFun<X>, F>) = fill(subtrahend.length, this) - subtrahend // infix operator fun <F: D100> ScalarFun<X>.times(multiplicand: VectorFun<ScalarFun<X>, F>) = fill(multiplicand.length, this) * multiplicand @JvmName("prefixNumPowFun") fun pow(`fun`: Fun<X>, number: Number) = `fun`.pow(wrap(number)) @JvmName("prefixFunPowNum") fun pow(number: Number, `fun`: Fun<X>) = wrap(number).pow(`fun`) @JvmName("infixNumPowFun") fun Number.pow(`fun`: Fun<X>) = wrap(this).pow(`fun`) @JvmName("infixFunPowNum") infix fun Fun<X>.pow(number: Number) = pow(wrap(number)) operator fun Fun<X>.invoke(vararg number: Number) = this(variables.zip(number).toMap()) operator fun Fun<X>.invoke(vararg number: X) = this(variables.zip(number).toMap()).proto.value operator fun Fun<X>.invoke(vararg subs: Fun<X>) = this(variables.zip(subs).toMap()) @JvmName("numInvoke") operator fun Fun<X>.invoke(pairs: Map<ScalarVar<X>, Number>) = this(pairs.map { (it.key to wrap(it.value)) }.toMap()).proto.value @JvmName("numInvoke") operator fun Fun<X>.invoke(vararg pairs: Pair<ScalarVar<X>, Number>) = this(pairs.map { (it.first to wrap(it.second)) }.toMap()).proto.value @JvmName("subInvoke") operator fun Fun<X>.invoke(vararg pairs: Pair<ScalarVar<X>, Fun<X>>) = this(pairs.map { it.first to it.second }.toMap()) operator fun Number.invoke(n: Number) = this fun Fun<X>.eval() = invoke(variables.map { Pair(it, it.value) }.toMap()).proto.value // operator fun <F: D100> VectorFun<X, F>.invoke(vararg number: Number) = this(variables.zip(number).toMap()) // operator fun <F: D100> VectorFun<X, F>.invoke(pairs: Map<ScalarVar<X>, Number>) = this(pairs.map { (it.key to wrap(it.value)) }.toMap()).value // operator fun <F: D100> VectorFun<X, F>.invoke(vararg pairs: Pair<ScalarVar<X>, Number>) = this(pairs.map { (it.first to wrap(it.second)) }.toMap()).value }
0
null
0
0
a105474549a6ae24df629164bd0cb546e449b4da
4,705
kotlingrad
Apache License 2.0
idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/KotlinGradleSourceSetDataService.kt
JakeWharton
99,388,807
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.configuration import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runReadAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.LibraryData import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.Key import com.intellij.util.PathUtil import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.extensions.ProjectExtensionDescriptor import org.jetbrains.kotlin.gradle.ArgsInfo import org.jetbrains.kotlin.gradle.CompilerArgumentsBySourceSet import org.jetbrains.kotlin.ide.konan.NativeLibraryKind import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder import org.jetbrains.kotlin.idea.configuration.GradlePropertiesFileFacade.Companion.KOTLIN_CODE_STYLE_GRADLE_SETTING import org.jetbrains.kotlin.idea.configuration.klib.KotlinNativeLibraryNameUtil.KOTLIN_NATIVE_LIBRARY_PREFIX import org.jetbrains.kotlin.idea.facet.* import org.jetbrains.kotlin.idea.formatter.ProjectCodeStyleImporter import org.jetbrains.kotlin.idea.framework.CommonLibraryKind import org.jetbrains.kotlin.idea.framework.JSLibraryKind import org.jetbrains.kotlin.idea.framework.detectLibraryKind import org.jetbrains.kotlin.idea.gradle.KotlinGradleFacadeImpl import org.jetbrains.kotlin.idea.inspections.gradle.getResolvedVersionByModuleData import org.jetbrains.kotlin.idea.platform.tooling import org.jetbrains.kotlin.idea.roots.findAll import org.jetbrains.kotlin.idea.roots.migrateNonJvmSourceFolders import org.jetbrains.kotlin.idea.statistics.KotlinGradleFUSLogger import org.jetbrains.kotlin.library.KLIB_FILE_EXTENSION import org.jetbrains.kotlin.platform.IdePlatformKind import org.jetbrains.kotlin.platform.impl.isCommon import org.jetbrains.kotlin.platform.impl.isJavaScript import org.jetbrains.kotlin.platform.impl.isJvm import org.jetbrains.kotlin.psi.UserDataProperty import org.jetbrains.plugins.gradle.model.data.BuildScriptClasspathData import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData import org.jetbrains.plugins.gradle.util.GradleConstants import java.io.File import java.util.* var Module.compilerArgumentsBySourceSet by UserDataProperty(Key.create<CompilerArgumentsBySourceSet>("CURRENT_COMPILER_ARGUMENTS")) var Module.sourceSetName by UserDataProperty(Key.create<String>("SOURCE_SET_NAME")) interface GradleProjectImportHandler { companion object : ProjectExtensionDescriptor<GradleProjectImportHandler>( "org.jetbrains.kotlin.gradleProjectImportHandler", GradleProjectImportHandler::class.java ) fun importBySourceSet(facet: KotlinFacet, sourceSetNode: DataNode<GradleSourceSetData>) fun importByModule(facet: KotlinFacet, moduleNode: DataNode<ModuleData>) } class KotlinGradleProjectSettingsDataService : AbstractProjectDataService<ProjectData, Void>() { override fun getTargetDataKey() = ProjectKeys.PROJECT override fun postProcess( toImport: MutableCollection<out DataNode<ProjectData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModifiableModelsProvider ) { val allSettings = modelsProvider.modules.mapNotNull { module -> if (module.isDisposed) return@mapNotNull null val settings = modelsProvider .getModifiableFacetModel(module) .findFacet(KotlinFacetType.TYPE_ID, KotlinFacetType.INSTANCE.defaultFacetName) ?.configuration ?.settings ?: return@mapNotNull null if (settings.useProjectSettings) null else settings } val languageVersion = allSettings.asSequence().mapNotNullTo(LinkedHashSet()) { it.languageLevel }.singleOrNull() val apiVersion = allSettings.asSequence().mapNotNullTo(LinkedHashSet()) { it.apiLevel }.singleOrNull() KotlinCommonCompilerArgumentsHolder.getInstance(project).update { if (languageVersion != null) { this.languageVersion = languageVersion.versionString } if (apiVersion != null) { this.apiVersion = apiVersion.versionString } } } } class KotlinGradleSourceSetDataService : AbstractProjectDataService<GradleSourceSetData, Void>() { override fun getTargetDataKey() = GradleSourceSetData.KEY override fun postProcess( toImport: Collection<out DataNode<GradleSourceSetData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModifiableModelsProvider ) { for (sourceSetNode in toImport) { val sourceSetData = sourceSetNode.data val ideModule = modelsProvider.findIdeModule(sourceSetData) ?: continue val moduleNode = ExternalSystemApiUtil.findParent(sourceSetNode, ProjectKeys.MODULE) ?: continue val kotlinFacet = configureFacetByGradleModule(ideModule, modelsProvider, moduleNode, sourceSetNode) ?: continue GradleProjectImportHandler.getInstances(project).forEach { it.importBySourceSet(kotlinFacet, sourceSetNode) } } } } class KotlinGradleProjectDataService : AbstractProjectDataService<ModuleData, Void>() { override fun getTargetDataKey() = ProjectKeys.MODULE override fun postProcess( toImport: MutableCollection<out DataNode<ModuleData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModifiableModelsProvider ) { for (moduleNode in toImport) { // If source sets are present, configure facets in the their modules if (ExternalSystemApiUtil.getChildren(moduleNode, GradleSourceSetData.KEY).isNotEmpty()) continue val moduleData = moduleNode.data val ideModule = modelsProvider.findIdeModule(moduleData) ?: continue val kotlinFacet = configureFacetByGradleModule(ideModule, modelsProvider, moduleNode, null) ?: continue GradleProjectImportHandler.getInstances(project).forEach { it.importByModule(kotlinFacet, moduleNode) } } runReadAction { val codeStyleStr = GradlePropertiesFileFacade.forProject(project).readProperty(KOTLIN_CODE_STYLE_GRADLE_SETTING) ProjectCodeStyleImporter.apply(project, codeStyleStr) } ApplicationManager.getApplication().executeOnPooledThread { KotlinGradleFUSLogger.reportStatistics() } } } class KotlinGradleLibraryDataService : AbstractProjectDataService<LibraryData, Void>() { override fun getTargetDataKey() = ProjectKeys.LIBRARY override fun postProcess( toImport: MutableCollection<out DataNode<LibraryData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModifiableModelsProvider ) { if (toImport.isEmpty()) return val projectDataNode = toImport.first().parent!! @Suppress("UNCHECKED_CAST") val moduleDataNodes = projectDataNode.children.filter { it.data is ModuleData } as List<DataNode<ModuleData>> val anyNonJvmModules = moduleDataNodes .any { node -> detectPlatformKindByPlugin(node)?.takeIf { !it.isJvm } != null } for (libraryDataNode in toImport) { val ideLibrary = modelsProvider.findIdeLibrary(libraryDataNode.data) ?: continue val modifiableModel = modelsProvider.getModifiableLibraryModel(ideLibrary) as LibraryEx.ModifiableModelEx if (anyNonJvmModules || ideLibrary.looksAsNonJvmLibrary()) { detectLibraryKind(modifiableModel.getFiles(OrderRootType.CLASSES))?.let { modifiableModel.kind = it } } else if ( ideLibrary is LibraryEx && (ideLibrary.kind === JSLibraryKind || ideLibrary.kind === NativeLibraryKind || ideLibrary.kind === CommonLibraryKind) ) { modifiableModel.kind = null } } } private fun Library.looksAsNonJvmLibrary(): Boolean { name?.let { name -> if (nonJvmSuffixes.any { it in name } || name.startsWith(KOTLIN_NATIVE_LIBRARY_PREFIX)) return true } return getFiles(OrderRootType.CLASSES).firstOrNull()?.extension == KLIB_FILE_EXTENSION } companion object { val LOG = Logger.getInstance(KotlinGradleLibraryDataService::class.java) val nonJvmSuffixes = listOf("-common", "-js", "-native", "-kjsm", "-metadata") } } fun detectPlatformKindByPlugin(moduleNode: DataNode<ModuleData>): IdePlatformKind<*>? { val pluginId = moduleNode.platformPluginId return IdePlatformKind.ALL_KINDS.firstOrNull { it.tooling.gradlePluginId == pluginId } } @Suppress("DEPRECATION_ERROR") @Deprecated( "Use detectPlatformKindByPlugin() instead", replaceWith = ReplaceWith("detectPlatformKindByPlugin(moduleNode)"), level = DeprecationLevel.ERROR ) fun detectPlatformByPlugin(moduleNode: DataNode<ModuleData>): TargetPlatformKind<*>? { return when (moduleNode.platformPluginId) { "kotlin-platform-jvm" -> TargetPlatformKind.Jvm[JvmTarget.DEFAULT] "kotlin-platform-js" -> TargetPlatformKind.JavaScript "kotlin-platform-common" -> TargetPlatformKind.Common else -> null } } private fun detectPlatformByLibrary(moduleNode: DataNode<ModuleData>): IdePlatformKind<*>? { val detectedPlatforms = mavenLibraryIdToPlatform.entries .filter { moduleNode.getResolvedVersionByModuleData(KOTLIN_GROUP_ID, listOf(it.key)) != null } .map { it.value }.distinct() return detectedPlatforms.singleOrNull() ?: detectedPlatforms.firstOrNull { !it.isCommon } } @Suppress("unused") // Used in the Android plugin fun configureFacetByGradleModule( moduleNode: DataNode<ModuleData>, sourceSetName: String?, ideModule: Module, modelsProvider: IdeModifiableModelsProvider ): KotlinFacet? { return configureFacetByGradleModule(ideModule, modelsProvider, moduleNode, null, sourceSetName) } fun configureFacetByGradleModule( ideModule: Module, modelsProvider: IdeModifiableModelsProvider, moduleNode: DataNode<ModuleData>, sourceSetNode: DataNode<GradleSourceSetData>?, sourceSetName: String? = sourceSetNode?.data?.id?.let { it.substring(it.lastIndexOf(':') + 1) } ): KotlinFacet? { if (moduleNode.kotlinSourceSet != null) return null // Suppress in the presence of new MPP model if (!moduleNode.isResolved) return null if (!moduleNode.hasKotlinPlugin) { val facetModel = modelsProvider.getModifiableFacetModel(ideModule) val facet = facetModel.getFacetByType(KotlinFacetType.TYPE_ID) if (facet != null) { facetModel.removeFacet(facet) } return null } val compilerVersion = KotlinGradleFacadeImpl.findKotlinPluginVersion(moduleNode) ?: return null val platformKind = detectPlatformKindByPlugin(moduleNode) ?: detectPlatformByLibrary(moduleNode) // TODO there should be a way to figure out the correct platform version val platform = platformKind?.defaultPlatform val kotlinFacet = ideModule.getOrCreateFacet(modelsProvider, false, GradleConstants.SYSTEM_ID.id) kotlinFacet.configureFacet( compilerVersion, platform, modelsProvider ) if (sourceSetNode == null) { ideModule.compilerArgumentsBySourceSet = moduleNode.compilerArgumentsBySourceSet ideModule.sourceSetName = sourceSetName } ideModule.hasExternalSdkConfiguration = sourceSetNode?.data?.sdkName != null val argsInfo = moduleNode.compilerArgumentsBySourceSet?.get(sourceSetName ?: "main") if (argsInfo != null) { configureFacetByCompilerArguments(kotlinFacet, argsInfo, modelsProvider) } with(kotlinFacet.configuration.settings) { implementedModuleNames = (sourceSetNode ?: moduleNode).implementedModuleNames productionOutputPath = getExplicitOutputPath(moduleNode, platformKind, "main") testOutputPath = getExplicitOutputPath(moduleNode, platformKind, "test") } kotlinFacet.noVersionAutoAdvance() if (platformKind != null && !platformKind.isJvm) { migrateNonJvmSourceFolders(modelsProvider.getModifiableRootModel(ideModule)) } return kotlinFacet } fun configureFacetByCompilerArguments(kotlinFacet: KotlinFacet, argsInfo: ArgsInfo, modelsProvider: IdeModifiableModelsProvider?) { val currentCompilerArguments = argsInfo.currentArguments val defaultCompilerArguments = argsInfo.defaultArguments val dependencyClasspath = argsInfo.dependencyClasspath.map { PathUtil.toSystemIndependentName(it) } if (currentCompilerArguments.isNotEmpty()) { parseCompilerArgumentsToFacet(currentCompilerArguments, defaultCompilerArguments, kotlinFacet, modelsProvider) } adjustClasspath(kotlinFacet, dependencyClasspath) } private fun getExplicitOutputPath(moduleNode: DataNode<ModuleData>, platformKind: IdePlatformKind<*>?, sourceSet: String): String? { if (!platformKind.isJavaScript) { return null } val k2jsArgumentList = moduleNode.compilerArgumentsBySourceSet?.get(sourceSet)?.currentArguments ?: return null return K2JSCompilerArguments().apply { parseCommandLineArguments(k2jsArgumentList, this) }.outputFile } internal fun adjustClasspath(kotlinFacet: KotlinFacet, dependencyClasspath: List<String>) { if (dependencyClasspath.isEmpty()) return val arguments = kotlinFacet.configuration.settings.compilerArguments as? K2JVMCompilerArguments ?: return val fullClasspath = arguments.classpath?.split(File.pathSeparator) ?: emptyList() if (fullClasspath.isEmpty()) return val newClasspath = fullClasspath - dependencyClasspath arguments.classpath = if (newClasspath.isNotEmpty()) newClasspath.joinToString(File.pathSeparator) else null }
214
null
4829
83
4383335168338df9bbbe2a63cb213a68d0858104
14,970
kotlin
Apache License 2.0
backend/feature-services/src/main/kotlin/at/sensatech/openfastlane/domain/entitlements/EntitlementsServiceImpl.kt
sensatech
724,093,399
false
{"Kotlin": 442921, "Dart": 408727, "HTML": 5563, "FreeMarker": 2659, "Dockerfile": 946, "Shell": 554}
package at.sensatech.openfastlane.domain.entitlements import at.sensatech.openfastlane.common.newId import at.sensatech.openfastlane.documents.FileResult import at.sensatech.openfastlane.documents.pdf.PdfGenerator import at.sensatech.openfastlane.documents.pdf.PdfInfo import at.sensatech.openfastlane.domain.config.RestConstantsService import at.sensatech.openfastlane.domain.events.EntitlementEvent import at.sensatech.openfastlane.domain.events.MailEvent import at.sensatech.openfastlane.domain.models.Campaign import at.sensatech.openfastlane.domain.models.Entitlement import at.sensatech.openfastlane.domain.models.EntitlementCause import at.sensatech.openfastlane.domain.models.EntitlementCriteria import at.sensatech.openfastlane.domain.models.EntitlementCriteriaType import at.sensatech.openfastlane.domain.models.EntitlementStatus import at.sensatech.openfastlane.domain.models.EntitlementValue import at.sensatech.openfastlane.domain.models.Person import at.sensatech.openfastlane.domain.models.logAudit import at.sensatech.openfastlane.domain.persons.PersonsError import at.sensatech.openfastlane.domain.repositories.CampaignRepository import at.sensatech.openfastlane.domain.repositories.EntitlementCauseRepository import at.sensatech.openfastlane.domain.repositories.EntitlementRepository import at.sensatech.openfastlane.domain.repositories.PersonRepository import at.sensatech.openfastlane.domain.services.AdminPermissions import at.sensatech.openfastlane.mailing.MailError import at.sensatech.openfastlane.mailing.MailRequests import at.sensatech.openfastlane.mailing.MailService import at.sensatech.openfastlane.security.OflUser import at.sensatech.openfastlane.security.UserRole import at.sensatech.openfastlane.tracking.TrackingService import org.assertj.core.util.VisibleForTesting import org.slf4j.LoggerFactory import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.util.Locale @Service class EntitlementsServiceImpl( private val entitlementRepository: EntitlementRepository, private val causeRepository: EntitlementCauseRepository, private val campaignRepository: CampaignRepository, private val personRepository: PersonRepository, private val restConstantsService: RestConstantsService, private val pdfGenerator: PdfGenerator, private val mailService: MailService, private val trackingService: TrackingService, ) : EntitlementsService { private val dateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy") override fun listAllEntitlements(user: OflUser): List<Entitlement> { AdminPermissions.assertPermission(user, UserRole.READER) trackingService.track(EntitlementEvent.List()) return entitlementRepository.findAll() } override fun getEntitlement(user: OflUser, id: String): Entitlement? { AdminPermissions.assertPermission(user, UserRole.READER) trackingService.track(EntitlementEvent.View()) return entitlementRepository.findByIdOrNull(id) } override fun getPersonEntitlements(user: OflUser, personId: String): List<Entitlement> { AdminPermissions.assertPermission(user, UserRole.READER) val person = guardPerson(personId) trackingService.track(EntitlementEvent.ViewPersonEntitlements()) return entitlementRepository.findByPersonId(person.id) } override fun createEntitlement(user: OflUser, request: CreateEntitlement): Entitlement { AdminPermissions.assertPermission(user, UserRole.MANAGER) val personId = request.personId val entitlementCauseId = request.entitlementCauseId val entitlementCause = guardEntitlementCause(entitlementCauseId) val person = guardPerson(personId) log.info("Creating entitlement for person {} with entitlement cause {}", personId, entitlementCauseId) val entitlements = getPersonEntitlements(user, person.id) val matchingEntitlements = entitlements.filter { it.entitlementCauseId == entitlementCauseId } if (matchingEntitlements.isNotEmpty()) { throw EntitlementsError.PersonEntitlementAlreadyExists(matchingEntitlements.first().id) } val valueSet = entitlementCause.criterias.map { EntitlementValue(it.id, it.type, "") } log.info("Creating base values for person {} with valueSet {}", personId, valueSet) val finalCreateValues = mergeValues(valueSet, request.values).toMutableList() val entitlement = Entitlement( id = newId(), personId = personId, campaignId = entitlementCause.campaignId, entitlementCauseId = entitlementCause.id, status = EntitlementStatus.PENDING, values = finalCreateValues, ) entitlement.audit.logAudit(user, "CREATED", "Angelegt mit ${request.values.size} Werten") trackingService.track(EntitlementEvent.Create(entitlementCause.name, length = finalCreateValues.size)) val saved = entitlementRepository.save(entitlement) return saved } fun mergeValues(baseValues: List<EntitlementValue>, newValues: List<EntitlementValue>): List<EntitlementValue> { return baseValues.map { value -> val newValue = newValues.find { it.criteriaId == value.criteriaId } if (newValue != null) { log.debug("Merging value for criteria {} with new value {}", value.criteriaId, newValue.value) EntitlementValue(value.criteriaId, value.type, newValue.value) } else { log.debug("Merging value for criteria {} with empty value", value.criteriaId) value } } } override fun updateEntitlement(user: OflUser, id: String, request: UpdateEntitlement): Entitlement { AdminPermissions.assertPermission(user, UserRole.MANAGER) val entitlement = guardEntitlement(id) val entitlementCause = guardEntitlementCause(entitlement.entitlementCauseId) val currentBaseValues = entitlementCause.criterias.map { EntitlementValue(it.id, it.type, "") } log.info("Updating entitlement {} with currentBaseValues {}", id, currentBaseValues) log.info("Updating entitlement {} with values {}", id, request.values) val validCurrentValues = mergeValues(currentBaseValues, entitlement.values) val patchedNewValues = mergeValues(validCurrentValues, request.values) entitlement.apply { updatedAt = ZonedDateTime.now() values = patchedNewValues.toMutableList() } val status = validateEntitlement(entitlement) log.info("Updating entitlement {} with status {}, old status was {}", id, status, entitlement.status) entitlement.audit.logAudit( user, "UPDATED", "${request.values.size} Werte aktualisiert, alter Status: ${entitlement.status}, neu: $status" ) entitlement.status = status val saved = entitlementRepository.save(entitlement) trackingService.track(EntitlementEvent.Update(entitlementCause.name, length = request.values.size)) return saved } override fun extendEntitlement(user: OflUser, id: String): Entitlement { AdminPermissions.assertPermission(user, UserRole.MANAGER) val entitlement = guardEntitlement(id) guardCampaign(entitlement.campaignId) val expandTime = expandForPeriod(ZonedDateTime.now()) val oldExpiresAt = dateFormatter.format(entitlement.expiresAt ?: ZonedDateTime.now()) val oldStatus = entitlement.status entitlement.apply { expiresAt = expandTime confirmedAt = ZonedDateTime.now() updatedAt = ZonedDateTime.now() } log.info("Extending entitlement {} to {}", id, expandTime) // call AFTER updating expiresAt val status = validateEntitlement(entitlement) entitlement.status = status entitlement.audit.logAudit( user, "EXTENDED", "Verlängert bis ${dateFormatter.format(expandTime)} (war $oldExpiresAt) mit Status $status (war $oldStatus)" ) trackingService.track(EntitlementEvent.Extend()) return entitlementRepository.save(entitlement) } fun validateEntitlement(entitlement: Entitlement): EntitlementStatus { val cause = guardEntitlementCause(entitlement.entitlementCauseId) if (entitlement.expiresAt == null) { log.info("Entitlement {} has no expiration date, status = PENDING", entitlement.id) return EntitlementStatus.PENDING } else if (entitlement.expiresAt!!.isBefore(ZonedDateTime.now())) { log.info("Entitlement {} has past expiration {}, status = EXPIRED", entitlement.id, entitlement.expiresAt) return EntitlementStatus.EXPIRED } val values = entitlement.values cause.criterias.forEach { criterion -> val currentValue = values.find { it.criteriaId == criterion.id } if (currentValue == null || currentValue.invalid()) { log.info( "Entitlement {} is missing criteria {}, status = INVALID", entitlement.id, criterion.toString() ) return EntitlementStatus.INVALID } else { if (!checkCriteria(criterion, currentValue)) { log.info( "Entitlement {} has invalid criteria {}, status = INVALID", entitlement.id, criterion.toString() ) return EntitlementStatus.INVALID } } } log.info("Entitlement {} status = INVALID", entitlement.id) return EntitlementStatus.VALID } /** * Attention: The time frame of periods is not a good indicator for expiration and expanding time. * We use 1 year as a default for now. */ private fun expandForPeriod(dateTime: ZonedDateTime): ZonedDateTime { return dateTime.plusYears(1) } fun checkCriteria(criterion: EntitlementCriteria, currentValue: EntitlementValue): Boolean { val value = currentValue.value val criteriaId = currentValue.criteriaId if (value.isEmpty()) { log.error("Entitlement is missing value for criteria {} {}", currentValue.criteriaId, criterion.type) return false } if (criterion.type == EntitlementCriteriaType.OPTIONS && criterion.options != null) { val option = criterion.options!!.find { it.key == value } if (option == null) { log.error("Entitlement has invalid OPTIONS value for criteria {}", criteriaId) return false } } if (criterion.type == EntitlementCriteriaType.CHECKBOX) { if (value != "true" && value != "false") { log.error("Entitlement has invalid CHECKBOX value for criteria {}", criteriaId) return false } } if (criterion.type == EntitlementCriteriaType.INTEGER) { try { value.trim().toInt() } catch (e: NumberFormatException) { log.error("Entitlement has invalid INTEGER value for criteria {}", criteriaId) return false } } if (criterion.type == EntitlementCriteriaType.FLOAT || criterion.type == EntitlementCriteriaType.CURRENCY) { try { value.trim().toDouble() } catch (e: NumberFormatException) { log.error( "Entitlement {} has invalid FLOAT value for criteria {}", currentValue.criteriaId, criteriaId ) return false } } return true } private fun createQrPdfFile(user: OflUser, entitlement: Entitlement, person: Person): FileResult? { AdminPermissions.assertPermission(user, UserRole.READER) val campaign = guardCampaign(entitlement.campaignId) val entitlementCause = guardEntitlementCause(entitlement.entitlementCauseId) val entitlementWithQr = ensureUpdatedQrCode(user, entitlement) val qrValue = restConstantsService.getWebBaseUrl() + "/qr/" + entitlementWithQr.code log.info("Creating QR PDF for entitlement {} code: {}", entitlementWithQr.id, entitlementWithQr.code) return pdfGenerator.createPersonEntitlementQrPdf( pdfInfo = PdfInfo("${entitlementWithQr.id}.pdf"), person = person, entitlement = entitlementWithQr, qrValue = qrValue, campaignName = campaign.name, entitlementName = entitlementCause.name, ) } override fun viewQrPdf(user: OflUser, id: String): FileResult? { AdminPermissions.assertPermission(user, UserRole.READER) val entitlement = guardEntitlement(id) val person = guardPerson(entitlement.personId) val fileResult = createQrPdfFile(user, entitlement, person) if (fileResult?.file == null) { log.error("viewQrPdf: Could not create QR PDF for entitlement {}", entitlement.id) throw EntitlementsError.InvalidEntitlementNoQr(entitlement.id) } trackingService.track(EntitlementEvent.ViewQrCode()) return fileResult } override fun sendQrPdf(user: OflUser, id: String, mailRecipient: String?) { AdminPermissions.assertPermission(user, UserRole.MANAGER) val entitlement = guardEntitlement(id) val person = guardPerson(entitlement.personId) val mail = assertUsefulMailAddress(mailRecipient, person.email) val fileResult = createQrPdfFile(user, entitlement, person) if (fileResult?.file == null) { log.error("sendQrPdf: Could not create QR PDF for entitlement {}", entitlement.id) throw EntitlementsError.InvalidEntitlementNoQr(entitlement.id) } trackingService.track(EntitlementEvent.SendQrCode()) try { mailService.sendMail( MailRequests.sendQrPdf( mail, Locale.GERMAN, person.firstName, person.lastName, ), attachments = listOf(fileResult.file!!) ) trackingService.track(MailEvent.Success()) entitlement.audit.logAudit(user, "QR SENT", "QR Mail versendet") entitlementRepository.save(entitlement) } catch (e: Throwable) { trackingService.track(MailEvent.Failure(e.cause?.message ?: e.message ?: "unknown")) log.error("Could not send QR PDF for entitlement {}", entitlement.id, e) throw e } } private fun assertUsefulMailAddress(mailRecipient: String?, storedMailAddress: String?): String { val mail = if (!mailRecipient.isNullOrEmpty()) mailRecipient else storedMailAddress if (mail.isNullOrEmpty()) { throw MailError.SendingFailedMissingRecipient("person.email and mailRecipient both are null/blank") } // check for valid mail: if (!mail.matches(Regex("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}\$"))) { throw MailError.SendingFailedInvalidRecipient("mailRecipient is not a valid email address") } return mail } @VisibleForTesting fun ensureUpdatedQrCode(user: OflUser, entitlement: Entitlement): Entitlement { if (entitlement.code != null && entitlement.status == EntitlementStatus.VALID) { log.info("VALID Entitlement {} already has a QR code", entitlement.id) return entitlement } val entitlementStatus = validateEntitlement(entitlement) if (entitlementStatus != EntitlementStatus.VALID) { throw EntitlementsError.InvalidEntitlement(entitlementStatus.toString()) } val now = ZonedDateTime.now() val stringId = generateQrCodeString(entitlement, now) trackingService.track(EntitlementEvent.UpdateQrCode()) return entitlementRepository.save( entitlement.apply { code = stringId updatedAt = now audit.logAudit(user, "QR UPDATED", "QR neu generiert") } ) } @VisibleForTesting fun generateQrCodeString(entitlement: Entitlement, time: ZonedDateTime = ZonedDateTime.now()): String { val causeId = entitlement.entitlementCauseId val personId = entitlement.personId val entitlementId = entitlement.id val epochs = time.toEpochSecond() val string = "$causeId-$personId-$entitlementId-$epochs" return string } private fun guardEntitlement(id: String): Entitlement { return entitlementRepository.findByIdOrNull(id) ?: throw EntitlementsError.NoEntitlementFound(id) } private fun guardEntitlementCause(id: String): EntitlementCause { return causeRepository.findByIdOrNull(id) ?: throw EntitlementsError.NoEntitlementCauseFound(id) } private fun guardPerson(personId: String): Person { return personRepository.findByIdOrNull(personId) ?: throw PersonsError.NotFoundException(personId) } private fun guardCampaign(id1: String): Campaign { return campaignRepository.findByIdOrNull(id1) ?: throw EntitlementsError.NoCampaignFound(id1) } companion object { private val log = LoggerFactory.getLogger(this::class.java) } }
0
Kotlin
1
1
f80421a9db7a2b3b4fee71ebc9724789623d74bd
17,872
openfastlane
Apache License 2.0
bibix-core/src/main/kotlin/com/giyeok/bibix/plugins/bibix/Base.kt
Joonsoo
477,378,536
false
{"Kotlin": 901499, "Java": 29118, "TeX": 16376, "Scala": 3164}
package com.giyeok.bibix.plugins.bibix import com.giyeok.bibix.base.* import com.giyeok.bibix.plugins.jvm.ClassPkg import com.giyeok.bibix.plugins.jvm.JarInfo import com.giyeok.bibix.plugins.jvm.LocalLib class Base { fun build(context: BuildContext): BibixValue { // TODO jar로 묶었으면 그 jar가 cp로 들어가면 될듯? val classpath = (context.arguments.getValue("classpath") as PathValue).path // val classpath = context.fileSystem.getPath("/home/joonsoo/Documents/workspace/bibix/bibix-base-0.0.4.jar") return ClassPkg( LocalLib(classpath), JarInfo(classpath, null), listOf(), listOf(), listOf() ).toBibix() } }
9
Kotlin
1
3
643c0ece3f98e5dc5087b50ecbd0559d9de5bf0c
652
bibix
MIT License
core/common/src/main/kotlin/app/k9mail/core/common/oauth/OAuthConfiguration.kt
thunderbird
1,326,671
false
{"Kotlin": 4766001, "Java": 2159946, "Shell": 2768, "AIDL": 1946}
package app.k9mail.core.common.oauth data class OAuthConfiguration( val clientId: String, val scopes: List<String>, val authorizationEndpoint: String, val tokenEndpoint: String, val redirectUri: String, )
846
Kotlin
5
9,969
8b3932098cfa53372d8a8ae364bd8623822bd74c
226
thunderbird-android
Apache License 2.0
core/common/src/main/kotlin/app/k9mail/core/common/oauth/OAuthConfiguration.kt
thunderbird
1,326,671
false
{"Kotlin": 4766001, "Java": 2159946, "Shell": 2768, "AIDL": 1946}
package app.k9mail.core.common.oauth data class OAuthConfiguration( val clientId: String, val scopes: List<String>, val authorizationEndpoint: String, val tokenEndpoint: String, val redirectUri: String, )
846
Kotlin
5
9,969
8b3932098cfa53372d8a8ae364bd8623822bd74c
226
thunderbird-android
Apache License 2.0
vyne-history-core/src/main/java/com/orbitalhq/history/remote/AnalyticsRSocketStrategies.kt
orbitalapi
541,496,668
false
{"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337}
//package com.orbitalhq.history.remote // //import org.springframework.context.annotation.Bean //import org.springframework.context.annotation.Configuration //import org.springframework.http.codec.cbor.KotlinSerializationCborDecoder //import org.springframework.http.codec.cbor.KotlinSerializationCborEncoder //import org.springframework.messaging.rsocket.RSocketStrategies // //@Configuration //class AnalyticsRSocketStrategies { // // companion object { // const val ANALYTICS_RSOCKET_STRATEGIES = "ANALYTICS_RSOCKET_STRATEGIES" // } // // @Bean(ANALYTICS_RSOCKET_STRATEGIES) // fun serde():RSocketStrategies { // return RSocketStrategies.builder() // .encoder(KotlinSerializationCborEncoder()) // .decoder(KotlinSerializationCborDecoder()) // .build() // } //}
9
TypeScript
10
292
2be59abde0bd93578f12fc1e2ecf1f458a0212ec
808
orbital
Apache License 2.0
projects/android/Sample/app/src/main/java/com/ezored/sample/ui/fragment/TodoListFragment.kt
kereko
355,354,539
true
{"C++": 612146, "Java": 106702, "Objective-C++": 105230, "Swift": 104865, "Python": 96270, "Objective-C": 93293, "Kotlin": 68932, "CMake": 38367, "C": 1674, "Shell": 636}
package com.ezored.sample.ui.fragment import android.text.TextUtils import android.view.MenuItem import android.view.View import androidx.lifecycle.MutableLiveData import com.ezored.dataservices.TodoDataService import com.ezored.domain.Todo import com.ezored.sample.R import com.ezored.sample.adapter.TodoAdapter import com.ezored.sample.enums.LoadStateEnum import com.ezored.sample.ui.fragment.base.BaseListFragment import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.* class TodoListFragment : BaseListFragment<Todo>(), TodoAdapter.TodoAdapterListener { private var searchText: String? = null override val fragmentLayout: Int get() = R.layout.fragment_todo_list override val screenNameForAnalytics: String? get() = "ToDo List" override fun createAll(view: View) { super.createAll(view) setupToolbar(R.string.title_todo_list) showToolbarBackButton(true) showLoadingView() createLiveData() validateLoadData() } override fun onLoadNewData() { super.onLoadNewData() GlobalScope.launch { var list = if (TextUtils.isEmpty(searchText)) { TodoDataService.findAllOrderByCreatedAtDesc() } else { TodoDataService.findByTitle(searchText) } withContext(context = Dispatchers.Main) { listData?.value = list remoteDataLoadState = LoadStateEnum.LOADED } } } private fun createLiveData() { listData = MutableLiveData() (listData as MutableLiveData<ArrayList<Todo>>).observe(this, androidx.lifecycle.Observer { list -> adapter = TodoAdapter(context!!, list) (adapter as TodoAdapter).setListener(this) updateAdapter() adapter.notifyDataSetChanged() }) } override fun needLoadNewData(): Boolean { return isAdded } override fun onTodoItemClick(view: View, todo: Todo) { TodoDataService.setDoneById(todo.id, !todo.done) if (remoteDataLoadState != LoadStateEnum.LOADING) { remoteDataLoadState = LoadStateEnum.NOT_LOADED validateLoadData() } } fun search(typedText: String) { if (remoteDataLoadState != LoadStateEnum.LOADING) { remoteDataLoadState = LoadStateEnum.NOT_LOADED searchText = typedText validateLoadData() } } override fun onOptionsItemSelected(item: MenuItem?): Boolean { item?.let { if (it.itemId == R.id.menu_search) { return true } } return super.onOptionsItemSelected(item) } companion object { fun newInstance(): TodoListFragment { return TodoListFragment() } } }
1
C++
0
0
f290446bdf982d184bfd2ce22891749e8ad91e44
2,953
ezored
MIT License
plugins/android-extensions/android-extensions-idea/src/org/jetbrains/kotlin/android/synthetic/idea/AndroidSimpleNameReferenceExtension.kt
gigliovale
89,726,097
false
{"Java": 23302590, "Kotlin": 21941511, "JavaScript": 137521, "Protocol Buffer": 56992, "HTML": 49980, "Lex": 18051, "Groovy": 14093, "ANTLR": 9797, "IDL": 7706, "Shell": 5152, "CSS": 4679, "Batchfile": 3721}
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.android.synthetic.idea import com.intellij.psi.PsiElement import com.intellij.psi.xml.XmlAttributeValue import org.jetbrains.android.dom.wrappers.ValueResourceElementWrapper import org.jetbrains.android.util.AndroidResourceUtil import org.jetbrains.kotlin.android.synthetic.AndroidConst import org.jetbrains.kotlin.android.synthetic.androidIdToName import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.plugin.references.SimpleNameReferenceExtension import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtPsiFactory class AndroidSimpleNameReferenceExtension : SimpleNameReferenceExtension { override fun isReferenceTo(reference: KtSimpleNameReference, element: PsiElement) = when { element is ValueResourceElementWrapper && AndroidResourceUtil.isIdDeclaration(element) -> true isLayoutPackageIdentifier(reference) -> true else -> false } private fun isLayoutPackageIdentifier(reference: KtSimpleNameReference): Boolean { val probablyVariant = reference.element?.parent as? KtDotQualifiedExpression ?: return false val probablyKAS = probablyVariant.receiverExpression as? KtDotQualifiedExpression ?: return false return probablyKAS.receiverExpression.text == AndroidConst.SYNTHETIC_PACKAGE } override fun handleElementRename(reference: KtSimpleNameReference, psiFactory: KtPsiFactory, newElementName: String): PsiElement? { val resolvedElement = reference.resolve() if (resolvedElement is XmlAttributeValue && AndroidResourceUtil.isIdDeclaration(resolvedElement)) { val newSyntheticPropertyName = androidIdToName(newElementName) ?: return null return psiFactory.createNameIdentifier(newSyntheticPropertyName.name) } else if (isLayoutPackageIdentifier(reference)) { return psiFactory.createSimpleName(newElementName.substringBeforeLast(".xml")).getIdentifier() } return null } }
1
Java
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
2,645
kotlin
Apache License 2.0
src/main/kotlin/com/github/kimcore/inko/Inko.kt
kimcore
280,815,352
false
null
package com.github.kimcore.inko import kotlin.math.floor @Suppress("unused", "DuplicatedCode") class Inko(private var allowDoubleConsonant: Boolean = false) { private val eng = "rRseEfaqQtTdwWczxvgASDFGZXCVkoiOjpuPhynbmlYUIHJKLBNM" private val kor = "ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎㅁㄴㅇㄹㅎㅋㅌㅊㅍㅏㅐㅑㅒㅓㅔㅕㅖㅗㅛㅜㅠㅡㅣㅛㅕㅑㅗㅓㅏㅣㅠㅜㅡ" private val chosung = "ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ" private val jungsung = "ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ" private val jongsung = "ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ" private val firstMoeum = 28 private val rk = 44032 private val glg = 55203 private val r = 12593 private val l = 12643 companion object { private val inko = Inko() val String.asKorean: String get() = inko.en2ko(this, false) val String.asKoreanWithDoubleConsonant: String get() = inko.en2ko(this, true) val String.asEnglish: String get() = inko.ko2en(this) } private val engIndex = run { val x = mutableMapOf<Char, Int>() eng.forEachIndexed { i, c -> x[c] = i } x } private val korIndex = run { val x = mutableMapOf<Char, Int>() kor.forEachIndexed { i, c -> x[c] = i } x } private val connectableConsonant = mapOf( "ㄱㅅ" to "ㄳ", "ㄴㅈ" to "ㄵ", "ㄴㅎ" to "ㄶ", "ㄹㄱ" to "ㄺ", "ㄹㅁ" to "ㄻ", "ㄹㅂ" to "ㄼ", "ㄹㅅ" to "ㄽ", "ㄹㅌ" to "ㄾ", "ㄹㅍ" to "ㄿ", "ㄹㅎ" to "ㅀ", "ㅂㅅ" to "ㅄ" ) private val connectableVowel = mapOf( "ㅗㅏ" to "ㅘ", "ㅗㅐ" to "ㅙ", "ㅗㅣ" to "ㅚ", "ㅜㅓ" to "ㅝ", "ㅜㅔ" to "ㅞ", "ㅜㅣ" to "ㅟ", "ㅡㅣ" to "ㅢ" ) private fun isVowel(e: Char) = korIndex[e]!! >= firstMoeum private fun generate(args: MutableList<Int>) = (44032 + args[0] * 588 + args[1] * 28 + args[2] + 1).toChar().toString() fun config(allowDoubleConsonant: Boolean) { this.allowDoubleConsonant = allowDoubleConsonant } fun en2ko(input: String, allowDoubleConsonant: Boolean = this.allowDoubleConsonant): String { val stateLength = arrayOf(0, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5) val transitions = arrayOf( arrayOf(1, 1, 2, 2), // 0, EMPTY arrayOf(3, 1, 4, 4), // 1, 자 arrayOf(1, 1, 5, 2), // 2, 모 arrayOf(3, 1, 4, -1), // 3, 자자 arrayOf(6, 1, 7, 2), // 4, 자모 arrayOf(1, 1, 2, 2), // 5, 모모 arrayOf(9, 1, 4, 4), // 6, 자모자 arrayOf(9, 1, 2, 2), // 7, 자모모 arrayOf(1, 1, 4, 4), // 8, 자모자자 arrayOf(10, 1, 4, 4), // 9, 자모모자 arrayOf(1, 1, 4, 4) // 10, 자모모자자 ) fun combine(arr: MutableList<Int>): String { val group = mutableListOf<MutableList<Char>>() for (i in 0 until arr.size) { val h = kor[arr[i]] if (i == 0 || isVowel(group.last()[0]) != isVowel(h)) group.add(mutableListOf()) group.last().add(h) } fun connect(e: MutableList<Char>): String { val w = e.joinToString("") return when { connectableConsonant.containsKey(w) -> connectableConsonant.getValue(w) connectableVowel.containsKey(w) -> connectableVowel.getValue(w) else -> w } } val group2 = group.map { connect(it) } if (group2.size == 1) return group2[0] val charSet = arrayOf(chosung, jungsung, jongsung) val code = group2.mapIndexed { i, w -> charSet[i].indexOf(w) }.toMutableList() if (code.size < 3) code.add(-1) return generate(code) } var last = -1 fun getLast(): Int = if (last == -1) kor.length - 1 else last fun setLast(_last: Int) { last = _last } val result = mutableListOf<String>() var state = 0 var tmp = mutableListOf<Int>() fun flush() { if (tmp.size > 0) result.add(combine(tmp)) tmp.clear() } for (chr in input) { val cur = engIndex[chr] if (cur == null) { state = 0 flush() result.add(chr.toString()) } else { val transition = fun(): Int { val c = (if (kor.getOrNull(getLast()) != null) kor[getLast()].toString() else "") + kor[cur] val lastIsVowel = isVowel(kor[getLast()]) val curIsVowel = isVowel(kor[cur]) if (!curIsVowel) { if (lastIsVowel) return if ("ㄸㅃㅉ".indexOf(kor[cur]) == -1) 0 else 1 if (state == 1 && !allowDoubleConsonant) return 1 return if (connectableConsonant.containsKey(c)) 0 else 1 } else if (lastIsVowel) return if (connectableVowel.containsKey(c)) 2 else 3 return 2 }() val nextState = transitions[state][transition] tmp.add(cur) val diff = tmp.size - stateLength[nextState] if (diff > 0) { result.add(combine(tmp.subList(0, diff))) tmp = tmp.slice(IntRange(diff, tmp.lastIndex)).toMutableList() } state = nextState setLast(cur) } } flush() return result.joinToString("") } fun ko2en(input: String): String { var result = "" if (input.isEmpty()) return result var detached: Array<Int> for (char in input) { val code = char.toInt() if (code in rk..glg || code in r..l) detached = detach(char) else { result += char detached = arrayOf(-1, -1, -1, -1, -1) } for (i in detached) if (i != -1) result += eng[i] } return result } private fun detach(char: Char): Array<Int> { return when (val code = char.toInt()) { in rk..glg -> { val ch = floor((code - rk) / 588.0).toInt() val wnd = floor((code - rk - ch * 588) / 28.0).toInt() val whd = code - rk - ch * 588 - wnd * 28 - 1 var wnd1 = wnd var wnd2 = -1 var whd1 = whd var whd2 = -1 when (wnd) { jungsung.indexOf("ㅘ") -> { wnd1 = kor.indexOf("ㅗ") wnd2 = kor.indexOf("ㅏ") } jungsung.indexOf("ㅙ") -> { wnd1 = kor.indexOf("ㅗ") wnd2 = kor.indexOf("ㅐ") } jungsung.indexOf("ㅚ") -> { wnd1 = kor.indexOf("ㅗ") wnd2 = kor.indexOf("ㅣ") } jungsung.indexOf("ㅝ") -> { wnd1 = kor.indexOf("ㅜ") wnd2 = kor.indexOf("ㅓ") } jungsung.indexOf("ㅞ") -> { wnd1 = kor.indexOf("ㅜ") wnd2 = kor.indexOf("ㅔ") } jungsung.indexOf("ㅟ") -> { wnd1 = kor.indexOf("ㅜ") wnd2 = kor.indexOf("ㅣ") } jungsung.indexOf("ㅢ") -> { wnd1 = kor.indexOf("ㅡ") wnd2 = kor.indexOf("ㅣ") } } when (whd) { jongsung.indexOf("ㄳ") -> { whd1 = kor.indexOf("ㄱ") whd2 = kor.indexOf("ㅅ") } jongsung.indexOf("ㄵ") -> { whd1 = kor.indexOf("ㄴ") whd2 = kor.indexOf("ㅈ") } jongsung.indexOf("ㄶ") -> { whd1 = kor.indexOf("ㄴ") whd2 = kor.indexOf("ㅎ") } jongsung.indexOf("ㄺ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㄱ") } jongsung.indexOf("ㄻ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㅁ") } jongsung.indexOf("ㄼ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㅂ") } jongsung.indexOf("ㄽ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㅅ") } jongsung.indexOf("ㄾ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㅌ") } jongsung.indexOf("ㄿ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㅍ") } jongsung.indexOf("ㅀ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㅎ") } jongsung.indexOf("ㅄ") -> { whd1 = kor.indexOf("ㅂ") whd2 = kor.indexOf("ㅅ") } } if (wnd2 == -1 && wnd != -1) wnd1 = kor.indexOf(jungsung[wnd]) // 복모음이 아니라면 if (whd2 == -1 && whd != -1) whd1 = kor.indexOf(jongsung[whd]) // 복자음이 아니라면 arrayOf(ch, wnd1, wnd2, whd1, whd2) } in r..l -> { when { chosung.indexOf(char) > -1 -> { val ch = kor.indexOf(char) arrayOf(ch, -1, -1, -1, -1) } jungsung.indexOf(char) > -1 -> { val wnd = jungsung.indexOf(char) var wnd1 = wnd var wnd2 = -1 when (wnd) { jungsung.indexOf("ㅘ") -> { wnd1 = kor.indexOf("ㅗ") wnd2 = kor.indexOf("ㅏ") } jungsung.indexOf("ㅙ") -> { wnd1 = kor.indexOf("ㅗ") wnd2 = kor.indexOf("ㅐ") } jungsung.indexOf("ㅚ") -> { wnd1 = kor.indexOf("ㅗ") wnd2 = kor.indexOf("ㅣ") } jungsung.indexOf("ㅝ") -> { wnd1 = kor.indexOf("ㅜ") wnd2 = kor.indexOf("ㅓ") } jungsung.indexOf("ㅞ") -> { wnd1 = kor.indexOf("ㅜ") wnd2 = kor.indexOf("ㅔ") } jungsung.indexOf("ㅟ") -> { wnd1 = kor.indexOf("ㅜ") wnd2 = kor.indexOf("ㅣ") } jungsung.indexOf("ㅢ") -> { wnd1 = kor.indexOf("ㅡ") wnd2 = kor.indexOf("ㅣ") } } if (wnd2 == -1) wnd1 = kor.indexOf(jungsung[wnd]) // 복모음이 아니라면 arrayOf(-1, wnd1, wnd2, -1, -1) } jongsung.indexOf(char) > -1 -> { val whd = jongsung.indexOf(char) var whd1 = whd var whd2 = -1 when (whd) { jongsung.indexOf("ㄳ") -> { whd1 = kor.indexOf("ㄱ") whd2 = kor.indexOf("ㅅ") } jongsung.indexOf("ㄵ") -> { whd1 = kor.indexOf("ㄴ") whd2 = kor.indexOf("ㅈ") } jongsung.indexOf("ㄶ") -> { whd1 = kor.indexOf("ㄴ") whd2 = kor.indexOf("ㅎ") } jongsung.indexOf("ㄺ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㄱ") } jongsung.indexOf("ㄻ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㅁ") } jongsung.indexOf("ㄼ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㅂ") } jongsung.indexOf("ㄽ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㅅ") } jongsung.indexOf("ㄾ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㅌ") } jongsung.indexOf("ㄿ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㅍ") } jongsung.indexOf("ㅀ") -> { whd1 = kor.indexOf("ㄹ") whd2 = kor.indexOf("ㅎ") } jongsung.indexOf("ㅄ") -> { whd1 = kor.indexOf("ㅂ") whd2 = kor.indexOf("ㅅ") } } arrayOf(whd1, whd2, -1, -1, -1) } else -> arrayOf(-1, -1, -1, -1, -1) } } else -> arrayOf(-1, -1, -1, -1, -1) } } }
0
null
0
9
40093fc4d6f431557c760eccba913fa55adcaa79
14,468
inko.kt
MIT License
mapper/logic/src/main/java/ir/ac/iust/dml/kg/mapper/logic/mapping/KSMappingLogic.kt
IUST-DMLab
143,078,400
false
{"Java": 1305698, "JavaScript": 309084, "Kotlin": 291339, "HTML": 262524, "Python": 140248, "CSS": 134871, "Shell": 11166}
/* * Farsi Knowledge Graph Project * Iran University of Science and Technology (Year 2017) * Developed by <NAME>. */ package ir.ac.iust.dml.kg.mapper.logic.mapping import ir.ac.iust.dml.kg.mapper.logic.data.PropertyStats import ir.ac.iust.dml.kg.raw.utils.ConfigReader import ir.ac.iust.dml.kg.raw.utils.PageUtils import ir.ac.iust.dml.kg.raw.utils.PagedData import ir.ac.iust.dml.kg.raw.utils.URIs import ir.ac.iust.dml.kg.services.client.ApiClient import ir.ac.iust.dml.kg.services.client.swagger.V2mappingsApi import ir.ac.iust.dml.kg.services.client.swagger.V2ontologyApi import ir.ac.iust.dml.kg.services.client.swagger.model.PagingListTemplateMapping import ir.ac.iust.dml.kg.services.client.swagger.model.TemplateData import ir.ac.iust.dml.kg.services.client.swagger.model.TemplateMapping import org.springframework.stereotype.Service import javax.annotation.PostConstruct @Service class KSMappingLogic { private val mappingApi: V2mappingsApi private val ontologyApi: V2ontologyApi private val allMapping = mutableListOf<TemplateMapping>() private val indexTemplateNames = mutableMapOf<String, Int>() private var propertyToTemplate = mutableListOf<PropertyStats>() private var uniquePredicates = mutableSetOf<String>() private var indexPropertyToTemplate = mutableMapOf<String, Int>() init { val client = ApiClient() client.basePath = ConfigReader.getString("knowledge.store.url", "http://localhost:8091/rs") client.connectTimeout = 1200000 mappingApi = V2mappingsApi(client) ontologyApi = V2ontologyApi(client) } @PostConstruct fun load() { var page = 0 do { val pages = mappingApi.readAll2(page++, 100) pages.data.forEach { fixData(it) } allMapping.addAll(pages.data.sortedByDescending { it.weight }) } while (pages.page < pages.pageCount) rebuildIndexes() } private fun fixData(data: TemplateMapping) { data.rules.forEach { if (it.predicate?.startsWith("http://") == true) it.predicate = URIs.replaceAllPrefixesInString(it.predicate) } data.properties.forEach { if (it.recommendations.size == 1 && it.rules.size > 0) it.recommendations.clear() it.rules?.forEach { if (it.predicate?.startsWith("http://") == true) it.predicate = URIs.replaceAllPrefixesInString(it.predicate) } it.recommendations.forEach { if (it.predicate?.startsWith("http://") == true) it.predicate = URIs.replaceAllPrefixesInString(it.predicate) } } } private fun fixData(data: TemplateData) { data.rules.forEach { if (it.predicate?.startsWith("http://") == true) it.predicate = URIs.replaceAllPrefixesInString(it.predicate) } data.properties.forEach { it.rules?.forEach { if (it.predicate?.startsWith("http://") == true) it.predicate = URIs.replaceAllPrefixesInString(it.predicate) } it.recommendations.forEach { if (it.predicate?.startsWith("http://") == true) it.predicate = URIs.replaceAllPrefixesInString(it.predicate) } } } fun insert(data: TemplateData): TemplateMapping? { fixData(data) if (indexTemplateNames.isEmpty()) load() data.incremental = false val success = mappingApi.insert5(data) if (success != null) { val mappingIndex = indexTemplateNames[data.template]!! val updated = mappingApi.readAll2(0, 0).data.first { it.template == data.template } if (updated != null) allMapping[mappingIndex] = updated // TODO make it faster. we don't need to calculate stats for all properties rebuildPropertyStats() return updated } return null } fun search(page: Int, pageSize: Int, templateName: String?, templateNameLike: Boolean, className: String?, classNameLike: Boolean, propertyName: String?, propertyNameLike: Boolean, predicateName: String?, predicateNameLike: Boolean, approved: Boolean?): PagingListTemplateMapping { var filtered: List<TemplateMapping> = allMapping if (templateName != null) { if (templateNameLike) filtered = filtered.filter { it.template?.contains(templateName) ?: false } else filtered = filtered.filter { it.template == templateName } } if (className != null) { val classNameAndPrefix = if (className.contains(":")) className else URIs.getFkgOntologyClassPrefixed(className) filtered = filtered.filter { it.rules.any { it.predicate == URIs.type && compare(classNameLike, it.constant, classNameAndPrefix) } } } if (propertyName != null) { filtered = filtered.filter { it.properties.any { compare(propertyNameLike, it.property, propertyName) } } } if (predicateName != null) { filtered = filtered.filter { it.properties.any { it.rules.any { compare(predicateNameLike, it.predicate, predicateName) } || it.recommendations.any { compare(predicateNameLike, it.predicate, predicateName) } } } } if (approved != null) { filtered = filtered.filter { it.properties.any { it.recommendations.isEmpty() == approved } } } return asPages(page, pageSize, filtered) } fun searchProperty(page: Int, pageSize: Int, propertyName: String?, propertyNameLike: Boolean, templateName: String?, templateNameLike: Boolean, className: String?, classNameLike: Boolean, predicateName: String?, predicateNameLike: Boolean, allNull: Boolean? = null, oneNull: Boolean? = null, approved: Boolean?): PagedData<PropertyStats> { var filtered: List<PropertyStats> = propertyToTemplate if (propertyName != null) filtered = filtered.filter { compare(propertyNameLike, it.property, propertyName) } if (templateName != null) filtered = filtered.filter { it.templates.filter { compare(templateNameLike, it, templateName) }.isNotEmpty() } if (className != null) { val fixedClassName = if (className.contains(":")) className else URIs.getFkgOntologyClassPrefixed(className) filtered = filtered.filter { it.classes.filter { compare(classNameLike, it, fixedClassName) }.isNotEmpty() } } if (predicateName != null) filtered = filtered.filter { it.predicates.filter { compare(predicateNameLike, it, predicateName) }.isNotEmpty() } if (allNull != null) filtered = filtered.filter { (it.nullInTemplates.size == it.templates.size) == allNull } if (oneNull != null) filtered = filtered.filter { it.nullInTemplates.isNotEmpty() == oneNull } if (approved != null) filtered = filtered.filter { (it.approvedInTemplates.size == it.templates.size) == approved } return PageUtils.asPages(page, pageSize, filtered) } fun predicateProposal(keyword: String): List<String> { val proposals = mutableListOf<String>() // search in ontology and other mapped predicates val lc = keyword.toLowerCase() uniquePredicates.forEach { if (it.toLowerCase().contains(lc)) proposals.add(it) } if (keyword.length < 2) return mutableListOf() val result = ontologyApi.search2(null, null, keyword, true, URIs.type, null, URIs.typeOfAnyProperties, null, null, 0, 0) val propertyPrefix = URIs.prefixedToUri(URIs.fkgNotMappedPropertyPrefix + ":")!! result.data.forEach { if (!it.subject.startsWith(propertyPrefix)) proposals.add(URIs.replaceAllPrefixesInString(it.subject)!!) } return proposals } private fun rebuildIndexes() { allMapping.forEachIndexed { index, mapping -> indexTemplateNames[mapping.template] = index } rebuildPropertyStats() } private fun rebuildPropertyStats() { val properties = mutableMapOf<String, PropertyStats>() uniquePredicates.clear() allMapping.forEach { template -> val classes = mutableSetOf<String>() template.rules.forEach { if (it.predicate == URIs.type && it.constant != null) classes.add(it.constant) if (it.predicate != null && !it.predicate.startsWith(URIs.fkgMainPrefix)) uniquePredicates.add(it.predicate) } template.properties.forEach { pm -> val stats = properties.getOrPut(pm.property, { PropertyStats(property = pm.property) }) stats.templates.add(template.template) stats.classes.addAll(classes) pm.recommendations.forEach { if (it.predicate != null) { stats.predicates.add(it.predicate) if (!it.predicate.startsWith(URIs.fkgMainPrefix)) uniquePredicates.add(it.predicate) } else stats.nullInTemplates.add(template.template) } pm.rules.forEach { if (it.predicate != null) { stats.predicates.add(it.predicate) if (!it.predicate.startsWith(URIs.fkgMainPrefix)) uniquePredicates.add(it.predicate) } else stats.nullInTemplates.add(template.template) stats.approvedInTemplates.add(template.template) } } } val list = properties.values.sortedBy { it.property }.toMutableList() val indexes = mutableMapOf<String, Int>() list.forEachIndexed { index, (property) -> indexes[property] = index } this.propertyToTemplate = list this.indexPropertyToTemplate = indexes } private fun asPages(page: Int, pageSize: Int, list: List<TemplateMapping>): PagingListTemplateMapping { val pages = PagingListTemplateMapping() val startIndex = page * pageSize pages.data = if (list.size < startIndex) listOf() else { val endIndex = startIndex + pageSize list.subList(startIndex, if (list.size < endIndex) list.size else endIndex) } pages.page = page pages.pageSize = pageSize pages.totalSize = list.size.toLong() pages.pageCount = (pages.totalSize / pages.pageSize) + (if (pages.totalSize % pages.pageSize == 0L) 0 else 1) return pages } private fun compare(like: Boolean, first: String?, second: String) = if (like) first?.contains(second, true) ?: false else first == second }
1
null
1
1
2e020ae3d619a35ffa00079b9aeb31ca77ce2346
10,180
farsbase
Apache License 2.0
library_api/src/main/java/com/crow/ksp/api/RouteHandler.kt
crowforkotlin
798,153,843
false
{"Kotlin": 27881}
package com.crow.ksp.api interface RouteHandler { fun handle(request: RouteRequest): Boolean }
0
Kotlin
0
0
5a89525b8254cf84f9da450714e8df631cbe2a76
100
Ksp-Template
Apache License 2.0
common/src/commonMain/kotlin/com/demo/ui/utils/chat/NeutralFace.kt
CoronelGlober
529,032,277
false
{"Kotlin": 188877, "Swift": 932, "Ruby": 271}
package com.demo.ui.utils.chat import androidx.compose.material.icons.Icons import androidx.compose.ui.graphics.* import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp val Icons.Filled.Floating_screen: ImageVector get() { if (_floating_screen != null) { return _floating_screen!! } _floating_screen = ImageVector.Builder( name = "Floating_screen", defaultWidth = 48.0.dp, defaultHeight = 48.0.dp, viewportWidth = 48.0F, viewportHeight = 48.0F, ).path( fill = SolidColor(Color(0xFFFFFFFF)), fillAlpha = 1.0F, strokeAlpha = 1.0F, strokeLineWidth = 0.0F, strokeLineCap = StrokeCap.Butt, strokeLineJoin = StrokeJoin.Miter, strokeLineMiter = 4.0F, pathFillType = PathFillType.NonZero, ) { moveTo(31.3F, 21.35F) quadTo(32.45F, 21.35F, 33.225F, 20.575F) quadTo(34.0F, 19.8F, 34.0F, 18.65F) quadTo(34.0F, 17.5F, 33.225F, 16.725F) quadTo(32.45F, 15.95F, 31.3F, 15.95F) quadTo(30.15F, 15.95F, 29.375F, 16.725F) quadTo(28.6F, 17.5F, 28.6F, 18.65F) quadTo(28.6F, 19.8F, 29.375F, 20.575F) quadTo(30.15F, 21.35F, 31.3F, 21.35F) moveTo(16.7F, 21.35F) quadTo(17.85F, 21.35F, 18.625F, 20.575F) quadTo(19.4F, 19.8F, 19.4F, 18.65F) quadTo(19.4F, 17.5F, 18.625F, 16.725F) quadTo(17.85F, 15.95F, 16.7F, 15.95F) quadTo(15.55F, 15.95F, 14.775F, 16.725F) quadTo(14.0F, 17.5F, 14.0F, 18.65F) quadTo(14.0F, 19.8F, 14.775F, 20.575F) quadTo(15.55F, 21.35F, 16.7F, 21.35F) moveTo(17.7F, 31.05F) horizontalLineTo(30.35F) verticalLineTo(28.6F) horizontalLineTo(17.7F) moveTo(24.0F, 44.0F) quadTo(19.9F, 44.0F, 16.25F, 42.425F) quadTo(12.6F, 40.85F, 9.875F, 38.125F) quadTo(7.15F, 35.4F, 5.575F, 31.75F) quadTo(4.0F, 28.1F, 4.0F, 23.95F) quadTo(4.0F, 19.85F, 5.575F, 16.2F) quadTo(7.15F, 12.55F, 9.875F, 9.85F) quadTo(12.6F, 7.15F, 16.25F, 5.575F) quadTo(19.9F, 4.0F, 24.05F, 4.0F) quadTo(28.15F, 4.0F, 31.8F, 5.575F) quadTo(35.45F, 7.15F, 38.15F, 9.85F) quadTo(40.85F, 12.55F, 42.425F, 16.2F) quadTo(44.0F, 19.85F, 44.0F, 24.0F) quadTo(44.0F, 28.1F, 42.425F, 31.75F) quadTo(40.85F, 35.4F, 38.15F, 38.125F) quadTo(35.45F, 40.85F, 31.8F, 42.425F) quadTo(28.15F, 44.0F, 24.0F, 44.0F) moveTo(24.0F, 24.0F) quadTo(24.0F, 24.0F, 24.0F, 24.0F) quadTo(24.0F, 24.0F, 24.0F, 24.0F) quadTo(24.0F, 24.0F, 24.0F, 24.0F) quadTo(24.0F, 24.0F, 24.0F, 24.0F) quadTo(24.0F, 24.0F, 24.0F, 24.0F) quadTo(24.0F, 24.0F, 24.0F, 24.0F) quadTo(24.0F, 24.0F, 24.0F, 24.0F) quadTo(24.0F, 24.0F, 24.0F, 24.0F) moveTo(24.0F, 41.0F) quadTo(31.1F, 41.0F, 36.05F, 36.025F) quadTo(41.0F, 31.05F, 41.0F, 24.0F) quadTo(41.0F, 16.9F, 36.05F, 11.95F) quadTo(31.1F, 7.0F, 24.0F, 7.0F) quadTo(16.95F, 7.0F, 11.975F, 11.95F) quadTo(7.0F, 16.9F, 7.0F, 24.0F) quadTo(7.0F, 31.05F, 11.975F, 36.025F) quadTo(16.95F, 41.0F, 24.0F, 41.0F) close() }.build() return _floating_screen!! } private var _floating_screen: ImageVector? = null
0
Kotlin
6
28
e7132da8475544a15b0288c64cdad8999c8747fa
3,777
demo-compose-multiplatform
MIT License
src/test/java/com/statsig/androidsdk/LogEventRetryTest.kt
statsig-io
357,712,105
false
{"Kotlin": 363747, "Java": 6781}
package com.statsig.androidsdk import android.app.Application import com.google.gson.Gson import io.mockk.mockk import kotlinx.coroutines.runBlocking import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okhttp3.mockwebserver.RecordedRequest import org.junit.Before import org.junit.Test class LogEventRetryTest { private lateinit var mockWebServer: MockWebServer private var logEventHits = 0 private val gson = Gson() private val app: Application = mockk() private var enforceLogEventException = false @Before fun setup() { logEventHits = 0 TestUtil.mockDispatchers() TestUtil.stubAppFunctions(app) mockWebServer = MockWebServer() val dispatcher = object : Dispatcher() { override fun dispatch(request: RecordedRequest): MockResponse { return if (request.path!!.contains("initialize")) { MockResponse() .setBody(gson.toJson(TestUtil.makeInitializeResponse())) .setResponseCode(200) } else if (request.path!!.contains("log_event")) { logEventHits++ val logEventStatusCode = if (logEventHits >= 2) 404 else 599 val response = MockResponse().setResponseCode(logEventStatusCode) if (!enforceLogEventException) { response.setBody("err") } return response } else { MockResponse().setResponseCode(404) } } } mockWebServer.dispatcher = dispatcher mockWebServer.start() } @Test fun testRetryOnRetryCode() = runBlocking { val url = mockWebServer.url("/v1").toString() Statsig.initialize(app, "client-key", StatsigUser("test"), StatsigOptions(api = url, eventLoggingAPI = url)) Statsig.logEvent("test-event1") Statsig.shutdown() assert(logEventHits == 2) } @Test fun testNoRetryOnException() = runBlocking { val url = mockWebServer.url("/v1").toString() Statsig.initialize(app, "client-key", StatsigUser("test"), StatsigOptions(api = url, eventLoggingAPI = url)) enforceLogEventException = true Statsig.logEvent("test") Statsig.shutdown() assert(logEventHits == 1) } }
3
Kotlin
4
9
503388337d8d2226ef6705d00a9b8cb5c42c5dd4
2,470
android-sdk
ISC License
prime-router/src/main/kotlin/transport/SoapTransport.kt
CDCgov
304,423,150
false
{"Kotlin": 5417139, "CSS": 3370586, "TypeScript": 1881870, "Java": 1326278, "HCL": 282334, "MDX": 140844, "PLpgSQL": 77695, "Shell": 69067, "HTML": 68387, "SCSS": 66843, "Smarty": 51325, "RouterOS Script": 17080, "Python": 13724, "Makefile": 8166, "JavaScript": 8003, "Dockerfile": 3127}
package gov.cdc.prime.router.transport import com.google.common.base.Preconditions import com.microsoft.azure.functions.ExecutionContext import gov.cdc.prime.router.Receiver import gov.cdc.prime.router.Report import gov.cdc.prime.router.ReportId import gov.cdc.prime.router.SoapTransportType import gov.cdc.prime.router.TransportType import gov.cdc.prime.router.azure.ActionHistory import gov.cdc.prime.router.azure.WorkflowEngine import gov.cdc.prime.router.azure.db.enums.TaskAction import gov.cdc.prime.router.credentials.CredentialHelper import gov.cdc.prime.router.credentials.CredentialRequestReason import gov.cdc.prime.router.credentials.SoapCredential import gov.cdc.prime.router.serializers.SoapEnvelope import gov.cdc.prime.router.serializers.SoapObjectService import io.ktor.client.HttpClient import io.ktor.client.call.receive import io.ktor.client.engine.apache.Apache import io.ktor.client.features.ClientRequestException import io.ktor.client.features.ServerResponseException import io.ktor.client.features.logging.LogLevel import io.ktor.client.features.logging.Logging import io.ktor.client.features.logging.SIMPLE import io.ktor.client.request.header import io.ktor.client.request.post import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.request import io.ktor.http.ContentType import io.ktor.http.content.TextContent import io.ktor.http.withCharset import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import java.io.StringReader import java.io.StringWriter import javax.xml.transform.OutputKeys import javax.xml.transform.TransformerFactory import javax.xml.transform.stream.StreamResult import javax.xml.transform.stream.StreamSource /** * A SOAP transport that will connect to the endpoint and send a message in a serialized SOAP envelope */ class SoapTransport(private val httpClient: HttpClient? = null) : ITransport { /** * Writes out the xml in a pretty way. This is primarily for our log files. */ private fun prettyPrintXmlResponse(value: String): String { val transformerFactory = TransformerFactory.newDefaultInstance() val transformer = transformerFactory.newTransformer().also { it.setOutputProperty(OutputKeys.INDENT, "yes") } val xmlOutput = StreamResult(StringWriter()) transformer.transform(StreamSource(StringReader(value)), xmlOutput) return xmlOutput.writer.toString() } /** * Make a SOAP connection. We're using the KTOR library here to make a direct HTTP call. * I defaulted to using the [Apache] engine to do our connections. There are a bunch of * different libraries you could use for this, but the Apache one is fairly vanilla and * straightforward for our purposes. * * This is a suspend function, meaning it can get called as an async method, though we call it * a blocking way. * * @param message The contents of the file we want to send, after it's been wrapped in the [SoapEnvelope] * object and converted to XML * @param soapEndpoint The URL to post to when sending the message * @param soapAction The command to invoke on the remote server * @param context Really just here to get logging injected */ private suspend fun connectToSoapService( message: String, soapEndpoint: String, soapAction: String, context: ExecutionContext, httpClient: HttpClient ): String { httpClient.use { client -> context.logger.info("Connecting to $soapEndpoint") // once we've created te client, we will use it to call post on the endpoint val response: HttpResponse = client.post(soapEndpoint) { // adds the SOAPAction header header("SOAPAction", soapAction) // we want to pass text in the body of our request. You need to do it this // way because the TextContent object sets other values like the charset, etc // Ktor will balk if you try to set it some other way body = TextContent( message, // force the encoding to be UTF-8. PA had issues understanding the message // unless it was explicitly set to UTF-8. Plus it's good to be explicit about // these things contentType = ContentType.Text.Xml.withCharset(Charsets.UTF_8) ) } // get the response object val body: String = response.receive() // return just the body of the message return prettyPrintXmlResponse(body) } } /** * Sends the actual message to the endpoint */ override fun send( transportType: TransportType, header: WorkflowEngine.Header, sentReportId: ReportId, retryItems: RetryItems?, context: ExecutionContext, actionHistory: ActionHistory ): RetryItems? { // verify that we have a SOAP transport type for our parameters. I think if we ever fell // into this scenario with different parameters there's something seriously wrong in the system, // but it is good to check. val soapTransportType = transportType as? SoapTransportType ?: error("Transport type passed in not of SOAPTransportType") // verify we have a receiver val receiver = header.receiver ?: error("No receiver defined for report ${header.reportFile.reportId}") // get the external file name to send to the client, if we need it val fileName = header.reportFile.externalName context.logger.info( "Preparing to send ${header.reportFile.reportId} " + "to ${soapTransportType.soapAction} at ${soapTransportType.endpoint}" ) // based on who we are sending this report to, we need to get the credentials, and we also need // to create the actual implementation object based on who we're sending to val credential = lookupCredentials(receiver) // calling the SOAP serializer in an attempt to be somewhat abstract here. this is based on the // namespaces provided to the SOAP transport info. It's kind of BS magical string garbage, but the // reality is that each client could have different objects we have to create for them, and these // objects might nest, and/or have different constructors, and it's really hard to be really generic // about this kind of stuff. So this is some semi-tight coupling we will just have to manage. // And honestly, if a client changes their SOAP endpoint, we'd (probably) need to do some coding // on our end, so incurring the maintenance cost here is (probably) okay. val xmlObject = SoapObjectService.getXmlObjectForAction(soapTransportType, header, context, credential) ?: error("Unable to find a SOAP object for the namespaces provided") // wrap the object in the generic envelope. At least this gets to be generic val soapEnvelope = SoapEnvelope(xmlObject, soapTransportType.namespaces ?: emptyMap()) return try { // run our call to the endpoint in a blocking fashion runBlocking { launch { val responseBody = connectToSoapService( soapEnvelope.toXml(), soapTransportType.endpoint, soapTransportType.soapAction, context, httpClient ?: createDefaultHttpClient() ) // update the action history val msg = "Success: SOAP transport of $fileName to $soapTransportType:\n$responseBody" context.logger.info("Message successfully sent!") actionHistory.trackActionResult(msg) actionHistory.trackSentReport( receiver, sentReportId, fileName, soapTransportType.toString(), msg, header.reportFile.itemCount ) actionHistory.trackItemLineages(Report.createItemLineagesFromDb(header, sentReportId)) } } // return null null } catch (t: Throwable) { // If Ktor fails to connect, or the server returns an error code, it is thrown // as an exception higher up, which we catch and then track here. We do not need // to worry about capturing and parsing out the return value from the response // because Ktor treats errors as exceptions val msg = "FAILED SOAP of inputReportId ${header.reportFile.reportId} to " + "$soapTransportType (orgService = ${header.receiver.fullName})" + ", Exception: ${t.localizedMessage}" context.logger.severe(msg) context.logger.severe(t.stackTraceToString()) // do some additional handling of the error here. if we are dealing with a 400 error, we // probably don't want to retry, and we need to stop now // if the error is a 500 we can do a retry, but both should probably throw a pager duty notification when (t) { is ClientRequestException -> { (t as ClientRequestException).let { context.logger.severe( "Received ${it.response.status.value}: ${it.response.status.description} " + "requesting ${it.response.request.url}. This is not recoverable. Will not retry." ) } actionHistory.setActionType(TaskAction.send_error) actionHistory.trackActionResult(msg) null } is ServerResponseException -> { // this is largely duplicated code as below, but we may want to add additional // instrumentation based on the specific error type we're getting. One benefit // we can use now is getting the specific response information from the // ServerResponseException (t as ServerResponseException).let { context.logger.severe( "Received ${it.response.status.value}: ${it.response.status.description} " + "from server ${it.response.request.url}. This may be recoverable. Will retry." ) } actionHistory.setActionType(TaskAction.send_warning) actionHistory.trackActionResult(msg) RetryToken.allItems } else -> { // this is an unknown exception, and maybe not one related to ktor, so we should // track, but try again actionHistory.setActionType(TaskAction.send_warning) actionHistory.trackActionResult(msg) RetryToken.allItems } } } } /** * Fetch the [SoapCredential] for a given [Receiver]. * @return the SOAP credential */ fun lookupCredentials(receiver: Receiver): SoapCredential { Preconditions.checkNotNull(receiver.transport) Preconditions.checkArgument(receiver.transport is SoapTransportType) val soapTransportInfo = receiver.transport as SoapTransportType // if the transport definition has defined default // credentials use them, otherwise go with the // standard way by using the receiver full name val credentialName = soapTransportInfo.credentialName ?: receiver.fullName val credentialLabel = credentialName .replace(".", "--") .replace("_", "-") .uppercase() // Assumes credential will be cast as SftpCredential, if not return null, and thus the error case return CredentialHelper.getCredentialService().fetchCredential( credentialLabel, "SoapTransport", CredentialRequestReason.SOAP_UPLOAD ) as? SoapCredential? ?: error("Unable to find SOAP credentials for $credentialName connectionId($credentialLabel)") } companion object { /** A default value for the timeouts to connect and send messages */ private const val TIMEOUT = 50_000 /** Our default Http Client */ private fun createDefaultHttpClient(): HttpClient { return HttpClient(Apache) { // installs logging into the call to post to the server install(Logging) { logger = io.ktor.client.features.logging.Logger.Companion.SIMPLE level = LogLevel.INFO } // configures the Apache client with our specified timeouts engine { followRedirects = true socketTimeout = TIMEOUT connectTimeout = TIMEOUT connectionRequestTimeout = TIMEOUT customizeClient { } } } } } }
978
Kotlin
40
71
81f5d3c284982ccdb7f24f36fc69fdd8fac2a919
13,450
prime-reportstream
Creative Commons Zero v1.0 Universal
egklib/src/commonMain/kotlin/electionguard/json2/ElementsJson.kt
votingworks
425,905,229
false
null
package electionguard.json2 import electionguard.core.Base16.fromHex import electionguard.core.Base16.toHex import electionguard.core.ElementModP import electionguard.core.ElementModQ import electionguard.core.GroupContext import electionguard.core.UInt256 import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder // // Note that Tjson.import([group]) return T?, while T.publishJson() returns Tjson /** External representation of an ElementModP. */ @Serializable(with = ElementModPAsStringSerializer::class) @SerialName("ElementModP") data class ElementModPJson(val bytes: ByteArray) { override fun toString() = bytes.toHex() } /** External representation of an ElementModQ. */ @Serializable(with = ElementModQAsStringSerializer::class) @SerialName("ElementModQ") data class ElementModQJson(val bytes: ByteArray) { override fun toString() = bytes.toHex() } /** External representation of a UInt256. */ @Serializable(with = UInt256AsStringSerializer::class) @SerialName("UInt256") data class UInt256Json(val bytes: ByteArray) { override fun toString() = bytes.toHex() } /** Custom serializer for [ElementModP]. */ object ElementModPAsStringSerializer : KSerializer<ElementModPJson> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("ElementModP", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: ElementModPJson) { val string = value.bytes.toHex() encoder.encodeString(string) } override fun deserialize(decoder: Decoder): ElementModPJson { val string = decoder.decodeString() return ElementModPJson(string.fromHex() ?: throw IllegalArgumentException ("invalid base16 ElementModP string '$string'")) } } /** Custom serializer for [ElementModQ]. */ object ElementModQAsStringSerializer : KSerializer<ElementModQJson> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("ElementModQ", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: ElementModQJson) { val string = value.bytes.toHex() encoder.encodeString(string) } override fun deserialize(decoder: Decoder): ElementModQJson { val string = decoder.decodeString() return ElementModQJson( string.fromHex() ?: throw IllegalArgumentException("invalid base16 ElementModQ string '$string'") ) } } /** Custom serializer for [UInt256Json]. */ object UInt256AsStringSerializer : KSerializer<UInt256Json> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("UInt256", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: UInt256Json) { val string = value.bytes.toHex() encoder.encodeString(string) } override fun deserialize(decoder: Decoder): UInt256Json { val string = decoder.decodeString() return UInt256Json( string.fromHex() ?: throw IllegalArgumentException("invalid base16 UInt256 string '$string'") ) } } /** Publishes an ElementModP to its external, serializable form. */ fun ElementModP.publishJson(): ElementModPJson = ElementModPJson(this.byteArray()) /** Publishes an ElementModQ to its external, serializable form. */ fun ElementModQ.publishJson(): ElementModQJson = ElementModQJson(this.byteArray()) /** Publishes an UInt256 to its external, serializable form. */ fun UInt256.publishJson(): UInt256Json = UInt256Json(this.bytes) fun ElementModPJson.import(group: GroupContext): ElementModP? = group.binaryToElementModP(this.bytes) fun ElementModQJson.import(group: GroupContext): ElementModQ? = group.binaryToElementModQ(this.bytes) fun UInt256Json.import(): UInt256? = if (this.bytes.size == 32) UInt256(this.bytes) else null
35
null
3
8
4e759afe9d57fa8f8beea82c3b78b920351023d8
3,865
electionguard-kotlin-multiplatform
MIT License
PumpkinLibrary/src/commonMain/kotlin/com/pumpkin/core/Debug.kt
FauxKiwi
315,724,386
false
null
package com.pumpkin.core import glm.Vec4 object Debug { private val coreLogger = Logger("Pumpkin") private val appLogger = Logger("Application") fun subscribe(callback: LoggerCallback) { coreLogger.subscribers.add(callback) appLogger.subscribers.add(callback) } fun setLogMinLevel(level: LogLevel) { coreLogger.minLevel = level appLogger.minLevel = level } internal fun logCore(level: LogLevel, message: String) = coreLogger.log(level, message) internal fun logTraceCore(message: String) = coreLogger.trace(message) internal fun logDebugCore(message: String) = coreLogger.debug(message) internal fun logInfoCore(message: String) = coreLogger.info(message) internal fun logWarnCore(message: String) = coreLogger.warn(message) internal fun logErrorCore(message: String, t: Throwable? = null) = coreLogger.error(message + if (t != null) ("\n" + t.stackTraceToString()) else "") internal fun logFatalCore(message: String, t: Throwable? = null) = coreLogger.fatal(message + if (t != null) ("\n" + t.stackTraceToString()) else "") fun log(level: LogLevel, message: String) = appLogger.trace(message) fun logTrace(message: String) = appLogger.trace(message) fun logDebug(message: String) = appLogger.debug(message) fun logInfo(message: String) = appLogger.info(message) fun logWarn(message: String) = appLogger.warn(message) fun logError(message: String, t: Throwable? = null) = appLogger.error(message + if (t != null) ("\n" + t.stackTraceToString()) else "") fun logFatal(message: String, t: Throwable? = null) = appLogger.fatal(message + if (t != null) ("\n" + t.stackTraceToString()) else "") fun assert(predicate: Boolean, failMessage: String? = null) { if (!predicate) exception(failMessage) } fun assert(not0: Number, failMessage: String? = null) { if (not0 == 0) exception(failMessage) } fun assert(notNull: Any?, failMessage: String? = null) { if (notNull == null) exception(failMessage) } fun exception(message: String? = null): Nothing = throw PumpkinError(message) } class Logger(private val name: String) { private fun color(level: LogLevel): String { return when (level) { LogLevel.DEBUG -> "\u001B[0;36m" LogLevel.INFO -> "\u001B[0;32m" LogLevel.WARN -> "\u001B[0;33m" LogLevel.ERROR -> "\u001B[0;31m" LogLevel.FATAL -> "\u001B[1;31m" else -> "\u001b[0;37m" } } internal val subscribers = mutableListOf<(LogLevel, String) -> Unit>() var minLevel = LogLevel.DEBUG private val resetColor = "\u001B[0m" fun log(level: LogLevel, message: String) { println(color(level) + "[${level.name}] $name: $message".also { subscribers.forEach { subscriber -> subscriber(level, it) } } + resetColor) } fun trace(message: String) { if (minLevel <= LogLevel.TRACE) { log(LogLevel.TRACE, message) }} fun debug(message: String) { if (minLevel <= LogLevel.DEBUG) { log(LogLevel.DEBUG, message) }} fun info(message: String) { if (minLevel <= LogLevel.INFO) { log(LogLevel.INFO, message) }} fun warn(message: String) { if (minLevel <= LogLevel.WARN) { log(LogLevel.WARN, message) }} fun error(message: String) { if (minLevel <= LogLevel.ERROR) { log(LogLevel.ERROR, message) }} fun fatal(message: String) { if (minLevel <= LogLevel.FATAL) { log(LogLevel.FATAL, message) }} fun addSubscriber(callback: LoggerCallback) { subscribers.add(callback) } } typealias LoggerCallback = (LogLevel, String) -> Unit enum class LogLevel(val color: Vec4) { TRACE(Vec4(0.5f, 0.5f, 0.5f, 1f)), DEBUG(Vec4(0.4f, 0.6f, 0.8f, 1f)), INFO(Vec4(0.5f, 0.8f, 0.4f, 1f)), WARN(Vec4(0.8f, 0.7f, 0.4f, 1f)), ERROR(Vec4(0.8f, 0.3f, 0.4f, 1f)), FATAL(Vec4(1f, 0f, 0.2f, 1f)); @Deprecated("Use property instead", ReplaceWith("color")) fun color() = color fun colorInt() = color.toColorInt() }
0
Kotlin
0
2
b384f2a430c0f714237e07621a01f094d9f5ee75
4,119
Pumpkin-Engine
Apache License 2.0
app/src/main/java/com/example/lunchtray/ui/AccompanimentMenuScreen.kt
dungd200803btvn
636,049,629
false
null
package com.example.lunchtray.ui import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.lunchtray.datasource.DataSource import com.example.lunchtray.model.MenuItem import com.example.lunchtray.model.MenuItem.AccompanimentItem @Composable fun AccompanimentMenuScreen( options: List<AccompanimentItem>, onCancelButtonClicked: () -> Unit, onNextButtonClicked: () -> Unit, onSelectionChanged: (AccompanimentItem) -> Unit, modifier: Modifier = Modifier ) { BaseMenuScreen( options = options, onCancelButtonClicked = onCancelButtonClicked, onNextButtonClicked = onNextButtonClicked, onSelectionChanged = onSelectionChanged as (MenuItem) -> Unit ) } @Preview @Composable fun AccompanimentMenuPreview(){ AccompanimentMenuScreen( options = DataSource.accompanimentMenuItems, onNextButtonClicked = {}, onCancelButtonClicked = {}, onSelectionChanged = {} ) }
0
Kotlin
0
0
e68f06b8016c313658e0f069515a549e07ada977
1,046
agregarPedido
Apache License 2.0
data/src/main/java/com/foobarust/data/mappers/CheckoutMapper.kt
foobar-UST
285,792,732
false
null
package com.foobarust.data.mappers import com.foobarust.data.models.checkout.PaymentMethodDto import com.foobarust.data.models.checkout.PlaceOrderResponse import com.foobarust.domain.models.checkout.PaymentMethod import com.foobarust.domain.models.checkout.PlaceOrderResult import javax.inject.Inject /** * Created by kevin on 1/9/21 */ class CheckoutMapper @Inject constructor() { fun toPaymentMethod(dto: PaymentMethodDto): PaymentMethod { return PaymentMethod( id = dto.id!!, identifier = dto.identifier!!, enabled = dto.enabled ?: false ) } fun toPlaceOrderResult(response: PlaceOrderResponse): PlaceOrderResult { return PlaceOrderResult( orderId = response.orderId, orderIdentifier = response.orderIdentifier ) } }
0
Kotlin
2
2
b4358ef0323a0b7a95483223496164e616a01da5
834
foobar-android
MIT License
srt/src/main/java/com/pedro/srt/srt/packets/control/ControlType.kt
pedroSG94
79,667,969
false
null
/* * Copyright (C) 2024 pedroSG94. * * 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.pedro.srt.srt.packets.control import java.io.IOException /** * Created by pedro on 21/8/23. */ enum class ControlType(val value: Int) { HANDSHAKE(0), KEEP_ALIVE(1), ACK(2), NAK(3), CONGESTION_WARNING(4), SHUTDOWN(5), ACK2(6), DROP_REQ(7), PEER_ERROR(8), USER_DEFINED(0x7FFF), SUB_TYPE(0); companion object { infix fun from(value: Int): ControlType = entries.firstOrNull { it.value == value } ?: throw IOException("unknown control type: $value") } }
87
null
772
2,545
eca59948009d5a7b564f9a838c149b850898d089
1,076
RootEncoder
Apache License 2.0
year2019/day24/bugs/src/main/kotlin/com/curtislb/adventofcode/year2019/day24/bugs/BugGrid.kt
curtislb
226,797,689
false
{"Kotlin": 2230363}
package com.curtislb.adventofcode.year2019.day24.bugs import java.io.File /** * A fixed-size grid containing bugs that may die off or infest other spaces over time. * * @param biodiversity A number that uniquely identifies the positions of all bugs in the grid. */ @JvmInline value class BugGrid(val biodiversity: Int) { /** * Returns the grid that results from waiting one minute for bugs in the current grid to die off * and/or infest empty spaces. * * The next grid is determined by applying the following rules to each space simultaneously: * * - A bug dies (becoming an empty space) unless there is exactly one bug adjacent to it. * - An empty space becomes infested with a bug if exactly one or two bugs are adjacent to it. * * If [upperLevel] is non-null, this grid is treated as replacing its center space, with bugs on * the exterior of this grid considered adjacent to spaces in [upperLevel] and vice versa. * * If [lowerLevel] is non-null, it is treated as replacing this grid's center space, with bugs * on the exterior of [lowerLevel] considered adjacent to spaces in this grid and vice versa. */ fun next(upperLevel: BugGrid? = null, lowerLevel: BugGrid? = null): BugGrid { var newBiodiversity = 0 for (spaceOffset in 0 until GRID_SPACES) { // Don't update the center space if lowerLevel is non-null. if (spaceOffset == OFFSET_CENTER && lowerLevel != null) { continue } // Apply the update rules to each space. val spaceFlag = 1 shl spaceOffset val bugFlag = biodiversity and spaceFlag val adjacentBugCount = countAdjacentBugs(spaceOffset, upperLevel, lowerLevel) newBiodiversity = when { bugFlag != 0 && adjacentBugCount != 1 -> newBiodiversity and spaceFlag.inv() bugFlag == 0 && adjacentBugCount in 1..2 -> newBiodiversity or spaceFlag else -> newBiodiversity or bugFlag } } return BugGrid(newBiodiversity) } /** * Returns the number of bugs in the grid that occupy spaces matching [spaceMask]. * * If no [spaceMask] is provided, returns the count of all bugs in the grid. */ fun countBugs(spaceMask: Int = 0.inv()): Int = Integer.bitCount(biodiversity and spaceMask) /** * Returns the number of bugs adjacent to the space at [spaceOffset] in the grid. * * When non-null, [upperLevel] and [lowerLevel] represent grid levels above and below the * current grid, respectively, for the purpose of determining adjacent spaces. * * @see [next] */ private fun countAdjacentBugs( spaceOffset: Int, upperLevel: BugGrid?, lowerLevel: BugGrid? ): Int { var count = 0 // Convert spaceOffset to grid coordinates. val rowIndex = spaceOffset / GRID_SIDE val colIndex = spaceOffset % GRID_SIDE // Count adjacent bugs within the current grid. if (rowIndex > 0 && isBugAt(spaceOffset - GRID_SIDE)) { count++ } if (rowIndex < GRID_SIDE - 1 && isBugAt(spaceOffset + GRID_SIDE)) { count++ } if (colIndex > 0 && isBugAt(spaceOffset - 1)) { count++ } if (colIndex < GRID_SIDE - 1 && isBugAt(spaceOffset + 1)) { count++ } // Count any adjacent bugs from the outer grid. if (upperLevel != null) { if (rowIndex == 0 && upperLevel.isBugAt(OFFSET_TOP_INTERIOR)) { count++ } if (rowIndex == GRID_SIDE - 1 && upperLevel.isBugAt(OFFSET_BOTTOM_INTERIOR)) { count++ } if (colIndex == 0 && upperLevel.isBugAt(OFFSET_LEFT_INTERIOR)) { count++ } if (colIndex == GRID_SIDE - 1 && upperLevel.isBugAt(OFFSET_RIGHT_INTERIOR)) { count++ } } // Count any adjacent bugs from the inner grid. if (lowerLevel != null) { when (spaceOffset) { OFFSET_TOP_INTERIOR -> count += lowerLevel.countBugs(MASK_TOP_EXTERIOR) OFFSET_BOTTOM_INTERIOR -> count += lowerLevel.countBugs(MASK_BOTTOM_EXTERIOR) OFFSET_LEFT_INTERIOR -> count += lowerLevel.countBugs(MASK_LEFT_EXTERIOR) OFFSET_RIGHT_INTERIOR -> count += lowerLevel.countBugs(MASK_RIGHT_EXTERIOR) } } return count } /** * Returns `true` if there is bug at [spaceOffset] in the grid, or `false` otherwise. */ private fun isBugAt(spaceOffset: Int): Boolean = biodiversity and (1 shl spaceOffset) != 0 companion object { /** * A grid containing no bugs. */ val EMPTY = BugGrid(0) /** * The width and height of a grid, in number of spaces. */ private const val GRID_SIDE = 5 /** * The total number of spaces in a grid. */ private const val GRID_SPACES = GRID_SIDE * GRID_SIDE /** * A bit mask for selecting spaces in the top row of the grid. */ private const val MASK_TOP_EXTERIOR = (1 shl GRID_SIDE) - 1 /** * A bit mask for selecting spaces in the bottom row of the grid. */ private const val MASK_BOTTOM_EXTERIOR = MASK_TOP_EXTERIOR shl (GRID_SPACES - GRID_SIDE) /** * A bit mask for selecting spaces in the leftmost column of the grid. */ private val MASK_LEFT_EXTERIOR = (0 until GRID_SPACES step GRID_SIDE).sumOf { 1 shl it } /** * A bit mask for selecting spaces in the rightmost column of the grid. */ private val MASK_RIGHT_EXTERIOR = MASK_LEFT_EXTERIOR shl (GRID_SIDE - 1) /** * The offset for the center grid space. */ private const val OFFSET_CENTER = (GRID_SIDE + 1) * (GRID_SIDE / 2) /** * The offset for the grid space that is adjacent to all top-row spaces of a lower grid. */ private const val OFFSET_TOP_INTERIOR = GRID_SIDE * (GRID_SIDE / 2 - 1) + (GRID_SIDE / 2) /** * The offset for the grid space that is adjacent to all bottom-row spaces of a lower grid. */ private const val OFFSET_BOTTOM_INTERIOR = OFFSET_TOP_INTERIOR + GRID_SIDE * 2 /** * The offset for the grid space that is adjacent to all leftmost spaces of a lower grid. */ private const val OFFSET_LEFT_INTERIOR = GRID_SIDE * (GRID_SIDE / 2) + (GRID_SIDE / 2) - 1 /** * The offset for the grid space that is adjacent to all rightmost spaces of a lower grid. */ private const val OFFSET_RIGHT_INTERIOR = OFFSET_LEFT_INTERIOR + 2 /** * Returns a grid matching the layout given by an input [file]. * * Each line of [file] should contain a row of characters, with `'.'` representing an empty * space and `'#'` representing a space that contains a bug. */ fun from(file: File): BugGrid { var biodiversity = 0 var spaceFlag = 1 file.forEachLine { line -> line.forEach { char -> if (char == '#') { biodiversity = biodiversity or spaceFlag } spaceFlag = spaceFlag shl 1 } } return BugGrid(biodiversity) } } }
0
Kotlin
1
1
06ddf047ea59b1383afd4596e2bf2607d750a324
7,647
AdventOfCode
MIT License
avropoet-gradle/src/main/kotlin/com/sksamuel/avropoet/encoders.kt
sksamuel
393,395,886
false
null
@file:Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") package com.sksamuel.avropoet import com.squareup.kotlinpoet.CodeBlock import org.apache.avro.LogicalTypes import org.apache.avro.Schema fun encode(schema: Schema, name: String): CodeBlock { return when (schema.type) { Schema.Type.RECORD -> encodeRecord(name) Schema.Type.ENUM -> encodeEnum(name) Schema.Type.ARRAY -> encodeList(name, schema) Schema.Type.MAP -> encodeMap(name, schema) Schema.Type.UNION -> encodeUnion(name, schema) Schema.Type.FIXED -> TODO("b") Schema.Type.STRING -> encodeString(name) Schema.Type.BYTES -> encodeBytes(name) Schema.Type.INT -> encodeInt(name) Schema.Type.LONG -> encodeLong(name, schema) Schema.Type.FLOAT -> encodeFloat(name) Schema.Type.DOUBLE -> encodeDouble(name) Schema.Type.BOOLEAN -> encodeBoolean(name) Schema.Type.NULL -> TODO("nullllls") } } fun encodeBytes(name: String) = CodeBlock.of(name) fun encodeInt(name: String): CodeBlock = CodeBlock.of(name) fun encodeBoolean(name: String): CodeBlock = CodeBlock.of(name) fun encodeFloat(name: String): CodeBlock = CodeBlock.of(name) fun encodeDouble(name: String): CodeBlock = CodeBlock.of(name) fun encodeString(name: String): CodeBlock { return CodeBlock.builder().add("Utf8($name)").build() } fun encodeMap(name: String, schema: Schema): CodeBlock { require(schema.type == Schema.Type.MAP) { "encodeMap requires Schema.Type.MAP, but was $schema" } return CodeBlock.builder().addStatement("$name.mapValues { ${encode(schema.valueType, "it.value")} }").build() } fun encodeLong(name: String, schema: Schema): CodeBlock { return when (schema.logicalType) { is LogicalTypes.TimestampMillis -> CodeBlock.builder().add("$name.time").build() else -> CodeBlock.builder().add(name).build() } } fun encodeList(name: String, schema: Schema): CodeBlock { require(schema.type == Schema.Type.ARRAY) { "encodeList requires Schema.Type.ARRAY, but was $schema" } return CodeBlock.builder() .addStatement("GenericData.Array(") .indent() .addStatement("schema.getField(%S).schema(),", name) .addStatement("$name.map { ${encode(schema.elementType, "it")} }") .unindent() .add(")") .build() } fun encodeEnum(name: String): CodeBlock { return CodeBlock.builder().add("GenericData.EnumSymbol(schema, $name.name)").build() } fun encodeRecord(name: String): CodeBlock { return CodeBlock.builder().add("$name.encode()").build() } fun encodeUnion(name: String, schema: Schema): CodeBlock { require(schema.isNullableUnion()) return CodeBlock.builder().add("$name?.let { ${encode(schema.types[1], "it")} }").build() }
0
null
0
2
b7f37979cfef443c4a7ad0b012d687a889628e9b
2,720
avropoet
Apache License 2.0
avropoet-gradle/src/main/kotlin/com/sksamuel/avropoet/encoders.kt
sksamuel
393,395,886
false
null
@file:Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") package com.sksamuel.avropoet import com.squareup.kotlinpoet.CodeBlock import org.apache.avro.LogicalTypes import org.apache.avro.Schema fun encode(schema: Schema, name: String): CodeBlock { return when (schema.type) { Schema.Type.RECORD -> encodeRecord(name) Schema.Type.ENUM -> encodeEnum(name) Schema.Type.ARRAY -> encodeList(name, schema) Schema.Type.MAP -> encodeMap(name, schema) Schema.Type.UNION -> encodeUnion(name, schema) Schema.Type.FIXED -> TODO("b") Schema.Type.STRING -> encodeString(name) Schema.Type.BYTES -> encodeBytes(name) Schema.Type.INT -> encodeInt(name) Schema.Type.LONG -> encodeLong(name, schema) Schema.Type.FLOAT -> encodeFloat(name) Schema.Type.DOUBLE -> encodeDouble(name) Schema.Type.BOOLEAN -> encodeBoolean(name) Schema.Type.NULL -> TODO("nullllls") } } fun encodeBytes(name: String) = CodeBlock.of(name) fun encodeInt(name: String): CodeBlock = CodeBlock.of(name) fun encodeBoolean(name: String): CodeBlock = CodeBlock.of(name) fun encodeFloat(name: String): CodeBlock = CodeBlock.of(name) fun encodeDouble(name: String): CodeBlock = CodeBlock.of(name) fun encodeString(name: String): CodeBlock { return CodeBlock.builder().add("Utf8($name)").build() } fun encodeMap(name: String, schema: Schema): CodeBlock { require(schema.type == Schema.Type.MAP) { "encodeMap requires Schema.Type.MAP, but was $schema" } return CodeBlock.builder().addStatement("$name.mapValues { ${encode(schema.valueType, "it.value")} }").build() } fun encodeLong(name: String, schema: Schema): CodeBlock { return when (schema.logicalType) { is LogicalTypes.TimestampMillis -> CodeBlock.builder().add("$name.time").build() else -> CodeBlock.builder().add(name).build() } } fun encodeList(name: String, schema: Schema): CodeBlock { require(schema.type == Schema.Type.ARRAY) { "encodeList requires Schema.Type.ARRAY, but was $schema" } return CodeBlock.builder() .addStatement("GenericData.Array(") .indent() .addStatement("schema.getField(%S).schema(),", name) .addStatement("$name.map { ${encode(schema.elementType, "it")} }") .unindent() .add(")") .build() } fun encodeEnum(name: String): CodeBlock { return CodeBlock.builder().add("GenericData.EnumSymbol(schema, $name.name)").build() } fun encodeRecord(name: String): CodeBlock { return CodeBlock.builder().add("$name.encode()").build() } fun encodeUnion(name: String, schema: Schema): CodeBlock { require(schema.isNullableUnion()) return CodeBlock.builder().add("$name?.let { ${encode(schema.types[1], "it")} }").build() }
0
null
0
2
b7f37979cfef443c4a7ad0b012d687a889628e9b
2,720
avropoet
Apache License 2.0
agp-7.1.0-alpha01/tools/base/lint/libs/lint-api/src/main/java/com/android/tools/lint/detector/api/Api.kt
jomof
502,039,754
false
{"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277}
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.lint.detector.api import com.android.tools.lint.client.api.IssueRegistry /** * The current API version for Lint's API. Custom checks should return * this value from [IssueRegistry.api]. Note that this is a constant, so * the compiler should inline the value, not read the current value from * the hosting lint environment when the custom lint checks are loaded * into lint. */ const val CURRENT_API = 10 /** Describes the given API level. */ fun describeApi(api: Int): String { return when (api) { 10 -> "7.0+" // 7.0.0-alpha04 9 -> "4.2" // 4.2.0-alpha08 8 -> "4.1" // 4.1.0-alpha06 7 -> "4.0" // 4.0.0-alpha08 6 -> "3.6" // 3.6.0-alpha06 5 -> "3.5" // 3.5.0-alpha07 4 -> "3.4" // 3.4.0-alpha03 3 -> "3.3" // 3.3.0-alpha12 2 -> "3.2" // 3.2.0-alpha07 1 -> "3.1" // Initial; 3.1.0-alpha4 0 -> "3.0 and older" -1 -> "Not specified" else -> "Future: $api" } }
1
Java
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
1,626
CppBuildCacheWorkInProgress
Apache License 2.0
tools/code-generator/src/main/kotlin/io/islandtime/codegen/generators/ConstantsGenerator.kt
erikc5000
202,192,185
false
null
package io.islandtime.codegen.generators import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.KModifier import io.islandtime.codegen.SingleFileGenerator import io.islandtime.codegen.descriptions.TemporalUnitConversion import io.islandtime.codegen.descriptions.TemporalUnitDescription import io.islandtime.codegen.descriptions.per import io.islandtime.codegen.dsl.file private val TemporalUnitConversion.classType get() = if (valueFitsInInt) Int::class else Long::class private val TemporalUnitConversion.valueString get() = "$constantValue" + if (valueFitsInInt) "" else "L" object ConstantsGenerator : SingleFileGenerator() { override fun generateSingle(): FileSpec = buildConstantsFile() } private fun buildConstantsFile() = file( packageName = "io.islandtime.internal", fileName = "_Constants", jvmName = "ConstantsKt" ) { TemporalUnitDescription.values() .flatMap { firstUnit -> TemporalUnitDescription.values() .filter { secondUnit -> secondUnit > firstUnit } .map { secondUnit -> firstUnit per secondUnit } .filter { conversion -> conversion.isSupportedAndNecessary() } } .map { conversion -> property(conversion.constantName, conversion.classType) { annotation(PublishedApi::class) modifiers(KModifier.CONST, KModifier.INTERNAL) initializer { conversion.valueString } } } }
14
null
6
76
78f8d1c9e3fc6697f619570dcc6373f838424cb5
1,487
island-time
Apache License 2.0
buildSrc/src/main/kotlin/Versions.kt
Flank
84,221,974
false
null
object Versions { // https://github.com/getsentry/sentry-java/releases const val SENTRY = "5.4.1" // https://github.com/mixpanel/mixpanel-java/releases const val MIXPANEL = "1.5.0" // https://github.com/3breadt/dd-plist/releases const val DD_PLIST = "1.23" // https://github.com/jeremymailen/kotlinter-gradle const val KTLINT_GRADLE = "3.7.0" const val KTLINT = "0.40.0" // https://github.com/Codearte/gradle-nexus-staging-plugin const val NEXUS_STAGING = "0.30.0" // https://github.com/johnrengelman/shadow/releases const val SHADOW = "7.1.0" // https://github.com/linkedin/dex-test-parser/releases const val DEX_TEST_PARSER = "2.3.3" // https://github.com/hsiafan/apk-parser const val APK_PARSER = "2.6.10" // match to Tools -> Kotlin -> Configure Kotlin Plugin Updates -> Update Channel: Stable const val KOTLIN = "1.6.0" // https://github.com/Kotlin/kotlinx.coroutines/releases const val KOTLIN_COROUTINES = "1.5.2" // https://github.com/remkop/picocli/releases const val PICOCLI = "4.6.2" // https://search.maven.org/search?q=a:google-api-services-toolresults%20g:com.google.apis const val GOOGLE_API_TOOLRESULTS = "v1beta3-rev20210809-1.32.1" // https://mvnrepository.com/artifact/com.google.api-client/google-api-client const val GOOGLE_API = "1.32.2" // https://github.com/googleapis/google-auth-library-java/releases // NOTE: https://github.com/googleapis/google-oauth-java-client is End of Life and replaced by google-auth-library-java // https://github.com/googleapis/google-oauth-java-client/issues/251#issuecomment-504565533 const val GOOGLE_AUTH = "1.3.0" // https://search.maven.org/search?q=a:google-cloud-nio%20g:com.google.cloud const val GOOGLE_NIO = "0.123.16" // https://search.maven.org/search?q=a:google-cloud-storage%20g:com.google.cloud const val GOOGLE_STORAGE = "2.2.1" // https://github.com/google/gson/releases const val GSON = "2.8.9" // https://github.com/FasterXML/jackson-core/releases // https://github.com/FasterXML/jackson-dataformat-xml/releases const val JACKSON = "2.13.0" const val JUNIT = "4.13.2" // https://github.com/jhy/jsoup/releases const val JSOUP = "1.13.1" // https://github.com/ktorio/ktor/releases const val KTOR = "1.6.5" // https://github.com/qos-ch/logback/releases const val LOGBACK = "1.2.7" // https://github.com/square/okhttp/releases const val OKHTTP = "4.9.1" // https://github.com/stefanbirkner/system-rules/releases const val SYSTEM_RULES = "1.19.0" // https://github.com/google/truth/releases const val TRUTH = "1.1.3" // https://github.com/FasterXML/woodstox/releases const val WOODSTOX = "6.2.4" const val KOTLIN_LOGGING = "2.1.0" // https://github.com/mockk/mockk const val MOCKK = "1.12.1" // https://commons.apache.org/proper/commons-text/ const val COMMON_TEXT = "1.9" // https://github.com/jboss-logging/commons-logging-jboss-logging // JBoss logging dep is used by the Google Auth library when configuring a proxy. // https://github.com/googleapis/google-auth-library-java#configuring-a-proxy const val JBOSS_LOGGING = "1.0.0.Final" // https://github.com/fusesource/jansi/releases const val JANSI = "2.4.0" // https://github.com/ben-manes/gradle-versions-plugin/releases const val BEN_MANES = "0.39.0" // https://github.com/Guardsquare/proguard const val PROGUARD = "7.1.1" // https://mvnrepository.com/artifact/org.json/json const val JSON = "20210307" // ============== flank-scripts ============== const val KOTLIN_SERIALIZATION = "1.3.1" const val ARCHIVE_LIB = "1.2.0" const val TUKAANI_XZ = "1.9" const val FUEL = "2.3.1" const val CLIKT = "2.8.0" const val JCABI_GITHUB = "1.1.2" const val SLF4J_NOP = "1.7.32" const val GLASSFISH_JSON = "1.1.4" }
56
null
119
649
2a4816ca953b1273e87ecf4b0a8c46bf5f4e795c
3,986
flank
Apache License 2.0
bluetape4k/core/src/test/kotlin/io/bluetape4k/utils/SingletonHolderTest.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.utils import io.bluetape4k.junit5.output.InMemoryLogbackAppender import io.bluetape4k.logging.KotlinLogging import io.bluetape4k.logging.debug import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldContain import org.junit.jupiter.api.Test class SingletonHolderTest { class Manager private constructor(private val name: String) { companion object: SingletonHolder<Manager>({ Manager("manager") }) { val log = KotlinLogging.logger {} } fun doStuff() { log.debug { "name=$name" } } } private val appender = InMemoryLogbackAppender() @Test fun `get singleton manager`() { val manager = Manager.getInstance() manager.doStuff() appender.lastMessage!! shouldContain "name=manager" } @Test fun `get singleton manager with parallel mode`() { val managers = List(100) { it } .parallelStream() .map { Manager.getInstance() } .distinct() .toList() managers.size shouldBeEqualTo 1 } }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
1,103
bluetape4k
MIT License
tests/value/src/jsTest/kotlin/com/test/example/NodeFilterTest.kt
turansky
279,976,108
false
{"Kotlin": 148063, "JavaScript": 1520, "Shell": 459, "HTML": 302}
package com.test.example import kotlin.test.Test class NodeFilterTest { @Test fun test() { assertEquals(1, NodeFilter.FILTER_ACCEPT) } }
0
Kotlin
7
53
627c6ecc6ac5406a95cdabd3078237ec371946d4
159
seskar
Apache License 2.0
plugins/git4idea/src/git4idea/index/actions/GitStageCompareWithVersionAction.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.index.actions import com.intellij.diff.DiffDialogHints import com.intellij.diff.DiffManager import com.intellij.diff.chains.SimpleDiffRequestChain import com.intellij.diff.chains.SimpleDiffRequestProducer import com.intellij.diff.requests.DiffRequest import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.vfs.VirtualFile import git4idea.index.* import git4idea.index.vfs.GitIndexVirtualFile import git4idea.index.vfs.filePath abstract class GitStageCompareWithVersionAction(private val currentVersion: ContentVersion, private val compareWithVersion: ContentVersion) : DumbAwareAction() { override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun update(e: AnActionEvent) { val project = e.project val file = e.getData(CommonDataKeys.VIRTUAL_FILE) if (project == null || !isStagingAreaAvailable(project) || file == null || (file is GitIndexVirtualFile != (currentVersion == ContentVersion.STAGED))) { e.presentation.isEnabledAndVisible = false return } val status = GitStageTracker.getInstance(project).status(file) e.presentation.isVisible = (status != null) e.presentation.isEnabled = (status?.has(compareWithVersion) == true) } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val file = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE) val root = getRoot(project, file) ?: return val status = GitStageTracker.getInstance(project).status(root, file) ?: return val producer = SimpleDiffRequestProducer.create(file.filePath(), ThrowableComputable { createDiffRequest(project, root, status) }) DiffManager.getInstance().showDiff(e.project, SimpleDiffRequestChain.fromProducer(producer), DiffDialogHints.DEFAULT) } abstract fun createDiffRequest(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest } class GitStageCompareLocalWithStagedAction : GitStageCompareWithVersionAction(ContentVersion.LOCAL, ContentVersion.STAGED) { override fun createDiffRequest(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest { return compareStagedWithLocal(project, root, status) } } class GitStageCompareStagedWithLocalAction : GitStageCompareWithVersionAction(ContentVersion.STAGED, ContentVersion.LOCAL) { override fun createDiffRequest(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest { return compareStagedWithLocal(project, root, status) } } class GitStageCompareStagedWithHeadAction : GitStageCompareWithVersionAction(ContentVersion.STAGED, ContentVersion.HEAD) { override fun createDiffRequest(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest { return compareHeadWithStaged(project, root, status) } }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
3,262
intellij-community
Apache License 2.0
src/main/kotlin/com/atlassian/performance/tools/aws/api/Storage.kt
atlassian-labs
314,701,354
false
{"Kotlin": 143884}
package com.atlassian.performance.tools.aws.api import com.amazonaws.regions.Regions import com.amazonaws.services.s3.AmazonS3 import com.amazonaws.services.s3.model.ListObjectsV2Request import com.amazonaws.services.s3.model.ListObjectsV2Result import com.atlassian.performance.tools.io.api.copy import com.atlassian.performance.tools.jvmtasks.api.ExponentialBackoff import com.atlassian.performance.tools.jvmtasks.api.IdempotentAction import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger import java.io.File import java.net.URI import java.nio.file.Files.newDirectoryStream import java.nio.file.Path import java.time.Duration @Suppress("LoggingStringTemplateAsArgument") data class Storage( private val s3: AmazonS3, private val prefix: String, private val bucketName: String ) { private val logger: Logger = LogManager.getLogger(this::class.java) private val dirPrefix = "$prefix/" /** * Still uses [prefix] instead of [dirPrefix], because it's used like: * ``` * ${location.uri}/remote.txt * ``` * It could lead to errors like: * ``` * Failed to download aws-resources-test-00f82558-93b2-4e28-92da-d4b22d8dc053//remote.txt despite 2 attempts * ``` * We'd need to find a deprecation path to roll out the correct trailing slash. */ val uri: URI = URI("s3", "//$bucketName/$prefix", null) val location = StorageLocation(uri, Regions.fromName(s3.regionName)) fun upload( file: File ) { if (file.isDirectory) { newDirectoryStream(file.toPath()).use { files -> files.forEach { uploadRecursively(it.toFile(), bucketName, dirPrefix + it.fileName) } } } else { val fileKey = dirPrefix + file.name logger.debug("Uploading $file to $bucketName under $fileKey") s3.putObject(bucketName, fileKey, file) } } private fun uploadRecursively( file: File, bucketName: String, key: String ) { if (file.isDirectory) { newDirectoryStream(file.toPath()).use { files -> files.forEach { uploadRecursively(it.toFile(), bucketName, "$key/${it.fileName}") } } } else { logger.debug("Uploading $file to $bucketName under $key") s3.putObject(bucketName, key, file) } } fun download( rootTarget: Path ): Path { var token: String? = null do { val listing = s3.listObjectsV2( ListObjectsV2Request() .withBucketName(bucketName) .withPrefix(dirPrefix) .withContinuationToken(token) ) download(listing, rootTarget) token = listing.nextContinuationToken } while (token != null) return rootTarget } private fun download( listing: ListObjectsV2Result, rootTarget: Path ) { listing .objectSummaries .map { it.key } .map { key -> IdempotentAction("download $key") { downloadObject(key, rootTarget) } } .forEach { download -> download.retry( maxAttempts = 2, backoff = ExponentialBackoff( baseBackoff = Duration.ofSeconds(5), exponent = 2.0 ) ) } } private fun downloadObject( key: String, rootTarget: Path ) { val path = key.removePrefix(dirPrefix) val leafTarget = rootTarget.resolve(path) logger.debug("Downloading $bucketName/$key into $leafTarget") s3.getObject(bucketName, key).objectContent.use { stream -> stream.copy(leafTarget) } } /** * @since 1.13.0 */ fun hasContent(): Boolean { val listRequest = ListObjectsV2Request() .withBucketName(bucketName) .withPrefix(dirPrefix) .withMaxKeys(1) return s3.listObjectsV2(listRequest).objectSummaries.isNotEmpty() } }
0
Kotlin
1
2
aa41e0843b6beaf4e4f711f5cce6839a1deffa82
4,301
aws-resources
Apache License 2.0
examples/src/tl/telegram/InputStickeredMedia.kt
andreypfau
719,064,910
false
{"Kotlin": 62259}
// This file is generated by TLGenerator.kt // Do not edit manually! package tl.telegram import io.github.andreypfau.tl.serialization.TLCombinatorId import kotlin.jvm.JvmName import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonClassDiscriminator @Serializable @JsonClassDiscriminator("@type") public sealed interface InputStickeredMedia { @Serializable @SerialName("inputStickeredMediaPhoto") @TLCombinatorId(0x4A992157) public data class InputStickeredMediaPhoto( @get:JvmName("id") public val id: InputPhoto, ) : InputStickeredMedia { public companion object } @Serializable @SerialName("inputStickeredMediaDocument") @TLCombinatorId(0x438865B) public data class InputStickeredMediaDocument( @get:JvmName("id") public val id: InputDocument, ) : InputStickeredMedia { public companion object } public companion object }
0
Kotlin
0
1
11f05ad1f977235e3e360cd6f6ada6f26993208e
993
tl-kotlin
MIT License
core/src/main/java/com/crocodic/core/data/CoreSession.kt
yzzzd
392,866,678
false
null
package com.crocodic.core.data import android.content.Context import android.content.SharedPreferences import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKey /** * Created by @yzzzd on 4/22/18. */ open class CoreSession(context: Context) { companion object { const val PREF_NAME = "_core_" const val PREF_FCMID = "fcm_id" const val PREF_UID = "user_id" } private val masterKey = MasterKey.Builder(context) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) .build() //private var pref: SharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) private var pref: SharedPreferences = EncryptedSharedPreferences.create(context, PREF_NAME, masterKey, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) fun setValue(key: String, value: String) { val editor = pref.edit() editor?.putString(key, value) editor?.apply() } fun setValue(key: String, value: Boolean) { val editor = pref.edit() editor?.putBoolean(key, value) editor?.apply() } fun setValue(key: String, value: Int) { val editor = pref.edit() editor?.putInt(key, value) editor?.apply() } fun setValue(key: String, value: Long) { val editor = pref.edit() editor?.putLong(key, value) editor?.apply() } fun getBoolean(key: String): Boolean { return pref.getBoolean(key, false) } fun getString(key: String): String { return pref.getString(key, "") ?: "" } fun getInt(key: String): Int { return pref.getInt(key, 0) } fun clearAll() { val bkFcmId = getString(PREF_FCMID) val bkUserId = getString(PREF_UID) val editor = pref.edit() editor.clear() editor.apply() setValue(PREF_FCMID, bkFcmId) setValue(PREF_UID, bkUserId) } }
0
null
3
3
9636aaebdaa75b36f0721ceb500c624cab0696d7
2,068
androidcore
Apache License 1.1
kt/godot-library/src/main/kotlin/godot/gen/godot/PopupMenu.kt
utopia-rise
289,462,532
false
{"Kotlin": 1549917, "GDScript": 535642, "C++": 403741, "C": 13152, "C#": 10278, "Shell": 7406, "Java": 2165, "CMake": 939, "Python": 75}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT", "RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate") package godot import godot.`annotation`.GodotBaseType import godot.core.Color import godot.core.TypeManager import godot.core.VariantType.ANY import godot.core.VariantType.BOOL import godot.core.VariantType.COLOR import godot.core.VariantType.DOUBLE import godot.core.VariantType.LONG import godot.core.VariantType.NIL import godot.core.VariantType.OBJECT import godot.core.VariantType.STRING import godot.core.memory.TransferContext import godot.signals.Signal0 import godot.signals.Signal1 import godot.signals.signal import godot.util.VoidPtr import kotlin.Any import kotlin.Boolean import kotlin.Double import kotlin.Float import kotlin.Int import kotlin.Long import kotlin.String import kotlin.Suppress import kotlin.Unit import kotlin.jvm.JvmOverloads /** * [PopupMenu] is a modal window used to display a list of options. Useful for toolbars and context * menus. * The size of a [PopupMenu] can be limited by using [Window.maxSize]. If the height of the list of * items is larger than the maximum height of the [PopupMenu], a [ScrollContainer] within the popup * will allow the user to scroll the contents. If no maximum size is set, or if it is set to `0`, the * [PopupMenu] height will be limited by its parent rect. * All `set_*` methods allow negative item indices, i.e. `-1` to access the last item, `-2` to * select the second-to-last item, and so on. * **Incremental search:** Like [ItemList] and [Tree], [PopupMenu] supports searching within the * list while the control is focused. Press a key that matches the first letter of an item's name to * select the first item starting with the given letter. After that point, there are two ways to * perform incremental search: 1) Press the same key again before the timeout duration to select the * next item starting with the same letter. 2) Press letter keys that match the rest of the word before * the timeout duration to match to select the item in question directly. Both of these actions will be * reset to the beginning of the list if the timeout duration has passed since the last keystroke was * registered. You can adjust the timeout duration by changing * [ProjectSettings.gui/timers/incrementalSearchMaxIntervalMsec]. * **Note:** The ID values used for items are limited to 32 bits, not full 64 bits of [int]. This * has a range of `-2^32` to `2^32 - 1`, i.e. `-2147483648` to `2147483647`. */ @GodotBaseType public open class PopupMenu : Popup() { /** * Emitted when an item of some [id] is pressed or its accelerator is activated. * **Note:** If [id] is negative (either explicitly or due to overflow), this will return the * corresponding index instead. */ public val idPressed: Signal1<Long> by signal("id") /** * Emitted when the user navigated to an item of some [id] using the [ProjectSettings.input/uiUp] * or [ProjectSettings.input/uiDown] input action. */ public val idFocused: Signal1<Long> by signal("id") /** * Emitted when an item of some [index] is pressed or its accelerator is activated. */ public val indexPressed: Signal1<Long> by signal("index") /** * Emitted when any item is added, modified or removed. */ public val menuChanged: Signal0 by signal() /** * If `true`, hides the [PopupMenu] when an item is selected. */ public var hideOnItemSelection: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isHideOnItemSelectionPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setHideOnItemSelectionPtr, NIL) } /** * If `true`, hides the [PopupMenu] when a checkbox or radio button is selected. */ public var hideOnCheckableItemSelection: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isHideOnCheckableItemSelectionPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setHideOnCheckableItemSelectionPtr, NIL) } /** * If `true`, hides the [PopupMenu] when a state item is selected. */ public var hideOnStateItemSelection: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isHideOnStateItemSelectionPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setHideOnStateItemSelectionPtr, NIL) } /** * Sets the delay time in seconds for the submenu item to popup on mouse hovering. If the popup * menu is added as a child of another (acting as a submenu), it will inherit the delay time of the * parent menu item. */ public var submenuPopupDelay: Float get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getSubmenuPopupDelayPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setSubmenuPopupDelayPtr, NIL) } /** * If `true`, allows navigating [PopupMenu] with letter keys. */ public var allowSearch: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getAllowSearchPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setAllowSearchPtr, NIL) } /** * If set to one of the values of [NativeMenu.SystemMenus], this [PopupMenu] is bound to the * special system menu. Only one [PopupMenu] can be bound to each special menu at a time. */ public var systemMenuId: NativeMenu.SystemMenus get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getSystemMenuPtr, LONG) return NativeMenu.SystemMenus.from(TransferContext.readReturnValue(LONG) as Long) } set(`value`) { TransferContext.writeArguments(LONG to value.id) TransferContext.callMethod(rawPtr, MethodBindings.setSystemMenuPtr, NIL) } /** * If `true`, [MenuBar] will use native menu when supported. * **Note:** If [PopupMenu] is linked to [StatusIndicator], [MenuBar], or another [PopupMenu] item * it can use native menu regardless of this property, use [isNativeMenu] to check it. */ public var preferNativeMenu: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isPreferNativeMenuPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setPreferNativeMenuPtr, NIL) } /** * The number of items currently in the list. */ public var itemCount: Int get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getItemCountPtr, LONG) return (TransferContext.readReturnValue(LONG, false) as Long).toInt() } set(`value`) { TransferContext.writeArguments(LONG to value.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.setItemCountPtr, NIL) } public override fun new(scriptIndex: Int): Unit { callConstructor(ENGINECLASS_POPUPMENU, scriptIndex) } /** * Checks the provided [event] against the [PopupMenu]'s shortcuts and accelerators, and activates * the first item with matching events. If [forGlobalOnly] is `true`, only shortcuts and accelerators * with `global` set to `true` will be called. * Returns `true` if an item was successfully activated. * **Note:** Certain [Control]s, such as [MenuButton], will call this method automatically. */ @JvmOverloads public fun activateItemByEvent(event: InputEvent, forGlobalOnly: Boolean = false): Boolean { TransferContext.writeArguments(OBJECT to event, BOOL to forGlobalOnly) TransferContext.callMethod(rawPtr, MethodBindings.activateItemByEventPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } /** * Returns `true` if the system native menu is supported and currently used by this [PopupMenu]. */ public fun isNativeMenu(): Boolean { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isNativeMenuPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } /** * Adds a new item with text [label]. * An [id] can optionally be provided, as well as an accelerator ([accel]). If no [id] is * provided, one will be created from the index. If no [accel] is provided, then the default value of * 0 (corresponding to [@GlobalScope.KEY_NONE]) will be assigned to the item (which means it won't * have any accelerator). See [getItemAccelerator] for more info on accelerators. * **Note:** The provided [id] is used only in [signal id_pressed] and [signal id_focused] * signals. It's not related to the `index` arguments in e.g. [setItemChecked]. */ @JvmOverloads public fun addItem( label: String, id: Int = -1, accel: Key = Key.KEY_NONE, ): Unit { TransferContext.writeArguments(STRING to label, LONG to id.toLong(), LONG to accel.id) TransferContext.callMethod(rawPtr, MethodBindings.addItemPtr, NIL) } /** * Adds a new item with text [label] and icon [texture]. * An [id] can optionally be provided, as well as an accelerator ([accel]). If no [id] is * provided, one will be created from the index. If no [accel] is provided, then the default value of * 0 (corresponding to [@GlobalScope.KEY_NONE]) will be assigned to the item (which means it won't * have any accelerator). See [getItemAccelerator] for more info on accelerators. */ @JvmOverloads public fun addIconItem( texture: Texture2D, label: String, id: Int = -1, accel: Key = Key.KEY_NONE, ): Unit { TransferContext.writeArguments(OBJECT to texture, STRING to label, LONG to id.toLong(), LONG to accel.id) TransferContext.callMethod(rawPtr, MethodBindings.addIconItemPtr, NIL) } /** * Adds a new checkable item with text [label]. * An [id] can optionally be provided, as well as an accelerator ([accel]). If no [id] is * provided, one will be created from the index. If no [accel] is provided, then the default value of * 0 (corresponding to [@GlobalScope.KEY_NONE]) will be assigned to the item (which means it won't * have any accelerator). See [getItemAccelerator] for more info on accelerators. * **Note:** Checkable items just display a checkmark, but don't have any built-in checking * behavior and must be checked/unchecked manually. See [setItemChecked] for more info on how to * control it. */ @JvmOverloads public fun addCheckItem( label: String, id: Int = -1, accel: Key = Key.KEY_NONE, ): Unit { TransferContext.writeArguments(STRING to label, LONG to id.toLong(), LONG to accel.id) TransferContext.callMethod(rawPtr, MethodBindings.addCheckItemPtr, NIL) } /** * Adds a new checkable item with text [label] and icon [texture]. * An [id] can optionally be provided, as well as an accelerator ([accel]). If no [id] is * provided, one will be created from the index. If no [accel] is provided, then the default value of * 0 (corresponding to [@GlobalScope.KEY_NONE]) will be assigned to the item (which means it won't * have any accelerator). See [getItemAccelerator] for more info on accelerators. * **Note:** Checkable items just display a checkmark, but don't have any built-in checking * behavior and must be checked/unchecked manually. See [setItemChecked] for more info on how to * control it. */ @JvmOverloads public fun addIconCheckItem( texture: Texture2D, label: String, id: Int = -1, accel: Key = Key.KEY_NONE, ): Unit { TransferContext.writeArguments(OBJECT to texture, STRING to label, LONG to id.toLong(), LONG to accel.id) TransferContext.callMethod(rawPtr, MethodBindings.addIconCheckItemPtr, NIL) } /** * Adds a new radio check button with text [label]. * An [id] can optionally be provided, as well as an accelerator ([accel]). If no [id] is * provided, one will be created from the index. If no [accel] is provided, then the default value of * 0 (corresponding to [@GlobalScope.KEY_NONE]) will be assigned to the item (which means it won't * have any accelerator). See [getItemAccelerator] for more info on accelerators. * **Note:** Checkable items just display a checkmark, but don't have any built-in checking * behavior and must be checked/unchecked manually. See [setItemChecked] for more info on how to * control it. */ @JvmOverloads public fun addRadioCheckItem( label: String, id: Int = -1, accel: Key = Key.KEY_NONE, ): Unit { TransferContext.writeArguments(STRING to label, LONG to id.toLong(), LONG to accel.id) TransferContext.callMethod(rawPtr, MethodBindings.addRadioCheckItemPtr, NIL) } /** * Same as [addIconCheckItem], but uses a radio check button. */ @JvmOverloads public fun addIconRadioCheckItem( texture: Texture2D, label: String, id: Int = -1, accel: Key = Key.KEY_NONE, ): Unit { TransferContext.writeArguments(OBJECT to texture, STRING to label, LONG to id.toLong(), LONG to accel.id) TransferContext.callMethod(rawPtr, MethodBindings.addIconRadioCheckItemPtr, NIL) } /** * Adds a new multistate item with text [label]. * Contrarily to normal binary items, multistate items can have more than two states, as defined * by [maxStates]. The default value is defined by [defaultState]. * An [id] can optionally be provided, as well as an accelerator ([accel]). If no [id] is * provided, one will be created from the index. If no [accel] is provided, then the default value of * 0 (corresponding to [@GlobalScope.KEY_NONE]) will be assigned to the item (which means it won't * have any accelerator). See [getItemAccelerator] for more info on accelerators. * **Note:** Multistate items don't update their state automatically and must be done manually. * See [toggleItemMultistate], [setItemMultistate] and [getItemMultistate] for more info on how to * control it. * Example usage: * [codeblock] * func _ready(): * add_multistate_item("Item", 3, 0) * * index_pressed.connect(func(index: int): * toggle_item_multistate(index) * match get_item_multistate(index): * 0: * print("First state") * 1: * print("Second state") * 2: * print("Third state") * ) * [/codeblock] */ @JvmOverloads public fun addMultistateItem( label: String, maxStates: Int, defaultState: Int = 0, id: Int = -1, accel: Key = Key.KEY_NONE, ): Unit { TransferContext.writeArguments(STRING to label, LONG to maxStates.toLong(), LONG to defaultState.toLong(), LONG to id.toLong(), LONG to accel.id) TransferContext.callMethod(rawPtr, MethodBindings.addMultistateItemPtr, NIL) } /** * Adds a [Shortcut]. * An [id] can optionally be provided. If no [id] is provided, one will be created from the index. * If [allowEcho] is `true`, the shortcut can be activated with echo events. */ @JvmOverloads public fun addShortcut( shortcut: Shortcut, id: Int = -1, global: Boolean = false, allowEcho: Boolean = false, ): Unit { TransferContext.writeArguments(OBJECT to shortcut, LONG to id.toLong(), BOOL to global, BOOL to allowEcho) TransferContext.callMethod(rawPtr, MethodBindings.addShortcutPtr, NIL) } /** * Adds a new item and assigns the specified [Shortcut] and icon [texture] to it. Sets the label * of the checkbox to the [Shortcut]'s name. * An [id] can optionally be provided. If no [id] is provided, one will be created from the index. * If [allowEcho] is `true`, the shortcut can be activated with echo events. */ @JvmOverloads public fun addIconShortcut( texture: Texture2D, shortcut: Shortcut, id: Int = -1, global: Boolean = false, allowEcho: Boolean = false, ): Unit { TransferContext.writeArguments(OBJECT to texture, OBJECT to shortcut, LONG to id.toLong(), BOOL to global, BOOL to allowEcho) TransferContext.callMethod(rawPtr, MethodBindings.addIconShortcutPtr, NIL) } /** * Adds a new checkable item and assigns the specified [Shortcut] to it. Sets the label of the * checkbox to the [Shortcut]'s name. * An [id] can optionally be provided. If no [id] is provided, one will be created from the index. * **Note:** Checkable items just display a checkmark, but don't have any built-in checking * behavior and must be checked/unchecked manually. See [setItemChecked] for more info on how to * control it. */ @JvmOverloads public fun addCheckShortcut( shortcut: Shortcut, id: Int = -1, global: Boolean = false, ): Unit { TransferContext.writeArguments(OBJECT to shortcut, LONG to id.toLong(), BOOL to global) TransferContext.callMethod(rawPtr, MethodBindings.addCheckShortcutPtr, NIL) } /** * Adds a new checkable item and assigns the specified [Shortcut] and icon [texture] to it. Sets * the label of the checkbox to the [Shortcut]'s name. * An [id] can optionally be provided. If no [id] is provided, one will be created from the index. * **Note:** Checkable items just display a checkmark, but don't have any built-in checking * behavior and must be checked/unchecked manually. See [setItemChecked] for more info on how to * control it. */ @JvmOverloads public fun addIconCheckShortcut( texture: Texture2D, shortcut: Shortcut, id: Int = -1, global: Boolean = false, ): Unit { TransferContext.writeArguments(OBJECT to texture, OBJECT to shortcut, LONG to id.toLong(), BOOL to global) TransferContext.callMethod(rawPtr, MethodBindings.addIconCheckShortcutPtr, NIL) } /** * Adds a new radio check button and assigns a [Shortcut] to it. Sets the label of the checkbox to * the [Shortcut]'s name. * An [id] can optionally be provided. If no [id] is provided, one will be created from the index. * **Note:** Checkable items just display a checkmark, but don't have any built-in checking * behavior and must be checked/unchecked manually. See [setItemChecked] for more info on how to * control it. */ @JvmOverloads public fun addRadioCheckShortcut( shortcut: Shortcut, id: Int = -1, global: Boolean = false, ): Unit { TransferContext.writeArguments(OBJECT to shortcut, LONG to id.toLong(), BOOL to global) TransferContext.callMethod(rawPtr, MethodBindings.addRadioCheckShortcutPtr, NIL) } /** * Same as [addIconCheckShortcut], but uses a radio check button. */ @JvmOverloads public fun addIconRadioCheckShortcut( texture: Texture2D, shortcut: Shortcut, id: Int = -1, global: Boolean = false, ): Unit { TransferContext.writeArguments(OBJECT to texture, OBJECT to shortcut, LONG to id.toLong(), BOOL to global) TransferContext.callMethod(rawPtr, MethodBindings.addIconRadioCheckShortcutPtr, NIL) } /** * Adds an item that will act as a submenu of the parent [PopupMenu] node when clicked. The * [submenu] argument must be the name of an existing [PopupMenu] that has been added as a child to * this node. This submenu will be shown when the item is clicked, hovered for long enough, or * activated using the `ui_select` or `ui_right` input actions. * An [id] can optionally be provided. If no [id] is provided, one will be created from the index. */ @JvmOverloads public fun addSubmenuItem( label: String, submenu: String, id: Int = -1, ): Unit { TransferContext.writeArguments(STRING to label, STRING to submenu, LONG to id.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.addSubmenuItemPtr, NIL) } /** * Adds an item that will act as a submenu of the parent [PopupMenu] node when clicked. This * submenu will be shown when the item is clicked, hovered for long enough, or activated using the * `ui_select` or `ui_right` input actions. * [submenu] must be either child of this [PopupMenu] or has no parent node (in which case it will * be automatically added as a child). If the [submenu] popup has another parent, this method will * fail. * An [id] can optionally be provided. If no [id] is provided, one will be created from the index. */ @JvmOverloads public fun addSubmenuNodeItem( label: String, submenu: PopupMenu, id: Int = -1, ): Unit { TransferContext.writeArguments(STRING to label, OBJECT to submenu, LONG to id.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.addSubmenuNodeItemPtr, NIL) } /** * Sets the text of the item at the given [index]. */ public fun setItemText(index: Int, text: String): Unit { TransferContext.writeArguments(LONG to index.toLong(), STRING to text) TransferContext.callMethod(rawPtr, MethodBindings.setItemTextPtr, NIL) } /** * Sets item's text base writing direction. */ public fun setItemTextDirection(index: Int, direction: Control.TextDirection): Unit { TransferContext.writeArguments(LONG to index.toLong(), LONG to direction.id) TransferContext.callMethod(rawPtr, MethodBindings.setItemTextDirectionPtr, NIL) } /** * Sets language code of item's text used for line-breaking and text shaping algorithms, if left * empty current locale is used instead. */ public fun setItemLanguage(index: Int, language: String): Unit { TransferContext.writeArguments(LONG to index.toLong(), STRING to language) TransferContext.callMethod(rawPtr, MethodBindings.setItemLanguagePtr, NIL) } /** * Replaces the [Texture2D] icon of the item at the given [index]. */ public fun setItemIcon(index: Int, icon: Texture2D): Unit { TransferContext.writeArguments(LONG to index.toLong(), OBJECT to icon) TransferContext.callMethod(rawPtr, MethodBindings.setItemIconPtr, NIL) } /** * Sets the maximum allowed width of the icon for the item at the given [index]. This limit is * applied on top of the default size of the icon and on top of [theme_item icon_max_width]. The * height is adjusted according to the icon's ratio. */ public fun setItemIconMaxWidth(index: Int, width: Int): Unit { TransferContext.writeArguments(LONG to index.toLong(), LONG to width.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.setItemIconMaxWidthPtr, NIL) } /** * Sets a modulating [Color] of the item's icon at the given [index]. */ public fun setItemIconModulate(index: Int, modulate: Color): Unit { TransferContext.writeArguments(LONG to index.toLong(), COLOR to modulate) TransferContext.callMethod(rawPtr, MethodBindings.setItemIconModulatePtr, NIL) } /** * Sets the checkstate status of the item at the given [index]. */ public fun setItemChecked(index: Int, checked: Boolean): Unit { TransferContext.writeArguments(LONG to index.toLong(), BOOL to checked) TransferContext.callMethod(rawPtr, MethodBindings.setItemCheckedPtr, NIL) } /** * Sets the [id] of the item at the given [index]. * The [id] is used in [signal id_pressed] and [signal id_focused] signals. */ public fun setItemId(index: Int, id: Int): Unit { TransferContext.writeArguments(LONG to index.toLong(), LONG to id.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.setItemIdPtr, NIL) } /** * Sets the accelerator of the item at the given [index]. An accelerator is a keyboard shortcut * that can be pressed to trigger the menu button even if it's not currently open. [accel] is * generally a combination of [KeyModifierMask]s and [Key]s using bitwise OR such as `KEY_MASK_CTRL | * KEY_A` ([kbd]Ctrl + A[/kbd]). */ public fun setItemAccelerator(index: Int, accel: Key): Unit { TransferContext.writeArguments(LONG to index.toLong(), LONG to accel.id) TransferContext.callMethod(rawPtr, MethodBindings.setItemAcceleratorPtr, NIL) } /** * Sets the metadata of an item, which may be of any type. You can later get it with * [getItemMetadata], which provides a simple way of assigning context data to items. */ public fun setItemMetadata(index: Int, metadata: Any?): Unit { TransferContext.writeArguments(LONG to index.toLong(), ANY to metadata) TransferContext.callMethod(rawPtr, MethodBindings.setItemMetadataPtr, NIL) } /** * Enables/disables the item at the given [index]. When it is disabled, it can't be selected and * its action can't be invoked. */ public fun setItemDisabled(index: Int, disabled: Boolean): Unit { TransferContext.writeArguments(LONG to index.toLong(), BOOL to disabled) TransferContext.callMethod(rawPtr, MethodBindings.setItemDisabledPtr, NIL) } /** * Sets the submenu of the item at the given [index]. The submenu is the name of a child * [PopupMenu] node that would be shown when the item is clicked. */ public fun setItemSubmenu(index: Int, submenu: String): Unit { TransferContext.writeArguments(LONG to index.toLong(), STRING to submenu) TransferContext.callMethod(rawPtr, MethodBindings.setItemSubmenuPtr, NIL) } /** * Sets the submenu of the item at the given [index]. The submenu is a [PopupMenu] node that would * be shown when the item is clicked. It must either be a child of this [PopupMenu] or has no parent * (in which case it will be automatically added as a child). If the [submenu] popup has another * parent, this method will fail. */ public fun setItemSubmenuNode(index: Int, submenu: PopupMenu): Unit { TransferContext.writeArguments(LONG to index.toLong(), OBJECT to submenu) TransferContext.callMethod(rawPtr, MethodBindings.setItemSubmenuNodePtr, NIL) } /** * Mark the item at the given [index] as a separator, which means that it would be displayed as a * line. If `false`, sets the type of the item to plain text. */ public fun setItemAsSeparator(index: Int, enable: Boolean): Unit { TransferContext.writeArguments(LONG to index.toLong(), BOOL to enable) TransferContext.callMethod(rawPtr, MethodBindings.setItemAsSeparatorPtr, NIL) } /** * Sets whether the item at the given [index] has a checkbox. If `false`, sets the type of the * item to plain text. * **Note:** Checkable items just display a checkmark, but don't have any built-in checking * behavior and must be checked/unchecked manually. */ public fun setItemAsCheckable(index: Int, enable: Boolean): Unit { TransferContext.writeArguments(LONG to index.toLong(), BOOL to enable) TransferContext.callMethod(rawPtr, MethodBindings.setItemAsCheckablePtr, NIL) } /** * Sets the type of the item at the given [index] to radio button. If `false`, sets the type of * the item to plain text. */ public fun setItemAsRadioCheckable(index: Int, enable: Boolean): Unit { TransferContext.writeArguments(LONG to index.toLong(), BOOL to enable) TransferContext.callMethod(rawPtr, MethodBindings.setItemAsRadioCheckablePtr, NIL) } /** * Sets the [String] tooltip of the item at the given [index]. */ public fun setItemTooltip(index: Int, tooltip: String): Unit { TransferContext.writeArguments(LONG to index.toLong(), STRING to tooltip) TransferContext.callMethod(rawPtr, MethodBindings.setItemTooltipPtr, NIL) } /** * Sets a [Shortcut] for the item at the given [index]. */ @JvmOverloads public fun setItemShortcut( index: Int, shortcut: Shortcut, global: Boolean = false, ): Unit { TransferContext.writeArguments(LONG to index.toLong(), OBJECT to shortcut, BOOL to global) TransferContext.callMethod(rawPtr, MethodBindings.setItemShortcutPtr, NIL) } /** * Sets the horizontal offset of the item at the given [index]. */ public fun setItemIndent(index: Int, indent: Int): Unit { TransferContext.writeArguments(LONG to index.toLong(), LONG to indent.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.setItemIndentPtr, NIL) } /** * Sets the state of a multistate item. See [addMultistateItem] for details. */ public fun setItemMultistate(index: Int, state: Int): Unit { TransferContext.writeArguments(LONG to index.toLong(), LONG to state.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.setItemMultistatePtr, NIL) } /** * Sets the max states of a multistate item. See [addMultistateItem] for details. */ public fun setItemMultistateMax(index: Int, maxStates: Int): Unit { TransferContext.writeArguments(LONG to index.toLong(), LONG to maxStates.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.setItemMultistateMaxPtr, NIL) } /** * Disables the [Shortcut] of the item at the given [index]. */ public fun setItemShortcutDisabled(index: Int, disabled: Boolean): Unit { TransferContext.writeArguments(LONG to index.toLong(), BOOL to disabled) TransferContext.callMethod(rawPtr, MethodBindings.setItemShortcutDisabledPtr, NIL) } /** * Toggles the check state of the item at the given [index]. */ public fun toggleItemChecked(index: Int): Unit { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.toggleItemCheckedPtr, NIL) } /** * Cycle to the next state of a multistate item. See [addMultistateItem] for details. */ public fun toggleItemMultistate(index: Int): Unit { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.toggleItemMultistatePtr, NIL) } /** * Returns the text of the item at the given [index]. */ public fun getItemText(index: Int): String { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemTextPtr, STRING) return (TransferContext.readReturnValue(STRING, false) as String) } /** * Returns item's text base writing direction. */ public fun getItemTextDirection(index: Int): Control.TextDirection { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemTextDirectionPtr, LONG) return Control.TextDirection.from(TransferContext.readReturnValue(LONG) as Long) } /** * Returns item's text language code. */ public fun getItemLanguage(index: Int): String { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemLanguagePtr, STRING) return (TransferContext.readReturnValue(STRING, false) as String) } /** * Returns the icon of the item at the given [index]. */ public fun getItemIcon(index: Int): Texture2D? { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemIconPtr, OBJECT) return (TransferContext.readReturnValue(OBJECT, true) as Texture2D?) } /** * Returns the maximum allowed width of the icon for the item at the given [index]. */ public fun getItemIconMaxWidth(index: Int): Int { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemIconMaxWidthPtr, LONG) return (TransferContext.readReturnValue(LONG, false) as Long).toInt() } /** * Returns a [Color] modulating the item's icon at the given [index]. */ public fun getItemIconModulate(index: Int): Color { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemIconModulatePtr, COLOR) return (TransferContext.readReturnValue(COLOR, false) as Color) } /** * Returns `true` if the item at the given [index] is checked. */ public fun isItemChecked(index: Int): Boolean { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.isItemCheckedPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } /** * Returns the ID of the item at the given [index]. `id` can be manually assigned, while index can * not. */ public fun getItemId(index: Int): Int { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemIdPtr, LONG) return (TransferContext.readReturnValue(LONG, false) as Long).toInt() } /** * Returns the index of the item containing the specified [id]. Index is automatically assigned to * each item by the engine and can not be set manually. */ public fun getItemIndex(id: Int): Int { TransferContext.writeArguments(LONG to id.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemIndexPtr, LONG) return (TransferContext.readReturnValue(LONG, false) as Long).toInt() } /** * Returns the accelerator of the item at the given [index]. An accelerator is a keyboard shortcut * that can be pressed to trigger the menu button even if it's not currently open. The return value * is an integer which is generally a combination of [KeyModifierMask]s and [Key]s using bitwise OR * such as `KEY_MASK_CTRL | KEY_A` ([kbd]Ctrl + A[/kbd]). If no accelerator is defined for the * specified [index], [getItemAccelerator] returns `0` (corresponding to [@GlobalScope.KEY_NONE]). */ public fun getItemAccelerator(index: Int): Key { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemAcceleratorPtr, LONG) return Key.from(TransferContext.readReturnValue(LONG) as Long) } /** * Returns the metadata of the specified item, which might be of any type. You can set it with * [setItemMetadata], which provides a simple way of assigning context data to items. */ public fun getItemMetadata(index: Int): Any? { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemMetadataPtr, ANY) return (TransferContext.readReturnValue(ANY, true) as Any?) } /** * Returns `true` if the item at the given [index] is disabled. When it is disabled it can't be * selected, or its action invoked. * See [setItemDisabled] for more info on how to disable an item. */ public fun isItemDisabled(index: Int): Boolean { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.isItemDisabledPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } /** * Returns the submenu name of the item at the given [index]. See [addSubmenuItem] for more info * on how to add a submenu. */ public fun getItemSubmenu(index: Int): String { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemSubmenuPtr, STRING) return (TransferContext.readReturnValue(STRING, false) as String) } /** * Returns the submenu of the item at the given [index], or `null` if no submenu was added. See * [addSubmenuNodeItem] for more info on how to add a submenu. */ public fun getItemSubmenuNode(index: Int): PopupMenu? { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemSubmenuNodePtr, OBJECT) return (TransferContext.readReturnValue(OBJECT, true) as PopupMenu?) } /** * Returns `true` if the item is a separator. If it is, it will be displayed as a line. See * [addSeparator] for more info on how to add a separator. */ public fun isItemSeparator(index: Int): Boolean { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.isItemSeparatorPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } /** * Returns `true` if the item at the given [index] is checkable in some way, i.e. if it has a * checkbox or radio button. * **Note:** Checkable items just display a checkmark or radio button, but don't have any built-in * checking behavior and must be checked/unchecked manually. */ public fun isItemCheckable(index: Int): Boolean { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.isItemCheckablePtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } /** * Returns `true` if the item at the given [index] has radio button-style checkability. * **Note:** This is purely cosmetic; you must add the logic for checking/unchecking items in * radio groups. */ public fun isItemRadioCheckable(index: Int): Boolean { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.isItemRadioCheckablePtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } /** * Returns `true` if the specified item's shortcut is disabled. */ public fun isItemShortcutDisabled(index: Int): Boolean { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.isItemShortcutDisabledPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } /** * Returns the tooltip associated with the item at the given [index]. */ public fun getItemTooltip(index: Int): String { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemTooltipPtr, STRING) return (TransferContext.readReturnValue(STRING, false) as String) } /** * Returns the [Shortcut] associated with the item at the given [index]. */ public fun getItemShortcut(index: Int): Shortcut? { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemShortcutPtr, OBJECT) return (TransferContext.readReturnValue(OBJECT, true) as Shortcut?) } /** * Returns the horizontal offset of the item at the given [index]. */ public fun getItemIndent(index: Int): Int { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemIndentPtr, LONG) return (TransferContext.readReturnValue(LONG, false) as Long).toInt() } /** * Returns the max states of the item at the given [index]. */ public fun getItemMultistateMax(index: Int): Int { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemMultistateMaxPtr, LONG) return (TransferContext.readReturnValue(LONG, false) as Long).toInt() } /** * Returns the state of the item at the given [index]. */ public fun getItemMultistate(index: Int): Int { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.getItemMultistatePtr, LONG) return (TransferContext.readReturnValue(LONG, false) as Long).toInt() } /** * Sets the currently focused item as the given [index]. * Passing `-1` as the index makes so that no item is focused. */ public fun setFocusedItem(index: Int): Unit { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.setFocusedItemPtr, NIL) } /** * Returns the index of the currently focused item. Returns `-1` if no item is focused. */ public fun getFocusedItem(): Int { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getFocusedItemPtr, LONG) return (TransferContext.readReturnValue(LONG, false) as Long).toInt() } /** * Moves the scroll view to make the item at the given [index] visible. */ public fun scrollToItem(index: Int): Unit { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.scrollToItemPtr, NIL) } /** * Removes the item at the given [index] from the menu. * **Note:** The indices of items after the removed item will be shifted by one. */ public fun removeItem(index: Int): Unit { TransferContext.writeArguments(LONG to index.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.removeItemPtr, NIL) } /** * Adds a separator between items. Separators also occupy an index, which you can set by using the * [id] parameter. * A [label] can optionally be provided, which will appear at the center of the separator. */ @JvmOverloads public fun addSeparator(label: String = "", id: Int = -1): Unit { TransferContext.writeArguments(STRING to label, LONG to id.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.addSeparatorPtr, NIL) } /** * Removes all items from the [PopupMenu]. If [freeSubmenus] is `true`, the submenu nodes are * automatically freed. */ @JvmOverloads public fun clear(freeSubmenus: Boolean = false): Unit { TransferContext.writeArguments(BOOL to freeSubmenus) TransferContext.callMethod(rawPtr, MethodBindings.clearPtr, NIL) } /** * Returns `true` if the menu is bound to the special system menu. */ public fun isSystemMenu(): Boolean { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isSystemMenuPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } public companion object internal object MethodBindings { public val activateItemByEventPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "activate_item_by_event") public val setPreferNativeMenuPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_prefer_native_menu") public val isPreferNativeMenuPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "is_prefer_native_menu") public val isNativeMenuPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "is_native_menu") public val addItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_item") public val addIconItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_icon_item") public val addCheckItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_check_item") public val addIconCheckItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_icon_check_item") public val addRadioCheckItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_radio_check_item") public val addIconRadioCheckItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_icon_radio_check_item") public val addMultistateItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_multistate_item") public val addShortcutPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_shortcut") public val addIconShortcutPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_icon_shortcut") public val addCheckShortcutPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_check_shortcut") public val addIconCheckShortcutPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_icon_check_shortcut") public val addRadioCheckShortcutPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_radio_check_shortcut") public val addIconRadioCheckShortcutPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_icon_radio_check_shortcut") public val addSubmenuItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_submenu_item") public val addSubmenuNodeItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_submenu_node_item") public val setItemTextPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_text") public val setItemTextDirectionPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_text_direction") public val setItemLanguagePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_language") public val setItemIconPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_icon") public val setItemIconMaxWidthPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_icon_max_width") public val setItemIconModulatePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_icon_modulate") public val setItemCheckedPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_checked") public val setItemIdPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_id") public val setItemAcceleratorPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_accelerator") public val setItemMetadataPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_metadata") public val setItemDisabledPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_disabled") public val setItemSubmenuPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_submenu") public val setItemSubmenuNodePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_submenu_node") public val setItemAsSeparatorPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_as_separator") public val setItemAsCheckablePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_as_checkable") public val setItemAsRadioCheckablePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_as_radio_checkable") public val setItemTooltipPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_tooltip") public val setItemShortcutPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_shortcut") public val setItemIndentPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_indent") public val setItemMultistatePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_multistate") public val setItemMultistateMaxPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_multistate_max") public val setItemShortcutDisabledPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_shortcut_disabled") public val toggleItemCheckedPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "toggle_item_checked") public val toggleItemMultistatePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "toggle_item_multistate") public val getItemTextPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_text") public val getItemTextDirectionPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_text_direction") public val getItemLanguagePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_language") public val getItemIconPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_icon") public val getItemIconMaxWidthPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_icon_max_width") public val getItemIconModulatePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_icon_modulate") public val isItemCheckedPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "is_item_checked") public val getItemIdPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_id") public val getItemIndexPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_index") public val getItemAcceleratorPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_accelerator") public val getItemMetadataPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_metadata") public val isItemDisabledPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "is_item_disabled") public val getItemSubmenuPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_submenu") public val getItemSubmenuNodePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_submenu_node") public val isItemSeparatorPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "is_item_separator") public val isItemCheckablePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "is_item_checkable") public val isItemRadioCheckablePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "is_item_radio_checkable") public val isItemShortcutDisabledPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "is_item_shortcut_disabled") public val getItemTooltipPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_tooltip") public val getItemShortcutPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_shortcut") public val getItemIndentPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_indent") public val getItemMultistateMaxPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_multistate_max") public val getItemMultistatePtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_multistate") public val setFocusedItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_focused_item") public val getFocusedItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_focused_item") public val setItemCountPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_item_count") public val getItemCountPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_item_count") public val scrollToItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "scroll_to_item") public val removeItemPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "remove_item") public val addSeparatorPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "add_separator") public val clearPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "clear") public val setHideOnItemSelectionPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_hide_on_item_selection") public val isHideOnItemSelectionPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "is_hide_on_item_selection") public val setHideOnCheckableItemSelectionPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_hide_on_checkable_item_selection") public val isHideOnCheckableItemSelectionPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "is_hide_on_checkable_item_selection") public val setHideOnStateItemSelectionPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_hide_on_state_item_selection") public val isHideOnStateItemSelectionPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "is_hide_on_state_item_selection") public val setSubmenuPopupDelayPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_submenu_popup_delay") public val getSubmenuPopupDelayPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_submenu_popup_delay") public val setAllowSearchPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_allow_search") public val getAllowSearchPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_allow_search") public val isSystemMenuPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "is_system_menu") public val setSystemMenuPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "set_system_menu") public val getSystemMenuPtr: VoidPtr = TypeManager.getMethodBindPtr("PopupMenu", "get_system_menu") } }
64
Kotlin
39
580
fd1af79075e7b918200aba3302496b70c76a2028
52,975
godot-kotlin-jvm
MIT License
src/main/kotlin/org/planx/managing/remote/admin/RabbitmqApiClient.kt
PlanX-Universe
511,478,531
false
null
package org.planx.managing.remote.admin import org.planx.managing.config.http.ApplicationHeaders import org.planx.managing.remote.admin.model.RabbitConnectionModel import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.amqp.RabbitProperties import org.springframework.stereotype.Component import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.util.UriComponentsBuilder import reactor.core.publisher.Mono @Component class RabbitmqApiClient( private val webClientBuilder: WebClient.Builder, @Value("\${spring.rabbitmq.admin.api.url}") private val adminUrl: String, private val rabbitProperties: RabbitProperties ) { private val webClient by lazy { webClientBuilder .baseUrl("http://${adminUrl}") .defaultHeader("Application-Name", ApplicationHeaders.APPLICATION_NAME) .build() } fun retrieveAllConnections(): Mono<RabbitConnectionModel> { val userUriBuilder = UriComponentsBuilder .fromPath("connections") return webClient.get() .uri(userUriBuilder.toUriString()) .headers { it.setBasicAuth(rabbitProperties.username, rabbitProperties.password) } .retrieve() .bodyToMono(RabbitConnectionModel::class.java) } }
0
Kotlin
0
0
66fd9cb343f4ea5dc4c1835a6ccf43dcfe6a91f3
1,378
managing-service
MIT License
src/test/kotlin/no/nav/familie/ef/sak/UnitTestLauncher.kt
blommish
359,371,467
false
{"YAML": 13, "Ignore List": 2, "CODEOWNERS": 1, "Maven POM": 1, "Dockerfile": 1, "Text": 1, "Markdown": 1, "XML": 4, "JSON": 21, "Kotlin": 394, "Java": 1, "GraphQL": 8, "SQL": 43, "Shell": 1}
package no.nav.familie.ef.sak import no.nav.familie.ef.sak.config.ApplicationConfig import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration import org.springframework.boot.builder.SpringApplicationBuilder import org.springframework.context.annotation.Import @SpringBootApplication(exclude = [ErrorMvcAutoConfiguration::class]) @Import(ApplicationConfig::class) class UnitTestLauncher { fun main(args: Array<String>) { val app = SpringApplicationBuilder(ApplicationConfig::class.java) .profiles("local", "mock-oauth") .build() app.run(*args) } }
8
null
2
1
0e850df593c82a910c68c2393e6d2f30fc49eaa7
732
familie-ef-sak
MIT License
src/main/java/no/stunor/origo/eventorapi/model/event/Document.kt
stunor92
763,985,971
false
{"Kotlin": 188540, "Dockerfile": 595}
package no.stunor.origo.eventorapi.model.event import java.io.Serializable data class EventorDocument ( var name: String = "", var url: String = "", var type: String = "" ) : Serializable
0
Kotlin
0
0
452d6357734e43c7c4d55de6a3add15ed0431805
214
OriGo-EventorApi
MIT License
src/main/kotlin/com/chattriggers/ctjs/engine/langs/js/Impl.kt
ChatTriggers
103,319,998
false
null
package com.chattriggers.ctjs.engine.langs.js import com.chattriggers.ctjs.engine.ILoader import com.chattriggers.ctjs.engine.IRegister import com.chattriggers.ctjs.minecraft.objects.display.Display import com.chattriggers.ctjs.minecraft.objects.display.DisplayLine import com.chattriggers.ctjs.minecraft.objects.gui.Gui import com.chattriggers.ctjs.minecraft.objects.keybind.KeyBind import com.chattriggers.ctjs.minecraft.wrappers.Client import net.minecraft.client.settings.KeyBinding import net.minecraft.network.INetHandler import net.minecraft.network.Packet import org.mozilla.javascript.NativeObject /* This file holds the "glue" for this language. Certain classes have triggers inside of them that need to know what loader to use, and that's where these implementations come in. */ object JSRegister : IRegister { override fun getImplementationLoader(): ILoader = JSLoader } class JSGui : Gui() { override fun getLoader(): ILoader = JSLoader } class JSDisplayLine : DisplayLine { constructor(text: String) : super(text) constructor(text: String, config: NativeObject) : super(text, config) override fun getLoader(): ILoader = JSLoader } class JSDisplay : Display { constructor() : super() constructor(config: NativeObject?) : super(config) override fun createDisplayLine(text: String): DisplayLine { return JSDisplayLine(text) } } class JSKeyBind : KeyBind { @JvmOverloads constructor(category: String, key: Int, description: String = "ChatTriggers") : super(category, key, description) constructor(keyBinding: KeyBinding) : super(keyBinding) override fun getLoader(): ILoader = JSLoader } object JSClient : Client() { override fun getKeyBindFromKey(keyCode: Int): KeyBind? { return getMinecraft().gameSettings.keyBindings .firstOrNull { it.keyCode == keyCode } ?.let(::JSKeyBind) } override fun getKeyBindFromKey(keyCode: Int, description: String, category: String): KeyBind { return getMinecraft().gameSettings.keyBindings .firstOrNull { it.keyCode == keyCode } ?.let(::JSKeyBind) ?: JSKeyBind(description, keyCode, category) } override fun getKeyBindFromKey(keyCode: Int, description: String): KeyBind { return getKeyBindFromKey(keyCode, description, "ChatTriggers") } override fun getKeyBindFromDescription(description: String): KeyBind? { return getMinecraft().gameSettings.keyBindings .firstOrNull { it.keyDescription == description } ?.let(::JSKeyBind) } val currentGui = Client.Companion.currentGui val camera = Client.Companion.camera }
8
null
28
96
d2c1f8da6110f54d1dd216c3eadade39fc76052d
2,687
ChatTriggers
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/approvedpremisesapi/integration/ApplicationReportsTest.kt
ministryofjustice
515,276,548
false
null
package uk.gov.justice.digital.hmpps.approvedpremisesapi.integration import org.assertj.core.api.Assertions.assertThat import org.jetbrains.kotlinx.dataframe.DataFrame import org.jetbrains.kotlinx.dataframe.api.ExcessiveColumns import org.jetbrains.kotlinx.dataframe.api.convertTo import org.jetbrains.kotlinx.dataframe.api.toList import org.jetbrains.kotlinx.dataframe.io.readExcel import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.repository.findByIdOrNull import org.springframework.test.web.reactive.server.returnResult import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.ApType import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.AppealDecision import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.AssessmentAcceptance import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.AssessmentRejection import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.Cas1ApplicationUserDetails import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.Gender import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.NewAppeal import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.NewBooking import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.NewPlacementApplication import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.NewReallocation import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.PlacementApplication import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.PlacementApplicationDecision import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.PlacementApplicationDecisionEnvelope import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.PlacementCriteria import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.PlacementDates import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.PlacementRequirements import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.PlacementType import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.ReleaseTypeOption import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.SentenceTypeOption import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.ServiceName import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.SubmitApprovedPremisesApplication import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.SubmitPlacementApplication import uk.gov.justice.digital.hmpps.approvedpremisesapi.api.model.UpdatePlacementApplication import uk.gov.justice.digital.hmpps.approvedpremisesapi.client.ApDeliusContextApiClient import uk.gov.justice.digital.hmpps.approvedpremisesapi.client.ClientResult import uk.gov.justice.digital.hmpps.approvedpremisesapi.factory.CaseDetailFactory import uk.gov.justice.digital.hmpps.approvedpremisesapi.factory.PersonRisksFactory import uk.gov.justice.digital.hmpps.approvedpremisesapi.factory.RegistrationClientResponseFactory import uk.gov.justice.digital.hmpps.approvedpremisesapi.factory.StaffUserTeamMembershipFactory import uk.gov.justice.digital.hmpps.approvedpremisesapi.factory.from import uk.gov.justice.digital.hmpps.approvedpremisesapi.integration.givens.`Given a User` import uk.gov.justice.digital.hmpps.approvedpremisesapi.integration.givens.`Given an AP Area` import uk.gov.justice.digital.hmpps.approvedpremisesapi.integration.givens.`Given an Offender` import uk.gov.justice.digital.hmpps.approvedpremisesapi.integration.httpmocks.APDeliusContext_mockSuccessfulCaseDetailCall import uk.gov.justice.digital.hmpps.approvedpremisesapi.integration.httpmocks.CommunityAPI_mockSuccessfulRegistrationsCall import uk.gov.justice.digital.hmpps.approvedpremisesapi.integration.httpmocks.GovUKBankHolidaysAPI_mockSuccessfullCallWithEmptyResponse import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.AppealEntity import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.AppealRepository import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.ApplicationEntity import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.ApplicationRepository import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.ApprovedPremisesApplicationEntity import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.ApprovedPremisesApplicationJsonSchemaEntity import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.ApprovedPremisesAssessmentEntity import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.ApprovedPremisesAssessmentJsonSchemaEntity import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.ApprovedPremisesPlacementApplicationJsonSchemaEntity import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.AssessmentDecision import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.AssessmentEntity import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.AssessmentRepository import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.BookingEntity import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.BookingRepository import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.UserEntity import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.UserRole import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.Mappa import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.PersonInfoResult import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.RiskStatus import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.RiskTier import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.RiskWithStatus import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.community.OffenderDetailSummary import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.community.RegistrationKeyValue import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.community.Registrations import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.community.StaffUserTeamMembership import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.deliuscontext.CaseDetail import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.deliuscontext.MappaDetail import uk.gov.justice.digital.hmpps.approvedpremisesapi.reporting.model.ApplicationReportRow import uk.gov.justice.digital.hmpps.approvedpremisesapi.service.OffenderService import uk.gov.justice.digital.hmpps.approvedpremisesapi.util.asCaseDetail import java.time.LocalDate import java.time.OffsetDateTime import java.time.Period import java.time.ZonedDateTime import java.util.UUID class ApplicationReportsTest : InitialiseDatabasePerClassTestBase() { @Autowired lateinit var realApplicationRepository: ApplicationRepository @Autowired lateinit var realAssessmentRepository: AssessmentRepository @Autowired lateinit var realBookingRepository: BookingRepository @Autowired lateinit var realAppealRepository: AppealRepository @Autowired lateinit var realOffenderService: OffenderService @Autowired lateinit var apDeliusContextApiClient: ApDeliusContextApiClient lateinit var referrerDetails: Pair<UserEntity, String> lateinit var referrerTeam: StaffUserTeamMembership lateinit var referrerProbationArea: String lateinit var assessorDetails: Pair<UserEntity, String> lateinit var managerDetails: Pair<UserEntity, String> lateinit var workflowManagerDetails: Pair<UserEntity, String> lateinit var matcherDetails: Pair<UserEntity, String> lateinit var appealManagerDetails: Pair<UserEntity, String> lateinit var applicationSchema: ApprovedPremisesApplicationJsonSchemaEntity lateinit var assessmentSchema: ApprovedPremisesAssessmentJsonSchemaEntity lateinit var placementApplicationSchema: ApprovedPremisesPlacementApplicationJsonSchemaEntity lateinit var applicationWithoutAssessment: ApprovedPremisesApplicationEntity lateinit var applicationWithBooking: ApprovedPremisesApplicationEntity lateinit var applicationWithPlacementApplication: ApprovedPremisesApplicationEntity lateinit var applicationWithReallocatedCompleteAssessments: ApprovedPremisesApplicationEntity lateinit var applicationShortNotice: ApprovedPremisesApplicationEntity lateinit var applicationWithAcceptedAppeal: ApprovedPremisesApplicationEntity lateinit var applicationWithRejectedAppeal: ApprovedPremisesApplicationEntity lateinit var applicationWithMultipleAppeals: ApprovedPremisesApplicationEntity lateinit var applicationWithMultipleAssessments: ApprovedPremisesApplicationEntity companion object Constants { const val AUTHORISED_DURATION_DAYS: Int = 12 } @BeforeAll fun setup() { GovUKBankHolidaysAPI_mockSuccessfullCallWithEmptyResponse() referrerTeam = StaffUserTeamMembershipFactory().produce() referrerProbationArea = "Referrer probation area" referrerDetails = `Given a User`(staffUserDetailsConfigBlock = { withTeams( listOf( referrerTeam, ), ) withProbationAreaDescription( referrerProbationArea, ) },) assessorDetails = `Given a User`( roles = listOf(UserRole.CAS1_ASSESSOR), probationRegion = probationRegionEntityFactory.produceAndPersist { withYieldedApArea { `Given an AP Area`(name = "Wales") } }, ) managerDetails = `Given a User`(roles = listOf(UserRole.CAS1_MANAGER)) workflowManagerDetails = `Given a User`(roles = listOf(UserRole.CAS1_WORKFLOW_MANAGER)) matcherDetails = `Given a User`(roles = listOf(UserRole.CAS1_MATCHER)) appealManagerDetails = `Given a User`(roles = listOf(UserRole.CAS1_APPEALS_MANAGER)) applicationSchema = approvedPremisesApplicationJsonSchemaEntityFactory.produceAndPersist { withAddedAt(OffsetDateTime.now()) withId(UUID.randomUUID()) withPermissiveSchema() } assessmentSchema = approvedPremisesAssessmentJsonSchemaEntityFactory.produceAndPersist { withAddedAt(OffsetDateTime.now()) withId(UUID.randomUUID()) withPermissiveSchema() } placementApplicationSchema = approvedPremisesPlacementApplicationJsonSchemaEntityFactory.produceAndPersist { withPermissiveSchema() } applicationWithoutAssessment = createApplication("applicationWithoutAssessment") val applicationWithBookingArgs = createApplicationWithBooking("applicationWithBooking") applicationWithBooking = applicationWithBookingArgs.first applicationWithPlacementApplication = createApplicationWithCompletedAssessment("applicationWithPlacementApplication") createAndAcceptPlacementApplication(applicationWithPlacementApplication) createBookingForApplication(applicationWithPlacementApplication) applicationWithMultipleAssessments = createApplication("applicationWithMultipleAssessments") reallocateAssessment(applicationWithMultipleAssessments) acceptAssessmentForApplication(applicationWithMultipleAssessments) applicationWithReallocatedCompleteAssessments = createApplication("applicationWithReallocatedCompleteAssessments") reallocateAssessment(applicationWithReallocatedCompleteAssessments) acceptAssessmentForApplication(applicationWithReallocatedCompleteAssessments) applicationShortNotice = createApplication("applicationShortNotice", shortNotice = true) acceptAssessmentForApplication(applicationShortNotice, shortNotice = true) applicationWithAcceptedAppeal = createApplication("applicationWithAcceptedAppeal") val assessmentToAppealAccepted = rejectAssessmentForApplication(applicationWithAcceptedAppeal) acceptAppealForAssessment(assessmentToAppealAccepted) applicationWithRejectedAppeal = createApplication("applicationWithRejectedAppeal") val assessmentToAppealRejected = rejectAssessmentForApplication(applicationWithRejectedAppeal) rejectAppealForAssessment(assessmentToAppealRejected) applicationWithMultipleAppeals = createApplication("applicationWithMultipleAppeals") val assessmentToAppealMultiple = rejectAssessmentForApplication(applicationWithMultipleAppeals) rejectAppealForAssessment(assessmentToAppealMultiple) acceptAppealForAssessment(assessmentToAppealMultiple) } @Test fun `Get application report returns 403 Forbidden if user does not have all regions access`() { `Given a User` { _, jwt -> webTestClient.get() .uri("/cas1/reports/applications?year=2023&month=4") .header("Authorization", "Bearer $jwt") .header("X-Service-Name", ServiceName.approvedPremises.value) .exchange() .expectStatus() .isForbidden } } @Test fun `Get application report returns 400 if month is provided and not within 1-12`() { `Given a User`(roles = listOf(UserRole.CAS1_REPORT_VIEWER)) { _, jwt -> webTestClient.get() .uri("/cas1/reports/applications?year=2023&month=-1") .header("Authorization", "Bearer $jwt") .header("X-Service-Name", ServiceName.approvedPremises.value) .exchange() .expectStatus() .isBadRequest .expectBody() .jsonPath("$.detail").isEqualTo("month must be between 1 and 12") } } @Test fun `Get application report returns OK with correct applications`() { `Given a User`(roles = listOf(UserRole.CAS1_REPORT_VIEWER)) { userEntity, jwt -> val now = LocalDate.now() val year = now.year.toString() val month = now.monthValue.toString() webTestClient.get() .uri("/cas1/reports/applications?year=$year&month=$month") .header("Authorization", "Bearer $jwt") .header("X-Service-Name", ServiceName.approvedPremises.value) .exchange() .expectStatus() .isOk .expectHeader().valuesMatch( "content-disposition", "attachment; filename=\"applications-$year-${month.padStart(2, '0')}-[0-9_]+.xlsx\"", ) .expectBody() .consumeWith { val actual = DataFrame .readExcel(it.responseBody!!.inputStream()) .convertTo<ApplicationReportRow>(ExcessiveColumns.Remove) .toList() assertThat(actual.size).isEqualTo(9) assertApplicationRowHasCorrectData(actual, applicationWithoutAssessment.id, userEntity, ApplicationFacets(isAssessed = false, isAccepted = false)) assertApplicationRowHasCorrectData(actual, applicationWithBooking.id, userEntity) assertApplicationRowHasCorrectData(actual, applicationWithPlacementApplication.id, userEntity, ApplicationFacets(hasPlacementApplication = true)) assertApplicationRowHasCorrectData(actual, applicationWithReallocatedCompleteAssessments.id, userEntity) assertApplicationRowHasCorrectData(actual, applicationWithMultipleAssessments.id, userEntity) assertApplicationRowHasCorrectData(actual, applicationShortNotice.id, userEntity, ApplicationFacets(isShortNotice = true)) assertApplicationRowHasCorrectData(actual, applicationWithAcceptedAppeal.id, userEntity, ApplicationFacets(hasAppeal = true, isAccepted = false)) assertApplicationRowHasCorrectData(actual, applicationWithRejectedAppeal.id, userEntity, ApplicationFacets(hasAppeal = true, isAccepted = false)) assertApplicationRowHasCorrectData(actual, applicationWithMultipleAppeals.id, userEntity, ApplicationFacets(hasAppeal = true, isAccepted = false)) } } } enum class ReportType { Applications, } data class ApplicationFacets( val isAssessed: Boolean = true, val isAccepted: Boolean = true, val hasPlacementApplication: Boolean = false, val hasAppeal: Boolean = false, val reportType: ReportType = ReportType.Applications, val isShortNotice: Boolean = false, ) private fun ApprovedPremisesApplicationEntity.getAppropriateAssessment(hasAppeal: Boolean): AssessmentEntity? = when (hasAppeal) { // By the time the assertions are made, a newer assessment will have automatically been made for accepted appeals. // To correctly assert on accepted appeals, the assessment that should be used is the latest one that was *rejected*, // not the latest one of any status. true -> this.assessments.filter { it.decision == AssessmentDecision.REJECTED }.maxByOrNull { it.createdAt } false -> this.getLatestAssessment() } private fun assertApplicationRowHasCorrectData( report: List<ApplicationReportRow>, applicationId: UUID, userEntity: UserEntity, applicationFacets: ApplicationFacets = ApplicationFacets(), ) { val reportRow = report.find { it.id == applicationId.toString() }!! val application = realApplicationRepository.findByIdOrNull(applicationId) as ApprovedPremisesApplicationEntity val assessment = application.getAppropriateAssessment(applicationFacets.hasAppeal)!! val offenderDetailSummary = getOffenderDetailForApplication(application, userEntity.deliusUsername) val caseDetail = getCaseDetailForApplication(application) val (referrerEntity, _) = referrerDetails assertThat(reportRow.crn).isEqualTo(application.crn) assertThat(reportRow.tier).isEqualTo("B") assertThat(reportRow.lastAllocatedToAssessorDate).isEqualTo(assessment.allocatedAt!!.toLocalDate()) if (applicationFacets.isAssessed) { assertThat(assessment).isNotNull assertThat(assessment.submittedAt).isNotNull assertThat(reportRow.applicationAssessedDate).isEqualTo(assessment.submittedAt!!.toLocalDate()) assertThat(reportRow.assessorCru).isEqualTo("Wales") if (!applicationFacets.hasAppeal) { assertThat(reportRow.assessmentDecision).isEqualTo(assessment.decision.toString()) } assertThat(reportRow.assessmentDecisionRationale).isEqualTo(assessment.rejectionRationale) if (applicationFacets.isShortNotice) { assertThat(reportRow.applicantReasonForLateApplication).isEqualTo("theReasonForShortNoticeReason") assertThat(reportRow.applicantReasonForLateApplicationDetail).isEqualTo("theReasonForShortNoticeOther") assertThat(reportRow.assessorAgreeWithShortNoticeReason).isEqualTo("yes") assertThat(reportRow.assessorReasonForLateApplication).isEqualTo("thisIsAgreeWithShortNoticeReasonComments") assertThat(reportRow.assessorReasonForLateApplicationDetail).isEqualTo("thisIsTheReasonForLateApplication") } else { assertThat(reportRow.applicantReasonForLateApplication).isNull() assertThat(reportRow.applicantReasonForLateApplicationDetail).isNull() assertThat(reportRow.assessorAgreeWithShortNoticeReason).isNull() assertThat(reportRow.assessorReasonForLateApplication).isNull() assertThat(reportRow.assessorReasonForLateApplicationDetail).isNull() } } assertThat(reportRow.ageInYears).isEqualTo(Period.between(offenderDetailSummary.dateOfBirth, LocalDate.now()).years) assertThat(reportRow.gender).isEqualTo(offenderDetailSummary.gender) assertThat(reportRow.mappa).isEqualTo(application.riskRatings!!.mappa.value!!.level) assertThat(reportRow.offenceId).isEqualTo(application.offenceId) assertThat(reportRow.noms).isEqualTo(application.nomsNumber) assertThat(reportRow.releaseType).isEqualTo(application.releaseType) assertThat(reportRow.applicationSubmissionDate).isEqualTo(application.submittedAt!!.toLocalDate()) assertThat(reportRow.targetLocation).isEqualTo(application.targetLocation) assertThat(reportRow.applicationWithdrawalReason).isEqualTo(application.withdrawalReason) assertThat(reportRow.referrerUsername).isEqualTo(referrerEntity.deliusUsername) assertThat(reportRow.referralLdu).isEqualTo(caseDetail.case.manager.team.ldu.name) assertThat(reportRow.referralRegion).isEqualTo(referrerProbationArea) assertThat(reportRow.referralTeam).isEqualTo(caseDetail.case.manager.team.name) val arrivalDate = application.arrivalDate?.toLocalDate() assertThat(reportRow.expectedArrivalDate).isEqualTo(arrivalDate) if (applicationFacets.isAssessed && applicationFacets.isAccepted && arrivalDate != null) { assertThat(reportRow.expectedDepartureDate).isEqualTo(arrivalDate?.plusDays(AUTHORISED_DURATION_DAYS.toLong())) } else { assertThat(reportRow.expectedDepartureDate).isNull() } if (applicationFacets.hasAppeal) { val appeals = realAppealRepository.findAllByAssessmentId(assessment.id) val latestAppeal = appeals.maxByOrNull { it.createdAt }!! assertThat(reportRow.assessmentAppealCount).isEqualTo(appeals.size) assertThat(reportRow.lastAssessmentAppealedDecision).isEqualTo(latestAppeal.decision) assertThat(reportRow.lastAssessmentAppealedDate).isEqualTo(latestAppeal.appealDate) assertThat(reportRow.assessmentAppealedFromStatus).isEqualTo(assessment.decision.toString()) assertThat(reportRow.assessmentDecision).isEqualTo(latestAppeal.decision) } } private fun getOffenderDetailForApplication(application: ApplicationEntity, deliusUsername: String): OffenderDetailSummary { return when (val personInfo = realOffenderService.getPersonInfoResult(application.crn, deliusUsername, true)) { is PersonInfoResult.Success.Full -> personInfo.offenderDetailSummary else -> throw Exception("No offender found for CRN ${application.crn}") } } private fun getCaseDetailForApplication(application: ApplicationEntity): CaseDetail { return when (val caseDetailResult = apDeliusContextApiClient.getCaseDetail(application.crn)) { is ClientResult.Success -> caseDetailResult.body is ClientResult.Failure -> caseDetailResult.throwException() } } private fun createApplication(crn: String, withArrivalDate: Boolean = true, shortNotice: Boolean = false): ApprovedPremisesApplicationEntity { return createAndSubmitApplication(ApType.normal, crn, withArrivalDate, shortNotice) } private fun createApplicationWithCompletedAssessment(crn: String, withArrivalDate: Boolean = true): ApprovedPremisesApplicationEntity { val application = createAndSubmitApplication(ApType.normal, crn, withArrivalDate) acceptAssessmentForApplication(application) return application } private fun createApplicationWithBooking(crn: String): Pair<ApprovedPremisesApplicationEntity, BookingEntity> { val application = createApplicationWithCompletedAssessment(crn) val booking = createBookingForApplication(application) return Pair(application, booking) } private fun createAndSubmitApplication(apType: ApType, crn: String, withArrivalDate: Boolean = true, shortNotice: Boolean = false): ApprovedPremisesApplicationEntity { val (referrer, jwt) = referrerDetails val (offenderDetails, _) = `Given an Offender`( offenderDetailsConfigBlock = { withCrn(crn) }, ) CommunityAPI_mockSuccessfulRegistrationsCall( offenderDetails.otherIds.crn, Registrations( registrations = listOf( RegistrationClientResponseFactory() .withType(RegistrationKeyValue(code = "MAPP", description = "MAPPA")) .withRegisterCategory(RegistrationKeyValue(code = "M2", description = "M2")) .withRegisterLevel(RegistrationKeyValue(code = "M2", description = "M2")) .withStartDate(LocalDate.parse("2022-09-06")) .produce(), ), ), ) APDeliusContext_mockSuccessfulCaseDetailCall( offenderDetails.otherIds.crn, CaseDetailFactory() .from(offenderDetails.asCaseDetail()) .withMappaDetail( MappaDetail( 2, "M2", 2, "M2", LocalDate.parse("2022-09-06"), ZonedDateTime.parse("2022-09-06T00:00:00Z"), ), ) .produce(), ) val basicInformationJson = mapOf( "basic-information" to listOfNotNull( "sentence-type" to mapOf("sentenceType" to "Some Sentence Type"), if (shortNotice) { "reason-for-short-notice" to mapOf( "reason" to "theReasonForShortNoticeReason", "other" to "theReasonForShortNoticeOther", ) } else { null }, ).toMap(), ) val application = approvedPremisesApplicationEntityFactory.produceAndPersist { withCreatedByUser(referrer) withCrn(offenderDetails.otherIds.crn) withNomsNumber(offenderDetails.otherIds.nomsNumber!!) withApplicationSchema(applicationSchema) withData(objectMapper.writeValueAsString(basicInformationJson)) withRiskRatings( PersonRisksFactory() .withTier( RiskWithStatus( status = RiskStatus.Retrieved, value = RiskTier( level = "B", lastUpdated = LocalDate.now(), ), ), ) .withMappa( RiskWithStatus( status = RiskStatus.Retrieved, value = Mappa( level = "CAT M2/LEVEL M2", lastUpdated = LocalDate.now(), ), ), ).produce(), ) } val arrivalDate = if (withArrivalDate) { LocalDate.now().plusMonths(8) } else { null } webTestClient.post() .uri("/applications/${application.id}/submission") .header("Authorization", "Bearer $jwt") .bodyValue( SubmitApprovedPremisesApplication( translatedDocument = {}, isPipeApplication = apType == ApType.pipe, isWomensApplication = false, isEmergencyApplication = false, isEsapApplication = apType == ApType.esap, targetLocation = "SW1A 1AA", releaseType = ReleaseTypeOption.licence, type = "CAS1", sentenceType = SentenceTypeOption.nonStatutory, arrivalDate = arrivalDate, applicantUserDetails = Cas1ApplicationUserDetails("applicantName", "applicantEmail", "applicationPhone"), caseManagerIsNotApplicant = false, ), ) .exchange() .expectStatus() .isOk return realApplicationRepository.findByIdOrNull(application.id) as ApprovedPremisesApplicationEntity } private fun acceptAssessmentForApplication(application: ApprovedPremisesApplicationEntity, shortNotice: Boolean = false): ApprovedPremisesAssessmentEntity { val (assessorEntity, jwt) = assessorDetails val assessment = realAssessmentRepository.findByApplication_IdAndReallocatedAtNull(application.id)!! val postcodeDistrict = postCodeDistrictFactory.produceAndPersist() assessment.data = if (shortNotice) { """{ "suitability-assessment": { "application-timeliness": { "agreeWithShortNoticeReason": "yes", "agreeWithShortNoticeReasonComments": "thisIsAgreeWithShortNoticeReasonComments", "reasonForLateApplication": "thisIsTheReasonForLateApplication" } } }""" } else { "{ }" } assessment.allocatedToUser = assessorEntity realAssessmentRepository.save(assessment) val essentialCriteria = listOf(PlacementCriteria.isArsonSuitable, PlacementCriteria.isESAP) val desirableCriteria = listOf(PlacementCriteria.isRecoveryFocussed, PlacementCriteria.acceptsSexOffenders) val placementDates = if (application.arrivalDate != null) { PlacementDates( expectedArrival = application.arrivalDate!!.toLocalDate(), duration = AUTHORISED_DURATION_DAYS, ) } else { null } val placementRequirements = PlacementRequirements( gender = Gender.male, type = ApType.normal, location = postcodeDistrict.outcode, radius = 50, essentialCriteria = essentialCriteria, desirableCriteria = desirableCriteria, ) webTestClient.post() .uri("/assessments/${assessment.id}/acceptance") .header("Authorization", "Bearer $jwt") .bodyValue(AssessmentAcceptance(document = mapOf("document" to "value"), requirements = placementRequirements, placementDates = placementDates)) .exchange() .expectStatus() .isOk return realAssessmentRepository.findByIdOrNull(assessment.id) as ApprovedPremisesAssessmentEntity } private fun rejectAssessmentForApplication(application: ApprovedPremisesApplicationEntity): ApprovedPremisesAssessmentEntity { val (assessorEntity, jwt) = assessorDetails val assessment = realAssessmentRepository.findByApplication_IdAndReallocatedAtNull(application.id)!! assessment.data = "{}" assessment.allocatedToUser = assessorEntity realAssessmentRepository.save(assessment) webTestClient.post() .uri("/assessments/${assessment.id}/rejection") .header("Authorization", "Bearer $jwt") .bodyValue( AssessmentRejection( document = mapOf("document" to "value"), rejectionRationale = "Some reason", ), ) .exchange() .expectStatus() .isOk return realAssessmentRepository.findByIdOrNull(assessment.id) as ApprovedPremisesAssessmentEntity } private fun createBookingForApplication(application: ApprovedPremisesApplicationEntity): BookingEntity { val (_, jwt) = matcherDetails val premises = approvedPremisesEntityFactory.produceAndPersist { withYieldedLocalAuthorityArea { localAuthorityEntityFactory.produceAndPersist() } withYieldedProbationRegion { probationRegionEntityFactory.produceAndPersist { withYieldedApArea { `Given an AP Area`() } } } } val room = roomEntityFactory.produceAndPersist { withPremises(premises) } val bed = bedEntityFactory.produceAndPersist { withRoom(room) } webTestClient.post() .uri("/premises/${premises.id}/bookings") .header("Authorization", "Bearer $jwt") .bodyValue( NewBooking( crn = application.crn, arrivalDate = LocalDate.parse("2022-08-12"), departureDate = LocalDate.parse("2022-08-30"), serviceName = ServiceName.approvedPremises, bedId = bed.id, eventNumber = "eventNumber", ), ) .exchange() .expectStatus() .isOk return realBookingRepository.findAllByCrn(application.crn).maxByOrNull { it.createdAt }!! } private fun reallocateAssessment(application: ApprovedPremisesApplicationEntity) { val (_, jwt) = workflowManagerDetails val (assigneeUser, _) = `Given a User`(roles = listOf(UserRole.CAS1_ASSESSOR)) val existingAssessment = application.getLatestAssessment()!! webTestClient.post() .uri("/tasks/assessment/${existingAssessment.id}/allocations") .header("Authorization", "Bearer $jwt") .header("X-Service-Name", ServiceName.approvedPremises.value) .bodyValue( NewReallocation( userId = assigneeUser.id, ), ) .exchange() .expectStatus() .isCreated } private fun createAndAcceptPlacementApplication(application: ApprovedPremisesApplicationEntity) { val (_, jwt) = assessorDetails val rawResult = webTestClient.post() .uri("/placement-applications") .header("Authorization", "Bearer $jwt") .bodyValue( NewPlacementApplication( applicationId = application.id, ), ) .exchange() .expectStatus() .isOk .returnResult<String>() .responseBody .blockFirst() val placementApplication = objectMapper.readValue(rawResult, PlacementApplication::class.java) webTestClient.put() .uri("/placement-applications/${placementApplication.id}") .header("Authorization", "Bearer $jwt") .bodyValue( UpdatePlacementApplication( data = mapOf("request-a-placement" to mapOf("decision-to-release" to mapOf("decisionToReleaseDate" to "2023-11-11"))), ), ) .exchange() .expectStatus() .isOk val placementDates = listOf( PlacementDates( expectedArrival = LocalDate.now(), duration = AUTHORISED_DURATION_DAYS, ), ) webTestClient.post() .uri("/placement-applications/${placementApplication.id}/submission") .header("Authorization", "Bearer $jwt") .bodyValue( SubmitPlacementApplication( translatedDocument = mapOf("thingId" to 123), placementType = PlacementType.additionalPlacement, placementDates = placementDates, ), ) .exchange() .expectStatus() .isOk val (_, matcherJwt) = matcherDetails webTestClient.post() .uri("/placement-applications/${placementApplication.id}/decision") .header("Authorization", "Bearer $matcherJwt") .bodyValue( PlacementApplicationDecisionEnvelope( decision = PlacementApplicationDecision.accepted, summaryOfChanges = "ChangeSummary", decisionSummary = "DecisionSummary", ), ) .exchange() .expectStatus() .isOk } private fun acceptAppealForAssessment(assessment: ApprovedPremisesAssessmentEntity): AppealEntity { val (_, jwt) = appealManagerDetails webTestClient.post() .uri("/applications/${assessment.application.id}/appeals") .header("Authorization", "Bearer $jwt") .bodyValue( NewAppeal( appealDate = LocalDate.now(), appealDetail = "Some details about the appeal", decision = AppealDecision.accepted, decisionDetail = "Some details about why the appeal was accepted", ), ) .exchange() .expectStatus() .isCreated return realAppealRepository.findAllByAssessmentId(assessment.id).maxByOrNull { it.createdAt }!! } private fun rejectAppealForAssessment(assessment: ApprovedPremisesAssessmentEntity): AppealEntity { val (_, jwt) = appealManagerDetails webTestClient.post() .uri("/applications/${assessment.application.id}/appeals") .header("Authorization", "Bearer $jwt") .bodyValue( NewAppeal( appealDate = LocalDate.now(), appealDetail = "Some details about the appeal", decision = AppealDecision.rejected, decisionDetail = "Some details about why the appeal was rejected", ), ) .exchange() .expectStatus() .isCreated return realAppealRepository.findAllByAssessmentId(assessment.id).maxByOrNull { it.createdAt }!! } }
32
null
2
5
5b02281acd56772dc5d587f8cd4678929a191ac0
34,524
hmpps-approved-premises-api
MIT License
app/infrastructure/src/main/kotlin/net/averak/gsync/infrastructure/mybatis/type_handler/LocalDateTimeTypeHandler.kt
averak
697,429,765
false
{"Kotlin": 142151, "Groovy": 109549, "Java": 4418, "Makefile": 1696, "Dockerfile": 287, "Shell": 246}
package net.averak.gsync.infrastructure.mybatis.type_handler import org.apache.ibatis.type.BaseTypeHandler import org.apache.ibatis.type.JdbcType import org.apache.ibatis.type.MappedTypes import java.sql.CallableStatement import java.sql.PreparedStatement import java.sql.ResultSet import java.sql.Timestamp import java.time.LocalDateTime @MappedTypes(LocalDateTime::class) class LocalDateTimeTypeHandler : BaseTypeHandler<LocalDateTime>() { override fun setNonNullParameter(ps: PreparedStatement, i: Int, parameter: LocalDateTime, jdbcType: JdbcType) { ps.setTimestamp(i, Timestamp.valueOf(parameter)) } override fun getNullableResult(rs: ResultSet, columnName: String): LocalDateTime? { val timestamp = rs.getTimestamp(columnName) return timestamp?.toLocalDateTime() } override fun getNullableResult(rs: ResultSet, columnIndex: Int): LocalDateTime? { val timestamp = rs.getTimestamp(columnIndex) return timestamp?.toLocalDateTime() } override fun getNullableResult(cs: CallableStatement, columnIndex: Int): LocalDateTime? { val timestamp = cs.getTimestamp(columnIndex) return timestamp?.toLocalDateTime() } }
23
Kotlin
0
1
504d350a5af2726693c3d154340c0a4f4b5db37b
1,205
gsync
MIT License
app/src/main/java/ru/alexmaryin/spacextimes_rx/data/model/parts/Cargo.kt
alexmaryin
324,776,487
false
null
package ru.alexmaryin.spacextimes_rx.data.model.parts import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Cargo( @Json(name = "solar_array") val solarArray: Int, @Json(name = "unpressurized_cargo") val unpressurized: Boolean )
1
Kotlin
2
1
556bcd18d9c60c8922055a11976056cad812856a
297
spacextimes
Apache License 2.0
src/main/kotlin/edu/csh/chase/kgeojson/models/Polygon.kt
chaseberry
43,023,920
false
null
package edu.csh.chase.kgeojson.models class Polygon(val ring: Line, val holes: Array<Line>)
0
Kotlin
0
1
af5a02485241acf2717065957b28cccd3bfeb9d9
92
KGeoJson
Apache License 2.0
src/main/kotlin/kotlin/internal/InlineOnly.kt
lppedd
208,670,987
false
null
package kotlin.internal /** * Specifies that this function should not be called directly without inlining. */ @Target( AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, ) @Retention(AnnotationRetention.BINARY) internal annotation class InlineOnly
34
null
19
333
5d55768a47a31a10147e7d69f2be261d028d1b85
338
idea-conventional-commit
MIT License
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/appsync/AppsyncFunctionProps.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.appsync import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.String import kotlin.Unit /** * the CDK properties for AppSync Functions. * * Example: * * ``` * GraphqlApi api; * AppsyncFunction appsyncFunction = AppsyncFunction.Builder.create(this, "function") * .name("appsync_function") * .api(api) * .dataSource(api.addNoneDataSource("none")) * .requestMappingTemplate(MappingTemplate.fromFile("request.vtl")) * .responseMappingTemplate(MappingTemplate.fromFile("response.vtl")) * .build(); * ``` */ public interface AppsyncFunctionProps : BaseAppsyncFunctionProps { /** * the GraphQL Api linked to this AppSync Function. */ public fun api(): IGraphqlApi /** * the data source linked to this AppSync Function. */ public fun dataSource(): BaseDataSource /** * A builder for [AppsyncFunctionProps] */ @CdkDslMarker public interface Builder { /** * @param api the GraphQL Api linked to this AppSync Function. */ public fun api(api: IGraphqlApi) /** * @param code The function code. */ public fun code(code: Code) /** * @param dataSource the data source linked to this AppSync Function. */ public fun dataSource(dataSource: BaseDataSource) /** * @param description the description for this AppSync Function. */ public fun description(description: String) /** * @param name the name of the AppSync Function. */ public fun name(name: String) /** * @param requestMappingTemplate the request mapping template for the AppSync Function. */ public fun requestMappingTemplate(requestMappingTemplate: MappingTemplate) /** * @param responseMappingTemplate the response mapping template for the AppSync Function. */ public fun responseMappingTemplate(responseMappingTemplate: MappingTemplate) /** * @param runtime The functions runtime. */ public fun runtime(runtime: FunctionRuntime) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.appsync.AppsyncFunctionProps.Builder = software.amazon.awscdk.services.appsync.AppsyncFunctionProps.builder() /** * @param api the GraphQL Api linked to this AppSync Function. */ override fun api(api: IGraphqlApi) { cdkBuilder.api(api.let(IGraphqlApi.Companion::unwrap)) } /** * @param code The function code. */ override fun code(code: Code) { cdkBuilder.code(code.let(Code.Companion::unwrap)) } /** * @param dataSource the data source linked to this AppSync Function. */ override fun dataSource(dataSource: BaseDataSource) { cdkBuilder.dataSource(dataSource.let(BaseDataSource.Companion::unwrap)) } /** * @param description the description for this AppSync Function. */ override fun description(description: String) { cdkBuilder.description(description) } /** * @param name the name of the AppSync Function. */ override fun name(name: String) { cdkBuilder.name(name) } /** * @param requestMappingTemplate the request mapping template for the AppSync Function. */ override fun requestMappingTemplate(requestMappingTemplate: MappingTemplate) { cdkBuilder.requestMappingTemplate(requestMappingTemplate.let(MappingTemplate.Companion::unwrap)) } /** * @param responseMappingTemplate the response mapping template for the AppSync Function. */ override fun responseMappingTemplate(responseMappingTemplate: MappingTemplate) { cdkBuilder.responseMappingTemplate(responseMappingTemplate.let(MappingTemplate.Companion::unwrap)) } /** * @param runtime The functions runtime. */ override fun runtime(runtime: FunctionRuntime) { cdkBuilder.runtime(runtime.let(FunctionRuntime.Companion::unwrap)) } public fun build(): software.amazon.awscdk.services.appsync.AppsyncFunctionProps = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.appsync.AppsyncFunctionProps, ) : CdkObject(cdkObject), AppsyncFunctionProps { /** * the GraphQL Api linked to this AppSync Function. */ override fun api(): IGraphqlApi = unwrap(this).getApi().let(IGraphqlApi::wrap) /** * The function code. * * Default: - no code is used */ override fun code(): Code? = unwrap(this).getCode()?.let(Code::wrap) /** * the data source linked to this AppSync Function. */ override fun dataSource(): BaseDataSource = unwrap(this).getDataSource().let(BaseDataSource::wrap) /** * the description for this AppSync Function. * * Default: - no description */ override fun description(): String? = unwrap(this).getDescription() /** * the name of the AppSync Function. */ override fun name(): String = unwrap(this).getName() /** * the request mapping template for the AppSync Function. * * Default: - no request mapping template */ override fun requestMappingTemplate(): MappingTemplate? = unwrap(this).getRequestMappingTemplate()?.let(MappingTemplate::wrap) /** * the response mapping template for the AppSync Function. * * Default: - no response mapping template */ override fun responseMappingTemplate(): MappingTemplate? = unwrap(this).getResponseMappingTemplate()?.let(MappingTemplate::wrap) /** * The functions runtime. * * Default: - no function runtime, VTL mapping templates used */ override fun runtime(): FunctionRuntime? = unwrap(this).getRuntime()?.let(FunctionRuntime::wrap) } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): AppsyncFunctionProps { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.appsync.AppsyncFunctionProps): AppsyncFunctionProps = CdkObjectWrappers.wrap(cdkObject) as? AppsyncFunctionProps ?: Wrapper(cdkObject) internal fun unwrap(wrapped: AppsyncFunctionProps): software.amazon.awscdk.services.appsync.AppsyncFunctionProps = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.appsync.AppsyncFunctionProps } }
4
null
0
4
9bf6f9403f8b24b070d23a2f895811be72f5d828
6,749
kotlin-cdk-wrapper
Apache License 2.0
model-api-gen-gradle-test/src/test/kotlin/org/modelix/modelql/typed/TypedModelQLTest.kt
modelix
533,211,353
false
{"Kotlin": 1864496, "JetBrains MPS": 345438, "TypeScript": 46778, "Java": 25036, "Gherkin": 7693, "JavaScript": 4774, "CSS": 2812, "Shell": 1922, "Dockerfile": 314, "Procfile": 76}
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.modelix.modelql.typed import io.ktor.client.HttpClient import io.ktor.server.testing.testApplication import jetbrains.mps.baseLanguage.C_ClassConcept import jetbrains.mps.baseLanguage.C_IntegerType import jetbrains.mps.baseLanguage.C_PlusExpression import jetbrains.mps.baseLanguage.C_PublicVisibility import jetbrains.mps.baseLanguage.C_ReturnStatement import jetbrains.mps.baseLanguage.C_StaticMethodDeclaration import jetbrains.mps.baseLanguage.C_VariableReference import jetbrains.mps.baseLanguage.ClassConcept import jetbrains.mps.baseLanguage.StaticMethodDeclaration import org.modelix.apigen.test.ApigenTestLanguages import org.modelix.metamodel.typed import org.modelix.model.api.IBranch import org.modelix.model.api.PBranch import org.modelix.model.api.getRootNode import org.modelix.model.api.resolve import org.modelix.model.client.IdGenerator import org.modelix.model.lazy.CLTree import org.modelix.model.lazy.ObjectStoreCache import org.modelix.model.persistent.MapBaseStore import org.modelix.model.server.light.LightModelServer import org.modelix.modelql.client.ModelQLClient import org.modelix.modelql.core.count import org.modelix.modelql.core.filter import org.modelix.modelql.core.map import org.modelix.modelql.core.toList import org.modelix.modelql.core.toSet import org.modelix.modelql.core.zip import org.modelix.modelql.gen.jetbrains.mps.baseLanguage.member import org.modelix.modelql.gen.jetbrains.mps.baseLanguage.parameter import org.modelix.modelql.gen.jetbrains.mps.baseLanguage.variableDeclaration import org.modelix.modelql.gen.jetbrains.mps.baseLanguage.visibility import org.modelix.modelql.gen.jetbrains.mps.lang.core.name import org.modelix.modelql.untyped.children import org.modelix.modelql.untyped.conceptReference import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals class TypedModelQLTest { private lateinit var branch: IBranch private fun runTest(block: suspend (HttpClient) -> Unit) = testApplication { application { LightModelServer(80, branch.getRootNode()).apply { installHandlers() } } val httpClient = createClient { } block(httpClient) } @BeforeTest fun setup() { ApigenTestLanguages.registerAll() val tree = CLTree(ObjectStoreCache(MapBaseStore())) branch = PBranch(tree, IdGenerator.getInstance(1)) val rootNode = branch.getRootNode() branch.runWrite { val cls1 = rootNode.addNewChild("classes", -1, C_ClassConcept.untyped()).typed<ClassConcept>() cls1.apply { name = "Math" member.addNew(C_StaticMethodDeclaration).apply { name = "plus" returnType.setNew(C_IntegerType) visibility.setNew(C_PublicVisibility) val a = parameter.addNew().apply { name = "a" type.setNew(C_IntegerType) } val b = parameter.addNew().apply { name = "b" type.setNew(C_IntegerType) } body.setNew().apply { statement.addNew(C_ReturnStatement).apply { expression.setNew(C_PlusExpression).apply { leftExpression.setNew(C_VariableReference).apply { variableDeclaration = a } rightExpression.setNew(C_VariableReference).apply { variableDeclaration = b } } } } } } } } @Test fun simpleTest() = runTest { httpClient -> val client = ModelQLClient("http://localhost/query", httpClient) val result: Int = client.query { root -> root.children("classes").ofConcept(C_ClassConcept) .member .ofConcept(C_StaticMethodDeclaration) .count() } assertEquals(1, result) } @Test fun test() = runTest { httpClient -> val client = ModelQLClient("http://localhost/query", httpClient) val result: List<Pair<String, String>> = client.query { root -> root.children("classes").ofConcept(C_ClassConcept) .member .ofConcept(C_StaticMethodDeclaration) .filter { it.visibility.instanceOf(C_PublicVisibility) } .map { it.name.zip(it.parameter.name.toList(), it.untyped().conceptReference()) } .toList() }.map { it.first to it.first + "(" + it.second.joinToString(", ") + ") [" + it.third?.resolve()?.getLongName() + "]" } assertEquals(listOf("plus" to "plus(a, b) [jetbrains.mps.baseLanguage.StaticMethodDeclaration]"), result) } @Test fun testReferences() = runTest { httpClient -> val client = ModelQLClient("http://localhost/query", httpClient) val usedVariables: Set<String> = client.query { root -> root.children("classes").ofConcept(C_ClassConcept) .member .ofConcept(C_StaticMethodDeclaration) .descendants() .ofConcept(C_VariableReference) .variableDeclaration .name .toSet() } assertEquals(setOf("a", "b"), usedVariables) } @Test fun testReferencesFqName() = runTest { httpClient -> val client = ModelQLClient("http://localhost/query", httpClient) val usedVariables: Set<String> = client.query { root -> root.children("classes").ofConcept(C_ClassConcept) .member .ofConcept(C_StaticMethodDeclaration) .map { method -> method.descendants() .ofConcept(C_VariableReference) .variableDeclaration .name .toSet() .zip(method.name) } .toList() }.map { it.first.map { simpleName -> it.second + "." + simpleName } }.flatten().toSet() assertEquals(setOf("plus.a", "plus.b"), usedVariables) // TODO simplify query } @Test fun testNodeSerialization() = runTest { httpClient -> val client = ModelQLClient.builder().url("http://localhost/query").httpClient(httpClient).build() val result: List<StaticMethodDeclaration> = client.query { root -> root.children("classes").ofConcept(C_ClassConcept) .member .ofConcept(C_StaticMethodDeclaration) .filter { it.visibility.instanceOf(C_PublicVisibility) } .untyped() .toList() }.map { it.typed<StaticMethodDeclaration>() } assertEquals("plus", branch.computeRead { result[0].name }) } @Test fun returnTypedNode() = runTest { httpClient -> val client = ModelQLClient.builder().url("http://localhost/query").httpClient(httpClient).build() val result: List<StaticMethodDeclaration> = client.query { root -> root.children("classes").ofConcept(C_ClassConcept) .member .ofConcept(C_StaticMethodDeclaration) .filter { it.visibility.instanceOf(C_PublicVisibility) } .toList() } assertEquals("plus", branch.computeRead { result[0].name }) } }
44
Kotlin
6
4
dc419d5b575d23a620a914bbb9455484e4611885
8,214
modelix.core
Apache License 2.0
android/quest/src/main/java/org/smartregister/fhircore/quest/ui/login/LoginActivity.kt
opensrp
339,242,809
false
null
/* * Copyright 2021-2024 Ona Systems, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.smartregister.fhircore.quest.ui.login import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.annotation.VisibleForTesting import androidx.compose.material.ExperimentalMaterialApi import androidx.core.os.bundleOf import androidx.work.WorkManager import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject import org.smartregister.fhircore.engine.data.remote.shared.TokenAuthenticator import org.smartregister.fhircore.engine.p2p.dao.P2PReceiverTransferDao import org.smartregister.fhircore.engine.p2p.dao.P2PSenderTransferDao import org.smartregister.fhircore.engine.sync.AppSyncWorker import org.smartregister.fhircore.engine.ui.base.BaseMultiLanguageActivity import org.smartregister.fhircore.engine.ui.theme.AppTheme import org.smartregister.fhircore.engine.util.extension.applyWindowInsetListener import org.smartregister.fhircore.engine.util.extension.isDeviceOnline import org.smartregister.fhircore.engine.util.extension.launchActivityWithNoBackStackHistory import org.smartregister.fhircore.quest.ui.main.AppMainActivity import org.smartregister.fhircore.quest.ui.pin.PinLoginActivity import org.smartregister.p2p.P2PLibrary @AndroidEntryPoint open class LoginActivity : BaseMultiLanguageActivity() { @Inject lateinit var p2pSenderTransferDao: P2PSenderTransferDao @Inject lateinit var p2pReceiverTransferDao: P2PReceiverTransferDao @Inject lateinit var workManager: WorkManager val loginViewModel by viewModels<LoginViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.applyWindowInsetListener() // Cancel sync background job to get new auth token; login required, refresh token expired val cancelBackgroundSync = intent.extras?.getBoolean(TokenAuthenticator.CANCEL_BACKGROUND_SYNC, false) ?: false if (cancelBackgroundSync) workManager.cancelAllWorkByTag(AppSyncWorker::class.java.name) navigateToScreen() setContent { AppTheme { LoginScreen(loginViewModel = loginViewModel) } } } @VisibleForTesting fun navigateToScreen() { loginViewModel.apply { val loginActivity = this@LoginActivity val isPinEnabled = pinEnabled() val hasActivePin = pinActive() // Navigate to PinLogin if needed if (isPinEnabled && hasActivePin) { if ((loginActivity.deviceOnline() && loginActivity.isRefreshTokenActive()) || !loginActivity.deviceOnline() ) { navigateToPinLogin(launchSetup = false) return } } // Observer to handle navigation to Home navigateToHome.observe(loginActivity) { launchHomeScreen -> if (launchHomeScreen) { downloadNowWorkflowConfigs(isInitialLogin = false) if (isPinEnabled && !hasActivePin) { navigateToPinLogin(launchSetup = true) } else { loginActivity.navigateToHome() } } } // Observer to handle launching the dial pad launchDialPad.observe(loginActivity) { dialPadNumber -> if (!dialPadNumber.isNullOrEmpty()) { launchDialPad(dialPadNumber) } } } } @VisibleForTesting open fun pinEnabled() = loginViewModel.isPinEnabled() @VisibleForTesting open fun pinActive() = !loginViewModel.secureSharedPreference.retrieveSessionPin().isNullOrEmpty() @VisibleForTesting open fun isRefreshTokenActive() = loginViewModel.tokenAuthenticator.isCurrentRefreshTokenActive() @VisibleForTesting open fun deviceOnline() = isDeviceOnline() @OptIn(ExperimentalMaterialApi::class) fun navigateToHome() { startActivity(Intent(this, AppMainActivity::class.java)) // Initialize P2P after login only when username is provided then finish activity val username = loginViewModel.secureSharedPreference.retrieveSessionUsername() if (!username.isNullOrEmpty()) { P2PLibrary.init( P2PLibrary.Options( context = applicationContext, dbPassphrase = <PASSWORD>, username = username, senderTransferDao = p2pSenderTransferDao, receiverTransferDao = p2pReceiverTransferDao, ), ) } finish() } private fun navigateToPinLogin(launchSetup: Boolean = false) { this.launchActivityWithNoBackStackHistory<PinLoginActivity>( bundle = bundleOf(Pair(PinLoginActivity.PIN_SETUP, launchSetup)), ) } private fun launchDialPad(phone: String) { startActivity(Intent(Intent.ACTION_DIAL).apply { data = Uri.parse(phone) }) } }
198
null
56
56
64a55e6920cb6280cf02a0d68152d9c03266518d
5,250
fhircore
Apache License 2.0
循环和区间/src/demo4.kt
zjgyb
127,631,036
false
null
fun main(args: Array<String>) { var num1 = 1 .. 10 var num2 = num1.reversed() for (num in num2) { println(num) } var count = num2.count() println(count) }
0
Kotlin
0
0
eeadf39595a52d0717890668798e5c2766b39c83
186
kotlin
MIT License
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/KotlinGradlePluginVersions.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeInsight.gradle import org.jetbrains.kotlin.tooling.core.KotlinToolingVersion import org.jetbrains.kotlin.tooling.core.isStable object KotlinGradlePluginVersions { val V_1_7_21 = KotlinToolingVersion(1, 7, 21, null) val V_1_8_0 = KotlinToolingVersion(1, 8, 0, null) val latest = KotlinToolingVersion("1.9.20-dev-2357") val all = listOf( V_1_7_21, V_1_8_0, latest ) val allStable = all.filter { it.isStable } val lastStable = allStable.max() }
236
null
4946
15,650
32f33d7b7126014b860912a5b6088ffc50fc241d
658
intellij-community
Apache License 2.0
things/src/main/java/net/bonysoft/doityourselfie/ExceptionHandler.kt
danybony
137,995,324
false
{"Gradle": 10, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 9, "Batchfile": 1, "Markdown": 2, "Proguard": 7, "Java": 5, "XML": 40, "Kotlin": 57, "JSON": 5}
package net.bonysoft.doityourselfie import android.app.Activity import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent class ExceptionHandler(private val activity: Activity) : Thread.UncaughtExceptionHandler { override fun uncaughtException(t: Thread?, e: Throwable?) { val intent = Intent(activity, MainActivity::class.java) intent.putExtra("crash", true) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) val pendingIntent = PendingIntent.getActivity(activity.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT) val mgr = activity.applicationContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent) activity.finish() System.exit(2) } }
1
Kotlin
0
3
75f172b282d5df41325f06f9ff034f97be773ed1
965
do-it-yourselfie
Apache License 2.0
Pokedex/app/src/main/java/com/ivettevaldez/pokedex/global/di/application/AppComponent.kt
ivettevaldez
635,742,104
false
{"Kotlin": 70978}
package com.ivettevaldez.pokedex.global.di.application import com.ivettevaldez.pokedex.global.PokedexApplication import com.ivettevaldez.pokedex.global.di.activity.ActivityComponent import dagger.BindsInstance import dagger.Component @AppScope @Component(modules = [AppModule::class]) interface AppComponent { fun newActivityComponentBuilder(): ActivityComponent.Builder @Component.Builder interface Builder { @BindsInstance fun application(application: PokedexApplication): Builder fun appModule(appModule: AppModule): Builder fun build(): AppComponent } }
0
Kotlin
0
0
f41fc30ae76558cd90b07464791be84f03406c52
609
pokedex
Apache License 2.0
android/app/src/main/kotlin/com/mishka/mishkaCmsAndroidFlutter/MainActivity.kt
husen-hn
442,097,455
true
{"Dart": 24015, "Kotlin": 139}
package com.mishka.mishkaCmsAndroidFlutter import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
8e92aced30d2497e98a012df82ae21f95f5a732e
139
mishka-cms-android-flutter
Apache License 2.0
src/main/kotlin/no/nav/familie/ef/sak/tilbakekreving/TilbakekrevingClient.kt
navikt
206,805,010
false
null
package no.nav.familie.ef.sak.tilbakekreving import no.nav.familie.ef.sak.infrastruktur.featuretoggle.FeatureToggleService import no.nav.familie.ef.sak.infrastruktur.http.AbstractRestWebClient import no.nav.familie.kontrakter.felles.Fagsystem import no.nav.familie.kontrakter.felles.Ressurs import no.nav.familie.kontrakter.felles.ef.StønadType import no.nav.familie.kontrakter.felles.getDataOrThrow import no.nav.familie.kontrakter.felles.klage.FagsystemVedtak import no.nav.familie.kontrakter.felles.tilbakekreving.Behandling import no.nav.familie.kontrakter.felles.tilbakekreving.FinnesBehandlingResponse import no.nav.familie.kontrakter.felles.tilbakekreving.ForhåndsvisVarselbrevRequest import no.nav.familie.kontrakter.felles.tilbakekreving.KanBehandlingOpprettesManueltRespons import no.nav.familie.kontrakter.felles.tilbakekreving.OpprettManueltTilbakekrevingRequest import no.nav.familie.kontrakter.felles.tilbakekreving.Ytelsestype import org.springframework.beans.factory.annotation.Qualifier import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import org.springframework.stereotype.Component import org.springframework.web.client.RestOperations import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.util.UriComponentsBuilder import java.net.URI @Component class TilbakekrevingClient( @Qualifier("azure") restOperations: RestOperations, @Qualifier("azureWebClient") webClient: WebClient, @Value("\${FAMILIE_TILBAKE_URL}") private val familieTilbakeUri: URI, featureToggleService: FeatureToggleService ) : AbstractRestWebClient(restOperations, webClient, "familie.tilbakekreving", featureToggleService) { private val hentForhåndsvisningVarselbrevUri: URI = UriComponentsBuilder.fromUri(familieTilbakeUri) .pathSegment("api/dokument/forhandsvis-varselbrev") .build() .toUri() private val opprettManueltTilbakekrevingUri = UriComponentsBuilder.fromUri(familieTilbakeUri).pathSegment("api/behandling/manuelt/task/v1").build().toUri() private fun kanBehandlingOpprettesManueltUri( stønadstype: StønadType, eksternFagsakId: Long ) = UriComponentsBuilder.fromUri(familieTilbakeUri) .pathSegment( "api", "ytelsestype", stønadstype.name, "fagsak", eksternFagsakId.toString(), "kanBehandlingOpprettesManuelt", "v1" ) .build() .toUri() private fun finnesÅpenBehandlingUri(eksternFagsakId: Long) = UriComponentsBuilder.fromUri(familieTilbakeUri) .pathSegment("api/fagsystem/${Fagsystem.EF}/fagsak/$eksternFagsakId/finnesApenBehandling/v1") .build() .toUri() private fun finnBehandlingerUri(eksternFagsakId: Long) = UriComponentsBuilder.fromUri(familieTilbakeUri) .pathSegment("api/fagsystem/${Fagsystem.EF}/fagsak/$eksternFagsakId/behandlinger/v1") .build() .toUri() private fun finnVedtakUri(eksternFagsakId: Long) = UriComponentsBuilder.fromUri(familieTilbakeUri) .pathSegment("api/fagsystem/${Fagsystem.EF}/fagsak/$eksternFagsakId/vedtak/v1") .build() .toUri() fun hentForhåndsvisningVarselbrev(forhåndsvisVarselbrevRequest: ForhåndsvisVarselbrevRequest): ByteArray { return postForEntity( hentForhåndsvisningVarselbrevUri, forhåndsvisVarselbrevRequest, HttpHeaders().apply { accept = listOf(MediaType.APPLICATION_PDF) } ) } fun finnesÅpenBehandling(fagsakEksternId: Long): Boolean { val response: Ressurs<FinnesBehandlingResponse> = getForEntity(finnesÅpenBehandlingUri(fagsakEksternId)) return response.getDataOrThrow().finnesÅpenBehandling } fun finnBehandlinger(eksternFagsakId: Long): List<Behandling> { val response: Ressurs<List<Behandling>> = getForEntity(finnBehandlingerUri(eksternFagsakId)) return response.getDataOrThrow() } fun finnVedtak(eksternFagsakId: Long): List<FagsystemVedtak> { val response: Ressurs<List<FagsystemVedtak>> = getForEntity(finnVedtakUri(eksternFagsakId)) return response.getDataOrThrow() } fun kanBehandlingOpprettesManuelt(stønadstype: StønadType, eksternFagsakId: Long): KanBehandlingOpprettesManueltRespons { val response: Ressurs<KanBehandlingOpprettesManueltRespons> = getForEntity(kanBehandlingOpprettesManueltUri(stønadstype, eksternFagsakId)) return response.getDataOrThrow() } fun opprettManuelTilbakekreving( eksternFagsakId: Long, kravgrunnlagsreferanse: String, stønadstype: StønadType ) { return postForEntity( opprettManueltTilbakekrevingUri, OpprettManueltTilbakekrevingRequest( eksternFagsakId.toString(), Ytelsestype.valueOf(stønadstype.name), kravgrunnlagsreferanse ) ) } }
8
Kotlin
2
0
d1d8385ead500c4d24739b970940af854fa5fe2c
5,121
familie-ef-sak
MIT License
app/src/main/java/com/jiwoo/choi/nanumcar/ui/dialogs/ParkDialog.kt
banziha104
149,975,830
false
null
package com.jiwoo.choi.nanumcar.ui.dialogs import android.app.Activity import android.app.Dialog import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.View import android.view.Window import com.jiwoo.choi.nanumcar.R import com.jiwoo.choi.nanumcar.api.model.park.Result import com.jiwoo.choi.nanumcar.util.KakaoNavi import kotlinx.android.synthetic.main.dialog_park.* import org.jetbrains.anko.startActivity import org.jetbrains.anko.toast class ParkDialog(var activity: Activity?, val item : Result) : Dialog(activity), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(Window.FEATURE_NO_TITLE) setContentView(R.layout.dialog_park) txtPaDiLocation.text = item.locationRoad txtPaDiLearing.text = item.learningDate txtPaDiOperation.text = item.operation txtPaDiOrg.text = item.org txtPaDiPriceType.text = item.priceType txtPaDiTitle.text = item.title txtPaDiType2.text = item.type2 txtPaDiQunatity.text = item.quantity.toString() txtPaDiTel.text = item.tel ?: "전화번호 없음" btnPaDiNavi.setOnClickListener { KakaoNavi.startNavi( item?.lat!!, item?.lon!!, item?.title!!, activity!! ) } btnPaDiTel.setOnClickListener { if(item.tel == null && item.tel == ""){ activity!!.toast("전화번호가 없습니다").show() }else{ activity!!.startActivity(Intent(Intent.ACTION_DIAL, Uri.parse("tel:${item.tel}"))) } } } override fun onClick(v: View) { dismiss() } }
1
Kotlin
0
0
ca87ca89b03af82f0e525e54a9b036ebaff4590a
1,787
NanumCar_And
Apache License 2.0
cupertino-icons-extended/src/commonMain/kotlin/io/github/alexzhirkevich/cupertino/icons/outlined/CursorarrowRays.kt
alexzhirkevich
636,411,288
false
null
/* * Copyright (c) 2023-2024. Compose Cupertino project and open source contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 io.github.alexzhirkevich.cupertino.icons.outlined import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import io.github.alexzhirkevich.cupertino.icons.CupertinoIcons public val CupertinoIcons.Outlined.CursorarrowRays: ImageVector get() { if (_cursorarrowRays != null) { return _cursorarrowRays!! } _cursorarrowRays = Builder(name = "CursorarrowRays", defaultWidth = 25.4414.dp, defaultHeight = 25.5352.dp, viewportWidth = 25.4414f, viewportHeight = 25.5352f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(11.7891f, 20.8594f) curveTo(11.7773f, 21.3164f, 12.3047f, 21.457f, 12.6094f, 21.1641f) lineTo(14.3906f, 19.3711f) lineTo(16.3945f, 24.3281f) curveTo(16.4883f, 24.5391f, 16.7227f, 24.6562f, 16.9336f, 24.5625f) lineTo(18.1055f, 24.1055f) curveTo(18.3164f, 24.0f, 18.3984f, 23.7539f, 18.293f, 23.543f) lineTo(16.1836f, 18.668f) lineTo(18.7148f, 18.5625f) curveTo(19.1484f, 18.5391f, 19.3711f, 18.1172f, 19.0547f, 17.7773f) lineTo(12.6445f, 11.2031f) curveTo(12.3516f, 10.8984f, 11.9062f, 11.0625f, 11.8945f, 11.4961f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.6055f, 17.8242f) curveTo(7.2305f, 17.4375f, 6.5625f, 17.4375f, 6.1641f, 17.8242f) lineTo(3.75f, 20.2266f) curveTo(3.3633f, 20.6133f, 3.3633f, 21.2812f, 3.7383f, 21.668f) curveTo(4.125f, 22.0547f, 4.793f, 22.0664f, 5.1914f, 21.6797f) lineTo(7.6055f, 19.2656f) curveTo(8.0039f, 18.8789f, 8.0039f, 18.2227f, 7.6055f, 17.8242f) close() moveTo(5.4844f, 12.7148f) curveTo(5.4844f, 12.1641f, 5.0156f, 11.6953f, 4.4531f, 11.6953f) lineTo(1.0195f, 11.6953f) curveTo(0.4688f, 11.6953f, 0.0f, 12.1641f, 0.0f, 12.7148f) curveTo(0.0f, 13.2656f, 0.4688f, 13.7344f, 1.0195f, 13.7344f) lineTo(4.4531f, 13.7344f) curveTo(5.0156f, 13.7344f, 5.4844f, 13.2656f, 5.4844f, 12.7148f) close() moveTo(7.4883f, 7.5f) curveTo(7.8867f, 7.1133f, 7.8867f, 6.457f, 7.4883f, 6.0586f) lineTo(5.0859f, 3.6445f) curveTo(4.6992f, 3.2578f, 4.043f, 3.2461f, 3.6445f, 3.6328f) curveTo(3.2578f, 4.0195f, 3.2578f, 4.6758f, 3.6445f, 5.0742f) lineTo(6.0469f, 7.5f) curveTo(6.4453f, 7.8984f, 7.1016f, 7.8984f, 7.4883f, 7.5f) close() moveTo(12.7148f, 5.4609f) curveTo(13.2773f, 5.4609f, 13.7461f, 4.9922f, 13.7461f, 4.4414f) lineTo(13.7461f, 1.0195f) curveTo(13.7461f, 0.4688f, 13.2773f, 0.0f, 12.7148f, 0.0f) curveTo(12.1641f, 0.0f, 11.6953f, 0.4688f, 11.6953f, 1.0195f) lineTo(11.6953f, 4.4414f) curveTo(11.6953f, 4.9922f, 12.1641f, 5.4609f, 12.7148f, 5.4609f) close() moveTo(17.8125f, 7.6172f) curveTo(18.2109f, 8.0156f, 18.8789f, 8.0156f, 19.2656f, 7.6172f) lineTo(21.6797f, 5.2031f) curveTo(22.0781f, 4.8047f, 22.0781f, 4.1484f, 21.6797f, 3.75f) curveTo(21.293f, 3.3633f, 20.6367f, 3.3633f, 20.25f, 3.75f) lineTo(17.8125f, 6.1758f) curveTo(17.4258f, 6.5742f, 17.4258f, 7.2305f, 17.8125f, 7.6172f) close() moveTo(19.9688f, 12.7148f) curveTo(19.9688f, 13.2656f, 20.4375f, 13.7344f, 20.9883f, 13.7344f) lineTo(24.4102f, 13.7344f) curveTo(24.9727f, 13.7344f, 25.4414f, 13.2656f, 25.4414f, 12.7148f) curveTo(25.4414f, 12.1641f, 24.9727f, 11.6953f, 24.4102f, 11.6953f) lineTo(20.9883f, 11.6953f) curveTo(20.4375f, 11.6953f, 19.9688f, 12.1641f, 19.9688f, 12.7148f) close() } } .build() return _cursorarrowRays!! } private var _cursorarrowRays: ImageVector? = null
18
null
31
848
54bfbb58f6b36248c5947de343567903298ee308
5,928
compose-cupertino
Apache License 2.0
backend.native/tests/codegen/boxing/boxing7.kt
JetBrains
58,957,623
false
null
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package codegen.boxing.boxing7 import kotlin.test.* fun printInt(x: Int) = println(x) fun foo(arg: Any) { val argAsInt = try { arg as Int } catch (e: ClassCastException) { 0 } printInt(argAsInt) } @Test fun runTest() { foo(1) foo("Hello") }
162
null
625
7,100
9fb0a75ab17e9d8cddd2c3d1802a1cdd83774dfa
436
kotlin-native
Apache License 2.0
mvi-presenter/src/main/java/pl/valueadd/mvi/presenter/IMviPresenter.kt
valueadd-poland
238,159,445
false
null
package pl.valueadd.mvi.presenter interface IMviPresenter<V : IBaseView<*, *, *>> { fun initializeState(view: V) fun attachView(view: V) fun detachView() fun destroy() }
6
Kotlin
0
3
7d52819415c10e85dc6806d41433ad7ced63b5e9
190
mvi-valueadd
Apache License 2.0
src/main/kotlin/ru/yoomoney/tech/grafana/dsl/json/JsonUtils.kt
yoomoney
158,901,967
false
{"Kotlin": 378524, "Shell": 644}
package ru.yandex.money.tools.grafana.dsl.json import org.json.JSONArray import org.json.JSONObject import ru.yandex.money.tools.grafana.dsl.time.Duration operator fun JSONObject.set(key: String, value: Any?) { this.put(key, value) } class JsonBuilder(private val properties: MutableMap<String, Any?> = mutableMapOf()) { infix fun String.to(duration: Duration?) { if (duration != null) { properties[this] = duration.toString() } } infix fun String.to(value: Json<*>?) { if (value != null) { properties[this] = value.toJson() } } infix fun String.to(value: JSONObject) { properties[this] = value } infix fun String.to(array: JSONArray) { properties[this] = array } infix fun String.to(value: Any?) { properties[this] = value } fun embed(value: Json<JSONObject>) { value.toJson().toMap().forEach { (k, v) -> properties[k] = v } } internal fun toJson() = JSONObject(properties) } fun jsonObject(build: JsonBuilder.() -> Unit): JSONObject { val builder = JsonBuilder() builder.build() return builder.toJson() } fun jsonObject(basic: JSONObject, build: JsonBuilder.() -> Unit): JSONObject { val builder = JsonBuilder(basic.toMap()) builder.build() return builder.toJson() } fun emptyJsonArray() = JSONArray() class JsonArrayBuilder { operator fun get(vararg values: Any?) = JSONArray(values.map { when (it) { is Boolean -> it is Int -> it is Long -> it is Json<*> -> it.toJson() is JSONObject -> it is JSONArray -> it else -> it?.toString() } }) } val jsonArray = JsonArrayBuilder()
2
Kotlin
8
53
58ab4e2e70e544c4160b97b4dc64e73235a4bd00
1,789
grafana-dashboard-dsl
MIT License
app/src/main/java/com/unblu/brandeableagentapp/model/AuthenticationType.kt
unblu
749,823,687
false
{"Kotlin": 107771, "Java": 452}
package com.unblu.brandeableagentapp.model sealed class AuthenticationType(var name: String) { object Direct : AuthenticationType("Direct") object OAuth : AuthenticationType("OAuth") object WebProxy : AuthenticationType("WebProxy") } fun authTypeFromName(string: String) :AuthenticationType{ return when(string){ AuthenticationType.Direct.name-> AuthenticationType.Direct AuthenticationType.WebProxy.name -> AuthenticationType.WebProxy AuthenticationType.OAuth.name-> AuthenticationType.OAuth else -> AuthenticationType.Direct } }
0
Kotlin
0
0
ef75696c4c489c2c2f8212cad7fb7ac7be19c17e
601
android-brandable-agent-app
Apache License 2.0
idea/jvm-debugger/jvm-debugger-coroutine/src/org/jetbrains/kotlin/idea/debugger/coroutine/command/CoroutineBuildFrameCommand.kt
arbazpirwani
233,908,049
false
null
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger.coroutine.command import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.JavaStackFrame import com.intellij.debugger.engine.evaluation.EvaluationContext import com.intellij.debugger.engine.evaluation.EvaluationContextImpl import com.intellij.debugger.impl.DebuggerContextImpl import com.intellij.debugger.jdi.StackFrameProxyImpl import com.intellij.debugger.jdi.ThreadReferenceProxyImpl import com.intellij.debugger.memory.utils.StackFrameItem import com.intellij.debugger.ui.impl.watch.* import org.jetbrains.kotlin.idea.debugger.coroutine.CoroutineAsyncStackTraceProvider import org.jetbrains.kotlin.idea.debugger.coroutine.data.* @Deprecated("Moved to XCoroutineView") class CoroutineBuildFrameCommand( node: DebuggerTreeNodeImpl, val descriptor: CoroutineDescriptorImpl, nodeManager: NodeManagerImpl, debuggerContext: DebuggerContextImpl ) : BuildCoroutineNodeCommand(node, debuggerContext, nodeManager) { companion object { val creationStackTraceSeparator = "\b\b\b" // the "\b\b\b" is used for creation stacktrace separator in kotlinx.coroutines } override fun threadAction() { val debugProcess = debuggerContext.debugProcess ?: return val evalContext = debuggerContext.createEvaluationContext() ?: return when (descriptor.infoData.state) { CoroutineInfoData.State.RUNNING -> { if (renderRunningCoroutine(debugProcess, evalContext)) return } CoroutineInfoData.State.SUSPENDED, CoroutineInfoData.State.CREATED -> { if (renderSuspendedCoroutine(evalContext)) return } } createCreationStackTraceDescriptor(evalContext) updateUI(true) } private fun createCreationStackTraceDescriptor(evalContext: EvaluationContextImpl) { val threadProxy = debuggerContext.suspendContext?.thread ?: return val proxy = threadProxy.forceFrames().first() val trace = descriptor.infoData.stackTrace val index = trace.indexOfFirst { it.className.startsWith(creationStackTraceSeparator) } val creationNode = myNodeManager.createNode( CreationFramesDescriptor(trace.subList(index + 1, trace.size)), evalContext) myChildren.add(creationNode) trace.subList(index + 1, trace.size).forEach { val descriptor = myNodeManager.createNode( CoroutineCreatedStackFrameDescriptor(it, proxy), evalContext) creationNode.add(descriptor) } } private fun renderSuspendedCoroutine(evalContext: EvaluationContextImpl): Boolean { val threadProxy = debuggerContext.suspendContext?.thread ?: return true val proxy = threadProxy.forceFrames().first() // the thread is paused on breakpoint - it has at least one frame for (it in descriptor.infoData.stackTrace) { if (it.className.startsWith(creationStackTraceSeparator)) break myChildren.add(createCoroutineFrameDescriptor(evalContext, it, proxy)) } return false } private fun createCoroutineFrameDescriptor( evalContext: EvaluationContextImpl, frame: StackTraceElement, proxy: StackFrameProxyImpl, parent: NodeDescriptorImpl? = null ): DebuggerTreeNodeImpl { return myNodeManager.createNode( myNodeManager.getDescriptor( parent, CoroutineStackTraceData(descriptor.infoData, proxy, evalContext, frame) ), evalContext ) } private fun renderRunningCoroutine( debugProcess: DebugProcessImpl, evalContext: EvaluationContextImpl ): Boolean { if (descriptor.infoData.activeThread == null) { myChildren.add(myNodeManager.createMessageNode("Frames are not available")) return true } val proxy = ThreadReferenceProxyImpl( debugProcess.virtualMachineProxy, descriptor.infoData.activeThread ) val frames = proxy.forceFrames() var endRange = findResumeWithMethodFrameIndex(frames) for (frame in 0..frames.lastIndex) { if (frame == endRange) { val javaStackFrame = JavaStackFrame(StackFrameDescriptorImpl(frames[endRange - 1], MethodsTracker()), true) val async = CoroutineAsyncStackTraceProvider() .getAsyncStackTrace(javaStackFrame, evalContext.suspendContext) async?.forEach { myChildren.add(createAsyncFrameDescriptor(evalContext, it, frames[frame])) } } else { val frameDescriptor = createFrameDescriptor(evalContext, frames[frame]) myChildren.add(frameDescriptor) } } updateUI(true) return false } private fun findResumeWithMethodFrameIndex(frames: List<StackFrameProxyImpl>) : Int { for (j: Int in frames.lastIndex downTo 0 ) if (isResumeMethodFrame(frames[j])) { return j } return 0 } private fun isResumeMethodFrame(frame: StackFrameProxyImpl) = frame.location().method().name() == "resumeWith" private fun createFrameDescriptor( evalContext: EvaluationContext, frame: StackFrameProxyImpl ): DebuggerTreeNodeImpl { return myNodeManager.createNode( myNodeManager.getStackFrameDescriptor(descriptor, frame), evalContext ) } private fun createAsyncFrameDescriptor( evalContext: EvaluationContextImpl, frame: StackFrameItem, proxy: StackFrameProxyImpl ): DebuggerTreeNodeImpl { return myNodeManager.createNode( myNodeManager.getDescriptor( descriptor, CoroutineStackFrameData(descriptor.infoData, proxy, evalContext, frame) ), evalContext ) } }
1
null
1
1
6be72321d03e3a5ff761a65aea4b7fa51e29445c
6,202
kotlin
Apache License 2.0
app/src/main/java/com/github/jayteealao/pastelmusic/app/mediaservice/MusicCommands.kt
jayteealao
530,847,226
false
{"Kotlin": 194323}
package com.github.jayteealao.pastelmusic.app.mediaservice object MusicCommands { const val REPEAT_SHUFFLE = "repeat_shuffle" const val REPEAT = "repeat" const val REPEAT_ONE = "repeat_one" const val SHUFFLE = "shuffle" }
0
Kotlin
0
0
34294059654b8fdbc194fe4df419f5118a523070
238
PastelMusic
MIT License
kotest-property/src/jvmTest/kotlin/com/sksamuel/kotest/property/arbitrary/StringArbTest.kt
swanandvk
268,596,932
true
{"Kotlin": 2715433, "HTML": 423, "Java": 145}
package com.sksamuel.kotest.property.arbitrary import io.kotest.core.spec.style.FunSpec import io.kotest.property.Arb import io.kotest.property.arbitrary.arabic import io.kotest.property.arbitrary.armenian import io.kotest.property.arbitrary.ascii import io.kotest.property.arbitrary.cyrillic import io.kotest.property.arbitrary.georgian import io.kotest.property.arbitrary.greekCoptic import io.kotest.property.arbitrary.hebrew import io.kotest.property.arbitrary.hiragana import io.kotest.property.arbitrary.katakana import io.kotest.property.arbitrary.string import io.kotest.property.checkAll import io.kotest.property.forAll class StringArbTest : FunSpec() { init { test("String arbitraries") { forAll( Arb.string(0, 10), Arb.string(0, 5) ) { a, b -> (a + b).length == a.length + b.length } } test("should honour sizes") { forAll(Arb.string(10..20)) { it.length >= 10 it.length <= 20 } forAll(Arb.string(3..8)) { it.length >= 3 it.length <= 8 } forAll(Arb.string(0..10)) { it.length <= 10 } forAll(Arb.string(0..3)) { it.length <= 3 } forAll(Arb.string(4..4)) { it.length == 4 } forAll(Arb.string(1..3)) { it.isNotEmpty() it.length <= 3 } } test("all ascii strings generated should be valid code codepoints") { checkAll(Arb.string(10..20, Arb.ascii())) { a -> a.codePoints().forEach { Character.isValidCodePoint(it) } } } test("all strings generated with georgian codepoints should be valid code codepoints") { checkAll(Arb.string(10..20, Arb.georgian())) { a -> a.codePoints().forEach { Character.isValidCodePoint(it) } } } test("all strings generated with Katakana codepoints should be valid code codepoints") { checkAll(Arb.string(10..20, Arb.katakana())) { a -> a.codePoints().forEach { Character.isValidCodePoint(it) } } } test("all strings generated with hiragana codepoints should be valid code codepoints") { checkAll(Arb.string(10..20, Arb.hiragana())) { a -> a.codePoints().forEach { Character.isValidCodePoint(it) } } } test("all strings generated with greek coptic Codepoints should be valid code codepoints") { checkAll(Arb.string(10..20, Arb.greekCoptic())) { a -> a.codePoints().forEach { Character.isValidCodePoint(it) } } } test("all strings generated with armenian codepoints should be valid code codepoints") { checkAll(Arb.string(10..20, Arb.armenian())) { a -> a.codePoints().forEach { Character.isValidCodePoint(it) } } } test("all strings generated with hebrew Codepoints should be valid code codepoints") { checkAll(Arb.string(10..20, Arb.hebrew())) { a -> a.codePoints().forEach { Character.isValidCodePoint(it) } } } test("all strings generated with arabic codepoints should be valid code codepoints") { checkAll(Arb.string(10..20, Arb.arabic())) { a -> a.codePoints().forEach { Character.isValidCodePoint(it) } } } test("all strings generated with cyrillic Codepoints should be valid code codepoints") { checkAll(Arb.string(10..20, Arb.cyrillic())) { a -> a.codePoints().forEach { Character.isValidCodePoint(it) } } } } }
5
Kotlin
0
1
5f0d6c5a7aa76ef373d62f2a4571ae89ae0ab21e
3,835
kotest
Apache License 2.0
app/src/main/java/com/bruhascended/organiso/settings/CategorySettingsFragment.kt
ChiragKalra
272,775,912
false
null
package com.bruhascended.organiso.settings import android.app.AlertDialog import android.content.SharedPreferences import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView.ViewHolder import androidx.recyclerview.widget.RecyclerView import com.bruhascended.organiso.R import com.bruhascended.core.constants.* import com.bruhascended.organiso.settings.categories.ItemMoveCallback import com.bruhascended.organiso.settings.categories.RecyclerViewAdapter import kotlin.collections.ArrayList /* Copyright 2020 Chirag Kalra 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. */ @Suppress("UNCHECKED_CAST") class CategorySettingsFragment: Fragment(), RecyclerViewAdapter.StartDragListener { private lateinit var touchHelper: ItemTouchHelper private lateinit var prefs: SharedPreferences private lateinit var mAdapter: RecyclerViewAdapter private lateinit var recycler: RecyclerView private lateinit var previousOrder: Array<Int> private lateinit var previousLabels: Array<String> private fun drawRecyclerView( visibleCategories: Array<Int>, hiddenCategories: Array<Int>, labels: Array<String> ) { val currentOrder = ArrayList<Int>().apply { add(CATEGORY_VISIBLE) for (category in visibleCategories) add(category) add(CATEGORY_HIDDEN) for (category in hiddenCategories) if (category!= LABEL_BLOCKED) add(category) } previousOrder = currentOrder.toTypedArray() mAdapter = RecyclerViewAdapter( requireContext(), currentOrder, this, labels.clone() ) val callback: ItemTouchHelper.Callback = ItemMoveCallback(mAdapter) touchHelper = ItemTouchHelper(callback) touchHelper.attachToRecyclerView(recycler) recycler.adapter = mAdapter } private fun getLabels() = Array(6) { prefs.getString(ARR_PREF_CUSTOM_LABELS[it], "")!! } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) prefs = PreferenceManager.getDefaultSharedPreferences(requireContext()) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { setHasOptionsMenu(true) val dark = prefs.getBoolean(PREF_DARK_THEME, false) inflater.cloneInContext( ContextThemeWrapper( requireActivity(), if (dark) R.style.DarkTheme else R.style.LightTheme ) ) val root = inflater.inflate(R.layout.fragment_settings_category, container, false) recycler = root.findViewById(R.id.recycler) val visibleCategories = prefs.getString(PREF_VISIBLE_CATEGORIES, "").toLabelArray() val hiddenCategories = prefs.getString(PREF_HIDDEN_CATEGORIES, "").toLabelArray() recycler.layoutManager = LinearLayoutManager(requireContext()).apply { orientation = LinearLayoutManager.VERTICAL } previousLabels = getLabels() drawRecyclerView(visibleCategories, hiddenCategories, previousLabels) return root } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.category_settings, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_reset -> { AlertDialog.Builder(requireContext()) .setTitle(getString(R.string.reset_to_default_query)) .setPositiveButton(getString(R.string.reset)) { dialog, _ -> val vis = Array(4){it} val hid = Array(2){4+it} prefs.edit() .putString(PREF_VISIBLE_CATEGORIES, vis.toJson()) .putString(PREF_HIDDEN_CATEGORIES, hid.toJson()) .apply { for (i in 0..5) remove(ARR_PREF_CUSTOM_LABELS[i]) }.apply() drawRecyclerView(vis, hid, Array(6){""}) dialog.dismiss() } .setNegativeButton(getString(R.string.cancel)) { dialog, _ -> dialog.dismiss() }.create().show() true } else -> super.onOptionsItemSelected(item) } } override fun onDestroy() { requireActivity().title = getString(R.string.interface_settings) super.onDestroy() val arr = mAdapter.data.apply { add(LABEL_BLOCKED) } if ( arr.toTypedArray() contentDeepEquals previousOrder && previousLabels contentDeepEquals mAdapter.customLabels ) { return } val hidePos = arr.indexOf(CATEGORY_HIDDEN) val vis = Array(hidePos-1){arr[it+1]} val hid = Array(7-hidePos){arr[it+hidePos+1]} prefs.edit() .putBoolean(KEY_STATE_CHANGED, true) .putString(PREF_VISIBLE_CATEGORIES, vis.toJson()) .putString(PREF_HIDDEN_CATEGORIES, hid.toJson()) .apply { mAdapter.customLabels.indices.forEach { putString( ARR_PREF_CUSTOM_LABELS[it], mAdapter.customLabels[it].filter { c -> c.isLetterOrDigit() } ) } }.apply() } override fun requestDrag(viewHolder: ViewHolder) { touchHelper.startDrag(viewHolder) } }
2
Kotlin
8
26
044536248f813f75afdbbd41c65eabf80f39946a
6,474
Organiso
Apache License 2.0
tools/intellij.tools.ide.metrics.collector/src/com/intellij/tools/ide/metrics/collector/analysis/CompareSetting.kt
JetBrains
2,489,216
false
null
package com.intellij.tools.ide.metrics.collector.analysis data class CompareSetting( val compareWithPrevResults: Boolean = false, val table: String = "", val notifierHook: ((Conclusion) -> Unit) = { } ) { companion object { val notComparing = CompareSetting(false) val withComparing = CompareSetting(true) } }
7
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
328
intellij-community
Apache License 2.0
ext-auth-provider/src/main/kotlin/org/ostelco/ext/authprovider/AuthProviderApp.kt
ostelco
112,729,477
false
{"Gradle Kotlin DSL": 51, "YAML": 65, "Go": 13, "Go Checksums": 1, "Markdown": 48, "Shell": 48, "Text": 3, "Ignore List": 24, "Batchfile": 1, "Go Module": 1, "Kotlin": 372, "JSON": 24, "Dockerfile": 11, "XML": 28, "Java": 11, "Java Properties": 3, "Protocol Buffer": 2, "Python": 2, "SQL": 4, "PLpgSQL": 2, "GraphQL": 2, "OASv2-yaml": 6, "SVG": 17, "PlantUML": 18, "Cypher": 1}
package org.ostelco.ext.authprovider import io.dropwizard.Application import io.dropwizard.Configuration import io.dropwizard.setup.Environment import io.jsonwebtoken.Jwts import javax.validation.Valid import javax.ws.rs.GET import javax.ws.rs.HeaderParam import javax.ws.rs.Path import javax.ws.rs.Produces import javax.ws.rs.core.Response internal const val JWT_SIGNING_KEY = "jwt_secret" fun main(args: Array<String>) { AuthProviderApp().run("server") } class AuthProviderApp : Application<Configuration>() { override fun run( config: Configuration, env: Environment) { env.jersey().register(UserInfoResource()) } } @Path("/userinfo") class UserInfoResource { @GET @Produces("application/json") fun getUserInfo(@Valid @HeaderParam("Authorization") token: String?): Response { if (token != null) { val claims = Jwts.parser() .setSigningKey(JWT_SIGNING_KEY.toByteArray()) .parseClaimsJws(token.removePrefix("Bearer ")) .body return Response.status(Response.Status.OK) .entity("""{ "email": "${claims.subject}" }""") .build() } return Response.status(Response.Status.NOT_FOUND).build() } }
23
Kotlin
13
37
b072ada4aca8c4bf5c3c2f6fe0d36a5ff16c11af
1,310
ostelco-core
Apache License 2.0
src/main/kotlin/kitowashere/boiled_witchcraft/common/world/glyph/RingGlyph.kt
AugustoMegener
750,093,937
false
{"Kotlin": 47328, "Java": 2932}
package kitowashere.boiled_witchcraft.common.world.glyph import kitowashere.boiled_witchcraft.common.world.glyph.data.GlyphData import org.joml.Vector2i import kotlin.math.abs object RingGlyph : Glyph(Array(8) { it + 2}) { override fun newData() = GlyphData(this) override fun isHollow(data: GlyphData) = true override fun getSignal(data: GlyphData) = HashMap<Vector2i, Boolean>().also { val size = data.size val radius = size / 2 for (x in 0..<size) for (y in 0..<size) { val d = abs(x - radius) + abs(y - radius) if (d == radius || d == radius - 1) it[Vector2i(x, y)] = true } } }
0
Kotlin
0
2
ec7f4c8b83b53f983d2a6c83fb2e290d8dddbdc8
659
boiled_witchcraft
MIT License
faucet/src/main/kotlin/org/basinmc/faucet/math/Vector3.kt
BasinMC
59,916,990
false
null
/* * Copyright 2019 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.basinmc.faucet.math /** * Represents a position or direction within 3D space. * * @author <a href="mailto:[email protected]">Johannes Donath</a> */ interface Vector3<N : Number> : Vector2<N> { val z: N override val normalized: Vector3<N> override val int: Vector3<Int> get() = Vector3Int(this.x.toInt(), this.y.toInt(), this.z.toInt()) override val long: Vector3<Long> get() = Vector3Long(this.x.toLong(), this.y.toLong(), this.z.toLong()) override val float: Vector3<Float> get() = Vector3Float(this.x.toFloat(), this.y.toFloat(), this.z.toFloat()) override val double: Vector3<Double> get() = Vector3Double(this.x.toDouble(), this.y.toDouble(), this.z.toDouble()) override fun plus(addend: N): Vector3<N> override fun plus(addend: Vector2<N>): Vector3<N> fun plus(addend: Vector3<N>): Vector3<N> override fun minus(subtrahend: N): Vector3<N> override fun minus(subtrahend: Vector2<N>): Vector3<N> fun minus(subtrahend: Vector3<N>): Vector3<N> override fun times(factor: N): Vector3<N> override fun times(factor: Vector2<N>): Vector3<N> fun times(factor: Vector3<N>): Vector3<N> override fun div(divisor: N): Vector3<N> override fun div(divisor: Vector2<N>): Vector3<N> fun div(divisor: Vector3<N>): Vector3<N> override fun rem(divisor: N): Vector3<N> override fun rem(divisor: Vector2<N>): Vector3<N> fun rem(divisor: Vector3<N>): Vector3<N> operator fun component3(): N = this.z interface Definition<N : Number> : Vector2.Definition<N> { override val zero: Vector3<N> override val one: Vector3<N> override val up: Vector3<N> override val right: Vector3<N> override val down: Vector3<N> override val left: Vector3<N> val forward: Vector3<N> val backward: Vector3<N> } }
1
Kotlin
1
12
151c6a1897d80d2808387f46925cb470f2292537
2,496
Basin
Apache License 2.0
app/src/main/java/com/vsn/dialogs/MainActivity.kt
VikramSN
199,631,370
false
null
package com.vsn.dialogs import android.os.Build import android.os.Bundle import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.LOLLIPOP) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
1
Kotlin
0
0
433dc196cf6858cbac5336d78e4b532de39fd76e
465
SweetDialog
MIT License
compiler/fir/analysis-tests/testData/resolve/expresssions/genericDecorator.kt
JetBrains
3,432,266
false
null
// FIR_DISABLE_LAZY_RESOLVE_CHECKS // FILE: LookupElement.java public abstract class LookupElement { public abstract String getLookupString(); } // FILE: Decorator.java public abstract class Decorator<T extends LookupElement> extends LookupElement { public T getDelegate() { return null; } } // FILE: test.kt class MyDecorator : <!SUPERTYPE_NOT_INITIALIZED!>Decorator<LookupElement><!> { override fun getLookupString(): String = delegate.lookupString }
7
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
482
kotlin
Apache License 2.0
ktmeta-app/src/main/kotlin/io/github/hochikong/ktmeta/swingui/controller/dialogs/SetESMapping.kt
DigiSTALKER
285,779,525
false
{"Java": 656309, "Kotlin": 168337}
/* * Copyright 2021 Hochikong * 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 io.github.hochikong.ktmeta.swingui.controller.dialogs import io.github.hochikong.ktmeta.swingui.dialogs.codegen.impSetESMapping import io.github.hochikong.ktmeta.swingui.controller.doWhenClickOnTextField import java.awt.Frame import java.awt.event.ActionEvent import javax.swing.JTextField import java.awt.event.FocusEvent //import javax.swing.JFrame //import com.formdev.flatlaf.FlatIntelliJLaf class SetESMapping(parent: Frame) : impSetESMapping(parent, true) { private val componentRegister = mapOf<String, JTextField>( "TextFieldESHost" to this.TextFieldESHost, "TextFieldESIndex" to this.TextFieldESIndex ) override fun impBTNCreateMappingActionPerformed(evt: ActionEvent?) { // TODO } override fun impTextFieldESHostFocusGained(evt: FocusEvent?) { doWhenClickOnTextField(componentRegister, "TextFieldESHost") } override fun impTextFieldESIndexFocusGained(evt: FocusEvent?) { doWhenClickOnTextField(componentRegister, "TextFieldESIndex") } override fun impBTNResetMappingActionPerformed(evt: ActionEvent?) { // TODO } override fun impBTNClearTextAreaActionPerformed(evt: ActionEvent?) { this.TextAreaJSONSample.text = "" } } //fun main() { // FlatIntelliJLaf.install() // val dialog = SetESMapping(JFrame()) // dialog.setLocationRelativeTo(null) // dialog.isVisible = true //}
1
Java
1
3
08bde12cb3f1767b21d53255e72debdab3a8225f
1,997
KtMeta
Apache License 2.0
app/src/main/java/com/lttrung/dormitory/ui/adapters/RoomPagerAdapter.kt
lttrung2001
622,933,615
false
null
package com.lttrung.dormitory.ui.adapters import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.viewpager2.adapter.FragmentStateAdapter import com.lttrung.dormitory.ui.main.dashboard.DashboardFragment import com.lttrung.dormitory.ui.main.home.ViewWaterBillsFragment import com.lttrung.dormitory.ui.main.home.ViewElectricBillsFragment import com.lttrung.dormitory.ui.registerroom.ViewRoomCommentsFragment import com.lttrung.dormitory.ui.registerroom.ViewRoomDetailsFragment class RoomPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) { override fun getItemCount(): Int { return 2 } override fun createFragment(position: Int): Fragment { return when(position) { 0 -> ViewRoomDetailsFragment() 1 -> ViewRoomCommentsFragment() else -> DashboardFragment() } } }
0
Kotlin
0
0
82a1fab3027ad106de61e7ff00c8331da227e92d
921
dormitory
MIT License
app/src/main/java/com/prime/player/Home.kt
prime-zs
506,656,610
false
null
package com.prime.player import androidx.activity.compose.BackHandler import androidx.compose.animation.* import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.google.accompanist.navigation.animation.AnimatedNavHost import com.google.accompanist.navigation.animation.composable import com.google.accompanist.navigation.animation.rememberAnimatedNavController import com.prime.player.common.* import com.prime.player.console.Console import com.prime.player.console.ConsoleViewModel import com.prime.player.core.compose.Player import com.prime.player.core.compose.PlayerState import com.prime.player.core.compose.PlayerValue import com.prime.player.core.compose.rememberPlayerState import com.prime.player.directory.local.* import com.prime.player.library.Library import com.prime.player.library.LibraryViewModel import com.prime.player.settings.Settings import com.prime.player.settings.SettingsViewModel import kotlinx.coroutines.launch @OptIn(ExperimentalAnimationApi::class) private val EnterTransition = scaleIn( initialScale = 0.98f, animationSpec = tween(220, delayMillis = 90) ) + fadeIn(animationSpec = tween(700)) private val ExitTransition = fadeOut(tween(700)) private suspend inline fun PlayerState.toggle() = if (isExpanded) collapse() else expand() @OptIn(ExperimentalAnimationApi::class) @Composable private fun NavGraph() { AnimatedNavHost( navController = LocalNavController.current, startDestination = Library.route, modifier = Modifier, enterTransition = { EnterTransition }, exitTransition = { ExitTransition }, builder = { composable(Library.route) { val viewModel = hiltViewModel<LibraryViewModel>() Library(viewModel = viewModel) } composable(Settings.route) { val viewModel = hiltViewModel<SettingsViewModel>() Settings(viewModel = viewModel) } composable(Albums.route) { val viewModel = hiltViewModel<AlbumsViewModel>() Albums(viewModel = viewModel) } composable(Artists.route) { val viewModel = hiltViewModel<ArtistsViewModel>() Artists(viewModel = viewModel) } composable(Audios.route) { val viewModel = hiltViewModel<AudiosViewModel>() Audios(viewModel = viewModel) } composable(Folders.route) { val viewModel = hiltViewModel<FoldersViewModel>() Folders(viewModel = viewModel) } composable(Genres.route) { val viewModel = hiltViewModel<GenresViewModel>() Genres(viewModel = viewModel) } composable(Playlists.route) { val viewModel = hiltViewModel<PlaylistsViewModel>() Playlists(viewModel = viewModel) } composable(Members.route) { val viewModel = hiltViewModel<MembersViewModel>() Members(viewModel = viewModel) } } ) } @OptIn(ExperimentalMaterialApi::class, ExperimentalAnimationApi::class) @Composable fun Home(show: Boolean) { // construct necessary variables. val controller = rememberAnimatedNavController() // required for toggling player. val scope = rememberCoroutineScope() //Handle messages etc. val state = rememberPlayerState(initial = PlayerValue.COLLAPSED) // collapse if expanded and // back button is clicked. BackHandler(state.isExpanded) { scope.launch { state.collapse() } } val peekHeight = if (show) Audiofy.MINI_PLAYER_HEIGHT else 0.dp val windowPadding by rememberUpdatedState(PaddingValues(bottom = peekHeight)) CompositionLocalProvider( //TODO: maybe use the windowInsets somehow LocalWindowPadding provides windowPadding, LocalNavController provides controller, ) { Player( sheet = { //FixMe: May be use some kind of scope. val consoleViewModel = hiltViewModel<ConsoleViewModel>() Console(consoleViewModel, state.progress.value) { scope.launch { state.toggle() } } }, state = state, sheetPeekHeight = peekHeight, toast = LocalContext.toastHostState, progress = LocalContext.inAppUpdateProgress.value, content = { Surface(modifier = Modifier.fillMaxSize(), color = Theme.colors.background) { NavGraph() } }, modifier = Modifier .background(Theme.colors.background) .navigationBarsPadding() ) } }
0
null
0
4
c39917fe70d1650dbb0a5ce7288c1a579dc295a4
5,270
Audiofy2
Apache License 2.0
src/main/kotlin/io/unthrottled/amii/config/PluginSettings.kt
ani-memes
303,354,188
false
null
package io.unthrottled.amii.config import java.net.URI data class ConfigSettingsModel( var allowedExitCodes: String, var positiveExitCodes: String, var idleTimeoutInMinutes: Long, var silenceTimeoutInMinutes: Long, var memeDisplayAnchorValue: String, var idleMemeDisplayAnchorValue: String, var memeDisplayModeValue: String, var memeDisplayInvulnerabilityDuration: Int, var memeDisplayTimedDuration: Int, var memeVolume: Int, var soundEnabled: Boolean, var preferredGenders: Int, var allowFrustration: Boolean, var probabilityOfFrustration: Int, var enabledEvents: Int, var logSearchTerms: String, var logSearchIgnoreCase: Boolean, var showMood: Boolean, var eventsBeforeFrustration: Int, var minimalMode: Boolean, var discreetMode: Boolean, var capDimensions: Boolean, var infoOnClick: Boolean, var allowLewds: Boolean, var onlyCustomAssets: Boolean, var createAutoTagDirectories: Boolean, var maxMemeWidth: Int, var maxMemeHeight: Int, var customAssetsPath: String ) { fun duplicate(): ConfigSettingsModel = copy() } object PluginSettings { const val PLUGIN_SETTINGS_DISPLAY_NAME = "AMII Settings" val CHANGELOG_URI = URI("https://github.com/ani-memes/AMII/blob/master/CHANGELOG.md") private const val REPOSITORY = "https://github.com/ani-memes/AMII" val ISSUES_URI = URI("$REPOSITORY/issues") @JvmStatic fun getInitialConfigSettingsModel() = ConfigSettingsModel( allowedExitCodes = Config.instance.allowedExitCodes, positiveExitCodes = Config.instance.positiveExitCodes, idleTimeoutInMinutes = Config.instance.idleTimeoutInMinutes, silenceTimeoutInMinutes = Config.instance.silenceTimeoutInMinutes, memeDisplayAnchorValue = Config.instance.memeDisplayAnchorValue, idleMemeDisplayAnchorValue = Config.instance.idleMemeDisplayAnchorValue, memeDisplayModeValue = Config.instance.memeDisplayModeValue, memeDisplayInvulnerabilityDuration = Config.instance.memeDisplayInvulnerabilityDuration, memeDisplayTimedDuration = Config.instance.memeDisplayTimedDuration, memeVolume = Config.instance.memeVolume, soundEnabled = Config.instance.soundEnabled, preferredGenders = Config.instance.preferredGenders, allowFrustration = Config.instance.allowFrustration, probabilityOfFrustration = Config.instance.probabilityOfFrustration, enabledEvents = Config.instance.enabledEvents, logSearchTerms = Config.instance.logSearchTerms, logSearchIgnoreCase = Config.instance.logSearchIgnoreCase, showMood = Config.instance.showMood, eventsBeforeFrustration = Config.instance.eventsBeforeFrustration, minimalMode = Config.instance.minimalMode, discreetMode = Config.instance.discreetMode, capDimensions = Config.instance.capDimensions, infoOnClick = Config.instance.infoOnClick, allowLewds = Config.instance.allowLewds, onlyCustomAssets = Config.instance.onlyCustomAssets, createAutoTagDirectories = Config.instance.createAutoTagDirectories, maxMemeWidth = Config.instance.maxMemeWidth, maxMemeHeight = Config.instance.maxMemeHeight, customAssetsPath = Config.instance.customAssetsPath ) }
7
null
5
257
c9a4ef10f6e1a5ce68dc3a007b45cadbc33deed0
3,167
AMII
Apache License 2.0
src/test/kotlin/no/nav/hm/grunndata/importapi/security/TokenAPIControllerTest.kt
navikt
585,058,090
false
{"Kotlin": 170637, "Dockerfile": 170, "Shell": 41}
package no.nav.hm.grunndata.importapi.security import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import io.micronaut.http.HttpStatus import io.micronaut.test.extensions.junit5.annotation.MicronautTest import kotlinx.coroutines.runBlocking import no.nav.hm.grunndata.importapi.supplier.Supplier import no.nav.hm.grunndata.importapi.supplier.SupplierService import org.junit.jupiter.api.Test import java.util.* @MicronautTest class TokenAPIControllerTest(private val tokenAPIClient: TokenAPIClient, private val tokenService: TokenService, private val supplierService: SupplierService) { val supplierId: UUID = UUID.randomUUID() init { runBlocking { supplierService.save( Supplier(id= supplierId, name = UUID.randomUUID().toString(), identifier = UUID.randomUUID().toString(), jwtid = UUID.randomUUID().toString()) ) } } @Test fun tokenApiTest() { val bearerToken = "bearer ${tokenService.adminToken("hm-grunndata-register")}" val supplierToken = tokenAPIClient.createSupplierToken(supplierId, bearerToken) val adminToken = tokenAPIClient.createAdminToken("hm-grunndata-register", bearerToken) supplierToken.status shouldBe HttpStatus.OK supplierToken.body().id shouldBe supplierId supplierToken.body().token.shouldNotBeNull() adminToken.status shouldBe HttpStatus.OK println(adminToken.body().token) } }
0
Kotlin
0
1
eb4cfd13098908713255032dd6fdd8ab55b26911
1,557
hm-grunndata-import
MIT License
tabscrollattacherlib/src/main/java/com/iammert/tabscrollattacherlib/RecyclerViewExt.kt
iammert
225,558,728
false
null
package chooongg.box.core.ext import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import chooongg.box.core.widget.tabLayoutAttache.ScrollMethod internal fun RecyclerView.scrollToPosition(position: Int, scrollMethod: ScrollMethod) { when (scrollMethod) { is ScrollMethod.Direct -> scrollToPosition(position) is ScrollMethod.Smooth -> smoothScrollToPosition(position) is ScrollMethod.LimitedSmooth -> smoothScrollToPosition(position, scrollMethod.limit) } } private fun RecyclerView.smoothScrollToPosition(position: Int, scrollLimit: Int) { layoutManager?.apply { when (this) { is LinearLayoutManager -> { val topItem = findFirstVisibleItemPosition() val distance = topItem - position val anchorItem = when { distance > scrollLimit -> position + scrollLimit distance < -scrollLimit -> position - scrollLimit else -> topItem } if (anchorItem != topItem) scrollToPosition(anchorItem) post { smoothScrollToPosition(position) } } else -> smoothScrollToPosition(position) } } }
3
Kotlin
16
222
75b40b399db307547435efdbd961aa4430f61a65
1,310
TabScrollAttacher
Apache License 2.0
android/app/src/main/java/kr/pnu/ga2019/presentation/main/MainViewModel.kt
ehdrms2034
250,954,396
false
null
/* * Created by <NAME> on 2020/06/20 .. */ package kr.pnu.ga2019.presentation.main import kr.pnu.ga2019.presentation.base.BaseViewModel class MainViewModel : BaseViewModel() { /* explicitly empty */ }
20
Kotlin
0
2
c07515a4b1cfd7fc89c227bb795d451a06a89252
210
SmartPathGuide
MIT License
keel-orca/src/test/kotlin/com/netflix/spinnaker/keel/orca/OrcaResponseDeserializationTests.kt
spinnaker
107,462,081
false
null
package com.netflix.spinnaker.keel.orca import com.fasterxml.jackson.module.kotlin.readValue import com.netflix.spinnaker.keel.serialization.configuredObjectMapper import dev.minutest.junit.JUnit5Minutests import dev.minutest.rootContext import strikt.api.expect import strikt.assertions.isEqualTo import java.time.Duration import java.time.Instant import java.time.temporal.ChronoUnit class OrcaResponseDeserializationTests : JUnit5Minutests { object Fixture { val startTime: Instant = Instant.now().truncatedTo(ChronoUnit.MILLIS) val response = """{ "id": "test", "name": "test", "application": "test", "buildTime": ${startTime.toEpochMilli()}, "startTime": ${startTime.toEpochMilli()}, "endTime": ${startTime.plus(Duration.ofMinutes(10)).toEpochMilli()}, "status": "SUCCEEDED", "execution": { "stages": [] } }""".trimIndent() val objectMapper = configuredObjectMapper() } fun tests() = rootContext<Fixture> { fixture { Fixture } test("fields represented as epoch with milliseconds are converted correctly") { val deserialized = objectMapper.readValue<ExecutionDetailResponse>(response) expect { that(deserialized.buildTime).isEqualTo(startTime) that(deserialized.startTime).isEqualTo(startTime) that(deserialized.endTime).isEqualTo(startTime + Duration.ofMinutes(10)) } } } }
2
Kotlin
135
99
956653ad493c386b88621eaf48ddc939a6372574
1,425
keel
Apache License 2.0
libraries/csm.cloud.project.avro/src/main/kotlin/com/bosch/pt/csm/cloud/projectmanagement/messageattachment/message/MessageAttachmentAggregateAvro.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2021 * * ************************************************************************ */ package com.bosch.pt.csm.cloud.projectmanagement.messageattachment.message import com.bosch.pt.csm.cloud.common.extensions.toInstantByMillis import com.bosch.pt.csm.cloud.common.extensions.toUUID import com.bosch.pt.csm.cloud.common.messages.buildAggregateIdentifier import com.bosch.pt.csm.cloud.projectmanagement.message.messages.MessageAttachmentAggregateAvro fun MessageAttachmentAggregateAvro.getIdentifier() = getAggregateIdentifier().getIdentifier().toUUID() fun MessageAttachmentAggregateAvro.getMessageIdentifier() = getMessage().getIdentifier().toUUID() fun MessageAttachmentAggregateAvro.getLastModifiedDate() = getAuditingInformation().getLastModifiedDate().toInstantByMillis() fun MessageAttachmentAggregateAvro.getLastModifiedByUserIdentifier() = getAuditingInformation().getLastModifiedBy().getIdentifier().toUUID() fun MessageAttachmentAggregateAvro.getMessageVersion() = getMessage().getVersion() fun MessageAttachmentAggregateAvro.buildAggregateIdentifier() = getAggregateIdentifier().buildAggregateIdentifier()
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
1,277
bosch-pt-refinemysite-backend
Apache License 2.0
redwood-tooling-codegen/src/main/kotlin/app/cash/redwood/tooling/codegen/kpx.kt
cashapp
305,409,146
false
{"Kotlin": 2089205, "Swift": 20649, "Objective-C": 4497, "Java": 1583, "Shell": 253, "HTML": 235, "C": 129}
/* * Copyright (C) 2024 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.redwood.tooling.codegen import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.MemberName internal fun buildFileSpec(className: ClassName, builder: FileSpec.Builder.() -> Unit): FileSpec { return FileSpec.builder(className) .apply(builder) .build() } internal fun buildFileSpec(memberName: MemberName, builder: FileSpec.Builder.() -> Unit): FileSpec { return FileSpec.builder(memberName) .apply(builder) .build() } internal fun buildFileSpec(packageName: String, fileName: String, builder: FileSpec.Builder.() -> Unit): FileSpec { return FileSpec.builder(packageName, fileName) .apply(builder) .build() }
108
Kotlin
73
1,648
3f14e622c2900ec7e0dfaff5bd850c95a7f29937
1,314
redwood
Apache License 2.0
compiler/testData/codegen/box/nullCheckOptimization/kt49136a.kt
JetBrains
3,432,266
false
null
// https://youtrack.jetbrains.com/issue/KT-50289/EXCBADACCESS-getting-non-null-property-in-safe-call-chain // IGNORE_NATIVE: optimizationMode=DEBUG // IGNORE_NATIVE: optimizationMode=NO abstract class Z { init { check(this) } abstract val b: B } class A(override val b: B) : Z() class B(val c: String) fun use(a: Any?) {} fun check(z: Z) { use(z?.b?.c) } fun box(): String { A(B("")) return "OK" }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
437
kotlin
Apache License 2.0
app/src/main/java/com/istu/schedule/ui/page/projfair/participation/CreateParticipationPage.kt
imysko
498,018,609
false
{"Kotlin": 747191}
package com.istu.schedule.ui.page.projfair.participation import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.windowInsetsBottomHeight import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.istu.schedule.R import com.istu.schedule.ui.components.base.SIAnimatedVisibilityFadeOnly import com.istu.schedule.ui.components.base.SIDialog import com.istu.schedule.ui.components.base.StringResourceItem import com.istu.schedule.ui.components.base.button.FilledButton import com.istu.schedule.ui.components.base.button.TextButton import com.istu.schedule.ui.components.base.button.radio.RadioButtonWithText import com.istu.schedule.ui.page.settings.TopBar import com.istu.schedule.ui.theme.AppTheme import com.istu.schedule.ui.theme.Shape20 import com.istu.schedule.ui.theme.ShapeTop15 import me.progneo.projfair.domain.model.Participation @Composable fun CreateParticipationPage( projectId: Int, navController: NavController, viewModel: CreateParticipationViewModel = hiltViewModel() ) { val isLoaded by viewModel.isLoaded.observeAsState(initial = false) val selectedPriorityId by viewModel.selectedPriorityId.observeAsState(initial = 0) val project by viewModel.project.observeAsState(initial = null) val existsParticipationList by viewModel.participationList.observeAsState(initial = emptyList()) LaunchedEffect(Unit) { viewModel.fetchParticipationList() viewModel.fetchProject(projectId) } CreateParticipationPage( isLoaded = isLoaded, existsParticipationList = existsParticipationList, selectedPriority = selectedPriorityId, onBackPressed = { navController.popBackStack() }, onCreatePressed = { viewModel.createParticipation() }, onSelect = { viewModel.setPriorityId(it) }, projectTitle = project?.title ) } @Composable fun CreateParticipationPage( isLoaded: Boolean, existsParticipationList: List<Participation>, selectedPriority: Int, onBackPressed: () -> Unit, onCreatePressed: () -> Unit, onSelect: (Int) -> Unit, projectTitle: String? = null ) { var confirmDialogVisible by remember { mutableStateOf(false) } val prioritiesList = mutableListOf( StringResourceItem(1, R.string.highest_priority), StringResourceItem(2, R.string.medium_priority), StringResourceItem(3, R.string.low_priority) ) existsParticipationList.forEach { participation -> val item = prioritiesList.firstOrNull { it.id == participation.priority } if (item != null) { prioritiesList.remove(item) } } SIDialog( modifier = Modifier.clip(Shape20), visible = confirmDialogVisible, backgroundColor = AppTheme.colorScheme.backgroundSecondary, title = { Text( modifier = Modifier.fillMaxWidth(), text = stringResource(R.string.participation_submitted), style = AppTheme.typography.title.copy( fontWeight = FontWeight.SemiBold ), color = AppTheme.colorScheme.textPrimary, textAlign = TextAlign.Center ) }, onDismissRequest = { confirmDialogVisible = false onBackPressed() }, confirmButton = { TextButton( text = stringResource(R.string.confirm), contentColor = AppTheme.colorScheme.primary, onClick = { onBackPressed() } ) } ) Scaffold( containerColor = AppTheme.colorScheme.backgroundPrimary, topBar = { TopBar( title = stringResource(R.string.send_participation_page_title), isShowBackButton = true, onBackClick = onBackPressed ) } ) { LazyColumn( modifier = Modifier .fillMaxSize() .padding(it) .clip(ShapeTop15) .background(AppTheme.colorScheme.backgroundSecondary), contentPadding = PaddingValues(20.dp), verticalArrangement = Arrangement.spacedBy(20.dp) ) { item { Text( text = projectTitle ?: stringResource(R.string.project), style = AppTheme.typography.title ) } item { SIAnimatedVisibilityFadeOnly(isLoaded) { Column { Text( modifier = Modifier.padding(bottom = 10.dp), text = stringResource(R.string.project_priority), style = AppTheme.typography.subtitle.copy( fontWeight = FontWeight.Bold ) ) Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { prioritiesList.map { priority -> RadioButtonWithText( text = stringResource(id = priority.stringId), selected = selectedPriority == priority.id, onSelect = { onSelect(priority.id) } ) } } } } } item { SIAnimatedVisibilityFadeOnly( isLoaded && prioritiesList.any { it.id == selectedPriority } ) { FilledButton( modifier = Modifier .fillMaxWidth() .height(42.dp), text = stringResource(R.string.send_participation), onClick = { onCreatePressed() confirmDialogVisible = true } ) } } item { Spacer(modifier = Modifier.height(64.dp)) Spacer( modifier = Modifier.windowInsetsBottomHeight( WindowInsets.navigationBars ) ) } } } } @Preview(showBackground = true) @Composable fun PreviewSendParticipationPage() { AppTheme { CreateParticipationPage( isLoaded = true, existsParticipationList = listOf(), selectedPriority = 1, onBackPressed = {}, onCreatePressed = {}, onSelect = {} ) } } @Preview(showBackground = true) @Composable fun PreviewSendParticipationPageLoading() { AppTheme { CreateParticipationPage( isLoaded = false, existsParticipationList = listOf(), selectedPriority = 1, onBackPressed = {}, onCreatePressed = {}, onSelect = {} ) } }
1
Kotlin
0
2
f2d173de20910b03ef762ffb5cf3752cfeccf6cf
8,504
Schedule-ISTU
MIT License
src/main/kotlin/no/nav/helse/flex/spreoppgave/HandterOppave.kt
navikt
451,810,928
false
{"Kotlin": 273479, "Dockerfile": 267}
package no.nav.helse.flex.spreoppgave import io.micrometer.core.instrument.MeterRegistry import no.nav.helse.flex.domain.OppdateringstypeDTO import no.nav.helse.flex.domain.OppgaveDTO import no.nav.helse.flex.logger import no.nav.helse.flex.repository.OppgaveStatus import no.nav.helse.flex.repository.SpreOppgaveDbRecord import no.nav.helse.flex.repository.SpreOppgaveRepository import no.nav.helse.flex.util.tilOsloZone import org.springframework.stereotype.Component import java.time.Instant interface HandterOppgaveInterface { fun håndterOppgaveFraBømlo( eksisterendeOppgave: SpreOppgaveDbRecord?, oppgave: OppgaveDTO ) fun håndterOppgaveFraSøknad( eksisterendeOppgave: SpreOppgaveDbRecord?, oppgave: OppgaveDTO ) } @Component class HandterOppave( private val spreOppgaveRepository: SpreOppgaveRepository, registry: MeterRegistry ) : HandterOppgaveInterface { private val log = logger() private val gjenopplivetCounter = registry.counter("gjenopplivet_oppgave") override fun håndterOppgaveFraBømlo( eksisterendeOppgave: SpreOppgaveDbRecord?, oppgave: OppgaveDTO ) { val tidspunkt = Instant.now() when { eksisterendeOppgave == null -> { spreOppgaveRepository.save( SpreOppgaveDbRecord( sykepengesoknadId = oppgave.dokumentId.toString(), timeout = timeout(oppgave), status = oppgave.oppdateringstype.tilOppgaveStatus(), opprettet = tidspunkt, modifisert = tidspunkt ) ) } eksisterendeOppgave.status == OppgaveStatus.Utsett -> { log.info("Mottok ${oppgave.oppdateringstype.name} oppgave for søknad ${oppgave.dokumentId} fra bømlo") spreOppgaveRepository.updateOppgaveBySykepengesoknadId( sykepengesoknadId = oppgave.dokumentId.toString(), timeout = timeout(oppgave), status = oppgave.oppdateringstype.tilOppgaveStatus(), tidspunkt ) } eksisterendeOppgave.status == OppgaveStatus.IkkeOpprett && oppgave.oppdateringstype == OppdateringstypeDTO.Opprett -> { log.info("Vil opprette oppgave for søknad ${oppgave.dokumentId} som vi tidligere ble bedt om å ikke opprette") gjenopplivetCounter.increment() spreOppgaveRepository.updateOppgaveBySykepengesoknadId( sykepengesoknadId = oppgave.dokumentId.toString(), timeout = timeout(oppgave), status = oppgave.oppdateringstype.tilOppgaveStatus(), tidspunkt ) } else -> { log.info("Gjør ikke ${oppgave.oppdateringstype.name} for søknad ${oppgave.dokumentId} fordi status er ${eksisterendeOppgave.status.name}") } } } override fun håndterOppgaveFraSøknad( eksisterendeOppgave: SpreOppgaveDbRecord?, oppgave: OppgaveDTO ) { log.info("Avstemmer oppgave opprettelse for søknad ${oppgave.dokumentId}") if (eksisterendeOppgave != null) { spreOppgaveRepository.updateAvstemtBySykepengesoknadId(eksisterendeOppgave.sykepengesoknadId) } else { val now = Instant.now() spreOppgaveRepository.save( SpreOppgaveDbRecord( sykepengesoknadId = oppgave.dokumentId.toString(), timeout = timeout(oppgave), status = oppgave.oppdateringstype.tilOppgaveStatus(), avstemt = true, opprettet = now, modifisert = now ) ) } } } internal fun timeout(oppgave: OppgaveDTO) = if (oppgave.oppdateringstype == OppdateringstypeDTO.Utsett) { oppgave.timeout?.tilOsloZone() ?.toInstant() } else { null } private fun OppdateringstypeDTO.tilOppgaveStatus() = when (this) { OppdateringstypeDTO.Utsett -> OppgaveStatus.Utsett OppdateringstypeDTO.Ferdigbehandlet -> OppgaveStatus.IkkeOpprett OppdateringstypeDTO.OpprettSpeilRelatert -> OppgaveStatus.OpprettSpeilRelatert OppdateringstypeDTO.Opprett -> OppgaveStatus.Opprett }
5
Kotlin
0
0
da01e56e485ec2de4e9fcd200383780f43f28578
4,442
sykepengesoknad-arkivering-oppgave
MIT License
src/commonMain/kotlin/kson/models/common/APIReference.kt
DrZoddiak
462,390,338
false
{"Kotlin": 39104}
package kson.models.common import kotlinx.serialization.Serializable /** * This is the concrete type of [IRef] */ @Serializable data class APIReference( override val index: String, override val name: String, override val url: String ) : IRef
0
Kotlin
0
1
b9ee2e0a1bc2db4e619aa916aaafb61a6f5539da
258
KsonMulti
MIT License
app/src/main/java/com/amora/myseasonalanime/data/source/remote/response/detailcharacter/DetailCharaItem.kt
irawan-r
481,205,369
false
null
package com.amora.myseasonalanime.data.source.remote.response.detailcharacter import androidx.room.Entity import androidx.room.PrimaryKey import com.amora.myseasonalanime.data.source.remote.response.images.Images import com.squareup.moshi.Json @Entity(tableName = "detail_chara") data class DetailCharaItem( @Json(name="favorites") val favorites: Int? = null, @Json(name="images") val images: Images? = null, @Json(name="name_kanji") val nameKanji: String? = null, @Json(name="name") val name: String? = null, @Json(name="about") val about: String? = null, @PrimaryKey @Json(name="mal_id") val malId: Int? = null, @Json(name="nicknames") val nicknames: List<String?>? = null, @Json(name="url") val url: String? = null )
0
Kotlin
0
0
9146fb51c53efe51441a1e201afa122b12d13e77
797
my-seasonal-anime
Apache License 2.0