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
tourtip/src/main/java/com/fappslab/tourtip/compose/TourtipLayout.kt
F4bioo
815,756,472
false
{"Kotlin": 94125, "Python": 2381}
/* * Copyright 2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fappslab.tourtip.compose import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import com.fappslab.tourtip.compose.component.TourtipComponent import com.fappslab.tourtip.model.TourtipAnimType import com.fappslab.tourtip.model.TourtipController import com.fappslab.tourtip.theme.TourtipTheme import com.fappslab.tourtip.theme.defaults.TourtipDefaults /** * A composable function that provides a layout for displaying a guided tooltip tour. * * @param modifier A [Modifier] for this layout. Default is [Modifier]. * @param onBack A callback invoked when the "back" action is triggered. Default is an empty function. * @param onNext A callback invoked when the "next" action is triggered. Default is an empty function. * @param onClose A callback invoked when the "close" action is triggered. Default is null. * @param onClickOut A callback invoked when a click outside the tooltip is detected. Default is null. * @param animType The type of animation to use for tooltip transitions. Default is [TourtipAnimType.Bouncy]. See other animations in [TourtipAnimType]. * @param scrimColor The color of the scrim background. Default is [TourtipDefaults.scrimColor]. * @param backgroundColor The background color of the tooltip. Default is [TourtipDefaults.backgroundColor]. * @param content The composable content that the tour will guide through, with access to the [TourtipController]. * * Example usage: * ``` * TourtipLayout( * onBack = { currentStep -> * // Handle back action for event tracking $currentStep * }, * onNext = { currentStep -> * // Handle next action for event tracking $currentStep * }, * onClose = { currentStep -> * // Handle close action for event tracking $currentStep * }, * onClickOut = { currentStep -> * // Handle click-out action for event tracking $currentStep * } * ) { controller -> * * // Screen content * Button(onClick = { controller.startTourtip() }) { * Text("Start Tour") * } * } * ``` */ @Composable fun TourtipLayout( modifier: Modifier = Modifier, onBack: (currentStep: Int) -> Unit = {}, onNext: (currentStep: Int) -> Unit = {}, onClose: ((currentStep: Int) -> Unit)? = null, onClickOut: ((currentStep: Int) -> Unit)? = null, animType: TourtipAnimType = TourtipAnimType.Bouncy, scrimColor: Color = TourtipDefaults.scrimColor, backgroundColor: Color = TourtipDefaults.backgroundColor, content: @Composable ColumnScope.(controller: TourtipController) -> Unit ) { TourtipTheme { TourtipComponent( onClose = onClose, onBack = onBack, onNext = onNext, onClickOut = onClickOut, animType = animType, scrimColor = scrimColor, backgroundColor = backgroundColor ) { viewModel -> Column( modifier = modifier ) { content(viewModel) } } } }
0
Kotlin
0
8
eabe396352ab9dafcae8e035d38809418cd31645
3,779
Tourtip
Apache License 2.0
app/src/main/java/hu/mostoha/mobile/android/huki/extensions/PermissionExtensions.kt
RolandMostoha
386,949,428
false
null
package hu.mostoha.mobile.android.huki.extensions import android.Manifest import android.app.Activity import android.content.Context import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat val locationPermissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) fun Context.isLocationPermissionGranted(): Boolean { return isGranted(Manifest.permission.ACCESS_COARSE_LOCATION) || isGranted(Manifest.permission.ACCESS_FINE_LOCATION) } fun Map<String, Boolean>.isLocationPermissionGranted(): Boolean { val isFineLocationEnabled = this.getOrDefault(Manifest.permission.ACCESS_FINE_LOCATION, false) val isCoarseLocationEnabled = this.getOrDefault(Manifest.permission.ACCESS_COARSE_LOCATION, false) return isFineLocationEnabled || isCoarseLocationEnabled } private fun Context.isGranted(permission: String): Boolean { return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED } fun Activity.shouldShowLocationRationale(): Boolean { return ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) }
0
null
1
9
92587e6dcc68d89b5ffb2afd8cdd3c0cc47fb7d4
1,221
HuKi-Android
The Unlicense
src/com/wxx/design/design_04_factory/abstract/Client.kt
wuxinxi
192,182,654
false
null
package com.wxx.design.design_04_factory.abstract /** * @author :DELL on 2021/5/12 . * @packages :com.wxx.design.design_04_factory.abstract . * TODO: */ fun main() { val miFactory = MiFactory() val miPhoneProduct = miFactory.phoneProduct() val miRouterProduct = miFactory.routerProduct() miPhoneProduct.start() miPhoneProduct.sendSMS() miRouterProduct.start() miRouterProduct.openWife() val huaWeiFactory=HuaWeiFactory() val huaWeiPhoneProduct=huaWeiFactory.phoneProduct() val huaWeiRouterProduct=huaWeiFactory.routerProduct() huaWeiPhoneProduct.start() huaWeiPhoneProduct.call() huaWeiRouterProduct.start() huaWeiRouterProduct.openWife() }
1
null
1
1
1fef75f988f384fb5f9ace7087ccca3b00d587fb
702
DesignPatternsDemo
MIT License
src/test/java/org/jackJew/biz/engine/test/JsEngineTest.kt
runjia1987
102,723,162
false
null
package org.jackJew.biz.engine.test import org.jackJew.biz.engine.JsEngine import org.jackJew.biz.engine.JsEngineNashorn import org.jackJew.biz.engine.JsEngineRhino import org.jackJew.biz.engine.util.IOUtils import org.junit.Test import com.google.gson.JsonObject /** * when MAX is below 50, Rhino is better than Nashorn; * <br></br> * when MAX is 100, Nashorn is better than Rhino. * @author Jack */ const val MAX = 200 class JsEngineTest { @Test fun testNashornJS() { val cl = Thread.currentThread().contextClassLoader cl.getResourceAsStream("site_source.html").use { val content = IOUtils.toString(it, JsEngine.DEFAULT_CHARSET) val config = JsonObject().also { it.addProperty("content", content) } val script = cl.getResourceAsStream("org/jackJew/biz/engine/test/config/test.js").use { IOUtils.toString(it, JsEngine.DEFAULT_CHARSET) } val startTime = System.currentTimeMillis() var i = 0 while (i < MAX) { val result = JsEngineNashorn.INSTANCE.runScript2JSON( "(function(args){$script})($config);") if (i++ == 0) { println(result) } } println("testNashornJS time cost: " + (System.currentTimeMillis() - startTime) + " ms.") } } @Test fun testRhinoJS() { val cl = Thread.currentThread().contextClassLoader cl.getResourceAsStream("site_source.html").use { val content = IOUtils.toString(it, JsEngine.DEFAULT_CHARSET) val config = JsonObject().also{ it.addProperty("content", content)} val script = cl.getResourceAsStream("org/jackJew/biz/engine/test/config/test.js").use { IOUtils.toString(it, JsEngine.DEFAULT_CHARSET) } val startTime = System.currentTimeMillis() var i = 0 while (i < MAX) { val result = JsEngineRhino.INSTANCE.runScript2JSON( "(function(args){$script})($config);") if (i++ == 0) { println(result) } } println("testRhinoJS time cost: " + (System.currentTimeMillis() - startTime) + " ms.") } } }
0
Kotlin
0
0
1256a8bb6d9f11b7157e73cae5f39d7b01aeb1d6
2,095
crawler-client-kt
Apache License 2.0
WeChat/src/main/java/io/github/devzwy/socialhelper/wechat/WeChatSocialEntryActivity.kt
devzwy
493,205,062
false
{"Kotlin": 69289, "Java": 10050}
package io.github.devzwy.socialhelper.wechat import android.app.Activity import android.content.Intent import android.os.Bundle import com.tencent.mm.opensdk.modelbase.BaseReq import com.tencent.mm.opensdk.modelbase.BaseResp import com.tencent.mm.opensdk.modelmsg.SendAuth import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler import io.github.devzwy.socialhelper.SocialHelper import io.github.devzwy.socialhelper.utils.* import io.github.devzwy.socialhelper.wechat.data.WeChatConst.Companion.WECHAT_ACCESSTOKEN_REQUEST_URL import io.github.devzwy.socialhelper.wechat.data.WeChatSocialAccessTokenData import io.github.devzwy.socialhelper.wechat.data.WeChatSocialReqAuthRespData /** * 客户端继承自该类即可 */ open class WeChatSocialEntryActivity : Activity(), IWXAPIEventHandler { //微信回传结果的类型 登陆 val WECHAT_RESULT_TYPE_LOGIN = 1 //微信回传结果的类型 分享 val WECHAT_RESULT_TYPE_SHARE = 2 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) "${localClassName}->onCreate():mIWXAPI:$mIWXAPI".logD() mIWXAPI.handleIntent(intent, this) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) "${localClassName}->onNewIntent():mIWXAPI:$mIWXAPI".logD() setIntent(intent) mIWXAPI.handleIntent(intent, this) } override fun onDestroy() { super.onDestroy() "${localClassName}->onDestroy()".logD() } override fun onReq(p0: BaseReq) { } override fun onResp(mBaseResp: BaseResp) { (mBaseResp.errCode == BaseResp.ErrCode.ERR_OK).yes { "${localClassName}->onResp():mBaseResp:${mBaseResp.toJsonStr()}".logD() when (mBaseResp.type) { WECHAT_RESULT_TYPE_LOGIN -> { //授权回调 onReqAuthSucc(mBaseResp as SendAuth.Resp) } WECHAT_RESULT_TYPE_SHARE -> { //分享回调 mWeChatReqShareSuccessListener?.let { it() } } else -> { "unknow result type from wechat,${mBaseResp.toJsonStr()}".logE() } } }.otherwise { "${localClassName}->onResp():mBaseResp:${mBaseResp.toJsonStr()}".logE() when (mBaseResp.type) { WECHAT_RESULT_TYPE_LOGIN -> { //授权失败回调 mWeChatReqAuthErrorListener( if (mBaseResp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) application.getString( R.string.social_wechat_req_auth_cancel ) else if (mBaseResp.errStr != null) mBaseResp.errStr else "${mBaseResp.errCode}" ) } WECHAT_RESULT_TYPE_SHARE -> { //分享回调 mWeChatReqShareErrorListener?.let { it( if (!mBaseResp.errStr.isNullOrEmpty()) mBaseResp.errStr else application.getString( R.string.social_wechat_share_err, mBaseResp.errCode ) ) } } else -> { "unknow result type from wechat,${mBaseResp.toJsonStr()}".logE() } } } mWeChatReqShareErrorListener = null mWeChatReqShareSuccessListener = null finish() } /** * 处理授权成功业务 */ private fun onReqAuthSucc(resp: SendAuth.Resp) { resp.toJsonStr().logD() //判断是否配置weChatAppSecretKey SocialHelper.socialConfig.weChatAppSecretKey.isEmpty().yes { //未配置时直接回传authCode即可 mWeChatReqAuthSuccessListener(WeChatSocialReqAuthRespData(authCodeData = resp)) }.otherwise { //查询accessToken appid secret code SocialHelper.socialConfig.apply { SocialNetUtil.sendGet( String.format( WECHAT_ACCESSTOKEN_REQUEST_URL, weChatAppId, weChatAppSecretKey, resp.code ), { it.toObject(WeChatSocialAccessTokenData::class.java) .let { mWeChatAccessTokenData -> (mWeChatAccessTokenData.errcode == 0).yes { mWeChatReqAuthSuccessListener( WeChatSocialReqAuthRespData( authCodeData = resp, socialAccessTokenData = mWeChatAccessTokenData ) ) }.otherwise { mWeChatReqAuthErrorListener( application.getString( R.string.social_wechat_get_access_token_err, if (mWeChatAccessTokenData.errmsg.isEmpty()) "${mWeChatAccessTokenData.errcode}" else mWeChatAccessTokenData.errmsg ) ) } } }, { mWeChatReqAuthErrorListener( application.getString( R.string.social_wechat_get_access_token_err, it ) ) }) } } } }
0
Kotlin
0
12
ef9417e624c5c41ed8dae86c25c4f1dbee12075a
5,755
SocialHelper
Apache License 2.0
frontend/shared/ui/src/commonMain/kotlin/com/ams/groundwater/main/MainScreenArrangementColumn.kt
meikefeliciah
710,363,969
false
{"Kotlin": 28346, "Swift": 652, "Dockerfile": 527, "Shell": 228}
package com.ams.groundwater.main import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateContentSize import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import com.ams.groundwater.GroundWaterInfo @Composable fun MainScreenArrangementColumn( groundWaterInfo: GroundWaterInfo?, selectedGroundWaterInfo: GroundWaterInfo?, isLoading: Boolean, onGroundWaterInfoClicked: (String?) -> Unit, modifier: Modifier = Modifier, ) { Column(modifier = modifier) { AnimatedVisibility( visible = isLoading, enter = slideInVertically(initialOffsetY = { -it }), exit = slideOutVertically(targetOffsetY = { -it }), ) { LoadingIndicator() } GroundWaterInfoMap( groundWaterInfo = groundWaterInfo, onGroundWaterInfoClicked = onGroundWaterInfoClicked, modifier = Modifier .animateContentSize() .fillMaxSize() .weight(1f), ) AnimatedVisibility( visible = selectedGroundWaterInfo != null, enter = slideInVertically(initialOffsetY = { it }) + fadeIn(), exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(), ) { GroundWaterInfoDetails( groundWaterInfo = selectedGroundWaterInfo, ) } } }
0
Kotlin
0
0
8d350e1104aa5e2c354f0a8f45592d5df79d438d
1,501
groundwater
Apache License 2.0
src/main/kotlin/flow/AwaitableMutableFlow.kt
giacomoaccursi
717,007,118
false
{"Kotlin": 47272, "JavaScript": 1187, "Dockerfile": 103}
/* * Copyright (c) 2024. <NAME> * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package flow import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.withContext import java.util.concurrent.CountDownLatch import kotlin.coroutines.CoroutineContext /** * Base implementation of a custom flow that waits for notification of consumed element. */ open class AwaitableMutableFlow<T>( private val flow: MutableSharedFlow<T>, private val ioDispatcher: CoroutineContext = Dispatchers.IO, ) { private var emitLatch: CountDownLatch = CountDownLatch(0) /** * Perform emit waiting for notification. */ suspend fun emitAndWait(value: T) { emitLatch = CountDownLatch(flow.subscriptionCount.value) flow.emit(value) withContext(ioDispatcher) { emitLatch.await() } emitLatch = CountDownLatch(0) } /** * A function for notifying the consumption. */ fun notifyConsumed() { emitLatch.countDown() } }
1
Kotlin
0
1
cdf79d9e75e3acb08290cb1e504b7867e0968289
1,168
Reactive-DES
MIT License
fluentui_calendar/src/main/java/com/microsoft/fluentui/view/Scroller.kt
Anthonysidesapp
454,785,341
true
{"Kotlin": 884615}
/* * Copyright (C) 2006 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. */ @file:Suppress("SpellCheckingInspection") package asada0.android.brighterbigger.numberpicker import android.content.Context import android.hardware.SensorManager import android.os.Build import android.view.ViewConfiguration import android.view.animation.AnimationUtils import android.view.animation.Interpolator import kotlin.math.* /** * * This class encapsulates scrolling. You can use scrollers ([Scroller] * to collect the data you need to produce a scrolling animationfor * example, in response to a fling gesture. Scrollers track scroll offsets * for you over time, but they don't automatically apply those positions * to your view. It's your responsibility to get and apply new coordinates * at a rate that will make the scrolling animation look smooth. * * * Here is a simple example: * * <pre> private Scroller mScroller = new Scroller(context); * ... * public void zoomIn() { * // Revert any animation currently in progress * mScroller.forceFinished(true); * // Start scrolling by providing a starting point and * // the distance to travel * mScroller.startScroll(0, 0, 100, 0); * // Invalidate to request a redraw * invalidate(); * }</pre> * * * To track the changing positions of the x/y coordinates, use * [.computeScrollOffset]. The method returns a boolean to indicate * whether the scroller is finished. If it isn't, it means that a fling or * programmatic pan operation is still in progress. You can use this method to * find the current offsets of the x and y coordinates, for example: * * <pre>if (mScroller.computeScrollOffset()) { * // Get current x and y positions * int currX = mScroller.getCurrX(); * int currY = mScroller.getCurrY(); * ... * }</pre> */ class Scroller /** * Create a Scroller with the specified interpolator. If the interpolator is * null, the default (viscous) interpolator will be used. Specify whether or * not to support progressive "flywheel" behavior in flinging. */ @JvmOverloads constructor(context: Context, interpolator: Interpolator? = null, private val mFlywheel: Boolean = context.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) { private val mInterpolator: Interpolator private var mMode: Int = 0 /** * Returns the start X offset in the scroll. * * @return The start X offset as an absolute distance from the origin. */ var startX: Int = 0 private set /** * Returns the start Y offset in the scroll. * * @return The start Y offset as an absolute distance from the origin. */ var startY: Int = 0 private set private var mFinalX: Int = 0 private var mFinalY: Int = 0 private var mMinX: Int = 0 private var mMaxX: Int = 0 private var mMinY: Int = 0 private var mMaxY: Int = 0 /** * Returns the current X offset in the scroll. * * @return The new X offset as an absolute distance from the origin. */ var currX: Int = 0 private set /** * Returns the current Y offset in the scroll. * * @return The new Y offset as an absolute distance from the origin. */ var currY: Int = 0 private set private var mStartTime: Long = 0 /** * Returns how long the scroll event will take, in milliseconds. * * @return The duration of the scroll in milliseconds. */ private var duration: Int = 0 private var mDurationReciprocal: Float = 0.toFloat() private var mDeltaX: Float = 0.toFloat() private var mDeltaY: Float = 0.toFloat() /** * * Returns whether the scroller has finished scrolling. * * @return True if the scroller has finished scrolling, false otherwise. */ var isFinished: Boolean = false private set private var mVelocity: Float = 0.toFloat() private var mCurrVelocity: Float = 0.toFloat() private var mDistance: Int = 0 private var mFlingFriction = ViewConfiguration.getScrollFriction() private var mDeceleration: Float = 0.toFloat() private val mPpi: Float // A context-specific coefficient adjusted to physical values. private val mPhysicalCoeff: Float /** * Returns the current velocity. * * @return The original velocity less the deceleration. Result may be * negative. */ private val currVelocity: Float get() = if (mMode == FLING_MODE) mCurrVelocity else mVelocity - mDeceleration * timePassed() / 2000.0f /** * Returns where the scroll will end. Valid only for "fling" scrolls. * * @return The final X offset as an absolute distance from the origin. */ /** * Sets the final position (X) for this scroller. * * @see .extendDuration * @see .setFinalY */ var finalX: Int get() = mFinalX set(newX) { mFinalX = newX mDeltaX = (mFinalX - startX).toFloat() isFinished = false } /** * Returns where the scroll will end. Valid only for "fling" scrolls. * * @return The final Y offset as an absolute distance from the origin. */ /** * Sets the final position (Y) for this scroller. * * @see .extendDuration * @see .setFinalX */ var finalY: Int get() = mFinalY set(newY) { mFinalY = newY mDeltaY = (mFinalY - startY).toFloat() isFinished = false } init { isFinished = true if (interpolator == null) { mInterpolator = ViscousFluidInterpolator() } else { mInterpolator = interpolator } mPpi = context.resources.displayMetrics.density * 160.0f mDeceleration = computeDeceleration(ViewConfiguration.getScrollFriction()) mPhysicalCoeff = computeDeceleration(0.84f) // look and feel tuning } /** * The amount of friction applied to flings. The default value * is [ViewConfiguration.getScrollFriction]. * * @param friction A scalar dimension-less value representing the coefficient of * friction. */ /* fun setFriction(friction: Float) { mDeceleration = computeDeceleration(friction) mFlingFriction = friction } */ private fun computeDeceleration(friction: Float): Float { return (SensorManager.GRAVITY_EARTH // g (m/s^2) * 39.37f // inch/meter * mPpi // pixels per inch * friction) } /** * Force the finished field to a particular value. * * @param finished The new finished value. */ fun forceFinished(finished: Boolean) { isFinished = finished } /** * Call this when you want to know the new location. If it returns true, * the animation is not yet finished. */ fun computeScrollOffset(): Boolean { if (isFinished) { return false } val timePassed = (AnimationUtils.currentAnimationTimeMillis() - mStartTime).toInt() if (timePassed < duration) { when (mMode) { SCROLL_MODE -> { val x = mInterpolator.getInterpolation(timePassed * mDurationReciprocal) currX = startX + (x * mDeltaX).roundToInt() currY = startY + (x * mDeltaY).roundToInt() } FLING_MODE -> { val t = timePassed.toFloat() / duration val index = (NB_SAMPLES * t).toInt() var distanceCoef = 1f var velocityCoef = 0f if (index < NB_SAMPLES) { val tInf = index.toFloat() / NB_SAMPLES val tSup = (index + 1).toFloat() / NB_SAMPLES val dInf = SPLINE_POSITION[index] val dSup = SPLINE_POSITION[index + 1] velocityCoef = (dSup - dInf) / (tSup - tInf) distanceCoef = dInf + (t - tInf) * velocityCoef } mCurrVelocity = velocityCoef * mDistance / duration * 1000.0f currX = startX + (distanceCoef * (mFinalX - startX)).roundToInt() // Pin to mMinX <= mCurrX <= mMaxX currX = min(currX, mMaxX) currX = max(currX, mMinX) currY = startY + (distanceCoef * (mFinalY - startY)).roundToInt() // Pin to mMinY <= mCurrY <= mMaxY currY = min(currY, mMaxY) currY = max(currY, mMinY) if (currX == mFinalX && currY == mFinalY) { isFinished = true } } } } else { currX = mFinalX currY = mFinalY isFinished = true } return true } /** * Start scrolling by providing a starting point, the distance to travel, * and the duration of the scroll. * * @param startX Starting horizontal scroll offset in pixels. Positive * numbers will scroll the content to the left. * @param startY Starting vertical scroll offset in pixels. Positive numbers * will scroll the content up. * @param dx Horizontal distance to travel. Positive numbers will scroll the * content to the left. * @param dy Vertical distance to travel. Positive numbers will scroll the * content up. * @param duration Duration of the scroll in milliseconds. */ @JvmOverloads fun startScroll(startX: Int, startY: Int, dx: Int, dy: Int, duration: Int = DEFAULT_DURATION) { mMode = SCROLL_MODE isFinished = false this.duration = duration mStartTime = AnimationUtils.currentAnimationTimeMillis() this.startX = startX this.startY = startY mFinalX = startX + dx mFinalY = startY + dy mDeltaX = dx.toFloat() mDeltaY = dy.toFloat() mDurationReciprocal = 1.0f / this.duration.toFloat() } /** * Start scrolling based on a fling gesture. The distance travelled will * depend on the initial velocity of the fling. * * @param startX Starting point of the scroll (X) * @param startY Starting point of the scroll (Y) * @param velocityX Initial velocity of the fling (X) measured in pixels per * second. * @param velocityY Initial velocity of the fling (Y) measured in pixels per * second * @param minX Minimum X value. The scroller will not scroll past this * point. * @param maxX Maximum X value. The scroller will not scroll past this * point. * @param minY Minimum Y value. The scroller will not scroll past this * point. * @param maxY Maximum Y value. The scroller will not scroll past this * point. */ fun fling(startX: Int, startY: Int, velocityX: Int, velocityY: Int, minX: Int, maxX: Int, minY: Int, maxY: Int) { var velocityX2 = velocityX var velocityY2 = velocityY // Continue a scroll or fling in progress if (mFlywheel && !isFinished) { val oldVel = currVelocity val dx = (mFinalX - this.startX).toFloat() val dy = (mFinalY - this.startY).toFloat() val hyp = hypot(dx.toDouble(), dy.toDouble()).toFloat() val ndx = dx / hyp val ndy = dy / hyp val oldVelocityX = ndx * oldVel val oldVelocityY = ndy * oldVel if (sign(velocityX2.toFloat()) == sign(oldVelocityX) && sign(velocityY2.toFloat()) == sign(oldVelocityY)) { velocityX2 += oldVelocityX.toInt() velocityY2 += oldVelocityY.toInt() } } mMode = FLING_MODE isFinished = false val velocity = hypot(velocityX.toDouble(), velocityY.toDouble()).toFloat() mVelocity = velocity duration = getSplineFlingDuration(velocity) mStartTime = AnimationUtils.currentAnimationTimeMillis() this.startX = startX this.startY = startY val coeffX = if (velocity == 0f) 1.0f else velocityX / velocity val coeffY = if (velocity == 0f) 1.0f else velocityY / velocity val totalDistance = getSplineFlingDistance(velocity) mDistance = (totalDistance * sign(velocity)).toInt() mMinX = minX mMaxX = maxX mMinY = minY mMaxY = maxY mFinalX = startX + (totalDistance * coeffX).roundToLong().toInt() // Pin to mMinX <= mFinalX <= mMaxX mFinalX = min(mFinalX, mMaxX) mFinalX = max(mFinalX, mMinX) mFinalY = startY + (totalDistance * coeffY).roundToLong().toInt() // Pin to mMinY <= mFinalY <= mMaxY mFinalY = min(mFinalY, mMaxY) mFinalY = max(mFinalY, mMinY) } private fun getSplineDeceleration(velocity: Float): Double { return ln((INFLEXION * abs(velocity) / (mFlingFriction * mPhysicalCoeff)).toDouble()) } private fun getSplineFlingDuration(velocity: Float): Int { val l = getSplineDeceleration(velocity) val decelMinusOne = DECELERATION_RATE - 1.0 return (1000.0 * exp(l / decelMinusOne)).toInt() } private fun getSplineFlingDistance(velocity: Float): Double { val l = getSplineDeceleration(velocity) val decelMinusOne = DECELERATION_RATE - 1.0 return mFlingFriction.toDouble() * mPhysicalCoeff.toDouble() * exp(DECELERATION_RATE / decelMinusOne * l) } /** * Stops the animation. Contrary to [.forceFinished], * aborting the animating cause the scroller to move to the final x and y * position * * @see .forceFinished */ /* fun abortAnimation() { currX = mFinalX currY = mFinalY isFinished = true } */ /** * Extend the scroll animation. This allows a running animation to scroll * further and longer, when used with [.setFinalX] or [.setFinalY]. * * @see .setFinalX * @see .setFinalY */ /* fun extendDuration(extend: Int) { val passed = timePassed() duration = passed + extend mDurationReciprocal = 1.0f / duration isFinished = false } */ /** * Returns the time elapsed since the beginning of the scrolling. * * @return The elapsed time in milliseconds. */ private fun timePassed(): Int { return (AnimationUtils.currentAnimationTimeMillis() - mStartTime).toInt() } /** * @hide */ /* fun isScrollingInDirection(xvel: Float, yvel: Float): Boolean { return !isFinished && Math.signum(xvel) == Math.signum((mFinalX - startX).toFloat()) && Math.signum(yvel) == Math.signum((mFinalY - startY).toFloat()) } */ internal class ViscousFluidInterpolator : Interpolator { override fun getInterpolation(input: Float): Float { val interpolated = VISCOUS_FLUID_NORMALIZE * viscousFluid(input) return if (interpolated > 0) { interpolated + VISCOUS_FLUID_OFFSET } else interpolated } companion object { /** Controls the viscous fluid effect (how much of it). */ private const val VISCOUS_FLUID_SCALE = 8.0f private val VISCOUS_FLUID_NORMALIZE: Float private val VISCOUS_FLUID_OFFSET: Float init { // must be set to 1.0 (used in viscousFluid()) VISCOUS_FLUID_NORMALIZE = 1.0f / viscousFluid(1.0f) // account for very small floating-point error VISCOUS_FLUID_OFFSET = 1.0f - VISCOUS_FLUID_NORMALIZE * viscousFluid(1.0f) } private fun viscousFluid(x: Float): Float { var x2 = x x2 *= VISCOUS_FLUID_SCALE if (x2 < 1.0f) { x2 -= 1.0f - exp((-x2).toDouble()).toFloat() } else { val start = 0.36787944117f // 1/e == exp(-1) x2 = 1.0f - exp((1.0f - x2).toDouble()).toFloat() x2 = start + x2 * (1.0f - start) } return x2 } } } companion object { private const val DEFAULT_DURATION = 250 private const val SCROLL_MODE = 0 private const val FLING_MODE = 1 private val DECELERATION_RATE = (ln(0.78) / ln(0.9)).toFloat() private const val INFLEXION = 0.35f // Tension lines cross at (INFLEXION, 1) private const val START_TENSION = 0.5f private const val END_TENSION = 1.0f private const val P1 = START_TENSION * INFLEXION private const val P2 = 1.0f - END_TENSION * (1.0f - INFLEXION) private const val NB_SAMPLES = 100 private val SPLINE_POSITION = FloatArray(NB_SAMPLES + 1) private val SPLINE_TIME = FloatArray(NB_SAMPLES + 1) init { var xMin = 0.0f var yMin = 0.0f for (i in 0 until NB_SAMPLES) { val alpha = i.toFloat() / NB_SAMPLES var xMax = 1.0f var x: Float var tx: Float var coef: Float while (true) { x = xMin + (xMax - xMin) / 2.0f coef = 3.0f * x * (1.0f - x) tx = coef * ((1.0f - x) * P1 + x * P2) + x * x * x if (abs(tx - alpha) < 1E-5) break if (tx > alpha) xMax = x else xMin = x } SPLINE_POSITION[i] = coef * ((1.0f - x) * START_TENSION + x) + x * x * x var yMax = 1.0f var y: Float var dy: Float while (true) { y = yMin + (yMax - yMin) / 2.0f coef = 3.0f * y * (1.0f - y) dy = coef * ((1.0f - y) * START_TENSION + y) + y * y * y if (abs(dy - alpha) < 1E-5) break if (dy > alpha) yMax = y else yMin = y } SPLINE_TIME[i] = coef * ((1.0f - y) * P1 + y * P2) + y * y * y } SPLINE_TIME[NB_SAMPLES] = 1.0f SPLINE_POSITION[NB_SAMPLES] = SPLINE_TIME[NB_SAMPLES] } } } /** * Create a Scroller with the default duration and interpolator. */ /** * Create a Scroller with the specified interpolator. If the interpolator is * null, the default (viscous) interpolator will be used. "Flywheel" behavior will * be in effect for apps targeting Honeycomb or newer. */ /** * Start scrolling by providing a starting point and the distance to travel. * The scroll will use the default value of 250 milliseconds for the * duration. * */
1
Kotlin
68
9
61cbb5799bba74342b342cd98680286a96f27f70
19,665
fluentui-android
MIT License
kotest-core/src/commonMain/kotlin/io/kotest/core/specs/AbstractFeatureSpec.kt
junron
214,570,871
false
null
package io.kotest.core.specs import io.kotest.Tag import io.kotest.TestType import io.kotest.core.TestCaseConfig import io.kotest.core.TestContext import io.kotest.extensions.TestCaseExtension import kotlin.time.Duration import kotlin.time.ExperimentalTime abstract class AbstractFeatureSpec(body: AbstractFeatureSpec.() -> Unit = {}) : AbstractSpecDsl() { init { body() } inner class ScenarioBuilder(val name: String, val context: TestContext) { @UseExperimental(ExperimentalTime::class) suspend fun config( invocations: Int? = null, enabled: Boolean? = null, timeout: Duration? = null, threads: Int? = null, tags: Set<Tag>? = null, extensions: List<TestCaseExtension>? = null, test: suspend TestContext.() -> Unit) { val config = TestCaseConfig( enabled ?: defaultTestCaseConfig.enabled, invocations ?: defaultTestCaseConfig.invocations, timeout ?: defaultTestCaseConfig.timeout, threads ?: defaultTestCaseConfig.threads, tags ?: defaultTestCaseConfig.tags, extensions ?: defaultTestCaseConfig.extensions) context.registerTestCase(name, this@AbstractFeatureSpec, test, config, TestType.Test) } } fun feature(name: String, init: suspend FeatureScope.() -> Unit) = addTestCase(createTestName("Feature: ", name), { [email protected](this).init() }, defaultTestCaseConfig, TestType.Container) @KotestDsl inner class FeatureScope(val context: TestContext) { suspend fun and(name: String, init: suspend FeatureScope.() -> Unit) = context.registerTestCase(createTestName("And: ", name), this@AbstractFeatureSpec, { [email protected](this).init() }, [email protected], TestType.Container) suspend fun scenario(name: String, test: suspend TestContext.() -> Unit) = context.registerTestCase(createTestName("Scenario: ", name), this@AbstractFeatureSpec, test, [email protected], TestType.Test) fun scenario(name: String) = [email protected](createTestName("Scenario: ", name), context) } }
1
null
1
1
3a00e967d50a43e6200060f7c3df44c730d02610
2,377
kotlintest
Apache License 2.0
hmpps-prisoner-search-indexer/src/main/kotlin/uk/gov/justice/digital/hmpps/prisonersearch/indexer/health/OpenSearchHealthIndicator.kt
ministryofjustice
636,804,116
false
null
package uk.gov.justice.digital.hmpps.prisonersearch.indexer.health import org.springframework.boot.actuate.health.AbstractHealthIndicator import org.springframework.boot.actuate.health.Health import org.springframework.boot.actuate.health.Status import org.springframework.data.elasticsearch.core.ElasticsearchOperations import org.springframework.data.elasticsearch.core.cluster.ClusterHealth import org.springframework.stereotype.Component @Component class OpenSearchHealthIndicator(private val template: ElasticsearchOperations) : AbstractHealthIndicator() { override fun doHealthCheck(builder: Health.Builder): Unit = processResponse(builder, template.cluster().health()) private fun processResponse(builder: Health.Builder, response: ClusterHealth) { if (response.isTimedOut) { builder.down().build() } else { val status = response.status builder.status(if (status == "RED") Status.OUT_OF_SERVICE else Status.UP) builder.withDetail("cluster_name", response.clusterName) builder.withDetail("status", response.status) builder.withDetail("timed_out", response.isTimedOut) builder.withDetail("number_of_nodes", response.numberOfNodes) builder.withDetail("number_of_data_nodes", response.numberOfDataNodes) builder.withDetail("active_primary_shards", response.activePrimaryShards) builder.withDetail("active_shards", response.activeShards) builder.withDetail("relocating_shards", response.relocatingShards) builder.withDetail("initializing_shards", response.initializingShards) builder.withDetail("unassigned_shards", response.unassignedShards) builder.withDetail("delayed_unassigned_shards", response.delayedUnassignedShards) builder.withDetail("number_of_pending_tasks", response.numberOfPendingTasks) builder.withDetail("number_of_in_flight_fetch", response.numberOfInFlightFetch) builder.withDetail("task_max_waiting_in_queue_millis", response.taskMaxWaitingTimeMillis) builder.withDetail("active_shards_percent_as_number", response.activeShardsPercent) builder.build() } } }
2
null
1
2
2ac87f7349d61e3d274bcb20b11be285c5a50700
2,119
hmpps-prisoner-search
MIT License
quickseq-plugin/src/test/kotlin/com/kiwi/quickseq/LogLineConversionTest.kt
jon-kroko
552,961,469
false
{"Kotlin": 104022, "Shell": 126}
/* * Copyright (C) 2021 Kira Weinlein * * 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.kiwi.quickseq import com.kiwi.quickseq.QuickSeqLogLine.Companion.callMarker import com.kiwi.quickseq.QuickSeqLogLine.Companion.diagramStartMarker import com.kiwi.quickseq.QuickSeqLogLine.Companion.functionNameMarker import com.kiwi.quickseq.QuickSeqLogLine.Companion.leftClassMarker import com.kiwi.quickseq.QuickSeqLogLine.Companion.notAnnotatedMarker import com.kiwi.quickseq.QuickSeqLogLine.Companion.returnMarker import com.kiwi.quickseq.QuickSeqLogLine.Companion.rightClassMarker import org.gradle.internal.impldep.org.testng.AssertJUnit.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class LogLineConversionTest { @BeforeEach fun setup() = clearGeneratedFiles() @Test fun `should convert diagram start to LogLine correctly`() { val diagramStartLine = QuickSeqLogLine("$diagramStartMarker My Title") assert(diagramStartLine.isAnnotated == true) assert(diagramStartLine.isCall == false) assert(diagramStartLine.isReturn == false) assert(diagramStartLine.isSilentReturn == false) assert(diagramStartLine.isDiagramStart == true) assert(diagramStartLine.isDiagramEnd == false) assert(diagramStartLine.parameterNames == null) assert(diagramStartLine.returnType == null) assert(diagramStartLine.diagramTitle == "My Title") assert(diagramStartLine.functionName == null) assert(diagramStartLine.leftClass == null) assert(diagramStartLine.rightClass == null) assert(diagramStartLine.activationLine == null) assert(diagramStartLine.toPlantUmlLine() == null) } @Test fun `should convert call to LogLine correctly`() { val callLine = QuickSeqLogLine("$notAnnotatedMarker $callMarker param1, param2 $leftClassMarker LeftClass $rightClassMarker RightClass $functionNameMarker foo") assert(callLine.isAnnotated == false) assert(callLine.isCall == true) assert(callLine.isReturn == false) assert(callLine.isSilentReturn == false) assert(callLine.isDiagramStart == false) assert(callLine.isDiagramEnd == false) assert(callLine.parameterNames == listOf("param1", "param2")) assert(callLine.returnType == null) assert(callLine.diagramTitle == null) assert(callLine.functionName == "foo") assert(callLine.leftClass == "LeftClass") assert(callLine.rightClass == "RightClass") assert(callLine.activationLine == "activate RightClass\n") assertEquals( "LeftClass -> RightClass: foo(<font size=10> param1, param2 <font size=13>)\n", callLine.toPlantUmlLine() ) } @Test fun `should convert return to LogLine correctly`() { val returnLine = QuickSeqLogLine("$returnMarker kotlin.Int $leftClassMarker LeftClass $rightClassMarker RightClass $functionNameMarker foo()") assert(returnLine.isAnnotated == true) assert(returnLine.isCall == false) assert(returnLine.isReturn == true) assert(returnLine.isSilentReturn == false) assert(returnLine.isDiagramStart == false) assert(returnLine.isDiagramEnd == false) assert(returnLine.parameterNames == null) assert(returnLine.returnType == "Int") assert(returnLine.diagramTitle == null) assert(returnLine.functionName == "foo()") assert(returnLine.leftClass == "LeftClass") assert(returnLine.rightClass == "RightClass") assert(returnLine.activationLine == "deactivate RightClass\n") assertEquals( "LeftClass <-- RightClass: <font color=AAAAAA><b>Int</b> <font size=10>by foo()\n", returnLine.toPlantUmlLine() ) } @Test fun `should trim return type correctly`() { var returnLine = QuickSeqLogLine("$returnMarker kotlin.Int") assertEquals("Int", returnLine.returnType) returnLine = QuickSeqLogLine("$returnMarker kotlin.collections.Map<kotlin.String, kotlin.Int>") assertEquals("Map<kotlin.String, kotlin.Int>", returnLine.returnType) returnLine = QuickSeqLogLine("$returnMarker kotlin.collections.Map<kotlin.String, kotlin.collections.Map<kotlin.String, kotlin.Int>>") assertEquals("Map<kotlin.String, kotlin.collections.Map<kotlin.String, kotlin.Int>>", returnLine.returnType) } }
0
Kotlin
0
0
7b9521a1842c9aca7b2d4ab0a4c0c351d46ec2d5
4,989
quickseq
Apache License 2.0
app/src/main/java/com/edricchan/studybuddy/providers/fcm/StudyBuddyMessagingService.kt
EdricChan03
100,260,817
false
{"Kotlin": 693890, "Ruby": 202}
package com.edricchan.studybuddy.providers.fcm import android.app.PendingIntent import android.content.Intent import android.content.res.Resources import android.graphics.Color import android.graphics.drawable.BitmapDrawable import android.os.Build import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import coil.imageLoader import coil.request.ImageRequest import com.edricchan.studybuddy.R import com.edricchan.studybuddy.constants.Constants import com.edricchan.studybuddy.core.resources.notification.AppNotificationChannel import com.edricchan.studybuddy.exts.android.buildIntent import com.edricchan.studybuddy.exts.common.TAG import com.edricchan.studybuddy.interfaces.NotificationAction import com.edricchan.studybuddy.ui.modules.main.MainActivity import com.edricchan.studybuddy.ui.modules.settings.SettingsActivity import com.edricchan.studybuddy.ui.theming.dynamicColorPrimary import com.edricchan.studybuddy.utils.NotificationUtils import com.google.firebase.auth.ktx.auth import com.google.firebase.crashlytics.ktx.crashlytics import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import kotlinx.serialization.json.Json class StudyBuddyMessagingService : FirebaseMessagingService() { private val notificationUtils = NotificationUtils.getInstance() override fun onMessageReceived(remoteMessage: RemoteMessage) { super.onMessageReceived(remoteMessage) val manager = NotificationManagerCompat.from(this) val builder = NotificationCompat.Builder( this, AppNotificationChannel.Uncategorized.channelId ) if (remoteMessage.notification != null) { if (remoteMessage.notification?.title != null) { builder.setContentTitle(remoteMessage.notification?.title) builder.setStyle( NotificationCompat.BigTextStyle().bigText(remoteMessage.notification?.body) ) } if (remoteMessage.notification?.body != null) { builder.setContentText(remoteMessage.notification?.body) } if (remoteMessage.notification?.icon != null) { val icon = resources.getIdentifier( remoteMessage.notification?.icon, "drawable", packageName ) // getIdentifier returns Resources.ID_NULL (0) if not such identifier exists if (icon != Resources.ID_NULL) { builder.setSmallIcon(icon) } else { // Use the default icon builder.setSmallIcon(R.drawable.ic_notification_studybuddy_pencil_24dp) } } else { // Use the default icon builder.setSmallIcon(R.drawable.ic_notification_studybuddy_pencil_24dp) } builder.color = if (remoteMessage.notification?.color != null) { Color.parseColor(remoteMessage.notification?.color) } else { // Use the default color dynamicColorPrimary } // Image support was added in FCM 20.0.0 if (remoteMessage.notification?.imageUrl != null) { val loader = applicationContext.imageLoader val req = ImageRequest.Builder(this) .data(remoteMessage.notification?.imageUrl) .target { result -> val bitmap = (result as BitmapDrawable).bitmap builder.setLargeIcon(bitmap) builder.setStyle( NotificationCompat.BigPictureStyle() .bigPicture(bitmap) ) } .build() loader.enqueue(req) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (remoteMessage.notification?.channelId != null) { if (manager.getNotificationChannel(remoteMessage.notification?.channelId!!) == null) { Log.w( TAG, "No such notification channel ${remoteMessage.notification?.channelId} exists." + "Assigning \"uncategorised\" channel." ) builder.setChannelId(AppNotificationChannel.Uncategorized.channelId) } else { builder.setChannelId(remoteMessage.notification?.channelId!!) } } } } if (remoteMessage.data["notificationActions"] != null) { Log.d(TAG, "notificationActions: ${remoteMessage.data["notificationActions"]}") var notificationActions: List<NotificationAction> = listOf() try { notificationActions = remoteMessage.data["notificationActions"]?.let { Json.decodeFromString(it) } ?: listOf() } catch (e: Exception) { Log.e(TAG, "Could not parse notification actions:", e) Firebase.crashlytics.recordException(e) } for (notificationAction in notificationActions) { // This property is set to 0 by default to indicate that no such icon exists var icon = 0 val intent: Intent var notificationPendingIntent: PendingIntent? = null val drawableIcon = resources.getIdentifier( notificationAction.icon, "drawable", packageName ) // getIdentifier returns Resources.ID_NULL (0) if no such resource exists if (drawableIcon != Resources.ID_NULL) { icon = drawableIcon } when (notificationAction.type) { // TODO: Don't hardcode action types Constants.actionNotificationsSettingsIntent -> { intent = buildIntent<SettingsActivity>(this) { flags = Intent.FLAG_ACTIVITY_CLEAR_TOP } notificationPendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_ONE_SHOT ) } else -> Log.w( TAG, "Unknown action type ${notificationAction.type} specified for $notificationAction." ) } builder.addAction( NotificationCompat.Action( icon, notificationAction.title, notificationPendingIntent ) ) } } val mainActivityIntent = buildIntent<MainActivity>(this) { flags = Intent.FLAG_ACTIVITY_CLEAR_TOP } val mainPendingIntent = PendingIntent.getActivity(this, 0, mainActivityIntent, PendingIntent.FLAG_ONE_SHOT) builder.setContentIntent(mainPendingIntent) manager.notify(notificationUtils.incrementAndGetId(), builder.build()) } override fun onNewToken(token: String) { Log.d(TAG, "Refreshed token: $token") // Add token to Firebase Firestore in the user's document val fs = Firebase.firestore val auth = Firebase.auth if (auth.currentUser != null) { fs.document("users/${auth.currentUser?.uid}") .update("registrationToken", token) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "Successfully updated token!") } else { Log.e( TAG, "An error occurred while attempting to update the token:", task.exception ) } } } else { Log.w(TAG, "There's currently no logged in user! Skipping document update.") } } }
8
Kotlin
8
9
f3bd7d548380f727e8bffc6c0608b0a8e1dd17bd
8,628
studybuddy-android
MIT License
app/src/main/java/gr/pchasapis/moviedb/mvvm/interactor/home/HomeInteractorImpl.kt
pandelisgreen13
210,415,019
false
null
package br.ifsp.moviedb.mvvm.interactor.home import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import br.ifsp.moviedb.common.Definitions import br.ifsp.moviedb.database.MovieDbDatabase import br.ifsp.moviedb.model.common.DataResult import br.ifsp.moviedb.model.data.HomeDataModel import br.ifsp.moviedb.model.data.MovieDataModel import br.ifsp.moviedb.model.mappers.HomeDataModelMapperImpl import br.ifsp.moviedb.model.parsers.search.SearchResponse import br.ifsp.moviedb.model.parsers.theatre.TheatreResponse import br.ifsp.moviedb.mvvm.interactor.base.BaseInteractor import br.ifsp.moviedb.mvvm.interactor.home.paging.SearchPagingDataSource import br.ifsp.moviedb.network.client.MovieClient import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import timber.log.Timber class HomeInteractorImpl( private var movieClient: MovieClient, private val movieDbDatabase: MovieDbDatabase, private val mapper: HomeDataModelMapperImpl ) : BaseInteractor(), HomeInteractor { override suspend fun onRetrieveSearchResult( queryText: String, page: Int ): Flow<DataResult<List<HomeDataModel>>> { return try { val response = movieClient.getSearchAsync(queryText, page) flow { emit(DataResult(toHomeDataModel(response))) } } catch (t: Throwable) { Timber.d(t) flow { DataResult(null, throwable = t) } } } override suspend fun getMoviesInTheatres(): DataResult<List<MovieDataModel>> { return try { val response = movieClient.getMovieTheatre(DATE_FROM, DATE_TO) DataResult(toMovieDataModel(response)) } catch (t: Throwable) { Timber.d(t) DataResult(throwable = t) } } override suspend fun flowPaging(queryText: String): Flow<PagingData<HomeDataModel>> { return Pager( // Configure how data is loaded by passing additional properties to // PagingConfig, such as prefetchDistance. PagingConfig( pageSize = 20 ) ) { SearchPagingDataSource(queryText, movieClient, mapper) }.flow } private fun toHomeDataModel(searchResponse: SearchResponse): List<HomeDataModel> { return (searchResponse.searchResultsList?.map { searchItem -> HomeDataModel( id = searchItem.id, title = searchItem.title ?: searchItem.name ?: searchItem.originalName ?: "-", mediaType = searchItem.mediaType ?: "-", summary = searchItem.overview ?: "-", thumbnail = "${Definitions.IMAGE_URL_W300}${searchItem.posterPath}", releaseDate = searchItem.releaseDate ?: searchItem.firstAirDate ?: "-", ratings = (searchItem.voteAverage ?: 0).toString(), page = searchResponse.page ?: 0, totalPage = searchResponse.totalPages ?: 0, isFavorite = movieDbDatabase.movieDbTableDao().isFavourite(searchItem.id ?: 0) ) } ?: arrayListOf()) } private fun toMovieDataModel(theatreResponse: TheatreResponse): List<MovieDataModel> { return (theatreResponse.searchResultsList?.map { movieItem -> MovieDataModel( id = movieItem.id, title = movieItem.title ?: "-", summary = movieItem.overview ?: "-", thumbnail = "${Definitions.IMAGE_URL_W300}${movieItem.posterPath}", releaseDate = movieItem.releaseDate ?: "-" ) } ?: arrayListOf()) } companion object { const val DATE_FROM = "2019-12-22" const val DATE_TO = "2019-12-31" } }
0
null
0
5
8f247cd825f5e1e68f135e206dea3c2ddd6a6a30
3,817
movieDB
MIT License
src/main/kotlin/de/tweerlei/plumber/pipeline/steps/text/UuidStep.kt
tweerlei
450,150,451
false
null
/* * Copyright 2022 tweerlei Wruck + Buchmeier GbR - http://www.tweerlei.de/ * * 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 de.tweerlei.plumber.pipeline.steps.text import de.tweerlei.plumber.pipeline.PipelineParams import de.tweerlei.plumber.pipeline.options.AllPipelineOptions import de.tweerlei.plumber.pipeline.steps.ProcessingStep import de.tweerlei.plumber.worker.Worker import de.tweerlei.plumber.worker.impl.text.UUIDWorker import org.springframework.stereotype.Service @Service("uuidWorker") class UuidStep: ProcessingStep { override val group = "Text" override val name = "Generate UUIDs" override val description = "Generate random UUIDs" override val help = "" override val options = "" override val example = """ uuid --${AllPipelineOptions.INSTANCE.maxFilesPerThread.name}=1 lines-write # result: 563de642-9a29-4804-b13c-1d5b129b47f6 """.trimIndent() override val argDescription = "" override val argInterpolated = false override fun createWorker( arg: String, w: Worker, predecessorName: String, params: PipelineParams, parallelDegree: Int ) = UUIDWorker(params.maxFilesPerThread, w) }
0
Kotlin
0
2
fe9dc936f9e76faead5f2a7e6ff5c027e1152615
1,736
plumber
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsalertsapi/common/LocalDateExtTest.kt
ministryofjustice
750,461,021
false
{"Kotlin": 272432, "Shell": 1799, "Mermaid": 1398, "Dockerfile": 1372}
package uk.gov.justice.digital.hmpps.hmppsalertsapi.common import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import java.time.LocalDate class LocalDateExtTest { @Nested @DisplayName("onOrBefore") inner class OnOrBefore { @Test fun `returns true if date is on`() { val date = LocalDate.of(2022, 1, 1) assertThat(date.onOrBefore(date)).isTrue() } @Test fun `returns true if date is before`() { val date = LocalDate.of(2022, 1, 1) val dayAfter = date.plusDays(1) assertThat(date.onOrBefore(dayAfter)).isTrue() } @Test fun `returns false if date is after`() { val date = LocalDate.of(2022, 1, 1) val dayBefore = date.minusDays(1) assertThat(date.onOrBefore(dayBefore)).isFalse() } } @Nested @DisplayName("onOrAfter") inner class OnOrAfter { @Test fun `returns true if date is on`() { val date = LocalDate.of(2022, 1, 1) assertThat(date.onOrAfter(date)).isTrue() } @Test fun `returns true if date is after`() { val date = LocalDate.of(2022, 1, 1) val dayBefore = date.minusDays(1) assertThat(date.onOrAfter(dayBefore)).isTrue() } @Test fun `returns false if date is after`() { val date = LocalDate.of(2022, 1, 1) val dayAfter = date.plusDays(1) assertThat(date.onOrAfter(dayAfter)).isFalse() } } }
1
Kotlin
0
0
e2fc6e4788371ca2c59da5126d7f4a92cb9089d5
1,496
hmpps-alerts-api
MIT License
fountain-testutils/src/main/java/com/xmartlabs/fountain/testutils/IntCacheDataSourceFactory.kt
xmartlabs
135,512,692
false
null
package com.xmartlabs.fountain.testutils import android.arch.paging.DataSource import android.arch.paging.ItemKeyedDataSource internal class IntCacheDataSourceFactory : DataSource.Factory<Int, Int>() { private val items: MutableList<Int> = ArrayList() private lateinit var dataSource: MockIntDataSource private var created: Boolean = false fun clearData() { if (created) { dataSource.clearData() } } fun addData(items: List<Int>) { if (created) { dataSource.addData(items) } else { this.items.addAll(items) } } fun invalidate() { if (created) { dataSource.invalidate() } } override fun create(): DataSource<Int, Int> { created = true dataSource = MockIntDataSource(items) return dataSource } } class MockIntDataSource(private val items: MutableList<Int>) : ItemKeyedDataSource<Int, Int>() { fun clearData() = items.clear() fun addData(items: List<Int>) { this.items.addAll(items) if (this.items.distinct() != this.items) { throw IllegalStateException("There are duplicate elements") } } private fun inRange(position: Int, start: Int, end: Int): Int { return when { position < start -> start position > end -> end else -> position } } override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int>) { val firstItem = inRange(params.requestedInitialKey ?: 0, 0, items.size) val lastItem = inRange(firstItem + params.requestedLoadSize, 0, items.size) val data = if (firstItem == lastItem) emptyList<Int>() else items.subList(firstItem, lastItem) if (params.placeholdersEnabled) { callback.onResult(data, firstItem, items.size) } else { callback.onResult(data) } } override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int>) { val firstItem = inRange(params.key + 1, 0, items.size) val lastItem = inRange(firstItem + params.requestedLoadSize, 0, items.size) val data = if (firstItem == lastItem) emptyList<Int>() else items.subList(firstItem, lastItem) callback.onResult(data) } override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int>) { val lastItem = inRange(params.key, 0, items.size) val firstItem = inRange(lastItem - params.requestedLoadSize, 0, items.size) val data = if (firstItem == lastItem) emptyList<Int>() else items.subList(firstItem, lastItem) callback.onResult(data) } override fun getKey(item: Int): Int = items.indexOfFirst { it == item } }
0
Kotlin
8
174
3dfc4240eb0d2b12223b85f7f6c504e5a04558cc
2,559
fountain
MIT License
library-base/src/main/java/com/vicpin/krealmextensions/RealmExtensions.kt
vicpinm
77,839,704
false
null
@file:Suppress("unused") package com.existing.boilerx.realm import io.realm.* import java.lang.reflect.Field typealias Query<T> = RealmQuery<T>.() -> Unit /** * Created by victor on 2/1/17. * Extensions for Realm. All methods here are synchronous. */ /** * Query to the database with RealmQuery instance as argument */ fun <T : RealmModel> T.query(query: Query<T>): List<T> { getRealmInstance().use { realm -> val result = realm.where(javaClass).withQuery(query).findAll() return realm.copyFromRealm(result) } } /** * Query to the database with RealmQuery instance as argument */ inline fun <reified T : RealmModel> query(query: Query<T>): List<T> { getRealmInstance<T>().use { realm -> val result = realm.where(T::class.java).runQuery(query).findAll() return realm.copyFromRealm(result) } } /** * Query to the database with RealmQuery instance as argument and returns all items founded */ fun <T : RealmModel> T.queryAll(): List<T> { getRealmInstance().use { realm -> val result = realm.where(this.javaClass).findAll() return realm.copyFromRealm(result) } } inline fun <reified T : RealmModel> queryAll(): List<T> { getRealmInstance<T>().use { realm -> val result = realm.where(T::class.java).findAll() return realm.copyFromRealm(result) } } /** * Query to the database with RealmQuery instance as argument. Return first result, or null. */ fun <T : RealmModel> T.queryFirst(): T? { getRealmInstance().use { realm -> val item: T? = realm.where(this.javaClass).findFirst() return if (item != null && RealmObject.isValid(item)) realm.copyFromRealm(item) else null } } inline fun <reified T : RealmModel> queryFirst(): T? { getRealmInstance<T>().use { realm -> val item: T? = realm.where(T::class.java).findFirst() return if (item != null && RealmObject.isValid(item)) realm.copyFromRealm(item) else null } } /** * Query to the database with RealmQuery instance as argument. Return first result, or null. */ fun <T : RealmModel> T.queryFirst(query: Query<T>): T? { getRealmInstance().use { realm -> val item: T? = realm.where(this.javaClass).withQuery(query).findFirst() return if (item != null && RealmObject.isValid(item)) realm.copyFromRealm(item) else null } } inline fun <reified T : RealmModel> queryFirst(query: Query<T>): T? { getRealmInstance<T>().use { realm -> val item: T? = realm.where(T::class.java).runQuery(query).findFirst() return if (item != null && RealmObject.isValid(item)) realm.copyFromRealm(item) else null } } /** * Query to the database with RealmQuery instance as argument. Return last result, or null. */ fun <T : RealmModel> T.queryLast(): T? { getRealmInstance().use { realm -> val result = realm.where(this.javaClass).findAll() return if (result != null && result.isNotEmpty()) realm.copyFromRealm(result.last()) else null } } inline fun <reified T : RealmModel> queryLast(): T? { getRealmInstance<T>().use { realm -> val result: RealmResults<T> = realm.where(T::class.java).findAll() return if (result.isNotEmpty()) realm.copyFromRealm(result.last()) else null } } /** * Query to the database with RealmQuery instance as argument. Return last result, or null. */ fun <T : RealmModel> T.queryLast(query: Query<T>): T? { getRealmInstance().use { realm -> val result = realm.where(this.javaClass).withQuery(query).findAll() return if (result != null && result.isNotEmpty()) realm.copyFromRealm(result.last()) else null } } inline fun <reified T : RealmModel> queryLast(query: Query<T>): T? { getRealmInstance<T>().use { realm -> val result: RealmResults<T> = realm.where(T::class.java).runQuery(query).findAll() return if (result.isNotEmpty()) realm.copyFromRealm(result.last()) else null } } /** * Query to the database with RealmQuery instance as argument */ fun <T : RealmModel> T.querySorted(fieldName: String, order: Sort, query: Query<T>): List<T> { getRealmInstance().use { realm -> val result = realm.where(this.javaClass).withQuery(query).findAll().sort(fieldName, order) return realm.copyFromRealm(result) } } inline fun <reified T : RealmModel> querySorted(fieldName: String, order: Sort, query: Query<T>): List<T> { getRealmInstance<T>().use { realm -> val result = realm.where(T::class.java).runQuery(query).findAll().sort(fieldName, order) return realm.copyFromRealm(result) } } /** * Query to the database with a specific order and a RealmQuery instance as argument */ fun <T : RealmModel> T.querySorted(fieldName: List<String>, order: List<Sort>, query: Query<T>): List<T> { getRealmInstance().use { realm -> val result = realm.where(this.javaClass).withQuery(query).findAll().sort(fieldName.toTypedArray(), order.toTypedArray()) return realm.copyFromRealm(result) } } inline fun <reified T : RealmModel> querySorted(fieldName: List<String>, order: List<Sort>, query: Query<T>): List<T> { getRealmInstance<T>().use { realm -> val result = realm.where(T::class.java).runQuery(query).findAll().sort(fieldName.toTypedArray(), order.toTypedArray()) return realm.copyFromRealm(result) } } /** * Query to the database with a specific order */ fun <T : RealmModel> T.querySorted(fieldName: String, order: Sort): List<T> { getRealmInstance().use { realm -> val result = realm.where(this.javaClass).findAll().sort(fieldName, order) return realm.copyFromRealm(result) } } inline fun <reified T : RealmModel> querySorted(fieldName: String, order: Sort): List<T> { getRealmInstance<T>().use { realm -> val result = realm.where(T::class.java).findAll().sort(fieldName, order) return realm.copyFromRealm(result) } } /** * Query to the database with a specific order */ fun <T : RealmModel> T.querySorted(fieldName: List<String>, order: List<Sort>): List<T> { getRealmInstance().use { realm -> val result = realm.where(this.javaClass).findAll().sort(fieldName.toTypedArray(), order.toTypedArray()) return realm.copyFromRealm(result) } } inline fun <reified T : RealmModel> querySorted(fieldName: List<String>, order: List<Sort>): List<T> { getRealmInstance<T>().use { realm -> val result = realm.where(T::class.java).findAll().sort(fieldName.toTypedArray(), order.toTypedArray()) return realm.copyFromRealm(result) } } /** * Utility extension for modifying database. Create a transaction, run the function passed as argument, * commit transaction and close realm instance. */ fun Realm.transaction(action: (Realm) -> Unit) { use { if (!isInTransaction) { executeTransaction { action(this) } } else { action(this) } } } /** * Utility extension for modifying database. Create a transaction, run the function passed as argument, * and commit transaction. */ fun Realm.transactionManaged(action: (Realm) -> Unit) { if (!isInTransaction) { executeTransaction { action(this) } } else { action(this) } } fun executeTransaction(realm: Realm = Realm.getDefaultInstance(), transaction: (Realm) -> Unit) { realm.use { realm.executeTransaction { transaction(it) } } } /** * Creates a new entry in database. Usefull for RealmObject with no primary key. */ fun <T : RealmModel> T.create() { getRealmInstance().transaction { it.copyToRealm(this) } } /** * Creates a new entry in database. Useful for RealmObject with no primary key. * @return a managed version of a saved object */ fun <T : RealmModel> T.createManaged(realm: Realm): T { var result: T? = null realm.transactionManaged { result = it.copyToRealm(this) } return result!! } /** * Creates or updates a entry in database. Requires a RealmObject with primary key, or IllegalArgumentException will be thrown */ fun <T : RealmModel> T.createOrUpdate() { getRealmInstance().transaction { it.copyToRealmOrUpdate(this) } } /** * Creates or updates a entry in database. Requires a RealmObject with primary key, or IllegalArgumentException will be thrown * @return a managed version of a saved object */ fun <T : RealmModel> T.createOrUpdateManaged(realm: Realm): T { var result: T? = null realm.transactionManaged { result = it.copyToRealmOrUpdate(this) } return result!! } /** * Creates a new entry in database or updates an existing one. If entity has no primary key, always create a new one. * If has primary key, it tries to updates an existing one. */ fun <T : RealmModel> T.save() { getRealmInstance().transaction { realm -> if (isAutoIncrementPK()) { initPk(realm) } if (this.hasPrimaryKey(realm)) realm.copyToRealmOrUpdate(this) else realm.copyToRealm(this) } } /** * Creates a new entry in database or updates an existing one. If entity has no primary key, always create a new one. * If has primary key, it tries to update an existing one. * @return a managed version of a saved object */ inline fun <reified T : RealmModel> T.saveManaged(realm: Realm): T { var result: T? = null realm.transactionManaged { if (isAutoIncrementPK()) { initPk(realm) } result = if (this.hasPrimaryKey(it)) it.copyToRealmOrUpdate(this) else it.copyToRealm(this) } return result!! } inline fun <reified D : RealmModel, T : Collection<D>> T.saveAll() { if (size > 0) { getRealmInstance().transaction { realm -> if (first().isAutoIncrementPK()) { initPk(realm) } forEach { if (it.hasPrimaryKey(realm)) realm.copyToRealmOrUpdate(it) else realm.copyToRealm(it) } } } } inline fun <reified T : RealmModel> Collection<T>.saveAllManaged(realm: Realm): List<T> { val results = mutableListOf<T>() realm.transactionManaged { if (first().isAutoIncrementPK()) { initPk(realm) } forEach { results += if (it.hasPrimaryKey(realm)) realm.copyToRealmOrUpdate(it) else realm.copyToRealm(it) } } return results } inline fun <reified D : RealmModel> Array<D>.saveAll() { getRealmInstance().transaction { realm -> if (first().isAutoIncrementPK()) { initPk(realm) } forEach { if (it.hasPrimaryKey(realm)) realm.copyToRealmOrUpdate(it) else realm.copyToRealm(it) } } } inline fun <reified T : RealmModel> Array<T>.saveAllManaged(realm: Realm): List<T> { val results = mutableListOf<T>() realm.transactionManaged { if (first().isAutoIncrementPK()) { initPk(realm) } forEach { results += if (it.hasPrimaryKey(realm)) realm.copyToRealmOrUpdate(it) else realm.copyToRealm(it) } } return results } /** * Delete all entries of this type in database */ fun <T : RealmModel> T.deleteAll() { getRealmInstance().transaction { it.where(this.javaClass).findAll().deleteAllFromRealm() } } inline fun <reified T : RealmModel> deleteAll() { getRealmInstance<T>().transaction { it.where(T::class.java).findAll().deleteAllFromRealm() } } /** * Delete all entries returned by the specified query */ fun <T : RealmModel> T.delete(myQuery: Query<T>) { getRealmInstance().transaction { it.where(this.javaClass).withQuery(myQuery).findAll().deleteAllFromRealm() } } inline fun <reified T : RealmModel> delete(crossinline query: Query<T>) { getRealmInstance<T>().transaction { it.where(T::class.java).runQuery(query).findAll().deleteAllFromRealm() } } /** * Update first entry returned by the specified query */ inline fun <reified T : RealmModel> T.queryAndUpdate(noinline query: Query<T>, noinline modify: (T) -> Unit) { queryFirst(query).let { modify(this) save() } } /** * Get count of entries */ fun <T : RealmModel> T.count(): Long { getRealmInstance().use { realm -> return realm.where(this::class.java).count() } } fun <T : RealmModel> T.count(realm: Realm): Long { return realm.where(this::class.java).count() } inline fun <reified T : RealmModel> count(): Long { getRealmInstance<T>().use { realm -> return realm.where(T::class.java).count() } } inline fun <reified T : RealmModel> count(realm: Realm): Long { return realm.where(T::class.java).count() } inline fun <reified T : RealmModel> count(query: Query<T>): Long { getRealmInstance<T>().use { realm -> return realm.where(T::class.java).runQuery(query).count() } } /** * UTILITY METHODS */ private fun <T> T.withQuery(block: (T) -> Unit): T { block(this); return this } /** * UTILITY METHODS */ inline fun <reified T : RealmModel> RealmQuery<T>.runQuery(block: RealmQuery<T>.() -> Unit): RealmQuery<T> { block(this); return this } fun <T : RealmModel> T.hasPrimaryKey(realm: Realm): Boolean { if (realm.schema.get(this.javaClass.simpleName) == null) { throw IllegalArgumentException(this.javaClass.simpleName + " is not part of the schema for this Realm. Did you added realm-android plugin in your build.gradle file?") } return realm.schema.get(this.javaClass.simpleName)?.hasPrimaryKey() ?: false } inline fun <reified T : RealmModel> hasPrimaryKey(realm: Realm): Boolean { val simpleName = T::class.java.simpleName if (realm.schema[simpleName] == null) { throw IllegalArgumentException("$simpleName is not part of the schema for this Realm. Did you add realm-android plugin in your build.gradle file?") } return realm.schema[simpleName]?.hasPrimaryKey() ?: false } inline fun <reified T : RealmModel> T.getLastPk(realm: Realm): Long { getPrimaryKeyFieldName(realm).let { fieldName -> val result = realm.where(this.javaClass).max(fieldName) return result?.toLong() ?: 0 } } inline fun <reified T : RealmModel> getLastPk(realm: Realm): Long { getPrimaryKeyFieldName<T>(realm).let { fieldName -> val result = realm.where(T::class.java).max(fieldName) return result?.toLong() ?: 0 } } inline fun <reified T : RealmModel> T.getPrimaryKeyFieldName(realm: Realm): String? { return realm.schema.get(this.javaClass.simpleName)?.primaryKey } inline fun <reified T : RealmModel> getPrimaryKeyFieldName(realm: Realm): String? { return realm.schema.get(T::class.java.simpleName)?.primaryKey } inline fun <reified T : RealmModel> T.setPk(realm: Realm, value: Long) { getPrimaryKeyFieldName(realm).let { fieldName -> val f1 = javaClass.getDeclaredField(fieldName) try { val accesible = f1.isAccessible f1.isAccessible = true if (f1.isNullFor(this)) { //We only set pk value if it does not have any value previously f1.set(this, value) } f1.isAccessible = accesible } catch (ex: IllegalArgumentException) { throw IllegalArgumentException("Primary key field $fieldName must be of type Long to set a primary key automatically") } } } fun Collection<RealmModel>.initPk(realm: Realm) { val nextPk = first().getLastPk(realm) + 1 for ((index, value) in withIndex()) { value.setPk(realm, nextPk + index) } } fun Array<out RealmModel>.initPk(realm: Realm) { val nextPk = first().getLastPk(realm) + 1 for ((index, value) in withIndex()) { value.setPk(realm, nextPk + index) } } fun RealmModel.initPk(realm: Realm) { setPk(realm, getLastPk(realm) + 1) } fun <T : RealmModel> T.isAutoIncrementPK(): Boolean { return this.javaClass.declaredAnnotations.any { it.annotationClass == AutoIncrementPK::class } } fun <T> RealmQuery<T>.equalToValue(fieldName: String, value: Int) = equalTo(fieldName, value) fun <T> RealmQuery<T>.equalToValue(fieldName: String, value: Long) = equalTo(fieldName, value) fun Field.isNullFor(obj: Any) = try { get(obj) == null } catch (ex: NullPointerException) { true }
17
null
54
534
b313cbbbc72b65008d38f7f1044ad25b45ca6a43
16,127
Kotlin-Realm-Extensions
Apache License 2.0
cams-module-mine/src/main/java/com/linwei/cams/module/mine/MainActivity.kt
WeiShuaiDev
390,640,743
false
null
package com.linwei.cams.module.mine import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } }
0
Kotlin
0
0
43a8a8327abb1ae2d3fd9881906bc59e32fc7b7f
261
CamsModular
Apache License 2.0
libs/serialization/serialization-amqp/src/test/kotlin/net/corda/internal/serialization/amqp/EnumTests.kt
corda
346,070,752
false
{"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.internal.serialization.amqp import net.corda.internal.serialization.amqp.helper.testSerializationContext import net.corda.internal.serialization.amqp.testutils.TestSerializationOutput import net.corda.internal.serialization.amqp.testutils.deserialize import net.corda.internal.serialization.amqp.testutils.deserializeAndReturnEnvelope import net.corda.internal.serialization.amqp.testutils.serializeAndReturnSchema import net.corda.internal.serialization.amqp.testutils.testDefaultFactoryNoEvolution import net.corda.internal.serialization.amqp.testutils.testName import net.corda.internal.serialization.registerCustomSerializers import net.corda.v5.base.annotations.CordaSerializable import net.corda.v5.serialization.SerializedBytes import org.assertj.core.api.Assertions import org.junit.jupiter.api.Assertions.assertNotSame import org.junit.jupiter.api.Test import org.junit.jupiter.api.Timeout import org.junit.jupiter.api.assertThrows import java.io.NotSerializableException import java.time.DayOfWeek import java.util.concurrent.TimeUnit import kotlin.test.assertEquals import kotlin.test.assertNotNull @Timeout(value = 30, unit = TimeUnit.SECONDS) @Suppress("VariableNaming") class EnumTests { @CordaSerializable enum class Bras { TSHIRT, UNDERWIRE, PUSHUP, BRALETTE, STRAPLESS, SPORTS, BACKLESS, PADDED } @CordaSerializable enum class AnnotatedBras { TSHIRT, UNDERWIRE, PUSHUP, BRALETTE, STRAPLESS, SPORTS, BACKLESS, PADDED } // The state of the OldBras enum when the tests in changedEnum1 were serialised // - use if the test file needs regenerating // enum class OldBras { // TSHIRT, UNDERWIRE, PUSHUP, BRALETTE // } // the new state, SPACER has been added to change the ordinality enum class OldBras { SPACER, TSHIRT, UNDERWIRE, PUSHUP, BRALETTE } // The state of the OldBras2 enum when the tests in changedEnum2 were serialised // - use if the test file needs regenerating // enum class OldBras2 { // TSHIRT, UNDERWIRE, PUSHUP, BRALETTE // } // the new state, note in the test we serialised with value UNDERWIRE so the spacer // occurring after this won't have changed the ordinality of our serialised value // and thus should still be deserializable enum class OldBras2 { TSHIRT, UNDERWIRE, PUSHUP, SPACER, BRALETTE, SPACER2 } @CordaSerializable enum class BrasWithInit(val someList: List<Int>) { TSHIRT(emptyList()), UNDERWIRE(listOf(1, 2, 3)), PUSHUP(listOf(100, 200)), BRALETTE(emptyList()) } private val brasTestName = "${this.javaClass.name}\$Bras" companion object { /** * If you want to see the schema encoded into the envelope after serialisation change this to true */ private const val VERBOSE = false } @Suppress("NOTHING_TO_INLINE") private inline fun classTestName(clazz: String) = "${this.javaClass.name}\$${testName()}\$$clazz" private val sf1 = testDefaultFactoryNoEvolution().also { registerCustomSerializers(it) } @Test fun serialiseSimpleTest() { @CordaSerializable data class C(val c: Bras) val schema = TestSerializationOutput(VERBOSE, sf1).serializeAndReturnSchema(C(Bras.UNDERWIRE)).schema assertEquals(2, schema.types.size) val schema_c = schema.types.find { it.name == classTestName("C") } as CompositeType val schema_bras = schema.types.find { it.name == brasTestName } as RestrictedType assertNotNull(schema_c) assertNotNull(schema_bras) assertEquals(1, schema_c.fields.size) assertEquals("c", schema_c.fields.first().name) assertEquals(brasTestName, schema_c.fields.first().type) assertEquals(8, schema_bras.choices.size) Bras.values().forEach { val bra = it assertNotNull(schema_bras.choices.find { it.name == bra.name }) } } @Test fun deserialiseSimpleTest() { @CordaSerializable data class C(val c: Bras) val objAndEnvelope = DeserializationInput(sf1).deserializeAndReturnEnvelope( TestSerializationOutput(VERBOSE, sf1).serialize(C(Bras.UNDERWIRE)) ) val obj = objAndEnvelope.obj val schema = objAndEnvelope.envelope.schema assertEquals(2, schema.types.size) val schema_c = schema.types.find { it.name == classTestName("C") } as CompositeType val schema_bras = schema.types.find { it.name == brasTestName } as RestrictedType assertEquals(1, schema_c.fields.size) assertEquals("c", schema_c.fields.first().name) assertEquals(brasTestName, schema_c.fields.first().type) assertEquals(8, schema_bras.choices.size) Bras.values().forEach { val bra = it assertNotNull(schema_bras.choices.find { it.name == bra.name }) } // Test the actual deserialised object assertEquals(obj.c, Bras.UNDERWIRE) } @Test fun multiEnum() { @CordaSerializable data class Support(val top: Bras, val day: DayOfWeek) @CordaSerializable data class WeeklySupport(val tops: List<Support>) val week = WeeklySupport( listOf( Support(Bras.PUSHUP, DayOfWeek.MONDAY), Support(Bras.UNDERWIRE, DayOfWeek.WEDNESDAY), Support(Bras.PADDED, DayOfWeek.SUNDAY) ) ) val obj = DeserializationInput(sf1).deserialize(TestSerializationOutput(VERBOSE, sf1).serialize(week)) assertEquals(week.tops[0].top, obj.tops[0].top) assertEquals(week.tops[0].day, obj.tops[0].day) assertEquals(week.tops[1].top, obj.tops[1].top) assertEquals(week.tops[1].day, obj.tops[1].day) assertEquals(week.tops[2].top, obj.tops[2].top) assertEquals(week.tops[2].day, obj.tops[2].day) } @Test fun enumWithInit() { @CordaSerializable data class C(val c: BrasWithInit) val c = C(BrasWithInit.PUSHUP) val obj = DeserializationInput(sf1).deserialize(TestSerializationOutput(VERBOSE, sf1).serialize(c)) assertEquals(c.c, obj.c) } @Test fun changedEnum1() { val resource = "EnumTests.changedEnum1" val url = EnumTests::class.java.getResource(resource) data class C(val a: OldBras) // Original version of the class for the serialised version of this class // // val a = OldBras.TSHIRT // val sc = SerializationOutput(sf1).serialize(C(a)) // File(URI("$localPath/$resource")).writeBytes(sc.bytes) val sc2 = url.readBytes() // we expect this to throw assertThrows<NotSerializableException> { DeserializationInput(sf1).deserialize(SerializedBytes<C>(sc2)) } } @Test fun changedEnum2() { val resource = "EnumTests.changedEnum2" val url = EnumTests::class.java.getResource(resource) data class C(val a: OldBras2) // DO NOT CHANGE THIS, it's important we serialise with a value that doesn't // change position in the updated enum class // Original version of the class for the serialised version of this class // // val a = OldBras2.UNDERWIRE // val sc = SerializationOutput(sf1).serialize(C(a)) // File(URI("$localPath/$resource")).writeBytes(sc.bytes) val sc2 = url.readBytes() // we expect this to throw assertThrows<NotSerializableException> { DeserializationInput(sf1).deserialize(SerializedBytes<C>(sc2)) } } @Test fun enumNotOnAllowListFails() { data class C(val c: Bras) val factory = SerializerFactoryBuilder.build(testSerializationContext.currentSandboxGroup()) Assertions.assertThatThrownBy { TestSerializationOutput(VERBOSE, factory).serialize(C(Bras.UNDERWIRE)) }.isInstanceOf(NotSerializableException::class.java) } @Test fun enumAnnotated() { @CordaSerializable data class C(val c: AnnotatedBras) val factory = SerializerFactoryBuilder.build(testSerializationContext.currentSandboxGroup()) // if it all works, this won't explode TestSerializationOutput(VERBOSE, factory).serialize(C(AnnotatedBras.UNDERWIRE)) } @Test fun deserializeCustomisedEnum() { val input = CustomEnumWrapper(CustomEnum.ONE) val factory1 = SerializerFactoryBuilder.build(testSerializationContext.currentSandboxGroup()) val serialized = TestSerializationOutput(VERBOSE, factory1).serialize(input) val factory2 = SerializerFactoryBuilder.build(testSerializationContext.currentSandboxGroup()) val output = DeserializationInput(factory2).deserialize(serialized) assertEquals(input, output) // Deserialized object should be brand new. assertNotSame(input, output) } @Suppress("unused") @CordaSerializable enum class CustomEnum { ONE, TWO, THREE; override fun toString(): String { return "[${name.lowercase()}]" } } @CordaSerializable data class CustomEnumWrapper(val data: CustomEnum) }
82
Kotlin
7
69
0766222eb6284c01ba321633e12b70f1a93ca04e
9,322
corda-runtime-os
Apache License 2.0
automation/test/TestNoop.kt
exertionriver
589,248,613
false
null
import org.junit.jupiter.api.Test import river.exertion.kcop.automation.btree.AutoUserBehaviorHandler import river.exertion.kcop.automation.btree.behavior.NoopBehavior class TestNoop { @Test fun testNoopRun() { AutoUserBehaviorHandler.behaviorSequenceList.add(NoopBehavior(1)) AutoUserBehaviorHandler.behaviorSequenceList.add(NoopBehavior(2)) AutoUserBehaviorHandler.behaviorSequenceList.add(NoopBehavior(3)) repeat(4) { AutoUserBehaviorHandler.execBehavior() } } }
0
Kotlin
0
1
d31e37bd786a4091c24fae3eaa0b627c7969747c
525
kcop
MIT License
automation/test/TestNoop.kt
exertionriver
589,248,613
false
null
import org.junit.jupiter.api.Test import river.exertion.kcop.automation.btree.AutoUserBehaviorHandler import river.exertion.kcop.automation.btree.behavior.NoopBehavior class TestNoop { @Test fun testNoopRun() { AutoUserBehaviorHandler.behaviorSequenceList.add(NoopBehavior(1)) AutoUserBehaviorHandler.behaviorSequenceList.add(NoopBehavior(2)) AutoUserBehaviorHandler.behaviorSequenceList.add(NoopBehavior(3)) repeat(4) { AutoUserBehaviorHandler.execBehavior() } } }
0
Kotlin
0
1
d31e37bd786a4091c24fae3eaa0b627c7969747c
525
kcop
MIT License
api/tmdb/src/main/java/app/tivi/tmdb/TmdbImageUrlProvider.kt
thesandipv
255,834,235
false
null
/* * Copyright 2017 Google, 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.tivi.tmdb private val IMAGE_SIZE_PATTERN = "w(\\d+)$".toRegex() class TmdbImageUrlProvider( private var baseImageUrl: String = TmdbImageSizes.baseImageUrl, private var posterSizes: Array<String> = TmdbImageSizes.posterSizes, private var backdropSizes: Array<String> = TmdbImageSizes.backdropSizes ) { fun getPosterUrl(path: String, imageWidth: Int): String { return "$baseImageUrl${selectSize(posterSizes, imageWidth)}$path" } fun getBackdropUrl(path: String, imageWidth: Int): String { return "$baseImageUrl${selectSize(backdropSizes, imageWidth)}$path" } private fun selectSize(sizes: Array<String>, imageWidth: Int, forceLarger: Boolean = false): String { var previousSize: String? = null var previousWidth = 0 for (i in sizes.indices) { val size = sizes[i] val sizeWidth = extractWidthAsIntFrom(size) ?: continue if (sizeWidth > imageWidth) { if (forceLarger || (previousSize != null && imageWidth > (previousWidth + sizeWidth) / 2)) { return size } else if (previousSize != null) { return previousSize } } else if (i == sizes.size - 1) { // If we get here then we're larger than the last bucket if (imageWidth < sizeWidth * 2) { return size } } previousSize = size previousWidth = sizeWidth } return previousSize ?: sizes.last() } private fun extractWidthAsIntFrom(size: String): Int? { return IMAGE_SIZE_PATTERN.matchEntire(size)?.groups?.get(1)?.value?.toInt() } }
8
null
792
6
e3e06960df9fa535b1a04373e7bd59ea442d9c9b
2,337
watchdone
Apache License 2.0
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/requests/bot/GetMyShortDescription.kt
InsanusMokrassar
163,152,024
false
{"Kotlin": 2489785, "Shell": 373}
package dev.inmo.tgbotapi.requests.bot import dev.inmo.micro_utils.language_codes.IetfLanguageCode import dev.inmo.micro_utils.language_codes.IetfLanguageCodeSerializer import dev.inmo.tgbotapi.requests.abstracts.SimpleRequest import dev.inmo.tgbotapi.types.* import dev.inmo.tgbotapi.types.abstracts.WithOptionalLanguageCode import dev.inmo.tgbotapi.types.commands.* import kotlinx.serialization.* import kotlinx.serialization.builtins.serializer @Serializable class GetMyShortDescription( @SerialName(languageCodeField) @Serializable(IetfLanguageCodeSerializer::class) override val ietfLanguageCode: IetfLanguageCode? = null ) : SimpleRequest<BotShortDescription>, WithOptionalLanguageCode { override fun method(): String = "getMyShortDescription" override val resultDeserializer: DeserializationStrategy<BotShortDescription> get() = BotShortDescription.serializer() override val requestSerializer: SerializationStrategy<*> get() = serializer() }
10
Kotlin
22
294
a6c90b3df5a9d9fde0bbb2db306d5b2f48ba7304
991
ktgbotapi
Apache License 2.0
workflow-runtime/src/jsMain/kotlin/com.squareup.workflow1.internal/SystemUtils.kt
square
268,864,554
false
null
package com.squareup.workflow1.internal import kotlin.js.Date actual fun currentTimeMillis(): Long = Date.now().toLong()
173
null
99
995
daf192e24d7b47943caf534e62e4b70d08028100
123
workflow-kotlin
Apache License 2.0
app/src/main/kotlin/io/github/erikjhordanrey/arch_components_paging_library/view/decorator/MarginDecoration.kt
erikjhordan-rey
133,196,502
false
null
package io.github.erikjhordanrey.arch_components_paging_library.view.decorator import android.content.Context import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView import io.github.erikjhordanrey.arch_components_paging_library.R class MarginDecoration(context: Context) : RecyclerView.ItemDecoration() { private var margin: Int = context.resources.getDimensionPixelSize(R.dimen.item_margin) override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { outRect.set(margin, margin, margin, margin) } }
1
null
16
92
f919f607ef60dd4475712545d227f9391e1846af
618
Movies-PagingLibrary-Arch-Components
Apache License 2.0
sample/src/main/java/com/androidchekhov/pagingrecyclerview/repository/CommentsRepository.kt
AndroidChekhov
162,025,190
false
null
package com.androidchekhov.pagingrecyclerview.repository interface CommentsRepository { suspend fun getComments(page: Int) : List<Comment> }
0
Kotlin
0
0
b56e1b0fe92c143e27a75f9a00ef82b81e741270
145
paging-indicator-list
Apache License 2.0
korim/src/commonMain/kotlin/com/soywiz/korim/vector/format/SVG.kt
dmitrykolesnikovich
419,672,302
true
{"Kotlin": 793601, "C": 13764, "Shell": 1701, "Batchfile": 1531}
package com.soywiz.korim.vector.format import com.soywiz.kds.* import com.soywiz.korim.color.Colors import com.soywiz.korim.color.RGBA import com.soywiz.korim.paint.* import com.soywiz.korim.text.* import com.soywiz.korim.vector.* import com.soywiz.korio.lang.invalidOp import com.soywiz.korio.lang.printStackTrace import com.soywiz.korio.lang.substr import com.soywiz.korio.serialization.xml.Xml import com.soywiz.korio.serialization.xml.allChildren import com.soywiz.korio.serialization.xml.isComment import com.soywiz.korio.util.* import com.soywiz.korma.geom.* import com.soywiz.korma.geom.vector.* import kotlin.collections.set import kotlin.math.* class SVG(val root: Xml, val warningProcessor: ((message: String) -> Unit)? = null) : SizedDrawable { //constructor(@Language("xml") str: String) : this(Xml(str)) constructor(str: String) : this(Xml(str)) override fun toString(): String = "SVG($width, $height)" val x = root.int("x", 0) val y = root.int("y", 0) val dwidth = root.double("width", 128.0) val dheight = root.double("height", 128.0) val viewBox = root.getString("viewBox") ?: "0 0 $dwidth $dheight" val viewBoxNumbers = viewBox.split(' ').map { it.trim().toDoubleOrNull() ?: 0.0 } val viewBoxRectangle = Rectangle( viewBoxNumbers.getOrElse(0) { 0.0 }, viewBoxNumbers.getOrElse(1) { 0.0 }, viewBoxNumbers.getOrElse(2) { dwidth }, viewBoxNumbers.getOrElse(3) { dheight } ) override val width get() = viewBoxRectangle.width.toInt() override val height get() = viewBoxRectangle.height.toInt() class Style { val props = hashMapOf<String, Any?>() } val defs = hashMapOf<String, Paint>() //interface Def fun parseDef(def: Xml) { val type = def.nameLC when (type) { "lineargradient", "radialgradient" -> { val id = def.str("id").toLowerCase() val stops = parseStops(def) val gradientUnits = when (def.getString("gradientUnits") ?: "objectBoundingBox") { "userSpaceOnUse" -> GradientUnits.USER_SPACE_ON_USE else -> GradientUnits.OBJECT_BOUNDING_BOX } val g: GradientPaint = if (type == "lineargradient") { //println("Linear: ($x0,$y0)-($x1-$y1)") val x0 = def.double("x1", 0.0) val y0 = def.double("y1", 0.0) val x1 = def.double("x2", 1.0) val y1 = def.double("y2", 1.0) GradientPaint(GradientKind.LINEAR, x0, y0, 0.0, x1, y1, 0.0, units = gradientUnits) } else { val cx = def.double("cx", 0.0) val cy = def.double("cy", 0.0) val r = def.double("r", 16.0) val fx = def.double("fx", 0.0) val fy = def.double("fy", 0.0) GradientPaint(GradientKind.RADIAL, cx, cy, 0.0, fx, fy, r, units = gradientUnits) } def.strNull("xlink:href")?.let { val id = it.trim('#') val original = defs[id] as? GradientPaint? //println("href: $it --> $original") original?.let { g.stops.add(original.stops) g.colors.add(original.colors) } } for ((offset, color) in stops) { //println(" - $offset: $color") g.addColorStop(offset, color) } //println("Gradient: $g") def.getString("gradientTransform")?.let { g.transform.premultiply(parseTransform(it)) } defs[id] = g } "style" -> { } "_text_" -> { } else -> { println("Unhandled def: '$type'") } } } override fun draw(c: Context2d) { c.keep { c.strokeStyle = NonePaint c.fillStyle = Colors.BLACK drawElement(root, c, true) } } fun drawChildren(xml: Xml, c: Context2d, render: Boolean) { for (child in xml.allChildren) { drawElement(child, c, render) } } fun parseFillStroke(c: Context2d, str2: String, bounds: Rectangle): Paint { val str = str2.toLowerCase().trim() val res = when { str.startsWith("url(") -> { val urlPattern = str.substr(4, -1).substringBefore(')') val extra = str.substringAfter(')') if (urlPattern.startsWith("#")) { val idName = urlPattern.substr(1).toLowerCase() val def = defs[idName] if (def == null) { println(defs) println("Can't find svg definition '$idName'") } //println("URL: def=$def") def ?: NonePaint } else { println("Unsupported $str") NonePaint } } str.startsWith("rgba(") -> { val components = str.removePrefix("rgba(").removeSuffix(")").split(",").map { it.trim().toDoubleOrNull() ?: 0.0 } ColorPaint(RGBA(components[0].toInt(), components[1].toInt(), components[2].toInt(), (components[3] * 255).toInt())) } str.startsWith("rgb(") -> { val components = str.removePrefix("rgb(").removeSuffix(")").split(",").map { it.trim().toDoubleOrNull() ?: 0.0 } ColorPaint(RGBA(components[0].toInt(), components[1].toInt(), components[2].toInt(), 255)) } else -> when (str) { "none" -> NonePaint else -> c.createColor(ColorDefaultBlack[str]) } } return when (res) { is GradientPaint -> { val m = Matrix() m.scale(bounds.width, bounds.height) val out = res.applyMatrix(m) //println(out) out } else -> { res } } } private val t = DoubleArray(6) fun drawElement(xml: Xml, c: Context2d, render: Boolean): Context2d = c.keepApply { val bounds = Rectangle() val nodeName = xml.nameLC var drawChildren = false var render = render val attributes = parseAttributesAndStyles(xml) attributes["transform"]?.let { applyTransform(state, parseTransform(it)) } when (nodeName) { "g", "a", "svg" -> { drawChildren = true } "defs" -> { drawChildren = true render = false } "_text_" -> Unit "_comment_" -> Unit "title" -> Unit "lineargradient", "radialgradient" -> { parseDef(xml) } "rect" -> { val x = xml.double("x") val y = xml.double("y") val width = xml.double("width") val height = xml.double("height") val ry = xml.double("ry", xml.double("rx")) val rx = xml.double("rx", xml.double("ry")) bounds.setTo(x, y, width, height) roundRect(x, y, width, height, rx, ry) } "circle" -> { val cx = xml.double("cx") val cy = xml.double("cy") val radius = xml.double("r") circle(cx, cy, radius) bounds.setBounds(cx - radius, cy - radius, cx + radius, cy + radius) } "ellipse" -> { val cx = xml.double("cx") val cy = xml.double("cy") val rx = xml.double("rx") val ry = xml.double("ry") ellipse(cx - rx, cy - ry, rx * 2, ry * 2) bounds.setBounds(cx - rx, cy - ry, cx + rx, cy + ry) } "polyline", "polygon" -> { beginPath() val ss = StrReader(xml.str("points")) val pps = ListReader(mapWhile(cond = { ss.hasMore }, gen = { ss.skipWhile { !it.isNumeric } val out = ss.readWhile { it.isNumeric }.toDouble() ss.skipWhile { !it.isNumeric } out }).toList()) val path = GraphicsPath() var edges = 0 path.moveTo(pps.read(), pps.read()) while (pps.hasMore) { val x = pps.read() val y = pps.read() path.lineTo(x, y) edges++ } if (nodeName == "polygon") path.close() path.getBounds(bounds) //println("bounds: $bounds, edges: $edges") c.path(path) } "line" -> { beginPath() val x1 = xml.double("x1") val y1 = xml.double("y1") val x2 = xml.double("x2") val y2 = xml.double("y2") moveTo(x1, y1) lineTo(x2, y2) bounds.setBounds(x1, y1, x2, y2) } "text" -> { } "path" -> { val d = xml.str("d") val tokens = tokenizePath(d) val tl = ListReader(tokens) fun dumpTokens() = run { for ((n, token) in tokens.withIndex()) warningProcessor?.invoke("- $n: $token") } fun isNextNumber(): Boolean = if (tl.hasMore) tl.peek() is PathTokenNumber else false fun readNumber(): Double { while (tl.hasMore) { val token = tl.read() if (token is PathTokenNumber) return token.value warningProcessor?.invoke("Invalid path (expected number but found $token) at ${tl.position - 1}") dumpTokens() } return 0.0 } fun n(): Double = readNumber() fun nX(relative: Boolean): Double = if (relative) lastX + readNumber() else readNumber() fun nY(relative: Boolean): Double = if (relative) lastY + readNumber() else readNumber() fun readNextTokenCmd(): Char? { while (tl.hasMore) { val token = tl.read() if (token is PathTokenCmd) return token.id warningProcessor?.invoke("Invalid path (expected command but found $token) at ${tl.position - 1}") dumpTokens() } return null } //dumpTokens() beginPath() moveTo(0.0, 0.0) // Supports relative positioning as first command var lastCX = 0.0 var lastCY = 0.0 var lastCmd = '-' while (tl.hasMore) { val cmd = readNextTokenCmd() ?: break if (cmd == '\u0000' || cmd.isWhitespaceFast()) continue val relative = cmd in 'a'..'z' // lower case var lastCurve = when (lastCmd) { 'S', 'C', 'T', 'Q', 's', 'c', 't', 'q' -> true else -> false } when (cmd) { 'M', 'm' -> { rMoveTo(n(), n(), relative) while (isNextNumber()) rLineTo(n(), n(), relative) } 'L', 'l' -> while (isNextNumber()) rLineTo(n(), n(), relative) 'H', 'h' -> while (isNextNumber()) rLineToH(n(), relative) 'V', 'v' -> while (isNextNumber()) rLineToV(n(), relative) 'Q', 'q' -> while (isNextNumber()) { val cx = nX(relative) val cy = nY(relative) val x2 = nX(relative) val y2 = nY(relative) lastCX = cx lastCY = cy quadTo(cx, cy, x2, y2) } 'C', 'c' -> while (isNextNumber()) { val x1 = nX(relative) val y1 = nY(relative) val x2 = nX(relative) val y2 = nY(relative) val x = nX(relative) val y = nY(relative) lastCX = x2 lastCY = y2 cubicTo(x1, y1, x2, y2, x, y) } 'S', 's' -> { while (isNextNumber()) { // https://www.stkent.com/2015/07/03/building-smooth-paths-using-bezier-curves.html // https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths // S produces the same type of curve as earlier—but if it follows another S command or a C command, // the first control point is assumed to be a reflection of the one used previously. // If the S command doesn't follow another S or C command, then the current position of the cursor // is used as the first control point. In this case the result is the same as what the Q command // would have produced with the same parameters. val x2 = nX(relative) val y2 = nY(relative) val x = nX(relative) val y = nY(relative) val x1 = if (lastCurve) lastX * 2 - lastCX else lastX val y1 = if (lastCurve) lastY * 2 - lastCY else lastY lastCX = x2 lastCY = y2 cubicTo(x1, y1, x2, y2, x, y) lastCurve = true } } 'T', 't' -> { var n = 0 while (isNextNumber()) { val x2 = nX(relative) val y2 = nY(relative) val cx = if (lastCurve) lastX * 2 - lastCX else lastX val cy = if (lastCurve) lastY * 2 - lastCY else lastY //println("[$cmd]: $lastX, $lastY, $cx, $cy, $x2, $y2 :: $lastX - $lastCX :: $cx :: $lastCurve :: $lastCmd") lastCX = cx lastCY = cy quadTo(cx, cy, x2, y2) n++ lastCurve = true } } 'A', 'a' -> { // Ported from nanosvg (https://github.com/memononen/nanosvg/blob/25241c5a8f8451d41ab1b02ab2d865b01600d949/src/nanosvg.h#L2067) // Ported from canvg (https://code.google.com/p/canvg/) var rx = readNumber().absoluteValue // y radius var ry = readNumber().absoluteValue // x radius val rotx = readNumber() / 180.0 * PI // x rotation angle val fa = if ((readNumber().absoluteValue) > 1e-6) 1 else 0 // Large arc val fs = if ((readNumber().absoluteValue) > 1e-6) 1 else 0 // Sweep direction val x1 = lastX // start point val y1 = lastY // end point val x2 = nX(relative) val y2 = nY(relative) var dx = x1 - x2 var dy = y1 - y2 val d = hypot(dx, dy) if (d < 1e-6f || rx < 1e-6f || ry < 1e-6f) { // The arc degenerates to a line lineTo(x2, y2) } else { val sinrx = kotlin.math.sin(rotx) val cosrx = kotlin.math.cos(rotx) // Convert to center point parameterization. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes // 1) Compute x1', y1' val x1p = cosrx * dx / 2.0f + sinrx * dy / 2.0f val y1p = -sinrx * dx / 2.0f + cosrx * dy / 2.0f var d = sqr(x1p) / sqr(rx) + sqr(y1p) / sqr(ry) if (d > 1) { d = sqr(d) rx *= d ry *= d } // 2) Compute cx', cy' var s = 0.0 var sa = sqr(rx) * sqr(ry) - sqr(rx) * sqr(y1p) - sqr(ry) * sqr(x1p) val sb = sqr(rx) * sqr(y1p) + sqr(ry) * sqr(x1p) if (sa < 0.0) sa = 0.0 if (sb > 0.0) s = sqrt(sa / sb) if (fa == fs) s = -s val cxp = s * rx * y1p / ry val cyp = s * -ry * x1p / rx // 3) Compute cx,cy from cx',cy' val cx = (x1 + x2) / 2.0 + cosrx * cxp - sinrx * cyp val cy = (y1 + y2) / 2.0 + sinrx * cxp + cosrx * cyp // 4) Calculate theta1, and delta theta. val ux = (x1p - cxp) / rx val uy = (y1p - cyp) / ry val vx = (-x1p - cxp) / rx val vy = (-y1p - cyp) / ry val a1 = vecang(1.0, 0.0, ux, uy) // Initial angle var da = vecang(ux, uy, vx, vy) // Delta angle // if (vecrat(ux,uy,vx,vy) <= -1.0f) da = NSVG_PI; // if (vecrat(ux,uy,vx,vy) >= 1.0f) da = 0; if (fs == 0 && da > 0) da -= 2 * PI else if (fs == 1 && da < 0) da += 2 * PI // Approximate the arc using cubic spline segments. t[0] = cosrx t[1] = sinrx t[2] = -sinrx t[3] = cosrx t[4] = cx t[5] = cy // Split arc into max 90 degree segments. // The loop assumes an iteration per end point (including start and end), this +1. val ndivs = (abs(da) / (PI * 0.5) + 1.0).toInt() val hda = (da / ndivs.toDouble()) / 2.0 var kappa = abs(4.0f / 3.0f * (1.0f - cos(hda)) / sin(hda)) if (da < 0.0f) kappa = -kappa var ptanx = 0.0 var ptany = 0.0 var px = 0.0 var py = 0.0 for (i in 0..ndivs) { val a = a1 + da * (i.toDouble() / ndivs.toDouble()) dx = cos(a) dy = sin(a) val x = xformPointX(dx*rx, dy*ry, t) // position val y = xformPointY( dx*rx, dy*ry, t) // position val tanx = xformVecX( -dy*rx * kappa, dx*ry * kappa, t) // tangent val tany = xformVecY(-dy*rx * kappa, dx*ry * kappa, t) // tangent if (i > 0) { cubicTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y) } px = x py = y ptanx = tanx ptany = tany } lastX = x2 lastY = y2 //*cpx = x2; //*cpy = y2; } } 'Z', 'z' -> close() else -> { TODO("Unsupported command '$cmd' (${cmd.toInt()}) : Parsed: '${state.path.toSvgPathString()}', Original: '$d'") } } lastCmd = cmd } warningProcessor?.invoke("Parsed SVG Path: '${state.path.toSvgPathString()}'") warningProcessor?.invoke("Original SVG Path: '$d'") warningProcessor?.invoke("Points: ${state.path.getPoints()}") getBounds(bounds) } else -> { warningProcessor?.invoke("Unhandled SVG node '$nodeName'") drawChildren = true } } for ((key, it) in attributes) { when (key) { "stroke-width" -> lineWidth = it.toDoubleOrNull() ?: 1.0 "stroke-linejoin" -> lineJoin = LineJoin[it] "stroke-linecap" -> lineCap = LineCap[it] "stroke" -> strokeStyle = parseFillStroke(c, it, bounds) "opacity" -> globalAlpha *= it.toDoubleOrNull() ?: 1.0 "fill-opacity" -> globalAlpha *= it.toDoubleOrNull() ?: 1.0 // @TODO: Do this properly "stroke-opacity" -> globalAlpha *= it.toDoubleOrNull() ?: 1.0 // @TODO: Do this properly "fill" -> applyFill(c, it, bounds) "font-size" -> fontSize = parseSizeAsDouble(it) "font-family" -> font = fontRegistry[it] "text-anchor" -> horizontalAlign = when (it.toLowerCase().trim()) { "left" -> HorizontalAlign.LEFT "center", "middle" -> HorizontalAlign.CENTER "right", "end" -> HorizontalAlign.RIGHT else -> horizontalAlign } "alignment-baseline" -> verticalAlign = when (it.toLowerCase().trim()) { "hanging" -> VerticalAlign.TOP "center", "middle" -> VerticalAlign.MIDDLE "baseline" -> VerticalAlign.BASELINE "bottom" -> VerticalAlign.BOTTOM else -> verticalAlign } "fill-rule" -> Unit // @TODO } } if (drawChildren) { drawChildren(xml, c, render) } when (nodeName) { "text" -> { fillText(xml.text.trim(), xml.double("x") + xml.double("dx"), xml.double("y") + xml.double("dy")) } } c.fillStroke() } private fun sqr(v: Double) = v * v private fun vmag(x: Double, y: Double): Double { return sqrt(x * x + y * y) } private fun vecrat(ux: Double, uy: Double, vx: Double, vy: Double): Double { return (ux * vx + uy * vy) / (vmag(ux, uy) * vmag(vx, vy)) } private fun vecang(ux: Double, uy: Double, vx: Double, vy: Double): Double { var r = vecrat(ux, uy, vx, vy) if (r < -1.0) r = -1.0 if (r > 1.0) r = 1.0 return (if (ux * vy < uy * vx) -1.0 else 1.0) * acos(r) } private fun xformPointX(x: Double, y: Double, t: DoubleArray) = x*t[0] + y*t[2] + t[4] private fun xformPointY(x: Double, y: Double, t: DoubleArray) = x*t[1] + y*t[3] + t[5] private fun xformVecX(x: Double, y: Double, t: DoubleArray) = x*t[0] + y*t[2] private fun xformVecY(x: Double, y: Double, t: DoubleArray): Double = x*t[1] + y*t[3] fun parseSizeAsDouble(size: String): Double { return size.filter { it !in 'a'..'z' && it !in 'A'..'Z' }.toDoubleOrNull() ?: 16.0 } fun applyFill(c: Context2d, str: String, bounds: Rectangle) { c.fillStyle = parseFillStroke(c, str, bounds) } private fun applyTransform(state: Context2d.State, transform: Matrix) { //println("Apply transform $transform to $state") state.transform.premultiply(transform) } fun parseTransform(str: String): Matrix { val tokens = SvgStyle.tokenize(str) val tr = ListReader(tokens) val out = Matrix() //println("Not implemented: parseTransform: $str: $tokens") while (tr.hasMore) { val id = tr.read().toLowerCase() val args = arrayListOf<String>() if (tr.peek() == "(") { tr.read() while (true) { if (tr.peek() == ")") { tr.read() break } if (tr.peek() == ",") { tr.read() continue } args += tr.read() } } val doubleArgs = args.map { it.toDoubleOrNull() ?: 0.0 } fun double(index: Int) = doubleArgs.getOrElse(index) { 0.0 } when (id) { "translate" -> out.pretranslate(double(0), double(1)) "scale" -> out.prescale(double(0), if (doubleArgs.size >= 2) double(1) else double(0)) "matrix" -> out.premultiply(double(0), double(1), double(2), double(3), double(4), double(5)) "rotate" -> { if (doubleArgs.size >= 3) out.pretranslate(double(1), double(2)) out.prerotate(double(0).degrees) if (doubleArgs.size >= 3) out.pretranslate(-double(1), -double(2)) } else -> invalidOp("Unsupported transform $id : $args : $doubleArgs ($str)") } //println("ID: $id, args=$args") } return out } class CSSDeclarations { val props = LinkedHashMap<String, String>() companion object { fun parseToMap(str: String): Map<String, String> = CSSDeclarations().parse(str).props } fun parse(str: String): CSSDeclarations = str.reader().parse() fun StrReader.parse(): CSSDeclarations { while (!eof) { parseCssDecl() } return this@CSSDeclarations } fun StrReader.parseCssDecl() { skipSpaces() val id = readCssId() skipSpaces() skipExpect(':') skipSpaces() //readStringLit() // @TODO: Proper parsing val value = readUntil { it == ';' }.trim() props[id] = value if (!eof) { skipExpect(';') } } fun StrReader.readCssId() = readWhile { it.isLetterOrDigit() || it == '-' } } companion object { val ColorDefaultBlack = Colors.WithDefault(Colors.BLACK) fun parseAttributesAndStyles(node: Xml): Map<String, String> { val out = node.attributes.toMutableMap() node.getString("style")?.let { out.putAll(CSSDeclarations.parseToMap(it)) } return out } fun parsePercent(str: String, default: Double = 0.0): Double { return if (str.endsWith("%")) { str.substr(0, -1).toDouble() / 100.0 } else { str.toDoubleOrNull() ?: default } } fun parseStops(xml: Xml): List<Pair<Double, RGBA>> { val out = arrayListOf<Pair<Double, RGBA>>() for (stop in xml.children("stop")) { val info = parseAttributesAndStyles(stop) var offset = 0.0 var colorStop = ColorDefaultBlack.defaultColor var alphaStop = 1.0 for ((key, value) in info) { when (key) { "offset" -> offset = parsePercent(value) "stop-color" -> colorStop = ColorDefaultBlack[value] "stop-opacity" -> alphaStop = value.toDoubleOrNull() ?: 1.0 } } out += Pair(offset, RGBA(colorStop.rgb, (alphaStop * 255).toInt())) } return out } // @TODO: Do not allocate PathToken! fun tokenizePath(str: String): List<PathToken> { val sr = StrReader(str) fun StrReader.skipSeparators() { skipWhile { it == ',' || it == ' ' || it == '\t' || it == '\n' || it == '\r' } } fun StrReader.readNumber(): Double { skipSeparators() var first = true val str = readWhile { if (first) { first = false it.isDigit() || it == '-' || it == '+' } else { it.isDigit() || it == '.' } } return if (str.isEmpty()) 0.0 else try { str.toDouble() } catch (e: Throwable) { e.printStackTrace() 0.0 } } val out = arrayListOf<PathToken>() while (sr.hasMore) { sr.skipSeparators() val c = sr.peekChar() out += if (c in '0'..'9' || c == '-' || c == '+') { PathTokenNumber(sr.readNumber()) } else { PathTokenCmd(sr.readChar()) } } return out } } interface PathToken data class PathTokenNumber(val value: Double) : PathToken data class PathTokenCmd(val id: Char) : PathToken data class SvgStyle( val styles: MutableMap<String, String> = hashMapOf() ) { companion object { fun tokenize(str: String): List<String> { val sr = StrReader(str) val out = arrayListOf<String>() while (sr.hasMore) { while (true) { sr.skipSpaces() val id = sr.readWhile { it.isLetterOrUnderscore() || it.isNumeric || it == '-' || it == '#' } if (id.isNotEmpty()) { out += id } else { break } } if (sr.eof) break sr.skipSpaces() val symbol = sr.read() out += "$symbol" } return out } fun ListReader<String>.readId() = this.read() fun ListReader<String>.readColon() = expect(":") fun ListReader<String>.readExpression() = this.read() fun parse(str: String, warningProcessor: ((message: String) -> Unit)? = null): SvgStyle { val tokens = tokenize(str) val tr = ListReader(tokens) //println("Style: $str : $tokens") val style = SvgStyle() while (tr.hasMore) { val id = tr.readId() if (tr.eof) { warningProcessor?.invoke("EOF. Parsing (ID='$id'): '$str', $tokens") break } tr.readColon() val rexpr = arrayListOf<String>() while (tr.hasMore && tr.peek() != ";") { rexpr += tr.readExpression() } style.styles[id.toLowerCase()] = rexpr.joinToString("") if (tr.hasMore) tr.expect(";") //println("$id --> $rexpr") } return style } } } }
0
null
0
1
d05eff45d0cb156336cf8dd9557731a3ec9243cb
29,932
korim
Apache License 2.0
core/src/commonMain/kotlin/work/socialhub/kslack/api/methods/response/admin/teams/AdminTeamsCreateResponse.kt
uakihir0
794,979,552
false
{"Kotlin": 868677, "Ruby": 2164, "Shell": 2095, "Makefile": 316}
package work.socialhub.kslack.api.methods.response.admin.teams import kotlinx.serialization.Serializable import work.socialhub.kslack.api.methods.SlackApiResponse @Serializable class AdminTeamsCreateResponse : SlackApiResponse() { var team: String? = null // created team id var responseMetadata: ResponseMetadata? = null @Serializable class ResponseMetadata { var messages: Array<String>? = null } }
5
Kotlin
0
0
3975e9de4fae5ef2ddc5b013c2a346536852f7b3
432
kslack
MIT License
src/main/kotlin/de/lostmekka/raymarcher/Shape.kt
LostMekka
166,667,888
false
null
package de.lostmekka.raymarcher import kotlin.math.abs import kotlin.math.max typealias SpatialTransformation = (Point) -> Point data class EstimatedDistance(val distance: Double, val shape: Shape) abstract class Geometry { protected abstract fun estimateDistanceLocally(localPoint: Point, distanceScaling: Double): EstimatedDistance private val transformations = mutableListOf<SpatialTransformation>() private var distanceScaling = 1.0 fun addTransform(transformation: SpatialTransformation) { transformations += transformation } fun grid(x: Double, y: Double, z: Double) = grid(Point(x, y, z)) fun grid(gridSize: Point) { transformations += { val halfGridSize = gridSize / 2.0 ((it + halfGridSize) floorMod gridSize) - halfGridSize } } fun mirrorOnPlane(origin: Point, normal: Point) { transformations += { val d = (it - origin) dot normal.normalized it + (normal.normalized * (abs(d) - d)) } } fun translate(x: Double, y: Double, z: Double) = translate(Point(x, y, z)) fun translate(amount: Point) { transformations += { it - amount } } fun scale(amount: Double) { transformations += { it / amount } distanceScaling *= amount } fun rotateX(angle: Double) { val matrix = xRotationMatrix(angle) transformations += { matrix * it } } fun rotateY(angle: Double) { val matrix = yRotationMatrix(angle) transformations += { matrix * it } } fun rotateZ(angle: Double) { val matrix = zRotationMatrix(angle) transformations += { matrix * it } } fun estimateDistanceTo(point: Point, distanceScaling: Double = 1.0): EstimatedDistance { var p = point transformations.reversed().forEach { p = it(p) } return estimateDistanceLocally(p, this.distanceScaling * distanceScaling) } } class Scene(val children: List<Geometry>) : Geometry() { constructor(vararg children: Geometry) : this(children.toList()) override fun estimateDistanceLocally(localPoint: Point, distanceScaling: Double): EstimatedDistance = children .map { it.estimateDistanceTo(localPoint, distanceScaling) } .minBy { it.distance } ?: throw Exception("cannot estimate distance of empty scene") } abstract class Shape(val material: Material) : Geometry() { protected abstract fun estimateLocalDistanceOnly(localPoint: Point): Double override fun estimateDistanceLocally(localPoint: Point, distanceScaling: Double) = EstimatedDistance(estimateLocalDistanceOnly(localPoint) * distanceScaling, this) } class Sphere(val radius: Double, material: Material) : Shape(material) { override fun estimateLocalDistanceOnly(localPoint: Point) = max(.0, localPoint.length - radius) } class Plane(val normal: Point, material: Material) : Shape(material) { override fun estimateLocalDistanceOnly(localPoint: Point) = abs(localPoint dot normal.normalized) } class Cube(val sideLength: Double, material: Material) : Shape(material) { override fun estimateLocalDistanceOnly(localPoint: Point) = maxOf( max(0.0, abs(localPoint.x) - sideLength / 2), max(0.0, abs(localPoint.y) - sideLength / 2), max(0.0, abs(localPoint.z) - sideLength / 2) ) }
0
Kotlin
0
0
ee4232112b2341901a32fa8378687cae3aab0c8d
3,357
ray-marcher-kt
MIT License
app/src/main/java/com/example/pocketplaner/comps/DashBoard.kt
TEHAQUE
773,157,128
false
{"Kotlin": 31566}
package com.example.pocketplaner.comps import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.focusModifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontVariation.weight import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp data class SavingsModel( val name: String, val description: String, val gradientColors: List<Color> ) @Composable fun DashBoard(modifier: Modifier = Modifier) { Column ( modifier = modifier .fillMaxSize() .background( brush = Brush.verticalGradient( colors = listOf(Color(0xFF815BD8), Color(0xFF2B0B75)) ) ) .padding(start = 10.dp, top = 25.dp, end = 10.dp, bottom = 110.dp), ) { Column( modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(8.dp)) .background(Color(0xFF4F3A7E)) .padding(8.dp) ) { Text( text = "Welcome back, " + "Michał", fontSize = 30.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) Spacer(modifier = Modifier.height(12.dp)) Text( text = "2341.12" + "$", fontSize = 30.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) Spacer(modifier = Modifier.height(12.dp)) Row( modifier = Modifier .fillMaxWidth() ) { Column( modifier = Modifier .weight(1f) .clip(RoundedCornerShape(8.dp)) .background(Color(0xFF614C91)) .padding(start = 8.dp, top = 5.dp, end = 8.dp, bottom = 5.dp) ) { Text( text = "rachunki", fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) Text( text = "989.12" + "$", fontSize = 21.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) } Spacer(modifier = Modifier.width(8.dp)) Column( modifier = Modifier .weight(1f) .clip(RoundedCornerShape(8.dp)) .background(Color(0xFF614C91)) .padding(start = 8.dp, top = 5.dp, end = 8.dp, bottom = 5.dp) ) { Text( text = "zabawa", fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) Text( text = "189.12" + "$", fontSize = 21.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) } Spacer(modifier = Modifier.width(8.dp)) Column( modifier = Modifier .weight(1f) .clip(RoundedCornerShape(8.dp)) .background(Color(0xFF614C91)) .padding(start = 8.dp, top = 5.dp, end = 8.dp, bottom = 5.dp) ) { Text( text = "inwestycje", fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) Text( text = "432.12" + "$", fontSize = 21.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) } } } Spacer(modifier = Modifier.height(8.dp)) Text( text = "Try some models", fontSize = 30.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) Spacer(modifier = Modifier.height(8.dp)) LazyRow( modifier = Modifier.fillMaxWidth() ) { val savingsModels = listOf( SavingsModel( name = "Zasada 50/30/20", description = "Save 50% on essentials, 30% on lifestyle, and 20% on savings.", gradientColors = listOf(Color(0xFF815BD8), Color(0xFF2B0B75)) ), SavingsModel( name = "Zasada 80/20", description = "Spend 80% on necessities and save 20%.", gradientColors = listOf(Color(0xFFE7A1FE), Color(0xFF4B0082)) ), SavingsModel( name = "Zasada 70/20/10", description = "Allocate 70% for living expenses, 20% for savings, and 10% for investments.", gradientColors = listOf(Color(0xFF7FFFD4), Color(0xFF00CED1)) ), SavingsModel( name = "Zasada 60/20/20", description = "Use 60% for essentials, 20% for lifestyle, and 20% for savings.", gradientColors = listOf(Color(0xFFFFD700), Color(0xFFFF6347)) ) ) items(savingsModels) { model -> Box( modifier = Modifier .padding(8.dp) .clip(RoundedCornerShape(8.dp)) .background( brush = Brush.verticalGradient( colors = model.gradientColors ) ) .padding(16.dp) .fillParentMaxWidth(.8f) .align(Alignment.CenterHorizontally) ) { Column { Text( text = model.name, fontSize = 21.sp, color = Color.White, fontWeight = FontWeight.SemiBold ) Spacer(modifier = Modifier.height(8.dp)) Text( text = model.description, fontSize = 16.sp, color = Color.White, ) Spacer(modifier = Modifier.height(8.dp)) Button(onClick = { /*TODO*/ }) { Text(text = "Try now!") } } } } } } }
0
Kotlin
0
0
cab1970d06249c97bd9d79272a878cc71eb986ef
8,084
PocketPlanner
MIT License
app/src/main/java/ch/abwesend/privatecontacts/domain/model/contact/InvalidContactIdException.kt
fgubler
462,182,037
false
{"Kotlin": 1163443, "Java": 369326}
/* * Private Contacts * Copyright (c) 2022. * <NAME> */ package ch.abwesend.privatecontacts.domain.model.contact import kotlin.reflect.KClass class InvalidContactIdException( requiredType: KClass<out ContactId>, actualType: KClass<out ContactId> ) : IllegalArgumentException( "Invalid contact-ID: is of type ${actualType.java.simpleName} " + "but should be of type ${requiredType.java.simpleName}" ) @Deprecated("Cannot be used in tests due to some unboxing issue") fun IContactBase.requireInternalId(): IContactIdInternal = id.let { contactId -> if (contactId !is IContactIdInternal) { throw InvalidContactIdException(requiredType = IContactIdInternal::class, actualType = id::class) } else contactId }
0
Kotlin
1
9
49b98707f8cd250f7f15279c4b9e61fef41f1fb1
748
PrivateContacts
Apache License 2.0
presentation/src/main/java/com/desarrollodroide/pagekeeper/ui/components/CategoriesView.kt
DesarrolloAntonio
585,604,683
false
{"Kotlin": 382374}
package com.desarrollodroide.pagekeeper.ui.components import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Done import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChipDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.desarrollodroide.model.Tag enum class CategoriesType { SELECTABLES, REMOVEABLES } @Composable @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) fun Categories( categoriesType: CategoriesType = CategoriesType.SELECTABLES, showCategories: Boolean, uniqueCategories: MutableState<List<Tag>>, selectedTags: MutableState<List<Tag>> = mutableStateOf(emptyList<Tag>()) ) { AnimatedVisibility(showCategories) { Column() { FlowRow() { uniqueCategories.value.forEach { category -> val selected = category in selectedTags.value FilterChip( colors = FilterChipDefaults.filterChipColors( containerColor = MaterialTheme.colorScheme.surface, labelColor = MaterialTheme.colorScheme.onSurface, iconColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f), disabledContainerColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.08f), disabledLabelColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f), selectedContainerColor = MaterialTheme.colorScheme.secondary, disabledSelectedContainerColor = MaterialTheme.colorScheme.secondary.copy(alpha = 0.5f), selectedLabelColor = MaterialTheme.colorScheme.onSecondary, selectedLeadingIconColor = MaterialTheme.colorScheme.onSecondary ), selected = selected, label = { Text(category.name) }, modifier = Modifier.padding(horizontal = 4.dp), shape = RoundedCornerShape(12.dp), onClick = { when (categoriesType) { CategoriesType.SELECTABLES -> { if (selected) { selectedTags.value = selectedTags.value - category } else { selectedTags.value = selectedTags.value + category } } CategoriesType.REMOVEABLES -> { uniqueCategories.value = uniqueCategories.value.filter { it != category } } } }, leadingIcon = { when(categoriesType){ CategoriesType.SELECTABLES -> { if (selected) { Icon( imageVector = Icons.Filled.Done, contentDescription = null, modifier = Modifier.size(FilterChipDefaults.IconSize) ) } } CategoriesType.REMOVEABLES -> { Icon( imageVector = Icons.Filled.Delete, contentDescription = null, modifier = Modifier.size(FilterChipDefaults.IconSize) ) } } } ) } } } } }
20
Kotlin
3
94
e2309af37b6c0a8036868afb1df0d45f5c080558
4,879
Shiori-Android-Client
Apache License 2.0
api/src/commonMain/kotlin/krono/PureDateTimeFormatter.kt
picortex
544,285,520
false
null
@file:JsExport package krono import kotlinx.JsExport /** * A class to format date * ``` * token: description: example: * {YYYY} 4-digit year 1999 * {YY} 2-digit year 99 * {MMMM} full month name February * {MMM} 3-letter month name Feb * {MM} 2-digit month number 02 * {M} month number 2 * {DDDD} full weekday name Wednesday * {DDD} 3-letter weekday name Wed * {DD} 2-digit day number 09 * {D} day number 9 * {th} day ordinal suffix nd * {HH} 2-digit 24-based hour 17 * {H} 1-digit 24-based hour 9 * {hh} 2-digit hour 05 * {h} 1-digit hour 5 * {mm} 2-digit minute 07 * {m} minute 7 * {ss} 2-digit second 09 * {s} second 9 * {ampm} "am" or "pm" pm * {AMPM} "AM" or "PM" PM * ``` */ interface PureDateTimeFormatter : PureDateFormatter, PureTimeFormatter { fun formatDateTime(year: Int, month: Int, day: Int, hour: Int, minutes: Int, seconds: Int): String }
0
null
0
1
a0a970a6c3dc21dba46701b41a38ee91f0c3f814
1,222
krono
MIT License
app/src/main/java/com/Alkemy/alkemybankbase/presentation/LoginViewModel.kt
MicaMathieu
566,627,293
false
null
package com.Alkemy.alkemybankbase.presentation import android.content.Context import androidx.core.util.PatternsCompat import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.Alkemy.alkemybankbase.R import com.Alkemy.alkemybankbase.data.local.AccountManager import com.Alkemy.alkemybankbase.data.local.SessionManager import com.Alkemy.alkemybankbase.data.model.login.LoginInput import com.Alkemy.alkemybankbase.data.model.login.LoginResponse import com.Alkemy.alkemybankbase.repository.account.AccountRepository import com.Alkemy.alkemybankbase.utils.Resource import com.google.android.gms.auth.api.signin.GoogleSignInOptions import dagger.hilt.android.lifecycle.HiltViewModel import java.lang.IllegalArgumentException import java.util.regex.Pattern import javax.inject.Inject import com.Alkemy.alkemybankbase.repository.login.LoginRepository import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInClient import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @HiltViewModel class LoginViewModel @Inject constructor(private val loginRepo : LoginRepository,private val accountRepo:AccountRepository) : ViewModel() { val emailErrorResourceIdLiveData = MutableLiveData<Int>() val passwordErrorResourceIdLiveData = MutableLiveData<Int>() val isFormValidLiveData = MutableLiveData<Boolean>() lateinit var loginResponse : LoginResponse var loginError : String = "" var accountsError = MutableLiveData<Int>() val isLoading = MutableLiveData<Boolean>() //Check email & password fun validateForm(email: String, password: String) { // check if email is valid with pattern val isEmailValid = PatternsCompat.EMAIL_ADDRESS.matcher(email).matches() // check if password is valid with pattern val passwordPattern = "^(?=.*[0-9])(?=.*[A-Z])(?=\\S+\$).{8,}" val pattern = Pattern.compile(passwordPattern) val isPasswordValid = pattern.matcher(password).matches() if (!isEmailValid){ emailErrorResourceIdLiveData.value = R.string.email_error isFormValidLiveData.value = false }else if (!isPasswordValid){ passwordErrorResourceIdLiveData.value = R.string.password_error isFormValidLiveData.value = false }else{ isFormValidLiveData.value = true } } suspend fun loginUser(context: Context, email:String, password:String){ var loginResult: Resource<LoginResponse> isLoading.value = true val loginInput = LoginInput(email = email, password = <PASSWORD>) loginResult = loginRepo.loginUser(loginInput = loginInput) loginResponse = LoginResponse() when(loginResult){ is Resource.Success -> { loginResponse = loginResult.data!! SessionManager.saveAuthToken(context, "Bearer ${loginResult.data!!.accessToken}") isLoading.value = false getAllAccounts(context) } is Resource.Failure -> { loginError = loginResult.message.toString() isLoading.value = false } else -> throw IllegalArgumentException("Illegal Result") } } fun getAllAccounts(context:Context){ isLoading.value = true viewModelScope.launch(Dispatchers.Main){ val response = withContext(Dispatchers.IO){ accountRepo.getAllAccounts("Bearer ${loginResponse.accessToken}") } when(response){ is Resource.Failure -> { isLoading.value = false accountsError.value = R.string.no_internet } is Resource.Loading -> { } is Resource.Success ->{ val userId = response.data!!.first().userId val accountId = response.data.first().id isLoading.value = false AccountManager.saveIds(context,userId.toString(),accountId.toString()) } } } } fun loginGoogle(context:Context) : GoogleSignInClient{ val googleConf = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken((R.string.default_web_client_id.toString())) .requestEmail() .build() val googleClient = GoogleSignIn.getClient(context, googleConf) googleClient.signOut() return googleClient //startActivityForResult(googleClient.signInIntent,GOOGLE_SIGN_IN) } }
0
Kotlin
0
0
30b3919f294626a2687d612fa2866d1e3e49c92e
4,758
AlkeBankBase
MIT License
src/main/kotlin/com/kb714/i18nrailstextextractor/PluginConfiguration.kt
kb714
767,507,822
false
{"Kotlin": 38946}
package com.kb714.i18nrailstextextractor import com.google.gson.Gson import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.options.Configurable import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.JBList import com.intellij.ui.components.JBScrollPane import com.intellij.ui.table.JBTable import com.kb714.i18nrailstextextractor.configuration.YamlTableModel import com.kb714.i18nrailstextextractor.utils.I18nFinder import org.yaml.snakeyaml.Yaml import java.awt.BorderLayout import java.awt.Dimension import java.awt.FlowLayout import java.io.FileInputStream import javax.swing.* class PluginConfiguration : Configurable { private var selectedFiles = mutableListOf<VirtualFile>() private val listModel = DefaultListModel<String>() private val filesList = JBList(listModel) private val tableModel = YamlTableModel() private val keysTable = JBTable(tableModel) private val i18nUtil = I18nFinder override fun getDisplayName(): String = "Extractor Settings" override fun isModified(): Boolean = false override fun createComponent(): JComponent { loadSelectedFiles() loadKeysTable() val mainPanel = JPanel(BorderLayout()) setupFilesListPanel(mainPanel) setupKeysTablePanel(mainPanel) setupButtonsPanel(mainPanel) return mainPanel } private fun setupFilesListPanel(mainPanel: JPanel) { val scrollPane = JBScrollPane(filesList) val scrollPaneContainer = JPanel(BorderLayout()).apply { preferredSize = Dimension(-1, 200) add(scrollPane, BorderLayout.CENTER) } mainPanel.add(scrollPaneContainer, BorderLayout.NORTH) } private fun setupKeysTablePanel(mainPanel: JPanel) { val tableScrollPane = JBScrollPane(keysTable) mainPanel.add(tableScrollPane, BorderLayout.CENTER) } private fun setupButtonsPanel(mainPanel: JPanel) { val buttonPanel = JPanel(FlowLayout(FlowLayout.RIGHT)) val selectButton = JButton("Select YAML Files").apply { addActionListener { val descriptor = FileChooserDescriptor(true, false, true, false, true, true) .withFileFilter { it.extension == "yml" || it.extension == "yaml" } val files = FileChooser.chooseFiles(descriptor, null, null) val newFiles = files.filterNot { selectedFile -> selectedFiles.any { it.path == selectedFile.path } } if (newFiles.isNotEmpty()) { selectedFiles.addAll(newFiles) refreshListModel() refreshKeysTable() saveSelectedFiles() } } } val removeButton = JButton("Remove Selected").apply { addActionListener { filesList.selectedIndices.reversedArray().forEach { selectedFiles.removeAt(it) listModel.remove(it) } refreshKeysTable() saveSelectedFiles() } } val clearButton = JButton("Clear All").apply { addActionListener { selectedFiles.clear() listModel.clear() refreshKeysTable() saveSelectedFiles() } } buttonPanel.add(selectButton) buttonPanel.add(removeButton) buttonPanel.add(clearButton) mainPanel.add(buttonPanel, BorderLayout.SOUTH) } override fun apply() { saveSelectedFiles() } private fun loadSelectedFiles() { val paths = PropertiesComponent.getInstance().getValue("PluginConfiguration.SelectedFiles", "") selectedFiles = paths.split(";").filter { it.isNotEmpty() }.mapNotNull { LocalFileSystem.getInstance().findFileByPath(it) }.toMutableList() refreshListModel() refreshKeysTable() } private fun loadKeysTable() { val i18nMap = i18nUtil.loadMap() tableModel.rowCount = 0 i18nMap.forEach { (key, value) -> tableModel.addYamlData(key, value) } } private fun refreshListModel() { listModel.removeAllElements() selectedFiles.forEach { file -> listModel.addElement(file.path) } } private fun refreshKeysTable() { val i18nMap = mutableMapOf<String, String>() val yaml = Yaml() selectedFiles.forEach { file -> try { FileInputStream(file.path).use { inputStream -> val data = yaml.load<Map<String, Any>>(inputStream) i18nMap.putAll(flattenMap("", data)) } } catch (e: Exception) { println("Error al analizar el archivo YAML: ${file.path}") } } tableModel.setRowCount(0) i18nMap.forEach { (key, value) -> tableModel.addRow(arrayOf(key, value)) } saveI18nMap(i18nMap) } private fun flattenMap(prefix: String, map: Map<String, Any>): Map<String, String> { val result = mutableMapOf<String, String>() map.forEach { (key, value) -> val fullKey = if (prefix.isBlank()) key else "$prefix.$key" when (value) { is Map<*, *> -> { @Suppress("UNCHECKED_CAST") result.putAll(flattenMap(fullKey, value as Map<String, Any>)) } else -> { result[fullKey] = value.toString() } } } return result } private fun saveI18nMap(i18nMap: Map<String, String>) { val gson = Gson() val i18nMapJson = gson.toJson(i18nMap) PropertiesComponent.getInstance().setValue("PluginConfiguration.I18nMap", i18nMapJson) } private fun saveSelectedFiles() { val paths = selectedFiles.joinToString(separator = ";") { it.path } PropertiesComponent.getInstance().setValue("PluginConfiguration.SelectedFiles", paths) } }
0
Kotlin
0
0
af0362715692944bed00e9f6388ab6abcbc176d0
6,266
intellij-i18n-rails-text-extractor
MIT License
feature/addplace/src/main/java/se/gustavkarlsson/skylight/android/feature/addplace/AddPlaceKnot.kt
wowselim
288,922,417
true
{"Kotlin": 316543}
package se.gustavkarlsson.skylight.android.feature.addplace import com.ioki.textref.TextRef import de.halfbit.knot.Knot import de.halfbit.knot.knot import io.reactivex.Observable import io.reactivex.Scheduler import io.reactivex.functions.Consumer import org.threeten.bp.Duration import se.gustavkarlsson.skylight.android.core.utils.buffer import se.gustavkarlsson.skylight.android.lib.geocoder.Geocoder import se.gustavkarlsson.skylight.android.lib.geocoder.GeocodingResult import se.gustavkarlsson.skylight.android.lib.geocoder.PlaceSuggestion internal data class State( val query: String = "", val suggestions: List<PlaceSuggestion> = emptyList(), val ongoingSearches: Long = 0 ) { val isSearching: Boolean get() = ongoingSearches > 0 } internal sealed class Change { data class Query(val query: String) : Change() data class SearchesSkipped(val skipped: Int) : Change() data class SearchFinished(val suggestions: List<PlaceSuggestion>) : Change() data class SearchFailed(val message: TextRef) : Change() } internal sealed class Action { data class Search(val query: String) : Action() data class ShowError(val message: TextRef) : Action() } internal typealias AddPlaceKnot = Knot<State, Change> internal fun createKnot( geocoder: Geocoder, querySampleDelay: Duration, errorMessageConsumer: Consumer<TextRef>, observeScheduler: Scheduler ): AddPlaceKnot = knot<State, Change, Action> { state { initial = State() observeOn = observeScheduler } changes { reduce { change -> when (change) { is Change.Query -> { val query = change.query.trim() when { this.query == query -> this.only query.isEmpty() -> copy(query = query).only else -> copy( query = query, ongoingSearches = ongoingSearches + 1 ) + Action.Search(query) } } is Change.SearchesSkipped -> copy(ongoingSearches = ongoingSearches - change.skipped).only is Change.SearchFinished -> copy( suggestions = change.suggestions, ongoingSearches = ongoingSearches - 1 ).only is Change.SearchFailed -> copy(ongoingSearches = ongoingSearches - 1) + Action.ShowError(change.message) } } } actions { perform<Action.Search> { map(Action.Search::query) .buffer(querySampleDelay) .filter { it.isNotEmpty() } .flatMap { texts -> Observable.concat( Observable.just(Change.SearchesSkipped(texts.size - 1)), geocoder.geocode(texts.last()) .map { when (val result = it) { is GeocodingResult.Success -> Change.SearchFinished(result.suggestions) GeocodingResult.Failure.Io -> Change.SearchFailed( TextRef.stringRes(R.string.place_search_failed_io) ) GeocodingResult.Failure.ServerError -> Change.SearchFailed( TextRef.stringRes(R.string.place_search_failed_server_response) ) GeocodingResult.Failure.Unknown -> Change.SearchFailed( TextRef.stringRes(R.string.place_search_failed_generic) ) } } .toObservable() ) } } watch<Action.ShowError> { errorMessageConsumer.accept(it.message) } } }
0
null
0
0
4da1731aca92d4e6d4b0e8128ca504fc0b3820b9
4,256
skylight-android
MIT License
src/main/kotlin/dto/Trigger.kt
novuhq
609,113,780
false
null
package co.novu.dto import com.google.gson.annotations.SerializedName data class Trigger( val type: String? = null, @SerializedName("_id") val id: String? = null, val identifier: String? = null, val variables: List<Variables>? = null, val subscriberVariables: List<Variables>? = null, val reservedVariables: List<Variables>? = null )
7
null
8
20
80969d7b96cf8009219bb9891eba5e3a4e2b84c1
364
novu-kotlin
MIT License
app/src/main/java/com/appat/graphicov/utilities/sharedpreferences/SharedPrefUtility.kt
rishadappat
338,528,633
false
null
package com.appat.graphicov.utilities.sharedpreferences import android.content.Context import android.content.SharedPreferences import androidx.lifecycle.LiveData import androidx.preference.PreferenceManager import com.appat.graphicov.utilities.Utility object SharedPrefUtility { private fun getAppPreferences(): SharedPreferences { return PreferenceManager.getDefaultSharedPreferences(Utility.getContext()) } fun getAppPreferences(context: Context): SharedPreferences { return PreferenceManager.getDefaultSharedPreferences(context) } fun saveSelectedCountry(selectedCountry: String) { if(selectedCountry.isNotEmpty()) { getAppPreferences().edit().putString("SelectedCountry", selectedCountry).apply() } } fun getSelectedCountry(): LiveData<String?> { return getAppPreferences().liveData("SelectedCountry", "") } fun saveAnalytics(enabled: Boolean) { getAppPreferences().edit().putBoolean("Analytics", enabled).apply() } fun getAnalytics(): LiveData<Boolean> { return getAppPreferences().liveData("Analytics", true) } }
0
Kotlin
0
5
51c1c81454549509f696b71e769f2966be0cfb4a
1,159
Graphicov
Apache License 2.0
src/main/kotlin/no/nav/klage/oppgave/api/filter/TimingFilter.kt
navikt
297,650,936
false
null
package no.nav.klage.oppgave.api.filter import no.nav.klage.oppgave.util.getLogger import org.springframework.stereotype.Component import java.io.IOException import java.time.Duration import java.time.Instant import javax.servlet.* import javax.servlet.annotation.WebFilter import javax.servlet.http.HttpServletRequest @Component @WebFilter("/klagebehandlinger/*") class TimingFilter : Filter { companion object { private val logger = getLogger(TimingFilter::class.java) } @Throws(ServletException::class) override fun init(filterConfig: FilterConfig) { // empty } @Throws(IOException::class, ServletException::class) override fun doFilter(req: ServletRequest, resp: ServletResponse, chain: FilterChain) { val start = Instant.now() try { chain.doFilter(req, resp) } finally { val finish = Instant.now() val time = Duration.between(start, finish).toMillis() logger.debug("{}: {} ms ", (req as HttpServletRequest).requestURI, time) } } override fun destroy() { // empty } }
2
Kotlin
1
1
7255f8d9a5b0c23e4a22b5bd736d3b656790dfb7
1,122
kabal-api
MIT License
app/src/main/java/com/concordium/wallet/ui/bakerdelegation/common/BaseDelegationBakerRegisterAmountActivity.kt
Concordium
358,250,608
false
null
package com.concordium.wallet.ui.bakerdelegation.common import android.widget.TextView import com.concordium.wallet.R import com.concordium.wallet.data.util.CurrencyUtil import com.concordium.wallet.uicore.view.AmountEditText import com.concordium.wallet.uicore.view.SegmentedControlView import java.math.BigDecimal import java.math.BigInteger import java.text.DecimalFormatSymbols abstract class BaseDelegationBakerRegisterAmountActivity : BaseDelegationBakerActivity() { protected var validateFee: BigInteger? = null protected var baseDelegationBakerRegisterAmountListener: BaseDelegationBakerRegisterAmountListener? = null interface BaseDelegationBakerRegisterAmountListener { fun onReStakeChanged() } protected fun initReStakeOptionsView(reStakeOptions: SegmentedControlView) { val initiallyReStake = if (viewModel.bakerDelegationData.isBakerFlow()) { viewModel.bakerDelegationData.account?.accountBaker?.restakeEarnings == true || viewModel.bakerDelegationData.account?.accountBaker?.restakeEarnings == null } else { viewModel.bakerDelegationData.account?.accountDelegation?.restakeEarnings == true || viewModel.bakerDelegationData.account?.accountDelegation?.restakeEarnings == null } viewModel.bakerDelegationData.restake = initiallyReStake reStakeOptions.clearAll() reStakeOptions.addControl( getString(R.string.delegation_register_delegation_yes_restake), object : SegmentedControlView.OnItemClickListener { override fun onItemClicked() { viewModel.markRestake(true) baseDelegationBakerRegisterAmountListener?.onReStakeChanged() } }, initiallyReStake ) reStakeOptions.addControl( getString(R.string.delegation_register_delegation_no_restake), object : SegmentedControlView.OnItemClickListener { override fun onItemClicked() { viewModel.markRestake(false) baseDelegationBakerRegisterAmountListener?.onReStakeChanged() } }, !initiallyReStake ) } protected fun moreThan95Percent(amountToStake: BigInteger): Boolean { return amountToStake.toBigDecimal() > (viewModel.bakerDelegationData.account?.finalizedBalance ?: BigInteger.ZERO).toBigDecimal() * BigDecimal(0.95) } protected fun validateAmountInput(amount: AmountEditText, amountError: TextView) { if (amount.text.isNotEmpty() && !amount.text.startsWith("Ͼ")) { amount.setText("Ͼ".plus(amount.text.toString())) amount.setSelection(amount.text.length) } setAmountHint(amount) if (amount.text.toString().isNotBlank() && amount.text.toString() != "Ͼ") { val stakeAmountInputValidator = getStakeAmountInputValidator() val stakeError = stakeAmountInputValidator.validate( CurrencyUtil.toGTUValue(amount.text.toString()), validateFee ) if (stakeError != StakeAmountInputValidator.StakeError.OK) { amountError.text = stakeAmountInputValidator.getErrorText(this, stakeError) showError(stakeError) } else { hideError() loadTransactionFee() } } else { hideError() } } protected fun setAmountHint(amount: AmountEditText) { when { amount.text.isNotEmpty() -> { amount.hint = "" } else -> { amount.hint = "Ͼ0" + DecimalFormatSymbols.getInstance().decimalSeparator + "00" } } } abstract fun getStakeAmountInputValidator(): StakeAmountInputValidator abstract fun showError(stakeError: StakeAmountInputValidator.StakeError?) abstract fun hideError() abstract fun loadTransactionFee() }
9
null
3
9
5a273dbcac459e6c2a94b2b9a241eccfcb229cb9
3,988
concordium-reference-wallet-android
Apache License 2.0
core/src/main/kotlin/finance/tegro/core/entity/Reserve.kt
TegroTON
586,902,794
false
{"Kotlin": 227007}
package finance.tegro.core.entity import finance.tegro.core.converter.MsgAddressConverter import org.ton.block.MsgAddress import java.math.BigInteger import java.time.Instant import java.util.* import javax.persistence.* @Entity(name = "reserve") @Table(name = "reserves") open class Reserve( @Convert(converter = MsgAddressConverter::class) @Column(name = "address", nullable = false, columnDefinition = "BYTEA") open val address: MsgAddress, @Column(name = "base", nullable = false, columnDefinition = "NUMERIC") open val base: BigInteger, @Column(name = "quote", nullable = false, columnDefinition = "NUMERIC") open val quote: BigInteger, @ManyToOne(optional = false) @JoinColumn(name = "block_id", nullable = false) open var blockId: BlockId, @Column(name = "timestamp", nullable = false, columnDefinition = "TIMESTAMPTZ") open val timestamp: Instant = Instant.now(), ) { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", nullable = false) open var id: UUID? = null @ManyToOne @JoinColumn(name = "exchange_pair_id") open var exchangePair: ExchangePair? = null }
17
Kotlin
4
0
f15616ec84716f9ecab118b855a8d5aaf5c2a9be
1,172
API-DEX-TON-Blockchain
MIT License
common/src/main/java/com/kernel/finch/components/Divider.kt
kernel0x
197,173,098
false
null
package com.kernel.finch.components import com.kernel.finch.common.contracts.component.Component data class Divider( override val id: String = Component.randomId ) : Component<Divider>
2
null
9
46
4f098309de71b690af5e2a7503444ad1959bf004
191
finch
Apache License 2.0
commons/src/commonMain/kotlin/jetbrains/datalore/base/observable/property/DerivedProperty.kt
JetBrains
176,771,727
false
null
/* * Copyright (c) 2019. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.datalore.base.observable.property import jetbrains.datalore.base.observable.event.EventHandler import jetbrains.datalore.base.observable.event.EventSource import jetbrains.datalore.base.registration.Registration /** * Simplified version of [BaseDerivedProperty] which can depend on generic observable objects. */ abstract class DerivedProperty<ValueT>(initialValue: ValueT, vararg deps: EventSource<*>) : BaseDerivedProperty<ValueT>(initialValue) { private val myDeps: Array<EventSource<*>> = Array(deps.size) { i -> deps[i] } private var myRegistrations: Array<Registration>? = null override fun doAddListeners() { myRegistrations = Array(myDeps.size) { i -> register(myDeps[i]) } } private fun <EventT> register(dep: EventSource<EventT>): Registration { return dep.addHandler(object : EventHandler<EventT> { override fun onEvent(event: EventT) { somethingChanged() } }) } override fun doRemoveListeners() { for (r in myRegistrations!!) { r.remove() } myRegistrations = null } }
98
Kotlin
47
889
c5c66ceddc839bec79b041c06677a6ad5f54e416
1,286
lets-plot
MIT License
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/stage/buff/Buffs.kt
qwewqa
390,928,568
false
null
package xyz.qwewqa.relive.simulator.core.stage.buff import xyz.qwewqa.relive.simulator.core.i54.I54 import xyz.qwewqa.relive.simulator.core.i54.i54 import xyz.qwewqa.relive.simulator.core.stage.ImplementationRegistry import xyz.qwewqa.relive.simulator.core.stage.actor.Actor import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute import xyz.qwewqa.relive.simulator.core.stage.actor.Character import xyz.qwewqa.relive.simulator.core.stage.actor.School import xyz.qwewqa.relive.simulator.core.stage.actor.abnormalCountableBuffs import xyz.qwewqa.relive.simulator.core.stage.modifier.Modifier import xyz.qwewqa.relive.simulator.core.stage.modifier.Modifiers import xyz.qwewqa.relive.simulator.core.stage.modifier.maxHp import xyz.qwewqa.relive.simulator.core.stage.platformSetOf object Buffs : ImplementationRegistry<BuffEffect>() { private fun BuffData.makeDamageOverTimeBuffEffect( modifier: Modifier, exclusive: Boolean = false, locked: Boolean = false, ) = makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, exclusive = exclusive, locked = locked, onStart = { value -> val damage = if (value <= 100) { self.mod { +maxHp ptmul value }.coerceAtMost(99_999.i54) } else { value.toI54() } self.mod { modifier += damage } }, onEnd = { value -> val damage = if (value <= 100) { self.mod { +maxHp ptmul value }.coerceAtMost(99_999.i54) } else { value.toI54() } self.mod { modifier -= damage } }, ) private fun BuffData.makeSpecificResistanceUpBuff( buff: BuffEffect, locked: Boolean = false, ) = makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, locked = locked, onStart = { value -> self.specificBuffResist[buff] = (self.specificBuffResist[buff] ?: 0.i54) + value }, onEnd = { value -> self.specificBuffResist[buff] = (self.specificBuffResist[buff] ?: 0.i54) - value }, ) private inline fun <T> BuffData.makeMapModifierContinuousBuffEffect( crossinline mapAccessor: (Actor) -> MutableMap<T, I54>, key: T, category: BuffCategory, locked: Boolean = false, exclusive: Boolean = false, ) = makeSimpleContinuousBuffEffect( category = category, locked = locked, exclusive = exclusive, onStart = { value -> mapAccessor(self)[key] = (mapAccessor(self)[key] ?: 0.i54) + value }, onEnd = { value -> mapAccessor(self)[key] = (mapAccessor(self)[key] ?: 0.i54) - value }, ) private fun BuffData.againstAttributeDamageReceivedUpBuff(attribute: Attribute) = makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, onStart = { value -> self.againstAttributeDamageReceivedDown[attribute] = (self.againstAttributeDamageReceivedDown[attribute] ?: 0.i54) - value }, onEnd = { value -> self.againstAttributeDamageReceivedDown[attribute] = self.againstAttributeDamageReceivedDown[attribute]!! + value }) private fun BuffData.againstAttributeDamageReceivedDownBuff(attribute: Attribute) = makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, onStart = { value -> self.againstAttributeDamageReceivedDown[attribute] = (self.againstAttributeDamageReceivedDown[attribute] ?: 0.i54) + value }, onEnd = { value -> self.againstAttributeDamageReceivedDown[attribute] = self.againstAttributeDamageReceivedDown[attribute]!! - value }) private fun BuffData.againstAttributeDamageDealtUpBuff(attribute: Attribute) = makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, onStart = { value -> self.againstAttributeDamageDealtUp[attribute] = (self.againstAttributeDamageDealtUp[attribute] ?: 0.i54) + value }, onEnd = { value -> self.againstAttributeDamageDealtUp[attribute] = self.againstAttributeDamageDealtUp[attribute]!! - value }) private fun BuffData.attributeDamageDealtUpBuff(attribute: Attribute) = makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, onStart = { value -> self.attributeDamageDealtUp[attribute] = (self.attributeDamageDealtUp[attribute] ?: 0.i54) + value }, onEnd = { value -> self.attributeDamageDealtUp[attribute] = self.attributeDamageDealtUp[attribute]!! - value }) private fun BuffData.attributeDamageDealtDownBuff(attribute: Attribute) = makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, onStart = { value -> self.attributeDamageDealtUp[attribute] = (self.attributeDamageDealtUp[attribute] ?: 0.i54) - value }, onEnd = { value -> self.attributeDamageDealtUp[attribute] = self.attributeDamageDealtUp[attribute]!! + value }) val ActPowerUpBuff: ContinuousBuffEffect<Unit> = +buffData(1) .makeModifierContinuousBuffEffect( modifier = Modifier.ActPowerUp, category = BuffCategory.Positive, flipped = { ActPowerDownBuff }) val ActPowerDownBuff: ContinuousBuffEffect<Unit> = +buffData(2) .makeModifierContinuousBuffEffect( modifier = Modifier.ActPowerDown, category = BuffCategory.Negative, flipped = { ActPowerUpBuff }) val NormalDefenseUpBuff: ContinuousBuffEffect<Unit> = +buffData(3) .makeModifierContinuousBuffEffect( modifier = Modifier.NormalDefenseUp, category = BuffCategory.Positive, flipped = { NormalDefenseDownBuff }) val NormalDefenseDownBuff: ContinuousBuffEffect<Unit> = +buffData(4) .makeModifierContinuousBuffEffect( modifier = Modifier.NormalDefenseDown, category = BuffCategory.Negative, flipped = { NormalDefenseUpBuff }) val SpecialDefenseUpBuff: ContinuousBuffEffect<Unit> = +buffData(5) .makeModifierContinuousBuffEffect( modifier = Modifier.SpecialDefenseUp, category = BuffCategory.Positive, flipped = { SpecialDefenseDownBuff }) val SpecialDefenseDownBuff: ContinuousBuffEffect<Unit> = +buffData(6) .makeModifierContinuousBuffEffect( modifier = Modifier.SpecialDefenseDown, category = BuffCategory.Negative, flipped = { SpecialDefenseUpBuff }) val AgilityUpBuff: ContinuousBuffEffect<Unit> = +buffData(7) .makeModifierContinuousBuffEffect( modifier = Modifier.AgilityUp, category = BuffCategory.Positive, flipped = { AgilityDownBuff }) val AgilityDownBuff: ContinuousBuffEffect<Unit> = +buffData(8) .makeModifierContinuousBuffEffect( modifier = Modifier.AgilityDown, category = BuffCategory.Negative, flipped = { AgilityUpBuff }) val AccuracyUpBuff: ContinuousBuffEffect<Unit> = +buffData(9) .makeModifierContinuousBuffEffect( modifier = Modifier.BuffAccuracy, category = BuffCategory.Positive, flipped = { AccuracyDownBuff }) val AccuracyDownBuff: ContinuousBuffEffect<Unit> = +buffData(10) .makeModifierContinuousBuffEffect( modifier = Modifier.DebuffAccuracy, category = BuffCategory.Negative, flipped = { AccuracyUpBuff }) val EvasionUpBuff: ContinuousBuffEffect<Unit> = +buffData(11) .makeModifierContinuousBuffEffect( modifier = Modifier.BuffEvasion, category = BuffCategory.Positive, flipped = { EvasionDownBuff }) val EvasionDownBuff: ContinuousBuffEffect<Unit> = +buffData(12) .makeModifierContinuousBuffEffect( modifier = Modifier.DebuffEvasion, category = BuffCategory.Negative, flipped = { EvasionUpBuff }) val DexterityUpBuff: ContinuousBuffEffect<Unit> = +buffData(13) .makeModifierContinuousBuffEffect( modifier = Modifier.BuffDexterity, category = BuffCategory.Positive, flipped = { DexterityDownBuff }) val DexterityDownBuff: ContinuousBuffEffect<Unit> = +buffData(14) .makeModifierContinuousBuffEffect( modifier = Modifier.DebuffDexterity, category = BuffCategory.Negative, flipped = { DexterityUpBuff }) val CriticalUpBuff: ContinuousBuffEffect<Unit> = +buffData(15) .makeModifierContinuousBuffEffect( modifier = Modifier.BuffCritical, category = BuffCategory.Positive, flipped = { CriticalDownBuff }) val CriticalDownBuff: ContinuousBuffEffect<Unit> = +buffData(16) .makeModifierContinuousBuffEffect( modifier = Modifier.DebuffCritical, category = BuffCategory.Negative, flipped = { CriticalUpBuff }) // Note: should not be used as a buff until DoTs are updated to support this val MaxHpUpBuff: ContinuousBuffEffect<Unit> = +buffData(17) .makeModifierContinuousBuffEffect( modifier = Modifier.BuffMaxHp, category = BuffCategory.Positive, ) val MaxHpDownBuff: ContinuousBuffEffect<Unit> = +buffData(18) .makeModifierContinuousBuffEffect( modifier = Modifier.DebuffMaxHp, category = BuffCategory.Negative, ) val ContinuousNegativeEffectResistanceUpBuff = +buffData(19) .makeModifierContinuousBuffEffect( modifier = Modifier.NegativeEffectResistanceUp, category = BuffCategory.Positive, ) val ContinuousNegativeEffectResistanceDownBuff = +buffData(20) .makeModifierContinuousBuffEffect( modifier = Modifier.NegativeEffectResistanceDown, category = BuffCategory.Negative, ) val HpRegenBuff = +buffData(21) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, onStart = { value -> if (value <= 100) { self.mod { Modifier.HpPercentRegen += value } } else { self.mod { Modifier.HpRegen += value } } }, onEnd = { value -> if (value <= 100) { self.mod { Modifier.HpPercentRegen -= value } } else { self.mod { Modifier.HpRegen -= value } } }, ) val BrillianceRegenBuff = +buffData(22) .makeModifierContinuousBuffEffect( modifier = Modifier.BrillianceRegen, category = BuffCategory.Positive, ) val NormalBarrierBuff = +buffData(23) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, ) val SpecialBarrierBuff = +buffData(24) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, ) val NormalReflectBuff = +buffData(25) .makeModifierContinuousBuffEffect( modifier = Modifier.NormalReflect, category = BuffCategory.Positive, ) val SpecialReflectBuff = +buffData(26) .makeModifierContinuousBuffEffect( modifier = Modifier.SpecialReflect, category = BuffCategory.Positive, ) val EvasionBuff = +buffData(27).makeCountableBuffEffect(BuffCategory.Positive) val PerfectAimBuff = +buffData(28) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, exclusive = true, ) val FortitudeBuff = +buffData(29).makeCountableBuffEffect(BuffCategory.Positive) val FixedNormalDefenseBoostBuff = +buffData(30) .makeModifierContinuousBuffEffect( modifier = Modifier.FixedNormalDefense, category = BuffCategory.Positive, ) val FixedSpecialDefenseBoostBuff = +buffData(31) .makeModifierContinuousBuffEffect( modifier = Modifier.FixedSpecialDefense, category = BuffCategory.Positive, ) val EffectiveDamageDealtUpBuff = +buffData(32) .makeModifierContinuousBuffEffect( modifier = Modifier.EffectiveDamageUp, category = BuffCategory.Positive, ) val ClimaxDamageUpBuff: ContinuousBuffEffect<Unit> = +buffData(33) .makeModifierContinuousBuffEffect( modifier = Modifier.ClimaxDamageUp, category = BuffCategory.Positive, exclusive = true, flipped = { ClimaxDamageDownBuff }) val CriticalDamageReceivedDownBuff: ContinuousBuffEffect<Unit> = +buffData(34) .makeModifierContinuousBuffEffect( modifier = Modifier.CriticalDamageReceivedDown, category = BuffCategory.Positive, ) val FixedActPowerBoostBuff = +buffData(35) .makeModifierContinuousBuffEffect( modifier = Modifier.FixedActPower, category = BuffCategory.Positive, ) val AbsorbBuff = +buffData(37) .makeModifierContinuousBuffEffect( modifier = Modifier.Absorb, category = BuffCategory.Positive, ) val CounterHealBuff = +buffData(38) .makeContinuousBuffEffect( category = BuffCategory.Positive, onStart = { value, _ -> if (value <= 100) { self.mod { Modifier.CounterHealPercent += value } } else { self.mod { Modifier.CounterHealFixed += value } } }, onEnd = { value, _, _ -> if (value <= 100) { self.mod { Modifier.CounterHealPercent -= value } } else { self.mod { Modifier.CounterHealFixed -= value } } }, ) // Note: EN localization got the names backwards val AgainstFlowerDamageDealtUpBuff = +buffData(39).againstAttributeDamageDealtUpBuff(Attribute.Flower) val AgainstWindDamageDealtUpBuff = +buffData(40).againstAttributeDamageDealtUpBuff(Attribute.Wind) val AgainstSnowDamageDealtUpBuff = +buffData(41).againstAttributeDamageDealtUpBuff(Attribute.Snow) val AgainstMoonDamageDealtUpBuff = +buffData(42).againstAttributeDamageDealtUpBuff(Attribute.Moon) val AgainstSpaceDamageDealtUpBuff = +buffData(43).againstAttributeDamageDealtUpBuff(Attribute.Space) val AgainstCloudDamageDealtUpBuff = +buffData(44).againstAttributeDamageDealtUpBuff(Attribute.Cloud) val AgainstDreamDamageDealtUpBuff = +buffData(45).againstAttributeDamageDealtUpBuff(Attribute.Dream) // TODO: Do something with this I guess val BonusDamageVsBossesBuff = +buffData(46).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val PoisonBuff = +buffData(47).makeDamageOverTimeBuffEffect(Modifier.PoisonDamage) val BurnBuff = +buffData(48).makeDamageOverTimeBuffEffect(Modifier.BurnDamage) val ProvokeBuff = +buffData(49) .makeContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, onStart = { _, source -> self.provokeTarget = source }, onEnd = { _, _, _ -> self.updateProvokeTarget() }, ) val StunBuff = +buffData(50) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, ) val SleepBuff = +buffData(51) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, ) val ConfusionBuff = +buffData(52) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, ) val StopBuff = +buffData(53) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, ) val FreezeBuff = +buffData(54) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, ) val BlindnessBuff = +buffData(55) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, ) // 56: ??? // 57: ??? val HpRecoveryDownBuff = +buffData(58) .makeModifierContinuousBuffEffect( modifier = Modifier.HpRecoveryDown, category = BuffCategory.Negative, ) val FlowerDamageReceivedDownBuff = +buffData(59).againstAttributeDamageReceivedDownBuff(Attribute.Flower) val WindDamageReceivedDownBuff = +buffData(60).againstAttributeDamageReceivedDownBuff(Attribute.Wind) val SnowDamageReceivedDownBuff = +buffData(61).againstAttributeDamageReceivedDownBuff(Attribute.Snow) val MoonDamageReceivedDownBuff = +buffData(62).againstAttributeDamageReceivedDownBuff(Attribute.Moon) val SpaceDamageReceivedDownBuff = +buffData(63).againstAttributeDamageReceivedDownBuff(Attribute.Space) val CloudDamageReceivedDownBuff = +buffData(64).againstAttributeDamageReceivedDownBuff(Attribute.Cloud) val DreamDamageReceivedDownBuff = +buffData(65).againstAttributeDamageReceivedDownBuff(Attribute.Dream) val FlowerDamageDealtUpBuff = +buffData(66).attributeDamageDealtUpBuff(Attribute.Flower) val WindDamageDealtUpBuff = +buffData(67).attributeDamageDealtUpBuff(Attribute.Wind) val SnowDamageDealtUpBuff = +buffData(68).attributeDamageDealtUpBuff(Attribute.Snow) val MoonDamageDealtUpBuff = +buffData(69).attributeDamageDealtUpBuff(Attribute.Moon) val SpaceDamageDealtUpBuff = +buffData(70).attributeDamageDealtUpBuff(Attribute.Space) val CloudDamageDealtUpBuff = +buffData(71).attributeDamageDealtUpBuff(Attribute.Cloud) val DreamDamageDealtUpBuff = +buffData(72).attributeDamageDealtUpBuff(Attribute.Dream) // We handle this using a special passive // val ActionRestrictionResistanceUpBuffAuto = +buffData(73) val ActionRestrictionResistanceUpBuff = +buffData(74) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, locked = true, onStart = { abnormalBuffs.forEach { buff -> self.specificBuffResist[buff] = (self.specificBuffResist[buff] ?: 0.i54) + 100 } abnormalCountableBuffs.forEach { buff -> self.specificBuffResist[buff] = (self.specificBuffResist[buff] ?: 0.i54) + 100 } }, onEnd = { abnormalBuffs.forEach { buff -> self.specificBuffResist[buff] = self.specificBuffResist[buff]!! - 100 } abnormalCountableBuffs.forEach { buff -> self.specificBuffResist[buff] = self.specificBuffResist[buff]!! - 100 } }, ) val PoisonResistanceUpBuff = +buffData(75).makeSpecificResistanceUpBuff(PoisonBuff) val BurnResistanceUpBuff = +buffData(76).makeSpecificResistanceUpBuff(BurnBuff) val ProvokeResistanceUpBuff = +buffData(77).makeSpecificResistanceUpBuff(ProvokeBuff) val StunResistanceUpBuff = +buffData(78).makeSpecificResistanceUpBuff(StunBuff) val SleepResistanceUpBuff = +buffData(79).makeSpecificResistanceUpBuff(SleepBuff) val ConfusionResistanceUpBuff = +buffData(80).makeSpecificResistanceUpBuff(ConfusionBuff) val StopResistanceUpBuff = +buffData(81).makeSpecificResistanceUpBuff(StopBuff) val FreezeResistanceUpBuff = +buffData(82).makeSpecificResistanceUpBuff(FreezeBuff) val BlindResistanceUpBuff = +buffData(83).makeSpecificResistanceUpBuff(BlindnessBuff) val RecoveryReductionResistance = +buffData(84).makeSpecificResistanceUpBuff(HpRecoveryDownBuff) // Not implemented val AntiSoliderBuff = +buffData(85).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val AntiLancerBuff = +buffData(86).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val AntiFencerBuff = +buffData(87).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val AntiMagicianBuff = +buffData(88).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val AntiShielderBuff = +buffData(89).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val AntiGunnerBuff = +buffData(90).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val AntiJokerBuff = +buffData(91).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val AntiBeastBuff = +buffData(92).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val AntiQQQBuff = +buffData(93).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val AntiMaterialBuff = +buffData(94).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val DamageDealtUpBuff: ContinuousBuffEffect<Unit> = +buffData(95) .makeModifierContinuousBuffEffect( modifier = Modifier.DamageDealtUp, category = BuffCategory.Positive, flipped = { DamageDealtDownBuff }) val DamageDealtDownBuff: ContinuousBuffEffect<Unit> = +buffData(96) .makeModifierContinuousBuffEffect( modifier = Modifier.DamageDealtDown, category = BuffCategory.Negative, flipped = { DamageDealtUpBuff }) val DamageReceivedUpBuff: ContinuousBuffEffect<Unit> = +buffData(97) .makeModifierContinuousBuffEffect( modifier = Modifier.DamageReceivedUp, category = BuffCategory.Negative, flipped = { DamageReceivedDownBuff }) val DamageReceivedDownBuff: ContinuousBuffEffect<Unit> = +buffData(98) .makeModifierContinuousBuffEffect( modifier = Modifier.DamageReceivedDown, category = BuffCategory.Positive, flipped = { DamageReceivedUpBuff }) val MarkBuff: ContinuousBuffEffect<Unit> = +buffData(99) .makeIdempotentContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, flipped = { FlippedMarkBuff }, onStart = { self.mod { Modifier.DamageReceivedUp += 30 } }, onEnd = { self.mod { Modifier.DamageReceivedUp -= 30 } }, ) val FlippedMarkBuff: ContinuousBuffEffect<Unit> = +buffData(100) .makeIdempotentContinuousBuffEffect( category = BuffCategory.Positive, exclusive = true, flipped = { MarkBuff }, onStart = { self.mod { Modifier.DamageReceivedDown += 30 } }, onEnd = { self.mod { Modifier.DamageReceivedDown -= 30 } }, ) val AggroBuff = +buffData(101) .makeContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, onStart = { _, source -> self.aggroTarget = source }, onEnd = { _, _, _ -> self.updateAggroTarget() }, ) val AggroResistanceUpBuff = +buffData(102).makeSpecificResistanceUpBuff(AggroBuff) val ExitEvasionBuff = +buffData(103) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, exclusive = true, ) val InvincibilityBuff = +buffData(104) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, exclusive = true, ) val ApDownBuff: ContinuousBuffEffect<Unit> = +buffData(105) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, flipped = { ApUpBuff }, ) val ApUpBuff: ContinuousBuffEffect<Unit> = +buffData(106) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, flipped = { ApDownBuff }, ) val ApUpResistanceUpBuff = +buffData(107).makeSpecificResistanceUpBuff(ApUpBuff) // 108: ??? // 109: ??? val LockedApUpBuff = +buffData(110).makeLockedVariantOf(ApUpBuff) val LockedStunBuff = +buffData(111).makeLockedVariantOf(StunBuff) val LockedHpRegenBuff = +buffData(112).makeLockedVariantOf(HpRegenBuff) val LockedStopBuff = +buffData(113).makeLockedVariantOf(StopBuff) val LockedCounterHealBuff = +buffData(114).makeLockedVariantOf(CounterHealBuff) // 115: ??? // 116: ??? val AllEffectResistanceUpBuff = +buffData(117) .makeContinuousBuffEffect( category = BuffCategory.Positive, locked = true, onStart = { value, _ -> self.mod { Modifier.PositiveEffectResistanceUp += value Modifier.PositiveCountableEffectResistanceUp += value Modifier.NegativeEffectResistanceUp += value Modifier.NegativeCountableEffectResistanceUp += value } }, onEnd = { value, _, _ -> self.mod { Modifier.PositiveEffectResistanceUp -= value Modifier.PositiveCountableEffectResistanceUp += value Modifier.NegativeEffectResistanceUp -= value Modifier.NegativeCountableEffectResistanceUp -= value } }, ) val MarkResistanceUpBuff = +buffData(118).makeSpecificResistanceUpBuff(MarkBuff) // Not implemented val EventBossDamageReductionBuff = +buffData(119).makeSimpleContinuousBuffEffect(BuffCategory.Positive) // Not Implemented val SealAct1Buff = +buffData(120).makeSimpleContinuousBuffEffect(BuffCategory.Negative) val SealAct2Buff = +buffData(121).makeSimpleContinuousBuffEffect(BuffCategory.Negative) val SealAct3Buff = +buffData(122).makeSimpleContinuousBuffEffect(BuffCategory.Negative) val SealAct1ResistanceUpBuff = +buffData(123).makeSpecificResistanceUpBuff(SealAct1Buff) val SealAct2ResistanceUpBuff = +buffData(124).makeSpecificResistanceUpBuff(SealAct2Buff) val SealAct3ResistanceUpBuff = +buffData(125).makeSpecificResistanceUpBuff(SealAct3Buff) val BrillianceGainDownBuff = +buffData(126) .makeModifierContinuousBuffEffect(Modifier.BrillianceGainDown, BuffCategory.Negative) val BrillianceGainDownResistanceBuff = +buffData(127).makeSpecificResistanceUpBuff(BrillianceGainDownBuff) val LockedPoisonResistanceUpBuff = +buffData(128).makeLockedVariantOf(PoisonResistanceUpBuff) val LockedBurnResistanceUpBuff = +buffData(129).makeLockedVariantOf(BurnResistanceUpBuff) val LockedStunResistanceUpBuff = +buffData(130).makeLockedVariantOf(StunResistanceUpBuff) val LockedSleepResistanceUpBuff = +buffData(131).makeLockedVariantOf(SleepResistanceUpBuff) val LockedConfusionResistanceUpBuff = +buffData(132).makeLockedVariantOf(ConfusionResistanceUpBuff) val LockedStopResistanceUpBuff = +buffData(133).makeLockedVariantOf(StopResistanceUpBuff) val LockedFreezeResistanceUpBuff = +buffData(134).makeLockedVariantOf(FreezeResistanceUpBuff) val LockedBlindResistanceUpBuff = +buffData(135).makeLockedVariantOf(BlindResistanceUpBuff) val CountableActChangeBuff = +buffData(136).makeCountableBuffEffect(BuffCategory.Positive) val ContinuousActChangeBuff = +buffData(137).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val LockedConfusionBuff = +buffData(138).makeLockedVariantOf(ConfusionBuff) val ResilienceBuff = +buffData(139) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, exclusive = true, ) val LockedPoisonBuff = +buffData(140).makeLockedVariantOf(PoisonBuff) val LockedBurnBuff = +buffData(141).makeLockedVariantOf(BurnBuff) val LockedBlindnessBuff = +buffData(142).makeLockedVariantOf(BlindnessBuff) val LockedHpRecoveryDownBuff = +buffData(143).makeLockedVariantOf(HpRecoveryDownBuff) // val ContinuousDamageResistanceUpBuff = // +buffData(144).makeSpecificResistanceUpBuff(ContinuousDamageBuff) // val StrongPoisonResistanceUpBuff = // +buffData(145).makeSpecificResistanceUpBuff(StrongPoisonBuff) // val HeavyBurnResistanceUpBuff = +buffData(146).makeSpecificResistanceUpBuff(HeavyBurnBuff) val FlowerDamageReceivedUpBuff = +buffData(147).againstAttributeDamageReceivedUpBuff(Attribute.Flower) val WindDamageReceivedUpBuff = +buffData(148).againstAttributeDamageReceivedUpBuff(Attribute.Wind) val SnowDamageReceivedUpBuff = +buffData(149).againstAttributeDamageReceivedUpBuff(Attribute.Snow) val MoonDamageReceivedUpBuff = +buffData(150).againstAttributeDamageReceivedUpBuff(Attribute.Moon) val SpaceDamageReceivedUpBuff = +buffData(151).againstAttributeDamageReceivedUpBuff(Attribute.Space) val CloudDamageReceivedUpBuff = +buffData(152).againstAttributeDamageReceivedUpBuff(Attribute.Cloud) val DreamDamageReceivedUpBuff = +buffData(153).againstAttributeDamageReceivedUpBuff(Attribute.Dream) val FlowerDamageDealtDownBuff = +buffData(154).attributeDamageDealtDownBuff(Attribute.Flower) val WindDamageDealtDownBuff = +buffData(155).attributeDamageDealtDownBuff(Attribute.Wind) val SnowDamageDealtDownBuff = +buffData(156).attributeDamageDealtDownBuff(Attribute.Snow) val MoonDamageDealtDownBuff = +buffData(157).attributeDamageDealtDownBuff(Attribute.Moon) val SpaceDamageDealtDownBuff = +buffData(158).attributeDamageDealtDownBuff(Attribute.Space) val CloudDamageDealtDownBuff = +buffData(159).attributeDamageDealtDownBuff(Attribute.Cloud) val DreamDamageDealtDownBuff = +buffData(160).attributeDamageDealtDownBuff(Attribute.Dream) val ClimaxDamageDownBuff: ContinuousBuffEffect<Unit> = +buffData(161) .makeModifierContinuousBuffEffect( modifier = Modifier.ClimaxDamageDown, category = BuffCategory.Negative, flipped = { ClimaxDamageUpBuff }) val LovesicknessBuff = +buffData(162) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, ) val LockedLovesicknessBuff = +buffData(163).makeLockedVariantOf(LovesicknessBuff) val LovesicknessResistanceUpBuff = +buffData(164).makeSpecificResistanceUpBuff(LovesicknessBuff) val LockedLovesicknessResistanceUpBuff = +buffData(165).makeLockedVariantOf(LovesicknessResistanceUpBuff) val LockedContinuousNegativeEffectResistanceUpBuff = +buffData(166).makeLockedVariantOf(ContinuousNegativeEffectResistanceUpBuff) // Not implemented val SealCABuff = +buffData(167).makeSimpleContinuousBuffEffect(BuffCategory.Negative) val LockedSealCABuff = +buffData(168).makeLockedVariantOf(SealCABuff) val ElectricShockBuff = +buffData(169) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, ) val LockedElectricShockBuff = +buffData(170).makeLockedVariantOf(ElectricShockBuff) val ElectricShockResistanceUpBuff = +buffData(171).makeSpecificResistanceUpBuff(ElectricShockBuff) val LockedElectricShockResistanceUpBuff = +buffData(172).makeLockedVariantOf(ElectricShockResistanceUpBuff) val ReviveBuff = +buffData(173).makeCountableBuffEffect(BuffCategory.Positive) val NightmareBuff = +buffData(174).makeDamageOverTimeBuffEffect(Modifier.NightmareDamage, exclusive = true) val ContinuousPositiveEffectResistanceUpBuff = +buffData(175) .makeModifierContinuousBuffEffect( modifier = Modifier.PositiveEffectResistanceUp, category = BuffCategory.Negative) val LockedContinuousPositiveEffectResistanceUpBuff = +buffData(176).makeLockedVariantOf(ContinuousPositiveEffectResistanceUpBuff) val PositiveEffectResistanceUpBuff = +buffData(177) .makeContinuousBuffEffect( category = BuffCategory.Positive, locked = true, onStart = { value, _ -> self.mod { Modifier.PositiveEffectResistanceUp += value Modifier.PositiveCountableEffectResistanceUp += value } }, onEnd = { value, _, _ -> self.mod { Modifier.PositiveEffectResistanceUp -= value Modifier.PositiveCountableEffectResistanceUp += value } }, ) val LockedPositiveEffectResistanceUpBuff = +buffData(178).makeLockedVariantOf(PositiveEffectResistanceUpBuff) val DazeBuff = +buffData(179).makeCountableBuffEffect(BuffCategory.Negative) val ImpudenceBuff = +buffData(180).makeCountableBuffEffect(BuffCategory.Negative) val HopeBuff = +buffData(181).makeCountableBuffEffect(BuffCategory.Positive) val WeakSpotBuff = +buffData(182).makeCountableBuffEffect(BuffCategory.Negative) val FixedAgilityBoost = +buffData(183) .makeModifierContinuousBuffEffect( modifier = Modifier.FixedAgility, category = BuffCategory.Positive, ) val FixedMaxHpBoost = +buffData(184) .makeModifierContinuousBuffEffect( modifier = Modifier.FixedMaxHp, category = BuffCategory.Positive, ) val FrostbiteBuff = +buffData(185).makeDamageOverTimeBuffEffect(Modifier.FrostbiteDamage, exclusive = true) val DamageToSeishoUpBuff = +buffData(186) .makeMapModifierContinuousBuffEffect( { it.againstSchoolDamageDealtUp }, key = School.Seisho, category = BuffCategory.Positive, ) val DamageToRinmeikanUpBuff = +buffData(187) .makeMapModifierContinuousBuffEffect( { it.againstSchoolDamageDealtUp }, key = School.Rinmeikan, category = BuffCategory.Positive, ) val DamageToFrontierUpBuff = +buffData(188) .makeMapModifierContinuousBuffEffect( { it.againstSchoolDamageDealtUp }, key = School.Frontier, category = BuffCategory.Positive, ) val DamageToSiegfeldUpBuff = +buffData(189) .makeMapModifierContinuousBuffEffect( { it.againstSchoolDamageDealtUp }, key = School.Siegfeld, category = BuffCategory.Positive, ) val DamageToSeiranUpBuff = +buffData(190) .makeMapModifierContinuousBuffEffect( { it.againstSchoolDamageDealtUp }, key = School.Seiran, category = BuffCategory.Positive, ) val DamageFromKarenUpBuff = +buffData(191) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Karen, category = BuffCategory.Negative, ) val DamageFromHikariUpBuff = +buffData(192) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Hikari, category = BuffCategory.Negative, ) val DamageFromMahiruUpBuff = +buffData(193) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Mahiru, category = BuffCategory.Negative, ) val DamageFromClaudineUpBuff = +buffData(194) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Claudine, category = BuffCategory.Negative, ) val DamageFromMayaUpBuff = +buffData(195) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Maya, category = BuffCategory.Negative, ) val DamageFromJunnaUpBuff = +buffData(196) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Junna, category = BuffCategory.Negative, ) val DamageFromNanaUpBuff = +buffData(197) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Nana, category = BuffCategory.Negative, ) val DamageFromFutabaUpBuff = +buffData(198) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Futaba, category = BuffCategory.Negative, ) val DamageFromKaorukoUpBuff = +buffData(199) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Kaoruko, category = BuffCategory.Negative, ) val DamageFromTamaoUpBuff = +buffData(200) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Tamao, category = BuffCategory.Negative, ) val DamageFromIchieUpBuff = +buffData(201) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Ichie, category = BuffCategory.Negative, ) val DamageFromFumiUpBuff = +buffData(202) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Fumi, category = BuffCategory.Negative, ) val DamageFromRuiUpBuff = +buffData(203) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Rui, category = BuffCategory.Negative, ) val DamageFromYuyukoUpBuff = +buffData(204) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Yuyuko, category = BuffCategory.Negative, ) val DamageFromAruruUpBuff = +buffData(205) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Aruru, category = BuffCategory.Negative, ) val DamageFromMisoraUpBuff = +buffData(206) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Misora, category = BuffCategory.Negative, ) val DamageFromLalafinUpBuff = +buffData(207) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Lalafin, category = BuffCategory.Negative, ) val DamageFromTsukasaUpBuff = +buffData(208) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Tsukasa, category = BuffCategory.Negative, ) val DamageFromShizuhaUpBuff = +buffData(209) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Shizuha, category = BuffCategory.Negative, ) val DamageFromAkiraUpBuff = +buffData(210) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Akira, category = BuffCategory.Negative, ) val DamageFromMichiruUpBuff = +buffData(211) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Michiru, category = BuffCategory.Negative, ) val DamageFromMeiFanUpBuff = +buffData(212) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.MeiFan, category = BuffCategory.Negative, ) val DamageFromShioriUpBuff = +buffData(213) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Shiori, category = BuffCategory.Negative, ) val DamageFromYachiyoUpBuff = +buffData(214) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Yachiyo, category = BuffCategory.Negative, ) val DamageFromKoharuUpBuff = +buffData(215) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Koharu, category = BuffCategory.Negative, ) val DamageFromSuzuUpBuff = +buffData(216) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Suzu, category = BuffCategory.Negative, ) val DamageFromHisameUpBuff = +buffData(217) .makeMapModifierContinuousBuffEffect( { it.fromCharacterDamageReceivedUp }, key = Character.Hisame, category = BuffCategory.Negative, ) val AgonyBuff = +buffData(218) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, ) val LockedAggroBuff = +buffData(219).makeLockedVariantOf(AggroBuff) val LockedSealAct1Buff = +buffData(220).makeLockedVariantOf(SealAct1Buff) val LockedSealAct2Buff = +buffData(221).makeLockedVariantOf(SealAct2Buff) val LockedSealAct3Buff = +buffData(222).makeLockedVariantOf(SealAct3Buff) val LockedNormalBarrierBuff = +buffData(223).makeLockedVariantOf(NormalBarrierBuff) val LockedSpecialBarrierBuff = +buffData(224).makeLockedVariantOf(SpecialBarrierBuff) val PossessionBuff = +buffData(225) .makeContinuousBuffEffect( BuffCategory.Positive, related = ResilienceBuff, onStart = { _, _ -> self.mod { Modifier.NegativeEffectResistanceUp += 100 } }, onEnd = { _, _, _ -> self.mod { Modifier.NegativeEffectResistanceUp -= 100 } self.exit() }, ) val LockedPossessionBuff = +buffData(226).makeLockedVariantOf(PossessionBuff) val LockedApDownBuff = +buffData(227).makeLockedVariantOf(ApDownBuff) val LockedCriticalUpBuff = +buffData(228).makeLockedVariantOf(CriticalUpBuff) // Not implemented // Doesn't work in PvE anyways val CurtainsClosedBuff = +buffData(229).makeSimpleContinuousBuffEffect(BuffCategory.Negative) val LockedCurtainsClosedBuff = +buffData(230).makeLockedVariantOf(CurtainsClosedBuff) val NegativeCountableEffectResistanceUpBuff = +buffData(231) .makeModifierContinuousBuffEffect( modifier = Modifier.NegativeCountableEffectResistanceUp, category = BuffCategory.Positive, ) val LockedNegativeCountableEffectResistanceUpBuff = +buffData(232).makeLockedVariantOf(NegativeCountableEffectResistanceUpBuff) val BrillianceGainUpBuff = +buffData(233) .makeModifierContinuousBuffEffect( modifier = Modifier.BrillianceGainUp, category = BuffCategory.Positive, ) val LockedResilienceBuff = +buffData(234).makeLockedVariantOf(ResilienceBuff) val ApUp2Buff: ContinuousBuffEffect<Unit> = +buffData(235) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, ) val LockedApUp2Buff: ContinuousBuffEffect<Unit> = +buffData(236) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, ) val ApDown2Buff: ContinuousBuffEffect<Unit> = +buffData(237) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, ) val LockedApDown2Buff: ContinuousBuffEffect<Unit> = +buffData(238) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, ) val CutinInitialCooldownReductionBuff = +buffData(239) .makeContinuousBuffEffect( category = BuffCategory.Positive, onStart = { value, _ -> self.cutinInitialCooldownReductionPool += value }, onEnd = { value, _, _ -> self.cutinInitialCooldownReductionPool -= value }, ) val CounterHealBuff2 = +buffData(240) .makeModifierContinuousBuffEffect( modifier = Modifier.CounterHealFixed, category = BuffCategory.Positive, ) val HoldBackBuff = +buffData(241).makeCountableBuffEffect(BuffCategory.Negative) val SealStageEffectBuff = +buffData(242).makeSimpleContinuousBuffEffect(BuffCategory.Negative) val LockedSealStageEffectBuff = +buffData(243).makeLockedVariantOf(SealStageEffectBuff) // This is for OR, so it's not really used val AddActs1Buff = +buffData(244).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val AddActs2Buff = +buffData(245).makeSimpleContinuousBuffEffect(BuffCategory.Positive) // val BulkheadBuff = +buffData(246).makeSimpleContinuousBuffEffect(BuffCategory.Positive) // Not implemented val AntiOathRevueBuff = +buffData(247).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val DisasterBrillianceReductionBuff = +buffData(248).makeCountableBuffEffect(BuffCategory.Negative) val BlessingHpRecoveryBuff = +buffData(249).makeCountableBuffEffect(BuffCategory.Positive) val BlessingReduceCountableNegativeEffectsBuff = +buffData(250).makeCountableBuffEffect(BuffCategory.Positive) val DisasterDaze = +buffData(251).makeCountableBuffEffect(BuffCategory.Negative) val BlessingRemoveContinuousNegativeEffectsBuff = +buffData(252).makeCountableBuffEffect(BuffCategory.Positive) val DazeResistanceUpBuff = +buffData(253).makeSpecificResistanceUpBuff(DazeBuff) val LockedDazeResistanceUpBuff = +buffData(254).makeLockedVariantOf(DazeResistanceUpBuff) val BlessingHopeBuff = +buffData(255).makeCountableBuffEffect(BuffCategory.Positive) val ImpudenceResistanceUpBuff = +buffData(256).makeSpecificResistanceUpBuff(ImpudenceBuff) val LockedImpudenceResistanceUpBuff = +buffData(257).makeLockedVariantOf(ImpudenceResistanceUpBuff) val NormalSuperReflectBuff = +buffData(258) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, ) val SpecialSuperReflectBuff = +buffData(259) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, ) val LockedNormalSuperReflectBuff = +buffData(260).makeLockedVariantOf(NormalSuperReflectBuff) val LockedSpecialSuperReflectBuff = +buffData(261).makeLockedVariantOf(SpecialSuperReflectBuff) val BlessingEffectiveDamageUpBuff = +buffData(262).makeCountableBuffEffect(BuffCategory.Positive) val InvincibleRebirthBuff = +buffData(263).makeCountableBuffEffect(BuffCategory.Positive) // TODO: implement this val SacrificeBuff = +buffData(264).makeCountableBuffEffect(BuffCategory.Negative) val DisasterApUpBuff = +buffData(265).makeCountableBuffEffect(BuffCategory.Negative) val BlessingApDown2 = +buffData(266).makeCountableBuffEffect(BuffCategory.Positive) val ContractionBuff = +buffData(267) .makeSimpleContinuousBuffEffect( category = BuffCategory.Negative, exclusive = true, ) val HpRegenBuff2 = +buffData(268) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, onStart = { value -> if (value <= 100) { self.mod { Modifier.HpPercentRegen += value } } else { self.mod { Modifier.HpRegen += value } } }, onEnd = { value -> if (value <= 100) { self.mod { Modifier.HpPercentRegen -= value } } else { self.mod { Modifier.HpRegen -= value } } }, ) // TODO: Not implemented val SealInstantSkillBuff = +buffData(269).makeSimpleContinuousBuffEffect(BuffCategory.Negative) val LockedSealInstantSkillBuff = +buffData(270).makeLockedVariantOf(SealInstantSkillBuff) val CountablePositiveEffectResistanceUpBuff = +buffData(271) .makeModifierContinuousBuffEffect( modifier = Modifier.PositiveCountableEffectResistanceUp, category = BuffCategory.Negative, ) val LockedCountablePositiveEffectResistanceUpBuff = +buffData(272).makeLockedVariantOf(CountablePositiveEffectResistanceUpBuff) val LockedPerfectAimBuff = +buffData(273).makeLockedVariantOf(PerfectAimBuff) val StaminaActPowerUpBuff = +buffData(274) .makeModifierContinuousBuffEffect( modifier = Modifier.StaminaActPowerUp, category = BuffCategory.Positive, ) val OverwhelmBuff = +buffData(275).makeCountableBuffEffect(BuffCategory.Negative, isLocked = true) val MultipleCAficationBuff = +buffData(276) .makeSimpleContinuousBuffEffect( category = BuffCategory.Positive, exclusive = true, ) val BrillianceSapBuff = +buffData(277) .makeModifierContinuousBuffEffect( modifier = Modifier.BrillianceSap, category = BuffCategory.Negative, ) val LockedEffectiveDamageDealtUpBuff = +buffData(278).makeLockedVariantOf(EffectiveDamageDealtUpBuff) val LockedBrillianceRegenBuff = +buffData(279).makeLockedVariantOf(BrillianceRegenBuff) val ReviveRegenBuff = +buffData(280) .makeModifierContinuousBuffEffect( modifier = Modifier.ReviveRegen, category = BuffCategory.Positive, ) val LockedInvincibilityBuff = +buffData(281).makeLockedVariantOf(InvincibilityBuff) val SealStageEffectResistanceUpBuff = +buffData(282).makeSpecificResistanceUpBuff(SealStageEffectBuff) val LockedSealStageEffectResistanceUpBuff = +buffData(283).makeLockedVariantOf(SealStageEffectResistanceUpBuff) val TurnRemoveContinuousNegativeEffectsBuff = +buffData(284).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val LockedTurnRemoveContinuousNegativeEffectsBuff = +buffData(285).makeLockedVariantOf(TurnRemoveContinuousNegativeEffectsBuff) val TurnRemoveCountableNegativeEffectsBuff = +buffData(286).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val LockedTurnRemoveCountableNegativeEffectsBuff = +buffData(287).makeLockedVariantOf(TurnRemoveCountableNegativeEffectsBuff) val TurnRemoveContinuousPositiveEffectsBuff = +buffData(288).makeSimpleContinuousBuffEffect(BuffCategory.Negative) val LockedTurnRemoveContinuousPositiveEffectsBuff = +buffData(289).makeLockedVariantOf(TurnRemoveContinuousPositiveEffectsBuff) // val TurnRemoveCountablePositiveEffectsBuff = // +buffData(xxx).makeSimpleContinuousBuffEffect(BuffCategory.Negative) // // val LockedTurnRemoveCountablePositiveEffectsBuff = // +buffData(xxx).makeLockedVariantOf(TurnRemoveCountablePositiveEffectsBuff) val SuperStrengthBuff = +buffData(290).makeCountableBuffEffect(BuffCategory.Positive) val SuperStrengthRegenBuff = +buffData(292) .makeModifierContinuousBuffEffect( modifier = Modifier.SuperStrengthRegen, category = BuffCategory.Positive, ) val LockedSuperStrengthRegenBuff = +buffData(293).makeLockedVariantOf(SuperStrengthRegenBuff) val CheerBuff = +buffData(294).makeCountableBuffEffect(BuffCategory.Positive) val TurnReduceCountableNegativeEffectsBuff = +buffData(297) .makeModifierContinuousBuffEffect( modifier = Modifier.TurnReduceCountableNegativeEffects, category = BuffCategory.Positive, ) val LockedTurnReduceCountableNegativeEffectsBuff = +buffData(298).makeLockedVariantOf(TurnReduceCountableNegativeEffectsBuff) val BrillianceRegenTurnScalingBuff = +buffData(299) .makeModifierContinuousBuffEffect( modifier = Modifier.BrillianceRegenTurnScaling, category = BuffCategory.Positive, ) val LockedBrillianceRegenTurnScalingBuff = +buffData(300).makeLockedVariantOf(BrillianceRegenTurnScalingBuff) val LockedAgonyBuff = +buffData(301).makeLockedVariantOf(AgonyBuff) val SealMultipleCABuff = +buffData(302).makeSimpleContinuousBuffEffect(BuffCategory.Negative) val LockedSealMultipleCABuff = +buffData(303).makeLockedVariantOf(SealMultipleCABuff) // TODO: Implement this if needed val FumblingInTheDarkBuff = +buffData(304).makeSimpleContinuousBuffEffect(BuffCategory.Negative) val EvilCurseBuff = +buffData(305).makeSimpleContinuousBuffEffect(BuffCategory.Negative) val ActBoostImpudenceBuff = +buffData(306).makeCountableBuffEffect(BuffCategory.Positive) val BlessingRemoveCountableNegativeEffectsBuff = +buffData(307).makeCountableBuffEffect(BuffCategory.Positive) val DelusionBuff = +buffData(308).makeCountableBuffEffect(BuffCategory.Negative) val CutinCustReductionBuff = +buffData(309) .makeContinuousBuffEffect( category = BuffCategory.Positive, onStart = { value, _ -> self.cutinCostReductionPool += value }, onEnd = { value, _, _ -> self.cutinCostReductionPool -= value }, ) val LockedCutinCustReductionBuff = +buffData(310).makeLockedVariantOf(CutinCustReductionBuff) val ActBoostDazeBuff = +buffData(311).makeCountableBuffEffect(BuffCategory.Positive) // TODO: Implement this if needed val ReflectStageEffectSelfTrappingBuff = +buffData(312).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val ReflectStageEffectCaptivatingPupilsBuff = +buffData(313).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val WeakenBuff = +buffData(314) .makeModifierContinuousBuffEffect( modifier = Modifier.Weaken, category = BuffCategory.Negative, ) // TODO: Implement val StageEffectSealResistanceRegenBuff = +buffData(315).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val ContinuousPositiveTurnReductionRegenBuff = +buffData(316) .makeModifierContinuousBuffEffect( modifier = Modifier.ContinuousPositiveTurnReductionRegen, category = BuffCategory.Negative, ) val LockedContinuousPositiveTurnReductionRegenBuff = +buffData(317).makeLockedVariantOf(ContinuousPositiveTurnReductionRegenBuff) val ReflectStageEffectHesitationBuffEffect = +buffData(318).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val ReflectStageEffectPlanOfTheAbyssBuffEffect = +buffData(319).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val ReflectStageEffectSugaryCorruptionBuffEffect = +buffData(320).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val AgonyResistanceUpBuff = +buffData(321).makeSpecificResistanceUpBuff(AgonyBuff) val LockedAgonyResistanceUpBuff = +buffData(322).makeLockedVariantOf(AgonyResistanceUpBuff) val SealCAResistanceUpBuff = +buffData(323).makeSpecificResistanceUpBuff(SealCABuff) val LockedSealCAResistanceUpBuff = +buffData(324).makeLockedVariantOf(SealCAResistanceUpBuff) val AccuracyDownResistanceUpBuff = +buffData(325).makeSpecificResistanceUpBuff(AccuracyDownBuff) val LockedAccuracyDownResistanceUpBuff = +buffData(326).makeLockedVariantOf(AccuracyDownResistanceUpBuff) val AgilityDownResistanceUpBuff = +buffData(327).makeSpecificResistanceUpBuff(AgilityDownBuff) val LockedAgilityDownResistanceUpBuff = +buffData(328).makeLockedVariantOf(AgilityDownResistanceUpBuff) val DelusionResistanceUpBuff = +buffData(329).makeSpecificResistanceUpBuff(DelusionBuff) val LockedDelusionResistanceUpBuff = +buffData(330).makeLockedVariantOf(DelusionResistanceUpBuff) // TODO: Implement falling out val FallingOutDaze = +buffData(331) .makeCountableBuffEffect( category = BuffCategory.Negative, ) val FallingOutImpudence = +buffData(332) .makeCountableBuffEffect( category = BuffCategory.Negative, ) val ContractionResistanceUpBuff = +buffData(333) .makeSpecificResistanceUpBuff( ContractionBuff, ) val LockedContractionResistanceUpBuff = +buffData(334).makeLockedVariantOf(ContractionResistanceUpBuff) val ReflectStageEffectGrayWorldBuff = +buffData(335).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val ReflectStageEffectThunderBuff = +buffData(336).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val StealResistanceUpBuff = +buffData(337).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val NegativeStageEffectResistanceUp = +buffData(338).makeSimpleContinuousBuffEffect(BuffCategory.Positive) val PositiveStageEffectResistanceUp = +buffData(339).makeSimpleContinuousBuffEffect(BuffCategory.Negative) val GreaterBurnBuff = +buffData(1001).makeGreaterVariantOf(BurnBuff) val GreaterConfusionBuff = +buffData(1002).makeGreaterVariantOf(ConfusionBuff) val GreaterBlindnessBuff = +buffData(1003).makeGreaterVariantOf(BlindnessBuff) val GreaterFreezeBuff = +buffData(1004).makeGreaterVariantOf(FreezeBuff) val GreaterApUpBuff = +buffData(1005).makeGreaterVariantOf(ApUpBuff) val GreaterProvokeBuff = +buffData(1006).makeGreaterVariantOf(ProvokeBuff) // TODO: figure out if greater resistances affect base resistances val GreaterBurnResistanceUpBuff = +buffData(1007).makeSpecificResistanceUpBuff(GreaterBurnBuff) val GreaterBlindnessResistanceUpBuff = +buffData(1008).makeSpecificResistanceUpBuff(GreaterBlindnessBuff) val GreaterConfusionResistanceUpBuff = +buffData(1009).makeSpecificResistanceUpBuff(GreaterConfusionBuff) val GreaterDamageReceivedDownBuff = +buffData(1010).makeGreaterVariantOf(DamageReceivedDownBuff) val GreaterEvasionBuff = +buffData(1011).makeGreaterVariantOf(EvasionBuff) val GreaterStopBuff = +buffData(1012).makeGreaterVariantOf(StopBuff) val GreaterFortitudeBuff = +buffData(1013).makeGreaterVariantOf(FortitudeBuff) val GreaterFreezeResistanceUpBuff = +buffData(1014).makeSpecificResistanceUpBuff(GreaterFreezeBuff) val GreaterStopResistanceUpBuff = +buffData(1015).makeSpecificResistanceUpBuff(GreaterStopBuff) val GreaterFrostbiteBuff = +buffData(1016).makeGreaterVariantOf(FrostbiteBuff) val GreaterElectricShockBuff = +buffData(1017).makeGreaterVariantOf(ElectricShockBuff) val GreaterAgonyBuff = +buffData(1018).makeGreaterVariantOf(AgonyBuff) val GreaterAgonyResistanceUpBuff = +buffData(1019).makeSpecificResistanceUpBuff(GreaterAgonyBuff) val abnormalBuffs = platformSetOf( StopBuff, SleepBuff, NightmareBuff, ConfusionBuff, FreezeBuff, StunBuff, LockedStunBuff, BurnBuff, LockedBurnBuff, PoisonBuff, LockedPoisonBuff, AgonyBuff, LockedAgonyBuff, LovesicknessBuff, LockedLovesicknessBuff, ElectricShockBuff, LockedElectricShockBuff, FrostbiteBuff, ) fun againstAttributeDamageDealtUpBuff(attribute: Attribute) = when (attribute) { Attribute.Flower -> AgainstFlowerDamageDealtUpBuff Attribute.Wind -> AgainstWindDamageDealtUpBuff Attribute.Snow -> AgainstSnowDamageDealtUpBuff Attribute.Moon -> AgainstMoonDamageDealtUpBuff Attribute.Space -> AgainstSpaceDamageDealtUpBuff Attribute.Cloud -> AgainstCloudDamageDealtUpBuff Attribute.Dream -> AgainstDreamDamageDealtUpBuff else -> error("Attribute $attribute not supported") } fun againstAttributeDamageReceivedUpBuff(attribute: Attribute) = when (attribute) { Attribute.Flower -> FlowerDamageReceivedUpBuff Attribute.Wind -> WindDamageReceivedUpBuff Attribute.Snow -> SnowDamageReceivedUpBuff Attribute.Moon -> MoonDamageReceivedUpBuff Attribute.Space -> SpaceDamageReceivedUpBuff Attribute.Cloud -> CloudDamageReceivedUpBuff Attribute.Dream -> DreamDamageReceivedUpBuff else -> error("Attribute $attribute not supported") } fun againstAttributeDamageReceivedDownBuff(attribute: Attribute) = when (attribute) { Attribute.Flower -> FlowerDamageReceivedDownBuff Attribute.Wind -> WindDamageReceivedDownBuff Attribute.Snow -> SnowDamageReceivedDownBuff Attribute.Moon -> MoonDamageReceivedDownBuff Attribute.Space -> SpaceDamageReceivedDownBuff Attribute.Cloud -> CloudDamageReceivedDownBuff Attribute.Dream -> DreamDamageReceivedDownBuff else -> error("Attribute $attribute not supported") } } inline val Modifiers.apChange: Int get() = actor.buffs.run { val decrease = when { Buffs.ApDown2Buff in this -> 2 Buffs.ApDownBuff in this -> 1 else -> 0 } val increase = when { Buffs.ApUp2Buff in this -> 2 Buffs.ApUpBuff in this || Buffs.GreaterApUpBuff in this -> 1 else -> 0 } increase - decrease } val Actor.hasMultipleCA get() = (dress.multipleCA || Buffs.MultipleCAficationBuff in buffs) && Buffs.SealMultipleCABuff !in buffs
2
Kotlin
11
7
e32dab696f56ead176e35fca40add33ad1e7f742
62,993
relight
MIT License
src/main/kotlin/pl/szymeker/csvwarehouse/query/AggregationValue.kt
szymeker
418,118,807
false
null
package pl.szymeker.csvwarehouse.query import pl.szymeker.csvwarehouse.dimension.MetricDimension data class AggregationValue(val metrics: MutableMap<MetricDimension, Number>) { fun merge(metricDimension: MetricDimension, value: String?) { metrics.merge(metricDimension, metricDimension.value(value)) { n1, n2 -> metricDimension.merge(n1, n2) } } }
0
Kotlin
0
0
4eb07020d2c21ed0ee9bb73e038115c4a14bd0f5
367
csv-warehouse-poc
Apache License 2.0
compiler/testData/codegen/box/ieee754/when.kt
AlexeyTsvetkov
17,321,988
true
{"Java": 22837096, "Kotlin": 18913890, "JavaScript": 180163, "HTML": 47571, "Protocol Buffer": 46162, "Lex": 18051, "Groovy": 13300, "ANTLR": 9729, "CSS": 9358, "IDL": 6426, "Shell": 4704, "Batchfile": 3703}
fun box(): String { val plusZero: Any = 0.0 val minusZero: Any = -0.0 if (plusZero is Double) { when (plusZero) { -0.0 -> { } else -> return "fail 1" } if (minusZero is Double) { when (plusZero) { minusZero -> { } else -> return "fail 2" } } } return "OK" }
1
Java
0
2
72a84083fbe50d3d12226925b94ed0fe86c9d794
419
kotlin
Apache License 2.0
app/src/main/java/dev/iwilltry42/timestrap/AppPreferences.kt
iwilltry42
276,853,576
false
null
package dev.iwilltry42.timestrap import android.content.Context import android.content.SharedPreferences object AppPreferences { private const val NAME = "Timestrap" private const val MODE = Context.MODE_PRIVATE private lateinit var preferences: SharedPreferences // Variables private val IS_LOGGED_IN = Pair("is_logged_in", false) private val USERNAME = Pair("username", "") private val TOKEN = Pair("token", "") private val ADDRESS = Pair("address", "") fun init(context: Context) { preferences = context.getSharedPreferences(NAME, MODE) } // inline fun to put & save new variable private inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) { val editor = edit() operation(editor) editor.apply() } // getters/setters var isLoggedIn: Boolean get() = preferences.getBoolean(IS_LOGGED_IN.first, IS_LOGGED_IN.second) set(value) = preferences.edit { it.putBoolean(IS_LOGGED_IN.first, value) } var username: String get() = preferences.getString(USERNAME.first, USERNAME.second) ?: "" set(value) = preferences.edit { it.putString(USERNAME.first, value) } var token: String get() = preferences.getString(TOKEN.first, TOKEN.second) ?: "" set(value) = preferences.edit { it.putString(TOKEN.first, value) } var address: String get() = preferences.getString(ADDRESS.first, ADDRESS.second) ?: "" set(value) = preferences.edit { it.putString(ADDRESS.first, value) } }
0
Kotlin
0
0
3b6b353c59cbb288949e2d8cd6dbfd979dcbc9db
1,642
timestrap-android
MIT License
backend/src/main/kotlin/ntnu/idatt2105/reservation/controller/ReservationControllerImpl.kt
olros
366,615,349
false
null
package ntnu.idatt2105.reservation.controller import com.querydsl.core.types.Predicate import ntnu.idatt2105.core.response.Response import ntnu.idatt2105.reservation.dto.ReservationCreateDto import ntnu.idatt2105.reservation.dto.ReservationDto import ntnu.idatt2105.reservation.service.ReservationService import org.springframework.data.domain.Pageable import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import java.util.* @RestController class ReservationControllerImpl(val reservationService: ReservationService) : ReservationController { override fun getAllReservations( predicate: Predicate, pageable: Pageable, sectionId: UUID ) = reservationService.getAllReservation(sectionId, pageable, predicate) override fun getReservation(sectionId: UUID, reservationId: UUID) = reservationService.getReservation(sectionId, reservationId) override fun createReservation(sectionId: UUID, reservation: ReservationCreateDto) = reservationService.createReservation(sectionId, reservation) override fun updateReservation(sectionId: UUID, reservationId: UUID, reservation: ReservationDto) = reservationService.updateReservation(sectionId, reservationId, reservation) override fun deleteReservation(sectionId: UUID, reservationId: UUID): ResponseEntity<Response> { reservationService.deleteReservation(sectionId, reservationId) return ResponseEntity.ok(Response("Reservation deleted")) } }
0
Kotlin
3
2
a2fa5bbca5a9db67f12733301b952807d66e673f
1,521
Rombestilling
MIT License
android/modules/module_common/src/main/java/github/tornaco/android/thanos/module/compose/common/widget/Spacers.kt
Tornaco
228,014,878
false
null
/* * (C) Copyright 2022 Thanox * * 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 github.tornaco.android.thanos.module.compose.common import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun SmallSpacer() { Spacer(modifier = Modifier.size(2.dp)) } @Composable fun TinySpacer() { Spacer(modifier = Modifier.size(4.dp)) } @Composable fun StandardSpacer() { Spacer(modifier = Modifier.size(16.dp)) }
392
null
87
2,145
b8b756152e609c96fd07f1f282b77582d8cde647
1,106
Thanox
Apache License 2.0
core/core/src/jsMain/kotlin/zakadabar/core/browser/table/columns/ZkBooleanColumnV2.kt
spxbhuhb
290,390,793
false
null
/* * Copyright © 2020-2021, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license. */ package zakadabar.core.browser.table.columns import zakadabar.core.browser.ZkElement import zakadabar.core.browser.table.ZkTable import zakadabar.core.data.BaseBo import zakadabar.core.resource.ZkIcons import zakadabar.core.resource.css.em import zakadabar.core.resource.localizedStrings open class ZkBooleanColumnV2<T : BaseBo>( table: ZkTable<T>, val getter: (T) -> Boolean ) : ZkColumn<T>(table) { override var max = 3.em override fun render(cell: ZkElement, index: Int, row: T) { with(cell) { + div { buildPoint.innerHTML = if (getter(row)) ZkIcons.check.svg(18) else ZkIcons.close.svg(18) } } } override fun sort() { table.sort(sortAscending) { getter(it.data) } } override fun exportCsv(row: T): String = if (getter(row)) localizedStrings.trueText else localizedStrings.falseText override fun exportRaw(row: T) : Any? = getter(row) }
7
null
3
24
00859b62570bf455addc9723015ba2c48b77028b
1,075
zakadabar-stack
Apache License 2.0
komapper-dialect-mariadb-jdbc/src/main/kotlin/org/komapper/dialect/mariadb/jdbc/MariaDbJdbcDialect.kt
komapper
349,909,214
false
null
package org.komapper.dialect.mariadb.jdbc import org.komapper.dialect.mariadb.MariaDbDialect import org.komapper.jdbc.JdbcDialect import java.sql.SQLException interface MariaDbJdbcDialect : MariaDbDialect, JdbcDialect { override fun isUniqueConstraintViolationError(exception: SQLException): Boolean { return exception.filterIsInstance<SQLException>().any { it.errorCode in MariaDbDialect.UNIQUE_CONSTRAINT_VIOLATION_ERROR_CODES } } } private object MariaDbJdbcDialectImpl : MariaDbJdbcDialect fun MariaDbJdbcDialect(): MariaDbJdbcDialect { return MariaDbJdbcDialectImpl }
7
null
4
97
851b313c66645d60f2e86934a5036efbe435396a
617
komapper
Apache License 2.0
app/src/main/java/me/ekhaled1836/tp/reddit/ui/comments/CommentsViewHolder.kt
ekhaled1836
178,427,940
false
null
package me.ekhaled1836.tp.reddit.ui.comments import android.os.Build import android.text.Html import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.AppCompatImageButton import androidx.appcompat.widget.AppCompatImageView import androidx.appcompat.widget.AppCompatTextView import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.DrawableCompat import androidx.core.text.PrecomputedTextCompat import androidx.core.widget.TextViewCompat import androidx.recyclerview.widget.RecyclerView import me.ekhaled1836.tp.reddit.R import me.ekhaled1836.tp.reddit.model.Comment import me.ekhaled1836.tp.reddit.model.Post import me.ekhaled1836.tp.reddit.util.PostUtils class CommentsViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val flair_user: AppCompatTextView = view.findViewById(R.id.view_comment_flair_user) private val text_user: AppCompatTextView = view.findViewById(R.id.view_comment_text_user) private val text_subtitle: AppCompatTextView = view.findViewById(R.id.view_comment_text_subtitle) private val text_score: AppCompatTextView = view.findViewById(R.id.view_comment_text_score) private val text: AppCompatTextView = view.findViewById(R.id.view_comment_text) private var comment: Comment? = null fun changeComment(comment: Comment?) { this.comment = comment if (comment?.distinguished == "moderator") text_user.setTextColor(ContextCompat.getColor(text_user.context, R.color.text_title_moderator)) else text_user.setTextColor(ContextCompat.getColor(text_user.context, R.color.text_title_normal)) if (!comment?.author_flair_text.isNullOrBlank()) { flair_user.visibility = View.VISIBLE flair_user.setTextFuture( PrecomputedTextCompat.getTextFuture( comment!!.author_flair_text!!, TextViewCompat.getTextMetricsParams(flair_user), null ) ) } else { flair_user.visibility = View.GONE } text_user.setTextFuture( PrecomputedTextCompat.getTextFuture( text_user.context.resources.getString( R.string.post_user, comment?.author ?: text_user.context.resources.getString(R.string.post_loading_author) ), TextViewCompat.getTextMetricsParams(text_user), null ) ) text_subtitle.setTextFuture( PrecomputedTextCompat.getTextFuture( text_subtitle.context.resources.getString( R.string.post_subtitle, PostUtils.getTime(comment?.created_utc ?: System.currentTimeMillis()) ), TextViewCompat.getTextMetricsParams(text_subtitle), null ) ) text_score.setTextFuture( PrecomputedTextCompat.getTextFuture( PostUtils.getShortNumber(comment?.score ?: 0), TextViewCompat.getTextMetricsParams(text_score), null ) ) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { val spanned = Html.fromHtml(comment?.body_html ?: text.context.resources.getString(R.string.post_loading_self)) text.setTextFuture( PrecomputedTextCompat.getTextFuture( spanned, TextViewCompat.getTextMetricsParams(text), null ) ) } else { val spanned = Html.fromHtml( comment?.body_html ?: text.context.resources.getString(R.string.post_loading_self), Html.FROM_HTML_MODE_COMPACT ) text.setTextFuture( PrecomputedTextCompat.getTextFuture( spanned, TextViewCompat.getTextMetricsParams(text), null ) ) } } fun updateScore(item: Comment?) { comment = item text_score.setTextFuture( PrecomputedTextCompat.getTextFuture( "${comment?.score ?: 0}", TextViewCompat.getTextMetricsParams(text_score), null ) ) } companion object { fun create(parent: ViewGroup): CommentsViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.view_comment, parent, false) return CommentsViewHolder(view) } } }
1
null
1
1
33ba25396f8c1a16d3a6731bc7115dc80568cc8e
4,579
RedditBrowser
MIT License
app/src/main/java/com/cxk/nwuhelper/ui/nwunet/NwunetViewModelFactory.kt
lionche
346,945,672
false
null
package com.cxk.nwuhelper.ui.nwunet import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.cxk.nwuhelper.ui.wenet.model.NetSpBean class NwunetViewModelFactory(private val netSpBean: NetSpBean) :ViewModelProvider.Factory{ // override fun <T : ViewModel?> create(modelClass: Class<T>): T { // return NwunetViewModel(netSpBean) as T // } override fun <T : ViewModel> create(modelClass: Class<T>): T { return NwunetViewModel(netSpBean) as T } }
0
Kotlin
0
0
070bb4120c895644525e7c70e5c235552196ab99
508
NWU_Helper
The Unlicense
app/src/main/java/com/cxk/nwuhelper/ui/nwunet/NwunetViewModelFactory.kt
lionche
346,945,672
false
null
package com.cxk.nwuhelper.ui.nwunet import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.cxk.nwuhelper.ui.wenet.model.NetSpBean class NwunetViewModelFactory(private val netSpBean: NetSpBean) :ViewModelProvider.Factory{ // override fun <T : ViewModel?> create(modelClass: Class<T>): T { // return NwunetViewModel(netSpBean) as T // } override fun <T : ViewModel> create(modelClass: Class<T>): T { return NwunetViewModel(netSpBean) as T } }
0
Kotlin
0
0
070bb4120c895644525e7c70e5c235552196ab99
508
NWU_Helper
The Unlicense
app/src/test/java/com/braffdev/steganofy/service/PayloadServiceTest.kt
mstaudt
319,281,666
false
null
package com.braffdev.steganofy.service import com.braffdev.steganofy.lib.domain.FilePayload import com.braffdev.steganofy.lib.domain.PlainTextPayload import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.mock import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.junit.runner.RunWith import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class PayloadServiceTest { @InjectMocks lateinit var payloadService: PayloadService @Mock lateinit var fileService: FileService @Test fun testCreatePayload_plainText() { // WHEN val payload = payloadService.createPayload("Test", null) // THEN assertThat(payload).isNotNull assertThat(payload).isInstanceOf(PlainTextPayload::class.java) } @Test fun testCreatePayload_file() { // GIVEN `when`(fileService.getByteArray(any())).thenReturn("Test".toByteArray()) `when`(fileService.getFileType(any())).thenReturn("text/plain") // WHEN val payload = payloadService.createPayload(null, mock()) // THEN assertThat(payload).isNotNull assertThat(payload).isInstanceOf(FilePayload::class.java) } }
1
Kotlin
0
3
098dd590e27f5c5bd1c9bd52f44ce12769f6996d
1,340
Steganofy
Apache License 2.0
app/src/main/java/com/queentylion/gestra/data/tflite/TFLiteGesturePredictorImpl.kt
hackfest-Queentylion
792,980,525
false
{"Kotlin": 138525}
package com.queentylion.gestra.data.tflite import android.content.Context import android.os.SystemClock import android.util.Log import com.queentylion.gestra.domain.tflite.TFLiteGesturePredictor import org.tensorflow.lite.DataType import org.tensorflow.lite.Interpreter import org.tensorflow.lite.nnapi.NnApiDelegate import org.tensorflow.lite.support.common.FileUtil import org.tensorflow.lite.support.tensorbuffer.TensorBuffer class TFLiteGesturePredictorImpl( private var numThreads: Int = 2, // Change to 4 maybe private var currentDelegate: Delegate = Delegate.CPU, /// Try use NNApi private var currentModel: Int = MODEL_INT8, private val context: Context, ) : TFLiteGesturePredictor { enum class Delegate { CPU, GPU, NNAPI } companion object { const val MODEL_INT8 = 0 private const val TAG = "Sign Lang Classifier" } private var interpreterPredict: Interpreter? = null private var inputPredictTargetWidth = 0 private var inputPredictTargetHeight = 0 private var inputTransformTargetWidth = 0 private var inputTransformTargetHeight = 0 private var outputPredictShape = intArrayOf() private val predictedLabels = arrayOf( "halo", "saudara", "aku", "apa", "beli", "jadi", "kabar", "kita", "makan", "sehat", "NONE" ) init { setupStyleTransfer() interpreterPredict!!.let { interpreter -> inputPredictTargetHeight = interpreter.getInputTensor(0).shape()[1] inputPredictTargetWidth = interpreter.getInputTensor(0).shape()[2] outputPredictShape = interpreter.getOutputTensor(0).shape() } } private fun setupStyleTransfer() { val tfliteOption = Interpreter.Options() tfliteOption.setNumThreads(numThreads) when (currentDelegate) { Delegate.CPU -> Unit // Default Delegate.GPU -> { // if (CompatibilityList().isDelegateSupportedOnThisDevice) { // tfliteOption.addDelegate(GpuDelegate()) // } else { // error("GPU is not supported on this device") // } } Delegate.NNAPI -> tfliteOption.addDelegate(NnApiDelegate()) } val modelPredict: String = if (currentModel == MODEL_INT8) { "model_sibi.tflite" } else { "model_sibi.tflite" } try { interpreterPredict = Interpreter( FileUtil.loadMappedFile(context, modelPredict), tfliteOption ) } catch (e: Exception) { Log.e(TAG, "TFLite failed to load model with error: " + e.message) error("Style transfer failed to initialize. See error logs for details") } } override fun predict(gloveKeypoint: List<List<Int>>): String { val startTime = System.currentTimeMillis() // Flatten the glove keypoints and convert them to float val flatInputArray = gloveKeypoint.flatten().map { it.toFloat() }.toFloatArray() // Ensure the size of the flatInputArray matches the expected shape val expectedInputSize = inputPredictTargetHeight * inputPredictTargetWidth if (flatInputArray.size != expectedInputSize) { error("Size of input array (${flatInputArray.size}) does not match the expected shape ($inputTransformTargetHeight x $inputTransformTargetWidth)") } // Reshape the input array to match the expected input shape val reshapedInputArray = flatInputArray.copyOf() // Create TensorBuffer from the reshaped input array val inputDataType = DataType.FLOAT32 val inputTensorBuffer = TensorBuffer.createFixedSize( intArrayOf( inputPredictTargetHeight, inputPredictTargetWidth ), inputDataType ) inputTensorBuffer.loadArray(reshapedInputArray) // Create TensorBuffer for the output val predictOutput = TensorBuffer.createFixedSize(outputPredictShape, DataType.FLOAT32) // Run inference interpreterPredict?.run(inputTensorBuffer.buffer, predictOutput.buffer) val endTime = System.currentTimeMillis() val inferenceTime = endTime - startTime Log.d("TIME ML", inferenceTime.toString()) // Return the predicted label return getOutputString(predictOutput) } fun clearStyleTransferUtil() { interpreterPredict = null } private fun getOutputString( output: TensorBuffer, ): String { val maxIndexFeature0 = indexOfMaxValue(output.floatArray) return predictedLabels[maxIndexFeature0] } private fun indexOfMaxValue(arr: FloatArray): Int { var maxIndex = -1 var maxValue = Float.MIN_VALUE for (i in arr.indices) { if (arr[i] > maxValue) { maxValue = arr[i] maxIndex = i } } Log.d("SIBIML", maxValue.toString()) return maxIndex } }
0
Kotlin
0
0
1bce5eecdfe9bf25559674a54b0b2021e69f9294
5,205
gestra-revamp
MIT License
firebasecloudmessaging/app/src/main/java/com/simple/instagram/service/FirebaseMessagingService.kt
farhanroy
326,154,185
false
{"Kotlin": 128152}
package com.simple.instagram.service import android.app.Notification import android.app.NotificationManager import android.content.Context import android.util.Log import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import com.simple.instagram.R class FirebaseMessagingService : FirebaseMessagingService() { private val db = Firebase.firestore override fun onMessageReceived(rm: RemoteMessage) { super.onMessageReceived(rm) Log.d("SEND", "Success") createNotification(rm.notification) } override fun onNewToken(newToken: String) { super.onNewToken(newToken) Log.d("TOKEN", newToken) saveNewToken(newToken) } private fun createNotification(remoteMessage: RemoteMessage.Notification?) { val builder = Notification.Builder(this) .setSmallIcon(R.drawable.ic_launcher_background) .setContentTitle(remoteMessage?.title) .build() val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(0, builder) } private fun saveNewToken(token: String) { val ref = db.collection("fire_notify").document("fcm") ref.update("token", token) .addOnSuccessListener { Log.d("", "Success update document") } .addOnFailureListener { e -> Log.w("", "Error update document", e) } } }
0
Kotlin
0
0
eb267505f33c365f110392fc19303fc9c468a075
1,577
android-self-research
MIT License
firebasecloudmessaging/app/src/main/java/com/simple/instagram/service/FirebaseMessagingService.kt
farhanroy
326,154,185
false
{"Kotlin": 128152}
package com.simple.instagram.service import android.app.Notification import android.app.NotificationManager import android.content.Context import android.util.Log import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import com.simple.instagram.R class FirebaseMessagingService : FirebaseMessagingService() { private val db = Firebase.firestore override fun onMessageReceived(rm: RemoteMessage) { super.onMessageReceived(rm) Log.d("SEND", "Success") createNotification(rm.notification) } override fun onNewToken(newToken: String) { super.onNewToken(newToken) Log.d("TOKEN", newToken) saveNewToken(newToken) } private fun createNotification(remoteMessage: RemoteMessage.Notification?) { val builder = Notification.Builder(this) .setSmallIcon(R.drawable.ic_launcher_background) .setContentTitle(remoteMessage?.title) .build() val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(0, builder) } private fun saveNewToken(token: String) { val ref = db.collection("fire_notify").document("fcm") ref.update("token", token) .addOnSuccessListener { Log.d("", "Success update document") } .addOnFailureListener { e -> Log.w("", "Error update document", e) } } }
0
Kotlin
0
0
eb267505f33c365f110392fc19303fc9c468a075
1,577
android-self-research
MIT License
src/main/kotlin/com/api/todolistsystem/jwt/Jwt.kt
Matysys
635,139,905
false
null
package com.api.todolistsystem.jwt import com.auth0.jwt.JWT import com.auth0.jwt.JWTVerifier import com.auth0.jwt.algorithms.Algorithm import com.auth0.jwt.exceptions.JWTVerificationException import com.auth0.jwt.interfaces.DecodedJWT import java.util.* class Jwt { companion object { // Chave secreta para assinar e verificar o token private const val SECRET = "minha_chave_secreta" @JvmStatic fun criarToken(email: String, userId: Long, userName: String): String { val algorithm = Algorithm.HMAC256(SECRET) val dataExpiracao = Date(System.currentTimeMillis() + 3600_000) // Token expira em 1 hora return JWT.create() .withIssuer("auth0") .withSubject(email) .withClaim("userId", userId) .withClaim("name", userName) .withExpiresAt(dataExpiracao) .sign(algorithm) } @JvmStatic fun validarToken(token: String): DecodedJWT? { return try { val algorithm: Algorithm = Algorithm.HMAC256(SECRET) val verifier: JWTVerifier = JWT.require(algorithm).withIssuer("auth0").build() verifier.verify(token) } catch (e: JWTVerificationException) { null } } } }
0
Kotlin
0
1
92afef6d5dcab5dc2defbc53f3057d9883c77acf
1,360
todolist-system-api-backend
MIT License
core/generated-sources/src/main/kotlin/org/jetbrains/kotlinx/dataframe/api/indices.kt
Kotlin
259,256,617
false
{"Kotlin": 8227503, "Java": 17608, "JavaScript": 11483, "CSS": 3083, "HTML": 137, "Shell": 73}
package org.jetbrains.kotlinx.dataframe.api import org.jetbrains.kotlinx.dataframe.AnyFrame import org.jetbrains.kotlinx.dataframe.DataFrame import org.jetbrains.kotlinx.dataframe.RowFilter import org.jetbrains.kotlinx.dataframe.indices // region DataFrame public fun AnyFrame.indices(): IntRange = 0 until rowsCount() public fun <T> DataFrame<T>.indices(filter: RowFilter<T>): List<Int> = indices.filter { val row = get(it) filter(row, row) } // endregion
235
Kotlin
60
833
54d00e69ae7c06ff254c6591242413eaf7894f01
470
dataframe
Apache License 2.0
innsender/src/main/kotlin/no/nav/soknad/innsending/consumerapis/arena/ArenaConsumer.kt
navikt
406,355,715
false
{"Kotlin": 899830, "Dockerfile": 250}
package no.nav.soknad.innsending.consumerapis.arena import no.nav.soknad.innsending.api.MaalgrupperApi import no.nav.soknad.innsending.api.TilleggsstonaderApi import no.nav.soknad.innsending.exceptions.BackendErrorException import no.nav.soknad.innsending.model.Aktivitet import no.nav.soknad.innsending.model.AktivitetEndepunkt import no.nav.soknad.innsending.model.Maalgruppe import no.nav.soknad.innsending.security.SubjectHandlerInterface import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Qualifier import org.springframework.context.annotation.Profile import org.springframework.stereotype.Component import org.springframework.web.client.RestClient import org.springframework.web.client.RestClientResponseException import java.time.LocalDate @Component @Profile("test | dev | prod") class ArenaConsumer( @Qualifier("arenaApiRestClient") private val arenaApiClient: RestClient, private val subjectHandler: SubjectHandlerInterface ) : ArenaConsumerInterface { private val maalgruppeApi = MaalgrupperApi(arenaApiClient) private val tilleggsstonaderApi = TilleggsstonaderApi(arenaApiClient) private val logger: Logger = LoggerFactory.getLogger(javaClass) private val secureLogger = LoggerFactory.getLogger("secureLogger") private val fromDate = LocalDate.now().minusMonths(6) private val toDate = LocalDate.now().plusMonths(2) override fun getMaalgrupper(): List<Maalgruppe> { val userId = subjectHandler.getUserIdFromToken() logger.info("Henter målgrupper") secureLogger.info("[{}] Henter målgrupper", userId) val maalgrupper = try { maalgruppeApi.getMaalgrupper(fromDate.toString(), toDate.toString()) } catch (e: RestClientResponseException) { if (e.statusCode.is4xxClientError) { logger.warn("[Arena] Klientfeil ved henting av målgrupper", e) return emptyList() } else { logger.warn("[Arena] Serverfeil ved henting av målgrupper", e) return emptyList() } } secureLogger.info("[{}] Målgrupper: {}", userId, maalgrupper.map { it.maalgruppetype }) return maalgrupper } override fun getAktiviteter(aktivitetEndepunkt: AktivitetEndepunkt): List<Aktivitet> { val userId = subjectHandler.getUserIdFromToken() logger.info("Henter aktiviteter") secureLogger.info("[{}] Henter aktiviteter", userId) val aktiviteter = try { when (aktivitetEndepunkt) { AktivitetEndepunkt.aktivitet -> tilleggsstonaderApi.getAktiviteter(fromDate.toString(), toDate.toString()) AktivitetEndepunkt.dagligreise -> tilleggsstonaderApi.getAktiviteterDagligreise( fromDate.toString(), toDate.toString() ) else -> throw BackendErrorException("Ukjent aktivitetstype") } } catch (e: RestClientResponseException) { if (e.statusCode.is4xxClientError) { logger.warn("[Arena] Klientfeil ved henting av aktiviteter", e) return emptyList() } else { logger.warn("[Arena] Serverfeil ved henting av aktiviteter", e) return emptyList() } } secureLogger.info( "[{}] Aktiviteter: {}", userId, aktiviteter.map { "aktivitet=" + it.aktivitetstype + ", er stønadsberettiget=" + it.erStoenadsberettigetAktivitet + "," + " tema=" + it.saksinformasjon?.sakstype + ", periode=" + it.periode.fom.toString() + "-" + it.periode.tom?.toString() + ", parkering = " + it.saksinformasjon?.vedtaksinformasjon?.first()?.trengerParkering } ) return aktiviteter } }
8
Kotlin
0
1
bfbec260e7dd6450ca842401b56557db9bad1040
3,438
innsending-api
MIT License
app/src/main/kotlin/dev/forcecodes/android/gitprofile/ui/BaseViewModel.kt
forceporquillo
484,089,537
false
{"Kotlin": 263716}
package dev.forcecodes.android.gitprofile.ui import androidx.lifecycle.ViewModel import dev.forcecodes.gitprofile.core.UiEvent import dev.forcecodes.gitprofile.core.UiState import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.receiveAsFlow abstract class BaseViewModel<State : UiState, Event : UiEvent>(initialState: State) : ViewModel() { abstract fun stateReducer(oldState: State, event: Event) private val _state: MutableStateFlow<State> = MutableStateFlow(initialState) val state: StateFlow<State> = _state private val _uiEvent = Channel<Event>(capacity = Channel.CONFLATED) val uiEvent: Flow<Event> = _uiEvent.receiveAsFlow() fun sendEvent(event: Event) { _uiEvent.trySend(event) stateReducer(_state.value, event) } protected fun setState(newState: State) { _state.tryEmit(newState) } override fun onCleared() { super.onCleared() _uiEvent.close() } }
0
Kotlin
0
0
0f7efc84f35ed04b1f4c8f88176098963a8375e5
1,094
github-profile-android
Apache License 2.0
library/src/main/java/com/getroadmap/r2rlib/models/Segment.kt
roadmaptravel
63,339,774
false
null
package com.getroadmap.r2rlib.models import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import java.util.ArrayList /** * https://www.rome2rio.com/documentation/search#Segment */ open class Segment() : Parcelable { /** * segmentKind string Segment kind [1] * depPlace integer Departure airport (index into places array) * arrPlace integer Arrival airport (index into places array) * vehicle integer Vehicle (index into vehicles array) * distance float Estimated distance (in km) * transitDuration float Estimated duration spent in transit (in minutes) * transferDuration float Estimated duration spent waiting for transfer (in minutes) * indicativePrices IndicativePrice[] Array of indicative prices (optional) */ @SerializedName("segmentKind") @Expose var segmentKind: String? = null //e.g. "air" @SerializedName("depPlace") @Expose var depPlace: Int? = null//Departure airport (index into places array) @SerializedName("arrPlace") @Expose var arrPlace: Int? = null//Arrival airport (index into places array) @SerializedName("vehicle") @Expose var vehicle: Int? = null//Vehicle (index into vehicles array) @SerializedName("distance") @Expose var distance: Float? = null//Estimated distance (in km) @SerializedName("transitDuration") @Expose var transitDuration: Float? = null//Estimated duration spent in transit (in minutes) @SerializedName("transferDuration") @Expose var transferDuration: Float? = null//Estimated duration spent waiting for transfer (in minutes) @SerializedName("indicativePrices") @Expose var indicativePrices: List<IndicativePrice>? = null//IndicativePrice[] Array of indicative prices (optional) constructor(parcel: Parcel) : this() { segmentKind = parcel.readString() depPlace = parcel.readValue(Int::class.java.classLoader) as? Int arrPlace = parcel.readValue(Int::class.java.classLoader) as? Int vehicle = parcel.readValue(Int::class.java.classLoader) as? Int distance = parcel.readValue(Float::class.java.classLoader) as? Float transitDuration = parcel.readValue(Float::class.java.classLoader) as? Float transferDuration = parcel.readValue(Float::class.java.classLoader) as? Float indicativePrices = parcel.createTypedArrayList(IndicativePrice.CREATOR) } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(segmentKind) parcel.writeValue(depPlace) parcel.writeValue(arrPlace) parcel.writeValue(vehicle) parcel.writeValue(distance) parcel.writeValue(transitDuration) parcel.writeValue(transferDuration) parcel.writeTypedList(indicativePrices) } override fun describeContents(): Int { return 0 } override fun toString(): String { return "Segment(segmentKind=$segmentKind, depPlace=$depPlace, arrPlace=$arrPlace, vehicle=$vehicle, distance=$distance, transitDuration=$transitDuration, transferDuration=$transferDuration, indicativePrices=$indicativePrices)" } companion object CREATOR : Parcelable.Creator<Segment> { override fun createFromParcel(parcel: Parcel): Segment { return Segment(parcel) } override fun newArray(size: Int): Array<Segment?> { return arrayOfNulls(size) } } }
1
null
1
5
c3e320a0024a11cdcbeb56efdc05199cb680fa2a
3,529
Rome2RioAndroid
Apache License 2.0
src/main/kotlin/com/github/taideli/gitlabsupport/services/MyApplicationService.kt
taideli
296,250,729
false
null
package com.github.taideli.gitlabsupport.services import com.github.taideli.gitlabsupport.MyBundle class MyApplicationService { init { println(MyBundle.message("applicationService")) } }
0
Kotlin
0
0
a513fa45a97308ffa54d5d7fd94b4ef04b78ba19
206
gitlab-support
Apache License 2.0
sqldelight-gradle-plugin/src/test/custom-dialect/dialect/src/main/kotlin/foo/FooDialect.kt
sqldelight
44,677,680
false
null
package foo import app.cash.sqldelight.dialect.api.DialectType import app.cash.sqldelight.dialect.api.IntermediateType import app.cash.sqldelight.dialect.api.SqlDelightDialect import app.cash.sqldelight.dialect.api.TypeResolver import app.cash.sqldelight.dialect.api.encapsulatingType import app.cash.sqldelight.dialects.sqlite_3_18.SqliteDialect import app.cash.sqldelight.dialects.sqlite_3_18.SqliteTypeResolver import com.alecstrong.sql.psi.core.psi.SqlFunctionExpr import com.alecstrong.sql.psi.core.psi.SqlTypeName import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.MemberName import com.squareup.kotlinpoet.TypeName class FooDialect : SqlDelightDialect by SqliteDialect() { override fun typeResolver(parentResolver: TypeResolver) = CustomResolver(parentResolver) class CustomResolver(private val parentResolver: TypeResolver) : TypeResolver by SqliteTypeResolver(parentResolver) { override fun functionType(functionExpr: SqlFunctionExpr): IntermediateType? { return when (functionExpr.functionName.text.lowercase()) { "foo" -> encapsulatingType(functionExpr.exprList, ExtensionType).asNonNullable() else -> parentResolver.functionType(functionExpr) } } override fun definitionType(typeName: SqlTypeName): IntermediateType { return when (typeName) { else -> IntermediateType(ExtensionType) } } } private object ExtensionType : DialectType { override val javaType: TypeName = ClassName("kotlin.time", "Duration") override fun cursorGetter(columnIndex: Int, cursorName: String): CodeBlock { return CodeBlock.builder() .add( "$cursorName.getLong($columnIndex)?.%M(%M)", MemberName("kotlin.time", "toDuration", isExtension = true), MemberName("kotlin.time.DurationUnit", "SECONDS"), ) .build() } override fun prepareStatementBinder(columnIndex: String, value: CodeBlock): CodeBlock { return CodeBlock.of("""TODO("Not yet implemented")""") } } }
606
null
516
6,152
f79bd8ae2cf991de6dccdb643376253402f665e1
2,060
sqldelight
Apache License 2.0
common/src/test/kotlin/digital/wup/superheroapp/common/TestUseCaseScheduler.kt
wupdigital
121,658,678
false
{"Kotlin": 37766, "Swift": 23746, "Shell": 1290, "Java": 1141, "Objective-C": 1064, "Ruby": 619}
package digital.wup.superheroapp.common /** * @author <NAME> */ class TestUseCaseScheduler : UseCaseScheduler { override fun execute(runnable: () -> Unit) { runnable() } override fun <Rs> notifyResponse(success: (Rs) -> Unit, response: Rs) { success(response) } override fun notifyError(error: () -> Unit) { error() } }
0
Kotlin
8
17
bd4069fdbbbeba74d8925db5cbad4fd220cac113
373
kotlin-native-superhero-app
Apache License 2.0
app/src/main/java/dev/kingbond/moveon/ui/packageandmovers/fragMov/cost/CoastPage.kt
Kingbond470
422,909,035
false
{"Kotlin": 129863, "Java": 9137}
package dev.kingbond.moveon.ui.packageandmovers.fragMov.cost import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.navigation.Navigation import dev.kingbond.moveon.R import android.content.Context.MODE_PRIVATE import android.content.SharedPreferences import android.widget.Switch import dev.kingbond.moveon.ui.packageandmovers.spref.GlobalV import dev.kingbond.moveon.ui.packageandmovers.spref.SharedPref class CoastPage : Fragment() { val sharedPref= SharedPref() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val view =inflater.inflate(R.layout.fragment_coast_page, container, false) view.findViewById<Button>(R.id.coastBtn).setOnClickListener { Navigation.findNavController(view).navigate(R.id.action_coastPage_to_confirmPage) } houseSizeData(view) // setFinal1(view) return view } fun houseSizeData(view:View){ val cost=view.findViewById<TextView>(R.id.EstCost) val date=view.findViewById<TextView>(R.id.Tdate) var value_1 = sharedPref.retriveData(requireContext(),"date") var Tcost = sharedPref.retriveIntData(requireContext(),"sum") cost.text = "₹${Tcost.toString()}.00" date.text = value_1.toString() } // fun setFinal1(view:View){ ////unable to implement // val type=view.findViewById<TextView>(R.id.Thouse_type) // // // // val Cat1=sharedPref.retriveData(requireContext(),"1rk") // // val Cat2=sharedPref.retriveData(requireContext(),"1bhk") // // val Cat3=sharedPref.retriveData(requireContext(),"2bhk") // // val Cat4=sharedPref.retriveData(requireContext(),"3bhk") // // when { // Cat1!=null -> { // Toast.makeText(requireContext(), Cat1, Toast.LENGTH_SHORT).show() // type.text = Cat1 // } // Cat2!=null -> { // Toast.makeText(requireContext(), Cat2, Toast.LENGTH_SHORT).show() // type.text = Cat2 // } // Cat3!=null -> { // Toast.makeText(requireContext(), Cat3, Toast.LENGTH_SHORT).show() // type.text = Cat3 // } // else -> { // type.text = Cat4 // } // } // } }
0
Kotlin
0
5
b1f790c6cf43354857f1f98e217fe68bdb3e9e3a
2,648
Move-On
MIT License
src/main/java/solar/blaz/gradle/play/tasks/CloseEditTask.kt
blazsolar
22,805,931
false
null
package solar.blaz.gradle.play.tasks import org.gradle.api.logging.Logging import javax.inject.Inject open class CloseEditTask @Inject constructor(applicationId: String, artifactName: String) : PlayEditTask(applicationId, artifactName) { override fun perform() { // Commit changes for edit. val appEdit = requestEdits() .commit(applicationId, requestEditId()) .execute() LOG.info("App edit with id ${appEdit.id} has been committed.") } companion object { private val LOG = Logging.getLogger(CloseEditTask::class.java) } }
1
Kotlin
1
3
aa2320ce57a9a567a0f76346e28d21c630889925
606
gradle-play-publisher
MIT License
common/src/jsMain/kotlin/AudioPlayer.kt
pilot51
10,723,709
false
{"Kotlin": 123024, "HTML": 2235}
/* * Copyright 2020-2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import externals.AudioBuffer import externals.AudioBufferSourceNode import externals.AudioContext import externals.MIDIjs import kotlinx.browser.window import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.await import kotlinx.coroutines.launch import org.w3c.fetch.CORS import org.w3c.fetch.RequestInit import org.w3c.fetch.RequestMode actual class AudioPlayer actual constructor( private val audio: Audio, private val doLoop: Boolean ) { private var srcNode: AudioBufferSourceNode? = null actual fun start() { if (audio.isMusic) { MIDIjs.play(audio.filename, true) } else { getAudio { play(it) } } } actual fun stop() { if (audio.isMusic) { MIDIjs.stop() } else { srcNode?.stop() } } private fun play(audioBuffer: AudioBuffer) { srcNode = audioContext.createBufferSource().apply { buffer = audioBuffer loop = doLoop connect(audioContext.destination) start() } } private fun getAudio(callback: (AudioBuffer) -> Unit) = audioCache[audio]?.let(callback) ?: run { window.fetch(audio.filename, RequestInit(mode = RequestMode.CORS)).then { it.arrayBuffer() }.then { CoroutineScope(Dispatchers.Default).launch { val buffer = audioContext.decodeAudioData(it).await() audioCache[audio] = buffer callback(buffer) } } } companion object { private val audioContext = AudioContext() private val audioCache = mutableMapOf<Audio, AudioBuffer>() } }
0
Kotlin
1
2
1b35cf64c360eaada6b6c126b9a8614a1ca2e5d4
2,085
cometbusters
Apache License 2.0
app/src/main/java/com/frogobox/webview/ConfigApp.kt
frogobox
240,291,693
false
null
package com.frogobox.research.core import androidx.appcompat.app.AppCompatActivity /** * Created by <NAME> on 24/10/22 * ----------------------------------------- * E-mail : <EMAIL> * Github : github.com/amirisback * ----------------------------------------- * Copyright (C) Frogobox ID / amirisback * All rights reserved */ abstract class BaseActivity : AppCompatActivity() { }
1
null
2
10
8fef6b8a0e2d57423699d0656c64fa30f4f8d533
394
kick-start-android-webview
Apache License 2.0
src/main/kotlin/dev/crashteam/uzumanalytics/service/SellerService.kt
crashteamdev
647,366,680
false
{"Kotlin": 414651, "Dockerfile": 714}
package dev.crashteam.uzumanalytics.service import dev.crashteam.uzumanalytics.domain.mongo.SellerDetailDocument import dev.crashteam.uzumanalytics.repository.mongo.SellerRepository import org.springframework.stereotype.Service import reactor.core.publisher.Flux @Service class SellerService( private val sellerRepository: SellerRepository ) { fun findSellersByLink(sellerLink: String): Flux<SellerDetailDocument> { return sellerRepository.findByLink(sellerLink).flatMapMany { sellerDetailDocument -> sellerRepository.findByAccountId(sellerDetailDocument.accountId) } } }
4
Kotlin
0
0
445cff2d2f68a38343d1638d261ace2198e7b8a9
615
uzum-analytics
Apache License 2.0
app/app/src/main/java/seven/drawalive/nodebase/NodeBaseAppConfigFile.kt
seejser
234,864,335
true
{"JavaScript": 170116, "HTML": 104071, "Kotlin": 55549, "CSS": 1380, "Shell": 338}
package seven.drawalive.nodebase import java.util.HashMap class NodeBaseAppConfigFile(config_text: String) { private val config: HashMap<String, HashMap<String, String>> private val defaultconfig: HashMap<String, String> init { config = HashMap() defaultconfig = HashMap() config["\u0000"] = defaultconfig var cur = defaultconfig // parse simple ini for (line in config_text.split("\n".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()) { var xline = line.trim({ it <= ' ' }) if (xline.length == 0) continue if (xline.get(0) == '[' && xline.get(xline.length - 1) == ']') { val section = xline.substring(1, xline.length - 1) if (config.containsKey(section)) { cur = config[section]!! } else { cur = HashMap() config[section] = cur } continue } val eqpos = line.indexOf('=') if (eqpos < 0) continue val key = line.substring(0, eqpos).trim({ it <= ' ' }) val `val` = line.substring(eqpos + 1).trim({ it <= ' ' }) cur[key] = `val` } } operator fun get(section: String?, key: String): String? { var section = section if (section == null) { section = "\u0000" } if (!config.containsKey(section)) { return null } val secmap = config[section] return if (secmap!!.containsKey(key)) { secmap!!.get(key) } else { null } } }
0
null
0
1
667a2ca55afd172bc674d15749ca29512ba86509
1,674
NodeBase
Apache License 2.0
src/main/kotlin/dev/turingcomplete/intellijdevelopertoolsplugin/_internal/tool/ui/converter/TextConverter.kt
marcelkliemannel
605,260,384
false
null
package dev.turingcomplete.intellijdevelopertoolsplugins._internal.tool.converter import com.intellij.icons.AllIcons import com.intellij.lang.Language import com.intellij.openapi.Disposable import com.intellij.openapi.observable.properties.AtomicProperty import com.intellij.openapi.project.Project import com.intellij.ui.dsl.builder.Align import com.intellij.ui.dsl.builder.Panel import com.intellij.ui.dsl.builder.RightGap import com.intellij.ui.dsl.builder.bindSelected import com.intellij.ui.dsl.builder.selected import com.intellij.ui.layout.not import com.intellij.util.Alarm import dev.turingcomplete.intellijdevelopertoolsplugins.DeveloperTool import dev.turingcomplete.intellijdevelopertoolsplugins.DeveloperToolConfiguration import dev.turingcomplete.intellijdevelopertoolsplugins.DeveloperToolConfiguration.PropertyType.INPUT import dev.turingcomplete.intellijdevelopertoolsplugins.DeveloperToolContext import dev.turingcomplete.intellijdevelopertoolsplugins._internal.common.DeveloperToolEditor import dev.turingcomplete.intellijdevelopertoolsplugins._internal.common.DeveloperToolEditor.EditorMode.INPUT_OUTPUT import dev.turingcomplete.intellijdevelopertoolsplugins._internal.common.ErrorHolder import dev.turingcomplete.intellijdevelopertoolsplugins._internal.common.PropertyComponentPredicate import dev.turingcomplete.intellijdevelopertoolsplugins._internal.tool.converter.TextConverter.ActiveInput.SOURCE import dev.turingcomplete.intellijdevelopertoolsplugins._internal.tool.converter.TextConverter.ActiveInput.TARGET import dev.turingcomplete.intellijdevelopertoolsplugins.common.ValueProperty internal abstract class TextConverter( protected val textConverterContext: TextConverterContext, protected val configuration: DeveloperToolConfiguration, protected val context: DeveloperToolContext, protected val project: Project?, parentDisposable: Disposable ) : DeveloperTool(parentDisposable), DeveloperToolConfiguration.ChangeListener { // -- Properties -------------------------------------------------------------------------------------------------- // private var liveConversion = configuration.register("liveConversion", true) protected var sourceText = configuration.register("sourceText", textConverterContext.defaultSourceText, INPUT) protected var targetText = configuration.register("targetText", textConverterContext.defaultTargetText, INPUT) private val conversationAlarm by lazy { Alarm(parentDisposable) } private var lastActiveInput = AtomicProperty(SOURCE) private val toSourceActive = PropertyComponentPredicate(lastActiveInput, TARGET) private val sourceEditor by lazy { createSourceEditor() } private val targetEditor by lazy { createTargetEditor() } // -- Initialization ---------------------------------------------------------------------------------------------- // init { liveConversion.afterChange(parentDisposable) { liveTransformToLastActiveInput() } } // -- Exposed Methods --------------------------------------------------------------------------------------------- // override fun Panel.buildUi() { buildTopConfigurationUi() row { resizableRow() val sourceEditorCell = cell(sourceEditor.component).align(Align.FILL) textConverterContext.sourceErrorHolder?.let { sourceErrorHolder -> sourceEditorCell .validationOnApply(sourceEditor.bindValidator(sourceErrorHolder.asValidation())) .validationRequestor(DUMMY_DIALOG_VALIDATION_REQUESTOR) } } buildMiddleFirstConfigurationUi() buildActionsUi() buildMiddleSecondConfigurationUi() row { resizableRow() val targetEditorCell = cell(targetEditor.component).align(Align.FILL) textConverterContext.targetErrorHolder?.let { targetErrorHolder -> targetEditorCell .validationOnApply(targetEditor.bindValidator(targetErrorHolder.asValidation())) .validationRequestor(DUMMY_DIALOG_VALIDATION_REQUESTOR) } } } protected open fun Panel.buildTopConfigurationUi() { // Override if needed } protected open fun Panel.buildMiddleFirstConfigurationUi() { // Override if needed } protected open fun Panel.buildMiddleSecondConfigurationUi() { // Override if needed } protected fun setSourceLanguage(language: Language) { sourceEditor.language = language } protected fun setTargetLanguage(language: Language) { targetEditor.language = language } abstract fun toTarget(text: String) abstract fun toSource(text: String) fun targetText(): String = targetText.get() fun sourceText(): String = sourceText.get() override fun configurationChanged(property: ValueProperty<out Any>) { liveTransformToLastActiveInput() } override fun activated() { configuration.addChangeListener(parentDisposable, this) } override fun deactivated() { configuration.removeChangeListener(this) } // -- Private Methods --------------------------------------------------------------------------------------------- // private fun Panel.buildActionsUi() { buttonsGroup { row { val liveConversionCheckBox = checkBox("Live conversion") .bindSelected(liveConversion) .gap(RightGap.SMALL) icon(AllIcons.General.ArrowUp) .visibleIf(toSourceActive) .enabledIf(liveConversion) .gap(RightGap.SMALL) icon(AllIcons.General.ArrowDown) .visibleIf(toSourceActive.not()) .enabledIf(liveConversion) .gap(RightGap.SMALL) button("▼ ${textConverterContext.convertActionTitle}") { transformToTarget() } .enabledIf(liveConversionCheckBox.selected.not()) .gap(RightGap.SMALL) button("▲ ${textConverterContext.revertActionTitle}") { transformToSource() } .enabledIf(liveConversionCheckBox.selected.not()) } } } private fun transformToSource() { doToSource(targetEditor.text) } private fun transformToTarget() { doToTarget(sourceEditor.text) } private fun doToTarget(text: String) { doConversation { try { toTarget(text) } catch (ignore: Exception) { } } } private fun doToSource(text: String) { doConversation { try { toSource(text) } catch (ignore: Exception) { } } } private fun doConversation(conversation: () -> Unit) { if (!isDisposed && !conversationAlarm.isDisposed) { conversationAlarm.cancelAllRequests() conversationAlarm.addRequest(conversation, 0) } } private fun createSourceEditor() = DeveloperToolEditor( id = "source", title = textConverterContext.sourceTitle, editorMode = INPUT_OUTPUT, parentDisposable = parentDisposable, configuration = configuration, context = context, project = project, textProperty = sourceText, diffSupport = textConverterContext.diffSupport?.let { diffSupport -> DeveloperToolEditor.DiffSupport( title = diffSupport.title, secondTitle = textConverterContext.targetTitle, secondText = { targetText.get() }, ) } ).apply { onFocusGained { lastActiveInput.set(SOURCE) } this.onTextChangeFromUi { text -> if (liveConversion.get()) { lastActiveInput.set(SOURCE) doToTarget(text) } } } private fun createTargetEditor(): DeveloperToolEditor { return DeveloperToolEditor( id = "target", title = textConverterContext.targetTitle, editorMode = INPUT_OUTPUT, parentDisposable = parentDisposable, configuration = configuration, context = context, project = project, textProperty = targetText, diffSupport = textConverterContext.diffSupport?.let { diffSupport -> DeveloperToolEditor.DiffSupport( title = diffSupport.title, secondTitle = textConverterContext.sourceTitle, secondText = { sourceText.get() }, ) } ).apply { onFocusGained { lastActiveInput.set(TARGET) } this.onTextChangeFromUi { text -> if (liveConversion.get()) { lastActiveInput.set(TARGET) doToSource(text) } } } } private fun liveTransformToLastActiveInput() { if (liveConversion.get()) { // Trigger a text change. So if the text was changed in manual mode, it // will now be converted once during the switch to live mode. when (lastActiveInput.get()) { SOURCE -> transformToTarget() TARGET -> transformToSource() } } } // -- Inner Type -------------------------------------------------------------------------------------------------- // enum class ActiveInput { SOURCE, TARGET } // -- Inner Type -------------------------------------------------------------------------------------------------- // data class TextConverterContext( val convertActionTitle: String, val revertActionTitle: String, val sourceTitle: String, val targetTitle: String, val sourceErrorHolder: ErrorHolder? = null, val targetErrorHolder: ErrorHolder? = null, val diffSupport: DiffSupport? = null, val defaultSourceText: String = "", val defaultTargetText: String = "" ) data class DiffSupport( val title: String ) // -- Companion Object -------------------------------------------------------------------------------------------- // }
7
null
7
97
c86a3986d6811fd022fa6a869e9b18f4054a44c8
9,521
intellij-developer-tools-plugin
Apache License 2.0
build-logic/publication/src/main/kotlin/com/avito/PublishAndroidLibraryPlugin.kt
avito-tech
230,265,582
false
{"Kotlin": 3573291, "Java": 67252, "Shell": 27675, "Dockerfile": 12799, "Makefile": 7970}
package com.avito import com.android.build.gradle.LibraryExtension import com.avito.android.publish.AndroidLibraryPublishExtension import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.publish.PublishingExtension import org.gradle.api.publish.maven.MavenPublication import org.gradle.api.tasks.bundling.Jar class PublishAndroidLibraryPlugin : Plugin<Project> { override fun apply(project: Project) { with(project) { plugins.apply(PublishReleasePlugin::class.java) val publishExtension = extensions.create("publish", AndroidLibraryPublishExtension::class.java) extensions.configure(LibraryExtension::class.java) { libraryExt -> with(libraryExt) { val sourcesTask = tasks.register("sourcesJar", Jar::class.java) { it.archiveClassifier.set("sources") it.from(libraryExt.sourceSets.getByName("main").java.srcDirs) } val allVariantNames = mutableListOf<String>() var registeredVariants = 0 // todo use new publishing: https://developer.android.com/studio/releases/gradle-plugin#build-variant-publishing libraryVariants .matching { allVariantNames += it.name it.name == publishExtension.variant.get() }.whenObjectAdded { extensions.configure(PublishingExtension::class.java) { publishing -> publishing.publications { pubs -> pubs.register( "${publishExtension.variant.get()}AndroidLibrary", MavenPublication::class.java ) { maven -> maven.from(components.getAt(publishExtension.variant.get())) maven.artifact(sourcesTask.get()) registeredVariants++ afterEvaluate { maven.artifactId = publishExtension.artifactId.getOrElse(project.name) } } } } } afterEvaluate { require(registeredVariants > 0) { val path = project.path val variant = publishExtension.variant.get() """ No created publications for $path, with plugin "convention.publish-android-library". Options: - Remove plugin if library was not supposed to be published - Check configuration: published variant:$variant;available variants=$allVariantNames """.trimIndent() } } } } } } }
10
Kotlin
48
393
accdcfc1f34054978018e583702ac3b4c808b6ee
3,252
avito-android
MIT License
build-logic/publication/src/main/kotlin/com/avito/PublishAndroidLibraryPlugin.kt
avito-tech
230,265,582
false
{"Kotlin": 3573291, "Java": 67252, "Shell": 27675, "Dockerfile": 12799, "Makefile": 7970}
package com.avito import com.android.build.gradle.LibraryExtension import com.avito.android.publish.AndroidLibraryPublishExtension import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.publish.PublishingExtension import org.gradle.api.publish.maven.MavenPublication import org.gradle.api.tasks.bundling.Jar class PublishAndroidLibraryPlugin : Plugin<Project> { override fun apply(project: Project) { with(project) { plugins.apply(PublishReleasePlugin::class.java) val publishExtension = extensions.create("publish", AndroidLibraryPublishExtension::class.java) extensions.configure(LibraryExtension::class.java) { libraryExt -> with(libraryExt) { val sourcesTask = tasks.register("sourcesJar", Jar::class.java) { it.archiveClassifier.set("sources") it.from(libraryExt.sourceSets.getByName("main").java.srcDirs) } val allVariantNames = mutableListOf<String>() var registeredVariants = 0 // todo use new publishing: https://developer.android.com/studio/releases/gradle-plugin#build-variant-publishing libraryVariants .matching { allVariantNames += it.name it.name == publishExtension.variant.get() }.whenObjectAdded { extensions.configure(PublishingExtension::class.java) { publishing -> publishing.publications { pubs -> pubs.register( "${publishExtension.variant.get()}AndroidLibrary", MavenPublication::class.java ) { maven -> maven.from(components.getAt(publishExtension.variant.get())) maven.artifact(sourcesTask.get()) registeredVariants++ afterEvaluate { maven.artifactId = publishExtension.artifactId.getOrElse(project.name) } } } } } afterEvaluate { require(registeredVariants > 0) { val path = project.path val variant = publishExtension.variant.get() """ No created publications for $path, with plugin "convention.publish-android-library". Options: - Remove plugin if library was not supposed to be published - Check configuration: published variant:$variant;available variants=$allVariantNames """.trimIndent() } } } } } } }
10
Kotlin
48
393
accdcfc1f34054978018e583702ac3b4c808b6ee
3,252
avito-android
MIT License
app/src/main/java/com/justwayward/reader/bean/support/DownloadQueue.kt
petma
198,171,907
true
{"Kotlin": 1560776, "Java": 34640, "JavaScript": 31488, "HTML": 5286, "CSS": 4040}
/** * Copyright 2016 JustWayward Team * * * 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.justwayward.reader.bean.support import com.justwayward.reader.bean.BookMixAToc import java.io.Serializable /** * 下载队列实体 * * @author yuyh. * @date 16/8/13. */ class DownloadQueue : Serializable { var bookId: String var list: List<BookMixAToc.mixToc.Chapters> var start: Int = 0 var end: Int = 0 /** * 是否已经开始下载 */ var isStartDownload = false /** * 是否中断下载 */ var isCancel = false /** * 是否下载完成 */ var isFinish = false constructor(bookId: String, list: List<BookMixAToc.mixToc.Chapters>, start: Int, end: Int) { this.bookId = bookId this.list = list this.start = start this.end = end } /** * 空事件。表示通知继续执行下一条任务 */ constructor() {} }
0
Kotlin
0
0
d011466692aae7c583ab8a264f760f7ff7d17458
1,390
BookReader-1
Apache License 2.0
app/src/main/java/com/opnay/todo/Util.kt
opnay
134,983,889
false
{"Kotlin": 35041}
package com.opnay.todo import android.content.Context import android.graphics.Color import android.graphics.drawable.Drawable import android.support.v4.content.ContextCompat import android.support.v4.graphics.drawable.DrawableCompat class Util { companion object { const val KEY_CATEGORY = "CATEGORY" const val KEY_ITEM = "ITEM" } } fun Boolean.toLong(): Long = if (this) 1 else 0 fun Long.toBoolean(): Boolean = (this != 0L) fun Boolean.toInt(): Int = if (this) 1 else 0 fun Int.toBoolean(): Boolean = (this != 0) fun Boolean.toByte(): Byte = if (this) 1 else 0 fun Byte.toBoolean(): Boolean = (this != 0.toByte()) fun Context.getTintedDrawable(id: Int, color: Int = Color.BLACK): Drawable = ContextCompat.getDrawable(this, id)!!.apply { DrawableCompat.setTint(this, color) } fun Context.getColorFromCompat(id: Int) = ContextCompat.getColor(this, id)
0
Kotlin
0
1
5e09e5da2a6bc2e258ff2f008c488810d7aec443
887
Todo
Apache License 2.0
projects/resettlement-passport-and-delius/src/dev/kotlin/uk/gov/justice/digital/hmpps/data/generator/ProviderGenerator.kt
ministryofjustice
500,855,647
false
{"Kotlin": 4262046, "HTML": 70066, "D2": 42781, "Ruby": 25921, "Shell": 19356, "SCSS": 6370, "HCL": 2712, "Dockerfile": 2447, "JavaScript": 1372, "Python": 268}
package uk.gov.justice.digital.hmpps.data.generator import uk.gov.justice.digital.hmpps.entity.* object ProviderGenerator { val DEFAULT_INSTITUTION = generateNomisInstitution(code = "LDN") val INSTITUTION_NO_TEAM = generateNomisInstitution(code = "MDL") val DEFAULT_AREA = generateProbationArea() val AREA_NO_TEAM = generateProbationArea(code = "MDL", institution = INSTITUTION_NO_TEAM) val DEFAULT_TEAM = generateTeam("N03DEF") val CSN_TEAM = generateTeam("LDNCSN") var DEFAULT_STAFF = generateStaff("N03DEF1", "John", "Smith", "James", probationAreaId = DEFAULT_AREA.id) var EXISTING_CSN_STAFF = generateStaff("LDNA001", "Terry", "Nutkins", "James", probationAreaId = DEFAULT_AREA.id) fun generateProbationArea( id: Long = IdGenerator.getAndIncrement(), code: String = "LDN", description: String = "London", institution: Institution? = DEFAULT_INSTITUTION ) = ProbationArea(id, code, description, institution) fun generateTeam( code: String, description: String = "Team $code", id: Long = IdGenerator.getAndIncrement() ) = Team(id, code, description) fun generateStaff( code: String, forename: String, surname: String, middleName: String? = null, id: Long = IdGenerator.getAndIncrement(), probationAreaId: Long ) = Staff(code, forename, surname, middleName, null, probationAreaId, id = id) fun generateStaffUser( username: String, staff: Staff, id: Long = IdGenerator.getAndIncrement() ) = StaffUser(username, staff, id) fun generateNomisInstitution( id: Long = IdGenerator.getAndIncrement(), code: String ) = Institution(id, code) }
3
Kotlin
0
2
3f85ef8108aa583819eeee66d9d436a760028962
1,760
hmpps-probation-integration-services
MIT License
ui/ui-foundation/src/main/kotlin/dev/teogor/ceres/ui/foundation/config/FeedbackConfig.kt
teogor
555,090,893
false
{"Kotlin": 1325679}
/* * Copyright 2023 teogor (Teodor Grigor) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.teogor.ceres.ui.foundation.config object FeedbackConfig { var disableAudioFeedback: Boolean = false var disableVibrationFeedback: Boolean = false var vibrationFeedbackIntensity: Long = 50L }
2
Kotlin
4
62
d7381c48a88dd5f887fb41e0ad13475a47589e87
818
ceres
Apache License 2.0
data/src/test/kotlin/com/vultisig/wallet/data/usecases/AesEncryptionTest.kt
vultisig
789,965,982
false
{"Kotlin": 1479669, "Ruby": 1713}
package com.vultisig.wallet.data.usecases import io.ktor.util.decodeBase64Bytes import org.junit.Assert.assertEquals import org.junit.Test import kotlin.test.assertFailsWith class AesEncryptionTest { private val aes = AesEncryption() private val originalInput = "Original Input 123" private val password = "<PASSWORD>" @Test fun `encryption is reversible`() { val encrypted = aes.encrypt(originalInput.toByteArray(Charsets.UTF_8), password) assertEquals( originalInput, aes.decrypt(encrypted, password)!!.toString(Charsets.UTF_8), ) } @Test fun `decryption works`() { val encryptedBase64 = "zPMOwnPVMFKMf9LOIFkyqBOr8AC1SIdQ34Ruk5gmRqxZ+lIyK7zM5/1NUjXlAg==" assertEquals( originalInput, aes.decrypt(encryptedBase64.decodeBase64Bytes(), password)!!.toString(Charsets.UTF_8), ) } @Test fun `decryption fails if password isn't correct`() { val encrypted = aes.encrypt(originalInput.toByteArray(Charsets.UTF_8), password) assertFailsWith<Exception> { aes.decrypt(encrypted, "321drowssap")!!.toString(Charsets.UTF_8) } } }
31
Kotlin
2
6
9a24026e09bafb8667f90c8ec7e3e806697e8a08
1,206
vultisig-android
Apache License 2.0
app/src/main/java/com/neokii/ntune/SshSession.kt
linu1983
290,173,226
true
{"Kotlin": 25996, "Python": 7334, "Java": 5369}
package com.neokii.ntune import android.os.Handler import android.os.Looper import com.jcraft.jsch.ChannelExec import com.jcraft.jsch.JSch import com.jcraft.jsch.Session import java.io.ByteArrayOutputStream import java.lang.Exception import java.util.* import java.util.concurrent.Executors class SshSession (val host: String, val port: Int) { val privateKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC+iXXq30Tq+J5N\n" + "Kat3KWHCzcmwZ55nGh6WggAqECa5CasBlM9VeROpVu3beA+5h0MibRgbD4DMtVXB\n" + "t6gEvZ8nd04E7eLA9LTZyFDZ7SkSOVj4oXOQsT0GnJmKrASW5KslTWqVzTfo2XCt\n" + "Z+004ikLxmyFeBO8NOcErW1pa8gFdQDToH9FrA7kgysic/XVESTOoe7XlzRoe/eZ\n" + "acEQ+jtnmFd21A4aEADkk00Ahjr0uKaJiLUAPatxs2icIXWpgYtfqqtaKF23wSt6\n" + "1OTu6cAwXbOWr3m+IUSRUO0IRzEIQS3z1jfd1svgzSgSSwZ1Lhj4AoKxIEAIc8qJ\n" + "rO4uymCJAgMBAAECggEBAISFevxHGdoL3Z5xkw6oO5SQKO2GxEeVhRzNgmu/HA+q\n" + "x8OryqD6O1CWY4037kft6iWxlwiLOdwna2P25ueVM3LxqdQH2KS4DmlCx+kq6FwC\n" + "gv063fQPMhC9LpWimvaQSPEC7VUPjQlo4tPY6sTTYBUOh0A1ihRm/x7juKuQCWix\n" + "Cq8C/DVnB1X4mGj+W3nJc5TwVJtgJbbiBrq6PWrhvB/3qmkxHRL7dU2SBb2iNRF1\n" + "LLY30dJx/cD73UDKNHrlrsjk3UJc29Mp4/MladKvUkRqNwlYxSuAtJV0nZ3+iFkL\n" + "s3adSTHdJpClQer45R51rFDlVsDz2ZBpb/hRNRoGDuECgYEA6A1EixLq7QYOh3cb\n" + "Xhyh3W4kpVvA/FPfKH1OMy3ONOD/Y9Oa+M/wthW1wSoRL2n+uuIW5OAhTIvIEivj\n" + "6bAZsTT3twrvOrvYu9rx9aln4p8BhyvdjeW4kS7T8FP5ol6LoOt2sTP3T1LOuJPO\n" + "uQvOjlKPKIMh3c3RFNWTnGzMPa0CgYEA0jNiPLxP3A2nrX0keKDI+VHuvOY88gdh\n" + "0W5BuLMLovOIDk9aQFIbBbMuW1OTjHKv9NK+Lrw+YbCFqOGf1dU/UN5gSyE8lX/Q\n" + "FsUGUqUZx574nJZnOIcy3ONOnQLcvHAQToLFAGUd7PWgP3CtHkt9hEv2koUwL4vo\n" + "ikTP1u9Gkc0CgYEA2apoWxPZrY963XLKBxNQecYxNbLFaWq67t3rFnKm9E8BAICi\n" + "<KEY>" + "<KEY>//<KEY>" + "<KEY>" + "<KEY>" + "jTadcgKFnRUmc+JT9p/ZbCxkA/ALFg8++G+0ghECgYA8vG3M/utweLvq4RI7l7U7\n" + "b+i2BajfK2OmzNi/xugfeLjY6k2tfQGRuv6ppTjehtji2uvgDWkgjJUgPfZpir3I\n" + "RsVMUiFgloWGHETOy0Qvc5AwtqTJFLTD1Wza2uBilSVIEsg6Y83Gickh+ejOmEsY\n" + "6co17RFaAZHwGfCFFjO76Q==\n" + "-----END PRIVATE KEY-----" val publicKey = "<KEY>" private val jsch: JSch = JSch() private lateinit var session: Session init { jsch.addIdentity("id_rsa", privateKey.toByteArray(), publicKey.toByteArray(), "passphrase".toByteArray()) } interface OnConnectListener { fun onConnect() fun onFail(e:Exception) } interface OnResponseListener { fun onResponse(res:String) fun onFail(e:Exception) } fun connect(listener: OnConnectListener?) { Executors.newSingleThreadExecutor().execute { try { session = jsch.getSession("root", host, port) val config = Properties() config["StrictHostKeyChecking"] = "no" session.setConfig(config) session.connect(5000) Handler(Looper.getMainLooper()).post { listener?.onConnect() } } catch (e: Exception) { Handler(Looper.getMainLooper()).post { listener?.onFail(e) } } } } fun send(command: String, listener: OnResponseListener?) { Executors.newSingleThreadExecutor().execute { try { val outputStream = ByteArrayOutputStream(1024*32) val channel: ChannelExec = session.openChannel("exec") as ChannelExec channel.setCommand(command) channel.setOutputStream(outputStream) channel.connect() waitUntilChannelClosed(channel) channel.disconnect() Handler(Looper.getMainLooper()).post { listener?.onResponse(outputStream.toString("UTF-8")) } } catch (e: Exception) { Handler(Looper.getMainLooper()).post { listener?.onFail(e) } } } } fun close() { session.disconnect() } private fun waitUntilChannelClosed(executionChannel: ChannelExec) { var waitTimeThusFar = 0L val sessionTimeout: Long = 10000L do { try { Thread.sleep(100L) waitTimeThusFar += 100L if (sessionTimeout > 0L && waitTimeThusFar > sessionTimeout) { break } } catch (e: InterruptedException) { } } while (!executionChannel.isClosed) if (!executionChannel.isClosed) { executionChannel.disconnect() throw Exception("Timeout: ${sessionTimeout}") } } }
0
null
0
0
33088473bd2b5d803ebd23219027129e92d28f46
4,981
nTune
MIT License
kotlin-mui-icons/src/main/generated/mui/icons/material/BorderColorRounded.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/BorderColorRounded") package mui.icons.material @JsName("default") external val BorderColorRounded: SvgIconComponent
12
null
5
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
200
kotlin-wrappers
Apache License 2.0
awesome-calendar/src/main/java/com/archit/calendardaterangepicker/customviews/CustomDateView.kt
ArchitShah248
100,138,200
false
null
package com.yehia.mira_calendar_date_range.customviews import android.content.Context import android.graphics.Color import android.graphics.PorterDuff.Mode.SRC_IN import android.graphics.PorterDuffColorFilter import android.graphics.Typeface import android.util.AttributeSet import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.View.OnClickListener import android.widget.FrameLayout import androidx.core.content.ContextCompat import com.yehia.mira_calendar_date_range.R import com.yehia.mira_calendar_date_range.R.drawable import com.yehia.mira_calendar_date_range.customviews.DateView.DateState import com.yehia.mira_calendar_date_range.customviews.DateView.DateState.DISABLE import com.yehia.mira_calendar_date_range.customviews.DateView.DateState.END import com.yehia.mira_calendar_date_range.customviews.DateView.DateState.HIDDEN import com.yehia.mira_calendar_date_range.customviews.DateView.DateState.MIDDLE import com.yehia.mira_calendar_date_range.customviews.DateView.DateState.SELECTABLE import com.yehia.mira_calendar_date_range.customviews.DateView.DateState.START import com.yehia.mira_calendar_date_range.customviews.DateView.DateState.START_END_SAME import com.yehia.mira_calendar_date_range.customviews.DateView.OnDateClickListener import com.yehia.mira_calendar_date_range.models.CalendarStyleAttrImpl import com.yehia.mira_calendar_date_range.models.CalendarStyleAttributes import java.text.ParseException import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.Locale class CustomDateView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr), DateView { private val tvDate: CustomTextView private val strip: View private val simpleDateFormat = SimpleDateFormat(CalendarDateRangeManager.DATE_FORMAT, Locale.getDefault()) private val filterMode = SRC_IN private var onDateClickListener: OnDateClickListener? = null private var mDateState: DateState private val isRightToLeft = resources.getBoolean(R.bool.cdr_is_right_to_left) init { val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater inflater.inflate(R.layout.layout_calendar_day, this, true) tvDate = findViewById(R.id.dayOfMonthText) strip = findViewById(R.id.viewStrip) mDateState = SELECTABLE if (!isInEditMode) { setDateStyleAttributes(CalendarStyleAttrImpl.getDefAttributes(context)) updateDateBackground(mDateState) } } private val defCalendarStyleAttr: CalendarStyleAttrImpl = CalendarStyleAttrImpl.getDefAttributes(context) override var dateTextSize: Float = defCalendarStyleAttr.textSizeDate override var defaultDateColor: Int = defCalendarStyleAttr.defaultDateColor override var disableDateColor: Int = defCalendarStyleAttr.disableDateColor override var selectedDateCircleColor: Int = defCalendarStyleAttr.selectedDateCircleColor override var selectedDateColor: Int = defCalendarStyleAttr.selectedDateColor override var rangeDateColor: Int = defCalendarStyleAttr.rangeDateColor override var stripColor: Int = defCalendarStyleAttr.rangeStripColor private val mViewClickListener = OnClickListener { val key = it.tag as Long if (onDateClickListener != null) { val selectedCal = Calendar.getInstance() var date = Date() try { date = simpleDateFormat.parse(key.toString()) } catch (e: ParseException) { e.printStackTrace() } selectedCal.time = date onDateClickListener?.onDateClicked(it, selectedCal) } } override fun setDateText(date: String) { tvDate.text = date } override fun setDateStyleAttributes(attr: CalendarStyleAttributes) { disableDateColor = attr.disableDateColor defaultDateColor = attr.defaultDateColor selectedDateCircleColor = attr.selectedDateCircleColor selectedDateColor = attr.selectedDateColor stripColor = attr.rangeStripColor rangeDateColor = attr.rangeDateColor tvDate.textSize = attr.textSizeDate refreshLayout() } override fun setTypeface(typeface: Typeface) { tvDate.typeface = typeface } override fun setDateTag(date: Calendar) { tag = DateView.getContainerKey(date) } override fun updateDateBackground(dateState: DateState) { mDateState = dateState when (dateState) { START, END, START_END_SAME -> makeAsSelectedDate(dateState) HIDDEN -> hideDayContainer() SELECTABLE -> enabledDayContainer() DISABLE -> disableDayContainer() MIDDLE -> makeAsRangeDate() else -> throw IllegalArgumentException("$dateState is an invalid state.") } } override fun refreshLayout() { tvDate.setTextSize(TypedValue.COMPLEX_UNIT_PX, dateTextSize) } override fun setDateClickListener(listener: OnDateClickListener) { onDateClickListener = listener } /** * To hide date if date is from previous month. */ private fun hideDayContainer() { tvDate.text = "" tvDate.setBackgroundColor(Color.TRANSPARENT) strip.setBackgroundColor(Color.TRANSPARENT) setBackgroundColor(Color.TRANSPARENT) visibility = View.INVISIBLE setOnClickListener(null) } /** * To disable past date. Click listener will be removed. */ private fun disableDayContainer() { tvDate.setBackgroundColor(Color.TRANSPARENT) strip.setBackgroundColor(Color.TRANSPARENT) setBackgroundColor(Color.TRANSPARENT) tvDate.setTextColor(disableDateColor) visibility = View.VISIBLE setOnClickListener(null) } /** * To enable date by enabling click listeners. */ private fun enabledDayContainer() { tvDate.setBackgroundColor(Color.TRANSPARENT) strip.setBackgroundColor(Color.TRANSPARENT) setBackgroundColor(Color.TRANSPARENT) tvDate.setTextColor(defaultDateColor) visibility = View.VISIBLE setOnClickListener(mViewClickListener) } /** * To draw date container as selected as end selection or middle selection. * * @param state - DateState */ private fun makeAsSelectedDate(state: DateState) { when (state) { START_END_SAME -> { val layoutParams = strip.layoutParams as LayoutParams strip.setBackgroundColor(Color.TRANSPARENT) layoutParams.setMargins(0, 0, 0, 0) strip.layoutParams = layoutParams } START -> { if (isRightToLeft) { setRightFacedSelectedDate() } else { setLeftFacedSelectedDate() } } END -> { if (isRightToLeft) { setLeftFacedSelectedDate() } else { setRightFacedSelectedDate() } } else -> { throw IllegalArgumentException("$state is an invalid state.") } } val mDrawable = ContextCompat.getDrawable(context, drawable.green_circle) mDrawable!!.colorFilter = PorterDuffColorFilter(selectedDateCircleColor, filterMode) tvDate.background = mDrawable setBackgroundColor(Color.TRANSPARENT) tvDate.setTextColor(selectedDateColor) visibility = View.VISIBLE setOnClickListener(mViewClickListener) } private fun setLeftFacedSelectedDate() { val layoutParams = strip.layoutParams as LayoutParams val drawable = ContextCompat.getDrawable(context, drawable.range_bg_left) drawable!!.colorFilter = PorterDuffColorFilter(stripColor, filterMode) strip.background = drawable layoutParams.setMargins(20, 0, 0, 0) strip.layoutParams = layoutParams } private fun setRightFacedSelectedDate() { val layoutParams = strip.layoutParams as LayoutParams val drawable = ContextCompat.getDrawable(context, drawable.range_bg_right) drawable!!.colorFilter = PorterDuffColorFilter(stripColor, filterMode) strip.background = drawable layoutParams.setMargins(0, 0, 20, 0) strip.layoutParams = layoutParams } /** * To draw date as middle date */ private fun makeAsRangeDate() { tvDate.setBackgroundColor(Color.TRANSPARENT) val mDrawable = ContextCompat.getDrawable(context, drawable.range_bg) mDrawable!!.colorFilter = PorterDuffColorFilter(stripColor, filterMode) strip.background = mDrawable setBackgroundColor(Color.TRANSPARENT) tvDate.setTextColor(rangeDateColor) visibility = View.VISIBLE val layoutParams = strip.layoutParams as LayoutParams layoutParams.setMargins(0, 0, 0, 0) strip.layoutParams = layoutParams setOnClickListener(mViewClickListener) } }
45
null
81
261
864d3b898b3d4d6ec06405dfe671e28227d78908
9,263
CalendarDateRangePicker
Apache License 2.0
question2/src/main/java/com/duytuan/screeningtest/question2/base/BaseDao.kt
duytuan001
354,739,265
false
null
package com.duytuan.screeningtest.question2.base import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Update // https://medium.com/androiddevelopers/7-pro-tips-for-room-fbadea4bfbd1 interface BaseDao<T> { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAll(list: List<T>) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(vararg t: T) @Update fun update(vararg t: T) @Delete fun delete(vararg t: T) @Delete fun deleteAll(list: List<T>) }
0
Kotlin
0
1
9ea4ae8844eb61e395354d0db5441889e1d779e9
571
FossilAndroidTest
MIT License
app/src/main/java/com/madonasyombua/sportsdb/ui/screen/teamdetails/event/TeamLastEvents.kt
Madonahs
120,659,933
false
null
package com.madonasyombua.sportsdb.ui.screen.teamdetails.event import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.Card import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle 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.compose.ui.unit.sp import com.madonasyombua.sportsdb.data.remote.model.Event import com.madonasyombua.sportsdb.ui.theme.Green800 import dev.chrisbanes.accompanist.coil.CoilImage import timber.log.Timber /** * Created by <NAME> * 3/23/2021 * */ @Composable fun TeamEventsScreen(viewModel: TeamEventViewModel) { val events = viewModel.eventsLiveData.observeAsState() LazyColumn( modifier = Modifier .background( color = Color(0xeeecf1) ) .fillMaxHeight() ) { events.value?.let {events-> items(events.size) { index -> EventsCardItem(event = events[index], viewModel) }} } } @Composable fun EventsCardItem(event: Event, viewModel: TeamEventViewModel) { val teamDetails = viewModel.teamDetailsLiveData.observeAsState() viewModel.getAwayTeamDetails(event.awayTeamId) Card(modifier = Modifier.padding(10.dp)) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxWidth() .padding(bottom = 16.dp) ) { Box( contentAlignment = Alignment.Center, modifier = Modifier .background(color = Green800) .padding(top = 8.dp, bottom = 8.dp) .fillMaxWidth() ) { Text(text = event.leagueName,color = Color.White ) } Row( modifier = Modifier .padding(top = 16.dp, bottom = 20.dp) .fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { teamDetails.value?.get(0)?.let { CoilImage( data = it.badgeUrl, contentDescription = null, modifier = Modifier .width(40.dp) .height(40.dp) .padding(end = 4.dp, bottom = 8.dp),contentScale = ContentScale.Crop ) } Text( text = event.homeTeam, style = MaterialTheme.typography.subtitle1, modifier = Modifier.width(70.dp), ) Text( text = " ${event.homeScore} - ", ) Text( text = event.awayScore.plus(" ") ) Text( text = event.awayTeam ,style = MaterialTheme.typography.subtitle1, modifier = Modifier.width(80.dp) ) val awayTeam = viewModel.teamAwayDetailsLiveData.observeAsState() awayTeam.value?.get(0)?.let { Timber.e(event.homeTeamId) if (it.teamId == event.awayTeamId) event.badge = it.badgeUrl CoilImage(data = event.badge ,contentDescription = null, modifier = Modifier .width(40.dp) .height(40.dp) .padding(start = 4.dp, bottom = 8.dp),contentScale = ContentScale.Crop) } } Text( text = event.eventDate, color = Color.Gray ) } } } @Preview @Composable fun EventPreview() { //TeamEventsScreen() }
1
null
11
47
52f63ddb4f97b6098fb3be53ceba1de8c4efb947
4,422
The-Sports-DB
Apache License 2.0
bgw-gui/src/test/kotlin/tools/aqua/bgw/layoutelements/grid/RemoveEmptyColumnsTest.kt
tudo-aqua
377,420,862
false
{"Kotlin": 1198455, "TypeScript": 2013, "JavaScript": 1242, "HTML": 507, "CSS": 359, "Ruby": 131}
/* * Copyright 2021-2022 The BoardGameWork Authors * SPDX-License-Identifier: Apache-2.0 * * 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 tools.aqua.bgw.layoutelements.grid import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test /** Test remove empty columns function in Grid. */ class RemoveEmptyColumnsTest : GridPaneTestBase() { /** Remove empty columns from full grid. */ @Test @DisplayName("Remove empty columns from full grid") fun testRemoveEmptyColumnsOnFullGrid() { grid.removeEmptyColumns() // Grid unchanged checkSize() testUnchanged() } /** Remove empty columns from partially full grid. */ @Test @DisplayName("Remove empty columns from partially full grid") fun testRemoveEmptyColumnsOnPartiallyFullGrid() { grid[1, 2] = null grid[2, 2] = null grid.removeEmptyColumns() checkSize() // Row 0-1 unchanged testUnchanged(rows = 0..1) // Row 2 unchanged assertEquals(contents[0][2], grid[0, 2]) assertEquals(null, grid[1, 2]) assertEquals(null, grid[2, 2]) } /** Remove empty first column. */ @Test @DisplayName("Remove empty first column") fun testRemoveEmptyFirstColumn() { grid[0, 0] = null grid[0, 1] = null grid[0, 2] = null grid.removeEmptyColumns() checkSize(2, 3) // Columns 0-1 contain former columns 1-2 testUnchanged(columns = 0..1, columnBias = 1) } /** Remove empty last column. */ @Test @DisplayName("Remove empty last column") fun testRemoveEmptyLastColumn() { grid[2, 0] = null grid[2, 1] = null grid[2, 2] = null grid.removeEmptyColumns() checkSize(2, 3) // Columns 0-1 unchanged testUnchanged(columns = 0..1) } /** Remove empty middle column. */ @Test @DisplayName("Remove empty middle column") fun testRemoveEmptyMiddleColumn() { grid[1, 0] = null grid[1, 1] = null grid[1, 2] = null grid.removeEmptyColumns() checkSize(2, 3) // Column 0 unchanged testUnchanged(columns = 0..0) // Column 1 contains former column 2 testUnchanged(columns = 1..1, columnBias = 1) } /** Remove empty columns from empty grid. */ @Test @DisplayName("Remove empty columns from empty grid") fun testRemoveEmptyColumnsFromEmptyGrid() { for (i in 0..2) { for (j in 0..2) { grid[i, j] = null } } grid.removeEmptyColumns() checkSize(0, 0) } }
31
Kotlin
16
24
266db439e4443d10bc1ec7eb7d9032f29daf6981
3,003
bgw
Apache License 2.0
app/src/main/java/de/droidcon/berlin2018/di/DaoModule.kt
OpenConference
100,889,869
false
null
package de.droidcon.berlin2018.di import android.content.Context import com.hannesdorfmann.sqlbrite.dao.DaoManager import dagger.Module import dagger.Provides import de.droidcon.berlin2018.schedule.database.dao.LocationDao import de.droidcon.berlin2018.schedule.database.dao.LocationDaoSqlite import de.droidcon.berlin2018.schedule.database.dao.SessionDao import de.droidcon.berlin2018.schedule.database.dao.SessionDaoSqlite import de.droidcon.berlin2018.schedule.database.dao.SpeakerDao import de.droidcon.berlin2018.schedule.database.dao.SpeakerDaoSqlite @Module class DaoModule(context: Context) { private val sessionDao: SessionDao private val speakerDao: SpeakerDao private val locationDao: LocationDao init { // DAO's sessionDao = SessionDaoSqlite() speakerDao = SpeakerDaoSqlite() locationDao = LocationDaoSqlite() DaoManager.with(context.applicationContext) .add(sessionDao) .add(speakerDao) .add(locationDao) .version(1) .databaseName("schedule.db") .build() } @Provides fun provideSessionDao() = sessionDao @Provides fun provideSpeakerDao() = speakerDao @Provides fun provideLocationDao() = locationDao }
1
Kotlin
1
27
142effaf4eb04abb12d5b812e797a89922b649a5
1,215
DroidconBerlin2017
Apache License 2.0
app/src/main/java/it/unibo/noteforall/utils/CurrentUser.kt
riccardopenazzi
788,878,884
false
{"Kotlin": 164881}
package it.unibo.noteforall.utils data class CurrentUser( val id: String ) object CurrentUserSingleton { var currentUser: CurrentUser? = null }
0
Kotlin
0
0
4abb0426a07820b9c3729bff4a06a8c18e3e2c12
153
mobile-project
MIT License
app/src/main/java/com/erkindilekci/foodbook/data/model/CategoryList.kt
erkindilekci
668,284,495
false
null
package com.erkindilekci.foodbook.data.model data class CategoryList( val categories: List<Category> )
0
Kotlin
0
0
5ec1cc1924628acce2e329aace2e03dec0d7df77
108
FoodBook
Apache License 2.0
autumn-core/src/main/kotlin/org/example/autumn/context/ApplicationContext.kt
NuclearMissile
776,826,220
false
{"Kotlin": 357540, "HTML": 8038, "FreeMarker": 4818, "Java": 1431, "JavaScript": 1347, "Dockerfile": 82}
package org.example.autumn.context import org.example.autumn.DEFAULT_ORDER import org.example.autumn.annotation.* import org.example.autumn.aop.AnnotationProxyBeanPostProcessor.Companion.createProxy import org.example.autumn.aop.Invocation import org.example.autumn.exception.* import org.example.autumn.utils.ClassUtils.findNestedAnnotation import org.example.autumn.utils.ClassUtils.getBeanName import org.example.autumn.utils.ClassUtils.scanClassNames import org.example.autumn.utils.IProperties import org.slf4j.LoggerFactory import java.lang.reflect.* interface ApplicationContext : AutoCloseable { /** * all bean classnames managed by ctx */ val managedClassNames: List<String> /** * all BeanInfos associated with bean names */ val beanInfoMap: Map<String, IBeanInfo> val config: IProperties fun getBeanInfos(type: Class<*>): List<IBeanInfo> fun <T> tryGetBean(name: String, requiredType: Class<T>? = null): T? fun <T> tryGetUniqueBean(type: Class<T>): T? /** * find bean instance by name, if not found, throw NoSuchBeanException, * if found but not fit into requireType, throw BeanTypeException */ fun <T> getBean(name: String, requiredType: Class<T>? = null): T = tryGetBean(name, requiredType) ?: throw NoSuchBeanException("No bean with name: $name") fun <T> getUniqueBean(type: Class<T>): T = tryGetUniqueBean(type) ?: throw NoSuchBeanException("No bean defined with type '$type'.") @Suppress("UNCHECKED_CAST") fun <T> getBeans(type: Class<T>) = getBeanInfos(type).map { it.requiredInstance as T } /** * 创建一个Bean,然后使用BeanPostProcessor处理,但不进行字段和方法级别的注入。 * 如果创建的Bean不是Configuration或BeanPostProcessor,则在构造方法中注入的依赖Bean会自动创建。 */ fun createEarlySingleton(info: IBeanInfo): Any override fun close() } interface BeanPostProcessor { /** * Invoked after new Bean(), before @PostConstruct bean.init(). */ fun beforeInitialization(bean: Any, beanName: String): Any { return bean } /** * Invoked after @PostConstruct bean.init() called. */ fun afterInitialization(bean: Any, beanName: String): Any { return bean } /** * Invoked before bean.setXyz() called. */ fun beforePropertySet(bean: Any, beanName: String): Any { return bean } } object ApplicationContextHolder { internal var instance: ApplicationContext? = null val required: ApplicationContext get() = requireNotNull(instance) { "ApplicationContext is not set." } } class AnnotationApplicationContext(configClass: Class<*>, override val config: IProperties) : ApplicationContext { private val logger = LoggerFactory.getLogger(javaClass) private val sortedBeanInfos: List<IBeanInfo> private val postProcessors = mutableListOf<BeanPostProcessor>() private val creatingBeanNames = mutableSetOf<String>() override val managedClassNames: List<String> override val beanInfoMap: MutableMap<String, IBeanInfo> init { // register this to app context holder ApplicationContextHolder.instance = this managedClassNames = scanClassNamesOnConfigClass(configClass) beanInfoMap = createBeanInfos(managedClassNames) sortedBeanInfos = beanInfoMap.values.sorted() // init @Configuration beans sortedBeanInfos.filter { it.isConfiguration }.forEach(::createEarlySingleton) // init BeanPostProcessor beans postProcessors += sortedBeanInfos.filter { it.isBeanPostProcessor }.map { createEarlySingleton(it) as BeanPostProcessor } // init naive beans sortedBeanInfos.forEach { it.instance ?: createEarlySingleton(it) } // inject depends via field or setter sortedBeanInfos.forEach { try { injectProperties(it, it.beanClass, getOriginalInstance(it)) } catch (e: ReflectiveOperationException) { throw BeanCreationException("Error while injectBean for $it", e) } } // call init method sortedBeanInfos.forEach { info -> invokeMethod(getOriginalInstance(info), info.initMethod, info.initMethodName) postProcessors.forEach { postProcessor -> val processed = postProcessor.afterInitialization(info.requiredInstance, info.beanName) if (processed !== info.requiredInstance) { logger.atDebug().log( "BeanPostProcessor {} return different bean from {} to {}.", postProcessor.javaClass.name, info.requiredInstance.javaClass.name, processed.javaClass.name ) info.instance = processed } } } if (logger.isDebugEnabled) { sortedBeanInfos.forEach { logger.debug("bean initialized: $it") } } } private fun Class<*>.getOrder() = getAnnotation(Order::class.java)?.value ?: DEFAULT_ORDER private fun Method.getOrder() = getAnnotation(Order::class.java)?.value ?: DEFAULT_ORDER private fun Class<*>.isPrimary() = isAnnotationPresent(Primary::class.java) private fun Method.isPrimary() = isAnnotationPresent(Primary::class.java) private fun Class<*>.beanCtor() = run { val ctors = declaredConstructors.sortedByDescending { it.parameterCount } ctors.firstOrNull { it.isAnnotationPresent(Autowired::class.java) } ?: ctors.firstOrNull { it.parameters.all { p -> p.isAnnotationPresent(Autowired::class.java) || p.isAnnotationPresent(Value::class.java) } } ?: throw BeanDefinitionException("No valid bean constructor found in class: $name.") } private fun scanClassNamesOnConfigClass(configClass: Class<*>): List<String> { val scanPackages = configClass.getAnnotation(ComponentScan::class.java)?.value?.toList() ?: listOf(configClass.packageName) logger.info("component scan in packages: {}", scanPackages.joinToString()) val classNameSet = scanClassNames(scanPackages).toMutableSet() configClass.getAnnotation(Import::class.java)?.value?.forEach { val importClassName = it.java.name if (classNameSet.contains(importClassName)) { logger.warn("ignore import: $importClassName, already imported.") } else { logger.debug("class found by import: {}", importClassName) classNameSet.add(importClassName) } } logger.atDebug().log("class found by component scan: {}", classNameSet) return classNameSet.toList() } private fun createBeanInfos(classNames: Collection<String>): MutableMap<String, IBeanInfo> { /** * Get non-arg method by @PostConstruct or @PreDestroy. Not search in super class. */ fun Class<*>.findLifecycleMethod(annoClass: Class<out Annotation>): Method? { // try get declared method: val ms = declaredMethods.filter { it.isAnnotationPresent(annoClass) } require(ms.size <= 1) { throw BeanDefinitionException( "Multiple methods with @${annoClass.simpleName} found in class: $name" ) } require(ms.isEmpty() || ms[0].parameterCount == 0) { throw BeanDefinitionException( "Method '${ms[0].name}' with @${annoClass.simpleName} must not have argument: $name" ) } return ms.firstOrNull() } /** * Scan factory method that annotated with @Bean: */ fun scanFactoryMethods( factoryBeanName: String, factoryClass: Class<*>, infos: MutableMap<String, IBeanInfo>, ) { for (method in factoryClass.declaredMethods) { val bean = method.getAnnotation(Bean::class.java) ?: continue val mod = method.modifiers if (Modifier.isAbstract(mod)) throw BeanDefinitionException("@Bean method ${factoryClass.name}.${method.name} cannot be abstract") if (Modifier.isFinal(mod)) throw BeanDefinitionException("@Bean method ${factoryClass.name}.${method.name} cannot be final") if (Modifier.isPrivate(mod)) throw BeanDefinitionException("@Bean method ${factoryClass.name}.${method.name} cannot be private") val beanClass = method.returnType if (beanClass.isPrimitive) throw BeanDefinitionException("@Bean method ${factoryClass.name}.${method.name} cannot return primitive type") if (beanClass == Void.TYPE || beanClass == Void::class.java) throw BeanDefinitionException("@Bean method ${factoryClass.name}.${method.name} cannot return void") val beanName = method.getAnnotation(Bean::class.java)!!.value.ifEmpty { method.name } val info = BeanInfo( beanName, beanClass, method.getOrder(), method.isPrimary(), factoryBeanName, method, bean.initMethod.ifEmpty { null }, bean.destroyMethod.ifEmpty { null } ) if (infos.put(info.beanName, info) != null) { throw BeanDefinitionException("Duplicate bean name: ${info.beanName}") } logger.atDebug().log("define bean info via factory method: {}", info) } } val infoMap = mutableMapOf<String, IBeanInfo>() for (className in classNames) { // 获取Class: val clazz = try { Class.forName(className, true, Thread.currentThread().contextClassLoader) } catch (e: ClassNotFoundException) { throw BeanCreationException("Class not found for name: $className", e) } if (clazz.isAnnotation || clazz.isEnum || clazz.isInterface || clazz.isRecord) { continue } // 是否标注@Component? clazz.findNestedAnnotation(Component::class.java) ?: continue val mod = clazz.modifiers if (Modifier.isAbstract(mod)) { throw BeanDefinitionException("@Component class ${clazz.name} must not be abstract.") } if (Modifier.isPrivate(mod)) { throw BeanDefinitionException("@Component class ${clazz.name} must not be private.") } val beanName = clazz.getBeanName() val info = BeanInfo( beanName, clazz, clazz.getOrder(), clazz.isPrimary(), clazz.beanCtor(), clazz.findLifecycleMethod(PostConstruct::class.java), clazz.findLifecycleMethod(PreDestroy::class.java) ) if (infoMap.put(info.beanName, info) != null) { throw BeanDefinitionException("Duplicate bean name: ${info.beanName}") } logger.atDebug().log("define bean info via @Component: {}", info) // handle factory method clazz.getAnnotation(Configuration::class.java) ?: continue if (BeanPostProcessor::class.java.isAssignableFrom(clazz)) { throw BeanDefinitionException("@Configuration class '${clazz.name}' cannot be BeanPostProcessor.") } scanFactoryMethods(beanName, clazz, infoMap) } return infoMap } private fun injectProperties(info: IBeanInfo, clazz: Class<*>, bean: Any) { fun Member.checkModifier() { when { Modifier.isStatic(modifiers) -> { throw BeanDefinitionException("Cannot inject static field or method: $this") } Modifier.isFinal(modifiers) -> { if (this is Field) { throw BeanDefinitionException("Cannot inject final field: $this") } if (this is Method) { logger.warn("Inject final method should be careful because it may cause NPE if that bean is proxied.") } } } } fun doInject(info: IBeanInfo, clazz: Class<*>, bean: Any, acc: AccessibleObject) { val valueAnno = acc.getAnnotation(Value::class.java) val autowiredAnno = acc.getAnnotation(Autowired::class.java) if (valueAnno == null && autowiredAnno == null) return acc.isAccessible = true val field: Field? val method: Method? when (acc) { is Field -> { acc.checkModifier() field = acc method = null } is Method -> { if (acc.parameterCount != 1) { throw BeanDefinitionException( "Cannot inject a non-setter method $acc for bean '${info.beanName}': ${info.beanClass.name}" ) } acc.checkModifier() method = acc field = null } else -> { throw AssertionError("Should not be here.") } } val accessibleName = field?.name ?: method!!.name val accessibleType = field?.type ?: method!!.parameterTypes.first() @Suppress("KotlinConstantConditions") when { valueAnno != null -> { val propValue = config.getRequired(valueAnno.value, accessibleType) if (field != null) { logger.atDebug().log( "Field injection by @Value: {}.{} = {}", info.beanClass.name, accessibleName, propValue ) field[bean] = propValue } if (method != null) { logger.atDebug().log( "Method injection by @Value: {}.{} ({})", info.beanClass.name, accessibleName, propValue ) method.invoke(bean, propValue) } } autowiredAnno != null -> { val name = autowiredAnno.name val required = autowiredAnno.value val depends = if (name.isEmpty()) tryGetUniqueBean(accessibleType) else tryGetBean(name, accessibleType) if (required && depends == null) { throw DependencyException( "Dependency bean not found when inject ${clazz.simpleName}.$accessibleName for bean '${info.beanName}': ${info.beanClass.name}" ) } if (depends != null) { if (field != null) { logger.atDebug().log( "Field injection by @Autowired: {}.{} = {}", info.beanClass.name, accessibleName, depends ) field[bean] = depends } if (method != null) { logger.atDebug().log( "Method injection by @AutoWired: {}.{} ({})", info.beanClass.name, accessibleName, depends ) method.invoke(bean, depends) } } } else -> { throw BeanCreationException( "Cannot specify both @Autowired and @Value when inject ${clazz.simpleName}.$accessibleName " + "for bean '${info.beanName}': ${info.beanClass.name}" ) } } } clazz.declaredFields.forEach { doInject(info, clazz, bean, it) } clazz.declaredMethods.forEach { doInject(info, clazz, bean, it) } val superClass = clazz.superclass if (superClass != null) { injectProperties(info, superClass, bean) } } /** * find IBeanInfo by type, if not found, return null; * if found multiple, return the one have @Primary anno, * if multiple or none @Primary anno found, throw NoUniqueBeanException */ private fun getUniqueBeanInfo(type: Class<*>): IBeanInfo? { val infos = getBeanInfos(type) if (infos.isEmpty()) return null if (infos.size == 1) return infos.single() val primaryInfos = infos.filter { it.isPrimary } if (primaryInfos.size == 1) return primaryInfos.single() if (primaryInfos.isEmpty()) { throw NoUniqueBeanException("Multiple beans with type '$type' found, but no @Primary specified.") } else { throw NoUniqueBeanException("Multiple beans with type '$type' found, and multiple @Primary specified.") } } /** * find IBeanInfo by name and requiredType, if name not found, return null; * if type not fit, throw BeanTypeException */ private fun getBeanInfo(name: String, requiredType: Class<*>? = null): IBeanInfo? { if (requiredType == null) { return beanInfoMap[name] } else { val info = beanInfoMap[name] ?: return null if (!requiredType.isAssignableFrom(info.beanClass)) { throw BeanTypeException( "Autowire required type '$requiredType' but bean '$name' has actual type '${info.beanClass}'." ) } return info } } override fun createEarlySingleton(info: IBeanInfo): Any { logger.atDebug().log("Try to create bean {} as early singleton: {}", info.beanName, info.beanClass.name) if (!creatingBeanNames.add(info.beanName)) { throw DependencyException("Circular dependency detected when create bean '${info.beanName}'") } val createFn = (info.beanCtor ?: info.factoryMethod)!! val createFnParams = createFn.parameters val ctorAutowiredAnno = if (createFn is Constructor<*>) createFn.getAnnotation(Autowired::class.java) else null val args = arrayOfNulls<Any>(createFnParams.size) for (i in createFnParams.indices) { val param = createFnParams[i] val paramAnnos = createFn.parameterAnnotations[i].toList() val paramValueAnno = paramAnnos.firstOrNull { Value::class.java.isInstance(it) } as Value? var paramAutowiredAnno = paramAnnos.firstOrNull { Autowired::class.java.isInstance(it) } as Autowired? if (ctorAutowiredAnno != null && paramValueAnno == null && paramAutowiredAnno == null) { paramAutowiredAnno = Autowired() } if (info.isConfiguration && paramAutowiredAnno != null) { throw BeanCreationException( "Cannot specify @Autowired when create @Configuration bean '${info.beanName}': ${info.beanClass.name}." ) } if (info.isBeanPostProcessor && paramAutowiredAnno != null) { throw BeanCreationException( "Cannot specify @Autowired when create BeanPostProcessor '${info.beanName}': ${info.beanClass.name}." ) } if (paramValueAnno != null && paramAutowiredAnno != null) { throw BeanCreationException( "Cannot specify both @Autowired and @Value when create bean '${info.beanName}': ${info.beanClass.name}." ) } if (paramValueAnno == null && paramAutowiredAnno == null) { throw BeanCreationException( "Must specify @Autowired or @Value when create bean '${info.beanName}': ${info.beanClass.name}." ) } val type = param.type when { paramValueAnno != null -> { args[i] = config.getRequired(paramValueAnno.value, type) } paramAutowiredAnno != null -> { val name = paramAutowiredAnno.name val required = paramAutowiredAnno.value val dependsOnInfo = if (name.isEmpty()) getUniqueBeanInfo(type) else getBeanInfo(name, type) if (required && dependsOnInfo == null) { throw BeanCreationException( "Missing autowired bean with type '${type.name}' when create bean '${info.beanName}': ${info.beanClass.name}." ) } if (dependsOnInfo != null) { // 获取依赖Bean: var autowiredBeanInstance = dependsOnInfo.instance if (autowiredBeanInstance == null && !info.isConfiguration && !info.isBeanPostProcessor) { // 当前依赖Bean尚未初始化,递归调用初始化该依赖Bean: autowiredBeanInstance = createEarlySingleton(dependsOnInfo) } args[i] = autowiredBeanInstance } else { args[i] = null } } else -> { throw AssertionError("Should not be here.") } } } // 创建Bean实例: info.instance = try { when { info.beanCtor != null -> info.beanCtor!!.newInstance(*args) info.factoryMethod != null -> info.factoryMethod!!.invoke(getBean(info.factoryName!!), *args) else -> BeanDefinitionException("cannot instantiate $info") } } catch (e: Exception) { throw BeanCreationException( "Exception when create bean '${info.beanName}': ${info.beanClass.name}", e ) } postProcessors.forEach { val proceed = it.beforeInitialization(info.requiredInstance, info.beanName) if (info.instance !== proceed) { logger.atDebug().log("Bean {} was replaced by post processor {}", info.beanName, it.javaClass.name) info.instance = proceed } } if (info.aopBeanInfos.isNotEmpty()) { logger.atDebug().log("Bean {} was replaced for adding aop handlers", info.beanName) info.instance = createProxy(info.instance, info.aopBeanInfos.sorted().map { (it.instance ?: createEarlySingleton(it)) as? Invocation ?: throw AopConfigException( "@${it.javaClass.simpleName} proxy handler '${it.beanName}' is not type of ${Invocation::class.java.name}." ) }) } return info.requiredInstance } override fun getBeanInfos(type: Class<*>): List<IBeanInfo> { return if (type == Any::class.java) sortedBeanInfos else sortedBeanInfos.filter { type.isAssignableFrom(it.beanClass) } } @Suppress("UNCHECKED_CAST") override fun <T> tryGetBean(name: String, requiredType: Class<T>?) = getBeanInfo(name, requiredType)?.requiredInstance as T? @Suppress("UNCHECKED_CAST") override fun <T> tryGetUniqueBean(type: Class<T>) = getUniqueBeanInfo(type)?.requiredInstance as T? override fun close() { logger.info("{} closing...", this.javaClass.name) sortedBeanInfos.forEach { invokeMethod(getOriginalInstance(it), it.destroyMethod, it.destroyMethodName) } beanInfoMap.clear() logger.info("{} closed.", this.javaClass.name) ApplicationContextHolder.instance = null } private fun getOriginalInstance(info: IBeanInfo): Any { var ret = info.requiredInstance // 如果Proxy改变了原始Bean,又希望注入到原始Bean,则由BeanPostProcessor指定原始Bean: postProcessors.reversed().forEach { val restoredInstance = it.beforePropertySet(ret, info.beanName) if (restoredInstance !== ret) { ret = restoredInstance } } if (info.requiredInstance !== ret) { logger.atDebug().log( "Get original bean instance for {}, original: {}.", info.requiredInstance.javaClass.simpleName, ret.javaClass.simpleName ) } return ret } private fun invokeMethod(beanInstance: Any, method: Method?, methodName: String?) { if (method != null) { try { method.invoke(beanInstance) } catch (e: ReflectiveOperationException) { throw BeanCreationException("Method $method invocation failed.", e) } } else if (methodName != null) { val namedMethod = try { beanInstance.javaClass.getDeclaredMethod(methodName) } catch (e: ReflectiveOperationException) { throw BeanDefinitionException("Method '$methodName' not found in class: ${beanInstance.javaClass.name}") } namedMethod.isAccessible = true try { namedMethod.invoke(beanInstance) } catch (e: ReflectiveOperationException) { throw BeanCreationException("Named method $namedMethod invocation failed.", e) } } } }
0
Kotlin
0
6
deeff25479eff195d5c4902c0aa17c43692598c6
25,658
Autumn
MIT License
diktat-ktlint-engine/src/main/kotlin/org/cqfn/diktat/ktlint/KtLintRuleWrapper.kt
saveourtool
275,879,956
false
null
package org.cqfn.diktat.ktlint import org.cqfn.diktat.api.DiktatRule import org.cqfn.diktat.api.DiktatRuleSet import org.cqfn.diktat.common.config.rules.DIKTAT_RULE_SET_ID import com.pinterest.ktlint.core.Rule import com.pinterest.ktlint.core.RuleProvider import org.jetbrains.kotlin.com.intellij.lang.ASTNode private typealias EmitType = (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit /** * This is a wrapper around __KtLint__'s [Rule] which adjusts visitorModifiers to keep order with prevRule. * @property rule */ class KtLintRuleWrapper( val rule: DiktatRule, prevRule: KtLintRuleWrapper? = null, ) : Rule( id = rule.id.qualifiedWithRuleSetId(DIKTAT_RULE_SET_ID), visitorModifiers = createVisitorModifiers(rule, prevRule), ) { override fun beforeVisitChildNodes( node: ASTNode, autoCorrect: Boolean, emit: EmitType, ) = rule.invoke(node, autoCorrect, emit) companion object { private fun Sequence<DiktatRule>.wrapRules(): Sequence<Rule> = runningFold(null as KtLintRuleWrapper?) { prevRule, diktatRule -> KtLintRuleWrapper(diktatRule, prevRule) }.filterNotNull() /** * @return [Set] of __KtLint__'s [RuleProvider]s created from [DiktatRuleSet] */ fun DiktatRuleSet.toKtLint(): Set<RuleProvider> = rules .asSequence() .wrapRules() .map { it.asProvider() } .toSet() private fun createVisitorModifiers( rule: DiktatRule, prevRule: KtLintRuleWrapper?, ): Set<VisitorModifier> = prevRule?.id?.qualifiedWithRuleSetId(DIKTAT_RULE_SET_ID) ?.let { previousRuleId -> val ruleId = rule.id.qualifiedWithRuleSetId(DIKTAT_RULE_SET_ID) require(ruleId != previousRuleId) { "PrevRule has same ID as rule: $ruleId" } setOf( VisitorModifier.RunAfterRule( ruleId = previousRuleId, loadOnlyWhenOtherRuleIsLoaded = false, runOnlyWhenOtherRuleIsEnabled = false ) ) } ?: emptySet() /** * @return a rule to which a logic is delegated */ internal fun Rule.unwrap(): DiktatRule = (this as? KtLintRuleWrapper)?.rule ?: error("Provided rule ${javaClass.simpleName} is not wrapped by diktat") /** * @return wraps [Rule] to [RuleProvider] */ internal fun Rule.asProvider(): RuleProvider = RuleProvider { this } } }
130
Kotlin
31
439
9fd78a6123c2564f693870086b5ff6982029ee2a
2,635
diktat
MIT License
src/main/kotlin/com/vermouthx/stocker/activities/StockerStartupActivity.kt
WhiteVermouth
281,630,639
false
null
package com.vermouthx.stocker.activities import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.startup.ProjectActivity import com.vermouthx.stocker.notifications.StockerNotification import com.vermouthx.stocker.settings.StockerSetting class StockerStartupActivity : ProjectActivity, DumbAware { private val setting = StockerSetting.instance private val pluginId = "com.vermouthx.intellij-investor-dashboard" override suspend fun execute(project: Project) { val currentVersion = PluginManagerCore.getPlugin(PluginId.getId(pluginId))?.version ?: "" if (setting.version.isEmpty()) { setting.version = currentVersion StockerNotification.notifyWelcome(project) return } if (setting.version != currentVersion) { setting.version = currentVersion StockerNotification.notifyReleaseNote(project, currentVersion) } } }
11
null
12
96
c08547ebd08d465f9d3d46555a89a30cb03e8687
1,090
intellij-investor-dashboard
Apache License 2.0
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/activity/michiae_matsuri/MichiaeMatsuriChallengePositionInfo.kt
Anime-Game-Servers
642,871,918
false
{"Kotlin": 1651536}
package org.anime_game_servers.multi_proto.gi.data.activity.michiae_matsuri import org.anime_game_servers.core.base.Version.GI_2_5_0 import org.anime_game_servers.core.base.annotations.AddedIn import org.anime_game_servers.core.base.annotations.proto.ProtoModel import org.anime_game_servers.multi_proto.gi.data.general.Vector @AddedIn(GI_2_5_0) @ProtoModel internal interface MichiaeMatsuriChallengePositionInfo { var gadgetId: Int var groupId: Int var pos: Vector }
0
Kotlin
2
6
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
482
anime-game-multi-proto
MIT License
java/src/main/java/trinsic/okapi/hashing/v1/Blake3DeriveKeyResponseKt.kt
trinsic-id
305,426,498
false
{"Dart": 573038, "Kotlin": 155130, "TypeScript": 147436, "Rust": 112106, "Python": 50752, "Java": 39903, "C#": 31124, "Go": 27567, "PowerShell": 7564, "JavaScript": 3820, "C": 3436}
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: okapi/hashing/v1/hashing.proto package trinsic.okapi.hashing.v1 @kotlin.jvm.JvmName("-initializeblake3DeriveKeyResponse") public inline fun blake3DeriveKeyResponse( block: trinsic.okapi.hashing.v1.Blake3DeriveKeyResponseKt.Dsl.() -> kotlin.Unit ): trinsic.okapi.hashing.v1.Hashing.Blake3DeriveKeyResponse = trinsic.okapi.hashing.v1.Blake3DeriveKeyResponseKt.Dsl._create( trinsic.okapi.hashing.v1.Hashing.Blake3DeriveKeyResponse.newBuilder()) .apply { block() } ._build() public object Blake3DeriveKeyResponseKt { @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @com.google.protobuf.kotlin.ProtoDslMarker public class Dsl private constructor( private val _builder: trinsic.okapi.hashing.v1.Hashing.Blake3DeriveKeyResponse.Builder ) { public companion object { @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _create( builder: trinsic.okapi.hashing.v1.Hashing.Blake3DeriveKeyResponse.Builder ): Dsl = Dsl(builder) } @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _build(): trinsic.okapi.hashing.v1.Hashing.Blake3DeriveKeyResponse = _builder.build() /** <code>bytes digest = 1;</code> */ public var digest: com.google.protobuf.ByteString @JvmName("getDigest") get() = _builder.getDigest() @JvmName("setDigest") set(value) { _builder.setDigest(value) } /** <code>bytes digest = 1;</code> */ public fun clearDigest() { _builder.clearDigest() } } } @kotlin.jvm.JvmSynthetic public inline fun trinsic.okapi.hashing.v1.Hashing.Blake3DeriveKeyResponse.copy( block: trinsic.okapi.hashing.v1.Blake3DeriveKeyResponseKt.Dsl.() -> kotlin.Unit ): trinsic.okapi.hashing.v1.Hashing.Blake3DeriveKeyResponse = trinsic.okapi.hashing.v1.Blake3DeriveKeyResponseKt.Dsl._create(this.toBuilder()) .apply { block() } ._build()
40
Dart
11
26
d4faa62a056caa08a406fd67c4b766747a2326e6
2,030
okapi
Apache License 2.0
src/main/kotlin/com/pineypiney/game_engine/objects/components/RenderedComponent.kt
PineyPiney
491,900,499
false
{"Kotlin": 541377, "GLSL": 31647}
package com.pineypiney.game_engine.objects.components import com.pineypiney.game_engine.objects.GameObject import com.pineypiney.game_engine.rendering.RendererI import com.pineypiney.game_engine.rendering.lighting.DirectionalLight import com.pineypiney.game_engine.rendering.lighting.PointLight import com.pineypiney.game_engine.rendering.lighting.SpotLight import com.pineypiney.game_engine.resources.shaders.Shader import com.pineypiney.game_engine.resources.shaders.ShaderLoader import com.pineypiney.game_engine.resources.shaders.uniforms.Uniforms import com.pineypiney.game_engine.util.ResourceKey import com.pineypiney.game_engine.util.extension_functions.filterValueIsInstance import com.pineypiney.game_engine.util.maths.shapes.Shape import glm_.vec2.Vec2 import glm_.vec3.Vec3 import kotlin.math.min abstract class RenderedComponent(parent: GameObject, s: Shader): Component("RND", parent) { var visible = true abstract val renderSize: Vec2 abstract val shape: Shape var shader: Shader = s set(value) { field = value uniforms = field.compileUniforms() } var uniforms: Uniforms = shader.compileUniforms() set(value) { field = value setUniforms() } override val fields: Array<Field<*>> = arrayOf( BooleanField("vsb", ::visible){ visible = it }, Field("vsh", ::DefaultFieldEditor, shader::vName, { shader = ShaderLoader[ResourceKey(it), ResourceKey(shader.fName)] }, { it }, { _, s -> s }), Field("fsh", ::DefaultFieldEditor, shader::fName, { shader = ShaderLoader[ResourceKey(shader.vName), ResourceKey(it)] }, { it }, { _, s -> s }) ) override fun init() { super.init() setUniforms() } open fun setUniforms(){ if(shader.hasView) uniforms.setMat4UniformR("view", RendererI<*>::view) if(shader.hasProj) uniforms.setMat4UniformR("projection", RendererI<*>::projection) if(shader.hasPort) uniforms.setVec2iUniformR("viewport", RendererI<*>::viewportSize) if(shader.hasPos) uniforms.setVec3UniformR("viewPos", RendererI<*>::viewPos) uniforms.setMat4Uniform("model", parent::worldModel) } abstract fun render(renderer: RendererI<*>, tickDelta: Double) open fun updateAspectRatio(renderer: RendererI<*>){} fun setLightUniforms(){ val lights = (parent.objects ?: return).getAllComponents().filterIsInstance<LightComponent>().filter { it.light.on } lights.firstOrNull { it.light is DirectionalLight }?.setShaderUniforms(shader, "dirLight") val pointLights = lights.associate { it.parent.position to it.light }.filterValueIsInstance<Vec3, PointLight>().entries.sortedByDescending { (it.key - parent.position).length() / it.value.linear } for(l in 0..<min(4, pointLights.size)){ val name = "pointLights[$l]" shader.setVec3("$name.position", pointLights[l].key) pointLights[l].value.setShaderUniforms(shader, name) } lights.firstOrNull { it.light is SpotLight }?.setShaderUniforms(shader, "spotlight") } companion object{ val default2DShader = ShaderLoader.getShader(ResourceKey("vertex\\2D"), ResourceKey("fragment\\texture")) val default3DShader = ShaderLoader.getShader(ResourceKey("vertex\\3D"), ResourceKey("fragment\\texture")) val colourShader = ShaderLoader[ResourceKey("vertex\\2D"), ResourceKey("fragment\\colour")] } }
0
Kotlin
0
0
f65818ca2e4426d4115fab5fdb6cef1ef31c3fc5
3,474
GameEngine
MIT License
cryptic-sequences-core/commonMain/src/net/plcarmel/crypticsequences/core/sequences/CrypticDoubleIterator.kt
plcarmel
344,168,944
false
null
package net.plcarmel.crypticsequences.core.sequences import net.plcarmel.crypticsequences.core.bits.BitQueueTwoLongs import net.plcarmel.crypticsequences.core.numbers.BaseSystem class CrypticDoubleIterator( private val baseIterator: Iterator<Long>, baseSystem: BaseSystem, wordSize: Int ): Iterator<Double> { private val nbValues = baseSystem.nbValues(wordSize) private val bitQueue = BitQueueTwoLongs() private fun replenishBitQueue() { while (bitQueue.size < 53 && baseIterator.hasNext()) { bitQueue.addRandomBitsFromNumber(baseIterator.next(), nbValues) } } override fun hasNext(): Boolean { if (bitQueue.size < 53) replenishBitQueue() return bitQueue.size >= 53 } override fun next(): Double { hasNext() return minValue * bitQueue.get(53) } companion object { const val minValue = 1.1102230246251565E-16 } }
0
Kotlin
0
0
2792e9632fef0cb22c4bacc49f209d3463ec5b19
880
cryptic-sequences
MIT License
src/main/kotlin/michi/bot/commands/misc/Math.kt
slz-br
598,900,844
false
{"Kotlin": 290077}
package michi.bot.commands.misc import com.charleskorn.kaml.YamlMap import com.charleskorn.kaml.yamlMap import kotlinx.coroutines.* import kotlinx.coroutines.Dispatchers.IO import michi.bot.commands.CommandScope.GLOBAL_SCOPE import michi.bot.commands.MichiCommand import michi.bot.util.Emoji import michi.bot.util.ReplyUtils.getText import michi.bot.util.ReplyUtils.getYML import michi.bot.util.ReplyUtils.michiReply import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent import net.dv8tion.jda.api.events.message.MessageReceivedEvent import net.dv8tion.jda.api.interactions.DiscordLocale import java.awt.Color import java.util.* @Suppress("Unused") object Math: MichiCommand("math", GLOBAL_SCOPE) { override val descriptionLocalization: Map<DiscordLocale, String> get() = mapOf( DiscordLocale.ENGLISH_US to "Gives you a basic math problem to solve", DiscordLocale.ENGLISH_UK to "Gives you a basic math problem to solve", DiscordLocale.PORTUGUESE_BRAZILIAN to "Te dá um problema de matemática básica para resolver" ) /** * Creates a math problem for the user if possible. * @param context The interaction to retrieve info from. * @author Slz * @see canHandle */ override suspend fun execute(context: SlashCommandInteractionEvent) { val sender = context.user if (!canHandle(context)) return MathProblemManager.instances += MathProblemManager(MathProblem(sender), context) } /** * Checks if the user that sent the slashCommand already has an active mathProblem to solve. * @param context The SlashCommandInteractionEvent that called the math function. * @author Slz * @see execute */ override suspend fun canHandle(context: SlashCommandInteractionEvent): Boolean { val sender = context.user val err: YamlMap = getYML(sender).yamlMap["error_messages"]!! val genericErr: YamlMap = err["generic"]!! val miscErr: YamlMap = err["misc"]!! MathProblemManager.instances.forEach { if (sender != it.problemInstance.user) return@forEach context.michiReply(String.format(miscErr.getText("user_already_has_math_problem"), Emoji.smolMichiAngry)) return false } context.guild?.let { guild -> val bot = guild.selfMember if (!bot.permissions.containsAll(botPermissions)) { context.michiReply(String.format(genericErr.getText("bot_missing_perms"), Emoji.michiSad)) return false } } return true } /** * Creates a math problem with a random operation and numbers * operations: sum(+), subtraction(-), multiplication(*) * @param sender The user that will need to solve this math problem. * @author Slz */ class MathProblem(sender: User) { val problemAsString: String val result: Int var isAnswered = false val user: User = sender init { val rng = Random() val x = rng.nextInt(100) val y = rng.nextInt(100) when (rng.nextInt(3)) { 0 -> { result = sum(x, y) problemAsString = "$x + $y" } 1 -> { result = subtract(x, y) problemAsString = "$x - $y" } else -> { result = multiply(x, y) problemAsString = "$x * $y" } } } /** * Function to get the result of a sum math problem. * @return The result of x + y * @author Slz */ private fun sum(x: Int, y: Int) = x + y /** * Function to get the result of a subtraction math problem. * @return The result of x - y * @author Slz */ private fun subtract(x: Int, y: Int) = x - y /** * Function to het the result of a multiplication math problem. * @return The result of x * y * @author Slz */ private fun multiply(x: Int, y: Int) = x * y } /** * Gives the user a math problem for the user solve. It also * counts the time that it took to the user solve the problem and cancels itself if the user takes longer than * 30 seconds to answer. * @param problem The math problem to manage. * @param event The slashCommandInteraction that called the math command. * @author Slz * @see MathProblem */ class MathProblemManager(problem: MathProblem, event: SlashCommandInteractionEvent) { private val initialTime: Long val problemInstance = problem private var timeEndedUp: Boolean = false val context = event companion object { /** * LinkedList containing all the instances of MathProblemManager. * @author Slz */ val instances = LinkedList<MathProblemManager>() } init { // making the embed val embed = EmbedBuilder() embed.setColor(Color.GREEN) .setTitle("**${problem.problemAsString}**") // sending the embed context.michiReply(embed.build()) // Counting the time initialTime = System.currentTimeMillis() CoroutineScope(IO).launch { checkDelay(problemInstance, context) } } /** * Checks if the math problem was solved after the delay. * @param problem The math problem to check. * @param context The context to reply if the problem wasn't answered in time. * @author Slz */ private suspend fun checkDelay(problem: MathProblem, context: SlashCommandInteractionEvent) { delay(35000L) if (!problemInstance.isAnswered) { context.michiReply("${problem.user.name} couldn't solve the problem in time.") if (this in instances) instances.remove(this) } } /** * Checks if the answer that the user gave matches the user's problem instance result. * @param event the message event from the user. * @param mathLogicInstance the user's math problem instance. * @author Slz */ suspend fun checkAnswer(event: MessageReceivedEvent, mathLogicInstance: MathProblemManager) { val channel = event.channel val answer = event.message.contentRaw.toInt() val user = event.author val success = getYML(user).yamlMap val successMisc: YamlMap = success["misc"]!! // guard clause if (this.problemInstance.isAnswered || this.timeEndedUp) return if (answer == this.problemInstance.result) { val finalTime = (System.currentTimeMillis() - mathLogicInstance.initialTime) / 1000 channel.sendMessage( String.format( successMisc.getText("math_correct_answer"), user.asMention, Emoji.michiYesCushion, finalTime ) ).queue() this.problemInstance.isAnswered = true } else { channel.sendMessage( String.format( successMisc.getText("math_wrong_answer"), user.asMention, Emoji.michiYesCushion, this.problemInstance.result ) ).queue() this.problemInstance.isAnswered = true } if (mathLogicInstance in instances) instances -= mathLogicInstance } } }
1
Kotlin
1
2
d2b2925993fb809d70007821b86d2c7253b9c38e
8,041
Michi
Apache License 2.0
SDKBridgeDemo/android/app/src/main/java/com/mytestapp/ReceiptCaptureActivity.kt
getsensibill
369,300,576
false
null
package com.mytestapp import android.annotation.SuppressLint import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.getsensibill.captureflow.coordinator.CaptureFlowCoordinator import com.getsensibill.captureflow.coordinator.CaptureFlowState import java.util.* /** * Used to launch the Receipt Capture Flow. * Creates a capture flow coordinator, launches it when user clicks the button. * A listener is used to track state changes, and outputs that to the layout. */ class ReceiptCaptureActivity : AppCompatActivity() { private lateinit var progressText: TextView private lateinit var launchCapture: TextView // Creates a capture flow Coordinator private val captureFlow = CaptureFlowCoordinator(this) // Capture flow listener, used to listen to the state changing private val captureFlowListener: CaptureFlowCoordinator.CaptureFlowListener = object : CaptureFlowCoordinator.CaptureFlowListener { @SuppressLint("SetTextI18n") override fun onCaptureFlowUpdate(newState: CaptureFlowState, externalAccountTransactionId: String?) { val text = when (newState) { is CaptureFlowState.IMAGES_CAPTURED -> "Images are captured" is CaptureFlowState.FLOW_CANCELLED -> "Capture flow cancelled" is CaptureFlowState.Error -> "Error occurred: ${newState.exception.message}" is CaptureFlowState.Transacting -> { val transaction = with(newState.transaction) { "status:$status\nlocalId:$localId\ntxnId:$transactionId\n" + "externalTxnId:$externalTransactionId\nreceiptId:$receiptId" } "Transacting\n$transaction\n(savedExtTxnId:$externalAccountTransactionId)" } } progressText.appendOnNewLine("${Date()}: $text") } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_receipt_capture) progressText = findViewById(R.id.progressText) launchCapture = findViewById(R.id.launchCapture) launchCapture.setOnClickListener { // launches the capture flow captureFlow.launchCaptureFlow(captureFlowListener, externalAccountTransactionId = "testTxnId1") } } /** * Helper function for appending new lines for the example */ @SuppressLint("SetTextI18n") private fun TextView.appendOnNewLine(newText: CharSequence) { runOnUiThread { text = "$text\n$newText" } } }
0
Kotlin
0
1
3d94876e6a31e1f2618207ffe78b0f7fc97b2717
2,817
sample-spend-manager-reactnative
MIT License
app/src/test/java/com/aliahmed/everylife/TasksViewModelTest.kt
aliahmedbd
552,127,211
false
{"Kotlin": 26090}
package com.aliahmed.everylife import com.aliahmed.everylife.model.Events import com.aliahmed.everylife.repository.TasksRepository import com.aliahmed.everylife.viewmodel.TasksViewModel import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.Mock class TasksViewModelTest { private lateinit var viewModel: TasksViewModel private lateinit var tasks : List<Events> private var filterList: MutableList<String> = mutableListOf("general", "medication", "hydration") private val tasksJson = "[\n" + " {\n" + " \"id\": 1,\n" + " \"name\": \"Take the rubbish out\",\n" + " \"description\": \"Empty the bin and take the rubbish and recycling to the communal rubbish bins that are on the lower ground floor of the building\",\n" + " \"type\": \"general\"\n" + " },\n" + " {\n" + " \"id\": 2,\n" + " \"name\": \"Make a hot drink\",\n" + " \"description\": \"Make David a cup of tea with full fat milk and no sugar. David likes to have his tea medium strength\",\n" + " \"type\": \"hydration\"\n" + " },\n" + " {\n" + " \"id\": 3,\n" + " \"name\": \"5 ml Azopt 10mg/1ml\",\n" + " \"description\": \"Instil one drop to both eyes at the morning. Put on by HM checked by VH. This is now only to be put in in the morning as the private carer will instil at lunch time\",\n" + " \"type\": \"medication\"\n" + " },\n" + " {\n" + " \"id\": 4,\n" + " \"name\": \"Asprin\",\n" + " \"description\": \"This is dispersible and should be dissolved in water and administered with or just after food.\",\n" + " \"type\": \"medication\"\n" + " },\n" + " {\n" + " \"id\": 5,\n" + " \"name\": \"Make a snack\",\n" + " \"description\": \"Soup, or biscuits or both. David also likes Advocate with salt on. Request from David's son not to make any other food as David is not eating it and it is then left out overnight and attracting mice.\",\n" + " \"type\": \"nutrition\"\n" + " },\n" + " {\n" + " \"id\": 6,\n" + " \"name\": \"Eyelid hygiene\",\n" + " \"description\": \"The eyelids should be washed with a cotton bud dipped into a mixture of 1 part baby shampoo and 4 parts water. Linda is going to ensure that the cotton buds and baby shampoo are available. The care worker should wipe the outside of the eyelids with the cotton bud.\",\n" + " \"type\": \"general\"\n" + " }\n" + "]" @Before fun initialize() { viewModel = TasksViewModel(null) } @Test fun tasksListFilterSizeTest() { val gson = GsonBuilder().create() val tasks = gson.fromJson<List<Events>>(tasksJson, object : TypeToken<List<Events>>(){}.type) val size = viewModel.filterData(tasks,filterList).size Assert.assertEquals(5, size) } }
0
Kotlin
0
0
cf1636bed010d959dd441a073d467674c9cd74aa
3,317
EveryLife
Apache License 2.0
src/main/kotlin/com/antwerkz/bottlerocket/configuration/blocks/Ldap.kt
evanchooly
36,263,772
false
{"Kotlin": 95442, "Java": 4726}
package com.antwerkz.bottlerocket.configuration.blocks import com.antwerkz.bottlerocket.configuration.ConfigBlock class Ldap( var servers: String? = null, var timeoutMS: Int? = null, var transportSecurity: String? = null, var userToDNMapping: String? = null, var validateLDAPServerConfig: Boolean? = null, var authz: Authz? = null, var bind: Bind? = null ) : ConfigBlock { fun authz(init: Authz.() -> Unit) { authz = initConfigBlock(Authz(), init) } fun bind(init: Bind.() -> Unit) { bind = initConfigBlock(Bind(), init) } }
4
Kotlin
1
2
c83adbbfecbac4327defa6da4ecb30fde0d60884
588
bottlerocket
Apache License 2.0