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
feature/home/src/main/java/com/hankki/feature/home/component/HankkiStateChip.kt
Team-Hankki
816,081,730
false
{"Kotlin": 587452}
package com.hankki.feature.home.component import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon 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.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.hankki.core.common.extension.bounceClick import com.hankki.core.designsystem.R import com.hankki.core.designsystem.theme.HankkiTheme import com.hankki.feature.home.model.ChipState @Composable fun HankkiStateChip( chipState: ChipState, defaultTitle: String, modifier: Modifier = Modifier, onClick: () -> Unit = {}, filterContent: @Composable ColumnScope.() -> Unit = {}, ) { Column { Box( modifier = modifier .bounceClick( scaleDown = 0.88f, onClick = onClick ) .clip(RoundedCornerShape(16.dp)) .border( width = 1.dp, color = chipState.style.borderColor, shape = RoundedCornerShape(16.dp) ) .background(color = chipState.style.containerColor) .padding(top = 4.dp, bottom = 4.dp, start = 12.dp, end = 4.dp), contentAlignment = Alignment.Center ) { Row( horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, ) { Text( text = when (chipState) { is ChipState.Selected -> defaultTitle is ChipState.Unselected -> defaultTitle is ChipState.Fixed -> chipState.title }, style = HankkiTheme.typography.caption1, color = chipState.style.labelColor ) Icon( painter = painterResource( id = when (chipState) { is ChipState.Selected -> R.drawable.ic_arrow_up is ChipState.Unselected -> R.drawable.ic_arrow_down is ChipState.Fixed -> R.drawable.ic_x } ), contentDescription = "icon", modifier = Modifier.size(24.dp), tint = chipState.style.iconColor ) } } Spacer(modifier = Modifier.height(8.dp)) filterContent() } } @Preview @Composable fun CustomChipPreview() { HankkiStateChip( ChipState.Selected(), "한식" ) }
3
Kotlin
0
43
e83ea4cf5cfd0b23d71da164090c29ba0e253b18
3,389
hankki-android
Apache License 2.0
components/analytics/shake2report/noop/src/main/java/com/flipperdevices/shake2report/noop/Shake2ReportStub.kt
flipperdevices
288,258,832
false
null
package com.flipperdevices.shake2report.noop import android.app.Application import com.flipperdevices.core.di.AppGraph import com.flipperdevices.shake2report.api.Shake2ReportApi import com.squareup.anvil.annotations.ContributesBinding import javax.inject.Inject @ContributesBinding(AppGraph::class) class Shake2ReportStub @Inject constructor() : Shake2ReportApi { override fun init(application: Application) { // Do nothing } }
1
Kotlin
27
250
fec10d206899db6d27b3addf5a7ceaa5d0990ff6
446
Flipper-Android-App
MIT License
app/src/main/java/com/example/sunnyweather/logic/network/PlaceService.kt
woshiliwai
403,922,933
false
{"Kotlin": 25204}
package com.example.sunnyweather.logic.network import com.example.sunnyweather.SunnyWeatherApplication import com.example.sunnyweather.logic.model.PlaceResponse import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query /** * Created by lw on 2021/9/7 20:16. */ interface PlaceService { @GET("v2/place?token=${SunnyWeatherApplication.TOKEN}&lang=zh_CN") fun searchPlaces(@Query("query") query: String): Call<PlaceResponse> }
0
Kotlin
0
1
e084a2af55140af687dcf3a6b7c5f270fd9db103
453
SunnyWeather
Apache License 2.0
core/src/commonMain/kotlin/com/dragselectcompose/core/DragSelectState.kt
jordond
654,306,203
false
null
package com.dragselectcompose.core import androidx.compose.foundation.lazy.grid.LazyGridState import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import com.dragselectcompose.core.DragSelectState.Companion.None /** * Creates a [DragSelectState] that is remembered across compositions. * * Changes to the provided initial values will **not** result in the state being recreated or * changed in any way if it has already been created. * * @param[Item] The type of the items in the list. * @param[lazyGridState] The [LazyGridState] that will be used to control the items in the grid. * @param[initialSelection] The initial selection of items. * @return A [DragSelectState] that can be used to control the selection. */ @Composable public fun <Item> rememberDragSelectState( lazyGridState: LazyGridState = rememberLazyGridState(), initialSelection: List<Item> = emptyList(), ): DragSelectState<Item> { val indexes by rememberSaveable { mutableStateOf(None) } return remember(lazyGridState) { DragSelectState(lazyGridState, indexes, initialSelection) } } /** * A state object that can be hoisted to control and observe selected items. * * In most cases, this will be created via [rememberDragSelectState]. * * @param[Item] The type of the items in the list. * @param[gridState] The [LazyGridState] that will be used to control the items in the grid. * @param[initialIndex] The initial index of the item that was long pressed. */ public class DragSelectState<Item>( public val gridState: LazyGridState, internal var initialIndex: Int, initialSelection: List<Item>, ) { /** * The state containing the selected items. */ private var selectedState: List<Item> by mutableStateOf(initialSelection) /** * The currently selected items. */ public val selected: List<Item> get() = selectedState /** * Whether or not the grid is in selection mode. */ public val inSelectionMode: Boolean get() = selectedState.isNotEmpty() internal val autoScrollSpeed = mutableStateOf(0f) /** * Will only invoke [block] if the initial index is not [None]. Meaning we are in selection mode. */ internal fun withInitialIndex( block: DragSelectState<Item>.(initial: Int) -> Unit, ) { if (initialIndex != None) { block(this, initialIndex) } } /** * Whether or not the provided item is selected. * * @param[item] The item to check. * @return Whether or not the item is selected. */ public fun isSelected(item: Item): Boolean = selectedState.contains(item) /** * Updates the selected items. * * @param[selected] The new selected items. */ public fun updateSelected(selected: List<Item>) { selectedState = selected } /** * Adds the provided item to the selected items. * * @param[item] The item to add. */ public fun addSelected(item: Item) { selectedState += item } /** * Removes the provided item from the selected items. * * @param[item] The item to remove. */ public fun removeSelected(photo: Item) { selectedState -= photo } /** * Clears the selected items. */ public fun clear() { selectedState = emptyList() } /** * Resets the drag state. */ internal fun resetDrag() { initialIndex = None autoScrollSpeed.value = 0f } internal companion object { internal const val None = -1 } }
2
Kotlin
0
4
c2db8bd2474c5c71c5891646724101c4bb54200b
3,879
drag-select-compose
MIT License
androidApp/src/main/java/com/jittyandiyan/androidApp/demo/features/tvshows/shows/TVShowsSearchActivity.kt
jittya
361,707,096
false
null
package com.jittyandiyan.androidApp.demo.features.tvshows.shows import android.os.Bundle import android.text.Editable import android.text.TextWatcher import androidx.recyclerview.widget.LinearLayoutManager import com.jittyandiyan.androidApp.databinding.ActivityTvshowsBinding import com.jittyandiyan.androidApp.demo.features.tvshows.shows.adapter.TVShowsAdapter import com.kmmt.core.architecture.view.KMMActivity import com.jittyandiyan.shared.demoTVMazeShowSearch.features.tvshows.TVShowsSearchPresenter import com.jittyandiyan.shared.demoTVMazeShowSearch.features.tvshows.TVShowsSearchView import com.kmmt.models.demotvshowsearch.domain.TVShowInfo import kotlin.reflect.KFunction1 class TVShowsSearchActivity : KMMActivity<TVShowsSearchPresenter, ActivityTvshowsBinding>(), TVShowsSearchView { private lateinit var adapter: TVShowsAdapter override fun initializePresenter(): TVShowsSearchPresenter { return TVShowsSearchPresenter(this) } override fun viewBindingInflate(): ActivityTvshowsBinding { return ActivityTvshowsBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) adapter = TVShowsAdapter() binding.showListRV.adapter = adapter binding.showListRV.layoutManager = LinearLayoutManager(this) } override fun showTVShowsList(tvShowList: List<TVShowInfo>) { adapter.submitList(tvShowList) } override fun setSearchQueryChangeListener(onSearchQueryStringChanged: KFunction1<String, Unit>) { binding.searchET.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(query: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(query: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun afterTextChanged(query: Editable?) { query?.let { onSearchQueryStringChanged(it.toString()) } } }) } }
0
Kotlin
10
221
2faa5eb1fdd785cc1b07f03b9c186af1a3acfc40
2,062
KMMT
MIT License
app/src/main/java/com/example/posetrackervrc/ui/camera/PoseDrawer.kt
t-34400
743,037,050
false
{"Kotlin": 69476}
package com.example.posetrackervrc.ui.camera import android.graphics.PointF import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import com.google.mlkit.vision.pose.Pose import com.google.mlkit.vision.pose.PoseLandmark private data class PoseConnection( val startIndex: Int, val endIndex: Int, val color: Color ) private val poseConnections: List<PoseConnection> = listOf( PoseConnection(PoseLandmark.NOSE, PoseLandmark.LEFT_EYE_INNER, Color.Red), PoseConnection(PoseLandmark.LEFT_EYE_INNER, PoseLandmark.LEFT_EYE, Color.Red), PoseConnection(PoseLandmark.LEFT_EYE, PoseLandmark.LEFT_EYE_OUTER, Color.Red), PoseConnection(PoseLandmark.LEFT_EYE_OUTER, PoseLandmark.LEFT_EAR, Color.Red), PoseConnection(PoseLandmark.NOSE, PoseLandmark.RIGHT_EYE_INNER, Color.Blue), PoseConnection(PoseLandmark.RIGHT_EYE_INNER, PoseLandmark.RIGHT_EYE, Color.Blue), PoseConnection(PoseLandmark.RIGHT_EYE, PoseLandmark.RIGHT_EYE_OUTER, Color.Blue), PoseConnection(PoseLandmark.RIGHT_EYE_OUTER, PoseLandmark.RIGHT_EAR, Color.Blue), PoseConnection(PoseLandmark.LEFT_MOUTH, PoseLandmark.RIGHT_MOUTH, Color.White), PoseConnection(PoseLandmark.LEFT_SHOULDER, PoseLandmark.RIGHT_SHOULDER, Color.White), PoseConnection(PoseLandmark.LEFT_HIP, PoseLandmark.RIGHT_HIP, Color.White), PoseConnection(PoseLandmark.LEFT_SHOULDER, PoseLandmark.LEFT_ELBOW, Color.Red), PoseConnection(PoseLandmark.LEFT_ELBOW, PoseLandmark.LEFT_WRIST, Color.Red), PoseConnection(PoseLandmark.LEFT_WRIST, PoseLandmark.LEFT_THUMB, Color.Red), PoseConnection(PoseLandmark.LEFT_WRIST, PoseLandmark.LEFT_INDEX, Color.Red), PoseConnection(PoseLandmark.LEFT_WRIST, PoseLandmark.LEFT_PINKY, Color.Red), PoseConnection(PoseLandmark.RIGHT_SHOULDER, PoseLandmark.RIGHT_ELBOW, Color.Blue), PoseConnection(PoseLandmark.RIGHT_ELBOW, PoseLandmark.RIGHT_WRIST, Color.Blue), PoseConnection(PoseLandmark.RIGHT_WRIST, PoseLandmark.RIGHT_THUMB, Color.Blue), PoseConnection(PoseLandmark.RIGHT_WRIST, PoseLandmark.RIGHT_INDEX, Color.Blue), PoseConnection(PoseLandmark.RIGHT_WRIST, PoseLandmark.RIGHT_PINKY, Color.Blue), PoseConnection(PoseLandmark.LEFT_SHOULDER, PoseLandmark.LEFT_HIP, Color.Red), PoseConnection(PoseLandmark.LEFT_HIP, PoseLandmark.LEFT_KNEE, Color.Red), PoseConnection(PoseLandmark.LEFT_KNEE, PoseLandmark.LEFT_ANKLE, Color.Red), PoseConnection(PoseLandmark.LEFT_ANKLE, PoseLandmark.LEFT_HEEL, Color.Red), PoseConnection(PoseLandmark.LEFT_ANKLE, PoseLandmark.LEFT_FOOT_INDEX, Color.Red), PoseConnection(PoseLandmark.RIGHT_SHOULDER, PoseLandmark.RIGHT_HIP, Color.Blue), PoseConnection(PoseLandmark.RIGHT_HIP, PoseLandmark.RIGHT_KNEE, Color.Blue), PoseConnection(PoseLandmark.RIGHT_KNEE, PoseLandmark.RIGHT_ANKLE, Color.Blue), PoseConnection(PoseLandmark.RIGHT_ANKLE, PoseLandmark.RIGHT_HEEL, Color.Blue), PoseConnection(PoseLandmark.RIGHT_ANKLE, PoseLandmark.RIGHT_FOOT_INDEX, Color.Blue), ) internal fun DrawScope.drawPoseConnections( offsets: Map<Int, Offset>, strokeWidth: Float, ) { poseConnections.forEach { poseConnection -> offsets[poseConnection.startIndex]?.let { startOffset -> offsets[poseConnection.endIndex]?.let { endOffset -> drawLine( color = poseConnection.color, start = startOffset, end = endOffset, strokeWidth = strokeWidth, cap = StrokeCap.Round ) } } } } internal fun DrawScope.drawPoseAnchors( offsets: Map<Int, Offset>, color: Color, radius: Float, strokeWidth: Float, ) { offsets.forEach { offset -> drawCircle( color = color, center = offset.value, radius = radius, style = Stroke(width = strokeWidth) ) } } internal fun Pose.convertToCanvasOffset( canvasSize: androidx.compose.ui.geometry.Size, widthRatio: Float, heightRatio: Float ): Map<Int, Offset> { return this.allPoseLandmarks.associate { poseLandmark -> poseLandmark.landmarkType to poseLandmark.position.convertToCanvasOffset(canvasSize, widthRatio, heightRatio) } } private fun PointF.convertToCanvasOffset( canvasSize: androidx.compose.ui.geometry.Size, widthRatio: Float, heightRatio: Float ): Offset { return Offset( x = canvasSize.width - this.x * widthRatio, y = this.y * heightRatio ) }
0
Kotlin
0
0
89daad8d0c9065e1954f38faf823a72b05a2fd99
4,710
PoseTrackerVRC
MIT License
Source/packages/apps/ThemePicker/src/com/android/customization/picker/quickaffordance/shared/model/KeyguardQuickAffordancePickerSlotModel.kt
stayboogy
784,959,483
false
{"XML": 12479, "Ignore List": 14, "Markdown": 7, "Text": 104, "Shell": 20, "Makefile": 32, "INI": 11, "Soong": 58, "Java": 9482, "Gradle": 8, "Java Properties": 5, "Batchfile": 3, "Proguard": 2, "Protocol Buffer": 33, "JSON": 83, "Python": 6, "Kotlin": 469, "C++": 24, "XSLT": 1, "HTML": 5, "C": 23, "AIDL": 5, "Git Attributes": 1, "Gradle Kotlin DSL": 2, "YAML": 3}
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.android.customization.picker.quickaffordance.shared.model /** Models a lock screen quick affordance slot (or position) where affordances can be displayed. */ data class KeyguardQuickAffordancePickerSlotModel( val id: String, /** Maximum number of affordances allowed to be set on this slot. */ val maxSelectedQuickAffordances: Int, )
0
Java
0
0
e6132560c5e2416db150b856bd3f331d80795c4c
983
stayboogy_AOSimPle_Pixel-5_Redfin
Apache License 2.0
04-2-One2NineAppWithRoom_kt2/app/src/main/java/com/example/one2nineappwithroom_kt2/repository/GameDatabase.kt
andreendo
30,557,910
false
{"Text": 3, "Ignore List": 134, "Markdown": 13, "Gradle": 90, "Java Properties": 77, "Shell": 38, "Batchfile": 38, "Proguard": 38, "Java": 181, "XML": 767, "Gradle Kotlin DSL": 42, "TOML": 14, "Kotlin": 179, "YAML": 14, "Dart": 42, "INI": 13, "HTML": 6, "JSON": 22, "OpenStep Property List": 24, "Objective-C": 6, "Swift": 12, "JavaScript": 1, "HTTP": 1}
package com.example.one2nineappwithroom_kt2.repository import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database( entities = [Score::class], version = 1, exportSchema = false ) abstract class GameDatabase : RoomDatabase() { abstract fun scoreDao(): ScoreDao companion object { @Volatile private var Instance: GameDatabase? = null fun getDatabase(context: Context): GameDatabase { // if the Instance is not null, return it, otherwise create a new database instance. return Instance ?: synchronized(this) { Room.databaseBuilder(context, GameDatabase::class.java, "game_database") .build() .also { Instance = it } } } } }
0
Java
0
2
7cd32456a3a6416d9a359ca2434435b20bbfaf1a
844
mobapps-course
MIT License
Project/Splash/app/src/main/java/com/med/splash/SplashActivity.kt
MuhammedErenDURSUN
155,055,527
false
null
package com.med.splash import android.annotation.SuppressLint import android.content.Intent import android.graphics.PorterDuff import android.os.* import android.support.v4.view.ViewPager import android.support.v7.app.AppCompatActivity import android.view.MotionEvent import android.view.View import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.* import android.view.View.OnFocusChangeListener class SplashActivity: AppCompatActivity() { lateinit var animZoomInFull:Animation lateinit var animZoomIn:Animation lateinit var animZoomOut:Animation lateinit var animDown:Animation lateinit var viewPager: ViewPager val FragmentAdapter = FragmentAdapter(supportFragmentManager) var currentPage:String="welcome" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) setTheme(R.style.AppTheme) viewPager = findViewById(R.id.viewPager) animZoomInFull = AnimationUtils.loadAnimation(applicationContext, R.anim.zoom_in_full); animZoomIn = AnimationUtils.loadAnimation(applicationContext, R.anim.zoom_in); animZoomOut = AnimationUtils.loadAnimation(applicationContext , R.anim.zoom_out); animDown = AnimationUtils.loadAnimation(applicationContext, R.anim.slide_down) FragmentAdapter.pageName = currentPage viewPager.adapter = FragmentAdapter } @SuppressLint("ClickableViewAccessibility") fun buttonEffect(button: Button, line: View, isLine:String="normal") { button.setOnTouchListener { v, event -> when (event.action) { MotionEvent.ACTION_DOWN -> { when (isLine){ "line" ->{ line.startAnimation(animZoomInFull) v.startAnimation(animZoomIn) } "normal" ->{ v.startAnimation(animZoomIn) } "color" ->{ v.background.setColorFilter(resources.getColor(R.color.colorPrimaryDark), PorterDuff.Mode.SRC_ATOP) button.setTextColor(resources.getColor(R.color.colorAccent)) v.invalidate() } } } MotionEvent.ACTION_UP -> { when (isLine){ "line" ->{ line.startAnimation(animZoomOut) v.startAnimation(animZoomOut) } "normal" ->{ v.startAnimation(animZoomOut) } "color" ->{ v.background.clearColorFilter() button.setTextColor(resources.getColor(R.color.colorPrimaryDark)) v.invalidate() } } } } false } } fun textEffect(editText: EditText) { editText.onFocusChangeListener = OnFocusChangeListener { view, hasFocus -> if (hasFocus) { editText.startAnimation(animZoomIn); } else { editText.startAnimation(animZoomOut); } } } fun pageSwitch() { val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } fun pageChange(pageName: String) { currentPage = pageName FragmentAdapter.pageName = pageName viewPager.adapter = FragmentAdapter } fun loadingButton(button:Button,view:View,loadingIcon:ImageView,isLoading:Boolean){ if (isLoading){ button.text="" val resizeAnimation = ResizeAnimation(button, 107) resizeAnimation.duration = 300 view.startAnimation(resizeAnimation) loadingIcon.visibility=View.VISIBLE val animLoading = AnimationUtils.loadAnimation(applicationContext, R.anim.loading) loadingIcon.startAnimation(animLoading) } else{ loadingIcon.clearAnimation() loadingIcon.visibility=View.GONE val resizeAnimation = ResizeAnimation(button, 847) resizeAnimation.duration = 300 view.startAnimation(resizeAnimation) } } fun messageShow(textView: TextView,message: String){ textView.visibility=View.VISIBLE textView.text= message textView.startAnimation(animDown) } override fun onBackPressed() { } }
3
Kotlin
0
0
6ff762112e023021f38c00feab47ba97703c9c54
4,775
Android_Splash
MIT License
src/main/kotlin/io/NumericTypeExtensions.kt
Vraiment
163,572,982
false
null
package vraiment.sage.ssr.io import java.nio.ByteBuffer import java.nio.ByteOrder // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- // // This file contains several extensions to make easier to work with numeric types // // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- // /** * Converts the array of bytes to the short they represent given they are little endian. * * @return The integer equivalent to the four bytes together. * * @throws IllegalArgumentException If the array is not of the same size of a short. */ fun ByteArray.toShort(): Short = takeIf { it.size == Short.SIZE_BYTES } ?.let { ByteBuffer.wrap(this).order(ByteOrder.LITTLE_ENDIAN).short } ?: throw IllegalArgumentException("Array is not the size of a short (${Short.SIZE_BYTES})") /** * Converts the array of bytes to the integer they represent given they are little endian. * * @return The integer equivalent to the four bytes together. * * @throws IllegalArgumentException If the array is not of the size of an integer. */ fun ByteArray.toInt(): Int = takeIf { it.size == Int.SIZE_BYTES } ?.let { ByteBuffer.wrap(this).order(ByteOrder.LITTLE_ENDIAN).int } ?: throw IllegalArgumentException("Array is not the size of an integer (${Int.SIZE_BYTES})") /** * Converts the integer to a float by interpreting the bits of the integer as a float number. * * @return The float that is represented by the bits in the integer. */ fun Int.bitsToFloat(): Float = java.lang.Float.intBitsToFloat(this)
0
Kotlin
0
1
bc1b09e963b56ffbeb607a85a8175d7d205c7e0a
1,578
SSR
MIT License
ivy-design/src/main/java/com/ivy/design/l3_ivyComponents/Card.kt
ILIYANGERMANOV
442,188,120
false
null
package com.ivy.design.l3_ivyComponents //Transaction history card
0
Kotlin
1
1
eab596d90f3580dea527d404a0f453e5b9d2167e
67
ivy-design-android
MIT License
ktor-client-metrics-micrometer/src/main/kotlin/net/codinux/web/ktor/client/metrics/MicrometerMetricsPluginConfig.kt
codinux-gmbh
784,210,650
false
{"Kotlin": 32700, "Java": 20482}
package net.codinux.web.ktor.client.metrics import io.micrometer.core.instrument.MeterRegistry class MicrometerMetricsPluginConfig : MetricsPluginConfigBase() { lateinit var meterRegistry: MeterRegistry internal fun applyConfig(): AppliedConfig { if (this::meterRegistry.isInitialized == false) { throw IllegalArgumentException("meterRegistry must be set") } return AppliedConfig(MicrometerMeterRegistry(meterRegistry), additionalTags, getUriTag, configureTags) } }
0
Kotlin
0
0
d4fb5dcf88e5e6c90d0c931794e94014a82ab02a
519
ktor-client-metrics-plugin
Apache License 2.0
notificare-push/src/main/java/re/notifica/push/NotificarePushIntentReceiver.kt
Notificare
279,260,636
false
null
package re.notifica.push import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import re.notifica.Notificare import re.notifica.NotificareLogger import re.notifica.models.NotificareNotification import re.notifica.push.models.NotificareSystemNotification import re.notifica.push.models.NotificareUnknownNotification open class NotificarePushIntentReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { when (intent.action) { NotificarePush.INTENT_ACTION_NOTIFICATION_RECEIVED -> { val notification: NotificareNotification = requireNotNull( intent.getParcelableExtra(Notificare.INTENT_EXTRA_NOTIFICATION) ) onNotificationReceived(notification) } NotificarePush.INTENT_ACTION_SYSTEM_NOTIFICATION_RECEIVED -> { val notification: NotificareSystemNotification = requireNotNull( intent.getParcelableExtra(Notificare.INTENT_EXTRA_NOTIFICATION) ) onSystemNotificationReceived(notification) } NotificarePush.INTENT_ACTION_UNKNOWN_NOTIFICATION_RECEIVED -> { val notification: NotificareUnknownNotification = requireNotNull( intent.getParcelableExtra(Notificare.INTENT_EXTRA_NOTIFICATION) ) onUnknownNotificationReceived(notification) } NotificarePush.INTENT_ACTION_NOTIFICATION_OPENED -> { val notification: NotificareNotification = requireNotNull( intent.getParcelableExtra(Notificare.INTENT_EXTRA_NOTIFICATION) ) onNotificationOpened(notification) } NotificarePush.INTENT_ACTION_ACTION_OPENED -> { val notification: NotificareNotification = requireNotNull( intent.getParcelableExtra(Notificare.INTENT_EXTRA_NOTIFICATION) ) val action: NotificareNotification.Action = requireNotNull( intent.getParcelableExtra(Notificare.INTENT_EXTRA_ACTION) ) onActionOpened(notification, action) } } } protected open fun onNotificationReceived(notification: NotificareNotification) { NotificareLogger.info("Received a notification, please override onNotificationReceived if you want to receive these intents.") } protected open fun onSystemNotificationReceived(notification: NotificareSystemNotification) { NotificareLogger.info("Received a system notification, please override onSystemNotificationReceived if you want to receive these intents.") } protected open fun onUnknownNotificationReceived(notification: NotificareUnknownNotification) { NotificareLogger.info("Received an unknown notification, please override onUnknownNotificationReceived if you want to receive these intents.") } protected open fun onNotificationOpened(notification: NotificareNotification) { NotificareLogger.debug("Opened a notification, please override onNotificationOpened if you want to receive these intents.") } protected open fun onActionOpened(notification: NotificareNotification, action: NotificareNotification.Action) { NotificareLogger.debug("Opened a notification action, please override onActionOpened if you want to receive these intents.") } }
0
Kotlin
0
0
9d89a98d10d74fb7c86674ccbf9d22550e2e98b3
3,527
notificare-sdk-android
MIT License
app/src/main/java/lab/maxb/dark/ui.theme/units/Scalable.kt
MaxBQb
408,174,279
false
null
package lab.maxb.dark.ui.theme.units import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp @Composable private fun getFieldId(id: String) = with (LocalContext.current) { resources.getIdentifier(id, "dimen", packageName) } val Int.sdp: Dp @Composable get() { val id = when (this) { in 1..600 -> "_${this}sdp" in (-60..-1) -> "_minus${this}sdp" else -> return this.dp } val resourceField = getFieldId(id) return if (resourceField != 0) dimensionResource(resourceField) else this.dp } val Int.ssp: TextUnit @Composable get() = with(LocalDensity.current) { sdp.toSp() }
0
Kotlin
0
3
15885b8ec13bc58d78c14a69e1c2f06f84ca4380
867
TheDarkApp.Client
MIT License
clients/dos/src/main/kotlin/DosService.kt
oss-review-toolkit
107,540,288
false
{"Kotlin": 5110480, "JavaScript": 333852, "Shell": 127273, "HTML": 98970, "Python": 51191, "Haskell": 30438, "FreeMarker": 27693, "CSS": 27239, "Dockerfile": 19565, "Swift": 12129, "Ruby": 10007, "Roff": 7688, "Vim Snippet": 6802, "Scala": 6656, "Starlark": 3270, "Go": 1909, "C++": 882, "Java": 559, "Rust": 280, "Emacs Lisp": 191, "C": 162}
/* * Copyright (C) 2024 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>) * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.ossreviewtoolkit.clients.dos import java.time.Duration import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Response import retrofit2.Retrofit import retrofit2.converter.kotlinx.serialization.asConverterFactory import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Path import retrofit2.http.Url /** * The service for the REST API client of the Double Open Server (DOS), see https://github.com/doubleopen-project/dos/. */ interface DosService { companion object { /** * Create a new service instance that connects to the specified DOS [url] with an authorization [token] and * uses the optionally provided [timeout] value and HTTP [client]. */ fun create(url: String, token: String, timeout: Duration? = null, client: OkHttpClient? = null): DosService { val contentType = "application/json; charset=utf-8".toMediaType() val loggingInterceptor = HttpLoggingInterceptor().apply { // For logging basic call-response statuses, use "BASIC". // For logging the request and response bodies of a call, use "BODY". level = HttpLoggingInterceptor.Level.NONE } val authorizationInterceptor = AuthorizationInterceptor(token) val okHttpClient = client ?: OkHttpClient.Builder() .apply { if (timeout != null) { callTimeout(timeout) connectTimeout(timeout) readTimeout(timeout) writeTimeout(timeout) } } .addInterceptor(loggingInterceptor) .addInterceptor(authorizationInterceptor) .build() val retrofit = Retrofit.Builder() .client(okHttpClient) .baseUrl(url) .addConverterFactory(JSON.asConverterFactory(contentType)) .build() return retrofit.create(DosService::class.java) } } /** * Get the package configuration for specified [purl][PackageConfigurationRequestBody.purl]. */ @POST("package-configuration") suspend fun getPackageConfiguration( @Body body: PackageConfigurationRequestBody ): Response<PackageConfigurationResponseBody> /** * Get the pre-signed upload URL for S3 object storage with the specified object [key][UploadUrlRequestBody.key]. */ @POST("upload-url") suspend fun getUploadUrl(@Body body: UploadUrlRequestBody): Response<UploadUrlResponseBody> /** * Put the [file] into the S3 object storage at [url]. */ @SkipAuthorization @PUT suspend fun uploadFile(@Url url: String, @Body file: RequestBody): Response<Unit> /** * Add new scanner job for specified [purls][JobRequestBody.purls]. In case multiple purls are provided, it is * assumed that they all refer to the same provenance (like a monorepo). */ @POST("job") suspend fun addScanJob(@Body body: JobRequestBody): Response<JobResponseBody> /** * Get scan results for specified [purls][ScanResultsRequestBody.purls]. In case multiple purls are provided, it is * assumed that they all refer to the same provenance (like a monorepo). */ @POST("scan-results") suspend fun getScanResults(@Body body: ScanResultsRequestBody): Response<ScanResultsResponseBody> /** * Get the state for scan job with given [id]. */ @GET("job-state/{id}") suspend fun getScanJobState(@Path("id") id: String): Response<JobStateResponseBody> }
304
Kotlin
309
1,590
ed4bccf37bab0620cc47dbfb6bfea8542164725a
4,572
ort
Apache License 2.0
lint/Intent/src/main/java/com/wada811/adx/intent/lint/UseIntentGetCharSequenceArrayExtraDetector.kt
wada811
562,910,344
false
null
package com.wada811.adx.intent.lint import com.android.tools.lint.detector.api.* import com.wada811.adx.core.lint.MethodDetector @Suppress("UnstableApiUsage") class UseIntentGetCharSequenceArrayExtraDetector : MethodDetector( issue = ISSUE, className = "android.content.Intent", applicableMethodNames = listOf("getCharSequenceArrayExtra"), replacementMethodNames = listOf("getCharSequenceArrayExtraOrNull", "getCharSequenceArrayExtraOrThrow"), imports = listOf("com.wada811.adx.intent.getCharSequenceArrayExtraOrNull", "com.wada811.adx.intent.getCharSequenceArrayExtraOrThrow") ) { companion object { val ISSUE = Issue.create( id = "UseIntentGetCharSequenceArrayExtra", briefDescription = "Use getCharSequenceArrayExtra", explanation = "Use getCharSequenceArrayExtraOrNull or getCharSequenceArrayExtraOrThrow", category = Category.PRODUCTIVITY, priority = 5, severity = Severity.WARNING, androidSpecific = true, implementation = Implementation( UseIntentGetCharSequenceArrayExtraDetector::class.java, Scope.JAVA_FILE_SCOPE, ), ) } }
0
Kotlin
0
2
5584c0ecbadbede23c519636c87ce6fa4b21faae
1,218
adx
Apache License 2.0
src/main/kotlin/no/nav/syfo/client/oppfolgingstilfelle/OppfolgingstilfelleClient.kt
navikt
602,146,320
false
{"Kotlin": 407372, "Dockerfile": 226}
package no.nav.syfo.client.oppfolgingstilfelle import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.plugins.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import net.logstash.logback.argument.StructuredArguments import no.nav.syfo.client.ClientEnvironment import no.nav.syfo.client.azuread.AzureAdClient import no.nav.syfo.client.httpClientDefault import no.nav.syfo.domain.PersonIdent import no.nav.syfo.util.* import org.slf4j.LoggerFactory import java.util.UUID class OppfolgingstilfelleClient( private val azureAdClient: AzureAdClient, private val clientEnvironment: ClientEnvironment, private val httpClient: HttpClient = httpClientDefault() ) { private val personOppfolgingstilfelleSystemUrl: String = "${clientEnvironment.baseUrl}$ISOPPFOLGINGSTILFELLE_OPPFOLGINGSTILFELLE_SYSTEM_PERSON_PATH" suspend fun getOppfolgingstilfelle( personIdent: PersonIdent, ): Oppfolgingstilfelle? { val callId = UUID.randomUUID().toString() val azureToken = azureAdClient.getSystemToken(clientEnvironment.clientId)?.accessToken ?: throw RuntimeException("Failed to get azure token") return try { val response: HttpResponse = httpClient.get(personOppfolgingstilfelleSystemUrl) { header(HttpHeaders.Authorization, bearerHeader(azureToken)) header(NAV_CALL_ID_HEADER, callId) header(NAV_PERSONIDENT_HEADER, personIdent.value) accept(ContentType.Application.Json) } response.body<OppfolgingstilfellePersonDTO>().toLatestOppfolgingstilfelle().also { COUNT_CALL_OPPFOLGINGSTILFELLE_PERSON_SUCCESS.increment() } } catch (responseException: ResponseException) { log.error( "Error while requesting OppfolgingstilfellePerson from Isoppfolgingstilfelle with {}, {}", StructuredArguments.keyValue("statusCode", responseException.response.status.value), callIdArgument(callId), ) COUNT_CALL_OPPFOLGINGSTILFELLE_PERSON_FAIL.increment() null } } companion object { private const val ISOPPFOLGINGSTILFELLE_OPPFOLGINGSTILFELLE_SYSTEM_PERSON_PATH = "/api/system/v1/oppfolgingstilfelle/personident" private val log = LoggerFactory.getLogger(OppfolgingstilfelleClient::class.java) } }
0
Kotlin
0
0
2fdd109aa5bcd8b9abf63d3ebb562a194f7970f7
2,481
isbehandlerdialog
MIT License
ExternalConnection/src/main/java/com/payz/externalconnection/data/model/Result.kt
burhanaras
327,103,273
false
null
package com.payz.externalconnection.data.model sealed class Result<out R> { data class Success<out T>(val data: T) : Result<T>() data class Error<out T>(val data: T?, val exception: Exception) : Result<T>() override fun toString(): String { return when (this) { is Success<*> -> "Success[data=$data]" is Error<*> -> "Error[Exception=$exception]" } } }
0
Kotlin
3
6
bf9e00e5e4cab7d6b81ed4b805d9b7bcf67572aa
409
SoftPos
Apache License 2.0
src/designPatterns/behavioral/StrategyWithEnum.kt
leneumann
184,633,870
false
null
package designPatterns.behavioral import javax.management.OperationsException fun main() { println(calculator(3,CalculatorWithEnum.PLUS.instance(),4)) } fun calculator(valueA: Int, operator: Calculator, valueB: Int): Int = operator.apply(valueA, valueB) enum class CalculatorWithEnum { PLUS { override fun instance() = Plus() }, TIMES { override fun instance() = Times() }, MINUS { override fun instance() = Minus() }, DIVIDE { override fun instance() = Divide() }; abstract fun instance(): Calculator } interface Calculator { fun apply(valueA: Int, valueB: Int): Int } class Plus : Calculator { override fun apply(valueA: Int, valueB: Int): Int = valueA + valueB } class Times : Calculator { override fun apply(valueA: Int, valueB: Int): Int = valueA * valueB } class Minus : Calculator { override fun apply(valueA: Int, valueB: Int): Int { if (valueA - valueB >= 0) return valueA - valueB throw OperationsException("Negative value") } } class Divide : Calculator { override fun apply(valueA: Int, valueB: Int): Int = valueA / valueB }
0
Kotlin
0
0
eea60353158a91abafb158ace325242adf03538b
1,168
HelloKotlin
MIT License
backend/src/main/java/com/paligot/confily/backend/third/parties/billetweb/BilletWebModule.kt
GerardPaligot
444,230,272
false
{"Kotlin": 897920, "Swift": 126158, "Shell": 1148, "Dockerfile": 576, "HTML": 338, "CSS": 102}
package com.paligot.confily.backend.third.parties.billetweb import com.paligot.confily.backend.events.EventModule.eventDao object BilletWebModule { val billetWebApi = lazy { BilletWebApi.Factory.create(enableNetworkLogs = true) } val billetWebRepository = lazy { BilletWebRepository(billetWebApi.value, eventDao.value) } }
9
Kotlin
6
143
8c0985b73422d6b388012d79c7ab33c054dc55c1
333
Confily
Apache License 2.0
app/src/main/java/com/kevalpatel2106/blockchain/info/dashboard/DashboardViewModel.kt
kevalpatel2106
162,750,849
false
null
package com.kevalpatel2106.blockchain.info.dashboard import androidx.annotation.VisibleForTesting import androidx.lifecycle.MutableLiveData import com.kevalpatel2106.blockchain.info.bin.Transaction import com.kevalpatel2106.blockchain.info.bin.Wallet import com.kevalpatel2106.blockchain.info.repository.BIRepository import com.kevalpatel2106.blockchain.info.utils.BaseViewModel import com.kevalpatel2106.blockchain.info.utils.SingleLiveEvent import com.kevalpatel2106.blockchain.info.utils.addTo import javax.inject.Inject class DashboardViewModel @Inject constructor( private val biRepository: BIRepository ) : BaseViewModel() { private var allTransactionsLoaded: Boolean = false internal val transactions = MutableLiveData<List<Transaction>>() internal val errorMessage = SingleLiveEvent<String>() internal val wallet = MutableLiveData<Wallet>() internal val isInitialLoading = MutableLiveData<Boolean>() init { transactions.value = arrayListOf() isInitialLoading.value = true observeWallet() // Start loading the first page loadMoreTransaction() } @VisibleForTesting internal fun observeWallet() { biRepository.observeWalletInfo() .subscribe({ wallet.value = it }, { errorMessage.value = it.message }) .addTo(compositeDisposable) } fun loadMoreTransaction() { if (allTransactionsLoaded) return val offset = transactions.value?.size ?: 0 biRepository.getTransactions( "xpub6CfLQa8fLgtouvLxrb8EtvjbXfoC1yqzH6YbTJw4dP7srt523AhcMV8Uh4K3TWSHz9oDWmn9MuJogzdGU3ncxkBsAC9wFBLmFrWT9Ek81kQ", offset ).doOnSubscribe { if (offset == 0) { isInitialLoading.value = true allTransactionsLoaded = false transactions.value = listOf() } else { transactions.value = transactions.value?.toMutableList()?.apply { add(Transaction.EMPTY_TRANSACTION) } } }.doOnSuccess { isInitialLoading.value = false }.subscribe({ (transactionsList, totalTransactions) -> transactions.value = transactions.value?.toMutableList()?.apply { removeAll { it == Transaction.EMPTY_TRANSACTION } addAll(transactionsList) } allTransactionsLoaded = totalTransactions == (transactions.value?.size ?: 0).toLong() }, { errorMessage.value = it.message }).addTo(compositeDisposable) } }
0
Kotlin
0
3
af7ccaad439599af26cdff12b9ba8b252aab772f
2,677
crypto-wallet
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppssubjectaccessrequestworker/services/GetSubjectAccessRequestDataService.kt
ministryofjustice
748,250,175
false
{"Kotlin": 38943, "Dockerfile": 1161}
package uk.gov.justice.digital.hmpps.hmppssubjectaccessrequestworker.services import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import uk.gov.justice.digital.hmpps.hmppssubjectaccessrequestworker.gateways.GenericHmppsApiGateway import java.time.LocalDate @Service class GetSubjectAccessRequestDataService(@Autowired val genericHmppsApiGateway: GenericHmppsApiGateway) { fun execute(services: String, nomisId: String? = null, ndeliusId: String? = null, dateFrom: LocalDate? = null, dateTo: LocalDate? = null): Map<String, Any> { val responseObject = mutableMapOf<String, Any>() val serviceMap = mutableMapOf<String, String>() val serviceNames = services.split(',').map { splitService -> splitService.trim() }.filterIndexed { index, _ -> index % 2 == 0 } val serviceUrls = services.split(',').map { splitService -> splitService.trim() }.filterIndexed { index, _ -> index % 2 != 0 } for (serviceName in serviceNames) { serviceMap.put(serviceName, serviceUrls[serviceNames.indexOf(serviceName)]) } serviceMap.forEach { (service, serviceUrl) -> val response: Map<*, *>? = genericHmppsApiGateway.getSarData(serviceUrl, nomisId, ndeliusId, dateFrom, dateTo) response?.get("content")?.let { responseObject[service] = it } } return responseObject } }
1
Kotlin
0
0
6cfa3e412afa473a1ac1838fa62d297c39d57782
1,362
hmpps-subject-access-request-worker
MIT License
app/src/main/java/com/sky/conversion/data/source/Filters.kt
dineshnukemars
465,553,041
false
null
package com.sky.conversion.data.source import com.sky.conversion.data.models.* import com.sky.conversion.usecase.CurrencyUseCase fun CurrencyUseCase.filterSymbols(keyword: String): SymbolsResponse { val response = symbolsResponse return if (response is SymbolsSuccess) { if (keyword.isBlank()) return SymbolsSuccess(response.list) val filter = response.list.filter { it.currencyCode.contains(keyword, ignoreCase = true) } SymbolsSuccess(filter) } else { SymbolsError(404, "no symbols found", "the response is error") } } fun CurrencyUseCase.getConvertedRates(currencyAmount: Float): RatesResponse { val response = ratesResponse return if (response is RatesSuccess) { val list = response.list.map { it.copy(amount = it.amount * currencyAmount) } return RatesSuccess(list) } else { RatesError(404, "no symbols found", "the response is error") } }
0
Kotlin
0
0
305d1594a8e88cb41114186a75d52e0f2d8599dd
993
ConvertForeignCurrency
Apache License 2.0
app/src/main/java/com/example/weather/ui/place/PlaceFragment.kt
Eugene-Forest
266,524,835
false
null
package com.example.weather.ui.place import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.widget.addTextChangedListener import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.example.weather.R import kotlinx.android.synthetic.main.fragment_place.* class PlaceFragment:Fragment() { //获取viewModel实例,为的是能从数据持有者中获取数据 private val viewModel by lazy { ViewModelProvider(this).get(PlaceViewModel::class.java) } private lateinit var adapter: PlaceAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_place,container,false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) //对recyclerview设置布局为线性布局 val layoutManager=LinearLayoutManager(activity) recyclerview.layoutManager=layoutManager //绑定recyclerview的适配器 adapter= PlaceAdapter(this,viewModel.places) recyclerview.adapter=adapter searchPlaceEdit.addTextChangedListener { text-> val content=text.toString() if (content.isNotEmpty()){ viewModel.getName(content) } else{ recyclerview.visibility=View.GONE bgImageView.visibility=View.VISIBLE viewModel.places.clear() adapter.notifyDataSetChanged() } } //对placeListData进行监视 viewModel.placeListData.observe(viewLifecycleOwner, Observer {result-> val places=result.getOrNull() if(places!=null){ recyclerview.visibility=View.VISIBLE bgImageView.visibility=View.GONE //把viewModel.placeList原有的元素清除 viewModel.places.clear() //把places中的元素全部添加到placeList中 viewModel.places.addAll(places) adapter.notifyDataSetChanged() } else{ Toast.makeText(activity,"未能查询到任何地点", Toast.LENGTH_SHORT).show() } }) } }
0
Kotlin
0
0
95cfc03c42ebb06db688fa15c23be57b76f9fff2
2,422
Weather
Apache License 2.0
src/main/kotlin/com/jetbrains/rider/aspire/sessionHost/wasmHost/WasmHostProjectSessionDebugProfile.kt
JetBrains
723,084,178
false
{"C#": 329427, "Kotlin": 327609}
package com.jetbrains.rider.aspire.sessionHost.wasmHost import com.intellij.execution.Executor import com.intellij.execution.process.ProcessListener import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.ide.browsers.StartBrowserSettings import com.jetbrains.rd.util.lifetime.Lifetime import com.jetbrains.rider.aspire.sessionHost.projectLaunchers.ProjectSessionProfile import com.jetbrains.rider.runtime.DotNetExecutable import com.jetbrains.rider.runtime.dotNetCore.DotNetCoreRuntime import java.nio.file.Path class WasmHostProjectSessionDebugProfile( private val sessionId: String, projectName: String, private val projectPath: Path, dotnetExecutable: DotNetExecutable, private val dotnetRuntime: DotNetCoreRuntime, private val browserSettings: StartBrowserSettings?, private val sessionProcessEventListener: ProcessListener, private val sessionProcessTerminatedListener: ProcessListener, private val sessionProcessLifetime: Lifetime, aspireHostProjectPath: Path? ) : ProjectSessionProfile(projectName, dotnetExecutable, aspireHostProjectPath) { override fun getState( executor: Executor, environment: ExecutionEnvironment ) = WasmHostProjectSessionDebugProfileState( sessionId, projectPath, dotnetExecutable, dotnetRuntime, environment, browserSettings, sessionProcessEventListener, sessionProcessTerminatedListener, sessionProcessLifetime ) }
9
C#
0
58
d543cfa9456897e3e65b21edc33cf9dfa2d25136
1,513
aspire-plugin
MIT License
core/src/io/github/advancerman/todd/thinker/jump/JumpToTargetThinker.kt
AdvancerMan
278,029,588
false
null
package io.github.advancerman.todd.thinker.jump import io.github.advancerman.todd.json.SerializationType import io.github.advancerman.todd.objects.creature.Creature import io.github.advancerman.todd.objects.creature.behaviour.JumpAction import io.github.advancerman.todd.screen.game.GameScreen import io.github.advancerman.todd.thinker.Thinker /** * Thinker that triggers jump every frame with cooldown if target is higher than operated object. * * ## Behaviour * * On each frame it checks if last jump was performed at least [jumpCooldown] seconds ago. * Then checks if target object is at least [highGroundThreshold] pixels higher than operated object. * Then checks if operated object is on ground. * If check succeeds operated object will perform jump. * */ @SerializationType([Thinker::class], "JumpToTargetThinker") class JumpToTargetThinker( private val jumpCooldown: Float, private val highGroundThreshold: Float, ) : Thinker { private var sinceJump = jumpCooldown override fun think(delta: Float, operatedObject: Creature, screen: GameScreen) { sinceJump += delta val myAABB = operatedObject.body.getAABB() val targetAABB = screen.player.body.getAABB() if (sinceJump >= jumpCooldown && targetAABB.y - myAABB.y > highGroundThreshold && operatedObject.isOnGround) { sinceJump = 0f operatedObject.getBehaviour<JumpAction>()?.jump(delta, operatedObject, screen) } } }
1
Kotlin
0
2
176d3618f18326b21df68b44da7438d8e9fb7410
1,472
todd-kt
MIT License
core/src/io/github/advancerman/todd/thinker/jump/JumpToTargetThinker.kt
AdvancerMan
278,029,588
false
null
package io.github.advancerman.todd.thinker.jump import io.github.advancerman.todd.json.SerializationType import io.github.advancerman.todd.objects.creature.Creature import io.github.advancerman.todd.objects.creature.behaviour.JumpAction import io.github.advancerman.todd.screen.game.GameScreen import io.github.advancerman.todd.thinker.Thinker /** * Thinker that triggers jump every frame with cooldown if target is higher than operated object. * * ## Behaviour * * On each frame it checks if last jump was performed at least [jumpCooldown] seconds ago. * Then checks if target object is at least [highGroundThreshold] pixels higher than operated object. * Then checks if operated object is on ground. * If check succeeds operated object will perform jump. * */ @SerializationType([Thinker::class], "JumpToTargetThinker") class JumpToTargetThinker( private val jumpCooldown: Float, private val highGroundThreshold: Float, ) : Thinker { private var sinceJump = jumpCooldown override fun think(delta: Float, operatedObject: Creature, screen: GameScreen) { sinceJump += delta val myAABB = operatedObject.body.getAABB() val targetAABB = screen.player.body.getAABB() if (sinceJump >= jumpCooldown && targetAABB.y - myAABB.y > highGroundThreshold && operatedObject.isOnGround) { sinceJump = 0f operatedObject.getBehaviour<JumpAction>()?.jump(delta, operatedObject, screen) } } }
1
Kotlin
0
2
176d3618f18326b21df68b44da7438d8e9fb7410
1,472
todd-kt
MIT License
src/main/java/com/sayzen/campfiresdk/screens/chat/SChats.kt
Daboo011
217,832,397
false
{"Kotlin": 1107825}
package com.sayzen.campfiresdk.screens.chat import com.dzen.campfire.api.models.notifications.NotificationChatMessage import com.dzen.campfire.api.models.units.chat.UnitChat import com.dzen.campfire.api.requests.chat.RChatsGetAll import com.sayzen.campfiresdk.R import com.sayzen.campfiresdk.controllers.ControllerApi import com.sayzen.campfiresdk.controllers.api import com.sayzen.campfiresdk.models.cards.CardChat import com.sayzen.campfiresdk.models.events.chat.EventChatSubscriptionChanged import com.sayzen.campfiresdk.models.events.chat.EventUpdateChats import com.sayzen.campfiresdk.models.events.notifications.EventNotification import com.sayzen.campfiresdk.screens.chat.create.SChatCreate import com.sup.dev.android.libs.screens.navigator.NavigationAction import com.sup.dev.android.libs.screens.navigator.Navigator import com.sup.dev.android.views.support.adapters.recycler_view.RecyclerCardAdapterLoading import com.sup.dev.android.views.screens.SLoadingRecycler import com.sup.dev.java.libs.eventBus.EventBus import com.sup.dev.java.tools.ToolsThreads class SChats constructor( var onSelected: ((UnitChat) -> Unit)? = null ) : SLoadingRecycler<CardChat, UnitChat>() { companion object { fun instance(action: NavigationAction) { Navigator.action(action, SChats()) } } private val eventBus = EventBus .subscribe(EventChatSubscriptionChanged::class) { reload() } .subscribe(EventNotification::class) { onEventNotification(it) } .subscribe(EventUpdateChats::class) { reloadOrFlag() } private var needReload = false init { setBackgroundImage(R.drawable.bg_5) setTextEmpty(R.string.chats_empty) setTextProgress(R.string.chats_loading) setTitle(R.string.app_chats) addToolbarIcon(R.drawable.ic_add_white_24dp) { Navigator.to(SChatCreate()) } } override fun instanceAdapter(): RecyclerCardAdapterLoading<CardChat, UnitChat> { return RecyclerCardAdapterLoading<CardChat, UnitChat>(CardChat::class) { unit -> val card = CardChat(unit, unit.unreadCount.toInt(), unit.subscribed) if (onSelected != null) card.onSelected = { Navigator.remove(this) onSelected!!.invoke(it) } card } .setBottomLoader { onLoad, cards -> if (ControllerApi.account.id == 0L) ToolsThreads.main(1000) { sendRequest(onLoad, cards) } else sendRequest(onLoad, cards) } } private fun sendRequest(onLoad: (Array<UnitChat>?) -> Unit, cards: ArrayList<CardChat>) { RChatsGetAll(cards.size) .onComplete { r -> onLoad.invoke(r.units) } .onNetworkError { onLoad.invoke(null) } .send(api) } override fun onResume() { super.onResume() if (needReload) { needReload = false reload() } } private fun reloadOrFlag() { if (Navigator.getCurrent() == this) reload() else needReload = true } // // EventBus // private fun onEventNotification(e: EventNotification) { if (e.notification is NotificationChatMessage) { if (adapter == null) return val cards = adapter!!.get(CardChat::class) if (cards.isNotEmpty() && cards[0].unit.tag == e.notification.tag) return reloadOrFlag() } } }
0
null
1
0
33c46da49d3758a1a006ac660dc823d35c66baea
3,555
CampfireSDK
Apache License 2.0
library-no-op/src/main/java/com/appspiriment/kashproxy/api/KashProxy.kt
appspirimentlabs
560,182,195
false
{"Kotlin": 358563}
package com.appspiriment.kashproxy.api import android.content.Context import android.content.Intent import com.chuckerteam.chucker.api.RetentionManager import com.chuckerteam.chucker.api.RetentionManager.* import com.chuckerteam.chucker.api.ChuckerInterceptor import okhttp3.Interceptor object KashProxy { /** * This method will get an instance of KashProxyInterceptor which is an OkHttp Interceptor which will enable the KashProxy mapping and Chucker * @param context An Android [Context]. * @param showNotification Whether to show the Chucker Notifications (KashProxy notifications are always enabled). default true[Boolean] , * @param retentionPeriod How long to retain the collected HTTP transactions data in Chucker. default ONE_HOUR [RetentionManager.Period] , * @param maxContentLength The max body content length in bytes, after this responses will be truncated. default ONE_HOUR [RetentionManager.Period] , * @param headersToRedact List of headers to replace with ** in the Chucker UI. [Iterable] , * @param alwaysReadResponseBody Read the whole response body even when the client does not consume the response completely. This is useful in case of parsing errors or when the response body is closed before being read like in Retrofit with Void and Unit types. [Boolean] , * @return An instance of ChuckerInterceptor which performs nothing[Interceptor]. */ public fun getInterceptor( context: Context, showNotification: Boolean = true, retentionPeriod: RetentionManager.Period = RetentionManager.Period.ONE_HOUR, maxContentLength: Long = 250000L, headersToRedact: Iterable<String> = emptyList(), alwaysReadResponseBody: Boolean = false ): Interceptor = Builder(context).build() /** * Assembles a new [KashProxyInterceptor]. * * @param context An Android [Context]. */ class Builder(context: Context) : ChuckerInterceptor.Builder(context) /** * Launches the KashProxy UI directly. * Empty method for the library-no-op artifact * @param context An Android [Context]. */ fun showMappingActivity(context: Context) { // Empty method for the library-no-op artifact } /** * Launches the Chucker UI directly. * Empty method for the library-no-op artifact * @param context An Android [Context]. */ public fun showChuckerActivity(context: Context) { // Empty method for the library-no-op artifact } /** * Get an Intent to launch the KashProxy Mapping UI directly. * @param context An Android [Context]. * @return An empty Intent for the library-no-op variant */ fun getMappingLaunchIntent(context: Context) = Intent() /** * Get an Intent to launch the Chucker UI directly. * Empty method for the library-no-op artifact * @param context An Android [Context]. * @return An empty Intent for the library-no-op variant */ fun getChuckerLaunchIntent(context: Context) = Intent() /** * Changes whether the response mapping is enabled or not. * Empty method for the library-no-op artifact * @param context An Android [Context]. * @param enabled Response mapping is enabled [Boolean] */ fun enableKashProxyMapping(context: Context, enabled: Boolean) { // Empty method for the library-no-op artifact } /** * Checks whether the response mapping is enabled or not. * @param context An Android [Context]. * @return Always return false for the library-no-op variant */ fun isKashProxyMappingEnabled(context: Context)= false /** * Dismisses all previous Chucker notifications. * Empty method for the library-no-op artifact */ @JvmStatic public fun dismissNotifications(context: Context) { // Empty method for the library-no-op artifact } }
0
Kotlin
0
12
0fef243f81a9b629d8aab589a0e29085f0c1c907
3,926
KashProxy
Apache License 2.0
src/test/kotlin/no/skatteetaten/aurora/boober/service/AuroraConfigHelper.kt
audunstrand
93,065,518
true
{"Kotlin": 97185, "Groovy": 45659, "Shell": 1985}
package no.skatteetaten.aurora.boober.service import com.fasterxml.jackson.databind.JsonNode import no.skatteetaten.aurora.boober.Configuration import no.skatteetaten.aurora.boober.model.ApplicationId import no.skatteetaten.aurora.boober.model.AuroraConfig import no.skatteetaten.aurora.boober.model.AuroraConfigFile import java.io.File class AuroraConfigHelper val folder = File(AuroraConfigHelper::class.java.getResource("/samples/config").file) @JvmOverloads fun getAuroraConfigSamples(secrets: Map<String, String> = mapOf()): AuroraConfig { val files = folder.walkBottomUp() .onEnter { it.name != "secret" } .filter { it.isFile } .associate { it.relativeTo(folder).path to it } val nodes = files.map { it.key to convertFileToJsonNode(it.value) }.toMap() return AuroraConfig(nodes.map { AuroraConfigFile(it.key, it.value!!, false) }, secrets) } @JvmOverloads fun createAuroraConfig(aid: ApplicationId, secrets: Map<String, String> = mapOf()): AuroraConfig { val files = getSampleFiles(aid) return AuroraConfig(files.map { AuroraConfigFile(it.key, it.value!!, false) }, secrets) } @JvmOverloads fun getSampleFiles(aid: ApplicationId, template: String? = null): Map<String, JsonNode?> { return collectFilesToMapOfJsonNode( "about.json", "${aid.application}.json", "${aid.environment}/about.json", "${aid.environment}/${aid.application}.json", template?.let { "templates/$it" } ?: "" ) } fun getResultFiles(aid: ApplicationId): Map<String, JsonNode?> { val baseFolder = File(AuroraConfigHelper::class.java.getResource("/samples/result/${aid.environment}/${aid.application}").file) return baseFolder.listFiles().toHashSet().map { it.nameWithoutExtension to convertFileToJsonNode(it) }.toMap() } private fun collectFilesToMapOfJsonNode(vararg fileNames: String): Map<String, JsonNode?> { return fileNames.filter { !it.isBlank() }.map { it to convertFileToJsonNode(File(folder, it)) }.toMap() } private fun convertFileToJsonNode(file: File): JsonNode? { val mapper = Configuration().mapper() return mapper.readValue(file, JsonNode::class.java) }
0
Kotlin
0
0
ec3649918ba28753bd6a207ef81b9ffe8603904a
2,229
boober
Apache License 2.0
src/main/java/io/github/redstoneparadox/paradoxconfig/config/ConfigOption.kt
RedstoneParadox
218,375,444
false
{"Kotlin": 35254}
package io.github.redstoneparadox.paradoxconfig.config import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.reflect.full.cast open class ConfigOption<T: Any>(protected val type: KClass<T>, protected var value: T, internal val key: String, val comment: String) { open operator fun getValue(thisRef : Any?, property: KProperty<*>): T { return value } open operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { this.value = value } open fun set(any: Any?) { if (type.isInstance(any)) { value = type.cast(any) } } open fun get(): Any { return value } fun getKClass(): KClass<*> { return type } }
2
Kotlin
2
9
d1560efa232d700a232e605377294131df449e36
739
ParadoxConfig
MIT License
src/main/kotlin/me/melijn/melijnbot/commands/image/GreyScaleCommand.kt
ToxicMushroom
107,187,088
false
null
package me.melijn.melijnbot.commands.image import com.sksamuel.scrimage.ImmutableImage import com.sksamuel.scrimage.filter.GrayscaleFilter import me.melijn.melijnbot.commandutil.image.ImageCommandUtil import me.melijn.melijnbot.enums.DiscordSize import me.melijn.melijnbot.internals.command.AbstractCommand import me.melijn.melijnbot.internals.command.CommandCategory import me.melijn.melijnbot.internals.command.ICommandContext import me.melijn.melijnbot.internals.utils.ImageType import me.melijn.melijnbot.internals.utils.ImageUtils import me.melijn.melijnbot.internals.utils.ParsedImageByteArray import net.dv8tion.jda.api.Permission class GreyScaleCommand : AbstractCommand("command.greyscale") { init { id = 128 name = "greyscale" aliases = arrayOf("greyScaleGif", "grayscale") discordChannelPermissions = arrayOf(Permission.MESSAGE_ATTACH_FILES) commandCategory = CommandCategory.IMAGE } override suspend fun execute(context: ICommandContext) { val acceptTypes = setOf(ImageType.PNG, ImageType.GIF) val image = ImageUtils.getImageBytesNMessage(context, 0, DiscordSize.X1024, acceptTypes) ?: return if (image.type == ImageType.GIF) { greyscaleGif(context, image) } else { greyscaleNormal(context, image) } } private val modification: (img: ImmutableImage) -> Unit = { img -> GrayscaleFilter().apply(img) } private suspend fun greyscaleNormal(context: ICommandContext, image: ParsedImageByteArray) { ImageCommandUtil.applyImmutableImgModification(context, image, modification) } private suspend fun greyscaleGif(context: ICommandContext, image: ParsedImageByteArray) { ImageCommandUtil.applyGifImmutableFrameModification(context, image, modification) } }
5
Kotlin
22
80
01107bbaad0e343d770b1e4124a5a9873b1bb5bd
1,834
Melijn
MIT License
app/src/main/java/com/photorithm/mediaplayerexample/MainActivity.kt
SebastianHelzer
162,193,677
false
null
package com.photorithm.mediaplayerexample import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Bundle import android.os.IBinder import android.support.v7.app.AppCompatActivity import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { // Made from following this guide: // https://www.sitepoint.com/a-step-by-step-guide-to-building-an-android-audio-player-app/ private var player: MediaPlayerService? = null var serviceBound = false //Binding this Client to the AudioPlayer Service private val serviceConnection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName, service: IBinder) { // We've bound to LocalService, cast the IBinder and get LocalService instance val binder = service as MediaPlayerService.LocalBinder player = binder.service serviceBound = true Toast.makeText(this@MainActivity, "Service Bound", Toast.LENGTH_SHORT).show() } override fun onServiceDisconnected(name: ComponentName) { serviceBound = false } } private fun playAudio() { //Check is service is active if (!serviceBound) { //Store Serializable audioList to SharedPreferences val playerIntent = Intent(this, MediaPlayerService::class.java) startService(playerIntent) bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE) } else { //Service is active //Send a broadcast to the service -> PLAY_NEW_AUDIO sendBroadcast(Intent(Broadcast_PLAY_NEW_AUDIO)) } } public override fun onSaveInstanceState(savedInstanceState: Bundle) { savedInstanceState.putBoolean("ServiceState", serviceBound) super.onSaveInstanceState(savedInstanceState) } public override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) serviceBound = savedInstanceState.getBoolean("ServiceState") } override fun onDestroy() { super.onDestroy() if (serviceBound) { unbindService(serviceConnection) //service is active player?.stopSelf() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) start_button.setOnClickListener { playAudio() } } companion object { const val Broadcast_PLAY_NEW_AUDIO = "com.photorithm.mediaplayerexample.PlayNewAudio" } }
0
Kotlin
0
0
1bf152e8608b7c70f643eaa641a0fc04caee277e
2,772
IP-Camera-Stream
Artistic License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/CapRounded.kt
walter-juan
868,046,028
false
{"Kotlin": 20416825}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound public val OutlineGroup.CapRounded: ImageVector get() { if (_capRounded != null) { return _capRounded!! } _capRounded = Builder(name = "CapRounded", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.0f, 6.0f) horizontalLineToRelative(-9.0f) arcToRelative(6.0f, 6.0f, 0.0f, true, false, 0.0f, 12.0f) horizontalLineToRelative(9.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.0f, 12.0f) arcToRelative(2.0f, 2.0f, 0.0f, true, true, -4.0f, 0.0f) arcToRelative(2.0f, 2.0f, 0.0f, false, true, 4.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin = strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(13.0f, 12.0f) horizontalLineToRelative(7.0f) } } .build() return _capRounded!! } private var _capRounded: ImageVector? = null
0
Kotlin
0
1
b037895588c2f62d069c724abe624b67c0889bf9
2,413
compose-icon-collections
MIT License
app/src/main/java/name/lmj0011/jetpackreleasetracker/helpers/AndroidXReleasePuller.kt
lmj0011
269,086,550
false
null
package name.lmj0011.jetpackreleasetracker.helpers import android.util.Xml import com.vdurmont.semver4j.Semver import com.vdurmont.semver4j.Semver.SemverType import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserException import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URL class AndroidXReleasePuller { private lateinit var xLibrary: AndroidXLibrary private val ns: String? = null // Given a string representation of a URL, sets up a connection and gets // an input stream. @Throws(IOException::class) private fun downloadUrl(urlString: String): InputStream? { val url = URL(urlString) return (url.openConnection() as? HttpURLConnection)?.run { readTimeout = 10000 connectTimeout = 15000 requestMethod = "GET" doInput = true // Starts the query connect() inputStream } } @Throws(XmlPullParserException::class, IOException::class) fun parse(inputStream: InputStream): MutableMap<String, Map<String,String>> { inputStream.use { inputStream -> val parser: XmlPullParser = Xml.newPullParser() parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false) parser.setInput(inputStream, null) parser.nextTag() return readFeed(parser) } } @Throws(XmlPullParserException::class, IOException::class) private fun readFeed(parser: XmlPullParser): MutableMap<String, Map<String,String>> { var allArtifactsMap = mutableMapOf<String, Map<String,String>>() //sorry. :( parser.require(XmlPullParser.START_TAG, ns, xLibrary.packageName) while (parser.next() != XmlPullParser.END_TAG) { if (parser.eventType != XmlPullParser.START_TAG) { continue } // Starts by looking for the packageName tag when (parser.name) { in xLibrary.artifactNames -> { val verMap = readArtifact(parser) allArtifactsMap.put("${xLibrary.packageName}:${parser.name}", verMap) } else -> { skip(parser) } } } return allArtifactsMap } @Throws(XmlPullParserException::class, IOException::class) private fun readArtifact(parser: XmlPullParser): Map<String, String> { parser.require(XmlPullParser.START_TAG, ns, parser.name) var versions = parser.getAttributeValue(null, "versions").split(',').toTypedArray() parser.next() return sortVersions(versions) } // skips tags we're not interested in @Throws(XmlPullParserException::class, IOException::class) private fun skip(parser: XmlPullParser) { if (parser.eventType != XmlPullParser.START_TAG) { throw IllegalStateException() } var depth = 1 while (depth != 0) { when (parser.next()) { XmlPullParser.END_TAG -> depth-- XmlPullParser.START_TAG -> depth++ } } } // returns a Map of the latest version and "Stable" version private fun sortVersions(versions: Array<String>): Map<String, String> { val stableVersions = versions.filter { Semver(it, SemverType.LOOSE).isStable }.toTypedArray() val allVersions = versions.clone() stableVersions.sortWith(Comparator { s1, s2 -> when { Semver(s1, SemverType.LOOSE).isGreaterThan(s2) -> 1 Semver(s1, SemverType.LOOSE).isEqualTo(s2) -> 0 else -> -1 } }) allVersions.sortWith(Comparator { s1, s2 -> when { Semver(s1, SemverType.LOOSE).isGreaterThan(s2) -> 1 Semver(s1, SemverType.LOOSE).isEqualTo(s2) -> 0 else -> -1 } }) var latestStableVersion = "" var latestVersion = "" stableVersions.lastOrNull()?.apply { latestStableVersion = this } allVersions.lastOrNull()?.apply { latestVersion = this } return mapOf( "latestStableVersion" to latestStableVersion, "latestVersion" to latestVersion ) } // parse the xml feed @Throws(XmlPullParserException::class, IOException::class) fun parseFeed(lib: AndroidXLibrary): MutableMap<String, Map<String,String>>? { xLibrary = lib return downloadUrl(xLibrary.groupIndexUrl)?.use { stream -> // Instantiate the parser this.parse(stream) } } }
0
Kotlin
16
85
3324eee360a3bf98f3988df31f353595e2d83e0d
4,750
jetpack-release-tracker
Apache License 2.0
composeApp/src/desktopMain/kotlin/com/atech/dict/ui/theme/theme.desktop.kt
aiyu-ayaan
853,731,717
false
{"Kotlin": 24633}
package com.atech.dict.ui.theme import com.jthemedetecor.OsThemeDetector private fun systemInDarkTheme(): Boolean { val osThemeDetector = OsThemeDetector.getDetector() return osThemeDetector.isDark } actual class isSystemInDarkTheme { actual fun isSystemInDarkTheme(): Boolean { return systemInDarkTheme() } }
0
Kotlin
0
1
09accef85a20c98e5eee3d4b128acfef08a28895
336
Dictionary-KMP
MIT License
example/src/main/java/com/spruceid/mobilesdkexample/wallet/AchievementCredentialItem.kt
spruceid
741,512,330
false
{"Kotlin": 5118229, "Makefile": 1753}
package com.spruceid.mobilesdkexample.wallet import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Text import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.spruceid.mobile.sdk.rs.decodeRevealSdJwt import com.spruceid.mobilesdkexample.R import com.spruceid.mobilesdkexample.ui.theme.Bg import com.spruceid.mobilesdkexample.ui.theme.CredentialBorder import com.spruceid.mobilesdkexample.ui.theme.GreenValid import com.spruceid.mobilesdkexample.ui.theme.Inter import com.spruceid.mobilesdkexample.ui.theme.SecondaryButtonRed import com.spruceid.mobilesdkexample.ui.theme.SpruceBlue import com.spruceid.mobilesdkexample.ui.theme.TextBody import com.spruceid.mobilesdkexample.ui.theme.TextHeader import kotlinx.coroutines.launch import org.json.JSONArray import org.json.JSONObject import java.time.OffsetDateTime import java.time.format.DateTimeFormatter class AchievementCredentialItem { private var credential: JSONObject private val onDelete: (() -> Unit)? constructor(credential: JSONObject, onDelete: (() -> Unit)? = null) { this.credential = credential this.onDelete = onDelete } constructor(rawCredential: String, onDelete: (() -> Unit)? = null) { val decodedSdJwt = decodeRevealSdJwt(rawCredential) this.credential = JSONObject(decodedSdJwt) this.onDelete = onDelete } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun listComponentTitleWithOptions() { val sheetState = rememberModalBottomSheetState() val scope = rememberCoroutineScope() var showBottomSheet by remember { mutableStateOf(false) } Column { Row( Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End ) { Image( painter = painterResource(id = R.drawable.three_dots_horizontal), contentDescription = stringResource(id = R.string.three_dots), modifier = Modifier .width(15.dp) .height(12.dp) .clickable { showBottomSheet = true } ) } listComponentTitle() } if (showBottomSheet) { ModalBottomSheet( onDismissRequest = { showBottomSheet = false }, sheetState = sheetState ) { Text( text = "Credential Options", textAlign = TextAlign.Center, fontFamily = Inter, fontWeight = FontWeight.Normal, fontSize = 12.sp, color = TextHeader, modifier = Modifier .fillMaxWidth() ) HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp)) Button( onClick = { onDelete?.invoke() }, shape = RoundedCornerShape(5.dp), colors = ButtonDefaults.buttonColors( containerColor = Color.Transparent, contentColor = SecondaryButtonRed, ), modifier = Modifier .fillMaxWidth() ) { Text( text = "Delete", fontFamily = Inter, fontWeight = FontWeight.Normal, color = SecondaryButtonRed, ) } Button( onClick = { scope.launch { sheetState.hide() }.invokeOnCompletion { if (!sheetState.isVisible) { showBottomSheet = false } } }, shape = RoundedCornerShape(5.dp), colors = ButtonDefaults.buttonColors( containerColor = Color.Transparent, contentColor = SpruceBlue, ), modifier = Modifier .fillMaxWidth() ) { Text( text = "Cancel", fontFamily = Inter, fontWeight = FontWeight.Bold, color = SpruceBlue, ) } } } } @Composable private fun listComponentTitle() { val achievementName = keyPathFinder(credential, mutableListOf("name")).toString() Text( text = achievementName, fontFamily = Inter, fontWeight = FontWeight.Medium, fontSize = 22.sp, color = TextHeader, modifier = Modifier.padding(bottom = 8.dp) ) } @Composable private fun listComponentDescription() { val issuerName = keyPathFinder(credential, mutableListOf("issuer", "name")).toString() Column { Text( text = issuerName, fontFamily = Inter, fontWeight = FontWeight.Normal, fontSize = 14.sp, color = TextBody ) Spacer(modifier = Modifier.height(16.dp)) Row(verticalAlignment = Alignment.CenterVertically) { Image( painter = painterResource(id = R.drawable.valid), contentDescription = stringResource(id = R.string.valid), modifier = Modifier.width(15.dp) ) Text( text = "Valid", fontFamily = Inter, fontWeight = FontWeight.Medium, fontSize = 10.sp, color = GreenValid ) } } } @Composable fun listComponent() { Row( Modifier.height(intrinsicSize = IntrinsicSize.Max) ) { // Leading icon Column { // Title listComponentTitle() // Description listComponentDescription() } Spacer(modifier = Modifier.weight(1.0f)) // Trailing action button } } @Composable fun listComponentWithOptions() { Row( Modifier.height(intrinsicSize = IntrinsicSize.Max) ) { // Leading icon Column { // Title listComponentTitleWithOptions() // Description listComponentDescription() } Spacer(modifier = Modifier.weight(1.0f)) // Trailing action button } } @Composable fun detailsComponent() { val awardedDate = keyPathFinder(credential, mutableListOf("awardedDate")).toString() val ISO8601DateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS]Z") val parsedDate = OffsetDateTime.parse(awardedDate, ISO8601DateFormat) val dateTimeFormatter = DateTimeFormatter.ofPattern("MMM dd, yyyy 'at' h:mm a") val identity = keyPathFinder(credential, mutableListOf("credentialSubject", "identity")) as JSONArray val details = MutableList(identity.length()) { i -> val obj = identity.get(i) as JSONObject Pair(obj["identityType"].toString(), obj["identityHash"].toString()) } details.add(0, Pair("awardedDate", parsedDate.format(dateTimeFormatter))) Row( Modifier.padding(horizontal = 12.dp) ) { Column { details.map { detail -> Text( text = splitCamelCase(detail.first), fontFamily = Inter, fontWeight = FontWeight.Normal, fontSize = 14.sp, color = TextBody, modifier = Modifier.padding(top = 10.dp) ) Text( text = detail.second, fontFamily = Inter, fontSize = 14.sp ) } } Spacer(modifier = Modifier.weight(1.0f)) } } @Composable fun borderedListComponent() { Box( Modifier .fillMaxWidth() .border( width = 1.dp, color = CredentialBorder, shape = RoundedCornerShape(8.dp) ) .padding(12.dp) ) { listComponent() } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun component() { var sheetOpen by remember { mutableStateOf(false) } Column( Modifier .padding(vertical = 10.dp) .border( width = 1.dp, color = CredentialBorder, shape = RoundedCornerShape(8.dp) ) ) { Box( Modifier .padding(all = 12.dp) .clickable { sheetOpen = true } ) { listComponentWithOptions() } } if (sheetOpen) { ModalBottomSheet( onDismissRequest = { sheetOpen = false }, modifier = Modifier .fillMaxHeight(0.8f), sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), dragHandle = null, containerColor = Bg, shape = RoundedCornerShape(8.dp) ) { Column( Modifier .padding(12.dp) ) { Text( text = "Review Info", textAlign = TextAlign.Center, fontFamily = Inter, fontWeight = FontWeight.Bold, fontSize = 24.sp, color = TextHeader, modifier = Modifier .fillMaxWidth() .padding(vertical = 20.dp), ) borderedListComponent() Column( Modifier .verticalScroll(rememberScrollState()) .weight(1f, false) ) { detailsComponent() } } } } } }
6
Kotlin
0
1
6b039d43609885792d36a10dbdbd163c982b8c9b
12,779
mobile-sdk-kt
Apache License 2.0
app/shared/bugsnag/impl/src/commonMain/kotlin/build/wallet/bugsnag/BugsnagKotlin.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.bugsnag expect fun bugsnagSetCustomValue( section: String, key: String, value: String, )
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
117
bitkey
MIT License
apps/mobile/src/main/kotlin/dev/marlonlom/cappajv/features/welcome/onboarding/OnboardingFinishedButton.kt
marlonlom
766,685,767
false
{"Kotlin": 354987}
/* * Copyright 2024 Marlonlom * SPDX-License-Identifier: Apache-2.0 */ package dev.marlonlom.cappajv.features.welcome.onboarding import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import dev.marlonlom.cappajv.R /** * Button composable ui. * * @author marlonlom * * @param onButtonClicked Action for continue to home screen button clicked. * @param modifier Modifier for this composable. */ @Composable internal fun OnboardingFinishedButton( onButtonClicked: () -> Unit, modifier: Modifier = Modifier ) { Button( modifier = modifier.testTag("onboarding_finish_btn"), onClick = { onButtonClicked() }, shape = MaterialTheme.shapes.small, colors = ButtonDefaults.buttonColors( containerColor = MaterialTheme.colorScheme.primary, contentColor = MaterialTheme.colorScheme.onPrimary, ) ) { Text( text = stringResource(R.string.text_onboarding_button), style = MaterialTheme.typography.bodyLarge, ) } }
0
Kotlin
0
0
8f86b3156427753b1925d2de0f1d93933e033103
1,275
cappajv
Apache License 2.0
app/src/main/java/pl/skipcode/basekotlinapp/utils/tools/parcel/ParcelableProvider.kt
Michax94
152,717,481
false
null
package pl.skipcode.basekotlinapp.utils.tools.parcel import android.os.Parcelable import org.parceler.Parcels class ParcelableProvider : ParcelableProviderInterface { override fun from(from: Any): Parcelable = Parcels.wrap(from) }
1
Kotlin
0
0
ca757e617063825e3ce3939d0cb96c3c854458a1
249
BaseKotlinApp
Apache License 2.0
OneSignalSDK/onesignal/in-app-messages/src/main/java/com/onesignal/inAppMessages/internal/triggers/TriggerModel.kt
OneSignal
33,515,679
false
{"Kotlin": 1777584, "Java": 49349, "Shell": 748}
package com.onesignal.inAppMessages.internal.triggers import com.onesignal.common.modeling.Model class TriggerModel : Model() { /** * The key of this trigger */ var key: String get() = getStringProperty(::key.name) { "" } set(value) { setStringProperty(::key.name, value) } /** * The value of this trigger */ var value: Any get() = getAnyProperty(::value.name) { "" } set(value) { setAnyProperty(::value.name, value, forceChange = true) } }
65
Kotlin
367
604
b03d5f5395f141ef3fed817d5d4d118b768e7294
552
OneSignal-Android-SDK
Apache License 2.0
src/main/kotlin/com/adverity/etl/controller/IndexController.kt
liodegar
415,680,713
false
null
package com.adverity.etl.controller import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.RequestMapping import springfox.documentation.annotations.ApiIgnore @Controller @ApiIgnore class IndexController { @RequestMapping("/") fun index(): String? { return "redirect:swagger-ui.html" } }
0
Kotlin
0
0
ddc4925236e71b2923125851056af10f3fd7f86b
351
etl-rest-api
Apache License 1.1
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/batch/v1/status.kt
fkorotkov
84,911,320
false
null
// GENERATED package com.fkorotkov.kubernetes.batch.v1 import io.fabric8.kubernetes.api.model.batch.v1.CronJob as v1_CronJob import io.fabric8.kubernetes.api.model.batch.v1.CronJobStatus as v1_CronJobStatus import io.fabric8.kubernetes.api.model.batch.v1.Job as v1_Job import io.fabric8.kubernetes.api.model.batch.v1.JobStatus as v1_JobStatus fun v1_CronJob.`status`(block: v1_CronJobStatus.() -> Unit = {}) { if(this.`status` == null) { this.`status` = v1_CronJobStatus() } this.`status`.block() } fun v1_Job.`status`(block: v1_JobStatus.() -> Unit = {}) { if(this.`status` == null) { this.`status` = v1_JobStatus() } this.`status`.block() }
6
Kotlin
19
317
ef8297132e6134b6f65ace3e50869dbb2b686b21
673
k8s-kotlin-dsl
MIT License
src/main/kotlin/polyglotter/MassTranslator.kt
slu-it
869,170,828
false
{"Kotlin": 5959}
package polyglotter import org.springframework.stereotype.Component import java.util.Locale import java.util.concurrent.CompletableFuture.supplyAsync import java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor @Component class MassTranslator( private val translator: Translator ) { private val executor = newVirtualThreadPerTaskExecutor() fun translate(sourceLanguage: Locale, targetLanguages: Set<Locale>, text: String): Map<Locale, String> { val original = mapOf(sourceLanguage to text) val translations = targetLanguages.sortedBy { it.language } .map { language -> language to asyncTranslate(sourceLanguage, language, text) } .associate { (language, supplier) -> language to supplier.get() } return original + translations } private fun asyncTranslate(sourceLanguage: Locale, language: Locale, text: String) = supplyAsync({ translator.translate(sourceLanguage, language, text) }, executor) }
0
Kotlin
0
0
e4f215436660af56708d43e26eee545aeb256f33
988
polyglotter
Apache License 2.0
app/src/main/java/com/zenika/story/tutorial/presentation/inventory/TutorialInventoryViewModel.kt
Zenika
628,692,757
false
{"Kotlin": 394194, "Shell": 305}
package com.zenika.story.tutorial.presentation.inventory import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.zenika.common.domain.Inventory import com.zenika.common.domain.ObserveInventoryUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class TutorialInventoryViewModel @Inject constructor( observeInventory: ObserveInventoryUseCase ) : ViewModel() { val inventory: StateFlow<Inventory> = observeInventory() .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(stopTimeoutMillis = 5_000), initialValue = Inventory.start() ) }
1
Kotlin
0
2
3e81f9e98c283fb243bb5c06e620c637ac61a6ef
824
ZEscape-Android
Apache License 2.0
androidApp/src/main/java/ap/panini/procrastaint/ui/MainActivityScreenModel.kt
Pahina0
808,750,600
false
{"Kotlin": 61443, "Swift": 31023}
package ap.panini.procrastaint.ui import androidx.compose.runtime.Immutable import ap.panini.procrastaint.data.model.Time import ap.panini.procrastaint.util.Parsed import ap.panini.procrastaint.util.Parser import cafe.adriel.voyager.core.model.StateScreenModel import kotlinx.coroutines.flow.update class MainActivityScreenModel : StateScreenModel<MainActivityScreenModel.State>(State()) { private var parser = Parser() @Immutable data class State( val task: String = "", val description: String = "", val manualStartTimes: Set<Long> = emptySet(), val endTime: Long? = null, val repeatInterval: Int? = null, val repeatTag: Time? = null, val viewing: Int = -1, val autoParsed: List<Parsed> = emptyList(), ) fun save() { TODO("Import into DB") } fun setRepeatTag(tag: Time?) { mutableState.update { it.copy( repeatTag = tag ) } } fun setRepeatInterval(interval: Int?) { mutableState.update { it.copy( repeatInterval = interval ) } } fun updateTask(title: String) { if (title.isBlank()) { parser = Parser() // resets the time to now } val parsed = parser.parse(title) mutableState.update { it.copy( task = title, autoParsed = parsed, viewing = if (parsed.isEmpty()) -1 else 0 ) } } fun editManualStartTime(time: Long) { mutableState.update { it.copy( manualStartTimes = if (state.value.manualStartTimes.contains(time)) { it.manualStartTimes - time } else { it.manualStartTimes + time } ) } } fun editEndTime(time: Long?) { mutableState.update { it.copy( endTime = time ) } } fun viewNextParsed() { if (state.value.viewing == -1) return mutableState.update { it.copy( viewing = (it.viewing + 1) % (it.autoParsed.size + 1) ) } } fun updateDescription(description: String) { mutableState.update { it.copy( description = description ) } } }
0
Kotlin
0
3
6b6209ef09751e3abd6c1c0ad31199e0a3ead85f
2,438
Procrastaint
Apache License 2.0
mealkitary-infrastructure/adapter-persistence-spring-data-jpa/src/main/kotlin/com/mealkitary/demo/adapter/out/persistence/UserPersistenceAdapter.kt
le2sky
640,586,872
false
null
package com.mealkitary.demo.adapter.out.persistence import com.mealkitary.demo.application.port.out.LoadUserPort import com.mealkitary.demo.domain.User import org.springframework.stereotype.Repository @Repository internal class UserPersistenceAdapter( private val userRepository: UserRepository ) : LoadUserPort { override fun loadUserById(userId: Long): User { val user = userRepository.findById(userId) if (user.isPresent) return user.get() val newUser = User(name = "leesky") userRepository.save(newUser) return newUser } }
0
Kotlin
0
0
c1f440b2abba433d6949752d9c0552e78ae49c02
582
mealkitary-server
Apache License 2.0
features/src/main/kotlin/ru/mobileup/template/features/pokemons/presentation/PokemonsComponent.kt
MobileUpLLC
485,284,340
false
{"Kotlin": 148289, "FreeMarker": 3830, "Shell": 3159}
package ru.mobileup.template.features.pokemons.presentation import com.arkivanov.decompose.router.stack.ChildStack import kotlinx.coroutines.flow.StateFlow import ru.mobileup.template.features.pokemons.presentation.details.PokemonDetailsComponent import ru.mobileup.template.features.pokemons.presentation.list.PokemonListComponent interface PokemonsComponent { val childStack: StateFlow<ChildStack<*, Child>> sealed interface Child { class List(val component: PokemonListComponent) : Child class Details(val component: PokemonDetailsComponent) : Child } }
1
Kotlin
2
22
d9a350ac4b25496221d146fbb9a838afc07db422
589
MobileUp-Android-Template
MIT License
libraries/loader/src/LoaderListener.kt
featurea
407,517,337
false
null
package featurea.loader interface LoaderListener { fun start() {} fun update(progress: Float) {} fun complete() {} }
24
Kotlin
1
6
07074dc37a838f16ece90c19a4e8d45e743013d3
130
engine
MIT License
app/src/main/java/com/vadmax/timetosleep/utils/previewprovider/AppInfoListPreviewProvider.kt
VadimZhuk0v
403,318,456
false
{"Kotlin": 214064, "Ruby": 928}
package com.vadmax.timetosleep.utils.previewprovider import androidx.compose.ui.tooling.preview.PreviewParameterProvider import com.vadmax.core.data.AppInfo class AppInfoListPreviewProvider : PreviewParameterProvider<List<AppInfo>> { override val values: Sequence<List<AppInfo>> get() = sequenceOf( listOf( AppInfo( packageName = "com.sample.name", name = "name", ), ), ) }
0
Kotlin
1
1
927e28d6b0dc422cb0d4a70be067566be13f40bb
493
TimeToSleep
MIT License
src/main/kotlin/io/github/clivelewis/assistant/telegram/commands/GenerateImageCommand.kt
clivelewis
781,393,282
false
{"Kotlin": 49773}
package io.github.clivelewis.assistant.telegram.commands import eu.vendeli.tgbot.TelegramBot import eu.vendeli.tgbot.annotations.CommandHandler import eu.vendeli.tgbot.annotations.InputHandler import eu.vendeli.tgbot.api.media.sendPhoto import eu.vendeli.tgbot.api.message.deleteMessage import eu.vendeli.tgbot.api.message.editMessageText import eu.vendeli.tgbot.api.message.message import eu.vendeli.tgbot.types.User import eu.vendeli.tgbot.types.internal.ProcessedUpdate import eu.vendeli.tgbot.types.internal.onFailure import io.github.clivelewis.assistant.image.ImageGenerationFactory import io.github.clivelewis.assistant.image.ImageGenerationProvider.* import io.github.clivelewis.assistant.logging.error import io.github.clivelewis.assistant.telegram.settings.UserSettingsService import io.github.oshai.kotlinlogging.KotlinLogging import org.springframework.stereotype.Component @Component class GenerateImageCommand( private val imageFactory: ImageGenerationFactory, private val settingsService: UserSettingsService) { private val log = KotlinLogging.logger {} @CommandHandler(["/image", "/generate"]) suspend fun askGenerateImagePrompt(user: User, bot: TelegramBot) { message { "What image do you want me to generate? \uD83D\uDC40" }.send(user, bot) bot.inputListener.set(user) { "generate-image" } } @InputHandler(["generate-image"]) suspend fun generateImage(user: User, bot: TelegramBot, update: ProcessedUpdate) { val messageId = message { "⌛ Generating..." }.sendAsync(user, bot).onFailure { log.error(user) { "Failed to send message: ${it.description}" } }?.messageId if (messageId == null) { log.error(user) { "Failed to send message" } return } try { val userSettings = settingsService.getUserSettings(user.id, bot.userData) imageFactory.getProvider(OPEN_AI).generateImage(update.text, userSettings.imageModel).apply { deleteMessage(messageId).send(user, bot) sendPhoto { this }.send(user, bot) } } catch (e: Exception) { editMessageText(messageId) { "❌ Failed to generate image. Please try again." }.send(user, bot) log.error(user, e) { "Failed to generate image! ${e.message}" } } } }
0
Kotlin
0
0
01cceb6539b4e0ff55698f26f034f52c9fda61f0
2,348
sam
Apache License 2.0
src/main/kotlin/com/antwerkz/bottlerocket/configuration/blocks/Authz.kt
evanchooly
36,263,772
false
null
package com.antwerkz.bottlerocket.configuration.blocks import com.antwerkz.bottlerocket.configuration.ConfigBlock class Authz( var queryTemplate: String? = null ) : ConfigBlock
0
Kotlin
1
2
53771868a7ddd93619655562231782a11f0eb94a
183
bottlerocket
Apache License 2.0
data/database/src/main/java/io/filmtime/data/database/dao/BookmarksDao.kt
moallemi
633,160,161
false
{"Kotlin": 522936, "Shell": 3102}
package io.filmtime.data.database.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import io.filmtime.data.database.entity.BookmarkEntity import io.filmtime.data.model.VideoType import kotlinx.coroutines.flow.Flow @Dao interface BookmarksDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun addBookmark(bookmarkEntity: BookmarkEntity) @Delete suspend fun removeBookmark(bookmarkEntity: BookmarkEntity) @Query("SELECT EXISTS(SELECT 1 FROM bookmarks WHERE tmdb_id = :tmdbId AND video_type = :type)") fun isBookmarked(tmdbId: Int, type: VideoType): Flow<Boolean> @Query("SELECT * FROM bookmarks") fun getAllBookmarks(): Flow<List<BookmarkEntity>> @Query("SELECT * FROM bookmarks WHERE video_type = :type") fun getAllBookmarksByType(type: VideoType): Flow<List<BookmarkEntity>> }
21
Kotlin
14
87
ad3eeed30bed20216a9fa12e34f06e43b70a74cc
920
Film-Time
MIT License
app/src/main/java/com/rektapps/assaulttimer/dagger/module/FactoryModule.kt
N3-M3-S1S
199,498,741
false
null
package com.rektapps.assaulttimer.dagger.module import com.rektapps.assaulttimer.model.enums.AssaultType import com.rektapps.assaulttimer.model.factory.AssaultIntervalsFactory import com.rektapps.assaulttimer.model.factory.AssaultsFactory import com.rektapps.assaulttimer.model.factory.impl.AssaultIntervalsFactoryImpl import com.rektapps.assaulttimer.model.factory.impl.AssaultsFactoryImpl import com.rektapps.assaulttimer.storage.dao.AssaultDao import dagger.Module import dagger.Provides import org.joda.time.Duration @Module object FactoryModule { @Provides @JvmStatic fun providesAssaultsFactory(assaultsDao: AssaultDao): AssaultsFactory = AssaultsFactoryImpl(assaultsDao, createIntervalFactories()) private fun createIntervalFactories(): Map<AssaultType, AssaultIntervalsFactory> { val bfaAssaultDuration = Duration.standardHours(7) val bfaBreakBetweenAssaults = Duration.standardHours(12) val legionAssaultDuration = Duration.standardHours(6) val legionBreakBetweenAssaults = Duration.standardHours(12).plus(Duration.standardMinutes(30)) val factories = mutableMapOf<AssaultType, AssaultIntervalsFactory>() factories[AssaultType.BFA] = AssaultIntervalsFactoryImpl( bfaAssaultDuration, bfaBreakBetweenAssaults ) factories[AssaultType.LEGION] = AssaultIntervalsFactoryImpl( legionAssaultDuration, legionBreakBetweenAssaults ) return factories } }
0
Kotlin
0
0
0a01605890842182d00963cad4e3165e2da81b45
1,514
assault_timer
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/prisonerfromnomismigration/contactperson/ContactPersonSynchronisationIntTest.kt
ministryofjustice
452,734,022
false
{"Kotlin": 2957292, "Shell": 2955, "Mustache": 1803, "Dockerfile": 1377}
package uk.gov.justice.digital.hmpps.prisonerfromnomismigration.contactperson import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.mockito.Mockito.eq import org.mockito.kotlin.check import org.mockito.kotlin.isNull import org.mockito.kotlin.verify import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.integration.SqsIntegrationTestBase import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.integration.sendMessage class ContactPersonSynchronisationIntTest : SqsIntegrationTestBase() { @Nested @DisplayName("PERSON-INSERTED") inner class PersonAdded { private val personId = 123456L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personEvent( eventType = "PERSON-INSERTED", personId = personId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-synchronisation-created-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) }, isNull(), ) } } @Nested @DisplayName("PERSON-UPDATED") inner class PersonUpdated { private val personId = 123456L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personEvent( eventType = "PERSON-UPDATED", personId = personId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-synchronisation-updated-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) }, isNull(), ) } } @Nested @DisplayName("PERSON-DELETED") inner class PersonDeleted { private val personId = 123456L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personEvent( eventType = "PERSON-DELETED", personId = personId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-synchronisation-deleted-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) }, isNull(), ) } } @Nested @DisplayName("ADDRESSES_PERSON-INSERTED") inner class PersonAddressAdded { private val personId = 123456L private val addressId = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personAddressEvent( eventType = "ADDRESSES_PERSON-INSERTED", personId = personId, addressId = addressId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-address-synchronisation-created-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["addressId"]).isEqualTo(addressId.toString()) }, isNull(), ) } } @Nested @DisplayName("ADDRESSES_PERSON-UPDATED") inner class PersonAddressUpdated { private val personId = 123456L private val addressId = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personAddressEvent( eventType = "ADDRESSES_PERSON-UPDATED", personId = personId, addressId = addressId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-address-synchronisation-updated-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["addressId"]).isEqualTo(addressId.toString()) }, isNull(), ) } } @Nested @DisplayName("ADDRESSES_PERSON-DELETED") inner class PersonAddressDeleted { private val personId = 123456L private val addressId = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personAddressEvent( eventType = "ADDRESSES_PERSON-DELETED", personId = personId, addressId = addressId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-address-synchronisation-deleted-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["addressId"]).isEqualTo(addressId.toString()) }, isNull(), ) } } @Nested @DisplayName("PHONES_PERSON-INSERTED") inner class PersonPhoneAdded { private val personId = 123456L private val phoneId = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personPhoneEvent( eventType = "PHONES_PERSON-INSERTED", personId = personId, phoneId = phoneId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-phone-synchronisation-created-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["phoneId"]).isEqualTo(phoneId.toString()) }, isNull(), ) } } @Nested @DisplayName("PHONES_PERSON-UPDATED") inner class PersonPhoneUpdated { private val personId = 123456L private val phoneId = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personPhoneEvent( eventType = "PHONES_PERSON-UPDATED", personId = personId, phoneId = phoneId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-phone-synchronisation-updated-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["phoneId"]).isEqualTo(phoneId.toString()) }, isNull(), ) } } @Nested @DisplayName("PHONES_PERSON-DELETED") inner class PersonPhoneDeleted { private val personId = 123456L private val phoneId = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personPhoneEvent( eventType = "PHONES_PERSON-DELETED", personId = personId, phoneId = phoneId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-phone-synchronisation-deleted-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["phoneId"]).isEqualTo(phoneId.toString()) }, isNull(), ) } } @Nested @DisplayName("PHONES_PERSON-INSERTED - address") inner class PersonAddressPhoneAdded { private val personId = 123456L private val phoneId = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personPhoneEvent( eventType = "PHONES_PERSON-INSERTED", personId = personId, phoneId = phoneId, isAddress = true, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-address-phone-synchronisation-created-todo"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["phoneId"]).isEqualTo(phoneId.toString()) }, isNull(), ) } } @Nested @DisplayName("PHONES_PERSON-UPDATED - address") inner class PersonAddressPhoneUpdated { private val personId = 123456L private val phoneId = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personPhoneEvent( eventType = "PHONES_PERSON-UPDATED", personId = personId, phoneId = phoneId, isAddress = true, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-address-phone-synchronisation-updated-todo"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["phoneId"]).isEqualTo(phoneId.toString()) }, isNull(), ) } } @Nested @DisplayName("PHONES_PERSON-DELETED - address") inner class PersonAddressPhoneDeleted { private val personId = 123456L private val phoneId = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personPhoneEvent( eventType = "PHONES_PERSON-DELETED", personId = personId, phoneId = phoneId, isAddress = true, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-address-phone-synchronisation-deleted-todo"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["phoneId"]).isEqualTo(phoneId.toString()) }, isNull(), ) } } @Nested @DisplayName("INTERNET_ADDRESSES_PERSON-INSERTED") inner class PersonEmailAdded { private val personId = 123456L private val internetAddressId = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personInternetAddressEvent( eventType = "INTERNET_ADDRESSES_PERSON-INSERTED", personId = personId, internetAddressId = internetAddressId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-email-synchronisation-created-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["internetAddressId"]).isEqualTo(internetAddressId.toString()) }, isNull(), ) } } @Nested @DisplayName("INTERNET_ADDRESSES_PERSON-UPDATED") inner class PersonEmailUpdated { private val personId = 123456L private val internetAddressId = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personInternetAddressEvent( eventType = "INTERNET_ADDRESSES_PERSON-UPDATED", personId = personId, internetAddressId = internetAddressId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-email-synchronisation-updated-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["internetAddressId"]).isEqualTo(internetAddressId.toString()) }, isNull(), ) } } @Nested @DisplayName("INTERNET_ADDRESSES_PERSON-DELETED") inner class PersonEmailDeleted { private val personId = 123456L private val internetAddressId = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personInternetAddressEvent( eventType = "INTERNET_ADDRESSES_PERSON-DELETED", personId = personId, internetAddressId = internetAddressId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-email-synchronisation-deleted-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["internetAddressId"]).isEqualTo(internetAddressId.toString()) }, isNull(), ) } } @Nested @DisplayName("PERSON_EMPLOYMENTS-INSERTED") inner class PersonEmploymentAdded { private val personId = 123456L private val employmentSequence = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personEmploymentEvent( eventType = "PERSON_EMPLOYMENTS-INSERTED", personId = personId, employmentSequence = employmentSequence, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-employment-synchronisation-created-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["employmentSequence"]).isEqualTo(employmentSequence.toString()) }, isNull(), ) } } @Nested @DisplayName("PERSON_EMPLOYMENTS-UPDATED") inner class PersonEmploymentUpdated { private val personId = 123456L private val employmentSequence = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personEmploymentEvent( eventType = "PERSON_EMPLOYMENTS-UPDATED", personId = personId, employmentSequence = employmentSequence, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-employment-synchronisation-updated-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["employmentSequence"]).isEqualTo(employmentSequence.toString()) }, isNull(), ) } } @Nested @DisplayName("PERSON_EMPLOYMENTS-DELETED") inner class PersonEmploymentDeleted { private val personId = 123456L private val employmentSequence = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personEmploymentEvent( eventType = "PERSON_EMPLOYMENTS-DELETED", personId = personId, employmentSequence = employmentSequence, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-employment-synchronisation-deleted-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["employmentSequence"]).isEqualTo(employmentSequence.toString()) }, isNull(), ) } } @Nested @DisplayName("PERSON_IDENTIFIERS-INSERTED") inner class PersonIdentifierAdded { private val personId = 123456L private val identifierSequence = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personIdentifierEvent( eventType = "PERSON_IDENTIFIERS-INSERTED", personId = personId, identifierSequence = identifierSequence, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-identifier-synchronisation-created-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["identifierSequence"]).isEqualTo(identifierSequence.toString()) }, isNull(), ) } } @Nested @DisplayName("PERSON_IDENTIFIERS-UPDATED") inner class PersonIdentifierUpdated { private val personId = 123456L private val identifierSequence = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personIdentifierEvent( eventType = "PERSON_IDENTIFIERS-UPDATED", personId = personId, identifierSequence = identifierSequence, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-identifier-synchronisation-updated-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["identifierSequence"]).isEqualTo(identifierSequence.toString()) }, isNull(), ) } } @Nested @DisplayName("PERSON_IDENTIFIERS-DELETED") inner class PersonIdentifierDeleted { private val personId = 123456L private val identifierSequence = 76543L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personIdentifierEvent( eventType = "PERSON_IDENTIFIERS-DELETED", personId = personId, identifierSequence = identifierSequence, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-identifier-synchronisation-deleted-success"), check { assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["identifierSequence"]).isEqualTo(identifierSequence.toString()) }, isNull(), ) } } @Nested @DisplayName("VISITOR_RESTRICTION-UPSERTED") inner class PersonRestrictionUpserted { private val restrictionId = 9876L private val personId = 123456L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personRestrictionEvent( eventType = "VISITOR_RESTRICTION-UPSERTED", personId = personId, restrictionId = restrictionId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-restriction-synchronisation-created-success"), check { assertThat(it["personRestrictionId"]).isEqualTo(restrictionId.toString()) assertThat(it["personId"]).isEqualTo(personId.toString()) }, isNull(), ) } } @Nested @DisplayName("VISITOR_RESTRICTION-DELETED") inner class PersonRestrictionDeleted { private val restrictionId = 9876L private val personId = 123456L @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, personRestrictionEvent( eventType = "VISITOR_RESTRICTION-DELETED", personId = personId, restrictionId = restrictionId, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-person-restriction-synchronisation-deleted-success"), check { assertThat(it["personRestrictionId"]).isEqualTo(restrictionId.toString()) assertThat(it["personId"]).isEqualTo(personId.toString()) }, isNull(), ) } } @Nested @DisplayName("OFFENDER_CONTACT-INSERTED") inner class ContactAdded { private val contactId = 3456L private val personId = 123456L private val bookingId = 890L private val offenderNo = "A1234KT" @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, contactEvent( eventType = "OFFENDER_CONTACT-INSERTED", personId = personId, contactId = contactId, bookingId = bookingId, offenderNo = offenderNo, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-contact-synchronisation-created-success"), check { assertThat(it["offenderNo"]).isEqualTo(offenderNo) assertThat(it["bookingId"]).isEqualTo(bookingId.toString()) assertThat(it["contactId"]).isEqualTo(contactId.toString()) assertThat(it["personId"]).isEqualTo(personId.toString()) }, isNull(), ) } } @Nested @DisplayName("OFFENDER_CONTACT-UPDATED") inner class ContactUpdated { private val contactId = 3456L private val personId = 123456L private val bookingId = 890L private val offenderNo = "A1234KT" @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, contactEvent( eventType = "OFFENDER_CONTACT-UPDATED", personId = personId, contactId = contactId, bookingId = bookingId, offenderNo = offenderNo, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-contact-synchronisation-updated-success"), check { assertThat(it["offenderNo"]).isEqualTo(offenderNo) assertThat(it["bookingId"]).isEqualTo(bookingId.toString()) assertThat(it["contactId"]).isEqualTo(contactId.toString()) assertThat(it["personId"]).isEqualTo(personId.toString()) }, isNull(), ) } } @Nested @DisplayName("OFFENDER_CONTACT-DELETED") inner class ContactDeleted { private val contactId = 3456L private val personId = 123456L private val bookingId = 890L private val offenderNo = "A1234KT" @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, contactEvent( eventType = "OFFENDER_CONTACT-DELETED", personId = personId, contactId = contactId, bookingId = bookingId, offenderNo = offenderNo, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-contact-synchronisation-deleted-success"), check { assertThat(it["offenderNo"]).isEqualTo(offenderNo) assertThat(it["bookingId"]).isEqualTo(bookingId.toString()) assertThat(it["contactId"]).isEqualTo(contactId.toString()) assertThat(it["personId"]).isEqualTo(personId.toString()) }, isNull(), ) } } @Nested @DisplayName("PERSON_RESTRICTION-UPSERTED") inner class ContactRestrictionUpserted { private val restrictionId = 9876L private val personId = 123456L private val contactId = 3456L private val offenderNo = "A1234KT" @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, contactRestrictionEvent( eventType = "PERSON_RESTRICTION-UPSERTED", personId = personId, restrictionId = restrictionId, contactId = contactId, offenderNo = offenderNo, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-contact-restriction-synchronisation-created-success"), check { assertThat(it["contactRestrictionId"]).isEqualTo(restrictionId.toString()) assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["contactId"]).isEqualTo(contactId.toString()) assertThat(it["offenderNo"]).isEqualTo(offenderNo) }, isNull(), ) } } @Nested @DisplayName("PERSON_RESTRICTION-DELETED") inner class ContactRestrictionDeleted { private val restrictionId = 9876L private val personId = 123456L private val contactId = 3456L private val offenderNo = "A1234KT" @BeforeEach fun setUp() { awsSqsContactPersonOffenderEventsClient.sendMessage( contactPersonQueueOffenderEventsUrl, contactRestrictionEvent( eventType = "PERSON_RESTRICTION-DELETED", personId = personId, restrictionId = restrictionId, contactId = contactId, offenderNo = offenderNo, ), ).also { waitForAnyProcessingToComplete() } } @Test fun `will track telemetry`() { verify(telemetryClient).trackEvent( eq("contactperson-contact-restriction-synchronisation-deleted-success"), check { assertThat(it["contactRestrictionId"]).isEqualTo(restrictionId.toString()) assertThat(it["personId"]).isEqualTo(personId.toString()) assertThat(it["contactId"]).isEqualTo(contactId.toString()) assertThat(it["offenderNo"]).isEqualTo(offenderNo) }, isNull(), ) } } } fun personEvent( eventType: String, personId: Long, auditModuleName: String = "OCUCNPER", ) = // language=JSON """{ "MessageId": "ae06c49e-1f41-4b9f-b2f2-dcca610d02cd", "Type": "Notification", "Timestamp": "2019-10-21T14:01:18.500Z", "Message": "{\"eventId\":\"5958295\",\"eventType\":\"$eventType\",\"eventDatetime\":\"2019-10-21T15:00:25.489964\",\"personId\": \"$personId\",\"auditModuleName\":\"$auditModuleName\",\"nomisEventType\":\"$eventType\" }", "TopicArn": "arn:aws:sns:eu-west-1:000000000000:offender_events", "MessageAttributes": { "eventType": {"Type": "String", "Value": "$eventType"}, "id": {"Type": "String", "Value": "8b07cbd9-0820-0a0f-c32f-a9429b618e0b"}, "contentType": {"Type": "String", "Value": "text/plain;charset=UTF-8"}, "timestamp": {"Type": "Number.java.lang.Long", "Value": "1571666478344"} } } """.trimIndent() fun personAddressEvent( eventType: String, personId: Long, addressId: Long, auditModuleName: String = "OCDOAPOP", ) = // language=JSON """{ "MessageId": "ae06c49e-1f41-4b9f-b2f2-dcca610d02cd", "Type": "Notification", "Timestamp": "2019-10-21T14:01:18.500Z", "Message": "{\"eventId\":\"5958295\",\"eventType\":\"$eventType\",\"eventDatetime\":\"2019-10-21T15:00:25.489964\",\"addressId\": \"$addressId\",\"personId\": \"$personId\",\"auditModuleName\":\"$auditModuleName\",\"nomisEventType\":\"$eventType\" }", "TopicArn": "arn:aws:sns:eu-west-1:000000000000:offender_events", "MessageAttributes": { "eventType": {"Type": "String", "Value": "$eventType"}, "id": {"Type": "String", "Value": "8b07cbd9-0820-0a0f-c32f-a9429b618e0b"}, "contentType": {"Type": "String", "Value": "text/plain;charset=UTF-8"}, "timestamp": {"Type": "Number.java.lang.Long", "Value": "1571666478344"} } } """.trimIndent() fun personPhoneEvent( eventType: String, personId: Long, phoneId: Long, auditModuleName: String = "OCDGNUMB", isAddress: Boolean = false, ) = // language=JSON """{ "MessageId": "ae06c49e-1f41-4b9f-b2f2-dcca610d02cd", "Type": "Notification", "Timestamp": "2019-10-21T14:01:18.500Z", "Message": "{\"eventId\":\"5958295\",\"eventType\":\"$eventType\",\"eventDatetime\":\"2019-10-21T15:00:25.489964\",\"phoneId\": \"$phoneId\",\"personId\": \"$personId\",\"isAddress\": \"$isAddress\",\"auditModuleName\":\"$auditModuleName\",\"nomisEventType\":\"$eventType\" }", "TopicArn": "arn:aws:sns:eu-west-1:000000000000:offender_events", "MessageAttributes": { "eventType": {"Type": "String", "Value": "$eventType"}, "id": {"Type": "String", "Value": "8b07cbd9-0820-0a0f-c32f-a9429b618e0b"}, "contentType": {"Type": "String", "Value": "text/plain;charset=UTF-8"}, "timestamp": {"Type": "Number.java.lang.Long", "Value": "1571666478344"} } } """.trimIndent() fun personInternetAddressEvent( eventType: String, personId: Long, internetAddressId: Long, auditModuleName: String = "OCDGNUMB", ) = // language=JSON """{ "MessageId": "ae06c49e-1f41-4b9f-b2f2-dcca610d02cd", "Type": "Notification", "Timestamp": "2019-10-21T14:01:18.500Z", "Message": "{\"eventId\":\"5958295\",\"eventType\":\"$eventType\",\"eventDatetime\":\"2019-10-21T15:00:25.489964\",\"internetAddressId\": \"$internetAddressId\",\"personId\": \"$personId\",\"auditModuleName\":\"$auditModuleName\",\"nomisEventType\":\"$eventType\" }", "TopicArn": "arn:aws:sns:eu-west-1:000000000000:offender_events", "MessageAttributes": { "eventType": {"Type": "String", "Value": "$eventType"}, "id": {"Type": "String", "Value": "8b07cbd9-0820-0a0f-c32f-a9429b618e0b"}, "contentType": {"Type": "String", "Value": "text/plain;charset=UTF-8"}, "timestamp": {"Type": "Number.java.lang.Long", "Value": "1571666478344"} } } """.trimIndent() fun personEmploymentEvent( eventType: String, personId: Long, employmentSequence: Long, auditModuleName: String = "OCDPERSO", ) = // language=JSON """{ "MessageId": "ae06c49e-1f41-4b9f-b2f2-dcca610d02cd", "Type": "Notification", "Timestamp": "2019-10-21T14:01:18.500Z", "Message": "{\"eventId\":\"5958295\",\"eventType\":\"$eventType\",\"eventDatetime\":\"2019-10-21T15:00:25.489964\",\"employmentSequence\": \"$employmentSequence\",\"personId\": \"$personId\",\"auditModuleName\":\"$auditModuleName\",\"nomisEventType\":\"$eventType\" }", "TopicArn": "arn:aws:sns:eu-west-1:000000000000:offender_events", "MessageAttributes": { "eventType": {"Type": "String", "Value": "$eventType"}, "id": {"Type": "String", "Value": "8b07cbd9-0820-0a0f-c32f-a9429b618e0b"}, "contentType": {"Type": "String", "Value": "text/plain;charset=UTF-8"}, "timestamp": {"Type": "Number.java.lang.Long", "Value": "1571666478344"} } } """.trimIndent() fun personIdentifierEvent( eventType: String, personId: Long, identifierSequence: Long, auditModuleName: String = "OCDPERSO", ) = // language=JSON """{ "MessageId": "ae06c49e-1f41-4b9f-b2f2-dcca610d02cd", "Type": "Notification", "Timestamp": "2019-10-21T14:01:18.500Z", "Message": "{\"eventId\":\"5958295\",\"eventType\":\"$eventType\",\"eventDatetime\":\"2019-10-21T15:00:25.489964\",\"identifierSequence\": \"$identifierSequence\",\"personId\": \"$personId\",\"auditModuleName\":\"$auditModuleName\",\"nomisEventType\":\"$eventType\" }", "TopicArn": "arn:aws:sns:eu-west-1:000000000000:offender_events", "MessageAttributes": { "eventType": {"Type": "String", "Value": "$eventType"}, "id": {"Type": "String", "Value": "8b07cbd9-0820-0a0f-c32f-a9429b618e0b"}, "contentType": {"Type": "String", "Value": "text/plain;charset=UTF-8"}, "timestamp": {"Type": "Number.java.lang.Long", "Value": "1571666478344"} } } """.trimIndent() fun personRestrictionEvent( eventType: String, restrictionId: Long, personId: Long, auditModuleName: String = "OMUVREST", ) = // language=JSON """{ "MessageId": "ae06c49e-1f41-4b9f-b2f2-dcca610d02cd", "Type": "Notification", "Timestamp": "2019-10-21T14:01:18.500Z", "Message": "{\"eventId\":\"5958295\",\"eventType\":\"$eventType\",\"eventDatetime\":\"2019-10-21T15:00:25.489964\",\"personId\": \"$personId\",\"visitorRestrictionId\": \"$restrictionId\",\"auditModuleName\":\"$auditModuleName\",\"restrictionType\": \"BAN\",\"effectiveDate\": \"2021-10-15\",\"expiryDate\": \"2022-01-13\",\"enteredById\": \"485887\",\"nomisEventType\":\"VISITOR_RESTRICTS-UPDATED\" }", "TopicArn": "arn:aws:sns:eu-west-1:000000000000:offender_events", "MessageAttributes": { "eventType": {"Type": "String", "Value": "$eventType"}, "id": {"Type": "String", "Value": "8b07cbd9-0820-0a0f-c32f-a9429b618e0b"}, "contentType": {"Type": "String", "Value": "text/plain;charset=UTF-8"}, "timestamp": {"Type": "Number.java.lang.Long", "Value": "1571666478344"} } } """.trimIndent() fun contactEvent( eventType: String, contactId: Long, personId: Long, bookingId: Long, offenderNo: String, auditModuleName: String = "OCDPERSO", ) = // language=JSON """{ "MessageId": "ae06c49e-1f41-4b9f-b2f2-dcca610d02cd", "Type": "Notification", "Timestamp": "2019-10-21T14:01:18.500Z", "Message": "{\"eventId\":\"5958295\",\"eventType\":\"$eventType\",\"eventDatetime\":\"2019-10-21T15:00:25.489964\",\"bookingId\": \"$bookingId\",\"offenderIdDisplay\": \"$offenderNo\",\"personId\": \"$personId\",\"contactId\": \"$contactId\",\"auditModuleName\":\"$auditModuleName\",\"approvedVisitor\": \"false\",\"nomisEventType\":\"OFFENDER_CONTACT-INSERTED\" }", "TopicArn": "arn:aws:sns:eu-west-1:000000000000:offender_events", "MessageAttributes": { "eventType": {"Type": "String", "Value": "$eventType"}, "id": {"Type": "String", "Value": "8b07cbd9-0820-0a0f-c32f-a9429b618e0b"}, "contentType": {"Type": "String", "Value": "text/plain;charset=UTF-8"}, "timestamp": {"Type": "Number.java.lang.Long", "Value": "1571666478344"} } } """.trimIndent() fun contactRestrictionEvent( eventType: String, restrictionId: Long, personId: Long, contactId: Long, offenderNo: String, auditModuleName: String = "OIUOVRES", ) = // language=JSON """{ "MessageId": "ae06c49e-1f41-4b9f-b2f2-dcca610d02cd", "Type": "Notification", "Timestamp": "2019-10-21T14:01:18.500Z", "Message": "{\"eventId\":\"5958295\",\"eventType\":\"$eventType\",\"eventDatetime\":\"2019-10-21T15:00:25.489964\",\"personId\": \"$personId\",\"offenderIdDisplay\": \"$offenderNo\",\"contactPersonId\": \"$contactId\",\"offenderPersonRestrictionId\": \"$restrictionId\",\"auditModuleName\":\"$auditModuleName\",\"restrictionType\": \"BAN\",\"effectiveDate\": \"2021-10-15\",\"expiryDate\": \"2022-01-13\",\"enteredById\": \"485887\",\"nomisEventType\":\"OFF_PERS_RESTRICTS-UPDATED\" }", "TopicArn": "arn:aws:sns:eu-west-1:000000000000:offender_events", "MessageAttributes": { "eventType": {"Type": "String", "Value": "$eventType"}, "id": {"Type": "String", "Value": "8b07cbd9-0820-0a0f-c32f-a9429b618e0b"}, "contentType": {"Type": "String", "Value": "text/plain;charset=UTF-8"}, "timestamp": {"Type": "Number.java.lang.Long", "Value": "1571666478344"} } } """.trimIndent()
1
Kotlin
1
2
706e653ba22b5275a821f57a2f3a5b11ae99ca08
35,952
hmpps-prisoner-from-nomis-migration
MIT License
src/main/kotlin/homework3/TestGenerator.kt
martilut
342,898,976
false
{"Kotlin": 107965}
package homework3 import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.FileSpec class TestGenerator(private val testClass: TestClass) { private fun generateFunction(function: TestFunction) = FunSpec.builder(function.name) .addAnnotation(ClassName("org.junit.jupiter.api", "Test")) .build() private fun generateClass(className: String, functions: List<TestFunction>) = TypeSpec.classBuilder(className) .addModifiers(KModifier.INTERNAL) .addFunctions(functions.map { generateFunction(it) }) .build() fun generateFile() = FileSpec.builder(testClass.packageName, testClass.className + "Test") .addType(generateClass(testClass.className, testClass.functions)) .build() }
0
Kotlin
0
0
091a57cbca3fca8869ea5b61d2e0f2f77ccdb792
930
spbu_2021_kotlin_homeworks
Apache License 2.0
app/src/main/java/com/romandevyatov/bestfinance/db/entities/relations/IncomeHistoryWithIncomeSubGroupAndWallet.kt
RomanDevyatov
587,557,441
false
null
package com.romandevyatov.bestfinance.db.entities.relations import androidx.room.Embedded import androidx.room.Relation import com.romandevyatov.bestfinance.db.entities.IncomeHistory import com.romandevyatov.bestfinance.db.entities.IncomeSubGroup import com.romandevyatov.bestfinance.db.entities.Wallet data class IncomeHistoryWithIncomeSubGroupAndWallet ( @Embedded var incomeHistory: IncomeHistory, @Relation( entity = IncomeSubGroup::class, parentColumn = "income_sub_group_id", entityColumn = "id") var incomeSubGroup: IncomeSubGroup, @Relation( entity = Wallet::class, parentColumn = "wallet_id", entityColumn = "id") var wallet: Wallet )
0
Kotlin
0
1
b810131126c84cd6daf6fcfb86b700ece556fd5b
722
BestFinance
Apache License 2.0
src/main/java/com/alcosi/lib/crypto/nodes/CryptoNodeHealthChecker.kt
alcosi
698,911,809
false
{"Kotlin": 412500, "Java": 97797, "HTML": 4094, "JavaScript": 1134, "CSS": 203}
/* * Copyright (c) 2023 Alcosi Group Ltd. and affiliates. * * 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.alcosi.lib.crypto.nodes import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import java.net.URL import java.util.* import java.util.logging.Level import java.util.logging.Logger /** * The CryptoNodeHealthChecker class is responsible for checking the health status of a crypto node. * * @property client OkHttpClient instance used for making HTTP requests. */ open class CryptoNodeHealthChecker(val client: OkHttpClient) { /** * Represents the request body used for checking the health status of a crypto node. * * The `body` property is created by calling*/ val body = createBody() /** * Represents the health status of a crypto node. * * @property status The status of the crypto node. * @property timeout The time taken for the health check in milliseconds. */ @JvmRecord data class HeathStatus(val status: Boolean, val timeout: Long) { override fun toString(): String { return "$status:$timeout ms" } } /** * Creates the request body for checking the health status of a crypto node. * * @return An instance of [RequestBody] representing the request body. */ protected open fun createBody(): RequestBody { val currentBlockRequest = """{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":"ethBlockNumberPing${UUID.randomUUID()}"}""" return currentBlockRequest.toRequestBody("application/json".toMediaTypeOrNull()) } /** * Checks the health status of a given URL. * * @param url The URL to check. * * @return The health status of the URL. */ open fun check(url: URL): HeathStatus { val time = System.currentTimeMillis() val status = checkStatus(url) return HeathStatus(status, System.currentTimeMillis() - time) } /** * Checks the status of a given URL. * * @param url The URL to check the status of. * @return True if the status check is successful, false otherwise. */ protected open fun checkStatus(url: URL): Boolean { try { val request = Request.Builder().url(url) .post(body) .build() val call = client.newCall(request) val response = call.execute() return response.isSuccessful } catch (th: Throwable) { logger.log(Level.SEVERE, "Error health check $url", th) return false } } /** * This class contains a companion object with a single property, `logger`, defined as a `Logger` object. * The `logger` is used to log messages related to the `CryptoNodeHealthChecker` class. * * @property logger A `Logger` object used for logging messages. */ companion object { /** * Logger - A variable representing a logger instance for logging purposes. * * @property logger The logger instance. */ val logger = Logger.getLogger(this::class.java.name) } }
0
Kotlin
0
0
5a9837c15b97dd94f0215c7f1ce628750baa73a8
3,832
alcosi_commons_library
Apache License 2.0
src/integrationTest/kotlin/de/bund/digitalservice/useid/api/ApiDocsIntegrationTest.kt
digitalservicebund
475,364,510
false
null
package de.bund.digitalservice.useid.api import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.http.MediaType import org.springframework.test.web.reactive.server.WebTestClient @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class ApiDocsIntegrationTest(@Autowired val webTestClient: WebTestClient) { @Test fun `api docs ui endpoint returns redirects to swagger ui`() { webTestClient .get() .uri("/api/docs") .exchange() .expectStatus().is3xxRedirection .expectHeader().location("/api/swagger-ui/index.html") } @Test fun `swagger ui endpoint returns html page successfully`() { webTestClient .get() .uri("/api/swagger-ui/index.html") .exchange() .expectStatus().isOk .expectHeader().contentType(MediaType.TEXT_HTML) } @Test fun `api docs endpoint returns json representation of api docs successfully`() { webTestClient .get() .uri("/api/docs.json") .exchange() .expectStatus().isOk .expectHeader().contentType(MediaType.APPLICATION_JSON) } }
0
Kotlin
1
6
2524d1377e3be2953942f40b36ce231963ddbda2
1,343
useid-backend-service
MIT License
src/main/kotlin/br/com/zupacademy/witer/pix/carregachave/GrpcExtensions.kt
witermendonca
383,890,247
true
{"Kotlin": 99526, "Smarty": 2172, "Dockerfile": 158}
package br.com.zupacademy.witer.pix.carregachave import br.com.zupacademy.witer.CarregaChavePixRequest import br.com.zupacademy.witer.CarregaChavePixRequest.FiltroCase.* import javax.validation.ConstraintViolationException import javax.validation.Validator fun CarregaChavePixRequest.toModel(validator: Validator): Filtro{ val filtro = when(filtroCase!!){ PIXECLIENTEID -> pixEClienteId.let { Filtro.PorPixEClenteId(clienteId= it.clienteId, pixId= it.pixId) } CHAVE -> Filtro.PorChave(chave) FILTRO_NOT_SET -> Filtro.Invalido() } val violations = validator.validate(filtro) if (violations.isNotEmpty()) { throw ConstraintViolationException(violations); } return filtro }
0
Kotlin
0
0
30a2c91aac64960d0f1cb798e103a2ad94364de8
751
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
src/Day01.kt
rbraeunlich
573,282,138
false
{"Kotlin": 63724}
fun main() { fun part1(input: List<String>): Int { var maxCalories = 0 var currentCalories = 0 input.forEach { line -> if(line.isBlank()) { if(currentCalories > maxCalories) { println("$currentCalories is more than $maxCalories") maxCalories = currentCalories } currentCalories = 0 } else { currentCalories += line.toInt() } } return maxCalories } fun part2(input: List<String>): Int { val allCalories = mutableListOf<Int>() var currentCalories = 0 input.forEach { line -> if(line.isBlank()) { allCalories.add(currentCalories) currentCalories = 0 } else { currentCalories += line.toInt() } } allCalories.sort() return allCalories.takeLast(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") // check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
3c7e46ddfb933281be34e58933b84870c6607acd
1,222
advent-of-code-2022
Apache License 2.0
app/src/main/java/caios/android/pixivion/utils/LogUtils.kt
CAIOS0922
485,093,354
false
null
package caios.android.pixivion.utils import android.util.Log object LogUtils { const val TAG = "<LOG>" const val STARTUP_TAG = "<START-UP>" const val EXCEPTION_TAG = "<EXCEPTION>" fun tryCatch(isTakeLog: Boolean = true, f: () -> (Unit)) { try { f() } catch (e: Throwable) { if (isTakeLog) Log.e(TAG, "tryCatch: ${e.message}", e) } } }
0
Kotlin
0
0
311f2b627abaf64dd891c0447b8ff0e99c8efecd
406
Pixivion
Apache License 2.0
ui-components/src/main/kotlin/com/jcgseco/myarmory/uicomponents/lists/GalleryItem.kt
IkariMeister
455,540,709
false
null
package com.jcgseco.myarmory.uicomponents.lists import android.view.View import androidx.recyclerview.widget.RecyclerView import com.jcgseco.myarmory.uicomponents.R import com.jcgseco.myarmory.uicomponents.databinding.ItemGalleryBinding import com.xwray.groupie.viewbinding.BindableItem import com.xwray.groupie.viewbinding.GroupieViewHolder class GalleryItem( private val adapter: RecyclerView.Adapter<*>, private val carouselDecoration: RecyclerView.ItemDecoration? = null ) : BindableItem<ItemGalleryBinding>() { override fun getLayout(): Int = R.layout.item_gallery override fun initializeViewBinding(view: View): ItemGalleryBinding = ItemGalleryBinding.bind(view) override fun createViewHolder(itemView: View): GroupieViewHolder<ItemGalleryBinding> { val viewHolder = super.createViewHolder(itemView) val recyclerView = viewHolder.binding.recyclerView carouselDecoration?.let { recyclerView.addItemDecoration(it) } return viewHolder } override fun bind(viewBinding: ItemGalleryBinding, position: Int) { viewBinding.recyclerView.adapter = adapter } }
1
Kotlin
0
0
c49f344aa268609280b75d3cc61224b5f24ef447
1,141
MyArmory
Apache License 2.0
utbot-instrumentation/src/test/kotlin/org/utbot/instrumentation/examples/mock/TestMock.kt
UnitTestBot
480,810,501
false
null
package org.utbot.instrumentation.examples.mock import org.utbot.instrumentation.samples.mock.ClassForMock import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Test class TestMock { @Test fun testClassForMock_getX() { val mockHelper = MockHelper(ClassForMock::class.java) val instrumentedClazz = mockHelper.instrumentedClazz val instance = instrumentedClazz.constructors.first { it.parameters.isEmpty() }.newInstance() val method = instrumentedClazz.declaredMethods.first { it.name == "getX" } assertEquals(15, method.invoke(instance)) val mockValues = listOf(1, 2, 3, 4, 5) mockHelper.withMockedMethod(method, instance, mockValues) { mockValues.forEach { assertEquals(it, method.invoke(instance)) } } } @Test fun getClassForMock_getX_multipleCalls() { val mockHelper = MockHelper(ClassForMock::class.java) val instrumentedClazz = mockHelper.instrumentedClazz val instance = instrumentedClazz.constructors.first { it.parameters.isEmpty() }.newInstance() val method = instrumentedClazz.declaredMethods.first { it.name == "getX" } assertEquals(15, method.invoke(instance)) val mockValues1 = listOf(1, 2, 3, 4, 5) mockHelper.withMockedMethod(method, instance, mockValues1) { mockValues1.forEach { assertEquals(it, method.invoke(instance)) } } assertEquals(15, method.invoke(instance)) // should be the same as it was before mocking val mockValues2 = listOf(-1, -2, -3, -4, -5) mockHelper.withMockedMethod(method, instance, mockValues2) { mockValues2.forEach { assertEquals(it, method.invoke(instance)) } } } @Test fun testClassForMock_getString() { val mockHelper = MockHelper(ClassForMock::class.java) val instrumentedClazz = mockHelper.instrumentedClazz val instance = null // static method val method = instrumentedClazz.declaredMethods.first { it.name == "getString" } assertEquals("string", method.invoke(instance)) val mockValues = listOf("a", "b", "c", "aa", "", "aaaaaa") mockHelper.withMockedMethod(method, instance, mockValues) { mockValues.forEach { assertEquals(it, method.invoke(instance)) } } } @Test fun testClassForMock_complicateMethod() { val mockHelper = MockHelper(ClassForMock::class.java) val instrumentedClazz = mockHelper.instrumentedClazz val instance = instrumentedClazz.constructors.first { it.parameters.isEmpty() }.newInstance() val method = instrumentedClazz.declaredMethods.first { it.name == "complicatedMethod" } assertEquals("x + y == z", method.invoke(instance, 1, 2, 3, null)) val mockValues1 = listOf("azaza", "lol", "ha", "kek") mockHelper.withMockedMethod(method, instance, mockValues1) { mockValues1.forEach { assertEquals(it, method.invoke(instance, 1, 2, 3, instance)) } } assertEquals("equals", method.invoke(instance, 0, 0, 0, instance)) val mockValues2 = listOf("ok", "ok", "", "da") mockHelper.withMockedMethod(method, instance, mockValues2) { mockValues2.forEach { assertEquals(it, method.invoke(instance, 1, 2, 3, instance)) } } } @Test fun testClassForMock_provideInt_mocksBoth() { val mockHelper = MockHelper(ClassForMock::class.java) val instrumentedClazz = mockHelper.instrumentedClazz val instance1 = instrumentedClazz.constructors.first { it.parameters.isEmpty() }.newInstance() val instance2 = instrumentedClazz.constructors.first { it.parameters.size == 1 }.newInstance("") val method = instrumentedClazz.declaredMethods.first { it.name == "provideInt" } assertNotEquals(method.invoke(instance1), method.invoke(instance2)) mockHelper.withMockedMethod(method, instance1, listOf(3, 3)) { mockHelper.withMockedMethod(method, instance2, listOf(1, 3)) { assertNotEquals(method.invoke(instance1), method.invoke(instance2)) assertEquals(method.invoke(instance1), method.invoke(instance2)) } } } @Test fun testClassForMock_check_usesMockedValues() { val mockHelper = MockHelper(ClassForMock::class.java) val instrumentedClazz = mockHelper.instrumentedClazz val instance1 = instrumentedClazz.constructors.first { it.parameters.isEmpty() }.newInstance() val instance2 = instrumentedClazz.constructors.first { it.parameters.size == 1 }.newInstance("") val method = instrumentedClazz.declaredMethods.first { it.name == "provideInt" } val methodCheck = instrumentedClazz.declaredMethods.first { it.name == "check" } assertNotEquals(method.invoke(instance1), method.invoke(instance2)) mockHelper.withMockedMethod(method, instance1, listOf(3, 3)) { mockHelper.withMockedMethod(method, instance2, listOf(1, 3)) { assertEquals(false, methodCheck.invoke(instance1, instance2)) assertEquals(true, methodCheck.invoke(instance1, instance2)) } } } }
398
Kotlin
32
91
abb62682c70d7d2ecc4ad610851d304f7ad716e4
5,470
UTBotJava
Apache License 2.0
app/src/main/java/com/alessandroborelli/floatapp/domain/DomainModule.kt
br00
455,222,224
false
null
package com.alessandroborelli.floatapp.domain import com.alessandroborelli.floatapp.domain.mapper.AddMooringRequestMapper import com.alessandroborelli.floatapp.domain.mapper.AddMooringRequestMapperImpl import com.alessandroborelli.floatapp.domain.mapper.GetMooringsResponseMapper import com.alessandroborelli.floatapp.domain.mapper.GetMooringsResponseMapperImpl import com.alessandroborelli.floatapp.domain.usecase.AddMooringUseCase import com.alessandroborelli.floatapp.domain.usecase.AddMooringUseCaseImpl import com.alessandroborelli.floatapp.domain.usecase.GetMooringsUseCase import com.alessandroborelli.floatapp.domain.usecase.GetMooringsUseCaseImpl import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @InstallIn(SingletonComponent::class) @Module internal abstract class DomainModule { @Binds abstract fun GetMooringsResponseMapperImpl.bindMooringsResponseMapper(): GetMooringsResponseMapper @Binds abstract fun GetMooringsUseCaseImpl.bindMooringsUseCase(): GetMooringsUseCase @Binds abstract fun AddMooringRequestMapperImpl.bindAddMooringRequestMapper(): AddMooringRequestMapper @Binds abstract fun AddMooringUseCaseImpl.bindAddMooringUseCase(): AddMooringUseCase }
1
Kotlin
1
0
eb4a2eb19c46dcfad4564a5700fd3493748896eb
1,278
float
Apache License 2.0
src/commonMain/kotlin/baaahs/shaders/SolidShader.kt
r3dcrosse
176,017,465
true
{"JavaScript": 3675254, "Kotlin": 56536, "HTML": 2063, "CSS": 1970}
package baaahs.shaders import baaahs.* class SolidShader : Shader(ShaderType.SOLID) { override val buffer = SolidShaderBuffer() override fun createImpl(pixels: Pixels): ShaderImpl = SolidShaderImpl(buffer, pixels) companion object { fun parse(reader: ByteArrayReader) = SolidShader() } } class SolidShaderImpl(val buffer: SolidShaderBuffer, val pixels: Pixels) : ShaderImpl { private val colors = Array(pixels.count) { Color.WHITE } override fun draw() { for (i in colors.indices) { colors[i] = buffer.color } pixels.set(colors) } } class SolidShaderBuffer : ShaderBuffer { var color: Color = Color.WHITE override fun serialize(writer: ByteArrayWriter) { color.serialize(writer) } override fun read(reader: ByteArrayReader) { color = Color.parse(reader) } }
0
JavaScript
0
0
5f4e831773ad268762431ee56d376dc8a9a46882
874
sparklemotion
MIT License
hazelnet-community/src/main/kotlin/io/hazelnet/community/data/discord/DiscordMemberActivity.kt
nilscodes
446,203,879
false
{"TypeScript": 1045486, "Kotlin": 810416, "Dockerfile": 4476, "Shell": 1830, "JavaScript": 1384}
package io.hazelnet.community.data.discord import com.fasterxml.jackson.databind.annotation.JsonSerialize import com.fasterxml.jackson.databind.ser.std.ToStringSerializer import java.util.* import javax.persistence.* @Entity @Table(name = "discord_activity") @IdClass(DiscordGuildMemberId::class) class DiscordMemberActivity( @Id @Column(name = "discord_server_id") var discordServerId: Int?, @Id @Column(name = "discord_user_id") @field:JsonSerialize(using = ToStringSerializer::class) var discordUserId: Long?, @Temporal(TemporalType.TIMESTAMP) @Column(name = "last_activity_time", updatable = true) var lastActivityTime: Date?, @Temporal(TemporalType.TIMESTAMP) @Column(name = "last_reminder_time", updatable = true) var lastReminderTime: Date? = null, ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as DiscordMemberActivity if (discordServerId != other.discordServerId) return false if (discordUserId != other.discordUserId) return false if (lastActivityTime != other.lastActivityTime) return false if (lastReminderTime != other.lastReminderTime) return false return true } override fun hashCode(): Int { var result = discordServerId ?: 0 result = 31 * result + (discordUserId?.hashCode() ?: 0) result = 31 * result + (lastActivityTime?.hashCode() ?: 0) result = 31 * result + (lastReminderTime?.hashCode() ?: 0) return result } override fun toString(): String { return "DiscordMemberActivity(discordServerId=$discordServerId, discordUserId=$discordUserId, lastActivityTime=$lastActivityTime, lastReminder=$lastReminderTime)" } }
0
TypeScript
4
13
79f8b096f599255acb03cc809464d0570a51d82c
1,819
hazelnet
Apache License 2.0
app/src/main/java/com/ghoulmind/habitica/HabiticaClient.kt
greatghoul
103,035,894
false
null
package com.ghoulmind.habitica import android.content.Context import com.ghoulmind.habitdrod.R import khttp.get import khttp.post import org.json.JSONArray import org.json.JSONObject class HabiticaClient { var api_base: String = "https://habitica.com/api/v3" constructor(api_base: String? = null) { if (api_base != null) { this.api_base = api_base } } fun endpoint(path: String): String { return "$api_base$path" } fun login(username: String, password: String): JSONObject { val result = post(endpoint("/user/auth/local/login"), data = mapOf("username" to username, "password" to <PASSWORD>)).jsonObject if (result.getBoolean("success")) { return result.getJSONObject("data") } else { val error = result.getString("error") val message = result.getString("message") throw HabiticaException("$error: $message") } } fun getTasks(apiKey: String, apiUser: String): JSONArray { val result = get(endpoint("/tasks/user"), headers = mapOf("x-api-key" to apiKey, "x-api-user" to apiUser)).jsonObject if (result.getBoolean("success")) { var data = result.getJSONArray("data") return data } else { val error = result.getString("error") val message = result.getString("message") throw HabiticaException("$error: $message") } } }
0
Kotlin
1
1
d9c11b8cb18f2202de0ecc1766e424da78ad9dfe
1,468
HabitDrod
MIT License
falkon-dao-extn/src/test/kotlin/com/jayrave/falkon/dao/testLib/EngineForTestingDaoExtn.kt
jayrave
65,279,209
false
null
package com.jayrave.falkon.dao.testLib import com.jayrave.falkon.engine.* import com.nhaarman.mockito_kotlin.mock import java.util.* /** * All build* methods return a constant dummy string as SQL. All compile* methods return * mock statements (they are stored before returned so as to help verify interactions with it) */ internal class EngineForTestingDaoExtn private constructor( private val insertProvider: () -> CompiledStatement<Int>, private val updateProvider: () -> CompiledStatement<Int>, private val deleteProvider: () -> CompiledStatement<Int>, private val insertOrReplaceProvider: () -> CompiledStatement<Int>, private val queryProvider: () -> CompiledStatement<Source>) : Engine { val compiledStatementsForInsert = ArrayList<CompiledStatement<Int>>() val compiledStatementsForUpdate = ArrayList<CompiledStatement<Int>>() val compiledStatementsForDelete = ArrayList<CompiledStatement<Int>>() val compiledStatementsForInsertOrReplace = ArrayList<CompiledStatement<Int>>() val compiledStatementsForQuery = ArrayList<CompiledStatement<Source>>() override fun <R> executeInTransaction(operation: () -> R): R { return operation.invoke() } override fun isInTransaction(): Boolean { throw UnsupportedOperationException() } override fun compileSql(tableNames: Iterable<String>?, rawSql: String): CompiledStatement<Unit> { throw UnsupportedOperationException() } override fun compileInsert(tableName: String, rawSql: String): CompiledStatement<Int> { compiledStatementsForInsert.add(insertProvider.invoke()) return compiledStatementsForInsert.last() } override fun compileUpdate(tableName: String, rawSql: String): CompiledStatement<Int> { compiledStatementsForUpdate.add(updateProvider.invoke()) return compiledStatementsForUpdate.last() } override fun compileDelete(tableName: String, rawSql: String): CompiledStatement<Int> { compiledStatementsForDelete.add(deleteProvider.invoke()) return compiledStatementsForDelete.last() } override fun compileInsertOrReplace(tableName: String, rawSql: String): CompiledStatement<Int> { compiledStatementsForInsertOrReplace.add(insertOrReplaceProvider.invoke()) return compiledStatementsForInsertOrReplace.last() } override fun compileQuery(tableNames: Iterable<String>, rawSql: String): CompiledStatement<Source> { compiledStatementsForQuery.add(queryProvider.invoke()) return compiledStatementsForQuery.last() } override fun registerDbEventListener(dbEventListener: DbEventListener) { throw UnsupportedOperationException() } override fun unregisterDbEventListener(dbEventListener: DbEventListener) { throw UnsupportedOperationException() } companion object { fun createWithMockStatements( insertProvider: () -> CompiledStatement<Int> = { mock<CompiledStatement<Int>>() }, updateProvider: () -> CompiledStatement<Int> = { mock<CompiledStatement<Int>>() }, deleteProvider: () -> CompiledStatement<Int> = { mock<CompiledStatement<Int>>() }, insertOrReplaceProvider: () -> CompiledStatement<Int> = { mock<CompiledStatement<Int>>() }, queryProvider: () -> CompiledStatement<Source> = { mock<CompiledStatement<Source>>() }): EngineForTestingDaoExtn { return EngineForTestingDaoExtn( insertProvider, updateProvider, deleteProvider, insertOrReplaceProvider, queryProvider ) } } }
6
Kotlin
2
12
ce42d553c578cd8e509bbfd7effc5d56bf3cdedd
3,747
falkon
Apache License 2.0
tracker/buildings/src/main/kotlin/com/iliasg/startrekfleetcommand/buildings/presentation/overview/adapter/OverviewListViewHolder.kt
Iliasgx
455,331,101
false
{"Kotlin": 145697}
package com.iliasg.startrekfleetcommand.buildings.presentation.overview.adapter import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.RecyclerView import com.iliasg.startrekfleetcommand.buildings.databinding.ItemBuildingGroupBinding import com.iliasg.startrekfleetcommand.buildings.databinding.ItemBuildingSingleBinding import com.iliasg.startrekfleetcommand.buildings.domain.models.BuildingListItem import com.iliasg.startrekfleetcommand.buildings.presentation.overview.adapter.OverviewAdapterEvent.* internal sealed class OverviewListViewHolder(binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) { abstract fun bind(item: BuildingListItem) class GroupViewHolder( private val binding: ItemBuildingGroupBinding, private val events: (event: OverviewAdapterEvent) -> Unit ) : OverviewListViewHolder(binding) { override fun bind(item: BuildingListItem) { binding.data = item as BuildingListItem.GroupItem binding.root.setOnClickListener { events(OnGroupClick(item.group)) } } } class BuildingViewHolder( private val binding: ItemBuildingSingleBinding, private val events: (event: OverviewAdapterEvent) -> Unit ) : OverviewListViewHolder(binding) { override fun bind(item: BuildingListItem) { binding.data = item as BuildingListItem.SingleItem binding.btnUpgrade.setOnClickListener { events(OnBuildingUpgrade(item)) } binding.root.setOnClickListener { events(OnBuildingClick(item.id, item.totalLevels)) } binding.btnUpgrade.setOnLongClickListener { events(OnBuildingDowngrade(item)) return@setOnLongClickListener true } } } }
0
Kotlin
0
1
277c4936facbddcffb354f2af6e273b44bb37dea
1,866
STFC-Padd-template
Apache License 2.0
app/src/main/java/com/experiments/jagsaund/asyncdiffutil/Repository.kt
jsaund
156,515,709
false
null
package com.experiments.jagsaund.asyncdiffutil import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.channels.ReceiveChannel import kotlinx.coroutines.experimental.channels.produce import kotlinx.coroutines.experimental.delay import java.util.* import java.util.concurrent.TimeUnit class Repository { private val random: Random = Random() fun data(time: Long, unit: TimeUnit): ReceiveChannel<List<Item>> = produce(CommonPool) { while (isActive) { delay(time, unit) val items = (1..100) .map { Item(it, label(random), 0xFF000000.toInt() or random.nextInt(0xFFFFFF)) } .shuffled(random) .subList(0, random.nextInt(100)) send(items) } } private inline fun label(random: Random): String { val c1 = (random.nextInt(25) + 'A'.toInt()).toChar() val c2 = (random.nextInt(25) + 'A'.toInt()).toChar() val c3 = (random.nextInt(25) + 'A'.toInt()).toChar() return String(charArrayOf(c1, c2, c3)) } }
1
Kotlin
3
30
22a8e50021101f667e15e8ca49402d86c905dea8
1,077
AsyncDiffUtil
Apache License 2.0
EcosystemSimulation/src/shmp/simulation/space/resource/action/ActionTag.kt
ShMPMat
212,499,539
false
null
package shmp.simulation.space.resource.action data class ActionTag(val name: String)
0
Kotlin
0
0
8c04ea13e1ee4381e61e0b52c0d26ff44f71092d
87
CulturesSim
MIT License
EcosystemSimulation/src/shmp/simulation/space/resource/action/ActionTag.kt
ShMPMat
212,499,539
false
null
package shmp.simulation.space.resource.action data class ActionTag(val name: String)
0
Kotlin
0
0
8c04ea13e1ee4381e61e0b52c0d26ff44f71092d
87
CulturesSim
MIT License
slack_data_layer/src/commonMain/kotlin/dev/baseio/slackdata/security/QRCodeDataService.kt
oianmol
528,898,439
false
null
package dev.baseio.slackdata.security import dev.baseio.slackdomain.qrcode.QrCodeGenerator import dev.baseio.slackdomain.security.IByteArraySplitter import dev.baseio.slackdomain.security.SecurityKeyDataPart class ByteArraySplitterImpl(private val qrCodeGenerator: QrCodeGenerator) : IByteArraySplitter { override fun split(key: ByteArray): List<SecurityKeyDataPart> { return qrCodeGenerator.generateFrom(key) } }
3
Kotlin
20
219
c519046fb07fd863c0118e6057b02895ae32e65e
431
SlackComposeMultiplatform
Apache License 2.0
j2k/tests/testData/ast/arrayType/arrayInitializationStatementWithDimensionExplicit.kt
craastad
18,462,025
false
{"Markdown": 18, "XML": 405, "Ant Build System": 23, "Ignore List": 7, "Maven POM": 34, "Kotlin": 10194, "Java": 3675, "CSS": 10, "Shell": 6, "Batchfile": 6, "Java Properties": 9, "Gradle": 61, "INI": 6, "JavaScript": 42, "HTML": 77, "Text": 875, "Roff": 53, "Roff Manpage": 8, "JFlex": 3, "JAR Manifest": 1, "Protocol Buffer": 2}
var d2: Array<IntArray?>? = Array<IntArray?>(5, { IntArray(5) })
1
null
1
1
f41f48b1124e2f162295718850426193ab55f43f
64
kotlin
Apache License 2.0
android/app/src/main/java/dev/imam/rnwidget/SharedStorage.kt
ahmetcangurel
737,801,136
true
{"JavaScript": 3, "TSX": 1, "JSON": 14, "Markdown": 1, "Text": 1, "JSON with Comments": 1, "Ignore List": 3, "Java Properties": 1, "Gradle": 3, "Shell": 1, "Batchfile": 1, "INI": 1, "Proguard": 1, "XML": 27, "Java": 4, "Kotlin": 3, "Ruby": 1, "Dotenv": 1, "Swift": 5, "OpenStep Property List": 4, "Objective-C": 2, "Objective-C++": 1, "C": 1}
package dev.imam.rnwidget import android.appwidget.AppWidgetManager import android.content.ComponentName import android.content.Context import android.content.Intent import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod class SharedStorage(private var context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { override fun getName(): String { return "SharedStorage" } @ReactMethod fun set(message: String?) { val editor = context.getSharedPreferences("DATA", Context.MODE_PRIVATE).edit() editor.putString("appData", message) editor.apply() val intent = Intent( currentActivity!!.applicationContext, StreakWidget::class.java ) intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE val ids = AppWidgetManager.getInstance( currentActivity!!.applicationContext ).getAppWidgetIds( ComponentName( currentActivity!!.applicationContext, StreakWidget::class.java ) ) intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids) currentActivity!!.applicationContext.sendBroadcast(intent) } }
0
Java
0
0
f455940323392456c2f48622e597e6521b977bc2
1,321
RNWidgetExpo
MIT License
app/src/main/java/com/lifesolutions/bd/kotlinCode/ui/adapter/ChatMessageAdapter.kt
alamin1x0
601,487,426
false
{"Java": 2650731, "Kotlin": 822798, "Assembly": 59}
package com.lifesolutions.bd.kotlinCode.ui.adapter import android.Manifest import android.annotation.SuppressLint import android.app.Activity import android.app.Dialog import android.app.DownloadManager import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager import android.media.MediaPlayer import android.net.Uri import android.os.Build import android.os.Environment import android.os.Handler import android.view.* import android.widget.* import androidx.annotation.RequiresApi import androidx.appcompat.app.AlertDialog import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.google.firebase.database.FirebaseDatabase import com.squareup.picasso.Picasso import com.lifesolutions.bd.Activities.ViewImageActivity import com.lifesolutions.bd.Models.Message import com.lifesolutions.bd.R import com.lifesolutions.bd.kotlinCode.utils.toast import java.text.SimpleDateFormat import java.util.* const val MESSAGE_LEFT = 0 const val MESSAGE_RIGHT = 1 class ChatMessageAdapter( private val activity: Activity, private val context: Context, private val messages: ArrayList<Message>, private val receiverId: String ): RecyclerView.Adapter<ChatMessageAdapter.ViewHolderMessage>(){ private val TAG = "ChatMessageAdapter" private var mediaPlayer = MediaPlayer() private val handler = Handler() private var seekBar: SeekBar? = null private var timer: TextView? = null // Shared Pref Current User data.. private var userPreferences: SharedPreferences = context.getSharedPreferences("com.starnote.CurrentAuthUser", Context.MODE_PRIVATE)!! private var db = FirebaseDatabase.getInstance() override fun getItemViewType(position: Int): Int { val currentUserID = userPreferences.getString("uID", null) return if (messages[position].senderId == currentUserID) { MESSAGE_RIGHT } else { MESSAGE_LEFT } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolderMessage { return if (viewType == MESSAGE_RIGHT) { ViewHolderMessage( LayoutInflater.from(context).inflate(R.layout.chat_item_right, parent, false) ) } else { ViewHolderMessage( LayoutInflater.from(context).inflate(R.layout.chat_item_left, parent, false) ) } } override fun getItemCount(): Int { return messages.size } @RequiresApi(Build.VERSION_CODES.O) @SuppressLint("ClickableViewAccessibility") override fun onBindViewHolder(holder: ChatMessageAdapter.ViewHolderMessage, position: Int) { val currentUserID = userPreferences.getString("uID", null) val message = messages[position] if (messages[position].senderId == currentUserID) { if (message.isSeen) { holder.seenIcon.setImageResource(R.drawable.ic_double_check_black) } else { holder.seenIcon.setImageResource(R.drawable.ic_check_black_24dp) } } val sdf = SimpleDateFormat("dd MMMM yy hh:mm aa") // val sdf = SimpleDateFormat("dd/MM/yy") val netDate = Date(message.time as Long) val date =sdf.format(netDate) holder.messageTime.text = date when(messages[position].type) { "text" -> { holder.imageMessageLayout.visibility = View.GONE holder.fileMessageLayout.visibility = View.GONE holder.voiceMessageLayout.visibility = View.GONE holder.textMessageLayout.visibility = View.VISIBLE holder.showMessage.text = messages[position].message holder.textMessageLayout.setOnLongClickListener { if (currentUserID == message.senderId) { deleteMessage(holder.textMessageLayout, currentUserID!!, message, position) } true } } "image" -> { holder.textMessageLayout.visibility = View.GONE holder.fileMessageLayout.visibility = View.GONE holder.voiceMessageLayout.visibility = View.GONE holder.imageMessageLayout.visibility = View.VISIBLE Picasso.get().load(messages[position].message).into(holder.showImage) holder.imageMessageLayout.setOnClickListener { Intent(context, ViewImageActivity::class.java).apply { putExtra("imageUrl", messages[position].imageUrlHD) flags = Intent.FLAG_ACTIVITY_NEW_TASK context.startActivity(this) } } holder.imageMessageLayout.setOnLongClickListener { if (currentUserID == message.senderId) { deleteMessage(holder.textMessageLayout, currentUserID!!, message, position) } true } } "voice" -> { holder.imageMessageLayout.visibility = View.GONE holder.fileMessageLayout.visibility = View.GONE holder.textMessageLayout.visibility = View.GONE holder.voiceMessageLayout.visibility = View.VISIBLE holder.voiceItem.setOnClickListener { val dialog = Dialog(activity) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.setContentView(R.layout.dialog_voice_message_player) dialog.setCancelable(false) dialog.window?.attributes?.windowAnimations = R.style.animation_dialog val timer = dialog.findViewById<TextView>(R.id.timer_music_player_dialog) val duration = dialog.findViewById<TextView>(R.id.duration_music_player_dialog) val closeBtn = dialog.findViewById<TextView>(R.id.close_button_music_player_dialog) val seek = dialog.findViewById<SeekBar>(R.id.seekbar_music_player_dialog) val playPause = dialog.findViewById<ImageButton>(R.id.play_pause_button_music_player_dialog) seek.max = 99 this.timer = timer seekBar = seek prepareMediaPlayer(duration, messages[position].message, playPause, seek) playPause.setOnClickListener { if (mediaPlayer.isPlaying) { handler.removeCallbacks(updater) mediaPlayer.pause() playPause.setImageResource(R.drawable.ic_play_circle_filled_black_24dp) } else { mediaPlayer.start() playPause.setImageResource(R.drawable.ic_pause_circle_filled_black_24dp) updateSeekBar(seek) } } seek.setOnTouchListener { v, _ -> val seekBar1 = v as SeekBar val musicPosition = mediaPlayer.duration / 100 * seekBar1.progress mediaPlayer.seekTo(musicPosition) false } closeBtn.setOnClickListener { if (mediaPlayer.isPlaying) { mediaPlayer.stop() mediaPlayer = MediaPlayer() } dialog.dismiss() } dialog.show() } holder.voiceItem.setOnLongClickListener { if (currentUserID == message.senderId) { deleteMessage(holder.textMessageLayout, currentUserID!!, message, position) } true } } "pdf" -> { holder.imageMessageLayout.visibility = View.GONE holder.textMessageLayout.visibility = View.GONE holder.voiceMessageLayout.visibility = View.GONE holder.fileMessageLayout.visibility = View.VISIBLE holder.file.setOnClickListener { showDownloadDialog(position, "pdf") } holder.file.setOnLongClickListener { if (currentUserID == message.senderId) { deleteMessage(holder.textMessageLayout, currentUserID!!, message, position) } true } } "docx" -> { holder.imageMessageLayout.visibility = View.GONE holder.textMessageLayout.visibility = View.GONE holder.voiceMessageLayout.visibility = View.GONE holder.fileMessageLayout.visibility = View.VISIBLE holder.file.text = "DOCX File" holder.file.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_docs_file, 0, 0, 0) holder.file.setOnClickListener { showDownloadDialog(position, "docx") } holder.file.setOnLongClickListener { if (currentUserID == message.senderId) { deleteMessage(holder.textMessageLayout, currentUserID!!, message, position) } true } } } } //Message View Holder... inner class ViewHolderMessage(view: View) : RecyclerView.ViewHolder(view) { val textMessageLayout: LinearLayout = view.findViewById(R.id.text_message_layout) val imageMessageLayout: LinearLayout = view.findViewById(R.id.image_message_layout) val fileMessageLayout: LinearLayout = view.findViewById(R.id.file_message_layout) val voiceMessageLayout: LinearLayout = view.findViewById(R.id.voice_message_layout) val showMessage: TextView = view.findViewById(R.id.show_message) val messageTime: TextView = view.findViewById(R.id.tv_message_time) val showImage: ImageView = view.findViewById(R.id.show_image) // val profileImage: CircleImageView = view.findViewById(R.id.profile_image_message) val file: TextView = view.findViewById(R.id.file_image) val voiceItem: ImageView = view.findViewById(R.id.voice_icon_message) val seenIcon: ImageView = view.findViewById(R.id.iv_seen_icon) } /** * Function */ private fun deleteMessage(holderItem: View, currentUserID: String, message: Message, position: Int) { val popupMenu = PopupMenu(context, holderItem) popupMenu.inflate(R.menu.menu_chat) popupMenu.setOnMenuItemClickListener { item: MenuItem -> when (item.itemId) { R.id.menu_delete -> { val ref = db.getReference("Messages").child(currentUserID).child(receiverId).child(message.messageId) val refConversation = db.getReference("StarnoteConversation").child(currentUserID).child(receiverId) ref.removeValue() // Conversation Update refConversation.child("lastMessage").setValue("You removed a message") } R.id.menu_delete_everyone -> { val ref1 = db.getReference("Messages").child(currentUserID).child(receiverId).child(message.messageId) val ref2 = db.getReference("Messages").child(receiverId).child(currentUserID).child(message.messageId) val refConversation1 = db.getReference("StarnoteConversation").child(currentUserID).child(receiverId) val refConversation2 = db.getReference("StarnoteConversation").child(receiverId).child(currentUserID) ref1.removeValue() ref2.removeValue() // Conversation Update refConversation1.child("lastMessage").setValue("A message removed") refConversation2.child("lastMessage").setValue("A message removed") } } true } popupMenu.show() } private fun prepareMediaPlayer( duration: TextView, musicUrl: String, playPause: ImageButton, seek: SeekBar ) { try { mediaPlayer.setDataSource(musicUrl) mediaPlayer.prepare() duration.text = milliSecondsToTime(mediaPlayer.duration.toLong()) mediaPlayer.start() playPause.setImageResource(R.drawable.ic_pause_circle_filled_black_24dp) updateSeekBar(seek) } catch (e: Exception) { Toast.makeText(context, "" + e.message, Toast.LENGTH_SHORT).show() } } private val updater = Runnable { updateSeekBar(seekBar!!) val currentDuration = mediaPlayer.currentPosition.toLong() timer?.text = milliSecondsToTime(currentDuration) } private fun updateSeekBar(seek: SeekBar) { if (mediaPlayer.isPlaying) { seek.progress = ((mediaPlayer.currentPosition.toFloat() / mediaPlayer.duration * 100).toInt()) handler.postDelayed(updater, 1000) } } private fun milliSecondsToTime(milliseconds: Long): String? { var timerString = "" val secondString: String val hours = (milliseconds / (1000 * 60 * 60)).toInt() val minutes = (milliseconds % (1000 * 60 * 60)).toInt() / (1000 * 60) val seconds = (milliseconds % (1000 * 60 * 60)).toInt() % (1000 * 60) / 1000 if (hours > 0) { timerString = "$hours:" } secondString = if (seconds < 10) { "0$seconds" } else { "" + seconds } timerString = "$timerString$minutes:$secondString" return timerString } private fun showDownloadDialog(position: Int, type: String) { if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale((activity), Manifest.permission.READ_PHONE_STATE)) { context.toast("Please go to app info and accept for required permission") } else { ActivityCompat.requestPermissions( (activity), arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1000 ) } } else { AlertDialog.Builder(activity) .setTitle("Are you sure to download ?") .setCancelable(false) .setPositiveButton("Yes") { dialogInterface, _ -> startDownloading(messages[position].message, type) dialogInterface.dismiss() } .setNegativeButton("No") { dialogInterface, _ -> dialogInterface.dismiss() }.show() } } private fun startDownloading(url: String, type: String) { Toast.makeText(context, "Download Started", Toast.LENGTH_SHORT).show() val request = DownloadManager.Request(Uri.parse(url)) request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE) request.setTitle("Download") request.setDescription("file downloading ... ") request.allowScanningByMediaScanner() request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) request.setDestinationInExternalPublicDir( Environment.DIRECTORY_DOWNLOADS, "" + System.currentTimeMillis() + "." + type ) val manager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager manager.enqueue(request) } }
1
null
1
1
87b3217cedb0340417a8a0fae3b0ef2741ad9012
16,330
Lifesolutions
BSD Source Code Attribution
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/opmodes/test/ExtensionTest.kt
ftc8569
651,162,740
false
{"Java Properties": 2, "Gradle": 6, "Shell": 1, "HTML": 2, "Markdown": 6, "Batchfile": 1, "Text": 4, "Ignore List": 1, "XML": 16, "Java": 96, "Kotlin": 100}
import com.arcrobotics.ftclib.command.CommandOpMode import com.arcrobotics.ftclib.command.InstantCommand import com.arcrobotics.ftclib.gamepad.GamepadEx import com.arcrobotics.ftclib.gamepad.GamepadKeys import com.qualcomm.robotcore.eventloop.opmode.TeleOp import org.firstinspires.ftc.teamcode.subsystems.ExtensionLinkageSubsystem import org.firstinspires.ftc.teamcode.subsystems.Robot @TeleOp class ExtensionTest: CommandOpMode() { override fun initialize() { val robot = Robot(hardwareMap, telemetry) val driver = GamepadEx(gamepad1) val rightDpad = driver.getGamepadButton(GamepadKeys.Button.DPAD_RIGHT) val leftDpad = driver.getGamepadButton(GamepadKeys.Button.DPAD_LEFT) val upDpad = driver.getGamepadButton(GamepadKeys.Button.DPAD_UP) val downDpad = driver.getGamepadButton(GamepadKeys.Button.DPAD_DOWN) robot.telemetry.addLine("Extension Test Initialized") robot.telemetry.update() rightDpad.whenPressed(InstantCommand({ robot.extension.targetLength = 0.0}, robot.extension)) leftDpad.whenPressed(InstantCommand({ robot.extension.targetLength = ExtensionLinkageSubsystem.LOW }, robot.extension)) upDpad.whenPressed(InstantCommand({ robot.extension.targetLength = ExtensionLinkageSubsystem.MID }, robot.extension)) downDpad.whenPressed(InstantCommand({ robot.extension.targetLength = ExtensionLinkageSubsystem.HIGH }, robot.extension)) } }
1
null
1
1
a696b287ee27a77a02288b105f2148c123a6e612
1,457
2023offseason
BSD 3-Clause Clear License
dkplayer-ui/src/main/java/xyz/doikki/videocontroller/scene/JustFullscreenPlayScene.kt
Jisucloud
563,157,256
true
{"Batchfile": 1, "Shell": 2, "Markdown": 3, "Java Properties": 2, "Proguard": 5, "Kotlin": 50, "Java": 203}
package xyz.doikki.videocontroller.scene import android.app.Activity import android.content.pm.ActivityInfo import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import xyz.doikki.videocontroller.R import xyz.doikki.videocontroller.StandardVideoController import xyz.doikki.videocontroller.component.* import xyz.doikki.videoplayer.DKVideoView import xyz.doikki.videoplayer.util.CutoutUtil import xyz.doikki.videoplayer.util.PlayerUtils /** * 只用于全屏播放的场景 */ open class JustFullscreenPlayScene private constructor( private val activity: Activity, val dkVideoView: DKVideoView ) { val controller: StandardVideoController init { CutoutUtil.adaptCutoutAboveAndroidP(activity, true) //设置video view 横屏展示 if (activity.requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || activity.requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) { dkVideoView.startFullScreen() } else { dkVideoView.startVideoViewFullScreen() } controller = StandardVideoController(activity) setupVideoView() } protected fun setupVideoView() { controller.addControlComponent(CompleteView(activity)) controller.addControlComponent(ErrorView(activity)) controller.addControlComponent(PrepareView(activity)) val vodControlView = VodControlView(activity) // 我这里隐藏了全屏按钮并且调整了边距,我不推荐这样做,我这样只是为了方便, // 如果你想对某个组件进行定制,直接将该组件的代码复制一份,改成你想要的样子 vodControlView.findViewById<View?>(R.id.ctrl_fullscreen).visibility = View.GONE val lp = vodControlView.findViewById<View>(R.id.total_time).layoutParams as LinearLayout.LayoutParams lp.rightMargin = PlayerUtils.dp2px(activity, 16f) controller.addControlComponent(vodControlView) controller.addControlComponent(GestureView(activity)) dkVideoView.videoController = controller dkVideoView.setScreenAspectRatioType(DKVideoView.SCREEN_ASPECT_RATIO_SCALE_16_9) } companion object { /** * 整个界面布局都不用,直接就一播放器的场景,该方法会创建一个播放器设置为界面的content view */ @JvmStatic fun bind(activity: Activity): JustFullscreenPlayScene { val videoView = DKVideoView(activity).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) } activity.setContentView(videoView) return bind(activity, videoView) } @JvmStatic fun bind(activity: Activity, videoView: DKVideoView): JustFullscreenPlayScene { return JustFullscreenPlayScene(activity, videoView) } } }
0
Java
0
0
43d319d6000357610461848eccc9af40099655a5
2,803
DKVideoPlayer
Apache License 2.0
src/main/java/com/slowgenius/toolkit/utils/MyActionUtils.kt
slowgenius
553,696,590
false
{"Java": 110047, "FreeMarker": 33282, "Kotlin": 15016, "Fluent": 2200, "HTML": 86}
package com.slowgenius.toolkit.utils import com.intellij.database.psi.DbTable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.psi.PsiElement import java.util.* import java.util.stream.Collectors /** * @author slowgenius * @version SlowToolkit * @since 2022/7/19 21:05:56 */ object MyActionUtils { @JvmStatic fun getPsiElement(anActionEvent: AnActionEvent): PsiElement? { return anActionEvent.getData(LangDataKeys.PSI_ELEMENT) } @JvmStatic fun getDbTableList(anActionEvent: AnActionEvent): List<DbTable?> { return Arrays.stream(anActionEvent.getData(LangDataKeys.PSI_ELEMENT_ARRAY)) .map { item: PsiElement? -> item as DbTable? } .collect(Collectors.toList()) } fun getDbTable(anActionEvent: AnActionEvent): DbTable? { return anActionEvent.getData(LangDataKeys.PSI_ELEMENT) as DbTable? } val defaultProject: Project get() = ProjectManager.getInstance().defaultProject }
1
null
1
1
feea07877b3280041fbe4b9148250acae619d132
1,146
SlowToolKit
Apache License 2.0
src/main/kotlin/io/github/chizganov/puzzlers/adventofcode/twentytwo/MonkeyInTheMiddle.kt
chizganov
260,441,259
false
{"Java": 243103, "Kotlin": 95445}
package io.github.chizganov.puzzlers.adventofcode.twentytwo /** * Advent of Code 2022 Day 10: Cathode-Ray Tube * https://adventofcode.com/2022/day/10 * */ class MonkeyInTheMiddle { fun countMonkeyBusinessLevel(notes: List<String>): Long { val monkeys = notes.filterNot(String::isEmpty) .map(String::trim) .chunked(6) // works for given size, better to take while not empty and split .map { plan -> Monkey( number = plan.first().filter(Char::isDigit).toInt(), items = plan.first { it.contains(STARTING_ITEMS) }.removePrefix(STARTING_ITEMS) .filterNot(Char::isWhitespace).split(',').map(String::toLong).toMutableList(), operation = plan.first { it.contains(OPERATION) } .takeLastWhile { it != '=' } .parseOperation(), test = plan.first { it.contains(TEST) }.removePrefix(TEST).parseTest(), onTrue = plan.first { it.contains(IF_TRUE) }.takeLastWhile(Char::isDigit).toInt(), onFalse = plan.first { it.contains(IF_FALSE) }.takeLastWhile(Char::isDigit).toInt() ) } val monkeyBusinessLevel = generateSequence { monkeys }.take(ROUNDS).flatten() .fold(mutableMapOf<Int, Int>()) { numberToInspected, monkey -> numberToInspected.putIfAbsent(monkey.number, 0) while (monkey.items.isNotEmpty()) { numberToInspected.computeIfPresent(monkey.number) { _, inspected -> inspected + 1 } // TODO part 2: % lcm 9_699_690L gives 16792940265 rewrite monkey.items[0] = monkey.operation(monkey.items.first()) / 3 if (monkey.test(monkey.items.first())) { monkey.throwItemTo(monkeys[monkey.onTrue]) } else { monkey.throwItemTo(monkeys[monkey.onFalse]) } } numberToInspected } .map(Map.Entry<Int, Int>::value) .sortedDescending() .take(2) .map(Int::toLong) .reduce(Long::times) return monkeyBusinessLevel } class Monkey( val number: Int, val items: MutableList<Long>, val operation: (Long) -> Long, val test: (Long) -> Boolean, val onTrue: Int, val onFalse: Int, ) { fun throwItemTo(monkey: Monkey) = monkey.items.add(items.removeFirst()) } private enum class Operators(val sign: String, val operation: (Long, Long) -> Long) { PLUS("+", { a, b -> a + b }), MULTIPLY("*", { a, b -> a * b }); } companion object { private const val STARTING_ITEMS = "Starting items:" private const val OPERATION = "Operation:" private const val TEST = "Test:" private const val IF_TRUE = "If true:" private const val IF_FALSE = "If false:" private const val ROUNDS = 20 fun String.parseOperation(): (Long) -> Long { val tokens = trim().split(' ') val opIndex = tokens.indexOfFirst { it in Operators.values().map(Operators::sign) } val operator = Operators.values().first { it.sign == tokens[opIndex] } val number = tokens[opIndex - 1].toLongOrNull() ?: tokens[opIndex + 1].toLongOrNull() return if (number != null) { old -> operator.operation(old, number) } else { old -> operator.operation(old, old) } } private fun String.parseTest(): (Long) -> Boolean { return { item -> item % trim().takeLastWhile { it.isDigit() }.toLong() == 0L } } } }
1
null
1
1
be7f818e74ee9a75f0320ebdea9a56607bd74942
3,789
puzzlers
Apache License 2.0
src/main/kotlin/ru/andreyTw/designPatternsTestGround/singleton/SingletonKotlinTestGround.kt
AndreyTW
650,614,946
false
{"Java": 18408, "Kotlin": 5267}
package ru.andreyTw.designPatternsTestGround.singleton import ru.andreyTw.designPatternsTestGround.singleton.MySingletonKotlin.Companion.getMySingletonKotlinInstance fun main() { // val mySingletonOne = MySingleton() // val mySingletonTwo = MySingleton() // val mySingletonThree = MySingleton() val mySingletonOne = getMySingletonKotlinInstance() val mySingletonTwo = getMySingletonKotlinInstance() val mySingletonThree = getMySingletonKotlinInstance() println(mySingletonOne.mySingletonKotlinNumberOfInstance) println(mySingletonTwo.mySingletonKotlinNumberOfInstance) println(mySingletonThree.mySingletonKotlinNumberOfInstance) println(mySingletonOne == mySingletonTwo) }
1
null
1
1
08454cb9abce85bbc9f2e26fa2a7d3357c9ead8a
711
design-patterns-test-ground
MIT License
PhoenixLib/src/main/java/com/faddy/phoenixlib/utils/Utils.kt
Fa-d
765,522,603
false
{"Gradle Kotlin DSL": 6, "INI": 2, "Shell": 1, "Java Properties": 2, "Text": 2, "Ignore List": 9, "Batchfile": 1, "Markdown": 1, "TOML": 1, "Gradle": 2, "Proguard": 6, "XML": 54, "Java": 155, "Kotlin": 46, "Makefile": 3, "C": 30, "AIDL": 12, "CMake": 1, "C++": 1}
package com.faddy.phoenixlib.utils import android.text.TextUtils import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData fun <T> LiveData<T>.toMutableLiveData(): MutableLiveData<T> { val mediatorLiveData = MediatorLiveData<T>() mediatorLiveData.addSource(this) { mediatorLiveData.value = it } return mediatorLiveData } fun ping(url: String): String { try { val command = "/system/bin/ping -c 1 $url" val process = Runtime.getRuntime().exec(command) val allText = process.inputStream.bufferedReader().use { it.readText() } if (!TextUtils.isEmpty(allText)) { val tempInfo = allText.substring(allText.indexOf("min/avg/max/mdev") + 19) val temps = tempInfo.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() if (temps.isNotEmpty() && temps[0].length < 10) { return temps[0].toFloat().toInt().toString() + " ms" } } } catch (e: Exception) { e.printStackTrace() } return "100 ms" }
0
Java
0
0
f5c2cdba44a9dbe28450d28b041b408068e75d9a
1,110
VPNSDK
MIT License
sceneview/src/main/java/io/github/sceneview/texture/Texture.kt
ninjz
485,306,566
true
{"Java Properties": 4, "Markdown": 3, "Shell": 2, "Batchfile": 3, "Kotlin": 81, "Proguard": 4, "Java": 148}
package io.github.sceneview.texture import androidx.lifecycle.Lifecycle import com.google.android.filament.Stream import com.google.android.filament.Texture import com.gorisse.thomas.lifecycle.observe import io.github.sceneview.Filament fun <R> Texture.use(block: (Texture) -> R): R = block(this).also { destroy() } fun Texture.Builder.build(lifecycle: Lifecycle? = null): Texture = build(Filament.engine) .also { texture -> lifecycle?.observe(onDestroy = { // Prevent double destroy in case of manually destroyed runCatching { texture.destroy() } }) } fun Texture.setExternalStream(stream: Stream) = setExternalStream(Filament.engine, stream) fun Texture.setImage(level: Int, buffer: Texture.PixelBufferDescriptor) = setImage(Filament.engine, level, buffer) /** * Destroys a Texture and frees all its associated resources. */ fun Texture.destroy() { Filament.engine.destroyTexture(this) }
0
Java
0
0
70c9776e3a3920d6cf6fef22ea0a6784479c490e
951
sceneview-android
Apache License 2.0
WZDCTool/app/src/main/java/com/wzdctool/android/dataclasses/VisualizationObj.kt
TonyEnglish
297,727,090
false
{"Markdown": 4, "Java Properties": 5, "YAML": 1, "Gradle": 3, "Shell": 2, "Ignore List": 4, "Batchfile": 2, "Proguard": 1, "Kotlin": 40, "XML": 196, "Java": 1, "SVG": 16}
package com.wzdctool.android.dataclasses import com.google.android.gms.maps.model.LatLng data class VisualizationObj (val dataPoints: List<LatLng>, val markers: List<CustomMarkerObj>, val dataFile: String)
1
null
1
1
6c7e72c300b0c4b47a36506ffb7bdf33a8c870a3
207
V2X_MobileApplication
MIT License
mail/common/src/main/java/com/mail/ann/mail/NetworkTimeouts.kt
ZhangXinmin528
516,242,626
true
{"INI": 1, "Shell": 6, "Gradle": 30, "EditorConfig": 1, "Markdown": 8, "Git Attributes": 1, "Batchfile": 1, "Text": 44, "Ignore List": 4, "Git Config": 1, "XML": 399, "YAML": 6, "Kotlin": 744, "AIDL": 2, "Java": 433, "Java Properties": 1, "SVG": 67, "PostScript": 1, "JSON": 23, "E-mail": 27, "Proguard": 1}
package com.mail.ann.mail object NetworkTimeouts { const val SOCKET_CONNECT_TIMEOUT = 30000 const val SOCKET_READ_TIMEOUT = 60000 }
0
Java
0
0
3efc82014d57307996329fd057c505d2b88ed044
141
Ann-mail
Apache License 2.0
app/src/main/java/com/ethan/hydrogen/demo/common/log/ImplLoggerManager.kt
ethann-tech
697,255,790
false
{"Gradle Kotlin DSL": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "TOML": 1, "Text": 1, "Proguard": 3, "XML": 103, "Java": 125, "Kotlin": 8, "HTML": 1, "JSON": 1}
package com.ethan.hydrogen.demo.common.log import android.content.Context import ch.qos.logback.classic.LoggerContext import ch.qos.logback.classic.joran.JoranConfigurator import com.ethan.hydrogen.demo.common.log.ILoggerManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext //import com.ethan.logbacktest.BuildConfig //import io.github.uhsk.kit.format //import kotlinx.coroutines.* //import org.apache.commons.compress.archivers.zip.Zip64Mode //import org.apache.commons.compress.archivers.zip.ZipArchiveEntry //import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream //import org.apache.commons.io.FileUtils import org.slf4j.LoggerFactory internal class ImplLoggerManager(private val mContext:Context) : ILoggerManager { //override suspend fun init() { // CoroutineScope(Dispatchers.IO).launch { // async { // val loggerContext: LoggerContext = LoggerFactory.getILoggerFactory() as LoggerContext // loggerContext.reset() // loggerContext.putProperty("LOG_DIR", mContext.externalCacheDir!!.path) // val joranConfigurator = JoranConfigurator() // joranConfigurator.context = loggerContext // joranConfigurator.doConfigure(mContext.assets.open("configs/logback.xml")) // } // // } // //} override suspend fun init() = withContext(context = Dispatchers.IO) { val loggerContext: LoggerContext = LoggerFactory.getILoggerFactory() as LoggerContext loggerContext.reset() loggerContext.putProperty("LOG_DIR", mContext.externalCacheDir!!.path) val joranConfigurator = JoranConfigurator() joranConfigurator.context = loggerContext joranConfigurator.doConfigure(mContext.assets.open("configs/logback.xml")) return@withContext } //override suspend fun zip(): Uri = withContext(context = Dispatchers.IO) { // val todayLogFile = File(mContext.externalCacheDir, String.format(Locale.ENGLISH, "logs/%s.log", Date().format(pattern = "yyyy-MM-dd"))) // val outputFile = File(mContext.externalCacheDir, "shared/today-log.zip") // if (outputFile.exists()) { // outputFile.delete() // } // FileUtils.forceMkdirParent(outputFile) // // val zipArchiveOutputStream = ZipArchiveOutputStream(outputFile) // zipArchiveOutputStream.setUseZip64(Zip64Mode.AsNeeded) // // val zipArchiveEntry = ZipArchiveEntry(todayLogFile, todayLogFile.name) // zipArchiveOutputStream.putArchiveEntry(zipArchiveEntry) // zipArchiveOutputStream.write(todayLogFile.readBytes()) // zipArchiveOutputStream.closeArchiveEntry() // zipArchiveOutputStream.finish() // zipArchiveOutputStream.close() // // return@withContext FileProvider.getUriForFile(mContext, "${BuildConfig.APPLICATION_ID}.providers.file", outputFile) //} }
0
Java
0
0
b392d29d8221a9a253d74c9bf786b8bca32ae541
2,959
Hydrogen
Apache License 2.0
app/src/main/java/org/ranapat/sensors/gps/example/services/stepper/StepCounterEventListener.kt
ranapat
591,635,819
false
{"Java": 171971, "Kotlin": 63345}
package org.ranapat.sensors.gps.example.services.stepper import android.content.pm.PackageManager import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import org.ranapat.instancefactory.Fi import org.ranapat.sensors.gps.example.data.entity.StepSet import java.util.* class StepCounterEventListener : SensorEventListener, AccuracyCalculator, DataCollector, StepLogger { override var accuracy: Int = SensorManager.SENSOR_STATUS_NO_CONTACT override val multiplier: Double get() = 1.0 override val method: String get() = PackageManager.FEATURE_SENSOR_STEP_COUNTER override val stepSet: ArrayList<StepSet> = arrayListOf() override val status: StepperStatus = Fi.get(StepperStatus::class.java) private var previousSteps: Int? = null private var previousStepDate: Date? = null override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) { this.accuracy = accuracy } override fun onSensorChanged(sensorEvent: SensorEvent?) { sensorEvent ?: return val steps = sensorEvent.values.getOrNull(0)?.toInt() ?: 0 val stepsToRecord = if (previousSteps == null) { 1 } else { steps - (previousSteps ?: 0) } previousSteps = steps val currentDate = add(stepsToRecord, previousStepDate, sensorEvent.timestamp, normalizedAccuracy) previousStepDate = currentDate log(method, stepsToRecord, currentDate, normalizedAccuracy, "raw steps: $steps") } }
1
null
1
1
16ccf3ec38350e65b7d9047fdc4fadc0c9ec6227
1,579
gps-sensors
The Unlicense
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/control/gainmatrices/PIDGains.kt
raleighmasjid
622,808,338
false
{"Gradle": 7, "Java Properties": 1, "Shell": 1, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Markdown": 7, "INI": 1, "Java": 170, "XML": 17, "JSON": 2, "Kotlin": 9}
package org.firstinspires.ftc.teamcode.control.gainmatrices import kotlin.Double.Companion.POSITIVE_INFINITY import kotlin.math.* data class PIDGains @JvmOverloads constructor( @JvmField var kP: Double = 0.0, @JvmField var kI: Double = 0.0, @JvmField var kD: Double = 0.0, @JvmField var maxOutputWithIntegral: Double = POSITIVE_INFINITY, ) { @JvmOverloads fun computeKd(gains: FeedforwardGains, percentOvershoot: Double = 0.0): PIDGains { kD = computeKd(kP, gains.kV, gains.kA, percentOvershoot) return this } } @JvmOverloads fun computeKd(kP: Double, kV: Double, kA: Double, percentOvershoot: Double = 0.0): Double { val overshoot: Double = percentOvershoot / 100.0 val zeta: Double = if (overshoot <= 0.0) 1.0 else -ln(overshoot) / sqrt(PI.pow(2) + ln(overshoot).pow(2)) return max( 2 * zeta * sqrt(kA * kP) - kV, 0.0 ) }
0
Java
0
0
598626cc3b5bed3c80546dd92d83c084105d39d3
905
ftc-21836-2023
BSD 3-Clause Clear License
logcat/testSrc/com/android/tools/idea/logcat/messages/TextAccumulatorTest.kt
TrellixVulnTeam
571,897,700
true
{"Text": 355, "EditorConfig": 2, "Markdown": 64, "Shell": 32, "Ignore List": 193, "XML": 13507, "Starlark": 142, "Kotlin": 6746, "Java": 8085, "Gradle": 2753, "Proguard": 169, "INI": 72, "JSON": 80, "Graphviz (DOT)": 1, "Ant Build System": 2, "Protocol Buffer": 8, "Java Properties": 166, "HTML": 67, "Batchfile": 20, "Gradle Kotlin DSL": 1655, "CMake": 19, "C": 29, "Checksums": 339, "C++": 14, "TOML": 2, "Smali": 5, "SVG": 1329, "AIDL": 9, "JFlex": 8, "Prolog": 6, "QMake": 2, "RenderScript": 1, "NSIS": 4, "GraphQL": 5, "Python": 10, "Makefile": 8, "YAML": 1, "HAProxy": 1, "Org": 2, "JavaScript": 3}
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.logcat.messages import com.android.tools.idea.logcat.messages.TextAccumulator.Range import com.google.common.truth.Truth.assertThat import com.intellij.openapi.editor.markup.TextAttributes import org.junit.Test import java.awt.Color private val blue = TextAttributes().apply { foregroundColor = Color.blue } private val red = TextAttributes().apply { foregroundColor = Color.red } /** * Tests for [TextAccumulator] */ class TextAccumulatorTest { @Test fun accumulate_noColor() { val buffer = TextAccumulator() buffer.accumulate("foo") buffer.accumulate("bar") assertThat(buffer.text).isEqualTo("foobar") assertThat(buffer.highlightRanges).isEmpty() } @Test fun accumulate_withColor() { val buffer = TextAccumulator() buffer.accumulate("foo-") buffer.accumulate("blue", blue) buffer.accumulate("-bar-") buffer.accumulate("red", red) assertThat(buffer.text).isEqualTo("foo-blue-bar-red") assertThat(buffer.highlightRanges).containsExactly(Range(4, 8, blue), Range(13, 16, red)) } @Test fun accumulate_withHint() { val buffer = TextAccumulator() buffer.accumulate("foo", hint="foo") buffer.accumulate("-") buffer.accumulate("bar", hint="bar") assertThat(buffer.text).isEqualTo("foo-bar") assertThat(buffer.hintRanges).containsExactly(Range(0, 3, "foo"), Range(4, 7, "bar")) } }
0
null
0
0
b373163869f676145341d60985cdbdaca3565c0b
2,029
android_74FW
Apache License 2.0
kotlin-dsl/example/src/test/kotlin/com/chutneytesting/example/scenario/RunHelloTests.kt
owerfelli
791,217,559
true
{"Markdown": 64, "Batchfile": 2, "Shell": 2, "Gradle Kotlin DSL": 6, "INI": 5, "Java": 984, "HTML": 64, "JavaScript": 6, "Kotlin": 241, "SQL": 4, "Java Properties": 1, "Dockerfile": 3, "CSS": 1, "TypeScript": 250}
package com.chutneytesting.example.scenario import com.chutneytesting.example.environment_en import com.chutneytesting.example.environment_fr import com.chutneytesting.kotlin.dsl.ChutneyScenario import com.chutneytesting.kotlin.junit.api.ChutneyTest import com.chutneytesting.kotlin.launcher.Launcher import org.junit.jupiter.api.Test class RunHelloTests { companion object { @JvmField val en_www = environment_en } @ChutneyTest(environment = "en_www") fun testMethod(): ChutneyScenario { return search_title_scenario } @Test fun `search title is displayed`() { Launcher().run(search_title_scenario, environment_fr) } }
0
null
0
0
a7b0bf69921fd29f846763ba4e67e271dbfaad13
690
chutney
Apache License 2.0
src/main/kotlin/ch/skyfy/fabricpermshiderkotlined/FabricPermsHiderKotlinedMod.kt
AmibeSkyfy16
586,606,158
false
{"Java": 26388, "Kotlin": 14092}
package ch.skyfy.fabricpermshiderkotlined import net.fabricmc.api.DedicatedServerModInitializer import net.fabricmc.loader.api.FabricLoader import net.minecraft.server.command.TellRawCommand import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger import java.nio.file.Path @Suppress("MemberVisibilityCanBePrivate") class FabricPermsHiderKotlinedMod : DedicatedServerModInitializer { // companion object { // const val MOD_ID: String = "fabricpermhiderkotlined" // val CONFIG_DIRECTORY: Path = FabricLoader.getInstance().configDir.resolve(MOD_ID) // val LOGGER: Logger = LogManager.getLogger(FabricPermsHiderKotlinedMod::class.java) // } init { } override fun onInitializeServer() { } }
1
null
1
1
7db6ecd78bc44771c7c7d4f29872569d67c105b5
762
FabricPermHiderKotlined
MIT License
Leetcode-Solution-Kotlin/knightProbablityInChessboard.kt
harshraj9988
491,534,142
false
{"Java": 591477, "Kotlin": 183437, "C++": 86767, "Python": 24653, "JavaScript": 4637}
fun knightProbability(n: Int, k: Int, row: Int, column: Int): Double { val dp = Array(k + 1) { Array(n) { DoubleArray(n) { -1.0 } } } return memoization(n, k, row, column, dp) } private val dir = arrayOf( Pair(1, -2), Pair(2, -1), Pair(2, 1), Pair(1, 2), Pair(-1, 2), Pair(-2, 1), Pair(-2, -1), Pair(-1, -2) ) private fun memoization(n: Int, k: Int, row: Int, column: Int, dp: Array<Array<DoubleArray>>): Double { if (row !in 0 until n || column !in 0 until n) return 0.0 if (k == 0) return 1.0 if (dp[k][row][column] != -1.0) return dp[k][row][column] var prob = 0.0 for (i in 0 until 8) { prob += memoization(n, k - 1, row + dir[i].first, column + dir[i].second, dp) / 8.0 } dp[k][row][column] = prob return prob }
1
null
1
1
3fc29ceffe3eaf92d9e6e79bfb097ba0db1c40ad
798
LeetCode-solutions
Apache License 2.0
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/autonomous/FieldConstants.kt
Rpergy
597,173,379
false
{"Java": 222719, "Kotlin": 89282}
package org.firstinspires.ftc.teamcode.autonomous import com.acmerobotics.roadrunner.geometry.Pose2d import com.acmerobotics.roadrunner.geometry.Vector2d class FieldConstants { object LeftBlueAutonomous { val startPosition = Pose2d(38.0, 64.0, Math.toRadians(-90.0)) val cyclePosition1 = Vector2d(39.0, 10.0) val cyclePosition2 = Pose2d(37.4, 6.0, Math.toRadians(-164.5)) val parkingTransition = Pose2d(38.0, 14.0, Math.toRadians(-90.0)) val parkPosition1 = Pose2d(72.0, 15.0, Math.toRadians(-90.0)) val parkPosition2 = Pose2d(38.0, 15.0, Math.toRadians(-90.0)) val parkPosition3 = Pose2d(13.0, 15.0, Math.toRadians(-90.0)) } object LeftRedAutonomous { val startPosition = Pose2d(-38.0, -64.0, Math.toRadians(90.0)) val cyclePosition1 = Vector2d(-37.0, -20.0) val cyclePosition2 = Pose2d(-38.0, -5.0, Math.toRadians(15.0)) val parkingTransition = Pose2d(-39.0, -15.0, Math.toRadians(90.0)) val parkPosition1 = Pose2d(-70.0, -15.0, Math.toRadians(90.0)) val parkPosition2 = Pose2d(-41.0, -15.0, Math.toRadians(90.0)) val parkPosition3 = Pose2d(-10.0, -15.0, Math.toRadians(90.0)) } object RightBlueAutonomous { val startPosition = Pose2d(-38.0, 64.0, Math.toRadians(-90.0)) val cyclePosition1 = Vector2d(-38.0, 20.0) val cyclePosition2 = Pose2d(-38.0, 4.0, Math.toRadians(-17.0)) val parkingTransition = Pose2d(-38.0, 14.0, Math.toRadians(-90.0)) val parkPosition1 = Pose2d(-15.0, 15.0, Math.toRadians(-90.0)) val parkPosition2 = Pose2d(-37.0, 15.0, Math.toRadians(-90.0)) val parkPosition3 = Pose2d(-70.0, 15.0, Math.toRadians(-90.0)) } object RightRedAutonomous { val startPosition = Pose2d(38.0, -64.0, Math.toRadians(90.0)) val cyclePosition1 = Vector2d(38.0, -20.0) val cyclePosition2 = Pose2d(38.0, -5.0, Math.toRadians(163.0)) val parkingTransition = Pose2d(35.0, -16.0, Math.toRadians(90.0)) val parkPosition1 = Pose2d(10.0, -15.0, Math.toRadians(90.0)) val parkPosition2 = Pose2d(38.0, -15.0, Math.toRadians(90.0)) val parkPosition3 = Pose2d(70.0, -15.0, Math.toRadians(90.0)) } object LeftBlueDumpling { val cyclePosition = Pose2d(36.0, 23.0, Math.toRadians(-193.0)) } object LeftRedDumpling { val cyclePosition = Pose2d(-36.0, -23.0, Math.toRadians(-16.0)) } object RightBlueDumpling { val cyclePosition = Pose2d(-36.0, 22.0, Math.toRadians(14.0)) } object RightRedDumpling { val cyclePosition = Pose2d(35.5, -22.0, Math.toRadians(194.0)) } }
1
null
1
1
b9b224abb0c82f0c48959be0963a22199df44e8f
2,680
PowerPlay
BSD 3-Clause Clear License
common/src/main/kotlin/io/github/remodstudios/lumidep/misc/LumidepStats.kt
ReMod-Studios
365,715,310
false
{"Gradle": 5, "INI": 3, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "JSON": 142, "Kotlin": 40, "Java": 4, "TOML": 1}
package io.github.remodstudios.lumidep.misc import io.github.remodstudios.remodcore.registry.RegistryHelper import me.shedaniel.architectury.registry.DeferredRegister import net.minecraft.stat.StatFormatter import net.minecraft.stat.Stats import net.minecraft.util.Identifier import net.minecraft.util.registry.Registry object LumidepStats: RegistryHelper<Identifier>( DeferredRegister.create(io.github.remodstudios.lumidep.Lumidep.MOD_ID, Registry.CUSTOM_STAT_KEY) ) { val CONSUME_KELPFRUIT_POWDER = add("consume_kelpfruit_powder", StatFormatter.DEFAULT) fun add(id: String, formatter: StatFormatter): Identifier { val ident = io.github.remodstudios.lumidep.Lumidep.id(id) registry.register(ident) { ident } Stats.CUSTOM.getOrCreateStat(ident, formatter) return ident } }
0
Kotlin
0
0
92310fb84c65d76552355f8cba0cdfbf43860576
823
lumidep-java
Apache License 2.0
ProjectFeedget/entity/src/main/java/kr/mashup/feedget/entity/Category.kt
mash-up-kr
109,485,907
false
{"Java": 101694, "Kotlin": 74233}
package kr.mashup.feedget.entity data class Category( val id: Long, val name: String ) : Entity
1
null
1
1
78dd05a711215f55d9a3bf8bde7c2349ee134f73
105
feedget-android
Apache License 2.0
src/test/kotlin/ru/ppzh/quoteParser/QuoteParserPhraseSpecs.kt
ppzhuk
52,633,828
false
{"Gradle": 2, "Markdown": 2, "CSS": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Java Properties": 1, "E-mail": 75, "Kotlin": 36, "Java": 1, "HTML": 87}
/* * Copyright 2016-2017 JetBrains s.r.o., 2017 <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 ru.ppzh.quoteParser import org.jetbrains.spek.api.Given import org.jetbrains.spek.api.Spek import java.io.File import kotlin.test.assertEquals private val dir = ".${File.separator}testEmls${File.separator}phrases${File.separator}" class QuoteParserPhraseSpecs : Spek() { private val parser = QuoteParser.Builder() .deleteQuoteMarks(false) .build() private fun Given.check(emailNum: Int, expectedQuoteHeader: QuoteHeader) { val url = parser.javaClass.classLoader.getResource("$dir$emailNum.eml") val file = File(url.toURI()) on("processing it") { val content = parser.parse(file) it("must define a quote") { assertEquals(expectedQuoteHeader, content.header) } } } init { given("eml file") { val emailNum = 92 val expectedQuoteHeader = QuoteHeader( startIndex = 9, endIndex = 10, text = listOf( """In reply to:""" ) ) check(emailNum, expectedQuoteHeader) } given("eml file") { val emailNum = 2555 val expectedQuoteHeader = QuoteHeader( startIndex = 2, endIndex = 3, text = listOf( """-------- Original message --------""" ) ) check(emailNum, expectedQuoteHeader) } given("eml file") { val emailNum = 17407 val expectedQuoteHeader = QuoteHeader( startIndex = 1, endIndex = 2, text = listOf( """##- Please type your reply above this line -##""" ) ) check(emailNum, expectedQuoteHeader) } } }
1
null
1
1
518fb571749f8ad5bacf9bf66f22818c6f4f61d8
2,561
email-parser
Apache License 2.0
post-comments/app/src/main/java/com/sample/postapp/di/NetworkModule.kt
tmehta813
786,357,342
false
{"Markdown": 2, "Gradle Kotlin DSL": 4, "Java Properties": 5, "Shell": 1, "Batchfile": 1, "Proguard": 2, "Ignore List": 3, "Kotlin": 24, "XML": 23, "TOML": 1, "INI": 3, "Java": 2}
package com.sample.postapp.di import com.sample.network.ApiService import com.sample.network.networkHandler.BasicAuthInterceptor import com.sample.network.networkHandler.ResultCallAdapterFactory import com.sample.network.utils.BASE_URL import com.sample.network.utils.CONNECT_TIMEOUT_IN_SECONDS import com.sample.network.utils.READ_TIMEOUT_IN_SECONDS import com.sample.network.utils.WRITE_TIMEOUT_IN_SECONDS import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module object NetworkModule { @Provides @Singleton fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(ResultCallAdapterFactory.create()) .build() } @Provides @Singleton fun provideOkHttpClient(): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(BasicAuthInterceptor()) .addInterceptor(HttpLoggingInterceptor().apply { setLevel(HttpLoggingInterceptor.Level.BODY) }) .connectTimeout(CONNECT_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS) // Connection timeout .readTimeout(READ_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS) // Read timeout .writeTimeout(WRITE_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS) // Write timeout .build() } @Provides @Singleton fun provideApiService(retrofit: Retrofit): ApiService { return retrofit.create(ApiService::class.java) } }
0
Java
0
0
fba12a8d23d7e84b0eced1e8d2e8165988da2685
1,925
fetch-post
MIT License
app/src/main/java/com/example/android/shoppingList/database/ShoppingList.kt
marcinbln
356,965,584
false
{"Gradle": 3, "Java Properties": 1, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Text": 1, "Markdown": 1, "INI": 1, "Proguard": 1, "Kotlin": 23, "XML": 36, "Java": 3}
package com.example.android.shoppingList.database import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "shopping_lists_table") data class ShoppingList( @PrimaryKey(autoGenerate = true) var listId: Long = 0L, @ColumnInfo(name = "start_time_milli") val startTimeMilli: Long = System.currentTimeMillis(), @ColumnInfo(name = "list_name") var listName: String = "", @ColumnInfo(name = "archived") var isArchived: Boolean = false )
1
null
1
1
714b2146265ab734a53192ec055e32f80efbabc8
554
ShoppingList
Apache License 2.0
heima_player/app/src/main/java/com/itheima/player/util/FragmentUtil.kt
Tecode
455,788,985
false
{"Java": 409665, "Kotlin": 196048}
package com.itheima.player.util import com.itheima.player.R import com.itheima.player.base.BaseFragment import com.itheima.player.ui.fragment.HomeFragment import com.itheima.player.ui.fragment.MvFragment import com.itheima.player.ui.fragment.VBangFragment import com.itheima.player.ui.fragment.YueDanFragment /** * ClassName:FragmentUtil * Description:管理fragment的util类 */ class FragmentUtil private constructor(){//私有化构造方法 val homeFragment by lazy { HomeFragment() } val mvFragment by lazy { MvFragment() } val vbangFragment by lazy { VBangFragment() } val yuedanFragment by lazy { YueDanFragment() } companion object { val fragmentUtil by lazy { FragmentUtil() } } /** * 根据tabid获取对应的fragment */ fun getFragment(tabId:Int):BaseFragment?{ when(tabId){ R.id.tab_home->return homeFragment R.id.tab_mv->return mvFragment R.id.tab_vbang->return vbangFragment R.id.tab_yuedan->return yuedanFragment } return null } }
1
null
1
1
78a8c1e661c3a8a3f9b3dee8c6cf806cfec49a98
1,043
android_learning
MIT License